@tokenboard/cli 0.1.4 → 0.1.6

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 CHANGED
@@ -587,13 +587,13 @@ function _getBuiltinFlags(long, short, userNames, userAliases) {
587
587
 
588
588
  // src/commands/preview.ts
589
589
  init_esm_shims();
590
- import { homedir as homedir2 } from "os";
590
+ import { homedir as homedir3 } from "os";
591
591
 
592
592
  // src/config/home.ts
593
593
  init_esm_shims();
594
594
  import { join } from "path";
595
- function resolveProjectsRoot(homedir3) {
596
- return join(homedir3, ".claude", "projects");
595
+ function resolveProjectsRoot(homedir4) {
596
+ return join(homedir4, ".claude", "projects");
597
597
  }
598
598
 
599
599
  // src/collectors/claude-code-source.ts
@@ -794,6 +794,9 @@ function parsedLineToRecord(line, timeZone) {
794
794
  // src/collectors/ccusage-source.ts
795
795
  init_esm_shims();
796
796
  import { spawn, spawnSync } from "child_process";
797
+ import { readdirSync as readdirSync2, readFileSync as readFileSync3 } from "fs";
798
+ import { homedir } from "os";
799
+ import { join as join4 } from "path";
797
800
 
798
801
  // src/collectors/ccusage-sources.ts
799
802
  init_esm_shims();
@@ -847,7 +850,30 @@ function ccusageDailyToRecords(source, daily) {
847
850
 
848
851
  // src/collectors/ccusage-source.ts
849
852
  var SPAWN_TIMEOUT_MS = 3e4;
853
+ var CCUSAGE_MAJOR = 20;
850
854
  var CLAUDE_AGENT = "claude";
855
+ function resolveCachedCcusageV20(npxCache = join4(homedir(), ".npm", "_npx")) {
856
+ try {
857
+ for (const hash of readdirSync2(npxCache)) {
858
+ const pkgDir = join4(npxCache, hash, "node_modules", "ccusage");
859
+ let pkg;
860
+ try {
861
+ pkg = JSON.parse(readFileSync3(join4(pkgDir, "package.json"), "utf8"));
862
+ } catch {
863
+ continue;
864
+ }
865
+ if (typeof pkg.version !== "string") continue;
866
+ const major = Number.parseInt(pkg.version.split(".")[0] ?? "", 10);
867
+ if (major !== CCUSAGE_MAJOR) continue;
868
+ const binField = pkg.bin;
869
+ const binRel = typeof binField === "string" ? binField : typeof binField === "object" && binField !== null ? binField["ccusage"] : void 0;
870
+ if (typeof binRel !== "string") continue;
871
+ return join4(pkgDir, binRel);
872
+ }
873
+ } catch {
874
+ }
875
+ return null;
876
+ }
851
877
  function hasNpx() {
852
878
  try {
853
879
  const r = spawnSync("npx", ["--version"], { stdio: "ignore" });
@@ -856,9 +882,16 @@ function hasNpx() {
856
882
  return false;
857
883
  }
858
884
  }
885
+ var cachedBinPath;
886
+ function ccusageV20Bin() {
887
+ if (cachedBinPath === void 0) cachedBinPath = resolveCachedCcusageV20();
888
+ return cachedBinPath;
889
+ }
859
890
  function runCcusage(args) {
891
+ const bin = ccusageV20Bin();
892
+ const [cmd, cmdArgs] = bin ? [process.execPath, [bin, ...args]] : ["npx", ["-y", "ccusage@20", ...args]];
860
893
  return new Promise((resolve, reject) => {
861
- const child = spawn("npx", ["-y", "ccusage@20", ...args], { stdio: ["ignore", "pipe", "ignore"] });
894
+ const child = spawn(cmd, cmdArgs, { stdio: ["ignore", "pipe", "ignore"] });
862
895
  let stdout = "";
863
896
  const killer = setTimeout(() => child.kill("SIGKILL"), SPAWN_TIMEOUT_MS);
864
897
  child.stdout.on("data", (chunk2) => {
@@ -909,7 +942,7 @@ function canSkipFanOut(agents) {
909
942
  return [...agents].every((a) => a === CLAUDE_AGENT);
910
943
  }
911
944
  async function collectCcusage() {
912
- if (!hasNpx()) {
945
+ if (ccusageV20Bin() === null && !hasNpx()) {
913
946
  return { records: [], skipped: [], npxAvailable: false };
914
947
  }
915
948
  const agents = await detectAgentsWithData();
@@ -1027,6 +1060,17 @@ if (provenance_default.priceTableVersion !== PRICE_TABLE_VERSION || provenance_d
1027
1060
  function recordTokens(r) {
1028
1061
  return r.input + r.output + r.cacheRead + r.cacheCreate5m + r.cacheCreate1h;
1029
1062
  }
1063
+ function dominantModel(byModel) {
1064
+ let best = "";
1065
+ let bestTokens = -1;
1066
+ for (const [model, tokens] of byModel) {
1067
+ if (tokens > bestTokens || tokens === bestTokens && model < best) {
1068
+ best = model;
1069
+ bestTokens = tokens;
1070
+ }
1071
+ }
1072
+ return best;
1073
+ }
1030
1074
  function summarize(records, prices) {
1031
1075
  let totalTokens = 0;
1032
1076
  let totalCostUsd = 0;
@@ -1044,9 +1088,10 @@ function summarize(records, prices) {
1044
1088
  unpricedTokens += tokens;
1045
1089
  unpricedModels.add(r.model);
1046
1090
  }
1047
- const d = perDay.get(r.date) ?? { tokens: 0, costUsd: 0 };
1091
+ const d = perDay.get(r.date) ?? { tokens: 0, costUsd: 0, byModel: /* @__PURE__ */ new Map() };
1048
1092
  d.tokens += tokens;
1049
1093
  d.costUsd += costUsd;
1094
+ d.byModel.set(r.model, (d.byModel.get(r.model) ?? 0) + tokens);
1050
1095
  perDay.set(r.date, d);
1051
1096
  const t = perTool.get(r.tool) ?? { tokens: 0, costUsd: 0 };
1052
1097
  t.tokens += tokens;
@@ -1064,7 +1109,7 @@ function summarize(records, prices) {
1064
1109
  anyUnpriced: unpricedModels.size > 0,
1065
1110
  unpricedTokens,
1066
1111
  unpricedModels: [...unpricedModels].sort(),
1067
- perDay: [...perDay.entries()].map(([date, v]) => ({ date, ...v })).sort((a, b) => a.date < b.date ? -1 : 1),
1112
+ perDay: [...perDay.entries()].map(([date, v]) => ({ date, tokens: v.tokens, costUsd: v.costUsd, model: dominantModel(v.byModel) })).sort((a, b) => a.date < b.date ? -1 : 1),
1068
1113
  perTool: [...perTool.entries()].map(([tool, v]) => ({ tool, ...v })).sort((a, b) => b.tokens - a.tokens),
1069
1114
  perModel: [...perModel.entries()].map(([model, v]) => ({ model, ...v })).sort((a, b) => b.tokens - a.tokens)
1070
1115
  };
@@ -1785,20 +1830,6 @@ function formatApproxUsd(n) {
1785
1830
  return "~$" + Math.round(n).toLocaleString("en-US");
1786
1831
  }
1787
1832
 
1788
- // src/render/sparkline.ts
1789
- init_esm_shims();
1790
- var GLYPHS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
1791
- var ASCII_GLYPHS = ["_", ".", ".", "-", "-", "=", "=", "#"];
1792
- function sparkline(values, ascii = false, colorize) {
1793
- const glyphs2 = ascii ? ASCII_GLYPHS : GLYPHS;
1794
- if (values.length === 0) return "";
1795
- const min = Math.min(...values);
1796
- const max = Math.max(...values);
1797
- const range = max - min;
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
1833
  // src/render/model-display.ts
1803
1834
  init_esm_shims();
1804
1835
  function displayModel(model) {
@@ -1817,14 +1848,16 @@ function renderLocalPreview(summary, style) {
1817
1848
  );
1818
1849
  lines.push("");
1819
1850
  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"];
1851
+ const headers = ["date", "model", "tokens", "~$ est"];
1852
+ const aligns = ["left", "left", "right", "right"];
1822
1853
  const bodyRows = summary.perDay.map((d) => [
1823
1854
  d.date,
1855
+ displayModel(d.model),
1824
1856
  humanizeTokens(d.tokens),
1825
1857
  formatApproxUsd(d.costUsd)
1826
1858
  ]);
1827
- const totalRow = ["TOTAL", humanizeTokens(summary.totalTokens), formatApproxUsd(summary.totalCostUsd)];
1859
+ const totalModel = summary.perModel[0] ? displayModel(summary.perModel[0].model) : "";
1860
+ const totalRow = ["TOTAL", totalModel, humanizeTokens(summary.totalTokens), formatApproxUsd(summary.totalCostUsd)];
1828
1861
  const allRows = [headers, ...bodyRows, totalRow];
1829
1862
  const colWidths = headers.map(
1830
1863
  (_, col) => Math.max(...allRows.map((r) => [...r[col]].length), 1)
@@ -1850,8 +1883,9 @@ function renderLocalPreview(summary, style) {
1850
1883
  summary.perDay.forEach((d, idx) => {
1851
1884
  lines.push(
1852
1885
  renderRow(bodyRows[idx], (p, col) => {
1853
- if (col === 1) return c.accentByLevel(p, norm(d.tokens));
1854
- if (col === 2) return c.dim(p);
1886
+ if (col === 1) return c.dim(p);
1887
+ if (col === 2) return c.accentByLevel(p, norm(d.tokens));
1888
+ if (col === 3) return c.dim(p);
1855
1889
  return p;
1856
1890
  })
1857
1891
  );
@@ -1860,15 +1894,12 @@ function renderLocalPreview(summary, style) {
1860
1894
  lines.push(
1861
1895
  renderRow(totalRow, (p, col) => {
1862
1896
  if (col === 0) return c.dim(c.bold(p));
1863
- if (col === 1) return c.bold(c.coral(p));
1897
+ if (col === 1) return c.coral(p);
1898
+ if (col === 2) return c.bold(c.coral(p));
1864
1899
  return c.coral(p);
1865
1900
  })
1866
1901
  );
1867
1902
  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);
1872
1903
  lines.push(
1873
1904
  c.dim("approx $ is a local estimate from a bundled LiteLLM snapshot \u2014 the server is authoritative")
1874
1905
  );
@@ -1877,46 +1908,32 @@ function renderLocalPreview(summary, style) {
1877
1908
  }
1878
1909
  return lines.join("\n");
1879
1910
  }
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
- }
1894
1911
  var CLAIM_PROMPT = "Sign in with GitHub to claim your spot?";
1895
1912
  var CLAIM_HINT = "\u2192 Claim your spot anytime \u2192 tokenboard claim";
1896
1913
 
1897
1914
  // src/config/auth-store.ts
1898
1915
  init_esm_shims();
1899
- import { homedir, platform } from "os";
1900
- import { join as join4, isAbsolute } from "path";
1916
+ import { homedir as homedir2, platform } from "os";
1917
+ import { join as join5, isAbsolute } from "path";
1901
1918
  import { mkdir, writeFile, chmod, rename, unlink, readFile } from "fs/promises";
1902
1919
  import { randomBytes as randomBytes2 } from "crypto";
1903
1920
  function resolveConfigDir(env = process.env) {
1904
1921
  if (platform() === "win32") {
1905
- const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA : join4(homedir(), "AppData", "Roaming");
1906
- return join4(appData, "tokenboard");
1922
+ const appData = env.APPDATA && env.APPDATA.trim() !== "" ? env.APPDATA : join5(homedir2(), "AppData", "Roaming");
1923
+ return join5(appData, "tokenboard");
1907
1924
  }
1908
1925
  const xdg = env.XDG_CONFIG_HOME;
1909
- const base = xdg && isAbsolute(xdg) ? xdg : join4(homedir(), ".config");
1910
- return join4(base, "tokenboard");
1926
+ const base = xdg && isAbsolute(xdg) ? xdg : join5(homedir2(), ".config");
1927
+ return join5(base, "tokenboard");
1911
1928
  }
1912
1929
  function resolveAuthPath(env = process.env) {
1913
- return join4(resolveConfigDir(env), "auth.json");
1930
+ return join5(resolveConfigDir(env), "auth.json");
1914
1931
  }
1915
1932
  async function writeAuthFile(auth, env = process.env) {
1916
1933
  const dir = resolveConfigDir(env);
1917
- const finalPath = join4(dir, "auth.json");
1934
+ const finalPath = join5(dir, "auth.json");
1918
1935
  await mkdir(dir, { recursive: true, mode: 448 });
1919
- const tmpPath = join4(dir, `.auth.json.${randomBytes2(6).toString("hex")}.tmp`);
1936
+ const tmpPath = join5(dir, `.auth.json.${randomBytes2(6).toString("hex")}.tmp`);
1920
1937
  const body = `${JSON.stringify(auth, null, 2)}
1921
1938
  `;
1922
1939
  try {
@@ -2503,7 +2520,7 @@ async function runClaim() {
2503
2520
  // src/commands/preview.ts
2504
2521
  async function collectLocalRecords() {
2505
2522
  const tz = resolveTimeZone();
2506
- const files = findJsonlFiles(resolveProjectsRoot(homedir2()));
2523
+ const files = findJsonlFiles(resolveProjectsRoot(homedir3()));
2507
2524
  const [claudeLines, ccusage] = await Promise.all([
2508
2525
  Promise.resolve().then(() => dedupeByMessageId(collectClaudeCodeLinesCached(files, resolveConfigDir()))),
2509
2526
  collectCcusage()