usagebench 0.0.0-stage → 0.2.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +251 -2
  3. package/dist/anon.d.ts +11 -0
  4. package/dist/anon.js +108 -0
  5. package/dist/audit.d.ts +1 -0
  6. package/dist/audit.js +173 -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 +95 -0
  11. package/dist/compare.d.ts +16 -0
  12. package/dist/compare.js +200 -0
  13. package/dist/diff.d.ts +1 -0
  14. package/dist/diff.js +86 -0
  15. package/dist/doctor.d.ts +1 -0
  16. package/dist/doctor.js +138 -0
  17. package/dist/index.d.ts +47 -0
  18. package/dist/index.js +181 -0
  19. package/dist/logs.d.ts +22 -0
  20. package/dist/logs.js +122 -0
  21. package/dist/repro.d.ts +1 -0
  22. package/dist/repro.js +154 -0
  23. package/dist/secrets.d.ts +11 -0
  24. package/dist/secrets.js +100 -0
  25. package/fixtures/claude/2.1.321_compaction-zeroed-usage.continued.expected.json +21 -0
  26. package/fixtures/claude/2.1.321_compaction-zeroed-usage.continued.jsonl +3 -0
  27. package/fixtures/claude/2.1.321_compaction-zeroed-usage.original.expected.json +21 -0
  28. package/fixtures/claude/2.1.321_compaction-zeroed-usage.original.jsonl +2 -0
  29. package/fixtures/claude/2.1.334_main.expected.json +21 -0
  30. package/fixtures/claude/2.1.334_main.jsonl +162 -0
  31. package/fixtures/claude/2.1.335_sidechain.expected.json +21 -0
  32. package/fixtures/claude/2.1.335_sidechain.jsonl +60 -0
  33. package/fixtures/claude/2.1.335_stream-abort-tool-error.expected.json +21 -0
  34. package/fixtures/claude/2.1.335_stream-abort-tool-error.jsonl +200 -0
  35. package/fixtures/claude/synthetic_duplicate-id-partial-usage.expected.json +22 -0
  36. package/fixtures/claude/synthetic_duplicate-id-partial-usage.jsonl +6 -0
  37. package/fixtures/codex/0.160.0_compacted.expected.json +38 -0
  38. package/fixtures/codex/0.160.0_compacted.jsonl +200 -0
  39. package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.expected.json +38 -0
  40. package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.jsonl +154 -0
  41. package/fixtures/codex/0.173.0-alpha.4.1_basic.expected.json +38 -0
  42. package/fixtures/codex/0.173.0-alpha.4.1_basic.jsonl +200 -0
  43. package/fixtures/codex/synthetic_total-reset.expected.json +39 -0
  44. package/fixtures/codex/synthetic_total-reset.jsonl +12 -0
  45. package/package.json +48 -4
