@deathbeam/pi-usage 0.0.8 → 0.0.10
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 +17 -5
- package/package.json +1 -4
- package/src/usage.ts +63 -13
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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** /usage — fullscreen token usage and cost dashboard. */
|
|
2
2
|
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
|
-
import { join } from "node:path";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
5
|
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";
|
|
@@ -162,14 +162,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
162
162
|
};
|
|
163
163
|
let render = () => {};
|
|
164
164
|
const agentDir = getAgentDir();
|
|
165
|
+
// getSessionDir() is this project's encoded-cwd dir under the default layout; count every project.
|
|
166
|
+
// shortcut: a custom dir named like --x-- reads as the default layout, use usesDefaultSessionDir() once it is exposed
|
|
167
|
+
const projectDir = ctx.sessionManager.getSessionDir();
|
|
168
|
+
const sessionDir = basename(projectDir).startsWith("-") ? dirname(projectDir) : projectDir;
|
|
169
|
+
const abort = new AbortController();
|
|
165
170
|
const loaded = collectUsage(
|
|
166
|
-
|
|
171
|
+
sessionDir,
|
|
167
172
|
(done, total) => {
|
|
168
173
|
state.done = done;
|
|
169
174
|
state.total = total;
|
|
170
175
|
render();
|
|
171
176
|
},
|
|
172
177
|
join(agentDir, "usage-cache.json"),
|
|
178
|
+
abort.signal,
|
|
173
179
|
).then((records) => {
|
|
174
180
|
state.records = records;
|
|
175
181
|
});
|
|
@@ -208,8 +214,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
208
214
|
function allDaily() {
|
|
209
215
|
return (allDays ??= dailyTotals(state.records!));
|
|
210
216
|
}
|
|
211
|
-
render = () =>
|
|
217
|
+
render = () => {
|
|
218
|
+
if (!abort.signal.aborted) tui.requestRender();
|
|
219
|
+
};
|
|
212
220
|
void loaded.then(render);
|
|
221
|
+
function close() {
|
|
222
|
+
abort.abort();
|
|
223
|
+
done(undefined);
|
|
224
|
+
}
|
|
213
225
|
function colorDelta(delta: number | undefined): string {
|
|
214
226
|
if (delta === undefined) return "-";
|
|
215
227
|
if (delta === 0) return "0%";
|
|
@@ -346,12 +358,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
346
358
|
invalidate() {},
|
|
347
359
|
handleInput(data: string) {
|
|
348
360
|
if (data === "q") {
|
|
349
|
-
|
|
361
|
+
close();
|
|
350
362
|
return;
|
|
351
363
|
} else if (keys.matches(data, "tui.select.cancel")) {
|
|
352
364
|
const frame = stack.pop();
|
|
353
365
|
if (!frame) {
|
|
354
|
-
|
|
366
|
+
close();
|
|
355
367
|
return;
|
|
356
368
|
}
|
|
357
369
|
({ 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.10",
|
|
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 = {
|
|
@@ -56,7 +58,7 @@ export type DailyCost = { label: string; cost: number };
|
|
|
56
58
|
|
|
57
59
|
type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; providers?: Set<string> };
|
|
58
60
|
|
|
59
|
-
const CACHE_VERSION =
|
|
61
|
+
const CACHE_VERSION = 2;
|
|
60
62
|
|
|
61
63
|
function emptyStats(): Stats {
|
|
62
64
|
return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
@@ -66,6 +68,29 @@ function num(value: unknown): number {
|
|
|
66
68
|
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
67
69
|
}
|
|
68
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
|
+
|
|
69
94
|
function addStats(stats: Stats, record: UsageRecord): void {
|
|
70
95
|
stats.cost += record.cost;
|
|
71
96
|
stats.input += record.input;
|
|
@@ -133,7 +158,12 @@ async function parseFile(file: string): Promise<UsageRecord[]> {
|
|
|
133
158
|
const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
|
|
134
159
|
for await (const line of lines) {
|
|
135
160
|
// Cheap prefilter: escaped JSON inside tool results never matches this literal.
|
|
136
|
-
|
|
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) {
|
|
137
167
|
// The session header (type:"session", cwd, id) is normally the first line.
|
|
138
168
|
if (sessionId === "" && line.includes('"type":"session"')) {
|
|
139
169
|
try {
|
|
@@ -154,19 +184,36 @@ async function parseFile(file: string): Promise<UsageRecord[]> {
|
|
|
154
184
|
} catch {
|
|
155
185
|
continue;
|
|
156
186
|
}
|
|
157
|
-
const
|
|
158
|
-
const usage =
|
|
159
|
-
|
|
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
|
+
}
|
|
160
205
|
const cost = typeof usage.cost === "number" ? usage.cost : num(usage.cost?.total);
|
|
206
|
+
const stamp = entry.type === "message" ? message.timestamp : entry.timestamp;
|
|
161
207
|
records.push({
|
|
162
|
-
provider
|
|
163
|
-
model
|
|
164
|
-
ts: num(
|
|
208
|
+
provider,
|
|
209
|
+
model,
|
|
210
|
+
ts: typeof stamp === "string" ? num(Date.parse(stamp)) : num(stamp),
|
|
165
211
|
cost,
|
|
166
212
|
input: num(usage.input),
|
|
167
213
|
output: num(usage.output),
|
|
168
214
|
cacheRead: num(usage.cacheRead),
|
|
169
215
|
cacheWrite: num(usage.cacheWrite),
|
|
216
|
+
requests: 1,
|
|
170
217
|
cwd,
|
|
171
218
|
sessionId,
|
|
172
219
|
});
|
|
@@ -191,6 +238,7 @@ export async function collectUsage(
|
|
|
191
238
|
dir: string,
|
|
192
239
|
onProgress?: (done: number, total: number) => void,
|
|
193
240
|
cacheFile?: string,
|
|
241
|
+
signal?: AbortSignal,
|
|
194
242
|
): Promise<UsageRecord[]> {
|
|
195
243
|
const files: string[] = [];
|
|
196
244
|
await sessionFiles(dir, files);
|
|
@@ -199,6 +247,7 @@ export async function collectUsage(
|
|
|
199
247
|
const records: UsageRecord[] = [];
|
|
200
248
|
let dirty = false;
|
|
201
249
|
for (const [done, file] of files.entries()) {
|
|
250
|
+
if (signal?.aborted) return records;
|
|
202
251
|
onProgress?.(done, files.length);
|
|
203
252
|
let info;
|
|
204
253
|
try {
|
|
@@ -215,14 +264,15 @@ export async function collectUsage(
|
|
|
215
264
|
}
|
|
216
265
|
dirty = true;
|
|
217
266
|
try {
|
|
218
|
-
const parsed = await parseFile(file);
|
|
267
|
+
const parsed = aggregate(await parseFile(file));
|
|
219
268
|
next[file] = { size: info.size, mtimeMs: info.mtimeMs, records: parsed };
|
|
220
269
|
for (const record of parsed) records.push(record);
|
|
221
270
|
} catch {
|
|
222
271
|
continue; // unreadable or truncated file: skip it, keep what other files gave
|
|
223
272
|
}
|
|
224
273
|
}
|
|
225
|
-
|
|
274
|
+
// A closed dashboard must not rewrite the cache with a partial scan.
|
|
275
|
+
if (!cacheFile || signal?.aborted) return records;
|
|
226
276
|
if (dirty || Object.keys(next).length !== Object.keys(cached).length) await writeCache(cacheFile, next);
|
|
227
277
|
return records;
|
|
228
278
|
}
|
|
@@ -334,13 +384,13 @@ export function buildRows(
|
|
|
334
384
|
groups.set(key, group);
|
|
335
385
|
}
|
|
336
386
|
addStats(group.stats, record);
|
|
337
|
-
group.requests
|
|
387
|
+
group.requests += record.requests;
|
|
338
388
|
if (mode === "model") group.providers!.add(record.provider);
|
|
339
389
|
if (mode === "provider") {
|
|
340
390
|
let model = group.models!.get(record.model);
|
|
341
391
|
if (!model) group.models!.set(record.model, (model = newTally()));
|
|
342
392
|
addStats(model.stats, record);
|
|
343
|
-
model.requests
|
|
393
|
+
model.requests += record.requests;
|
|
344
394
|
}
|
|
345
395
|
}
|
|
346
396
|
if (mode === "day") {
|
|
@@ -379,7 +429,7 @@ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinit
|
|
|
379
429
|
for (const record of records) {
|
|
380
430
|
if (record.ts < sinceMs || record.ts >= untilMs) continue;
|
|
381
431
|
addStats(stats, record);
|
|
382
|
-
requests
|
|
432
|
+
requests += record.requests;
|
|
383
433
|
sessions.add(record.sessionId);
|
|
384
434
|
}
|
|
385
435
|
return { stats, requests, sessions: sessions.size };
|