usagebench 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +236 -2
  3. package/dist/anon.d.ts +11 -0
  4. package/dist/anon.js +107 -0
  5. package/dist/audit.d.ts +1 -0
  6. package/dist/audit.js +127 -0
  7. package/dist/bip39_english.d.ts +1 -0
  8. package/dist/bip39_english.js +126 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +77 -0
  11. package/dist/compare.d.ts +16 -0
  12. package/dist/compare.js +189 -0
  13. package/dist/diff.d.ts +1 -0
  14. package/dist/diff.js +80 -0
  15. package/dist/doctor.d.ts +1 -0
  16. package/dist/doctor.js +109 -0
  17. package/dist/index.d.ts +45 -0
  18. package/dist/index.js +171 -0
  19. package/dist/logs.d.ts +22 -0
  20. package/dist/logs.js +105 -0
  21. package/dist/repro.d.ts +1 -0
  22. package/dist/repro.js +149 -0
  23. package/dist/secrets.d.ts +11 -0
  24. package/dist/secrets.js +100 -0
  25. package/fixtures/claude/2.1.334_main.expected.json +21 -0
  26. package/fixtures/claude/2.1.334_main.jsonl +162 -0
  27. package/fixtures/claude/2.1.335_sidechain.expected.json +21 -0
  28. package/fixtures/claude/2.1.335_sidechain.jsonl +60 -0
  29. package/fixtures/claude/2.1.335_stream-abort-tool-error.expected.json +21 -0
  30. package/fixtures/claude/2.1.335_stream-abort-tool-error.jsonl +200 -0
  31. package/fixtures/claude/synthetic_duplicate-id-partial-usage.expected.json +22 -0
  32. package/fixtures/claude/synthetic_duplicate-id-partial-usage.jsonl +6 -0
  33. package/fixtures/codex/0.160.0_compacted.expected.json +38 -0
  34. package/fixtures/codex/0.160.0_compacted.jsonl +200 -0
  35. package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.expected.json +38 -0
  36. package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.jsonl +154 -0
  37. package/fixtures/codex/0.173.0-alpha.4.1_basic.expected.json +38 -0
  38. package/fixtures/codex/0.173.0-alpha.4.1_basic.jsonl +200 -0
  39. package/fixtures/codex/synthetic_total-reset.expected.json +39 -0
  40. package/fixtures/codex/synthetic_total-reset.jsonl +12 -0
  41. package/package.json +34 -4