@@ -0,0 +1,126 @@
1
+ // BIP39 English wordlist (2048 words), from bitcoin/bips bip-0039/english.txt
2
+ // (sha256 of the original file: 2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda).
3
+ export const BIP39_ENGLISH = `
4
+ abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve
5
+ acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult
6
+ advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album
7
+ alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount
8
+ amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique
9
+ anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around
10
+ arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete
11
+ atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake
12
+ aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner
13
+ bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave
14
+ behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird
15
+ birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat
16
+ body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass
17
+ brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush
18
+ bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter
19
+ buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe
20
+ canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual
21
+ cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal
22
+ certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest
23
+ chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil
24
+ claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth
25
+ cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine
26
+ come comfort comic common company concert conduct confirm congress connect consider control convince cook cool
27
+ copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle
28
+ craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch
29
+ crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain
30
+ curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris
31
+ decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise
32
+ denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy
33
+ detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma
34
+ dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide
35
+ divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon
36
+ drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch
37
+ duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort
38
+ egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace
39
+ emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine
40
+ enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase
41
+ erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example
42
+ excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect
43
+ expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame
44
+ family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal
45
+ fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find
46
+ fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip
47
+ float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork
48
+ fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost
49
+ frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage
50
+ garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant
51
+ gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue
52
+ goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity
53
+ great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half
54
+ hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog
55
+ height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow
56
+ home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred
57
+ hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image
58
+ imitate immense immune impact impose improve impulse inch include income increase index indicate indoor
59
+ industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane
60
+ insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory
61
+ jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk
62
+ just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife
63
+ knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn
64
+ lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens
65
+ leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list
66
+ little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky
67
+ luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage
68
+ mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material
69
+ math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory
70
+ mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum
71
+ minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor
72
+ monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much
73
+ muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow
74
+ nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news
75
+ next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear
76
+ number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer
77
+ office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option
78
+ orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside
79
+ oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper
80
+ parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear
81
+ peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano
82
+ picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate
83
+ play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position
84
+ possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty
85
+ prevent price pride primary print priority prison private prize problem process produce profit program project
86
+ promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy
87
+ purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote
88
+ rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather
89
+ raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform
90
+ refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent
91
+ reopen repair repeat replace report require rescue resemble resist resource response result retire retreat
92
+ return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple
93
+ risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route
94
+ royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same
95
+ sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science
96
+ scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed
97
+ seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft
98
+ shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove
99
+ shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing
100
+ siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide
101
+ slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer
102
+ social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source
103
+ south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split
104
+ spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage
105
+ stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool
106
+ story stove strategy street strike strong struggle student stuff stumble style subject submit subway success
107
+ such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise
108
+ surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol
109
+ symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell
110
+ ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive
111
+ throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler
112
+ toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado
113
+ tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel
114
+ tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth
115
+ try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly
116
+ umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown
117
+ unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless
118
+ usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor
119
+ venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village
120
+ vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage
121
+ wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel
122
+ weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width
123
+ wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood
124
+ wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra
125
+ zero zone zoo
126
+ `.trim().split(/\s+/);
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { basename } from "node:path";
4
+ import { report, usage, zeroedTop } 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 --version | -v package version
17
+ usagebench doctor how much a naive tracker would overcount on your logs
18
+ usagebench audit [--fix [--yes]] plaintext secrets in your logs (masked; --fix redacts, dry run without --yes)
19
+ usagebench repro [--latest|--session <id>] [--agent claude|codex] [--tracker <name>] [--out <dir>] [--max-kb 50]
20
+ anonymized minimal repro + expected.json + issue.md
21
+ usagebench diff [--days 7] installed trackers vs usagebench on a temp copy of your recent logs
22
+ usagebench compare [--ccusage <cmd>] [--tokscale <cmd>] [--splitrail <bin>]
23
+ trackers vs the bundled fixtures (scorecard)
24
+ usagebench <claude|codex> [file.jsonl] naive and deduplicated totals (all local logs when no file is given)
25
+ usagebench agy <transcript.jsonl> same for an antigravity-cli transcript
26
+
27
+ compare, diff and repro --tracker run the trackers you have (ccusage, tokscale, splitrail); they may go online.`;
28
+ const [cmd, ...rest] = process.argv.slice(2);
29
+ const commands = { compare, doctor: () => doctor(), audit, repro, diff };
30
+ // `--version` / `-v` anywhere: the package version (package.json sits one level above both src/ and dist/).
31
+ if ([cmd, ...rest].some((a) => a === "--version" || a === "-v")) {
32
+ console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
33
+ process.exit(0);
34
+ }
35
+ if (!cmd || cmd === "--help" || cmd === "-h" || cmd === "help") {
36
+ console.log(HELP);
37
+ process.exit(cmd ? 0 : 2);
38
+ }
39
+ // `<cmd> --help` / `-h` prints help before any command code runs (no log scan, no file access).
40
+ if (rest.includes("--help") || rest.includes("-h")) {
41
+ console.log(HELP);
42
+ process.exit(0);
43
+ }
44
+ if (commands[cmd])
45
+ process.exit(commands[cmd](rest));
46
+ const file = rest[0];
47
+ try {
48
+ if (file) {
49
+ console.log(JSON.stringify(report(cmd, readFileSync(file, "utf8"), { sourceFile: basename(file) }), null, 1));
50
+ }
51
+ else if (cmd === "claude" || cmd === "codex") {
52
+ // All local logs of this agent; per file for Codex, (sessionId, message.id) across files for Claude.
53
+ // Claude: running naive sum + last non-zeroed tokens per key (same result as usage(), without keeping every record)
54
+ const agent = cmd, last = new Map();
55
+ const cNaive = { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 };
56
+ const sum = (ts) => ts.reduce((a, t) => { for (const k of Object.keys(a))
57
+ a[k] += t[k]; return a; }, { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 });
58
+ const naive = [], dedup = [], tcn = [], tcd = [];
59
+ let files = 0;
60
+ for (const f of logFiles(agent)) {
61
+ const text = readText(f);
62
+ if (text === null)
63
+ continue;
64
+ files++;
65
+ const { records } = parseLenient(agent, text);
66
+ if (agent === "claude")
67
+ for (const r of records) {
68
+ for (const k of Object.keys(cNaive))
69
+ cNaive[k] += r.tokens[k] ?? 0;
70
+ if (!zeroedTop(r.tokens))
71
+ last.set(JSON.stringify([r.session_id, r.message_id]), { ...r.tokens });
72
+ }
73
+ else {
74
+ naive.push(usage(agent, records, { dedup: false }));
75
+ dedup.push(usage(agent, records));
76
+ tcn.push(usage(agent, records, { dedup: false, source: "token_count" }));
77
+ tcd.push(usage(agent, records, { source: "token_count" }));
78
+ }
79
+ }
80
+ const res = { agent, files };
81
+ if (agent === "claude")
82
+ Object.assign(res, { naive: cNaive, dedup: sum([...last.values()]) });
83
+ else
84
+ Object.assign(res, { naive: sum(naive), dedup: sum(dedup), token_count_naive: sum(tcn), token_count_dedup: sum(tcd) });
85
+ console.log(JSON.stringify(res, null, 1));
86
+ }
87
+ else {
88
+ console.error(cmd === "agy" ? "usagebench agy needs a transcript file" : `unknown command "${cmd}"\n\n${HELP}`);
89
+ process.exit(2);
90
+ }
91
+ }
92
+ catch (e) {
93
+ console.error(String(e.message ?? e));
94
+ process.exit(1);
95
+ }
@@ -0,0 +1,16 @@
1
+ export type Totals = Record<string, number | null | undefined>;
2
+ export declare function place(agent: string, fixture: string, home: string, n?: number): 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 | null | undefined, 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,200 @@
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, n = 0) {
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}${n ? "-" + n : ""}.jsonl`);
37
+ }
38
+ else {
39
+ dst = join(home, ".codex", "sessions", "2026", "01", "01", `rollout-2026-01-01T00-00-00-0199a000-0000-7000-8000-00000000000${n + 1}.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
+ XDG_CONFIG_HOME: join(home, ".config"), XDG_CACHE_HOME: join(home, ".cache"), XDG_DATA_HOME: join(home, ".local", "share") };
94
+ // keep npx's cache where it was (on Linux/macOS it lives under HOME)
95
+ if (process.platform !== "win32" && !env.npm_config_cache)
96
+ env.npm_config_cache = join(homedir(), ".npm");
97
+ return env;
98
+ }
99
+ // "match", or "diff <field> +n, ..." (tool minus expected).
100
+ export function delta(got, e) {
101
+ // empty/undefined totals (tracker printed nothing usable) are a mismatch, never a crash or a silent match
102
+ if (!got || typeof got !== "object" || F.every((k) => k === "reasoning" || got[k] == null))
103
+ return "diff: no totals reported";
104
+ const diff = F.filter((k) => got[k] != null && got[k] !== e[k]);
105
+ // A tool that does not report reasoning (null/0 while expected > 0) is not a diff.
106
+ const real = diff.filter((k) => !(k === "reasoning" && !got[k]));
107
+ return real.length ? "diff " + real.map((k) => `${k} ${got[k] - e[k] > 0 ? "+" : ""}${got[k] - e[k]}`).join(", ")
108
+ : "match";
109
+ }
110
+ // Is a command on PATH? (no process spawned)
111
+ export function onPath(name) {
112
+ const exts = process.platform === "win32" ? [".cmd", ".exe", ".bat", ""] : [""];
113
+ for (const d of (process.env.PATH ?? "").split(process.platform === "win32" ? ";" : ":"))
114
+ for (const x of exts)
115
+ if (d && existsSync(join(d, name + x)))
116
+ return join(d, name + x);
117
+ return null;
118
+ }
119
+ // Trackers given by --ccusage/--tokscale/--splitrail, else found on PATH. Nothing is downloaded.
120
+ export function installedTrackers(args, only) {
121
+ const opt = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
122
+ const out = {};
123
+ const mk = { ccusage, tokscale };
124
+ for (const t of ["ccusage", "tokscale", "splitrail"]) {
125
+ if (only && t !== only)
126
+ continue;
127
+ const given = opt("--" + t), found = given ? null : onPath(t);
128
+ if (t === "splitrail") {
129
+ const bin = given ?? found;
130
+ if (bin)
131
+ out[t] = { fn: splitrail(bin), ver: version(`"${bin}"`) };
132
+ continue;
133
+ }
134
+ const cmd = given ?? (found ? `"${found}"` : null);
135
+ if (cmd)
136
+ out[t] = { fn: mk[t](cmd), ver: version(cmd) };
137
+ }
138
+ return out;
139
+ }
140
+ export function compare(args) {
141
+ const opt = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
142
+ const tools = {};
143
+ const cc = opt("--ccusage") ?? "npx -y ccusage@latest", ts = opt("--tokscale") ?? "npx -y tokscale@latest";
144
+ tools.ccusage = { fn: ccusage(cc), ver: version(cc) };
145
+ tools.tokscale = { fn: tokscale(ts), ver: version(ts) };
146
+ const sr = opt("--splitrail");
147
+ if (sr)
148
+ tools.splitrail = { fn: splitrail(sr), ver: version(`"${sr}"`) };
149
+ const fx = fixturesDir();
150
+ const score = {};
151
+ for (const t of Object.keys(tools))
152
+ score[t] = { ok: 0, n: 0 };
153
+ const tmp = mkdtempSync(join(tmpdir(), "usagebench_cmp_"));
154
+ try {
155
+ for (const agent of ["claude", "codex"]) {
156
+ const dir = join(fx, agent);
157
+ if (!existsSync(dir))
158
+ continue;
159
+ // `<case>.original.*` + `<case>.continued.*` are one case: both logs go into one home, expected = their sum
160
+ const cases = new Map();
161
+ for (const f of readdirSync(dir).filter((n) => n.endsWith(".expected.json")).sort()) {
162
+ const stem = f.replace(/\.expected\.json$/, ""), key = stem.replace(/\.(original|continued)$/, "");
163
+ cases.set(key, [...(cases.get(key) ?? []), stem]);
164
+ }
165
+ for (const [stem, members] of cases) {
166
+ const home = join(tmp, stem, "home");
167
+ const exps = members.map((m, i) => {
168
+ place(agent, join(dir, `${m}.jsonl`), home, i);
169
+ return expectedInToolTerms(agent, JSON.parse(readFileSync(join(dir, `${m}.expected.json`), "utf8")));
170
+ });
171
+ const env = homeEnv(home);
172
+ const e = Object.fromEntries(F.map((k) => [k, exps.reduce((s, x) => s + (x[k] ?? 0), 0)]));
173
+ for (const [tool, { fn }] of Object.entries(tools)) {
174
+ score[tool].n++;
175
+ let result;
176
+ try {
177
+ result = delta(fn(agent, env), e);
178
+ }
179
+ catch (x) {
180
+ result = `error: ${x.message}`;
181
+ }
182
+ if (result === "match")
183
+ score[tool].ok++;
184
+ console.log(`${result === "match" ? "PASS" : "FAIL"} ${agent}/${stem} ${tool}${result === "match" ? "" : ": " + result}`);
185
+ }
186
+ }
187
+ }
188
+ }
189
+ finally {
190
+ rmSync(tmp, { recursive: true, force: true });
191
+ }
192
+ console.log("\nscorecard (fixtures matching .expected.json)");
193
+ let bad = 0;
194
+ for (const [t, s] of Object.entries(score)) {
195
+ console.log(`${tools[t].ver.startsWith(t) ? tools[t].ver : t + " " + tools[t].ver}: ${s.ok}/${s.n}`);
196
+ if (s.ok !== s.n || s.n === 0)
197
+ bad++;
198
+ }
199
+ return bad ? 1 : 0;
200
+ }
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,86 @@
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, zeroedTop } 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
+ if (!Number.isFinite(days) || days < 0) {
15
+ console.error("--days must be a number >= 0 (0 = any time)");
16
+ return 2;
17
+ }
18
+ const since = days > 0 ? Date.now() - days * 86400_000 : 0;
19
+ const tools = installedTrackers(args);
20
+ if (!Object.keys(tools).length) {
21
+ console.log("no tracker found on PATH (ccusage, tokscale, splitrail); pass one with --ccusage <cmd>, --tokscale <cmd> or --splitrail <bin>");
22
+ return 2;
23
+ }
24
+ console.log(`usagebench diff: logs modified in the last ${days > 0 ? days + " days" : "any time"}, copied to a temp dir; `
25
+ + `trackers: ${Object.values(tools).map((t) => t.ver).join(", ")}`);
26
+ const tmp = mkdtempSync(join(tmpdir(), "usagebench_diff_"));
27
+ let bad = 0;
28
+ try {
29
+ for (const agent of LOG_AGENTS) {
30
+ const files = logFiles(agent).filter((f) => f.mtimeMs >= since && f.size <= MAX_FILE_BYTES);
31
+ if (!files.length)
32
+ continue;
33
+ const home = join(tmp, agent, "home");
34
+ const base = agent === "claude" ? join(home, ".claude", "projects") : join(home, ".codex", "sessions");
35
+ const last = new Map();
36
+ const ours = { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 };
37
+ let bytes = 0, used = 0;
38
+ for (const f of files) {
39
+ const text = readText(f);
40
+ if (text === null)
41
+ continue;
42
+ const dst = join(base, f.rel);
43
+ mkdirSync(dirname(dst), { recursive: true });
44
+ copyFileSync(f.path, dst);
45
+ bytes += f.size;
46
+ used++;
47
+ const { records } = parseLenient(agent, text);
48
+ if (agent === "claude") {
49
+ for (const r of records)
50
+ if (!zeroedTop(r.tokens))
51
+ last.set(JSON.stringify([r.session_id, r.message_id]), r);
52
+ }
53
+ else {
54
+ const t = usage("codex", records, { dedup: true, source: "token_count" });
55
+ for (const k of F)
56
+ ours[k] += t[k];
57
+ }
58
+ }
59
+ if (agent === "claude")
60
+ for (const r of last.values())
61
+ for (const k of F)
62
+ ours[k] += r.tokens[k] ?? 0;
63
+ const exp = expectedInToolTerms(agent, agent === "claude" ? { dedup: ours } : { token_count_dedup: ours });
64
+ console.log(`\n${agent === "claude" ? "Claude Code" : "Codex"}: ${used} files, ${(bytes / 1048576).toFixed(1)} MB`);
65
+ console.log(` usagebench: ${F.map((k) => `${k} ${exp[k]}`).join(", ")}`);
66
+ for (const [name, t] of Object.entries(tools)) {
67
+ let r;
68
+ try {
69
+ r = delta(t.fn(agent, homeEnv(home)), exp);
70
+ }
71
+ catch (x) {
72
+ r = `error: ${x.message.slice(0, 200)}`;
73
+ }
74
+ if (r !== "match")
75
+ bad++;
76
+ console.log(` ${name}: ${r}${r.startsWith("diff") ? " (tracker minus usagebench)" : ""}`);
77
+ if (r.startsWith("diff"))
78
+ console.log(` narrow it down: usagebench repro --latest --agent ${agent} --tracker ${name}`);
79
+ }
80
+ }
81
+ }
82
+ finally {
83
+ rmSync(tmp, { recursive: true, force: true });
84
+ }
85
+ return bad ? 1 : 0;
86
+ }
@@ -0,0 +1 @@
1
+ export declare function doctor(): number;