@tokenboard/cli 0.1.2 → 0.1.4
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/dist/cli.js +416 -215
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -598,8 +598,15 @@ function resolveProjectsRoot(homedir3) {
|
|
|
598
598
|
|
|
599
599
|
// src/collectors/claude-code-source.ts
|
|
600
600
|
init_esm_shims();
|
|
601
|
-
import { readdirSync, readFileSync } from "fs";
|
|
601
|
+
import { readdirSync, readFileSync as readFileSync2 } from "fs";
|
|
602
|
+
import { join as join3 } from "path";
|
|
603
|
+
|
|
604
|
+
// src/collectors/claude-code-cache.ts
|
|
605
|
+
init_esm_shims();
|
|
606
|
+
import { readFileSync, statSync } from "fs";
|
|
607
|
+
import { mkdirSync, writeFileSync, renameSync } from "fs";
|
|
602
608
|
import { join as join2 } from "path";
|
|
609
|
+
import { randomBytes } from "crypto";
|
|
603
610
|
|
|
604
611
|
// src/collectors/claude-code-filter.ts
|
|
605
612
|
init_esm_shims();
|
|
@@ -609,6 +616,88 @@ function isCountableAssistantLine(line) {
|
|
|
609
616
|
return l?.["type"] === "assistant" && message?.["usage"] != null && message?.["model"] !== "<synthetic>" && l?.["isApiErrorMessage"] !== true;
|
|
610
617
|
}
|
|
611
618
|
|
|
619
|
+
// src/collectors/claude-code-cache.ts
|
|
620
|
+
var CACHE_VERSION = 1;
|
|
621
|
+
function parseFileLines(file, text) {
|
|
622
|
+
const out2 = [];
|
|
623
|
+
const lines = text.split("\n");
|
|
624
|
+
for (let i = 0; i < lines.length; i++) {
|
|
625
|
+
const raw = lines[i];
|
|
626
|
+
if (!raw) continue;
|
|
627
|
+
let parsed;
|
|
628
|
+
try {
|
|
629
|
+
parsed = JSON.parse(raw);
|
|
630
|
+
} catch {
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
if (!isCountableAssistantLine(parsed)) continue;
|
|
634
|
+
const line = parsed;
|
|
635
|
+
out2.push({
|
|
636
|
+
messageId: line.message.id ?? null,
|
|
637
|
+
model: line.message.model ?? "",
|
|
638
|
+
usage: line.message.usage,
|
|
639
|
+
timestamp: line.timestamp ?? null,
|
|
640
|
+
sourcePath: file,
|
|
641
|
+
lineIndex: i
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
return out2;
|
|
645
|
+
}
|
|
646
|
+
function cachePath(configDir) {
|
|
647
|
+
return join2(configDir, "parse-cache.json");
|
|
648
|
+
}
|
|
649
|
+
function loadCache(configDir) {
|
|
650
|
+
try {
|
|
651
|
+
const c = JSON.parse(readFileSync(cachePath(configDir), "utf8"));
|
|
652
|
+
if (c.version !== CACHE_VERSION || typeof c.files !== "object" || c.files === null) {
|
|
653
|
+
return { version: CACHE_VERSION, files: {} };
|
|
654
|
+
}
|
|
655
|
+
return c;
|
|
656
|
+
} catch {
|
|
657
|
+
return { version: CACHE_VERSION, files: {} };
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
function saveCache(configDir, cache) {
|
|
661
|
+
try {
|
|
662
|
+
mkdirSync(configDir, { recursive: true });
|
|
663
|
+
const tmp = join2(configDir, `.parse-cache.json.${randomBytes(6).toString("hex")}.tmp`);
|
|
664
|
+
writeFileSync(tmp, JSON.stringify(cache), "utf8");
|
|
665
|
+
renameSync(tmp, cachePath(configDir));
|
|
666
|
+
} catch {
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
function linesForFile(file, prev, next) {
|
|
670
|
+
let st;
|
|
671
|
+
try {
|
|
672
|
+
const s = statSync(file);
|
|
673
|
+
st = { mtimeMs: s.mtimeMs, size: s.size };
|
|
674
|
+
} catch {
|
|
675
|
+
return [];
|
|
676
|
+
}
|
|
677
|
+
const hit = prev.files[file];
|
|
678
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
|
|
679
|
+
next.files[file] = hit;
|
|
680
|
+
return hit.lines;
|
|
681
|
+
}
|
|
682
|
+
let text;
|
|
683
|
+
try {
|
|
684
|
+
text = readFileSync(file, "utf8");
|
|
685
|
+
} catch {
|
|
686
|
+
return [];
|
|
687
|
+
}
|
|
688
|
+
const lines = parseFileLines(file, text);
|
|
689
|
+
next.files[file] = { mtimeMs: st.mtimeMs, size: st.size, lines };
|
|
690
|
+
return lines;
|
|
691
|
+
}
|
|
692
|
+
function collectClaudeCodeLinesCached(files, configDir) {
|
|
693
|
+
const prev = loadCache(configDir);
|
|
694
|
+
const next = { version: CACHE_VERSION, files: {} };
|
|
695
|
+
const out2 = [];
|
|
696
|
+
for (const file of files) out2.push(...linesForFile(file, prev, next));
|
|
697
|
+
saveCache(configDir, next);
|
|
698
|
+
return out2;
|
|
699
|
+
}
|
|
700
|
+
|
|
612
701
|
// src/collectors/claude-code-source.ts
|
|
613
702
|
function findJsonlFiles(dir) {
|
|
614
703
|
let entries;
|
|
@@ -619,65 +708,30 @@ function findJsonlFiles(dir) {
|
|
|
619
708
|
}
|
|
620
709
|
const out2 = [];
|
|
621
710
|
for (const entry of entries) {
|
|
622
|
-
const full =
|
|
711
|
+
const full = join3(dir, entry.name);
|
|
623
712
|
if (entry.isDirectory()) out2.push(...findJsonlFiles(full));
|
|
624
713
|
else if (entry.isFile() && entry.name.endsWith(".jsonl")) out2.push(full);
|
|
625
714
|
}
|
|
626
715
|
return out2;
|
|
627
716
|
}
|
|
628
|
-
function collectClaudeCodeLines(projectsRoot) {
|
|
629
|
-
const files = findJsonlFiles(projectsRoot);
|
|
630
|
-
const out2 = [];
|
|
631
|
-
for (const file of files) {
|
|
632
|
-
let text;
|
|
633
|
-
try {
|
|
634
|
-
text = readFileSync(file, "utf8");
|
|
635
|
-
} catch {
|
|
636
|
-
continue;
|
|
637
|
-
}
|
|
638
|
-
const lines = text.split("\n");
|
|
639
|
-
for (let i = 0; i < lines.length; i++) {
|
|
640
|
-
const raw = lines[i];
|
|
641
|
-
if (!raw) continue;
|
|
642
|
-
let parsed;
|
|
643
|
-
try {
|
|
644
|
-
parsed = JSON.parse(raw);
|
|
645
|
-
} catch {
|
|
646
|
-
continue;
|
|
647
|
-
}
|
|
648
|
-
if (!isCountableAssistantLine(parsed)) continue;
|
|
649
|
-
const line = parsed;
|
|
650
|
-
out2.push({
|
|
651
|
-
messageId: line.message.id ?? null,
|
|
652
|
-
model: line.message.model ?? "",
|
|
653
|
-
usage: line.message.usage,
|
|
654
|
-
timestamp: line.timestamp ?? null,
|
|
655
|
-
sourcePath: file,
|
|
656
|
-
lineIndex: i
|
|
657
|
-
});
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
return out2;
|
|
661
|
-
}
|
|
662
717
|
|
|
663
718
|
// src/collectors/dedup.ts
|
|
664
719
|
init_esm_shims();
|
|
720
|
+
function outputOf(line) {
|
|
721
|
+
return line.usage.output_tokens ?? 0;
|
|
722
|
+
}
|
|
665
723
|
function dedupeByMessageId(lines) {
|
|
666
|
-
const
|
|
667
|
-
|
|
668
|
-
)
|
|
669
|
-
const seen = /* @__PURE__ */ new Set();
|
|
670
|
-
const kept = [];
|
|
671
|
-
for (const line of ordered) {
|
|
724
|
+
const best = /* @__PURE__ */ new Map();
|
|
725
|
+
const idless = [];
|
|
726
|
+
for (const line of lines) {
|
|
672
727
|
if (line.messageId == null || line.messageId === "") {
|
|
673
|
-
|
|
728
|
+
idless.push(line);
|
|
674
729
|
continue;
|
|
675
730
|
}
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
kept.push(line);
|
|
731
|
+
const cur = best.get(line.messageId);
|
|
732
|
+
if (cur === void 0 || outputOf(line) > outputOf(cur)) best.set(line.messageId, line);
|
|
679
733
|
}
|
|
680
|
-
return
|
|
734
|
+
return [...best.values(), ...idless];
|
|
681
735
|
}
|
|
682
736
|
|
|
683
737
|
// src/collectors/claude-code-map.ts
|
|
@@ -990,7 +1044,10 @@ function summarize(records, prices) {
|
|
|
990
1044
|
unpricedTokens += tokens;
|
|
991
1045
|
unpricedModels.add(r.model);
|
|
992
1046
|
}
|
|
993
|
-
|
|
1047
|
+
const d = perDay.get(r.date) ?? { tokens: 0, costUsd: 0 };
|
|
1048
|
+
d.tokens += tokens;
|
|
1049
|
+
d.costUsd += costUsd;
|
|
1050
|
+
perDay.set(r.date, d);
|
|
994
1051
|
const t = perTool.get(r.tool) ?? { tokens: 0, costUsd: 0 };
|
|
995
1052
|
t.tokens += tokens;
|
|
996
1053
|
t.costUsd += costUsd;
|
|
@@ -1007,7 +1064,7 @@ function summarize(records, prices) {
|
|
|
1007
1064
|
anyUnpriced: unpricedModels.size > 0,
|
|
1008
1065
|
unpricedTokens,
|
|
1009
1066
|
unpricedModels: [...unpricedModels].sort(),
|
|
1010
|
-
perDay: [...perDay.entries()].map(([date,
|
|
1067
|
+
perDay: [...perDay.entries()].map(([date, v]) => ({ date, ...v })).sort((a, b) => a.date < b.date ? -1 : 1),
|
|
1011
1068
|
perTool: [...perTool.entries()].map(([tool, v]) => ({ tool, ...v })).sort((a, b) => b.tokens - a.tokens),
|
|
1012
1069
|
perModel: [...perModel.entries()].map(([model, v]) => ({ model, ...v })).sort((a, b) => b.tokens - a.tokens)
|
|
1013
1070
|
};
|
|
@@ -1016,22 +1073,101 @@ function summarize(records, prices) {
|
|
|
1016
1073
|
// src/render/terminal-style.ts
|
|
1017
1074
|
init_esm_shims();
|
|
1018
1075
|
var import_picocolors = __toESM(require_picocolors(), 1);
|
|
1076
|
+
function detectColorLevel(i) {
|
|
1077
|
+
const force = i.forceColor;
|
|
1078
|
+
if (force !== void 0 && force !== "") {
|
|
1079
|
+
const n = Number(force);
|
|
1080
|
+
if (n === 0) return 0;
|
|
1081
|
+
if (n === 1 || n === 2 || n === 3) return n;
|
|
1082
|
+
return 3;
|
|
1083
|
+
}
|
|
1084
|
+
const ct = (i.colorterm ?? "").toLowerCase();
|
|
1085
|
+
if (ct === "truecolor" || ct === "24bit") return 3;
|
|
1086
|
+
const term = (i.term ?? "").toLowerCase();
|
|
1087
|
+
if (term === "xterm-kitty" || term === "ghostty" || term === "wezterm") return 3;
|
|
1088
|
+
if (/-256(color)?$/.test(term)) return 2;
|
|
1089
|
+
return 1;
|
|
1090
|
+
}
|
|
1019
1091
|
function resolveStyle(inputs) {
|
|
1092
|
+
const color = inputs.isTTY && !inputs.noColorEnv && !inputs.noColorFlag;
|
|
1020
1093
|
return {
|
|
1021
|
-
color
|
|
1094
|
+
color,
|
|
1095
|
+
level: color ? detectColorLevel(inputs) : 0,
|
|
1096
|
+
// master gate: NO_COLOR/non-TTY => 0
|
|
1022
1097
|
width: Math.min(inputs.columns ?? 80, 80),
|
|
1023
1098
|
ascii: inputs.asciiFlag
|
|
1024
1099
|
};
|
|
1025
1100
|
}
|
|
1101
|
+
var CORAL_TC = "\x1B[38;2;204;120;92m";
|
|
1102
|
+
var CORAL_HI_TC = "\x1B[38;2;214;141;114m";
|
|
1103
|
+
var RESET_FG = "\x1B[39m";
|
|
1104
|
+
var CORAL_256 = "\x1B[38;5;173m";
|
|
1105
|
+
var CORAL_HI_256 = "\x1B[38;5;180m";
|
|
1026
1106
|
function styler(style) {
|
|
1027
1107
|
const on = style.color;
|
|
1108
|
+
const lvl = style.level;
|
|
1109
|
+
const coral = (s) => {
|
|
1110
|
+
if (lvl >= 3) return CORAL_TC + s + RESET_FG;
|
|
1111
|
+
if (lvl === 2) return CORAL_256 + s + RESET_FG;
|
|
1112
|
+
if (lvl === 1) return import_picocolors.default.yellow(s);
|
|
1113
|
+
return s;
|
|
1114
|
+
};
|
|
1115
|
+
const coralHi = (s) => {
|
|
1116
|
+
if (lvl >= 3) return CORAL_HI_TC + s + RESET_FG;
|
|
1117
|
+
if (lvl === 2) return CORAL_HI_256 + s + RESET_FG;
|
|
1118
|
+
if (lvl === 1) return import_picocolors.default.yellow(s);
|
|
1119
|
+
return s;
|
|
1120
|
+
};
|
|
1028
1121
|
return {
|
|
1029
1122
|
dim: (s) => on ? import_picocolors.default.dim(s) : s,
|
|
1030
1123
|
bold: (s) => on ? import_picocolors.default.bold(s) : s,
|
|
1031
1124
|
green: (s) => on ? import_picocolors.default.green(s) : s,
|
|
1032
1125
|
red: (s) => on ? import_picocolors.default.red(s) : s,
|
|
1033
1126
|
cyan: (s) => on ? import_picocolors.default.cyan(s) : s,
|
|
1034
|
-
inverse: (s) => on ? import_picocolors.default.inverse(s) : s
|
|
1127
|
+
inverse: (s) => on ? import_picocolors.default.inverse(s) : s,
|
|
1128
|
+
coral,
|
|
1129
|
+
coralHi,
|
|
1130
|
+
// Accent a busy day WITHOUT ever dimming real data: a normal/low day stays DEFAULT full-weight
|
|
1131
|
+
// text (readable), a busy day (t >= 0.34 of the per-series max) gets coral, the peak (t > 0.67)
|
|
1132
|
+
// gets bold hi-coral. Identity at level 0. "Tasteful: accent peaks only."
|
|
1133
|
+
accentByLevel: (s, t) => {
|
|
1134
|
+
if (lvl === 0) return s;
|
|
1135
|
+
if (t > 0.67) return import_picocolors.default.bold(coralHi(s));
|
|
1136
|
+
if (t >= 0.34) return coral(s);
|
|
1137
|
+
return s;
|
|
1138
|
+
}
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// src/render/spinner.ts
|
|
1143
|
+
init_esm_shims();
|
|
1144
|
+
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1145
|
+
var FRAMES_ASCII = ["|", "/", "-", "\\"];
|
|
1146
|
+
var INTERVAL_MS = 80;
|
|
1147
|
+
function startSpinner(label, ascii = false) {
|
|
1148
|
+
if (!process.stderr.isTTY) return { stop: () => {
|
|
1149
|
+
} };
|
|
1150
|
+
const frames = ascii ? FRAMES_ASCII : FRAMES;
|
|
1151
|
+
let i = 0;
|
|
1152
|
+
const write = (s) => process.stderr.write(s);
|
|
1153
|
+
write("\x1B[?25l");
|
|
1154
|
+
const render = () => {
|
|
1155
|
+
const frame = frames[i % frames.length];
|
|
1156
|
+
i += 1;
|
|
1157
|
+
write(`\r${frame} ${label}`);
|
|
1158
|
+
};
|
|
1159
|
+
render();
|
|
1160
|
+
const timer = setInterval(render, INTERVAL_MS);
|
|
1161
|
+
timer.unref?.();
|
|
1162
|
+
let stopped = false;
|
|
1163
|
+
return {
|
|
1164
|
+
stop: () => {
|
|
1165
|
+
if (stopped) return;
|
|
1166
|
+
stopped = true;
|
|
1167
|
+
clearInterval(timer);
|
|
1168
|
+
write("\r\x1B[2K");
|
|
1169
|
+
write("\x1B[?25h");
|
|
1170
|
+
}
|
|
1035
1171
|
};
|
|
1036
1172
|
}
|
|
1037
1173
|
|
|
@@ -1653,17 +1789,22 @@ function formatApproxUsd(n) {
|
|
|
1653
1789
|
init_esm_shims();
|
|
1654
1790
|
var GLYPHS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
|
|
1655
1791
|
var ASCII_GLYPHS = ["_", ".", ".", "-", "-", "=", "=", "#"];
|
|
1656
|
-
function sparkline(values, ascii = false) {
|
|
1792
|
+
function sparkline(values, ascii = false, colorize) {
|
|
1657
1793
|
const glyphs2 = ascii ? ASCII_GLYPHS : GLYPHS;
|
|
1658
1794
|
if (values.length === 0) return "";
|
|
1659
1795
|
const min = Math.min(...values);
|
|
1660
1796
|
const max = Math.max(...values);
|
|
1661
1797
|
const range = max - min;
|
|
1662
|
-
|
|
1663
|
-
return values.map((v) =>
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1798
|
+
const pick = (v) => range === 0 ? glyphs2[0] : glyphs2[Math.round((v - min) / range * (glyphs2.length - 1))];
|
|
1799
|
+
return values.map((v, i) => colorize ? colorize(pick(v), i) : pick(v)).join("");
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
// src/render/model-display.ts
|
|
1803
|
+
init_esm_shims();
|
|
1804
|
+
function displayModel(model) {
|
|
1805
|
+
const m = model.match(/^claude-(opus|sonnet|haiku)-(\d+)-(\d+)(?:-\d+)?$/i);
|
|
1806
|
+
if (m) return `${m[1].toLowerCase()}-${m[2]}.${m[3]}`;
|
|
1807
|
+
return model.startsWith("claude-") ? model.slice("claude-".length) : model;
|
|
1667
1808
|
}
|
|
1668
1809
|
|
|
1669
1810
|
// src/render/local-preview.ts
|
|
@@ -1672,34 +1813,62 @@ function renderLocalPreview(summary, style) {
|
|
|
1672
1813
|
const g = glyphs(style.ascii);
|
|
1673
1814
|
const lines = [];
|
|
1674
1815
|
lines.push(
|
|
1675
|
-
c.
|
|
1816
|
+
c.dim("you've burned ") + c.bold(c.coral(humanizeTokens(summary.totalTokens))) + c.dim(" tokens all-time \xB7 ") + c.coral(formatApproxUsd(summary.totalCostUsd)) + c.dim(" est")
|
|
1676
1817
|
);
|
|
1677
1818
|
lines.push("");
|
|
1678
|
-
lines.push(c.
|
|
1679
|
-
const
|
|
1680
|
-
const
|
|
1681
|
-
const
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
humanizeTokens(t.tokens),
|
|
1686
|
-
formatApproxUsd(t.costUsd),
|
|
1687
|
-
spark
|
|
1688
|
-
// same per-day series across the board in Phase 2 (per-tool series is Phase 6+)
|
|
1819
|
+
lines.push(c.coral("\u{1FA99} tokenboard") + c.dim(" \xB7 your usage by day"));
|
|
1820
|
+
const headers = ["date", "tokens", "~$ est"];
|
|
1821
|
+
const aligns = ["left", "right", "right"];
|
|
1822
|
+
const bodyRows = summary.perDay.map((d) => [
|
|
1823
|
+
d.date,
|
|
1824
|
+
humanizeTokens(d.tokens),
|
|
1825
|
+
formatApproxUsd(d.costUsd)
|
|
1689
1826
|
]);
|
|
1690
|
-
const
|
|
1827
|
+
const totalRow = ["TOTAL", humanizeTokens(summary.totalTokens), formatApproxUsd(summary.totalCostUsd)];
|
|
1828
|
+
const allRows = [headers, ...bodyRows, totalRow];
|
|
1691
1829
|
const colWidths = headers.map(
|
|
1692
1830
|
(_, col) => Math.max(...allRows.map((r) => [...r[col]].length), 1)
|
|
1693
1831
|
);
|
|
1694
1832
|
const cellAlign = (i) => aligns[i] ?? "left";
|
|
1695
1833
|
const width = (i) => colWidths[i] ?? 1;
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1834
|
+
const renderRow = (cells, colorize) => row(
|
|
1835
|
+
cells.map((cell, i) => {
|
|
1836
|
+
const padded = padCell(cell, width(i), cellAlign(i));
|
|
1837
|
+
return colorize ? colorize(padded, i) : padded;
|
|
1838
|
+
}),
|
|
1839
|
+
g
|
|
1840
|
+
);
|
|
1841
|
+
const dayTokens = summary.perDay.map((d) => d.tokens);
|
|
1842
|
+
const min = dayTokens.length ? Math.min(...dayTokens) : 0;
|
|
1843
|
+
const max = dayTokens.length ? Math.max(...dayTokens) : 0;
|
|
1844
|
+
const range = max - min;
|
|
1845
|
+
const norm = (v) => range === 0 ? 0 : (v - min) / range;
|
|
1846
|
+
const dimRule = (pos) => c.dim(rule(colWidths, pos, g));
|
|
1847
|
+
lines.push(dimRule("top"));
|
|
1848
|
+
lines.push(renderRow(headers, (p) => c.dim(p)));
|
|
1849
|
+
lines.push(dimRule("mid"));
|
|
1850
|
+
summary.perDay.forEach((d, idx) => {
|
|
1851
|
+
lines.push(
|
|
1852
|
+
renderRow(bodyRows[idx], (p, col) => {
|
|
1853
|
+
if (col === 1) return c.accentByLevel(p, norm(d.tokens));
|
|
1854
|
+
if (col === 2) return c.dim(p);
|
|
1855
|
+
return p;
|
|
1856
|
+
})
|
|
1857
|
+
);
|
|
1858
|
+
});
|
|
1859
|
+
lines.push(dimRule("mid"));
|
|
1860
|
+
lines.push(
|
|
1861
|
+
renderRow(totalRow, (p, col) => {
|
|
1862
|
+
if (col === 0) return c.dim(c.bold(p));
|
|
1863
|
+
if (col === 1) return c.bold(c.coral(p));
|
|
1864
|
+
return c.coral(p);
|
|
1865
|
+
})
|
|
1866
|
+
);
|
|
1867
|
+
lines.push(dimRule("bottom"));
|
|
1868
|
+
const spark = sparkline(dayTokens, style.ascii, (glyph, i) => c.accentByLevel(glyph, norm(dayTokens[i])));
|
|
1869
|
+
if (spark) lines.push(c.dim("daily burn ") + spark);
|
|
1870
|
+
const modelStrip = renderModelStrip(summary, c);
|
|
1871
|
+
if (modelStrip) lines.push(modelStrip);
|
|
1703
1872
|
lines.push(
|
|
1704
1873
|
c.dim("approx $ is a local estimate from a bundled LiteLLM snapshot \u2014 the server is authoritative")
|
|
1705
1874
|
);
|
|
@@ -1708,32 +1877,46 @@ function renderLocalPreview(summary, style) {
|
|
|
1708
1877
|
}
|
|
1709
1878
|
return lines.join("\n");
|
|
1710
1879
|
}
|
|
1880
|
+
function renderModelStrip(summary, c) {
|
|
1881
|
+
if (summary.perModel.length === 0) return "";
|
|
1882
|
+
const TOP = 3;
|
|
1883
|
+
const shown = summary.perModel.slice(0, TOP);
|
|
1884
|
+
const parts = shown.map((m, rank) => {
|
|
1885
|
+
const name = displayModel(m.model) + (m.priced ? "" : c.dim("*"));
|
|
1886
|
+
const nameStyled = rank === 0 ? c.coral(name) : name;
|
|
1887
|
+
return `${nameStyled} ${humanizeTokens(m.tokens)} ${c.dim(formatApproxUsd(m.costUsd))}`;
|
|
1888
|
+
});
|
|
1889
|
+
let strip = c.dim("models ") + parts.join(c.dim(" \xB7 "));
|
|
1890
|
+
const extra = summary.perModel.length - shown.length;
|
|
1891
|
+
if (extra > 0) strip += c.dim(` \xB7 +${extra} more`);
|
|
1892
|
+
return strip;
|
|
1893
|
+
}
|
|
1711
1894
|
var CLAIM_PROMPT = "Sign in with GitHub to claim your spot?";
|
|
1712
1895
|
var CLAIM_HINT = "\u2192 Claim your spot anytime \u2192 tokenboard claim";
|
|
1713
1896
|
|
|
1714
1897
|
// src/config/auth-store.ts
|
|
1715
1898
|
init_esm_shims();
|
|
1716
1899
|
import { homedir, platform } from "os";
|
|
1717
|
-
import { join as
|
|
1900
|
+
import { join as join4, isAbsolute } from "path";
|
|
1718
1901
|
import { mkdir, writeFile, chmod, rename, unlink, readFile } from "fs/promises";
|
|
1719
|
-
import { randomBytes } from "crypto";
|
|
1902
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
1720
1903
|
function resolveConfigDir(env = process.env) {
|
|
1721
1904
|
if (platform() === "win32") {
|
|
1722
|
-
const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA :
|
|
1723
|
-
return
|
|
1905
|
+
const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA : join4(homedir(), "AppData", "Roaming");
|
|
1906
|
+
return join4(appData, "tokenboard");
|
|
1724
1907
|
}
|
|
1725
1908
|
const xdg = env.XDG_CONFIG_HOME;
|
|
1726
|
-
const base = xdg && isAbsolute(xdg) ? xdg :
|
|
1727
|
-
return
|
|
1909
|
+
const base = xdg && isAbsolute(xdg) ? xdg : join4(homedir(), ".config");
|
|
1910
|
+
return join4(base, "tokenboard");
|
|
1728
1911
|
}
|
|
1729
1912
|
function resolveAuthPath(env = process.env) {
|
|
1730
|
-
return
|
|
1913
|
+
return join4(resolveConfigDir(env), "auth.json");
|
|
1731
1914
|
}
|
|
1732
1915
|
async function writeAuthFile(auth, env = process.env) {
|
|
1733
1916
|
const dir = resolveConfigDir(env);
|
|
1734
|
-
const finalPath =
|
|
1917
|
+
const finalPath = join4(dir, "auth.json");
|
|
1735
1918
|
await mkdir(dir, { recursive: true, mode: 448 });
|
|
1736
|
-
const tmpPath =
|
|
1919
|
+
const tmpPath = join4(dir, `.auth.json.${randomBytes2(6).toString("hex")}.tmp`);
|
|
1737
1920
|
const body = `${JSON.stringify(auth, null, 2)}
|
|
1738
1921
|
`;
|
|
1739
1922
|
try {
|
|
@@ -2137,133 +2320,6 @@ function clientLabel() {
|
|
|
2137
2320
|
return `${hostname()} (${platform3()})`;
|
|
2138
2321
|
}
|
|
2139
2322
|
|
|
2140
|
-
// src/commands/claim.ts
|
|
2141
|
-
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2142
|
-
var out = (line) => process.stdout.write(`${line}
|
|
2143
|
-
`);
|
|
2144
|
-
async function runClaim() {
|
|
2145
|
-
const base = resolveApiBase();
|
|
2146
|
-
const grant = await startDeviceGrant(base, clientLabel(), machineHash());
|
|
2147
|
-
if (process.stdout.isTTY) openInBrowser(grant.verification_url);
|
|
2148
|
-
out("");
|
|
2149
|
-
out(" Open this URL to approve this machine:");
|
|
2150
|
-
out(` ${grant.verification_url}`);
|
|
2151
|
-
out(` Code: ${grant.user_code}`);
|
|
2152
|
-
out(" Waiting for approval...");
|
|
2153
|
-
out("");
|
|
2154
|
-
const deadline = Date.now() + grant.expires_in * 1e3;
|
|
2155
|
-
let intervalMs = grant.interval * 1e3;
|
|
2156
|
-
let first = true;
|
|
2157
|
-
while (Date.now() < deadline) {
|
|
2158
|
-
if (!first) await sleep(intervalMs);
|
|
2159
|
-
first = false;
|
|
2160
|
-
const result = await pollDeviceGrant(base, grant.device_code);
|
|
2161
|
-
if (result.status === "complete") {
|
|
2162
|
-
const path2 = await writeAuthFile({
|
|
2163
|
-
token: result.ingest_token,
|
|
2164
|
-
userId: result.userId,
|
|
2165
|
-
handle: result.user.handle,
|
|
2166
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2167
|
-
});
|
|
2168
|
-
out(` Claimed as @${result.user.handle}. Saved credentials to ${path2}`);
|
|
2169
|
-
return;
|
|
2170
|
-
}
|
|
2171
|
-
if (result.status === "denied") {
|
|
2172
|
-
throw new Error("Approval was denied in the browser.");
|
|
2173
|
-
}
|
|
2174
|
-
if (result.status === "expired") {
|
|
2175
|
-
throw new Error("This claim request expired. Run `tokenboard claim` again.");
|
|
2176
|
-
}
|
|
2177
|
-
if (result.status === "slow_down") {
|
|
2178
|
-
intervalMs += 5e3;
|
|
2179
|
-
continue;
|
|
2180
|
-
}
|
|
2181
|
-
}
|
|
2182
|
-
throw new Error("This claim request expired. Run `tokenboard claim` again.");
|
|
2183
|
-
}
|
|
2184
|
-
|
|
2185
|
-
// src/commands/preview.ts
|
|
2186
|
-
async function collectLocalRecords() {
|
|
2187
|
-
const tz = resolveTimeZone();
|
|
2188
|
-
const claudeLines = dedupeByMessageId(collectClaudeCodeLines(resolveProjectsRoot(homedir2())));
|
|
2189
|
-
const claudeRecords = claudeLines.map((l) => parsedLineToRecord(l, tz));
|
|
2190
|
-
const ccusage = await collectCcusage();
|
|
2191
|
-
const records = aggregateByKey([...claudeRecords, ...ccusage.records]);
|
|
2192
|
-
return { records, ccusageSkipped: ccusage.skipped, npxAvailable: ccusage.npxAvailable };
|
|
2193
|
-
}
|
|
2194
|
-
async function runPreview(args) {
|
|
2195
|
-
const prices = loadPriceTable();
|
|
2196
|
-
const { records } = await collectLocalRecords();
|
|
2197
|
-
const summary = summarize(records, prices);
|
|
2198
|
-
if (args.json) {
|
|
2199
|
-
process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
|
|
2200
|
-
return;
|
|
2201
|
-
}
|
|
2202
|
-
const style = resolveStyle({
|
|
2203
|
-
isTTY: Boolean(process.stdout.isTTY),
|
|
2204
|
-
// Per the NO_COLOR spec (no-color.org), color is disabled when the var is PRESENT
|
|
2205
|
-
// regardless of value — so `NO_COLOR=` (empty) still counts. Test presence, not truthiness.
|
|
2206
|
-
noColorEnv: process.env["NO_COLOR"] !== void 0,
|
|
2207
|
-
noColorFlag: args.noColor,
|
|
2208
|
-
asciiFlag: args.ascii,
|
|
2209
|
-
columns: process.stdout.columns
|
|
2210
|
-
});
|
|
2211
|
-
process.stdout.write(renderLocalPreview(summary, style) + "\n");
|
|
2212
|
-
await offerClaim(style);
|
|
2213
|
-
}
|
|
2214
|
-
async function offerClaim(style) {
|
|
2215
|
-
if (!process.stdin.isTTY || !process.stdout.isTTY) return;
|
|
2216
|
-
const c = styler(style);
|
|
2217
|
-
const auth = await readAuthFile();
|
|
2218
|
-
if (auth) {
|
|
2219
|
-
process.stdout.write("\n" + c.dim(`\u2713 claimed as @${auth.handle} \xB7 run \`tokenboard sync\` to upload`) + "\n");
|
|
2220
|
-
return;
|
|
2221
|
-
}
|
|
2222
|
-
process.stdout.write("\n");
|
|
2223
|
-
if (await confirm(c.cyan(CLAIM_PROMPT))) {
|
|
2224
|
-
await runClaim();
|
|
2225
|
-
return;
|
|
2226
|
-
}
|
|
2227
|
-
process.stdout.write(c.dim(CLAIM_HINT) + "\n");
|
|
2228
|
-
}
|
|
2229
|
-
|
|
2230
|
-
// src/commands/show-data.ts
|
|
2231
|
-
init_esm_shims();
|
|
2232
|
-
async function runShowData() {
|
|
2233
|
-
const { records, ccusageSkipped, npxAvailable } = await collectLocalRecords();
|
|
2234
|
-
const failures = [];
|
|
2235
|
-
for (const rec of records) {
|
|
2236
|
-
const result = normalizedRecordSchema.safeParse(rec);
|
|
2237
|
-
if (!result.success) failures.push({ record: rec, issues: result.error.issues });
|
|
2238
|
-
}
|
|
2239
|
-
process.stdout.write(
|
|
2240
|
-
" tokenboard show-data \u2014 dry run. This is EXACTLY what a future `sync` would upload.\n Counts only \u2014 no prompts, code, file paths, or repo names. NOTHING is uploaded in this release.\n\n"
|
|
2241
|
-
);
|
|
2242
|
-
if (failures.length > 0) {
|
|
2243
|
-
process.stderr.write(
|
|
2244
|
-
`show-data: ${failures.length} record(s) failed contract validation (parser bug):
|
|
2245
|
-
` + JSON.stringify(failures, null, 2) + "\n"
|
|
2246
|
-
);
|
|
2247
|
-
process.exitCode = 1;
|
|
2248
|
-
return;
|
|
2249
|
-
}
|
|
2250
|
-
process.stdout.write(JSON.stringify(records, null, 2) + "\n");
|
|
2251
|
-
if (!npxAvailable) {
|
|
2252
|
-
process.stdout.write("\n (npx not found \u2014 ccusage long-tail skipped; Claude Code data shown above)\n");
|
|
2253
|
-
} else if (ccusageSkipped.length > 0) {
|
|
2254
|
-
process.stdout.write(`
|
|
2255
|
-
(ccusage sources skipped: ${ccusageSkipped.join(", ")})
|
|
2256
|
-
`);
|
|
2257
|
-
}
|
|
2258
|
-
}
|
|
2259
|
-
|
|
2260
|
-
// src/commands/stub.ts
|
|
2261
|
-
init_esm_shims();
|
|
2262
|
-
function notAvailableYet(name, phase) {
|
|
2263
|
-
process.stdout.write(` tokenboard ${name} \u2014 coming in a later release (${phase}).
|
|
2264
|
-
`);
|
|
2265
|
-
}
|
|
2266
|
-
|
|
2267
2323
|
// src/commands/sync.ts
|
|
2268
2324
|
init_esm_shims();
|
|
2269
2325
|
|
|
@@ -2339,7 +2395,7 @@ var CHUNK_SIZE = 500;
|
|
|
2339
2395
|
var CLI_VERSION = "0.0.1";
|
|
2340
2396
|
var IN_PROGRESS_RETRIES = 3;
|
|
2341
2397
|
var IN_PROGRESS_BACKOFF_MS = 1e3;
|
|
2342
|
-
var
|
|
2398
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2343
2399
|
async function sendChunk(base, token, body) {
|
|
2344
2400
|
const key = chunkIdempotencyKey(body);
|
|
2345
2401
|
for (let attempt = 0; ; attempt++) {
|
|
@@ -2347,7 +2403,7 @@ async function sendChunk(base, token, body) {
|
|
|
2347
2403
|
return await postSyncChunk(base, token, key, CLI_VERSION, body);
|
|
2348
2404
|
} catch (err) {
|
|
2349
2405
|
if (err instanceof SyncInProgressError && attempt < IN_PROGRESS_RETRIES) {
|
|
2350
|
-
await
|
|
2406
|
+
await sleep(IN_PROGRESS_BACKOFF_MS * (attempt + 1));
|
|
2351
2407
|
continue;
|
|
2352
2408
|
}
|
|
2353
2409
|
throw err;
|
|
@@ -2393,6 +2449,151 @@ async function runSync() {
|
|
|
2393
2449
|
`);
|
|
2394
2450
|
}
|
|
2395
2451
|
|
|
2452
|
+
// src/commands/claim.ts
|
|
2453
|
+
var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2454
|
+
var out = (line) => process.stdout.write(`${line}
|
|
2455
|
+
`);
|
|
2456
|
+
async function runClaim() {
|
|
2457
|
+
const base = resolveApiBase();
|
|
2458
|
+
const grant = await startDeviceGrant(base, clientLabel(), machineHash());
|
|
2459
|
+
if (process.stdout.isTTY) openInBrowser(grant.verification_url);
|
|
2460
|
+
out("");
|
|
2461
|
+
out(" Open this URL to approve this machine:");
|
|
2462
|
+
out(` ${grant.verification_url}`);
|
|
2463
|
+
out(` Code: ${grant.user_code}`);
|
|
2464
|
+
out(" Waiting for approval...");
|
|
2465
|
+
out("");
|
|
2466
|
+
const deadline = Date.now() + grant.expires_in * 1e3;
|
|
2467
|
+
let intervalMs = grant.interval * 1e3;
|
|
2468
|
+
let first = true;
|
|
2469
|
+
while (Date.now() < deadline) {
|
|
2470
|
+
if (!first) await sleep2(intervalMs);
|
|
2471
|
+
first = false;
|
|
2472
|
+
const result = await pollDeviceGrant(base, grant.device_code);
|
|
2473
|
+
if (result.status === "complete") {
|
|
2474
|
+
const path2 = await writeAuthFile({
|
|
2475
|
+
token: result.ingest_token,
|
|
2476
|
+
userId: result.userId,
|
|
2477
|
+
handle: result.user.handle,
|
|
2478
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2479
|
+
});
|
|
2480
|
+
out(` Claimed as @${result.user.handle}. Saved credentials to ${path2}`);
|
|
2481
|
+
out("");
|
|
2482
|
+
try {
|
|
2483
|
+
await runSync();
|
|
2484
|
+
} catch {
|
|
2485
|
+
out(" Couldn't sync usage just now \u2014 run `tokenboard sync` to appear on the board.");
|
|
2486
|
+
}
|
|
2487
|
+
return;
|
|
2488
|
+
}
|
|
2489
|
+
if (result.status === "denied") {
|
|
2490
|
+
throw new Error("Approval was denied in the browser.");
|
|
2491
|
+
}
|
|
2492
|
+
if (result.status === "expired") {
|
|
2493
|
+
throw new Error("This claim request expired. Run `tokenboard claim` again.");
|
|
2494
|
+
}
|
|
2495
|
+
if (result.status === "slow_down") {
|
|
2496
|
+
intervalMs += 5e3;
|
|
2497
|
+
continue;
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
throw new Error("This claim request expired. Run `tokenboard claim` again.");
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
// src/commands/preview.ts
|
|
2504
|
+
async function collectLocalRecords() {
|
|
2505
|
+
const tz = resolveTimeZone();
|
|
2506
|
+
const files = findJsonlFiles(resolveProjectsRoot(homedir2()));
|
|
2507
|
+
const [claudeLines, ccusage] = await Promise.all([
|
|
2508
|
+
Promise.resolve().then(() => dedupeByMessageId(collectClaudeCodeLinesCached(files, resolveConfigDir()))),
|
|
2509
|
+
collectCcusage()
|
|
2510
|
+
]);
|
|
2511
|
+
const claudeRecords = claudeLines.map((l) => parsedLineToRecord(l, tz));
|
|
2512
|
+
const records = aggregateByKey([...claudeRecords, ...ccusage.records]);
|
|
2513
|
+
return { records, ccusageSkipped: ccusage.skipped, npxAvailable: ccusage.npxAvailable };
|
|
2514
|
+
}
|
|
2515
|
+
async function runPreview(args) {
|
|
2516
|
+
const prices = loadPriceTable();
|
|
2517
|
+
const spinner = args.json ? null : startSpinner("reading your local usage\u2026", args.ascii);
|
|
2518
|
+
let records;
|
|
2519
|
+
try {
|
|
2520
|
+
({ records } = await collectLocalRecords());
|
|
2521
|
+
} finally {
|
|
2522
|
+
spinner?.stop();
|
|
2523
|
+
}
|
|
2524
|
+
const summary = summarize(records, prices);
|
|
2525
|
+
if (args.json) {
|
|
2526
|
+
process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
|
|
2527
|
+
return;
|
|
2528
|
+
}
|
|
2529
|
+
const style = resolveStyle({
|
|
2530
|
+
isTTY: Boolean(process.stdout.isTTY),
|
|
2531
|
+
// Per the NO_COLOR spec (no-color.org), color is disabled when the var is PRESENT
|
|
2532
|
+
// regardless of value — so `NO_COLOR=` (empty) still counts. Test presence, not truthiness.
|
|
2533
|
+
noColorEnv: process.env["NO_COLOR"] !== void 0,
|
|
2534
|
+
noColorFlag: args.noColor,
|
|
2535
|
+
asciiFlag: args.ascii,
|
|
2536
|
+
columns: process.stdout.columns,
|
|
2537
|
+
colorterm: process.env["COLORTERM"],
|
|
2538
|
+
term: process.env["TERM"],
|
|
2539
|
+
forceColor: process.env["FORCE_COLOR"]
|
|
2540
|
+
});
|
|
2541
|
+
process.stdout.write(renderLocalPreview(summary, style) + "\n");
|
|
2542
|
+
await offerClaim(style);
|
|
2543
|
+
}
|
|
2544
|
+
async function offerClaim(style) {
|
|
2545
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return;
|
|
2546
|
+
const c = styler(style);
|
|
2547
|
+
const auth = await readAuthFile();
|
|
2548
|
+
if (auth) {
|
|
2549
|
+
process.stdout.write("\n" + c.dim(`\u2713 claimed as @${auth.handle} \xB7 run \`tokenboard sync\` to upload`) + "\n");
|
|
2550
|
+
return;
|
|
2551
|
+
}
|
|
2552
|
+
process.stdout.write("\n");
|
|
2553
|
+
if (await confirm(c.cyan(CLAIM_PROMPT))) {
|
|
2554
|
+
await runClaim();
|
|
2555
|
+
return;
|
|
2556
|
+
}
|
|
2557
|
+
process.stdout.write(c.dim(CLAIM_HINT) + "\n");
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
// src/commands/show-data.ts
|
|
2561
|
+
init_esm_shims();
|
|
2562
|
+
async function runShowData() {
|
|
2563
|
+
const { records, ccusageSkipped, npxAvailable } = await collectLocalRecords();
|
|
2564
|
+
const failures = [];
|
|
2565
|
+
for (const rec of records) {
|
|
2566
|
+
const result = normalizedRecordSchema.safeParse(rec);
|
|
2567
|
+
if (!result.success) failures.push({ record: rec, issues: result.error.issues });
|
|
2568
|
+
}
|
|
2569
|
+
process.stdout.write(
|
|
2570
|
+
" tokenboard show-data \u2014 dry run. This is EXACTLY what a future `sync` would upload.\n Counts only \u2014 no prompts, code, file paths, or repo names. NOTHING is uploaded in this release.\n\n"
|
|
2571
|
+
);
|
|
2572
|
+
if (failures.length > 0) {
|
|
2573
|
+
process.stderr.write(
|
|
2574
|
+
`show-data: ${failures.length} record(s) failed contract validation (parser bug):
|
|
2575
|
+
` + JSON.stringify(failures, null, 2) + "\n"
|
|
2576
|
+
);
|
|
2577
|
+
process.exitCode = 1;
|
|
2578
|
+
return;
|
|
2579
|
+
}
|
|
2580
|
+
process.stdout.write(JSON.stringify(records, null, 2) + "\n");
|
|
2581
|
+
if (!npxAvailable) {
|
|
2582
|
+
process.stdout.write("\n (npx not found \u2014 ccusage long-tail skipped; Claude Code data shown above)\n");
|
|
2583
|
+
} else if (ccusageSkipped.length > 0) {
|
|
2584
|
+
process.stdout.write(`
|
|
2585
|
+
(ccusage sources skipped: ${ccusageSkipped.join(", ")})
|
|
2586
|
+
`);
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
// src/commands/stub.ts
|
|
2591
|
+
init_esm_shims();
|
|
2592
|
+
function notAvailableYet(name, phase) {
|
|
2593
|
+
process.stdout.write(` tokenboard ${name} \u2014 coming in a later release (${phase}).
|
|
2594
|
+
`);
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2396
2597
|
// src/cli.ts
|
|
2397
2598
|
var windowArgs = {
|
|
2398
2599
|
"7d": { type: "boolean", description: "leaderboard window: last 7 days" },
|