-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoken-meter.mjs
More file actions
1407 lines (1244 loc) · 56.1 KB
/
Copy pathtoken-meter.mjs
File metadata and controls
1407 lines (1244 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Agent Token Meter — zero-dependency burn-rate monitor for AI coding agents.
*
* Reads session logs and displays live token usage with burn-rate
* acceleration, compaction prediction, and workflow advisor.
*
* Currently supports: Claude Code. More agents planned.
*
* Usage:
* npx agent-token-meter # auto-detect agent and session
* npx agent-token-meter --all # summary of all sessions
* npx agent-token-meter --help # show help
*/
import fs from "fs";
import path from "path";
import os from "os";
import { fileURLToPath } from "url";
import * as protocol from "./protocol.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// VERSION is sourced from package.json so a single bump stays in sync
// across dashboard header, --version, help text, and the npm tarball.
const VERSION = (() => {
try {
return JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"), "utf8")).version;
} catch { return "0.0.0"; }
})();
// ── Agent Profiles ───────────────────────────────────────────────────
// Each profile defines everything agent-specific. To add a new agent,
// add an entry here with the same shape.
const AGENTS = {
"claude-code": {
id: "claude-code",
name: "Claude Code",
sessionDir: () => path.join(os.homedir(), ".claude", "projects"),
configDir: () => path.join(os.homedir(), ".claude"),
configFile: "token-meter.json",
pricing: {
"claude-opus-4-7": { input: 15, output: 75, cacheWrite: 18.75, cacheRead: 1.5 },
"claude-opus-4-6": { input: 15, output: 75, cacheWrite: 18.75, cacheRead: 1.5 },
"claude-opus-4-5": { input: 15, output: 75, cacheWrite: 18.75, cacheRead: 1.5 },
"claude-sonnet-4-6": { input: 3, output: 15, cacheWrite: 3.75, cacheRead: 0.3 },
"claude-sonnet-4-5": { input: 3, output: 15, cacheWrite: 3.75, cacheRead: 0.3 },
"claude-haiku-4-5": { input: 0.8, output: 4, cacheWrite: 1, cacheRead: 0.08 },
},
defaultPricing: { input: 15, output: 75, cacheWrite: 18.75, cacheRead: 1.5 },
contextLimits: {
"claude-opus-4-7": 1_000_000,
"claude-opus-4-6": 1_000_000,
"claude-opus-4-5": 1_000_000,
"claude-sonnet-4-6": 1_000_000,
"claude-sonnet-4-5": 200_000,
"claude-haiku-4-5": 200_000,
},
defaultContextLimit: 1_000_000,
commands: { clear: "/clear", compact: "/compact" },
hook: {
supported: true,
settingsPath: () => path.join(os.homedir(), ".claude", "settings.json"),
hookDir: () => path.join(os.homedir(), ".claude", "hooks"),
hookEvent: "PostToolUse",
hookFileName: "token-meter-hook.mjs",
stateFile: "token-meter-hook-state.json",
},
detect: () => {
try { return fs.existsSync(path.join(os.homedir(), ".claude", "projects")); }
catch { return false; }
},
},
};
// ── External provider pricing (cross-agent comparisons) ──────────────
const EXTERNAL_PROVIDERS = {
"kimi-k2.5": { input: 0.6, output: 3.0, cacheWrite: 0.6, cacheRead: 0.15 },
"kimi-k2-thinking": { input: 0.6, output: 2.5, cacheWrite: 0.6, cacheRead: 0.15 },
};
const EXTERNAL_CONTEXT_LIMITS = {
"kimi-k2.5": 262_144,
"kimi-k2-thinking": 262_144,
};
// ── Constants ────────────────────────────────────────────────────────
const COMPACT_BUFFER = 33_000;
const HANDOFF_SIZE = 2_000;
const CLEAR_LOOKAHEAD = 20;
const OUTPUT_RATIO_WARN = 0.03; // warn when output > 3% of total inputs (verbose agent)
const DEFAULT_COMPARE = ["claude-sonnet-4-6", "kimi-k2.5"];
// ── ANSI ──────────────────────────────────────────────────────────────
const DIM = "\x1b[2m";
const BOLD = "\x1b[1m";
const RESET = "\x1b[0m";
const CYAN = "\x1b[36m";
const YELLOW = "\x1b[33m";
const GREEN = "\x1b[32m";
const RED = "\x1b[31m";
const MAGENTA = "\x1b[35m";
const WHITE = "\x1b[37m";
const BG_RED = "\x1b[41m";
const DIM_CYAN = "\x1b[2;36m";
const BG_WHITE = "\x1b[47m";
// Render sequence for dashboard refresh. Uses the alt-screen buffer so
// repeated redraws don't accumulate in terminal scrollback (a default
// behavior of Windows Terminal that visually duplicated the header
// across scrollback frames in pre-1.2.1).
const ENTER_ALT = "\x1b[?1049h\x1b[?25l"; // enter alt screen + hide cursor
const LEAVE_ALT = "\x1b[?25h\x1b[?1049l"; // show cursor + leave alt screen
const CLR_SCR = "\x1b[H\x1b[2J"; // home cursor then clear (no scrollback push in alt screen)
// ── Workflow phases ───────────────────────────────────────────────────
const PHASES = [
{ maxPct: 10, name: "EXPLORE", color: GREEN, advice: "Context is cheap. Explore, plan, read broadly." },
{ maxPct: 25, name: "BUILD", color: CYAN, advice: "Productive zone. Context is earning its keep." },
{ maxPct: 45, name: "HANDOFF", color: YELLOW, advice: "Write a plan file soon: \"save our plan to plan.md\"" },
{ maxPct: 100, name: "RESET", color: RED, advice: "Write handoff, then {{clear}}. Reload with the plan file." },
];
// ── Helpers ───────────────────────────────────────────────────────────
function fmtTokens(n) {
if (n >= 1e6) return (n / 1e6).toFixed(1) + "M";
if (n >= 1e3) return (n / 1e3).toFixed(1) + "k";
return String(n);
}
function fmtCost(n) {
return n < 0.01 ? "$" + n.toFixed(4) : "$" + n.toFixed(2);
}
function fmtDuration(ms) {
const s = Math.floor(ms / 1000);
if (s < 60) return s + "s";
const m = Math.floor(s / 60);
if (m < 60) return m + "m " + (s % 60) + "s";
const h = Math.floor(m / 60);
return h + "h " + (m % 60) + "m";
}
function bar(pct, width = 30) {
const clamped = Math.max(0, Math.min(100, pct));
const filled = Math.round((clamped / 100) * width);
const empty = width - filled;
const color = pct > 80 ? RED : pct > 50 ? YELLOW : GREEN;
return `${color}${"█".repeat(filled)}${DIM}${"░".repeat(empty)}${RESET}`;
}
// Claude Code encodes a working directory into its project subdirectory
// by replacing `/`, `\`, and `:` each with `-`. Verified against real
// dirs: B:\A5DS-HQ\agent-token-meter → B--A5DS-HQ-agent-token-meter.
function cwdToProjectName(cwd) {
return cwd.replace(/[/\\:]/g, "-");
}
// ── Agent resolution ─────────────────────────────────────────────────
function resolveAgent(args) {
// 1. Explicit --agent flag
const agentIdx = args.indexOf("--agent");
if (agentIdx >= 0 && agentIdx + 1 < args.length) {
const id = args[agentIdx + 1];
if (!AGENTS[id]) {
console.error(`${RED}Unknown agent: ${id}${RESET}`);
console.error(`${DIM}Supported: ${Object.keys(AGENTS).join(", ")}${RESET}`);
process.exit(1);
}
return AGENTS[id];
}
// 2. Infer from positional file path
const positional = args.filter(a => !a.startsWith("--"));
if (positional.length > 0) {
const fp = positional[0].toLowerCase();
for (const profile of Object.values(AGENTS)) {
if (fp.includes(`.${profile.id.split("-")[0]}`)) return profile;
}
}
// 3. Auto-detect
for (const profile of Object.values(AGENTS)) {
if (profile.detect()) return profile;
}
// 4. No agent found
console.error(`${RED}No supported agent detected.${RESET}`);
console.error(`${DIM}Supported agents: ${Object.values(AGENTS).map(a => a.name).join(", ")}${RESET}`);
console.error(`${DIM}Use --agent <id> to specify manually.${RESET}`);
process.exit(1);
}
function renderAgents() {
console.log(`\n${BOLD}Supported Agents${RESET}\n`);
console.log(` ${"Agent".padEnd(20)} ${"Status".padEnd(12)} Data Directory`);
console.log(` ${DIM}${"─".repeat(60)}${RESET}`);
for (const p of Object.values(AGENTS)) {
const detected = p.detect();
const status = detected ? `${GREEN}detected${RESET}` : `${DIM}not found${RESET}`;
console.log(` ${p.name.padEnd(20)} ${status}${" ".repeat(Math.max(0, 12 - (detected ? 8 : 9)))} ${DIM}${p.sessionDir()}${RESET}`);
}
console.log();
}
// ── Config & provider resolution ─────────────────────────────────────
function loadConfig(profile) {
try {
const configPath = path.join(profile.configDir(), profile.configFile);
return JSON.parse(fs.readFileSync(configPath, "utf8"));
} catch {
return {};
}
}
function resolveConfig(config, profile) {
const allPricing = { ...profile.pricing, ...EXTERNAL_PROVIDERS };
const allLimits = { ...profile.contextLimits, ...EXTERNAL_CONTEXT_LIMITS };
if (config.providers) {
for (const [k, v] of Object.entries(config.providers)) {
if (v.input != null && v.output != null) allPricing[k] = v;
if (v.context) allLimits[k] = v.context;
}
}
return {
allPricing,
allLimits,
defaultPricing: profile.defaultPricing,
defaultContextLimit: profile.defaultContextLimit,
compare: config.compare || DEFAULT_COMPARE,
labels: Object.fromEntries(
Object.entries(config.providers || {})
.filter(([, v]) => v.label)
.map(([k, v]) => [k, v.label])
),
};
}
function findPricing(model, rc) {
if (rc.allPricing[model]) return rc.allPricing[model];
for (const key of Object.keys(rc.allPricing)) {
if (model.startsWith(key)) return rc.allPricing[key];
}
return rc.defaultPricing;
}
function findContextLimit(model, rc) {
if (rc.allLimits[model]) return rc.allLimits[model];
for (const key of Object.keys(rc.allLimits)) {
if (model.startsWith(key)) return rc.allLimits[key];
}
return rc.defaultContextLimit;
}
function providerLabel(key, labels) {
if (labels && labels[key]) return labels[key];
const m = key.match(/^claude-(\w+)-(\d+)-(\d+)/);
if (m) return m[1].charAt(0).toUpperCase() + m[1].slice(1) + " " + m[2] + "." + m[3];
return key.split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
}
// ── Session discovery ─────────────────────────────────────────────────
function findSessions(projectFilter, profile, opts = {}) {
const projectsDir = profile.sessionDir();
const results = [];
if (!fs.existsSync(projectsDir)) return results;
let projects;
try {
projects = fs.readdirSync(projectsDir);
} catch {
return results;
}
const matchFilter = opts.exact
? (proj) => proj === projectFilter
: (proj) => proj.toLowerCase().includes(projectFilter.toLowerCase());
for (const proj of projects) {
if (projectFilter && !matchFilter(proj)) continue;
const projPath = path.join(projectsDir, proj);
let stat;
try { stat = fs.statSync(projPath); } catch { continue; }
if (!stat.isDirectory()) continue;
let files;
try { files = fs.readdirSync(projPath); } catch { continue; }
for (const file of files) {
if (!file.endsWith(".jsonl")) continue;
const fullPath = path.join(projPath, file);
try {
const fstat = fs.statSync(fullPath);
results.push({ path: fullPath, project: proj, mtime: fstat.mtimeMs, size: fstat.size });
} catch { /* skip unreadable */ }
}
}
return results.sort((a, b) => b.mtime - a.mtime);
}
// ── JSONL parser ──────────────────────────────────────────────────────
function parseSession(filePath) {
let content;
try {
content = fs.readFileSync(filePath, "utf8");
} catch (e) {
return { turns: [], userTurns: 0, compactions: [], model: "unknown", project: "", filePath };
}
const lines = content.split("\n");
const apiCalls = [];
const userTimestamps = [];
let model = "unknown";
let project = "";
// Extract project name from path
const sep = /[\\/]/;
const parts = filePath.split(sep);
const pidx = parts.indexOf("projects");
if (pidx >= 0 && pidx + 1 < parts.length) project = parts[pidx + 1];
for (const line of lines) {
if (!line) continue;
let obj;
try { obj = JSON.parse(line); } catch { continue; }
// Track user messages for turn grouping
if (obj.type === "user" && obj.message?.role === "user") {
const isToolResult = Array.isArray(obj.message.content) &&
obj.message.content.some(c => c.type === "tool_result");
if (!isToolResult) {
userTimestamps.push(obj.timestamp || "");
}
}
// Track assistant API responses with usage
if (obj.type === "assistant" && obj.message?.usage) {
const u = obj.message.usage;
const input = u.input_tokens || 0;
const output = u.output_tokens || 0;
const cacheCreate = u.cache_creation_input_tokens || 0;
const cacheRead = u.cache_read_input_tokens || 0;
const thinking = u.thinking_tokens || 0;
if (input === 0 && output === 0 && cacheCreate === 0 && cacheRead === 0) continue;
if (obj.message.model) model = obj.message.model;
apiCalls.push({
input, output, cacheCreate, cacheRead, thinking,
contextSize: input + cacheCreate + cacheRead,
model: obj.message.model || model,
stopReason: obj.message.stop_reason || "?",
timestamp: obj.timestamp || "",
});
}
}
// Detect compaction events: context drops > 20% between consecutive calls
const compactions = [];
for (let i = 1; i < apiCalls.length; i++) {
const prev = apiCalls[i - 1].contextSize;
const curr = apiCalls[i].contextSize;
if (prev > 0 && curr < prev * 0.8 && (prev - curr) > 5000) {
compactions.push({
index: i,
before: prev,
after: curr,
reduction: prev - curr,
timestamp: apiCalls[i].timestamp,
});
}
}
return { turns: apiCalls, userTurns: userTimestamps.length, compactions, model, project, filePath };
}
// ── Metrics engine ────────────────────────────────────────────────────
function computeMetrics(session, rc) {
const { turns, compactions, model } = session;
if (turns.length === 0) return null;
const contextLimit = findContextLimit(model, rc);
const usableContext = contextLimit - COMPACT_BUFFER;
const pricing = findPricing(model, rc);
let totalInput = 0, totalOutput = 0, totalCacheCreate = 0, totalCacheRead = 0, totalCost = 0;
const turnCosts = [];
const contextSizes = [];
for (const t of turns) {
totalInput += t.input;
totalOutput += t.output;
totalCacheCreate += t.cacheCreate;
totalCacheRead += t.cacheRead;
const cost =
(t.input / 1e6) * pricing.input +
(t.output / 1e6) * pricing.output +
(t.cacheCreate / 1e6) * pricing.cacheWrite +
(t.cacheRead / 1e6) * pricing.cacheRead;
totalCost += cost;
turnCosts.push(cost);
contextSizes.push(t.contextSize);
}
const currentContext = contextSizes[contextSizes.length - 1] || 0;
const contextPct = (currentContext / usableContext) * 100;
// ── Burn rate (last 10 API calls, after last compaction) ──
const lastCompactIdx = compactions.length > 0 ? compactions[compactions.length - 1].index : 0;
const postCompactSizes = contextSizes.slice(lastCompactIdx);
const window = Math.min(10, postCompactSizes.length);
let burnRate = 0;
if (postCompactSizes.length >= 2) {
const recent = postCompactSizes.slice(-window);
burnRate = (recent[recent.length - 1] - recent[0]) / (recent.length - 1);
}
// ── Acceleration (burn rate change: last 5 vs previous 5) ──
let acceleration = 0;
if (postCompactSizes.length >= 10) {
const older = postCompactSizes.slice(-10, -5);
const newer = postCompactSizes.slice(-5);
const olderRate = (older[older.length - 1] - older[0]) / (older.length - 1);
const newerRate = (newer[newer.length - 1] - newer[0]) / (newer.length - 1);
acceleration = newerRate - olderRate;
}
// ── Compaction ETA ──
const remaining = usableContext - currentContext;
const turnsToCompact = burnRate > 0
? Math.max(0, Math.floor(remaining / burnRate))
: Infinity;
const overContext = currentContext > usableContext;
// ── Cost rate ──
const recentCosts = turnCosts.slice(-10);
const avgCostPerTurn = recentCosts.reduce((a, b) => a + b, 0) / recentCosts.length;
// ── Cache efficiency ──
const totalBilledInput = totalInput + totalCacheCreate + totalCacheRead;
const cacheHitRate = totalBilledInput > 0 ? (totalCacheRead / totalBilledInput) * 100 : 0;
// ── Session duration ──
const firstTs = turns[0].timestamp;
const lastTs = turns[turns.length - 1].timestamp;
let durationMs = 0;
if (firstTs && lastTs) {
durationMs = new Date(lastTs).getTime() - new Date(firstTs).getTime();
}
// ── Workflow advisor ──
const baseline = contextSizes.length > 0 ? contextSizes[0] : 16_000;
const overhead = Math.max(0, currentContext - baseline);
const overheadPct = (overhead / usableContext) * 100;
const contextTaxPerCall = (overhead / 1e6) * pricing.cacheRead;
const postClearContext = baseline + HANDOFF_SIZE;
const savedPerCall = ((currentContext - postClearContext) / 1e6) * pricing.cacheRead;
const savingsOverLookahead = savedPerCall * CLEAR_LOOKAHEAD;
// ── Per-call cost multiplier (current call vs fresh-conversation call) ──
// Cache-read dominates billing and scales linearly with context, so the
// context-size ratio closely approximates the $/call ratio. Keep one
// decimal so the user can distinguish ×1.2 (fresh) from ×1.8 (warming up).
const multiplier = baseline > 0 ? Math.max(1, currentContext / baseline) : 1;
const baselineCostPerCall = (baseline / 1e6) * pricing.cacheRead;
// ── Reset-overdue duration (when context has already exceeded usable) ──
let overdueMs = 0;
if (overContext) {
for (const t of turns) {
if (t.contextSize > usableContext) {
const ts = t.timestamp ? new Date(t.timestamp).getTime() : 0;
if (ts > 0) overdueMs = Date.now() - ts;
break;
}
}
}
let phase = PHASES[PHASES.length - 1];
for (const p of PHASES) {
if (overheadPct <= p.maxPct) { phase = p; break; }
}
// ── Cost per hour ──
let costPerHour = 0;
if (durationMs > 60_000 && turns.length >= 2) {
costPerHour = (totalCost / durationMs) * 3_600_000;
}
// ── Session cost projection ──
const projectedCostToCompact = burnRate > 0 && turnsToCompact !== Infinity
? totalCost + turnsToCompact * avgCostPerTurn
: null;
// ── Cache ROI ──
const cacheWriteCost = (totalCacheCreate / 1e6) * pricing.cacheWrite;
const cacheReadSavings = (totalCacheRead / 1e6) * (pricing.input - pricing.cacheRead);
const cacheNetSavings = cacheReadSavings - cacheWriteCost;
// ── Multi-provider comparison ──
const comparisons = {};
for (const name of rc.compare) {
if (name === model) continue;
const p = findPricing(name, rc);
if (p === rc.defaultPricing && !rc.allPricing[name]) continue;
comparisons[name] =
(totalInput / 1e6) * p.input +
(totalOutput / 1e6) * p.output +
(totalCacheCreate / 1e6) * (p.cacheWrite || p.input) +
(totalCacheRead / 1e6) * (p.cacheRead || p.input);
}
// ── Thinking tokens ──
let totalThinking = 0;
for (const t of turns) totalThinking += t.thinking;
return {
model, usableContext, contextLimit, pricing,
turnCount: turns.length,
userTurnCount: session.userTurns,
totalInput, totalOutput, totalCacheCreate, totalCacheRead, totalBilledInput,
totalCost, avgCostPerTurn, costPerHour,
currentContext, contextPct,
burnRate, acceleration, turnsToCompact,
cacheHitRate,
compactions,
durationMs,
lastTurn: turns[turns.length - 1],
turnCosts, contextSizes,
baseline, overhead, overheadPct,
contextTaxPerCall, savedPerCall, savingsOverLookahead,
multiplier, baselineCostPerCall,
overContext, overdueMs,
phase,
projectedCostToCompact,
cacheWriteCost, cacheReadSavings, cacheNetSavings,
comparisons, totalThinking,
};
}
// ── Renderers ─────────────────────────────────────────────────────────
// ── Multiplier styling ───────────────────────────────────────────────
// Color reflects how much more the current call costs vs. a fresh one.
function multColor(mult) {
if (mult >= 4) return RED;
if (mult >= 3) return YELLOW;
return GREEN;
}
function sessionShortId(filePath) {
if (!filePath) return "";
const base = filePath.split(/[\\/]/).pop() || "";
return base.replace(/\.jsonl$/, "").slice(0, 8);
}
// Reasoning-zone band derived from contextPct — independent of cost multiplier.
// Maps the U-shaped attention degradation curve (Liu et al. 2023; RULER; NoLiMa)
// to context fill percentage. Bands are coarse but defensible for any 1M-window
// model. For 200k-window models the same bands apply since contextPct is relative.
function reasoningZone(contextPct) {
if (contextPct > 100) return { name: "OVER", color: BG_RED + WHITE + BOLD, bar: BG_RED + WHITE };
if (contextPct > 80) return { name: "TOLERANCE", color: RED + BOLD, bar: RED };
if (contextPct > 60) return { name: "DRIFT", color: YELLOW + BOLD, bar: YELLOW };
if (contextPct > 35) return { name: "SOFTENING", color: CYAN, bar: DIM_CYAN };
return { name: "SHARP", color: GREEN + BOLD, bar: GREEN };
}
// Render a fixed-width context bar with zone-tinted fill.
// Width is 30 cells so the bar plus trailing percent+pages+tag stays under ~70 chars total.
function renderContextBar(pct, zone, width = 30) {
const filled = Math.max(0, Math.min(width, Math.round((pct / 100) * width)));
const empty = width - filled;
return zone.bar + "█".repeat(filled) + RESET + DIM + "░".repeat(empty) + RESET;
}
function buildPhaseBanner(m, cmds) {
const clearCaps = cmds.clear.replace("/", "").toUpperCase();
const fillPct = m.contextPct.toFixed(0);
const overheadPct = m.overheadPct.toFixed(0);
const resetFrag = m.overContext
? `${RED}${BOLD}reset overdue${m.overdueMs > 60_000 ? ` ${fmtDuration(m.overdueMs)}` : ""}${RESET}`
: m.turnsToCompact === Infinity
? `${GREEN}no pressure${RESET}`
: m.turnsToCompact < 10
? `${BG_RED}${WHITE}${BOLD} reset in ~${m.turnsToCompact} turns ${RESET}`
: m.turnsToCompact < 50
? `${RED}reset in ~${m.turnsToCompact} turns${RESET}`
: m.turnsToCompact < 200
? `${YELLOW}reset in ~${m.turnsToCompact} turns${RESET}`
: `${DIM}reset in ~${m.turnsToCompact} turns${RESET}`;
// Dual-signal fragment: shows both context fill (budget) and overhead (drift).
const signalFrag = m.overContext
? `${RED}${BOLD}fill ${fillPct}% OVER${RESET} ${DIM}(overhead ${overheadPct}%)${RESET}`
: `${DIM}fill ${fillPct}% (overhead ${overheadPct}%)${RESET}`;
switch (m.phase.name) {
case "EXPLORE":
return `${GREEN}${BOLD}EXPLORE${RESET} ${DIM}—${RESET} context cheap, reasoning sharp · ${signalFrag} · ${resetFrag}`;
case "BUILD":
return `${CYAN}${BOLD}BUILD${RESET} ${DIM}—${RESET} productive zone, reasoning sharp · ${signalFrag} · ${resetFrag}`;
case "HANDOFF":
return `${YELLOW}${BOLD}HANDOFF${RESET} ${DIM}—${RESET} curate handoff now · ${signalFrag} · ${resetFrag}`;
case "RESET":
default: {
const head = m.overContext
? `${RED}${BOLD}⚠ HANDOFF AND ${clearCaps}${RESET}`
: `${RED}${BOLD}⚠ ${clearCaps}${RESET}`;
return `${head} ${DIM}—${RESET} ${signalFrag} · ${resetFrag}`;
}
}
}
function renderDashboard(metrics, session, rc, profile, hud = {}) {
if (!metrics) {
process.stdout.write(CLR_SCR);
process.stdout.write(`${DIM}Waiting for session data...${RESET}\n`);
return;
}
const m = metrics;
const cmds = profile.commands;
// Acceleration arrow
let accelArrow = "";
if (m.acceleration > 100) accelArrow = `${RED}↑${RESET}`;
else if (m.acceleration < -100) accelArrow = `${GREEN}↓${RESET}`;
else if (m.turnCount >= 10) accelArrow = `${DIM}=${RESET}`;
// Multiplier styling — color = cost-multiplier band, suffix [ZONE] tag = reasoning band
const mc = multColor(m.multiplier);
const multText = `×${m.multiplier.toFixed(1)}`;
const multStyled = m.multiplier >= 5
? `${BG_RED}${WHITE}${BOLD} ${multText} ${RESET}`
: `${mc}${BOLD}${multText}${RESET}`;
const zone = reasoningZone(m.contextPct);
const zoneTag = `${zone.color}[${zone.name}]${RESET}`;
// Header — prefer the cwd's basename as a friendly project name; fall back to
// Claude Code's encoded form (B:--path--like--this) only when watching a
// session outside the current cwd (e.g. --all-projects mode).
const shortId = sessionShortId(session?.filePath);
const projRaw = session?.project || "";
const cwdBase = path.basename(process.cwd() || "");
const cwdEncoded = cwdBase.replace(/[/\\:]/g, "-");
const proj = (cwdBase && projRaw.endsWith(cwdEncoded))
? cwdBase
: (projRaw.length > 40 ? "…" + projRaw.slice(-39) : projRaw);
const header = `${BOLD}${CYAN} Agent Token Meter ${RESET}${DIM}v${VERSION}${RESET} ${DIM}·${RESET} ${DIM}${profile.name}${RESET}`;
const subHeader = (proj || shortId)
? ` ${DIM}${[proj, shortId].filter(Boolean).join(" · ")}${RESET}`
: null;
const noticeLine = hud.notice ? ` ${CYAN}${hud.notice}${RESET}` : null;
const W = 60;
const sepHeavy = `${DIM}${"═".repeat(W)}${RESET}`;
const sepLight = `${DIM}${"─".repeat(W)}${RESET}`;
// NOW section
const compactionAnnotation = (m.compactions && m.compactions.length > 0)
? ` ${DIM}(post-compaction × ${m.compactions.length})${RESET}`
: "";
const contextBar = renderContextBar(m.contextPct, zone);
const contextLine = ` ${DIM}context${RESET} ${contextBar} ${BOLD}${m.contextPct.toFixed(0)}%${RESET} ${zoneTag}`;
const burnLine = ` ${DIM}burn${RESET} ${MAGENTA}${m.burnRate >= 0 ? "+" : ""}${Math.round(m.burnRate)}${RESET} ${DIM}tok/call${RESET}${accelArrow ? ` ${accelArrow}` : ""}`;
const lastTurnLine = ` ${DIM}last turn${RESET} ${DIM}${fmtTokens(m.lastTurn.contextSize)} in · ${fmtTokens(m.lastTurn.output)} out · ${m.lastTurn.stopReason}${RESET}`;
// IF YOU CLEAR section — triggers on cost savings OR reasoning-zone DRIFT/TOLERANCE/OVER
const clearCaps = cmds.clear.replace("/", "").toUpperCase();
const attentionTrigger = ["DRIFT", "TOLERANCE", "OVER"].includes(zone.name);
const costTrigger = m.savedPerCall > 0.005;
const showClearSection = costTrigger || attentionTrigger;
let clearSection = null;
if (showClearSection) {
const lines = [
sepLight,
` ${DIM}IF YOU ${clearCaps}${RESET}`,
];
if (costTrigger) {
lines.push(` ${DIM}per call${RESET} ${GREEN}save ${fmtCost(m.savedPerCall)}${RESET}`);
}
if (attentionTrigger) {
lines.push(` ${DIM}reasoning${RESET} ${zone.color}${zone.name}${RESET} ${DIM}→${RESET} ${GREEN}${BOLD}SHARP${RESET}`);
}
if (costTrigger) {
lines.push(` ${DIM}next ${CLEAR_LOOKAHEAD}${RESET} ${GREEN}save ~${fmtCost(m.savingsOverLookahead)}${RESET}`);
}
lines.push(` ${DIM}steps${RESET} ${DIM}curate handoff → ${cmds.clear} → reload (lands at position 0)${RESET}`);
clearSection = lines;
}
// HANDOFF SECTIONS — surfaces the schema during HANDOFF/RESET phases as a
// proper section (not a row), so it visually reads as a teaching aid, not
// data. Full schema lives in AGENT-PROTOCOL.md.
let handoffSection = null;
if (m.phase.name === "HANDOFF" || m.phase.name === "RESET") {
handoffSection = [
sepLight,
` ${DIM}HANDOFF SECTIONS${RESET}`,
` ${DIM}mission · constraints · decisions · open · next · files · avoid${RESET}`,
];
}
// SESSION section
const sessionParts = [`${BOLD}${GREEN}${fmtCost(m.totalCost)}${RESET}`, `${m.userTurnCount} turns`];
if (m.durationMs > 0) sessionParts.push(fmtDuration(m.durationMs));
if (m.costPerHour > 0) sessionParts.push(`${fmtCost(m.costPerHour)}/hr`);
const spendLine = ` ${DIM}spend${RESET} ${sessionParts.map((p, i) => i === 0 ? p : DIM + p + RESET).join(` ${DIM}·${RESET} `)}`;
const cacheParts = [`${m.cacheHitRate.toFixed(0)}% hit`];
if (m.cacheNetSavings > 0.01) cacheParts.push(`saved ${GREEN}${fmtCost(m.cacheNetSavings)}${RESET}`);
cacheParts.push(`${fmtTokens(m.totalBilledInput)} in`);
cacheParts.push(`${fmtTokens(m.totalOutput)} out`);
const cacheLine = ` ${DIM}cache${RESET} ${DIM}${cacheParts.join(" · ")}${RESET}`;
// Output-ratio line — surfaces "output competes for budget" insight from Gary's article
const outputRatio = m.totalBilledInput > 0 ? (m.totalOutput / m.totalBilledInput) : 0;
const outputVerbose = outputRatio > OUTPUT_RATIO_WARN;
const outputWarn = outputVerbose ? ` ${YELLOW}⚠ verbose${RESET}` : "";
const outputLine = ` ${DIM}output${RESET} ${DIM}${fmtTokens(m.totalOutput)} total · ${(outputRatio * 100).toFixed(1)}% of inputs${RESET}${outputWarn}`;
const altLine = Object.keys(m.comparisons).length > 0
? ` ${DIM}alt models${RESET} ${DIM}${Object.entries(m.comparisons).slice(0, 3).map(([k, v]) => `${providerLabel(k, rc.labels)} ${fmtCost(v)}`).join(" ")}${RESET}`
: null;
const lines = [
"",
header,
subHeader,
sepHeavy,
// MULTIPLIER line: pure cost signal (×N + dollar deltas). The reasoning-zone
// tag lives only on the context-bar line two rows below — one axis per line
// keeps the scan clean.
` ${DIM}MULTIPLIER${RESET} ${multStyled}${accelArrow ? " " + accelArrow : ""} ${BOLD}${fmtCost(m.avgCostPerTurn)}${RESET} ${DIM}now${RESET} ${DIM}${fmtCost(m.baselineCostPerCall)} fresh${RESET}`,
` ${buildPhaseBanner(m, cmds)}`,
sepHeavy,
` ${DIM}NOW${RESET}${compactionAnnotation}`,
contextLine,
burnLine,
lastTurnLine,
...(clearSection || []),
...(handoffSection || []),
sepLight,
` ${DIM}SESSION${RESET}`,
spendLine,
cacheLine,
outputLine,
altLine,
sepHeavy,
` ${DIM}Watching · Ctrl+C to exit${RESET}`,
noticeLine,
].filter(Boolean);
process.stdout.write(CLR_SCR);
process.stdout.write(lines.join("\n") + "\n");
}
function renderAllSessions(projectFilter, limit, rc, profile, exact = false) {
const sessions = findSessions(projectFilter, profile, { exact });
if (sessions.length === 0) {
console.log(`\n${DIM}No sessions found.${RESET}\n`);
return;
}
console.log(`\n${BOLD}${profile.name} Sessions${RESET}${projectFilter ? ` ${DIM}(filter: "${projectFilter}")${RESET}` : ""}\n`);
console.log(
` ${DIM}${"Date".padEnd(12)}${"Context".padStart(9)}${"Turns".padStart(7)}${"Cost".padStart(9)} ` +
`${"Cache%".padStart(7)} Project${RESET}`
);
console.log(` ${DIM}${"─".repeat(70)}${RESET}`);
let totalCost = 0;
let shown = 0;
for (const s of sessions) {
if (shown >= limit) break;
const parsed = parseSession(s.path);
const m = computeMetrics(parsed, rc);
if (!m) continue;
shown++;
totalCost += m.totalCost;
const date = new Date(s.mtime).toLocaleDateString();
const compact = m.compactions.length > 0 ? ` ${DIM}(${m.compactions.length}x compacted)${RESET}` : "";
console.log(
` ${DIM}${date.padEnd(12)}${RESET}` +
`${fmtTokens(m.currentContext).padStart(9)} ` +
`${String(m.userTurnCount || m.turnCount).padStart(5)} ` +
`${fmtCost(m.totalCost).padStart(9)} ` +
`${m.cacheHitRate.toFixed(0).padStart(5)}% ` +
`${parsed.project}${compact}`
);
}
console.log(` ${DIM}${"─".repeat(70)}${RESET}`);
console.log(` ${BOLD}Total: ${fmtCost(totalCost)}${RESET} across ${shown} sessions\n`);
}
function renderHelp(profile) {
const cmd = "npx agent-token-meter";
const cmds = profile ? profile.commands : { clear: "/clear", compact: "/compact" };
const configDir = profile ? profile.configDir() : "~/.claude";
console.log(`
${BOLD}${CYAN}Agent Token Meter${RESET} v${VERSION}
Zero-dependency burn-rate monitor for AI coding agents.
${BOLD}Usage:${RESET}
${cmd} Auto-detect agent and watch active session
${cmd} --all List all sessions with cost summary
${cmd} --project X Filter sessions by project name
${cmd} <file> Watch a specific .jsonl session file
${BOLD}Options:${RESET}
--agent <id> Select agent (default: auto-detect)
--agents List supported agents and detection status
--all Show all sessions summary
--sessions List sessions active in the last 10 min
--session <id|path> Watch a specific session (disables auto-follow)
--no-follow Pin to initial session; don't auto-switch
--project <name> Filter by project name (substring match)
--all-projects Watch any session machine-wide (default: cwd scope)
--limit <n> Max sessions to show in --all (default: 20)
--install-hooks Install threshold hooks (agent-specific)
--uninstall-hooks Remove threshold hooks
--emit-agent-protocol Print AGENT-PROTOCOL.md to stdout (for piping)
--install-protocol [...] Install AGENT-PROTOCOL.md in cwd + CLAUDE.md import
(use --no-claude-md to skip CLAUDE.md edit)
--uninstall-protocol Remove AGENT-PROTOCOL.md + CLAUDE.md section
--help, -h Show this help
--version, -v Show version
${BOLD}Multi-instance:${RESET}
By default the meter scopes to the project matching your current
working directory — so launching it in terminal A only ever watches
sessions for that project, never a newer one from terminal B in a
different repo. Auto-follow switches between sessions inside the
same project after 30s of local idle. Escape hatches:
--all-projects watch any session machine-wide
--no-follow pin to the initial session
--session <id> lock to one specific session
The meter self-exits if its launching shell dies, so orphaned
processes don't accumulate if you close the terminal without Ctrl+C.
${BOLD}Hooks (threshold nudges):${RESET}
Threshold hooks inject a one-line nudge into the agent's context
when your session crosses a reasoning-degradation boundary:
50% — curation still cheap, draft the handoff
75% — drift zone, finish the handoff before /clear
90% — attention degraded + cost biting, /clear from handoff
Each fires once. Compaction re-arms them. Zero tokens wasted
when below thresholds. Currently supported: Claude Code.
For the full agent contract (handoff schema, exact request-to-clear
phrasing, bootstrap protocol), install the bundled AGENT-PROTOCOL.md:
npx agent-token-meter --install-protocol
Install: ${cmd} --install-hooks
Uninstall: ${cmd} --uninstall-hooks
${BOLD}What it shows:${RESET}
Reasoning-zone band [SHARP / SOFTENING / DRIFT / TOLERANCE] alongside cost
Context bar with zone-tinted fill + percent + page-equivalent
Burn rate (tokens/call) with acceleration detection
Compaction ETA, history, and post-compaction annotation
Cost tracking with cache efficiency breakdown
Output-vs-input ratio with verbose-agent warning
Multi-provider comparison (same workload on Sonnet, Kimi, etc.)
Cost per hour and session cost projection
Cache ROI (net savings from prompt caching)
Workflow advisor: phase, context tax, ${cmds.clear} savings projection
WHAT TO HANDOFF widget during HANDOFF / RESET phases
${BOLD}Config:${RESET}
Optional: ${configDir}/token-meter.json
Add custom providers or change the comparison list:
{ "compare": ["claude-sonnet-4-6", "kimi-k2.5"],
"providers": { "my-llm": { "input": 1, "output": 5 } } }
${BOLD}Setup:${RESET}
Run in a split terminal pane alongside your coding agent.
It reads session JSONL logs (read-only).
`);
}
// ── Hook installer ───────────────────────────────────────────────────
// Write settings atomically via tmp-file + rename. Claude Code may be
// writing to settings.json concurrently; a naive read→mutate→write
// clobbers unrelated hook entries on race. Same-directory rename replaces
// in one step on POSIX and NTFS. The tmp name carries the pid so two
// concurrent writers don't collide on it; on rename failure (e.g. the
// target is briefly open on Windows) we clean up the tmp file rather than
// leave it stranded in ~/.claude/.
function writeSettingsAtomic(settingsPath, settings) {
const tmp = `${settingsPath}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2));
try {
fs.renameSync(tmp, settingsPath);
} catch (e) {
try { fs.unlinkSync(tmp); } catch {}
throw e;
}
}
// Identify our hook entries by the hook filename we installed, not by
// a "token-meter" substring — the substring match could silently
// delete an unrelated user hook whose command happens to contain that
// string. `hookFileName` is specific enough that only our entries hit.
function isTokenMeterHook(entry, hookFileName) {
return Array.isArray(entry?.hooks) && entry.hooks.some(h =>
h?.type === "command" &&
typeof h?.command === "string" &&
h.command.includes(hookFileName)
);
}
function installHooks(profile) {
if (!profile.hook?.supported) {
console.error(`\n${RED}Hooks are not supported for ${profile.name}.${RESET}`);
console.error(`${DIM}Currently only Claude Code supports threshold hooks.${RESET}\n`);
process.exit(1);
}
const hk = profile.hook;
const hooksDir = hk.hookDir();
const hookDest = path.join(hooksDir, hk.hookFileName);
const hookSrc = path.join(__dirname, "hook.mjs");
const settingsPath = hk.settingsPath();
if (!fs.existsSync(hookSrc)) {
console.error(`${RED}hook.mjs not found at ${hookSrc}${RESET}`);
console.error(`${DIM}Try reinstalling: npm install -g agent-token-meter${RESET}`);
process.exit(1);
}
// 1. Copy hook script to stable location
fs.mkdirSync(hooksDir, { recursive: true });
fs.copyFileSync(hookSrc, hookDest);
// 2. Merge into settings
let settings = {};
try { settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); } catch {}
if (!settings.hooks) settings.hooks = {};
// v1.4: register for multiple events so we can act on SessionStart and PostCompact
// explicitly, not just PostToolUse heuristics.
const eventsToRegister = ["PostToolUse", "SessionStart", "PostCompact"];
const hookCmd = `node "${hookDest.replace(/\\/g, "/")}"`;
for (const event of eventsToRegister) {
if (!settings.hooks[event]) settings.hooks[event] = [];
settings.hooks[event] = settings.hooks[event].filter(
h => !isTokenMeterHook(h, hk.hookFileName)
);
settings.hooks[event].push({
matcher: "",
hooks: [{ type: "command", command: hookCmd }],
});
}
writeSettingsAtomic(settingsPath, settings);
console.log(`\n${GREEN}✓${RESET} Token Meter hooks installed for ${BOLD}${profile.name}${RESET}\n`);
console.log(` ${DIM}Hook:${RESET} ${hookDest}`);
console.log(` ${DIM}Config:${RESET} ${settingsPath}`);
console.log(`\n ${profile.name} receives a one-line nudge when context crosses:`);
console.log(` ${YELLOW}50%${RESET} — reasoning still sharp, draft the handoff`);
console.log(` ${YELLOW}75%${RESET} — drift zone, finish the handoff before ${profile.commands.clear}`);
console.log(` ${RED}90%${RESET} — attention degraded + cost biting, ${profile.commands.clear} from handoff`);
console.log(`\n Each fires ${BOLD}once${RESET} per session. Compaction re-arms them.`);
console.log(` To remove: ${CYAN}npx agent-token-meter --uninstall-hooks${RESET}\n`);
}
function uninstallHooks(profile) {
if (!profile.hook?.supported) {
console.error(`\n${RED}Hooks are not supported for ${profile.name}.${RESET}\n`);
process.exit(1);
}
const hk = profile.hook;
const hookDest = path.join(hk.hookDir(), hk.hookFileName);
const statePath = path.join(profile.configDir(), hk.stateFile);
const settingsPath = hk.settingsPath();
// Remove hook file and state
try { fs.unlinkSync(hookDest); } catch {}
try { fs.unlinkSync(statePath); } catch {}
// Remove from settings
try {
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
if (settings.hooks) {
// v1.4: remove our entries from every event we may have registered for