@tokenboard/cli 0.1.1 → 0.1.3
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 +349 -214
- 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
|
|
@@ -793,6 +847,7 @@ function ccusageDailyToRecords(source, daily) {
|
|
|
793
847
|
|
|
794
848
|
// src/collectors/ccusage-source.ts
|
|
795
849
|
var SPAWN_TIMEOUT_MS = 3e4;
|
|
850
|
+
var CLAUDE_AGENT = "claude";
|
|
796
851
|
function hasNpx() {
|
|
797
852
|
try {
|
|
798
853
|
const r = spawnSync("npx", ["--version"], { stdio: "ignore" });
|
|
@@ -801,11 +856,9 @@ function hasNpx() {
|
|
|
801
856
|
return false;
|
|
802
857
|
}
|
|
803
858
|
}
|
|
804
|
-
function
|
|
859
|
+
function runCcusage(args) {
|
|
805
860
|
return new Promise((resolve, reject) => {
|
|
806
|
-
const child = spawn("npx", ["-y", "ccusage@20",
|
|
807
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
808
|
-
});
|
|
861
|
+
const child = spawn("npx", ["-y", "ccusage@20", ...args], { stdio: ["ignore", "pipe", "ignore"] });
|
|
809
862
|
let stdout = "";
|
|
810
863
|
const killer = setTimeout(() => child.kill("SIGKILL"), SPAWN_TIMEOUT_MS);
|
|
811
864
|
child.stdout.on("data", (chunk2) => {
|
|
@@ -818,22 +871,51 @@ function runSource(source) {
|
|
|
818
871
|
child.on("close", (code) => {
|
|
819
872
|
clearTimeout(killer);
|
|
820
873
|
if (code !== 0) {
|
|
821
|
-
reject(new Error(`ccusage ${
|
|
874
|
+
reject(new Error(`ccusage ${args.join(" ")} exited ${code}`));
|
|
822
875
|
return;
|
|
823
876
|
}
|
|
824
|
-
|
|
825
|
-
const parsed = JSON.parse(stdout);
|
|
826
|
-
resolve(parsed.daily ?? []);
|
|
827
|
-
} catch (err) {
|
|
828
|
-
reject(err);
|
|
829
|
-
}
|
|
877
|
+
resolve(stdout);
|
|
830
878
|
});
|
|
831
879
|
});
|
|
832
880
|
}
|
|
881
|
+
function runSource(source) {
|
|
882
|
+
return runCcusage([source, "daily", "--json", "--offline"]).then((stdout) => {
|
|
883
|
+
const parsed = JSON.parse(stdout);
|
|
884
|
+
return parsed.daily ?? [];
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
function agentsFromDailyPayload(parsed) {
|
|
888
|
+
const rows = typeof parsed === "object" && parsed !== null && Array.isArray(parsed.daily) ? parsed.daily : [];
|
|
889
|
+
const agents = /* @__PURE__ */ new Set();
|
|
890
|
+
for (const row2 of rows) {
|
|
891
|
+
const list = row2?.metadata?.agents;
|
|
892
|
+
if (Array.isArray(list)) {
|
|
893
|
+
for (const a of list) if (typeof a === "string") agents.add(a.toLowerCase());
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
if (rows.length > 0 && agents.size === 0) return null;
|
|
897
|
+
return agents;
|
|
898
|
+
}
|
|
899
|
+
async function detectAgentsWithData() {
|
|
900
|
+
try {
|
|
901
|
+
const stdout = await runCcusage(["daily", "--json", "--offline"]);
|
|
902
|
+
return agentsFromDailyPayload(JSON.parse(stdout));
|
|
903
|
+
} catch {
|
|
904
|
+
return null;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
function canSkipFanOut(agents) {
|
|
908
|
+
if (agents === null) return false;
|
|
909
|
+
return [...agents].every((a) => a === CLAUDE_AGENT);
|
|
910
|
+
}
|
|
833
911
|
async function collectCcusage() {
|
|
834
912
|
if (!hasNpx()) {
|
|
835
913
|
return { records: [], skipped: [], npxAvailable: false };
|
|
836
914
|
}
|
|
915
|
+
const agents = await detectAgentsWithData();
|
|
916
|
+
if (canSkipFanOut(agents)) {
|
|
917
|
+
return { records: [], skipped: [], npxAvailable: true };
|
|
918
|
+
}
|
|
837
919
|
const records = [];
|
|
838
920
|
const skipped = [];
|
|
839
921
|
await Promise.all(
|
|
@@ -962,7 +1044,10 @@ function summarize(records, prices) {
|
|
|
962
1044
|
unpricedTokens += tokens;
|
|
963
1045
|
unpricedModels.add(r.model);
|
|
964
1046
|
}
|
|
965
|
-
|
|
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);
|
|
966
1051
|
const t = perTool.get(r.tool) ?? { tokens: 0, costUsd: 0 };
|
|
967
1052
|
t.tokens += tokens;
|
|
968
1053
|
t.costUsd += costUsd;
|
|
@@ -979,7 +1064,7 @@ function summarize(records, prices) {
|
|
|
979
1064
|
anyUnpriced: unpricedModels.size > 0,
|
|
980
1065
|
unpricedTokens,
|
|
981
1066
|
unpricedModels: [...unpricedModels].sort(),
|
|
982
|
-
perDay: [...perDay.entries()].map(([date,
|
|
1067
|
+
perDay: [...perDay.entries()].map(([date, v]) => ({ date, ...v })).sort((a, b) => a.date < b.date ? -1 : 1),
|
|
983
1068
|
perTool: [...perTool.entries()].map(([tool, v]) => ({ tool, ...v })).sort((a, b) => b.tokens - a.tokens),
|
|
984
1069
|
perModel: [...perModel.entries()].map(([model, v]) => ({ model, ...v })).sort((a, b) => b.tokens - a.tokens)
|
|
985
1070
|
};
|
|
@@ -1007,6 +1092,38 @@ function styler(style) {
|
|
|
1007
1092
|
};
|
|
1008
1093
|
}
|
|
1009
1094
|
|
|
1095
|
+
// src/render/spinner.ts
|
|
1096
|
+
init_esm_shims();
|
|
1097
|
+
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1098
|
+
var FRAMES_ASCII = ["|", "/", "-", "\\"];
|
|
1099
|
+
var INTERVAL_MS = 80;
|
|
1100
|
+
function startSpinner(label, ascii = false) {
|
|
1101
|
+
if (!process.stderr.isTTY) return { stop: () => {
|
|
1102
|
+
} };
|
|
1103
|
+
const frames = ascii ? FRAMES_ASCII : FRAMES;
|
|
1104
|
+
let i = 0;
|
|
1105
|
+
const write = (s) => process.stderr.write(s);
|
|
1106
|
+
write("\x1B[?25l");
|
|
1107
|
+
const render = () => {
|
|
1108
|
+
const frame = frames[i % frames.length];
|
|
1109
|
+
i += 1;
|
|
1110
|
+
write(`\r${frame} ${label}`);
|
|
1111
|
+
};
|
|
1112
|
+
render();
|
|
1113
|
+
const timer = setInterval(render, INTERVAL_MS);
|
|
1114
|
+
timer.unref?.();
|
|
1115
|
+
let stopped = false;
|
|
1116
|
+
return {
|
|
1117
|
+
stop: () => {
|
|
1118
|
+
if (stopped) return;
|
|
1119
|
+
stopped = true;
|
|
1120
|
+
clearInterval(timer);
|
|
1121
|
+
write("\r\x1B[2K");
|
|
1122
|
+
write("\x1B[?25h");
|
|
1123
|
+
}
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1010
1127
|
// src/render/local-preview.ts
|
|
1011
1128
|
init_esm_shims();
|
|
1012
1129
|
|
|
@@ -1647,31 +1764,34 @@ function renderLocalPreview(summary, style) {
|
|
|
1647
1764
|
c.bold(`you burned ${humanizeTokens(summary.totalTokens)} tokens`) + ` \xB7 ${formatApproxUsd(summary.totalCostUsd)} est`
|
|
1648
1765
|
);
|
|
1649
1766
|
lines.push("");
|
|
1650
|
-
lines.push(c.dim("\u{1FA99} tokenboard \xB7 your local usage"));
|
|
1651
|
-
const
|
|
1652
|
-
const
|
|
1653
|
-
const
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
humanizeTokens(t.tokens),
|
|
1658
|
-
formatApproxUsd(t.costUsd),
|
|
1659
|
-
spark
|
|
1660
|
-
// same per-day series across the board in Phase 2 (per-tool series is Phase 6+)
|
|
1767
|
+
lines.push(c.dim("\u{1FA99} tokenboard \xB7 your local usage by day"));
|
|
1768
|
+
const headers = ["date", "tokens", "~$ est"];
|
|
1769
|
+
const aligns = ["left", "right", "right"];
|
|
1770
|
+
const bodyRows = summary.perDay.map((d) => [
|
|
1771
|
+
d.date,
|
|
1772
|
+
humanizeTokens(d.tokens),
|
|
1773
|
+
formatApproxUsd(d.costUsd)
|
|
1661
1774
|
]);
|
|
1662
|
-
const
|
|
1775
|
+
const totalRow = ["TOTAL", humanizeTokens(summary.totalTokens), formatApproxUsd(summary.totalCostUsd)];
|
|
1776
|
+
const allRows = [headers, ...bodyRows, totalRow];
|
|
1663
1777
|
const colWidths = headers.map(
|
|
1664
1778
|
(_, col) => Math.max(...allRows.map((r) => [...r[col]].length), 1)
|
|
1665
1779
|
);
|
|
1666
1780
|
const cellAlign = (i) => aligns[i] ?? "left";
|
|
1667
1781
|
const width = (i) => colWidths[i] ?? 1;
|
|
1782
|
+
const renderRow = (cells) => row(cells.map((cell, i) => padCell(cell, width(i), cellAlign(i))), g);
|
|
1668
1783
|
lines.push(rule(colWidths, "top", g));
|
|
1669
|
-
lines.push(
|
|
1784
|
+
lines.push(renderRow(headers));
|
|
1670
1785
|
lines.push(rule(colWidths, "mid", g));
|
|
1671
|
-
for (const r of bodyRows)
|
|
1672
|
-
|
|
1673
|
-
|
|
1786
|
+
for (const r of bodyRows) lines.push(renderRow(r));
|
|
1787
|
+
lines.push(rule(colWidths, "mid", g));
|
|
1788
|
+
lines.push(renderRow(totalRow));
|
|
1674
1789
|
lines.push(rule(colWidths, "bottom", g));
|
|
1790
|
+
const spark = sparkline(
|
|
1791
|
+
summary.perDay.map((d) => d.tokens),
|
|
1792
|
+
style.ascii
|
|
1793
|
+
);
|
|
1794
|
+
if (spark) lines.push(c.dim("daily burn ") + spark);
|
|
1675
1795
|
lines.push(
|
|
1676
1796
|
c.dim("approx $ is a local estimate from a bundled LiteLLM snapshot \u2014 the server is authoritative")
|
|
1677
1797
|
);
|
|
@@ -1686,26 +1806,26 @@ var CLAIM_HINT = "\u2192 Claim your spot anytime \u2192 tokenboard claim";
|
|
|
1686
1806
|
// src/config/auth-store.ts
|
|
1687
1807
|
init_esm_shims();
|
|
1688
1808
|
import { homedir, platform } from "os";
|
|
1689
|
-
import { join as
|
|
1809
|
+
import { join as join4, isAbsolute } from "path";
|
|
1690
1810
|
import { mkdir, writeFile, chmod, rename, unlink, readFile } from "fs/promises";
|
|
1691
|
-
import { randomBytes } from "crypto";
|
|
1811
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
1692
1812
|
function resolveConfigDir(env = process.env) {
|
|
1693
1813
|
if (platform() === "win32") {
|
|
1694
|
-
const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA :
|
|
1695
|
-
return
|
|
1814
|
+
const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA : join4(homedir(), "AppData", "Roaming");
|
|
1815
|
+
return join4(appData, "tokenboard");
|
|
1696
1816
|
}
|
|
1697
1817
|
const xdg = env.XDG_CONFIG_HOME;
|
|
1698
|
-
const base = xdg && isAbsolute(xdg) ? xdg :
|
|
1699
|
-
return
|
|
1818
|
+
const base = xdg && isAbsolute(xdg) ? xdg : join4(homedir(), ".config");
|
|
1819
|
+
return join4(base, "tokenboard");
|
|
1700
1820
|
}
|
|
1701
1821
|
function resolveAuthPath(env = process.env) {
|
|
1702
|
-
return
|
|
1822
|
+
return join4(resolveConfigDir(env), "auth.json");
|
|
1703
1823
|
}
|
|
1704
1824
|
async function writeAuthFile(auth, env = process.env) {
|
|
1705
1825
|
const dir = resolveConfigDir(env);
|
|
1706
|
-
const finalPath =
|
|
1826
|
+
const finalPath = join4(dir, "auth.json");
|
|
1707
1827
|
await mkdir(dir, { recursive: true, mode: 448 });
|
|
1708
|
-
const tmpPath =
|
|
1828
|
+
const tmpPath = join4(dir, `.auth.json.${randomBytes2(6).toString("hex")}.tmp`);
|
|
1709
1829
|
const body = `${JSON.stringify(auth, null, 2)}
|
|
1710
1830
|
`;
|
|
1711
1831
|
try {
|
|
@@ -2109,133 +2229,6 @@ function clientLabel() {
|
|
|
2109
2229
|
return `${hostname()} (${platform3()})`;
|
|
2110
2230
|
}
|
|
2111
2231
|
|
|
2112
|
-
// src/commands/claim.ts
|
|
2113
|
-
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2114
|
-
var out = (line) => process.stdout.write(`${line}
|
|
2115
|
-
`);
|
|
2116
|
-
async function runClaim() {
|
|
2117
|
-
const base = resolveApiBase();
|
|
2118
|
-
const grant = await startDeviceGrant(base, clientLabel(), machineHash());
|
|
2119
|
-
if (process.stdout.isTTY) openInBrowser(grant.verification_url);
|
|
2120
|
-
out("");
|
|
2121
|
-
out(" Open this URL to approve this machine:");
|
|
2122
|
-
out(` ${grant.verification_url}`);
|
|
2123
|
-
out(` Code: ${grant.user_code}`);
|
|
2124
|
-
out(" Waiting for approval...");
|
|
2125
|
-
out("");
|
|
2126
|
-
const deadline = Date.now() + grant.expires_in * 1e3;
|
|
2127
|
-
let intervalMs = grant.interval * 1e3;
|
|
2128
|
-
let first = true;
|
|
2129
|
-
while (Date.now() < deadline) {
|
|
2130
|
-
if (!first) await sleep(intervalMs);
|
|
2131
|
-
first = false;
|
|
2132
|
-
const result = await pollDeviceGrant(base, grant.device_code);
|
|
2133
|
-
if (result.status === "complete") {
|
|
2134
|
-
const path2 = await writeAuthFile({
|
|
2135
|
-
token: result.ingest_token,
|
|
2136
|
-
userId: result.userId,
|
|
2137
|
-
handle: result.user.handle,
|
|
2138
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2139
|
-
});
|
|
2140
|
-
out(` Claimed as @${result.user.handle}. Saved credentials to ${path2}`);
|
|
2141
|
-
return;
|
|
2142
|
-
}
|
|
2143
|
-
if (result.status === "denied") {
|
|
2144
|
-
throw new Error("Approval was denied in the browser.");
|
|
2145
|
-
}
|
|
2146
|
-
if (result.status === "expired") {
|
|
2147
|
-
throw new Error("This claim request expired. Run `tokenboard claim` again.");
|
|
2148
|
-
}
|
|
2149
|
-
if (result.status === "slow_down") {
|
|
2150
|
-
intervalMs += 5e3;
|
|
2151
|
-
continue;
|
|
2152
|
-
}
|
|
2153
|
-
}
|
|
2154
|
-
throw new Error("This claim request expired. Run `tokenboard claim` again.");
|
|
2155
|
-
}
|
|
2156
|
-
|
|
2157
|
-
// src/commands/preview.ts
|
|
2158
|
-
async function collectLocalRecords() {
|
|
2159
|
-
const tz = resolveTimeZone();
|
|
2160
|
-
const claudeLines = dedupeByMessageId(collectClaudeCodeLines(resolveProjectsRoot(homedir2())));
|
|
2161
|
-
const claudeRecords = claudeLines.map((l) => parsedLineToRecord(l, tz));
|
|
2162
|
-
const ccusage = await collectCcusage();
|
|
2163
|
-
const records = aggregateByKey([...claudeRecords, ...ccusage.records]);
|
|
2164
|
-
return { records, ccusageSkipped: ccusage.skipped, npxAvailable: ccusage.npxAvailable };
|
|
2165
|
-
}
|
|
2166
|
-
async function runPreview(args) {
|
|
2167
|
-
const prices = loadPriceTable();
|
|
2168
|
-
const { records } = await collectLocalRecords();
|
|
2169
|
-
const summary = summarize(records, prices);
|
|
2170
|
-
if (args.json) {
|
|
2171
|
-
process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
|
|
2172
|
-
return;
|
|
2173
|
-
}
|
|
2174
|
-
const style = resolveStyle({
|
|
2175
|
-
isTTY: Boolean(process.stdout.isTTY),
|
|
2176
|
-
// Per the NO_COLOR spec (no-color.org), color is disabled when the var is PRESENT
|
|
2177
|
-
// regardless of value — so `NO_COLOR=` (empty) still counts. Test presence, not truthiness.
|
|
2178
|
-
noColorEnv: process.env["NO_COLOR"] !== void 0,
|
|
2179
|
-
noColorFlag: args.noColor,
|
|
2180
|
-
asciiFlag: args.ascii,
|
|
2181
|
-
columns: process.stdout.columns
|
|
2182
|
-
});
|
|
2183
|
-
process.stdout.write(renderLocalPreview(summary, style) + "\n");
|
|
2184
|
-
await offerClaim(style);
|
|
2185
|
-
}
|
|
2186
|
-
async function offerClaim(style) {
|
|
2187
|
-
if (!process.stdin.isTTY || !process.stdout.isTTY) return;
|
|
2188
|
-
const c = styler(style);
|
|
2189
|
-
const auth = await readAuthFile();
|
|
2190
|
-
if (auth) {
|
|
2191
|
-
process.stdout.write("\n" + c.dim(`\u2713 claimed as @${auth.handle} \xB7 run \`tokenboard sync\` to upload`) + "\n");
|
|
2192
|
-
return;
|
|
2193
|
-
}
|
|
2194
|
-
process.stdout.write("\n");
|
|
2195
|
-
if (await confirm(c.cyan(CLAIM_PROMPT))) {
|
|
2196
|
-
await runClaim();
|
|
2197
|
-
return;
|
|
2198
|
-
}
|
|
2199
|
-
process.stdout.write(c.dim(CLAIM_HINT) + "\n");
|
|
2200
|
-
}
|
|
2201
|
-
|
|
2202
|
-
// src/commands/show-data.ts
|
|
2203
|
-
init_esm_shims();
|
|
2204
|
-
async function runShowData() {
|
|
2205
|
-
const { records, ccusageSkipped, npxAvailable } = await collectLocalRecords();
|
|
2206
|
-
const failures = [];
|
|
2207
|
-
for (const rec of records) {
|
|
2208
|
-
const result = normalizedRecordSchema.safeParse(rec);
|
|
2209
|
-
if (!result.success) failures.push({ record: rec, issues: result.error.issues });
|
|
2210
|
-
}
|
|
2211
|
-
process.stdout.write(
|
|
2212
|
-
" 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"
|
|
2213
|
-
);
|
|
2214
|
-
if (failures.length > 0) {
|
|
2215
|
-
process.stderr.write(
|
|
2216
|
-
`show-data: ${failures.length} record(s) failed contract validation (parser bug):
|
|
2217
|
-
` + JSON.stringify(failures, null, 2) + "\n"
|
|
2218
|
-
);
|
|
2219
|
-
process.exitCode = 1;
|
|
2220
|
-
return;
|
|
2221
|
-
}
|
|
2222
|
-
process.stdout.write(JSON.stringify(records, null, 2) + "\n");
|
|
2223
|
-
if (!npxAvailable) {
|
|
2224
|
-
process.stdout.write("\n (npx not found \u2014 ccusage long-tail skipped; Claude Code data shown above)\n");
|
|
2225
|
-
} else if (ccusageSkipped.length > 0) {
|
|
2226
|
-
process.stdout.write(`
|
|
2227
|
-
(ccusage sources skipped: ${ccusageSkipped.join(", ")})
|
|
2228
|
-
`);
|
|
2229
|
-
}
|
|
2230
|
-
}
|
|
2231
|
-
|
|
2232
|
-
// src/commands/stub.ts
|
|
2233
|
-
init_esm_shims();
|
|
2234
|
-
function notAvailableYet(name, phase) {
|
|
2235
|
-
process.stdout.write(` tokenboard ${name} \u2014 coming in a later release (${phase}).
|
|
2236
|
-
`);
|
|
2237
|
-
}
|
|
2238
|
-
|
|
2239
2232
|
// src/commands/sync.ts
|
|
2240
2233
|
init_esm_shims();
|
|
2241
2234
|
|
|
@@ -2311,7 +2304,7 @@ var CHUNK_SIZE = 500;
|
|
|
2311
2304
|
var CLI_VERSION = "0.0.1";
|
|
2312
2305
|
var IN_PROGRESS_RETRIES = 3;
|
|
2313
2306
|
var IN_PROGRESS_BACKOFF_MS = 1e3;
|
|
2314
|
-
var
|
|
2307
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2315
2308
|
async function sendChunk(base, token, body) {
|
|
2316
2309
|
const key = chunkIdempotencyKey(body);
|
|
2317
2310
|
for (let attempt = 0; ; attempt++) {
|
|
@@ -2319,7 +2312,7 @@ async function sendChunk(base, token, body) {
|
|
|
2319
2312
|
return await postSyncChunk(base, token, key, CLI_VERSION, body);
|
|
2320
2313
|
} catch (err) {
|
|
2321
2314
|
if (err instanceof SyncInProgressError && attempt < IN_PROGRESS_RETRIES) {
|
|
2322
|
-
await
|
|
2315
|
+
await sleep(IN_PROGRESS_BACKOFF_MS * (attempt + 1));
|
|
2323
2316
|
continue;
|
|
2324
2317
|
}
|
|
2325
2318
|
throw err;
|
|
@@ -2365,6 +2358,148 @@ async function runSync() {
|
|
|
2365
2358
|
`);
|
|
2366
2359
|
}
|
|
2367
2360
|
|
|
2361
|
+
// src/commands/claim.ts
|
|
2362
|
+
var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2363
|
+
var out = (line) => process.stdout.write(`${line}
|
|
2364
|
+
`);
|
|
2365
|
+
async function runClaim() {
|
|
2366
|
+
const base = resolveApiBase();
|
|
2367
|
+
const grant = await startDeviceGrant(base, clientLabel(), machineHash());
|
|
2368
|
+
if (process.stdout.isTTY) openInBrowser(grant.verification_url);
|
|
2369
|
+
out("");
|
|
2370
|
+
out(" Open this URL to approve this machine:");
|
|
2371
|
+
out(` ${grant.verification_url}`);
|
|
2372
|
+
out(` Code: ${grant.user_code}`);
|
|
2373
|
+
out(" Waiting for approval...");
|
|
2374
|
+
out("");
|
|
2375
|
+
const deadline = Date.now() + grant.expires_in * 1e3;
|
|
2376
|
+
let intervalMs = grant.interval * 1e3;
|
|
2377
|
+
let first = true;
|
|
2378
|
+
while (Date.now() < deadline) {
|
|
2379
|
+
if (!first) await sleep2(intervalMs);
|
|
2380
|
+
first = false;
|
|
2381
|
+
const result = await pollDeviceGrant(base, grant.device_code);
|
|
2382
|
+
if (result.status === "complete") {
|
|
2383
|
+
const path2 = await writeAuthFile({
|
|
2384
|
+
token: result.ingest_token,
|
|
2385
|
+
userId: result.userId,
|
|
2386
|
+
handle: result.user.handle,
|
|
2387
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2388
|
+
});
|
|
2389
|
+
out(` Claimed as @${result.user.handle}. Saved credentials to ${path2}`);
|
|
2390
|
+
out("");
|
|
2391
|
+
try {
|
|
2392
|
+
await runSync();
|
|
2393
|
+
} catch {
|
|
2394
|
+
out(" Couldn't sync usage just now \u2014 run `tokenboard sync` to appear on the board.");
|
|
2395
|
+
}
|
|
2396
|
+
return;
|
|
2397
|
+
}
|
|
2398
|
+
if (result.status === "denied") {
|
|
2399
|
+
throw new Error("Approval was denied in the browser.");
|
|
2400
|
+
}
|
|
2401
|
+
if (result.status === "expired") {
|
|
2402
|
+
throw new Error("This claim request expired. Run `tokenboard claim` again.");
|
|
2403
|
+
}
|
|
2404
|
+
if (result.status === "slow_down") {
|
|
2405
|
+
intervalMs += 5e3;
|
|
2406
|
+
continue;
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
throw new Error("This claim request expired. Run `tokenboard claim` again.");
|
|
2410
|
+
}
|
|
2411
|
+
|
|
2412
|
+
// src/commands/preview.ts
|
|
2413
|
+
async function collectLocalRecords() {
|
|
2414
|
+
const tz = resolveTimeZone();
|
|
2415
|
+
const files = findJsonlFiles(resolveProjectsRoot(homedir2()));
|
|
2416
|
+
const [claudeLines, ccusage] = await Promise.all([
|
|
2417
|
+
Promise.resolve().then(() => dedupeByMessageId(collectClaudeCodeLinesCached(files, resolveConfigDir()))),
|
|
2418
|
+
collectCcusage()
|
|
2419
|
+
]);
|
|
2420
|
+
const claudeRecords = claudeLines.map((l) => parsedLineToRecord(l, tz));
|
|
2421
|
+
const records = aggregateByKey([...claudeRecords, ...ccusage.records]);
|
|
2422
|
+
return { records, ccusageSkipped: ccusage.skipped, npxAvailable: ccusage.npxAvailable };
|
|
2423
|
+
}
|
|
2424
|
+
async function runPreview(args) {
|
|
2425
|
+
const prices = loadPriceTable();
|
|
2426
|
+
const spinner = args.json ? null : startSpinner("reading your local usage\u2026", args.ascii);
|
|
2427
|
+
let records;
|
|
2428
|
+
try {
|
|
2429
|
+
({ records } = await collectLocalRecords());
|
|
2430
|
+
} finally {
|
|
2431
|
+
spinner?.stop();
|
|
2432
|
+
}
|
|
2433
|
+
const summary = summarize(records, prices);
|
|
2434
|
+
if (args.json) {
|
|
2435
|
+
process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
|
|
2436
|
+
return;
|
|
2437
|
+
}
|
|
2438
|
+
const style = resolveStyle({
|
|
2439
|
+
isTTY: Boolean(process.stdout.isTTY),
|
|
2440
|
+
// Per the NO_COLOR spec (no-color.org), color is disabled when the var is PRESENT
|
|
2441
|
+
// regardless of value — so `NO_COLOR=` (empty) still counts. Test presence, not truthiness.
|
|
2442
|
+
noColorEnv: process.env["NO_COLOR"] !== void 0,
|
|
2443
|
+
noColorFlag: args.noColor,
|
|
2444
|
+
asciiFlag: args.ascii,
|
|
2445
|
+
columns: process.stdout.columns
|
|
2446
|
+
});
|
|
2447
|
+
process.stdout.write(renderLocalPreview(summary, style) + "\n");
|
|
2448
|
+
await offerClaim(style);
|
|
2449
|
+
}
|
|
2450
|
+
async function offerClaim(style) {
|
|
2451
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return;
|
|
2452
|
+
const c = styler(style);
|
|
2453
|
+
const auth = await readAuthFile();
|
|
2454
|
+
if (auth) {
|
|
2455
|
+
process.stdout.write("\n" + c.dim(`\u2713 claimed as @${auth.handle} \xB7 run \`tokenboard sync\` to upload`) + "\n");
|
|
2456
|
+
return;
|
|
2457
|
+
}
|
|
2458
|
+
process.stdout.write("\n");
|
|
2459
|
+
if (await confirm(c.cyan(CLAIM_PROMPT))) {
|
|
2460
|
+
await runClaim();
|
|
2461
|
+
return;
|
|
2462
|
+
}
|
|
2463
|
+
process.stdout.write(c.dim(CLAIM_HINT) + "\n");
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2466
|
+
// src/commands/show-data.ts
|
|
2467
|
+
init_esm_shims();
|
|
2468
|
+
async function runShowData() {
|
|
2469
|
+
const { records, ccusageSkipped, npxAvailable } = await collectLocalRecords();
|
|
2470
|
+
const failures = [];
|
|
2471
|
+
for (const rec of records) {
|
|
2472
|
+
const result = normalizedRecordSchema.safeParse(rec);
|
|
2473
|
+
if (!result.success) failures.push({ record: rec, issues: result.error.issues });
|
|
2474
|
+
}
|
|
2475
|
+
process.stdout.write(
|
|
2476
|
+
" 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"
|
|
2477
|
+
);
|
|
2478
|
+
if (failures.length > 0) {
|
|
2479
|
+
process.stderr.write(
|
|
2480
|
+
`show-data: ${failures.length} record(s) failed contract validation (parser bug):
|
|
2481
|
+
` + JSON.stringify(failures, null, 2) + "\n"
|
|
2482
|
+
);
|
|
2483
|
+
process.exitCode = 1;
|
|
2484
|
+
return;
|
|
2485
|
+
}
|
|
2486
|
+
process.stdout.write(JSON.stringify(records, null, 2) + "\n");
|
|
2487
|
+
if (!npxAvailable) {
|
|
2488
|
+
process.stdout.write("\n (npx not found \u2014 ccusage long-tail skipped; Claude Code data shown above)\n");
|
|
2489
|
+
} else if (ccusageSkipped.length > 0) {
|
|
2490
|
+
process.stdout.write(`
|
|
2491
|
+
(ccusage sources skipped: ${ccusageSkipped.join(", ")})
|
|
2492
|
+
`);
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
// src/commands/stub.ts
|
|
2497
|
+
init_esm_shims();
|
|
2498
|
+
function notAvailableYet(name, phase) {
|
|
2499
|
+
process.stdout.write(` tokenboard ${name} \u2014 coming in a later release (${phase}).
|
|
2500
|
+
`);
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2368
2503
|
// src/cli.ts
|
|
2369
2504
|
var windowArgs = {
|
|
2370
2505
|
"7d": { type: "boolean", description: "leaderboard window: last 7 days" },
|