pi-tokenburn 0.0.0-stage โ 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 +64 -2
- package/extensions/tokenburn.ts +397 -0
- package/package.json +14 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sorinirimies
|
|
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
CHANGED
|
@@ -1,3 +1,65 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-tokenburn
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Token usage and cost monitor with budgets, directly in your [Pi](https://github.com/earendil-works/pi-coding-agent) session.
|
|
4
|
+
|
|
5
|
+
TypeScript port of the pi collector from [tokenburn](https://github.com/sorinirimies/tokenburn).
|
|
6
|
+
Reads Pi's local session logs (`~/.pi/agent/sessions/**/*.jsonl`). **No network, zero prompt tokens.**
|
|
7
|
+
Totals match the `tokenburn` CLI exactly.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- **Status bar:** `๐ฅ 1.20M ($52.79) [today]`, turns red with `OVER BUDGET` past your limit.
|
|
12
|
+
- **Window panel (optional):** Today / Week / Month / Total below the editor, with in/out tokens and cost.
|
|
13
|
+
- **Budgets** per day, week and month, in tokens and/or dollars.
|
|
14
|
+
- **Fast:** per-file cache keyed on mtime+size. First scan of ~400 MB of sessions takes under a second; refreshes after that take milliseconds. Refresh never blocks the agent loop.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pi install npm:pi-tokenburn
|
|
20
|
+
# or
|
|
21
|
+
pi install git:github.com/sorinirimies/pi-tokenburn
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Commands
|
|
25
|
+
|
|
26
|
+
| Command | What it does |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `/tokenburn` | Print the Today / Week / Month / All-time report |
|
|
29
|
+
| `/tokenburn window` | Toggle the panel below the editor |
|
|
30
|
+
| `/tokenburn status <today\|week\|month\|total>` | Period shown in the status bar |
|
|
31
|
+
| `/tokenburn budget <day\|week\|month> <tokens>` | Token budget, e.g. `budget day 5000000` |
|
|
32
|
+
| `/tokenburn budget <day\|week\|month> $<cost>` | Dollar budget, e.g. `budget week $50` |
|
|
33
|
+
| `/tokenburn cache` | Toggle counting cache read/write tokens |
|
|
34
|
+
|
|
35
|
+
Weeks start on Monday, in local time.
|
|
36
|
+
|
|
37
|
+
## Config
|
|
38
|
+
|
|
39
|
+
`~/.pi/agent/tokenburn.json` (written by the commands, editable by hand):
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"includeCache": true,
|
|
44
|
+
"showStatus": true,
|
|
45
|
+
"showWidget": false,
|
|
46
|
+
"statusWindow": "today",
|
|
47
|
+
"budgets": { "dayTokens": 5000000, "weekCost": 50 }
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- `includeCache` (default `true`): count cache read/write tokens in totals, like the `tokenburn` CLI. Cache reads dominate (often 95%+ of tokens) but are billed far cheaper; set `false` to budget on input + output only.
|
|
52
|
+
|
|
53
|
+
Environment overrides for the session directory: `TOKENBURN_PI_SESSIONS`, `PI_CODING_AGENT_SESSION_DIR`, `PI_CODING_AGENT_DIR`.
|
|
54
|
+
|
|
55
|
+
## Develop
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
bun test
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Scope
|
|
62
|
+
|
|
63
|
+
Pi sessions only. For Zed, Claude Code, Codex, Gemini and more, use the Rust [tokenburn](https://github.com/sorinirimies/tokenburn).
|
|
64
|
+
|
|
65
|
+
MIT
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-tokenburn โ token usage monitor with budget alerts in your Pi session.
|
|
3
|
+
*
|
|
4
|
+
* Inspired by the tokenburn Rust project (https://github.com/sorinirimies/tokenburn).
|
|
5
|
+
* Reads local Pi session JSONL logs directly (0 network, 0 prompt tokens).
|
|
6
|
+
*
|
|
7
|
+
* Features:
|
|
8
|
+
* - Status bar indicator: `๐ฅ 1.2M (today) ยท $0.45`
|
|
9
|
+
* - Optional widget window with Day / Week / Month / Total breakdown
|
|
10
|
+
* - Configurable limits with visual warning when budget threshold is exceeded
|
|
11
|
+
* - Commands:
|
|
12
|
+
* /tokenburn show token burn report
|
|
13
|
+
* /tokenburn window toggle permanent tokenburn widget in editor
|
|
14
|
+
* /tokenburn budget <d|w|m> <tokens|cost> set budget
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { readdirSync, statSync } from "node:fs";
|
|
18
|
+
import { open } from "node:fs/promises";
|
|
19
|
+
import { homedir } from "node:os";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
|
23
|
+
|
|
24
|
+
export interface TokenUsage {
|
|
25
|
+
input: number;
|
|
26
|
+
output: number;
|
|
27
|
+
cacheRead: number;
|
|
28
|
+
cacheWrite: number;
|
|
29
|
+
cost: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface PeriodStats {
|
|
33
|
+
/** input + output (+ cache read/write when includeCache). */
|
|
34
|
+
tokens: number;
|
|
35
|
+
input: number;
|
|
36
|
+
output: number;
|
|
37
|
+
cacheRead: number;
|
|
38
|
+
cacheWrite: number;
|
|
39
|
+
cost: number;
|
|
40
|
+
sessions: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface TokenBurnReport {
|
|
44
|
+
today: PeriodStats;
|
|
45
|
+
week: PeriodStats;
|
|
46
|
+
month: PeriodStats;
|
|
47
|
+
total: PeriodStats;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface TokenBurnConfig {
|
|
51
|
+
/** Count cache read/write tokens in totals (matches the tokenburn CLI). */
|
|
52
|
+
includeCache: boolean;
|
|
53
|
+
showStatus: boolean;
|
|
54
|
+
showWidget: boolean;
|
|
55
|
+
statusWindow: "today" | "week" | "month" | "total";
|
|
56
|
+
budgets: {
|
|
57
|
+
dayTokens?: number;
|
|
58
|
+
weekTokens?: number;
|
|
59
|
+
monthTokens?: number;
|
|
60
|
+
dayCost?: number;
|
|
61
|
+
weekCost?: number;
|
|
62
|
+
monthCost?: number;
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const DEFAULT_CONFIG: TokenBurnConfig = {
|
|
67
|
+
includeCache: true,
|
|
68
|
+
showStatus: true,
|
|
69
|
+
showWidget: false,
|
|
70
|
+
statusWindow: "today",
|
|
71
|
+
budgets: {},
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
function getConfigDir(): string {
|
|
75
|
+
if (process.env.PI_CODING_AGENT_DIR) return process.env.PI_CODING_AGENT_DIR;
|
|
76
|
+
if (process.env.XDG_CONFIG_HOME) return join(process.env.XDG_CONFIG_HOME, "pi", "agent");
|
|
77
|
+
return join(homedir(), ".pi", "agent");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function getSessionsDir(): string {
|
|
81
|
+
if (process.env.TOKENBURN_PI_SESSIONS) return process.env.TOKENBURN_PI_SESSIONS;
|
|
82
|
+
if (process.env.PI_CODING_AGENT_SESSION_DIR) return process.env.PI_CODING_AGENT_SESSION_DIR;
|
|
83
|
+
return join(getConfigDir(), "sessions");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function loadConfig(): Promise<TokenBurnConfig> {
|
|
87
|
+
try {
|
|
88
|
+
const raw = await readFile(join(getConfigDir(), "tokenburn.json"), "utf8");
|
|
89
|
+
const parsed = JSON.parse(raw);
|
|
90
|
+
return {
|
|
91
|
+
includeCache: typeof parsed.includeCache === "boolean" ? parsed.includeCache : DEFAULT_CONFIG.includeCache,
|
|
92
|
+
showStatus: typeof parsed.showStatus === "boolean" ? parsed.showStatus : DEFAULT_CONFIG.showStatus,
|
|
93
|
+
showWidget: typeof parsed.showWidget === "boolean" ? parsed.showWidget : DEFAULT_CONFIG.showWidget,
|
|
94
|
+
statusWindow: ["today", "week", "month", "total"].includes(parsed.statusWindow)
|
|
95
|
+
? parsed.statusWindow
|
|
96
|
+
: DEFAULT_CONFIG.statusWindow,
|
|
97
|
+
budgets: typeof parsed.budgets === "object" && parsed.budgets !== null ? parsed.budgets : {},
|
|
98
|
+
};
|
|
99
|
+
} catch {
|
|
100
|
+
return { ...DEFAULT_CONFIG };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function saveConfig(cfg: TokenBurnConfig): Promise<void> {
|
|
105
|
+
await mkdir(getConfigDir(), { recursive: true });
|
|
106
|
+
await writeFile(join(getConfigDir(), "tokenburn.json"), JSON.stringify(cfg, null, 2) + "\n", "utf8");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function formatNum(n: number): string {
|
|
110
|
+
if (n >= 1_000_000_000) return (n / 1_000_000_000).toFixed(2) + "B";
|
|
111
|
+
if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + "M";
|
|
112
|
+
if (n >= 1_000) return (n / 1_000).toFixed(1) + "k";
|
|
113
|
+
return n.toString();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function formatCost(c: number): string {
|
|
117
|
+
return `$${c.toFixed(2)}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface Turn {
|
|
121
|
+
ts: number;
|
|
122
|
+
input: number;
|
|
123
|
+
output: number;
|
|
124
|
+
cacheRead: number;
|
|
125
|
+
cacheWrite: number;
|
|
126
|
+
cost: number;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Parsed turns per session file, reused while the file is unchanged (mtime + size). */
|
|
130
|
+
const FILE_CACHE = new Map<string, { sig: string; turns: Turn[] }>();
|
|
131
|
+
|
|
132
|
+
async function parseFile(file: string): Promise<Turn[]> {
|
|
133
|
+
const turns: Turn[] = [];
|
|
134
|
+
try {
|
|
135
|
+
const fd = await open(file, "r");
|
|
136
|
+
try {
|
|
137
|
+
for await (const line of fd.readLines({ encoding: "utf8" })) {
|
|
138
|
+
if (!line.includes('"usage"')) continue;
|
|
139
|
+
try {
|
|
140
|
+
const obj = JSON.parse(line);
|
|
141
|
+
const usage = obj.message?.usage;
|
|
142
|
+
if (!obj.timestamp || !usage) continue;
|
|
143
|
+
const ts = new Date(obj.timestamp).getTime();
|
|
144
|
+
if (!Number.isFinite(ts)) continue;
|
|
145
|
+
turns.push({
|
|
146
|
+
ts,
|
|
147
|
+
input: Number(usage.input) || 0,
|
|
148
|
+
output: Number(usage.output) || 0,
|
|
149
|
+
cacheRead: Number(usage.cacheRead) || 0,
|
|
150
|
+
cacheWrite: Number(usage.cacheWrite) || 0,
|
|
151
|
+
cost: Number(usage.cost?.total) || 0,
|
|
152
|
+
});
|
|
153
|
+
} catch {}
|
|
154
|
+
}
|
|
155
|
+
} finally {
|
|
156
|
+
await fd.close();
|
|
157
|
+
}
|
|
158
|
+
} catch {}
|
|
159
|
+
return turns;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function listSessionFiles(root: string): string[] {
|
|
163
|
+
const files: string[] = [];
|
|
164
|
+
const walk = (dir: string) => {
|
|
165
|
+
let entries;
|
|
166
|
+
try {
|
|
167
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
168
|
+
} catch {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
for (const e of entries) {
|
|
172
|
+
const full = join(dir, e.name);
|
|
173
|
+
if (e.isDirectory()) walk(full);
|
|
174
|
+
else if (e.isFile() && e.name.endsWith(".jsonl")) files.push(full);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
walk(root);
|
|
178
|
+
return files;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const emptyStats = (): PeriodStats => ({
|
|
182
|
+
tokens: 0,
|
|
183
|
+
input: 0,
|
|
184
|
+
output: 0,
|
|
185
|
+
cacheRead: 0,
|
|
186
|
+
cacheWrite: 0,
|
|
187
|
+
cost: 0,
|
|
188
|
+
sessions: 0,
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
export async function collectUsage(
|
|
192
|
+
sessionsRoot: string,
|
|
193
|
+
now: Date = new Date(),
|
|
194
|
+
includeCache = true,
|
|
195
|
+
): Promise<TokenBurnReport> {
|
|
196
|
+
const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
|
197
|
+
const dayOfWeek = (now.getDay() + 6) % 7; // Monday = 0
|
|
198
|
+
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - dayOfWeek).getTime();
|
|
199
|
+
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1).getTime();
|
|
200
|
+
|
|
201
|
+
const report: TokenBurnReport = {
|
|
202
|
+
today: emptyStats(),
|
|
203
|
+
week: emptyStats(),
|
|
204
|
+
month: emptyStats(),
|
|
205
|
+
total: emptyStats(),
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const files = listSessionFiles(sessionsRoot);
|
|
209
|
+
const live = new Set(files);
|
|
210
|
+
for (const key of FILE_CACHE.keys()) if (!live.has(key)) FILE_CACHE.delete(key);
|
|
211
|
+
|
|
212
|
+
const add = (p: PeriodStats, t: Turn) => {
|
|
213
|
+
p.tokens += t.input + t.output + (includeCache ? t.cacheRead + t.cacheWrite : 0);
|
|
214
|
+
p.input += t.input;
|
|
215
|
+
p.output += t.output;
|
|
216
|
+
p.cacheRead += t.cacheRead;
|
|
217
|
+
p.cacheWrite += t.cacheWrite;
|
|
218
|
+
p.cost += t.cost;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
for (const file of files) {
|
|
222
|
+
let sig: string;
|
|
223
|
+
try {
|
|
224
|
+
const st = statSync(file);
|
|
225
|
+
sig = `${st.mtimeMs}:${st.size}`;
|
|
226
|
+
} catch {
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
let entry = FILE_CACHE.get(file);
|
|
230
|
+
if (!entry || entry.sig !== sig) {
|
|
231
|
+
entry = { sig, turns: await parseFile(file) };
|
|
232
|
+
FILE_CACHE.set(file, entry);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
let maxTs = 0;
|
|
236
|
+
for (const t of entry.turns) {
|
|
237
|
+
if (t.ts > maxTs) maxTs = t.ts;
|
|
238
|
+
add(report.total, t);
|
|
239
|
+
if (t.ts >= startOfMonth) add(report.month, t);
|
|
240
|
+
if (t.ts >= startOfWeek) add(report.week, t);
|
|
241
|
+
if (t.ts >= startOfDay) add(report.today, t);
|
|
242
|
+
}
|
|
243
|
+
if (entry.turns.length > 0) report.total.sessions++;
|
|
244
|
+
if (maxTs >= startOfMonth) report.month.sessions++;
|
|
245
|
+
if (maxTs >= startOfWeek) report.week.sessions++;
|
|
246
|
+
if (maxTs >= startOfDay) report.today.sessions++;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return report;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Clear the per-file cache (tests). */
|
|
253
|
+
export function clearCache(): void {
|
|
254
|
+
FILE_CACHE.clear();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export type Window = "today" | "week" | "month" | "total";
|
|
258
|
+
|
|
259
|
+
export function budgetsFor(cfg: TokenBurnConfig, w: Window): { tokens?: number; cost?: number } {
|
|
260
|
+
const b = cfg.budgets;
|
|
261
|
+
if (w === "today") return { tokens: b.dayTokens, cost: b.dayCost };
|
|
262
|
+
if (w === "week") return { tokens: b.weekTokens, cost: b.weekCost };
|
|
263
|
+
if (w === "month") return { tokens: b.monthTokens, cost: b.monthCost };
|
|
264
|
+
return {};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function isOverBudget(p: PeriodStats, b: { tokens?: number; cost?: number }): boolean {
|
|
268
|
+
return (b.tokens !== undefined && p.tokens > b.tokens) || (b.cost !== undefined && p.cost > b.cost);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export default function tokenBurnExtension(pi: ExtensionAPI) {
|
|
272
|
+
let config: TokenBurnConfig = { ...DEFAULT_CONFIG };
|
|
273
|
+
|
|
274
|
+
const updateUI = async (ctx: ExtensionContext) => {
|
|
275
|
+
if (!ctx.hasUI) return;
|
|
276
|
+
const report = await collectUsage(getSessionsDir(), new Date(), config.includeCache);
|
|
277
|
+
const theme = ctx.ui.theme;
|
|
278
|
+
|
|
279
|
+
// Status bar update
|
|
280
|
+
if (config.showStatus) {
|
|
281
|
+
const stat = report[config.statusWindow];
|
|
282
|
+
const isOver = isOverBudget(stat, budgetsFor(config, config.statusWindow));
|
|
283
|
+
const fire = isOver ? theme.fg("error", "๐ฅ OVER BUDGET") : theme.fg("warning", "๐ฅ");
|
|
284
|
+
const tokensText = theme.fg(isOver ? "error" : "accent", formatNum(stat.tokens));
|
|
285
|
+
const costText = theme.fg("dim", `(${formatCost(stat.cost)})`);
|
|
286
|
+
const label = theme.fg("dim", `[${config.statusWindow}]`);
|
|
287
|
+
|
|
288
|
+
ctx.ui.setStatus("tokenburn", `${fire} ${tokensText} ${costText} ${label}`);
|
|
289
|
+
} else {
|
|
290
|
+
ctx.ui.setStatus("tokenburn", "");
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Widget panel update
|
|
294
|
+
if (config.showWidget) {
|
|
295
|
+
const border = theme.fg("dim", "โ".repeat(46));
|
|
296
|
+
const header = theme.fg("accent", " ๐ฅ TokenBurn Dashboard ");
|
|
297
|
+
const line = (label: string, p: PeriodStats, b: { tokens?: number; cost?: number } = {}) => {
|
|
298
|
+
const over = isOverBudget(p, b);
|
|
299
|
+
const tokStr = (over ? theme.fg("error", "!") : " ") + formatNum(p.tokens).padStart(8);
|
|
300
|
+
const inStr = `(in:${formatNum(p.input)} out:${formatNum(p.output)})`.padEnd(20);
|
|
301
|
+
const costStr = formatCost(p.cost).padStart(8);
|
|
302
|
+
return ` ${theme.fg("muted", label.padEnd(8))} ${tokStr} ${theme.fg("dim", inStr)} ${costStr}`;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
const lines = [
|
|
306
|
+
`โ${header}${"โ".repeat(21)}โ`,
|
|
307
|
+
line("Today", report.today, budgetsFor(config, "today")),
|
|
308
|
+
line("Week", report.week, budgetsFor(config, "week")),
|
|
309
|
+
line("Month", report.month, budgetsFor(config, "month")),
|
|
310
|
+
line("Total", report.total),
|
|
311
|
+
`โ${"โ".repeat(46)}โ`,
|
|
312
|
+
];
|
|
313
|
+
|
|
314
|
+
ctx.ui.setWidget("tokenburn-panel", lines, { placement: "belowEditor" });
|
|
315
|
+
} else {
|
|
316
|
+
ctx.ui.setWidget("tokenburn-panel", []);
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
321
|
+
config = await loadConfig();
|
|
322
|
+
await updateUI(ctx);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
// Fire-and-forget: never block the agent loop on a stats refresh.
|
|
326
|
+
pi.on("turn_end", (_event, ctx) => {
|
|
327
|
+
void updateUI(ctx).catch(() => {});
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
pi.registerCommand("tokenburn", {
|
|
331
|
+
description: "TokenBurn stats: show report, toggle widget, or set budgets",
|
|
332
|
+
getArgumentCompletions: (prefix: string) => {
|
|
333
|
+
const opts = ["report", "window", "cache", "status <today|week|month|total>", "budget <day|week|month> <tokens|$cost>"];
|
|
334
|
+
return opts.filter((o) => o.startsWith(prefix)).map((value) => ({ value }));
|
|
335
|
+
},
|
|
336
|
+
handler: async (args, ctx) => {
|
|
337
|
+
const [cmd, p1, p2] = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
338
|
+
|
|
339
|
+
if (cmd === "window" || cmd === "widget") {
|
|
340
|
+
config.showWidget = !config.showWidget;
|
|
341
|
+
await saveConfig(config);
|
|
342
|
+
await updateUI(ctx);
|
|
343
|
+
ctx.ui.notify(`tokenburn widget: ${config.showWidget ? "enabled" : "hidden"}`, "info");
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (cmd === "status" && ["today", "week", "month", "total"].includes(p1)) {
|
|
348
|
+
config.statusWindow = p1 as any;
|
|
349
|
+
await saveConfig(config);
|
|
350
|
+
await updateUI(ctx);
|
|
351
|
+
ctx.ui.notify(`tokenburn status window set to: ${p1}`, "info");
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
if (cmd === "cache") {
|
|
356
|
+
config.includeCache = !config.includeCache;
|
|
357
|
+
await saveConfig(config);
|
|
358
|
+
await updateUI(ctx);
|
|
359
|
+
ctx.ui.notify(`tokenburn: cache tokens ${config.includeCache ? "included" : "excluded"}`, "info");
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (cmd === "budget") {
|
|
364
|
+
const isCost = (p2 ?? "").startsWith("$");
|
|
365
|
+
const val = Number((p2 ?? "").replace(/^\$/, ""));
|
|
366
|
+
if (!["day", "week", "month"].includes(p1 ?? "") || !Number.isFinite(val) || val <= 0) {
|
|
367
|
+
ctx.ui.notify("Usage: /tokenburn budget <day|week|month> <tokens | $cost>", "warning");
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
const key = `${p1}${isCost ? "Cost" : "Tokens"}` as keyof TokenBurnConfig["budgets"];
|
|
371
|
+
config.budgets[key] = val;
|
|
372
|
+
await saveConfig(config);
|
|
373
|
+
await updateUI(ctx);
|
|
374
|
+
ctx.ui.notify(`tokenburn ${p1} budget: ${isCost ? formatCost(val) : formatNum(val) + " tokens"}`, "info");
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// Default: print report
|
|
379
|
+
const report = await collectUsage(getSessionsDir(), new Date(), config.includeCache);
|
|
380
|
+
const formatRow = (name: string, p: PeriodStats) =>
|
|
381
|
+
`${name.padEnd(8)}: ${formatNum(p.tokens).padStart(8)} tokens (${formatCost(p.cost)}) ยท in:${formatNum(p.input)} out:${formatNum(p.output)} cache:${formatNum(p.cacheRead + p.cacheWrite)} ยท ${p.sessions} sessions`;
|
|
382
|
+
|
|
383
|
+
const output = [
|
|
384
|
+
"๐ฅ TokenBurn Report",
|
|
385
|
+
"--------------------------------------------------",
|
|
386
|
+
formatRow("Today", report.today),
|
|
387
|
+
formatRow("This Week", report.week),
|
|
388
|
+
formatRow("This Month", report.month),
|
|
389
|
+
formatRow("All Time", report.total),
|
|
390
|
+
"--------------------------------------------------",
|
|
391
|
+
`Use '/tokenburn window' to toggle persistent status window.`,
|
|
392
|
+
].join("\n");
|
|
393
|
+
|
|
394
|
+
ctx.ui.notify(output, "info");
|
|
395
|
+
},
|
|
396
|
+
});
|
|
397
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-tokenburn",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Pi extension for live token usage monitoring and budget tracking (Day / Week / Month / Total). 0 prompt tokens.",
|
|
5
|
+
"keywords": ["pi-package", "pi-extension", "tokenburn", "tokens", "analytics", "budget", "stats"],
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "sorinirimies",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/sorinirimies/pi-tokenburn.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/sorinirimies/pi-tokenburn#readme",
|
|
13
|
+
"files": ["extensions", "README.md", "LICENSE"],
|
|
14
|
+
"pi": { "extensions": ["./extensions/tokenburn.ts"] },
|
|
15
|
+
"peerDependencies": { "@earendil-works/pi-coding-agent": "*" }
|
|
16
|
+
}
|