@firstpick/pi-extension-stats 0.1.0
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/LICENSE +21 -0
- package/README.md +30 -0
- package/index.ts +260 -0
- package/package.json +25 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Firstpick
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# pi-extension-stats
|
|
2
|
+
|
|
3
|
+
Token and cost analytics for Pi session history.
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
- Parses local Pi session `.jsonl` files for the current workspace.
|
|
8
|
+
- Aggregates usage by UTC day.
|
|
9
|
+
- Displays compact daily token bars with totals.
|
|
10
|
+
- Shows input/output/cache breakdown and top model usage.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pi install npm:@firstpick/pi-extension-stats
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Configuration
|
|
19
|
+
|
|
20
|
+
No required configuration.
|
|
21
|
+
|
|
22
|
+
## Commands
|
|
23
|
+
|
|
24
|
+
- `/stats` — show last 14 days.
|
|
25
|
+
- `/stats <days>` — show last N days.
|
|
26
|
+
- `/stats all` — show all available days.
|
|
27
|
+
|
|
28
|
+
## Tools
|
|
29
|
+
|
|
30
|
+
None.
|
package/index.ts
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
4
|
+
|
|
5
|
+
type DayUsage = {
|
|
6
|
+
input: number;
|
|
7
|
+
output: number;
|
|
8
|
+
cacheRead: number;
|
|
9
|
+
cacheWrite: number;
|
|
10
|
+
total: number;
|
|
11
|
+
cost: number;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
type UsageRecord = {
|
|
15
|
+
day: string;
|
|
16
|
+
input: number;
|
|
17
|
+
output: number;
|
|
18
|
+
cacheRead: number;
|
|
19
|
+
cacheWrite: number;
|
|
20
|
+
total: number;
|
|
21
|
+
cost: number;
|
|
22
|
+
model: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const DEFAULT_DAYS = 14;
|
|
26
|
+
const MAX_BAR_WIDTH = 24;
|
|
27
|
+
|
|
28
|
+
function formatTokens(count: number): string {
|
|
29
|
+
if (count < 1000) return count.toString();
|
|
30
|
+
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
|
31
|
+
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
|
32
|
+
if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;
|
|
33
|
+
return `${Math.round(count / 1000000)}M`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function getDayKey(timestamp: string): string | null {
|
|
37
|
+
const parsed = Date.parse(timestamp);
|
|
38
|
+
if (!Number.isFinite(parsed)) return null;
|
|
39
|
+
return new Date(parsed).toISOString().slice(0, 10);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parseDaysArg(args: string): { mode: "range"; days: number } | { mode: "all" } | null {
|
|
43
|
+
const trimmed = args.trim().toLowerCase();
|
|
44
|
+
if (!trimmed) return { mode: "range", days: DEFAULT_DAYS };
|
|
45
|
+
if (trimmed === "all") return { mode: "all" };
|
|
46
|
+
|
|
47
|
+
const n = Number.parseInt(trimmed, 10);
|
|
48
|
+
if (!Number.isFinite(n) || n <= 0 || n > 3650) return null;
|
|
49
|
+
return { mode: "range", days: n };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function listSessionFiles(sessionDir: string): string[] {
|
|
53
|
+
try {
|
|
54
|
+
return fs
|
|
55
|
+
.readdirSync(sessionDir, { withFileTypes: true })
|
|
56
|
+
.filter((e) => e.isFile() && e.name.endsWith(".jsonl"))
|
|
57
|
+
.map((e) => path.join(sessionDir, e.name));
|
|
58
|
+
} catch {
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function collectUsageRecords(sessionFiles: string[]): UsageRecord[] {
|
|
64
|
+
const records: UsageRecord[] = [];
|
|
65
|
+
|
|
66
|
+
for (const file of sessionFiles) {
|
|
67
|
+
let content: string;
|
|
68
|
+
try {
|
|
69
|
+
content = fs.readFileSync(file, "utf8");
|
|
70
|
+
} catch {
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
for (const line of content.split(/\r?\n/)) {
|
|
75
|
+
if (!line.trim()) continue;
|
|
76
|
+
|
|
77
|
+
let entry: any;
|
|
78
|
+
try {
|
|
79
|
+
entry = JSON.parse(line);
|
|
80
|
+
} catch {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (entry?.type !== "message") continue;
|
|
85
|
+
if (entry?.message?.role !== "assistant") continue;
|
|
86
|
+
|
|
87
|
+
const usage = entry?.message?.usage;
|
|
88
|
+
if (!usage || typeof usage !== "object") continue;
|
|
89
|
+
|
|
90
|
+
const day = getDayKey(entry?.timestamp ?? "");
|
|
91
|
+
if (!day) continue;
|
|
92
|
+
|
|
93
|
+
const input = Number(usage.input ?? 0) || 0;
|
|
94
|
+
const output = Number(usage.output ?? 0) || 0;
|
|
95
|
+
const cacheRead = Number(usage.cacheRead ?? 0) || 0;
|
|
96
|
+
const cacheWrite = Number(usage.cacheWrite ?? 0) || 0;
|
|
97
|
+
const total = Number(usage.totalTokens ?? input + output + cacheRead + cacheWrite) || 0;
|
|
98
|
+
const cost = Number(usage?.cost?.total ?? 0) || 0;
|
|
99
|
+
const provider = String(entry?.message?.provider ?? "unknown");
|
|
100
|
+
const model = String(entry?.message?.responseModel ?? entry?.message?.model ?? "unknown");
|
|
101
|
+
|
|
102
|
+
records.push({
|
|
103
|
+
day,
|
|
104
|
+
input,
|
|
105
|
+
output,
|
|
106
|
+
cacheRead,
|
|
107
|
+
cacheWrite,
|
|
108
|
+
total,
|
|
109
|
+
cost,
|
|
110
|
+
model: `${provider}/${model}`,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return records;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function aggregateUsageByDay(records: UsageRecord[]): Map<string, DayUsage> {
|
|
119
|
+
const byDay = new Map<string, DayUsage>();
|
|
120
|
+
for (const r of records) {
|
|
121
|
+
const prev = byDay.get(r.day) ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, cost: 0 };
|
|
122
|
+
prev.input += r.input;
|
|
123
|
+
prev.output += r.output;
|
|
124
|
+
prev.cacheRead += r.cacheRead;
|
|
125
|
+
prev.cacheWrite += r.cacheWrite;
|
|
126
|
+
prev.total += r.total;
|
|
127
|
+
prev.cost += r.cost;
|
|
128
|
+
byDay.set(r.day, prev);
|
|
129
|
+
}
|
|
130
|
+
return byDay;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function buildDayRange(days: number): string[] {
|
|
134
|
+
const keys: string[] = [];
|
|
135
|
+
const now = new Date();
|
|
136
|
+
now.setUTCHours(0, 0, 0, 0);
|
|
137
|
+
|
|
138
|
+
for (let i = days - 1; i >= 0; i--) {
|
|
139
|
+
const d = new Date(now);
|
|
140
|
+
d.setUTCDate(d.getUTCDate() - i);
|
|
141
|
+
keys.push(d.toISOString().slice(0, 10));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return keys;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function getScopeDayKeys(byDay: Map<string, DayUsage>, args: { mode: "range"; days: number } | { mode: "all" }): string[] {
|
|
148
|
+
return args.mode === "all"
|
|
149
|
+
? Array.from(byDay.keys()).sort((a, b) => a.localeCompare(b))
|
|
150
|
+
: buildDayRange(args.days);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function aggregateModelUsage(records: UsageRecord[], dayKeys: string[]): Array<{ model: string; tokens: number; percent: number; cost: number }> {
|
|
154
|
+
if (dayKeys.length === 0) return [];
|
|
155
|
+
|
|
156
|
+
const daySet = new Set(dayKeys);
|
|
157
|
+
const modelTotals = new Map<string, { tokens: number; cost: number }>();
|
|
158
|
+
let totalTokens = 0;
|
|
159
|
+
|
|
160
|
+
for (const r of records) {
|
|
161
|
+
if (!daySet.has(r.day)) continue;
|
|
162
|
+
totalTokens += r.total;
|
|
163
|
+
const prev = modelTotals.get(r.model) ?? { tokens: 0, cost: 0 };
|
|
164
|
+
prev.tokens += r.total;
|
|
165
|
+
prev.cost += r.cost;
|
|
166
|
+
modelTotals.set(r.model, prev);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (totalTokens <= 0) return [];
|
|
170
|
+
|
|
171
|
+
return Array.from(modelTotals.entries())
|
|
172
|
+
.map(([model, v]) => ({ model, tokens: v.tokens, percent: (v.tokens / totalTokens) * 100, cost: v.cost }))
|
|
173
|
+
.sort((a, b) => b.tokens - a.tokens)
|
|
174
|
+
.slice(0, 3);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function buildGraphLines(byDay: Map<string, DayUsage>, dayKeys: string[]): string[] {
|
|
178
|
+
if (dayKeys.length === 0) {
|
|
179
|
+
return ["No usage data found yet."];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const data = dayKeys.map((day) => ({
|
|
183
|
+
day,
|
|
184
|
+
usage: byDay.get(day) ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, cost: 0 },
|
|
185
|
+
}));
|
|
186
|
+
|
|
187
|
+
const maxTotal = Math.max(...data.map((d) => d.usage.total), 0);
|
|
188
|
+
const lines: string[] = [];
|
|
189
|
+
|
|
190
|
+
for (const { day, usage } of data) {
|
|
191
|
+
const barLen =
|
|
192
|
+
usage.total <= 0 || maxTotal <= 0 ? 0 : Math.max(1, Math.round((usage.total / maxTotal) * MAX_BAR_WIDTH));
|
|
193
|
+
const bar = "█".repeat(barLen).padEnd(MAX_BAR_WIDTH, "·");
|
|
194
|
+
|
|
195
|
+
lines.push(
|
|
196
|
+
`${day} ${bar} ${formatTokens(usage.total)} tok (↑${formatTokens(usage.input)} ↓${formatTokens(usage.output)} R${formatTokens(usage.cacheRead)} W${formatTokens(usage.cacheWrite)})`,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const totals = data.reduce(
|
|
201
|
+
(acc, d) => {
|
|
202
|
+
acc.input += d.usage.input;
|
|
203
|
+
acc.output += d.usage.output;
|
|
204
|
+
acc.cacheRead += d.usage.cacheRead;
|
|
205
|
+
acc.cacheWrite += d.usage.cacheWrite;
|
|
206
|
+
acc.total += d.usage.total;
|
|
207
|
+
acc.cost += d.usage.cost;
|
|
208
|
+
return acc;
|
|
209
|
+
},
|
|
210
|
+
{ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, cost: 0 },
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
lines.push(
|
|
214
|
+
"",
|
|
215
|
+
`Σ ${formatTokens(totals.total)} tok (↑${formatTokens(totals.input)} ↓${formatTokens(totals.output)} R${formatTokens(totals.cacheRead)} W${formatTokens(totals.cacheWrite)}) · $${totals.cost.toFixed(3)}`,
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
return lines;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export default function statsExtension(pi: ExtensionAPI) {
|
|
222
|
+
pi.registerCommand("stats", {
|
|
223
|
+
description: "Show token usage graph per day. Usage: /stats, /stats 30, /stats all",
|
|
224
|
+
handler: async (args, ctx) => {
|
|
225
|
+
const parsedArgs = parseDaysArg(args);
|
|
226
|
+
if (!parsedArgs) {
|
|
227
|
+
ctx.ui.notify("Usage: /stats [days|all] e.g. /stats, /stats 30, /stats all", "warning");
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const sessionDir = ctx.sessionManager.getSessionDir();
|
|
232
|
+
const files = listSessionFiles(sessionDir);
|
|
233
|
+
if (files.length === 0) {
|
|
234
|
+
ctx.ui.notify("No sessions found for this workspace yet.", "info");
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const records = collectUsageRecords(files);
|
|
239
|
+
const byDay = aggregateUsageByDay(records);
|
|
240
|
+
const dayKeys = getScopeDayKeys(byDay, parsedArgs);
|
|
241
|
+
const lines = buildGraphLines(byDay, dayKeys);
|
|
242
|
+
const topModels = aggregateModelUsage(records, dayKeys);
|
|
243
|
+
const scopeLabel = parsedArgs.mode === "all" ? "all days" : `last ${parsedArgs.days} days`;
|
|
244
|
+
|
|
245
|
+
const hasAnyModelCost = topModels.some((m) => m.cost > 0);
|
|
246
|
+
const modelLines =
|
|
247
|
+
topModels.length === 0
|
|
248
|
+
? ["Top models: no model usage in selected range"]
|
|
249
|
+
: [
|
|
250
|
+
"Top models:",
|
|
251
|
+
...topModels.map((m, i) => {
|
|
252
|
+
const costPart = hasAnyModelCost ? ` · $${m.cost.toFixed(3)}` : "";
|
|
253
|
+
return `${i + 1}. ${m.model} — ${m.percent.toFixed(1)}% (${formatTokens(m.tokens)} tok)${costPart}`;
|
|
254
|
+
}),
|
|
255
|
+
];
|
|
256
|
+
|
|
257
|
+
ctx.ui.notify(`📊 Token stats (${scopeLabel}, ${files.length} sessions)\n\n${lines.join("\n")}\n\n${modelLines.join("\n")}`, "info");
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@firstpick/pi-extension-stats",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Token and cost usage analytics command for Pi session history.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi",
|
|
9
|
+
"pi-coding-agent",
|
|
10
|
+
"extension"
|
|
11
|
+
],
|
|
12
|
+
"pi": {
|
|
13
|
+
"extensions": [
|
|
14
|
+
"./index.ts"
|
|
15
|
+
]
|
|
16
|
+
},
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"@mariozechner/pi-coding-agent": "*"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"index.ts",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
]
|
|
25
|
+
}
|