package/dist/cli.js ADDED
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { basename } from "node:path";
4
+ import { report, usage } from "./index.js";
5
+ import { compare } from "./compare.js";
6
+ import { doctor } from "./doctor.js";
7
+ import { audit } from "./audit.js";
8
+ import { repro } from "./repro.js";
9
+ import { diff } from "./diff.js";
10
+ import { logFiles, parseLenient, readText } from "./logs.js";
11
+ const HELP = `usagebench: token-usage QA for AI coding agent logs (Claude Code, Codex, antigravity-cli)
12
+ No network code; read-only (only \`audit --fix --yes\` writes, and keeps a backup).
13
+ Log directories are found automatically (~/.claude/projects, ~/.codex/sessions; CLAUDE_CONFIG_DIR / CODEX_HOME override).
14
+
15
+ usage:
16
+ usagebench doctor how much a naive tracker would overcount on your logs
17
+ usagebench audit [--fix [--yes]] plaintext secrets in your logs (masked; --fix redacts, dry run without --yes)
18
+ usagebench repro [--latest|--session <id>] [--agent claude|codex] [--tracker <name>] [--out <dir>] [--max-kb 50]
19
+ anonymized minimal repro + expected.json + issue.md
20
+ usagebench diff [--days 7] installed trackers vs usagebench on a temp copy of your recent logs
21
+ usagebench compare [--ccusage <cmd>] [--tokscale <cmd>] [--splitrail <bin>]
22
+ trackers vs the bundled fixtures (scorecard)
23
+ usagebench <claude|codex> [file.jsonl] naive and deduplicated totals (all local logs when no file is given)
24
+ usagebench agy <transcript.jsonl> same for an antigravity-cli transcript
25
+
26
+ compare, diff and repro --tracker run the trackers you have (ccusage, tokscale, splitrail); they may go online.`;
27
+ const [cmd, ...rest] = process.argv.slice(2);
28
+ const commands = { compare, doctor: () => doctor(), audit, repro, diff };
29
+ if (!cmd || cmd === "--help" || cmd === "-h" || cmd === "help") {
30
+ console.log(HELP);
31
+ process.exit(cmd ? 0 : 2);
32
+ }
33
+ if (commands[cmd])
34
+ process.exit(commands[cmd](rest));
35
+ const file = rest[0];
36
+ try {
37
+ if (file) {
38
+ console.log(JSON.stringify(report(cmd, readFileSync(file, "utf8"), { sourceFile: basename(file) }), null, 1));
39
+ }
40
+ else if (cmd === "claude" || cmd === "codex") {
41
+ // All local logs of this agent; per file for Codex, (sessionId, message.id) across files for Claude.
42
+ const agent = cmd, all = [];
43
+ const sum = (ts) => ts.reduce((a, t) => { for (const k of Object.keys(a))
44
+ a[k] += t[k]; return a; }, { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 });
45
+ const naive = [], dedup = [], tcn = [], tcd = [];
46
+ let files = 0;
47
+ for (const f of logFiles(agent)) {
48
+ const text = readText(f);
49
+ if (text === null)
50
+ continue;
51
+ files++;
52
+ const { records } = parseLenient(agent, text);
53
+ if (agent === "claude")
54
+ all.push(...records);
55
+ else {
56
+ naive.push(usage(agent, records, { dedup: false }));
57
+ dedup.push(usage(agent, records));
58
+ tcn.push(usage(agent, records, { dedup: false, source: "token_count" }));
59
+ tcd.push(usage(agent, records, { source: "token_count" }));
60
+ }
61
+ }
62
+ const res = { agent, files };
63
+ if (agent === "claude")
64
+ Object.assign(res, { naive: usage(agent, all, { dedup: false }), dedup: usage(agent, all) });
65
+ else
66
+ Object.assign(res, { naive: sum(naive), dedup: sum(dedup), token_count_naive: sum(tcn), token_count_dedup: sum(tcd) });
67
+ console.log(JSON.stringify(res, null, 1));
68
+ }
69
+ else {
70
+ console.error(cmd === "agy" ? "usagebench agy needs a transcript file" : `unknown command "${cmd}"\n\n${HELP}`);
71
+ process.exit(2);
72
+ }
73
+ }
74
+ catch (e) {
75
+ console.error(String(e.message ?? e));
76
+ process.exit(1);
77
+ }
@@ -0,0 +1,16 @@
1
+ export type Totals = Record<string, number | null | undefined>;
2
+ export declare function place(agent: string, fixture: string, home: string): void;
3
+ export declare const ccusage: (cmd: string) => (agent: string, env: NodeJS.ProcessEnv) => Totals;
4
+ export declare const tokscale: (cmd: string) => (agent: string, env: NodeJS.ProcessEnv) => Totals;
5
+ export declare const splitrail: (bin: string) => (agent: string, env: NodeJS.ProcessEnv) => Totals;
6
+ export declare function version(cmd: string): string;
7
+ export declare function expectedInToolTerms(agent: string, exp: any): Totals;
8
+ export declare function homeEnv(home: string): NodeJS.ProcessEnv;
9
+ export declare function delta(got: Totals, e: Totals): string;
10
+ export declare function onPath(name: string): string | null;
11
+ export type Tracker = {
12
+ fn: (a: string, env: NodeJS.ProcessEnv) => Totals;
13
+ ver: string;
14
+ };
15
+ export declare function installedTrackers(args: string[], only?: string): Record<string, Tracker>;
16
+ export declare function compare(args: string[]): number;
@@ -0,0 +1,189 @@
1
+ // `usagebench compare`: run ccusage, tokscale and (optionally) splitrail on every bundled Claude/Codex fixture
2
+ // and compare their totals with .expected.json. Port of tools/compare_tools.py (same placement, env and
3
+ // expected-value rules; see that file's docstring). Prints a scorecard; returns 1 on any mismatch or error.
4
+ import { spawnSync } from "node:child_process";
5
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
6
+ import { homedir, tmpdir } from "node:os";
7
+ import { basename, dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ const F = ["input", "output", "cache_write", "cache_read", "reasoning"];
10
+ const pkg = join(dirname(fileURLToPath(import.meta.url)), "..");
11
+ // In a clone, use the repo's fixtures/; an installed package uses the copy made at prepack.
12
+ function fixturesDir() {
13
+ const repo = join(pkg, "..", "fixtures");
14
+ if (basename(pkg) === "parser" && existsSync(repo))
15
+ return repo;
16
+ return join(pkg, "fixtures");
17
+ }
18
+ function run(cmd, env, cwd) {
19
+ const r = spawnSync(cmd, { shell: true, env, cwd, encoding: "utf8", timeout: 300_000, windowsHide: true,
20
+ maxBuffer: 64 * 1024 * 1024 });
21
+ if (r.error)
22
+ throw r.error;
23
+ if (r.status !== 0)
24
+ throw new Error(`exit ${r.status}: ${(r.stderr ?? "").trim().slice(-300)}`);
25
+ return r.stdout;
26
+ }
27
+ function runJson(cmd, env) {
28
+ const out = run(cmd, env, env.HOME); // cwd = throwaway home: tokscale writes .tokscale/ into it
29
+ return JSON.parse(out.slice(out.indexOf("{"))); // ccusage/tokscale may print a notice first
30
+ }
31
+ export function place(agent, fixture, home) {
32
+ let dst;
33
+ if (agent === "claude") {
34
+ const lines = readFileSync(fixture, "utf8").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
35
+ const sid = lines.find((o) => o.sessionId)?.sessionId ?? "session";
36
+ dst = join(home, ".claude", "projects", "fixture", `${sid}.jsonl`);
37
+ }
38
+ else {
39
+ dst = join(home, ".codex", "sessions", "2026", "01", "01", "rollout-2026-01-01T00-00-00-0199a000-0000-7000-8000-000000000001.jsonl");
40
+ }
41
+ mkdirSync(dirname(dst), { recursive: true });
42
+ copyFileSync(fixture, dst);
43
+ }
44
+ export const ccusage = (cmd) => (agent, env) => {
45
+ const t = runJson(`${cmd} ${agent} daily --json --offline`, env).totals;
46
+ return { input: t.inputTokens, output: t.outputTokens, cache_write: t.cacheCreationTokens,
47
+ cache_read: t.cacheReadTokens, reasoning: t.reasoningOutputTokens };
48
+ };
49
+ export const tokscale = (cmd) => (agent, env) => {
50
+ const d = runJson(`${cmd} models --json --offline --client ${agent}`, env);
51
+ const reasoning = d.entries.reduce((s, e) => s + (e.reasoning ?? 0), 0);
52
+ return { input: d.totalInput, output: d.totalOutput + (agent === "codex" ? reasoning : 0), // excludes reasoning
53
+ cache_write: d.totalCacheWrite, cache_read: d.totalCacheRead, reasoning };
54
+ };
55
+ export const splitrail = (bin) => (agent, env) => {
56
+ const name = agent === "claude" ? "Claude Code" : "Codex CLI";
57
+ const d = runJson(`"${bin}" stats`, env);
58
+ const t = { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 };
59
+ for (const a of d.analyzer_stats.filter((a) => a.analyzer_name === name))
60
+ for (const day of Object.values(a.daily_stats))
61
+ for (const m of Object.values(day.model_stats ?? {})) {
62
+ t.input += m.inputTokens;
63
+ t.output += m.outputTokens;
64
+ t.cache_write += m.cacheCreationTokens;
65
+ t.cache_read += m.cacheReadTokens;
66
+ t.reasoning += m.reasoningTokens;
67
+ }
68
+ if (agent === "codex") {
69
+ t.input += t.cache_write;
70
+ t.cache_write = 0;
71
+ } // estimated split (splitrail #300)
72
+ return t;
73
+ };
74
+ export function version(cmd) {
75
+ try {
76
+ return run(`${cmd} --version`, process.env, tmpdir()).trim().split(/\r?\n/).pop() || "?";
77
+ }
78
+ catch (e) {
79
+ return `unavailable (${e.message.slice(0, 80)})`;
80
+ }
81
+ }
82
+ export function expectedInToolTerms(agent, exp) {
83
+ if (agent === "claude")
84
+ return { ...exp.dedup };
85
+ const e = { ...exp.token_count_dedup };
86
+ e.input -= e.cache_read; // uncached input
87
+ return e;
88
+ }
89
+ // Environment that points every tracker at a throwaway home holding only the logs placed there.
90
+ export function homeEnv(home) {
91
+ const env = { ...process.env, HOME: home, USERPROFILE: home,
92
+ CLAUDE_CONFIG_DIR: join(home, ".claude"), CODEX_HOME: join(home, ".codex") };
93
+ // keep npx's cache where it was (on Linux/macOS it lives under HOME)
94
+ if (process.platform !== "win32" && !env.npm_config_cache)
95
+ env.npm_config_cache = join(homedir(), ".npm");
96
+ return env;
97
+ }
98
+ // "match", or "diff <field> +n, ..." (tool minus expected).
99
+ export function delta(got, e) {
100
+ const diff = F.filter((k) => got[k] != null && got[k] !== e[k]);
101
+ // A tool that does not report reasoning (null/0 while expected > 0) is not a diff.
102
+ const real = diff.filter((k) => !(k === "reasoning" && !got[k]));
103
+ return real.length ? "diff " + real.map((k) => `${k} ${got[k] - e[k] > 0 ? "+" : ""}${got[k] - e[k]}`).join(", ")
104
+ : "match";
105
+ }
106
+ // Is a command on PATH? (no process spawned)
107
+ export function onPath(name) {
108
+ const exts = process.platform === "win32" ? [".cmd", ".exe", ".bat", ""] : [""];
109
+ for (const d of (process.env.PATH ?? "").split(process.platform === "win32" ? ";" : ":"))
110
+ for (const x of exts)
111
+ if (d && existsSync(join(d, name + x)))
112
+ return join(d, name + x);
113
+ return null;
114
+ }
115
+ // Trackers given by --ccusage/--tokscale/--splitrail, else found on PATH. Nothing is downloaded.
116
+ export function installedTrackers(args, only) {
117
+ const opt = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
118
+ const out = {};
119
+ const mk = { ccusage, tokscale };
120
+ for (const t of ["ccusage", "tokscale", "splitrail"]) {
121
+ if (only && t !== only)
122
+ continue;
123
+ const given = opt("--" + t), found = given ? null : onPath(t);
124
+ if (t === "splitrail") {
125
+ const bin = given ?? found;
126
+ if (bin)
127
+ out[t] = { fn: splitrail(bin), ver: version(`"${bin}"`) };
128
+ continue;
129
+ }
130
+ const cmd = given ?? (found ? `"${found}"` : null);
131
+ if (cmd)
132
+ out[t] = { fn: mk[t](cmd), ver: version(cmd) };
133
+ }
134
+ return out;
135
+ }
136
+ export function compare(args) {
137
+ const opt = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
138
+ const tools = {};
139
+ const cc = opt("--ccusage") ?? "npx -y ccusage@latest", ts = opt("--tokscale") ?? "npx -y tokscale@latest";
140
+ tools.ccusage = { fn: ccusage(cc), ver: version(cc) };
141
+ tools.tokscale = { fn: tokscale(ts), ver: version(ts) };
142
+ const sr = opt("--splitrail");
143
+ if (sr)
144
+ tools.splitrail = { fn: splitrail(sr), ver: version(`"${sr}"`) };
145
+ const fx = fixturesDir();
146
+ const score = {};
147
+ for (const t of Object.keys(tools))
148
+ score[t] = { ok: 0, n: 0 };
149
+ const tmp = mkdtempSync(join(tmpdir(), "usagebench_cmp_"));
150
+ try {
151
+ for (const agent of ["claude", "codex"]) {
152
+ const dir = join(fx, agent);
153
+ if (!existsSync(dir))
154
+ continue;
155
+ for (const f of readdirSync(dir).filter((n) => n.endsWith(".expected.json")).sort()) {
156
+ const exp = JSON.parse(readFileSync(join(dir, f), "utf8"));
157
+ const stem = f.replace(/\.expected\.json$/, "");
158
+ const home = join(tmp, stem, "home");
159
+ place(agent, join(dir, `${stem}.jsonl`), home);
160
+ const env = homeEnv(home);
161
+ const e = expectedInToolTerms(agent, exp);
162
+ for (const [tool, { fn }] of Object.entries(tools)) {
163
+ score[tool].n++;
164
+ let result;
165
+ try {
166
+ result = delta(fn(agent, env), e);
167
+ }
168
+ catch (x) {
169
+ result = `error: ${x.message}`;
170
+ }
171
+ if (result === "match")
172
+ score[tool].ok++;
173
+ console.log(`${result === "match" ? "PASS" : "FAIL"} ${agent}/${stem} ${tool}${result === "match" ? "" : ": " + result}`);
174
+ }
175
+ }
176
+ }
177
+ }
178
+ finally {
179
+ rmSync(tmp, { recursive: true, force: true });
180
+ }
181
+ console.log("\nscorecard (fixtures matching .expected.json)");
182
+ let bad = 0;
183
+ for (const [t, s] of Object.entries(score)) {
184
+ console.log(`${tools[t].ver.startsWith(t) ? tools[t].ver : t + " " + tools[t].ver}: ${s.ok}/${s.n}`);
185
+ if (s.ok !== s.n || s.n === 0)
186
+ bad++;
187
+ }
188
+ return bad ? 1 : 0;
189
+ }
package/dist/diff.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function diff(args: string[]): number;
package/dist/diff.js ADDED
@@ -0,0 +1,80 @@
1
+ // `usagebench diff [--days 7] [--ccusage <cmd>] [--tokscale <cmd>] [--splitrail <bin>]`
2
+ // Runs the installed trackers on a temporary copy of your own recent logs and compares their totals with usagebench's.
3
+ // Your log directories are only read; trackers see the copy (HOME, CLAUDE_CONFIG_DIR, CODEX_HOME point to it).
4
+ import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { dirname, join } from "node:path";
7
+ import { logFiles, parseLenient, readText, MAX_FILE_BYTES, LOG_AGENTS } from "./logs.js";
8
+ import { usage } from "./index.js";
9
+ import { delta, expectedInToolTerms, homeEnv, installedTrackers } from "./compare.js";
10
+ const F = ["input", "output", "cache_write", "cache_read", "reasoning"];
11
+ export function diff(args) {
12
+ const opt = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
13
+ const days = Number(opt("--days") ?? 7);
14
+ const since = days > 0 ? Date.now() - days * 86400_000 : 0;
15
+ const tools = installedTrackers(args);
16
+ if (!Object.keys(tools).length) {
17
+ console.log("no tracker found on PATH (ccusage, tokscale, splitrail); pass one with --ccusage <cmd>, --tokscale <cmd> or --splitrail <bin>");
18
+ return 2;
19
+ }
20
+ console.log(`usagebench diff: logs modified in the last ${days > 0 ? days + " days" : "any time"}, copied to a temp dir; `
21
+ + `trackers: ${Object.values(tools).map((t) => t.ver).join(", ")}`);
22
+ const tmp = mkdtempSync(join(tmpdir(), "usagebench_diff_"));
23
+ let bad = 0;
24
+ try {
25
+ for (const agent of LOG_AGENTS) {
26
+ const files = logFiles(agent).filter((f) => f.mtimeMs >= since && f.size <= MAX_FILE_BYTES);
27
+ if (!files.length)
28
+ continue;
29
+ const home = join(tmp, agent, "home");
30
+ const base = agent === "claude" ? join(home, ".claude", "projects") : join(home, ".codex", "sessions");
31
+ const last = new Map();
32
+ const ours = { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 };
33
+ let bytes = 0, used = 0;
34
+ for (const f of files) {
35
+ const text = readText(f);
36
+ if (text === null)
37
+ continue;
38
+ const dst = join(base, f.rel);
39
+ mkdirSync(dirname(dst), { recursive: true });
40
+ copyFileSync(f.path, dst);
41
+ bytes += f.size;
42
+ used++;
43
+ const { records } = parseLenient(agent, text);
44
+ if (agent === "claude")
45
+ for (const r of records)
46
+ last.set(JSON.stringify([r.session_id, r.message_id]), r);
47
+ else {
48
+ const t = usage("codex", records, { dedup: true, source: "token_count" });
49
+ for (const k of F)
50
+ ours[k] += t[k];
51
+ }
52
+ }
53
+ if (agent === "claude")
54
+ for (const r of last.values())
55
+ for (const k of F)
56
+ ours[k] += r.tokens[k] ?? 0;
57
+ const exp = expectedInToolTerms(agent, agent === "claude" ? { dedup: ours } : { token_count_dedup: ours });
58
+ console.log(`\n${agent === "claude" ? "Claude Code" : "Codex"}: ${used} files, ${(bytes / 1048576).toFixed(1)} MB`);
59
+ console.log(` usagebench: ${F.map((k) => `${k} ${exp[k]}`).join(", ")}`);
60
+ for (const [name, t] of Object.entries(tools)) {
61
+ let r;
62
+ try {
63
+ r = delta(t.fn(agent, homeEnv(home)), exp);
64
+ }
65
+ catch (x) {
66
+ r = `error: ${x.message.slice(0, 200)}`;
67
+ }
68
+ if (r !== "match")
69
+ bad++;
70
+ console.log(` ${name}: ${r}${r.startsWith("diff") ? " (tracker minus usagebench)" : ""}`);
71
+ if (r.startsWith("diff"))
72
+ console.log(` narrow it down: usagebench repro --latest --agent ${agent} --tracker ${name}`);
73
+ }
74
+ }
75
+ }
76
+ finally {
77
+ rmSync(tmp, { recursive: true, force: true });
78
+ }
79
+ return bad ? 1 : 0;
80
+ }
@@ -0,0 +1 @@
1
+ export declare function doctor(): number;
package/dist/doctor.js ADDED
@@ -0,0 +1,109 @@
1
+ // `usagebench doctor`: how much would a naive tracker overcount on this machine's own logs?
2
+ // Read-only, offline. Prints counts and ratios only: no log content, no paths below the log root.
3
+ import { homedir } from "node:os";
4
+ import { logFiles, logRoots, parseLenient, progress, readText } from "./logs.js";
5
+ import { usage } from "./index.js";
6
+ const F = ["input", "output", "cache_write", "cache_read", "reasoning"];
7
+ const zero = () => ({ input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 });
8
+ const add = (a, b) => { for (const k of F)
9
+ a[k] += b[k]; };
10
+ const ratio = (a, b) => (b ? `${(a / b).toFixed(2)}x` : "n/a");
11
+ const pct = (a, b) => (b ? `${((100 * a) / b).toFixed(1)}%` : "n/a");
12
+ const tilde = (p) => { const h = homedir().replaceAll("\\", "/"), q = p.replaceAll("\\", "/"); return q.startsWith(h) ? "~" + q.slice(h.length) : q; };
13
+ const fmt = (n) => n.toLocaleString("en-US");
14
+ function scanAgent(agent, files, tick) {
15
+ const s = { files: 0, skipped: 0, bad: 0, naive: zero(), dedup: zero(), extra: {} };
16
+ const claudeLast = new Map();
17
+ let usageLines = 0, repeated = 0, compactedSessions = 0, tcEvents = 0, tcReemit = 0, sessions = 0;
18
+ const tc = { naive: zero(), dedup: zero() };
19
+ for (const f of files) {
20
+ tick();
21
+ const text = readText(f);
22
+ if (text === null) {
23
+ s.skipped++;
24
+ continue;
25
+ }
26
+ s.files++;
27
+ const { records, bad } = parseLenient(agent, text);
28
+ s.bad += bad;
29
+ if (agent === "claude") {
30
+ for (const r of records) {
31
+ const k = JSON.stringify([r.session_id, r.message_id]);
32
+ usageLines++;
33
+ if (claudeLast.has(k))
34
+ repeated++;
35
+ claudeLast.set(k, r);
36
+ for (const x of F)
37
+ s.naive[x] += r.tokens[x] ?? 0;
38
+ }
39
+ }
40
+ else {
41
+ if (records.length || text.includes('"session_meta"'))
42
+ sessions++;
43
+ if (records.some((r) => r.raw_type.startsWith("compacted")))
44
+ compactedSessions++;
45
+ const t = records.filter((r) => r.raw_type === "event_msg/token_count");
46
+ tcEvents += t.length;
47
+ tcReemit += t.filter((r) => !r.total_changed).length;
48
+ add(s.naive, usage("codex", records, { dedup: false }));
49
+ add(s.dedup, usage("codex", records, { dedup: true }));
50
+ add(tc.naive, usage("codex", records, { dedup: false, source: "token_count" }));
51
+ add(tc.dedup, usage("codex", records, { dedup: true, source: "token_count" }));
52
+ }
53
+ }
54
+ if (agent === "claude") {
55
+ for (const r of claudeLast.values())
56
+ for (const x of F)
57
+ s.dedup[x] += r.tokens[x] ?? 0;
58
+ s.extra = { usageLines, repeated };
59
+ }
60
+ else {
61
+ s.extra = { sessions, compactedSessions, tcEvents, tcReemit };
62
+ s.tc = tc;
63
+ }
64
+ return s;
65
+ }
66
+ export function doctor() {
67
+ const out = ["usagebench doctor: read-only, offline; counts and ratios only"];
68
+ const all = { claude: logFiles("claude"), codex: logFiles("codex") };
69
+ const total = all.claude.length + all.codex.length;
70
+ const prog = progress(total);
71
+ let n = 0;
72
+ const verdict = [];
73
+ for (const agent of ["claude", "codex"]) {
74
+ const roots = logRoots(agent);
75
+ const label = agent === "claude" ? "Claude Code" : "Codex";
76
+ if (!roots.length) {
77
+ out.push(`\n${label}: no log directory found`);
78
+ continue;
79
+ }
80
+ const s = scanAgent(agent, all[agent], () => prog.tick(++n));
81
+ out.push(`\n${label}: ${roots.map(tilde).join(", ")}`);
82
+ out.push(` files scanned: ${fmt(s.files)}` + (s.skipped ? `, skipped (unreadable or > size cap): ${s.skipped}` : "")
83
+ + (s.bad ? `, invalid JSON lines ignored: ${fmt(s.bad)}` : ""));
84
+ if (agent === "claude") {
85
+ const { usageLines, repeated } = s.extra;
86
+ out.push(` usage lines: ${fmt(usageLines)}; repeating an earlier (sessionId, message.id): ${fmt(repeated)} (${pct(repeated, usageLines)})`);
87
+ out.push(` naive vs dedup: output ${fmt(s.naive.output)} vs ${fmt(s.dedup.output)} (${ratio(s.naive.output, s.dedup.output)}), `
88
+ + `cache_read ${fmt(s.naive.cache_read)} vs ${fmt(s.dedup.cache_read)} (${ratio(s.naive.cache_read, s.dedup.cache_read)})`);
89
+ if (s.dedup.output)
90
+ verdict.push(`Claude Code output by ${ratio(s.naive.output, s.dedup.output)}`);
91
+ }
92
+ else {
93
+ const { sessions, compactedSessions, tcEvents, tcReemit } = s.extra;
94
+ out.push(` sessions: ${fmt(sessions)}; with compacted records: ${fmt(compactedSessions)}`);
95
+ out.push(` token_count events: ${fmt(tcEvents)}; re-emitted with unchanged total: ${fmt(tcReemit)} (${pct(tcReemit, tcEvents)})`);
96
+ out.push(` token_count naive vs dedup: output ${fmt(s.tc.naive.output)} vs ${fmt(s.tc.dedup.output)} (${ratio(s.tc.naive.output, s.tc.dedup.output)}), `
97
+ + `input ${fmt(s.tc.naive.input)} vs ${fmt(s.tc.dedup.input)} (${ratio(s.tc.naive.input, s.tc.dedup.input)})`);
98
+ if (s.dedup.output || s.naive.output)
99
+ out.push(` token_usage_record naive vs dedup: output ${fmt(s.naive.output)} vs ${fmt(s.dedup.output)} (${ratio(s.naive.output, s.dedup.output)})`);
100
+ if (s.tc.dedup.output)
101
+ verdict.push(`Codex output by ${ratio(s.tc.naive.output, s.tc.dedup.output)}`);
102
+ }
103
+ }
104
+ prog.done();
105
+ out.push("", verdict.length ? `A tracker that sums every usage line would overstate ${verdict.join(" and ")}.`
106
+ : "No usage lines found.");
107
+ console.log(out.join("\n"));
108
+ return 0;
109
+ }
@@ -0,0 +1,45 @@
1
+ export type Agent = "claude" | "codex" | "agy";
2
+ export type NormalizedAgent = "claude_code" | "codex" | "gemini_antigravity";
3
+ export interface Tokens {
4
+ input: number | null;
5
+ output: number | null;
6
+ cache_write: number | null;
7
+ cache_read: number | null;
8
+ reasoning: number | null;
9
+ }
10
+ export interface UsageRecord {
11
+ schema: "usagebench/0";
12
+ agent: NormalizedAgent;
13
+ agent_version: string | null;
14
+ session_id: string | null;
15
+ message_id: string | null;
16
+ parent_id: string | null;
17
+ parent_session_id: string | null;
18
+ is_sidechain: boolean;
19
+ timestamp: string | null;
20
+ model: string | null;
21
+ tokens: Tokens;
22
+ source_file: string;
23
+ source_line: number;
24
+ raw_type: string;
25
+ total_changed?: boolean;
26
+ }
27
+ export interface Totals {
28
+ input: number;
29
+ output: number;
30
+ cache_write: number;
31
+ cache_read: number;
32
+ reasoning: number;
33
+ }
34
+ export interface ParseOptions {
35
+ sourceFile?: string;
36
+ sessionId?: string;
37
+ }
38
+ export interface UsageOptions {
39
+ dedup?: boolean;
40
+ source?: "record" | "token_count";
41
+ }
42
+ export declare function agentName(name: string): Agent;
43
+ export declare function parse(agentIn: string, jsonlText: string, opts?: ParseOptions): UsageRecord[];
44
+ export declare function usage(agentIn: string, records: UsageRecord[], opts?: UsageOptions): Totals;
45
+ export declare function report(agentIn: string, jsonlText: string, opts?: ParseOptions): Record<string, unknown>;