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.
- package/LICENSE +21 -0
- package/README.md +251 -2
- package/dist/anon.d.ts +11 -0
- package/dist/anon.js +108 -0
- package/dist/audit.d.ts +1 -0
- package/dist/audit.js +173 -0
- package/dist/bip39_english.d.ts +1 -0
- package/dist/bip39_english.js +126 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +95 -0
- package/dist/compare.d.ts +16 -0
- package/dist/compare.js +200 -0
- package/dist/diff.d.ts +1 -0
- package/dist/diff.js +86 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +138 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.js +181 -0
- package/dist/logs.d.ts +22 -0
- package/dist/logs.js +122 -0
- package/dist/repro.d.ts +1 -0
- package/dist/repro.js +154 -0
- package/dist/secrets.d.ts +11 -0
- package/dist/secrets.js +100 -0
- package/fixtures/claude/2.1.321_compaction-zeroed-usage.continued.expected.json +21 -0
- package/fixtures/claude/2.1.321_compaction-zeroed-usage.continued.jsonl +3 -0
- package/fixtures/claude/2.1.321_compaction-zeroed-usage.original.expected.json +21 -0
- package/fixtures/claude/2.1.321_compaction-zeroed-usage.original.jsonl +2 -0
- package/fixtures/claude/2.1.334_main.expected.json +21 -0
- package/fixtures/claude/2.1.334_main.jsonl +162 -0
- package/fixtures/claude/2.1.335_sidechain.expected.json +21 -0
- package/fixtures/claude/2.1.335_sidechain.jsonl +60 -0
- package/fixtures/claude/2.1.335_stream-abort-tool-error.expected.json +21 -0
- package/fixtures/claude/2.1.335_stream-abort-tool-error.jsonl +200 -0
- package/fixtures/claude/synthetic_duplicate-id-partial-usage.expected.json +22 -0
- package/fixtures/claude/synthetic_duplicate-id-partial-usage.jsonl +6 -0
- package/fixtures/codex/0.160.0_compacted.expected.json +38 -0
- package/fixtures/codex/0.160.0_compacted.jsonl +200 -0
- package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.expected.json +38 -0
- package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.jsonl +154 -0
- package/fixtures/codex/0.173.0-alpha.4.1_basic.expected.json +38 -0
- package/fixtures/codex/0.173.0-alpha.4.1_basic.jsonl +200 -0
- package/fixtures/codex/synthetic_total-reset.expected.json +39 -0
- package/fixtures/codex/synthetic_total-reset.jsonl +12 -0
- package/package.json +48 -4
package/dist/doctor.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
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 { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { logFiles, logRoots, parseLenient, progress, readText } from "./logs.js";
|
|
7
|
+
import { usage, zeroedTop } from "./index.js";
|
|
8
|
+
const F = ["input", "output", "cache_write", "cache_read", "reasoning"];
|
|
9
|
+
const zero = () => ({ input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 });
|
|
10
|
+
const add = (a, b) => { for (const k of F)
|
|
11
|
+
a[k] += b[k]; };
|
|
12
|
+
const ratio = (a, b) => (b ? `${(a / b).toFixed(2)}x` : "n/a");
|
|
13
|
+
const pct = (a, b) => (b ? `${((100 * a) / b).toFixed(1)}%` : "n/a");
|
|
14
|
+
const tilde = (p) => { const h = homedir().replaceAll("\\", "/"), q = p.replaceAll("\\", "/"); return q.startsWith(h) ? "~" + q.slice(h.length) : q; };
|
|
15
|
+
const fmt = (n) => n.toLocaleString("en-US");
|
|
16
|
+
function scanAgent(agent, files, tick) {
|
|
17
|
+
const s = { files: 0, skipped: 0, bad: 0, naive: zero(), dedup: zero(), extra: {} };
|
|
18
|
+
const claudeLast = new Map();
|
|
19
|
+
let usageLines = 0, repeated = 0, zeroedCopies = 0, compactedSessions = 0, tcEvents = 0, tcReemit = 0, sessions = 0;
|
|
20
|
+
const tc = { naive: zero(), dedup: zero() };
|
|
21
|
+
for (const f of files) {
|
|
22
|
+
tick();
|
|
23
|
+
const text = readText(f);
|
|
24
|
+
if (text === null) {
|
|
25
|
+
s.skipped++;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
s.files++;
|
|
29
|
+
const { records, bad } = parseLenient(agent, text);
|
|
30
|
+
s.bad += bad;
|
|
31
|
+
if (agent === "claude") {
|
|
32
|
+
for (const r of records) {
|
|
33
|
+
const k = JSON.stringify([r.session_id, r.message_id]);
|
|
34
|
+
usageLines++;
|
|
35
|
+
if (claudeLast.has(k))
|
|
36
|
+
repeated++;
|
|
37
|
+
if (r.zeroed_copy)
|
|
38
|
+
zeroedCopies++;
|
|
39
|
+
if (!zeroedTop(r.tokens))
|
|
40
|
+
claudeLast.set(k, r);
|
|
41
|
+
for (const x of F)
|
|
42
|
+
s.naive[x] += r.tokens[x] ?? 0;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
if (records.length || text.includes('"session_meta"'))
|
|
47
|
+
sessions++;
|
|
48
|
+
if (records.some((r) => r.raw_type.startsWith("compacted")))
|
|
49
|
+
compactedSessions++;
|
|
50
|
+
const t = records.filter((r) => r.raw_type === "event_msg/token_count");
|
|
51
|
+
tcEvents += t.length;
|
|
52
|
+
tcReemit += t.filter((r) => !r.total_changed).length;
|
|
53
|
+
add(s.naive, usage("codex", records, { dedup: false }));
|
|
54
|
+
add(s.dedup, usage("codex", records, { dedup: true }));
|
|
55
|
+
add(tc.naive, usage("codex", records, { dedup: false, source: "token_count" }));
|
|
56
|
+
add(tc.dedup, usage("codex", records, { dedup: true, source: "token_count" }));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (agent === "claude") {
|
|
60
|
+
for (const r of claudeLast.values())
|
|
61
|
+
for (const x of F)
|
|
62
|
+
s.dedup[x] += r.tokens[x] ?? 0;
|
|
63
|
+
s.extra = { usageLines, repeated, zeroedCopies };
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
s.extra = { sessions, compactedSessions, tcEvents, tcReemit };
|
|
67
|
+
s.tc = tc;
|
|
68
|
+
}
|
|
69
|
+
return s;
|
|
70
|
+
}
|
|
71
|
+
// Claude Code deletes transcripts older than cleanupPeriodDays (default 30, by file mtime, silently) and rejects 0
|
|
72
|
+
// (code.claude.com/docs/en/settings-reference#cleanupperioddays). settings.json is only read.
|
|
73
|
+
function retention(files) {
|
|
74
|
+
const dirs = process.env.CLAUDE_CONFIG_DIR?.split(",").map((d) => d.trim()).filter(Boolean);
|
|
75
|
+
const vals = (dirs?.length ? dirs : [join(homedir(), ".claude")]).map((d) => join(d, "settings.json")).filter((p) => existsSync(p))
|
|
76
|
+
.map((p) => { try {
|
|
77
|
+
return JSON.parse(readFileSync(p, "utf8"))?.cleanupPeriodDays;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return undefined;
|
|
81
|
+
} });
|
|
82
|
+
if (vals.includes(0))
|
|
83
|
+
return [" WARNING: settings.json sets cleanupPeriodDays to 0. Current Claude Code rejects 0 (minimum 1); "
|
|
84
|
+
+ "older versions stopped writing transcripts at all with it (anthropics/claude-code#23710)."];
|
|
85
|
+
if (vals.some((v) => v !== undefined))
|
|
86
|
+
return [];
|
|
87
|
+
const old = files.filter((f) => Date.now() - f.mtimeMs >= 25 * 86400_000).length;
|
|
88
|
+
return old ? [` NOTE: cleanupPeriodDays is not set (default 30): ${fmt(old)} transcript file(s) last modified 25+ days ago; `
|
|
89
|
+
+ "Claude Code deletes them without a message once they pass 30 days (anthropics/claude-code#62250). "
|
|
90
|
+
+ "Set a larger cleanupPeriodDays in settings.json to keep them."] : [];
|
|
91
|
+
}
|
|
92
|
+
export function doctor() {
|
|
93
|
+
const out = ["usagebench doctor: read-only, offline; counts and ratios only"];
|
|
94
|
+
const all = { claude: logFiles("claude"), codex: logFiles("codex") };
|
|
95
|
+
const total = all.claude.length + all.codex.length;
|
|
96
|
+
const prog = progress(total);
|
|
97
|
+
let n = 0;
|
|
98
|
+
const verdict = [];
|
|
99
|
+
for (const agent of ["claude", "codex"]) {
|
|
100
|
+
const roots = logRoots(agent);
|
|
101
|
+
const label = agent === "claude" ? "Claude Code" : "Codex";
|
|
102
|
+
if (!roots.length) {
|
|
103
|
+
out.push(`\n${label}: no log directory found`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const s = scanAgent(agent, all[agent], () => prog.tick(++n));
|
|
107
|
+
out.push(`\n${label}: ${roots.map(tilde).join(", ")}`);
|
|
108
|
+
out.push(` files scanned: ${fmt(s.files)}` + (s.skipped ? `, skipped (unreadable or > size cap): ${s.skipped}` : "")
|
|
109
|
+
+ (s.bad ? `, invalid JSON lines ignored: ${fmt(s.bad)}` : ""));
|
|
110
|
+
if (agent === "claude") {
|
|
111
|
+
const { usageLines, repeated } = s.extra;
|
|
112
|
+
out.push(` usage lines: ${fmt(usageLines)}; repeating an earlier (sessionId, message.id): ${fmt(repeated)} (${pct(repeated, usageLines)})`);
|
|
113
|
+
out.push(` naive vs dedup: output ${fmt(s.naive.output)} vs ${fmt(s.dedup.output)} (${ratio(s.naive.output, s.dedup.output)}), `
|
|
114
|
+
+ `cache_read ${fmt(s.naive.cache_read)} vs ${fmt(s.dedup.cache_read)} (${ratio(s.naive.cache_read, s.dedup.cache_read)})`);
|
|
115
|
+
out.push(` rows with all 4 top-level usage counters 0 but usage.cache_creation or usage.iterations[0] non-zero: `
|
|
116
|
+
+ `${fmt(s.extra.zeroedCopies)} (see anthropics/claude-code#95555)`);
|
|
117
|
+
out.push(...retention(all.claude));
|
|
118
|
+
if (s.dedup.output)
|
|
119
|
+
verdict.push(`Claude Code output by ${ratio(s.naive.output, s.dedup.output)}`);
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
const { sessions, compactedSessions, tcEvents, tcReemit } = s.extra;
|
|
123
|
+
out.push(` sessions: ${fmt(sessions)}; with compacted records: ${fmt(compactedSessions)}`);
|
|
124
|
+
out.push(` token_count events: ${fmt(tcEvents)}; re-emitted with unchanged total: ${fmt(tcReemit)} (${pct(tcReemit, tcEvents)})`);
|
|
125
|
+
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)}), `
|
|
126
|
+
+ `input ${fmt(s.tc.naive.input)} vs ${fmt(s.tc.dedup.input)} (${ratio(s.tc.naive.input, s.tc.dedup.input)})`);
|
|
127
|
+
if (s.dedup.output || s.naive.output)
|
|
128
|
+
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)})`);
|
|
129
|
+
if (s.tc.dedup.output)
|
|
130
|
+
verdict.push(`Codex output by ${ratio(s.tc.naive.output, s.tc.dedup.output)}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
prog.done();
|
|
134
|
+
out.push("", verdict.length ? `A tracker that sums every usage line would overstate ${verdict.join(" and ")}.`
|
|
135
|
+
: "No usage lines found.");
|
|
136
|
+
console.log(out.join("\n"));
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
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
|
+
zeroed_copy?: boolean;
|
|
27
|
+
}
|
|
28
|
+
export interface Totals {
|
|
29
|
+
input: number;
|
|
30
|
+
output: number;
|
|
31
|
+
cache_write: number;
|
|
32
|
+
cache_read: number;
|
|
33
|
+
reasoning: number;
|
|
34
|
+
}
|
|
35
|
+
export interface ParseOptions {
|
|
36
|
+
sourceFile?: string;
|
|
37
|
+
sessionId?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface UsageOptions {
|
|
40
|
+
dedup?: boolean;
|
|
41
|
+
source?: "record" | "token_count";
|
|
42
|
+
}
|
|
43
|
+
export declare const zeroedTop: (t: Tokens) => boolean;
|
|
44
|
+
export declare function agentName(name: string): Agent;
|
|
45
|
+
export declare function parse(agentIn: string, jsonlText: string, opts?: ParseOptions): UsageRecord[];
|
|
46
|
+
export declare function usage(agentIn: string, records: UsageRecord[], opts?: UsageOptions): Totals;
|
|
47
|
+
export declare function report(agentIn: string, jsonlText: string, opts?: ParseOptions): Record<string, unknown>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// usagebench reference parser. Zero runtime dependencies; runs on Node >= 23.6 (native type stripping).
|
|
2
|
+
// Normalized records follow docs/schema_draft.md (schema "usagebench/0").
|
|
3
|
+
const FIELDS = ["input", "output", "cache_write", "cache_read", "reasoning"];
|
|
4
|
+
const AGENT_NAMES = {
|
|
5
|
+
claude: "claude", claude_code: "claude", codex: "codex", agy: "agy", gemini_antigravity: "agy",
|
|
6
|
+
};
|
|
7
|
+
const NORMALIZED = { claude: "claude_code", codex: "codex", agy: "gemini_antigravity" };
|
|
8
|
+
// A Claude usage row whose four top-level counters are all 0 bills nothing: a real response always has input or
|
|
9
|
+
// cache tokens. Such rows are copies (anthropics/claude-code#95555); dedup ignores them so they cannot replace
|
|
10
|
+
// the original row of the same message.
|
|
11
|
+
export const zeroedTop = (t) => !t.input && !t.output && !t.cache_write && !t.cache_read;
|
|
12
|
+
export function agentName(name) {
|
|
13
|
+
const a = AGENT_NAMES[name];
|
|
14
|
+
if (!a)
|
|
15
|
+
throw new Error(`unknown agent "${name}" (use claude, codex or agy)`);
|
|
16
|
+
return a;
|
|
17
|
+
}
|
|
18
|
+
const num = (v) => (typeof v === "number" ? v : null);
|
|
19
|
+
const str = (v) => (typeof v === "string" ? v : null);
|
|
20
|
+
const obj = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
21
|
+
// Same key-order-insensitive equality Python uses for dicts.
|
|
22
|
+
function stable(v) {
|
|
23
|
+
if (Array.isArray(v))
|
|
24
|
+
return `[${v.map(stable).join(",")}]`;
|
|
25
|
+
const o = obj(v);
|
|
26
|
+
if (o)
|
|
27
|
+
return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${stable(o[k])}`).join(",")}}`;
|
|
28
|
+
return JSON.stringify(v ?? null);
|
|
29
|
+
}
|
|
30
|
+
function codexTokens(u) {
|
|
31
|
+
// tokens.input is the raw input_tokens; whether it includes cached_input_tokens is an open question.
|
|
32
|
+
return {
|
|
33
|
+
input: num(u.input_tokens), output: num(u.output_tokens), cache_write: num(u.cache_write_input_tokens),
|
|
34
|
+
cache_read: num(u.cached_input_tokens), reasoning: num(u.reasoning_output_tokens),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export function parse(agentIn, jsonlText, opts = {}) {
|
|
38
|
+
const agent = agentName(agentIn);
|
|
39
|
+
const out = [];
|
|
40
|
+
const base = (line, raw_type, tokens) => ({
|
|
41
|
+
schema: "usagebench/0", agent: NORMALIZED[agent], agent_version: null,
|
|
42
|
+
session_id: null, message_id: null, parent_id: null,
|
|
43
|
+
parent_session_id: null, is_sidechain: false, timestamp: null,
|
|
44
|
+
model: null, tokens, source_file: opts.sourceFile ?? "", source_line: line, raw_type,
|
|
45
|
+
});
|
|
46
|
+
// Codex state carried forward through the file.
|
|
47
|
+
let version = null, session = null, parentSession = null;
|
|
48
|
+
let sidechain = false, model = null, prevTotal = null, metaSeen = false;
|
|
49
|
+
const lines = jsonlText.split(/\r?\n/);
|
|
50
|
+
for (let i = 0; i < lines.length; i++) {
|
|
51
|
+
if (!lines[i].trim())
|
|
52
|
+
continue;
|
|
53
|
+
const o = obj(JSON.parse(lines[i]));
|
|
54
|
+
if (!o)
|
|
55
|
+
continue;
|
|
56
|
+
const line = i + 1;
|
|
57
|
+
if (agent === "claude") {
|
|
58
|
+
const m = o.type === "assistant" ? obj(o.message) : null;
|
|
59
|
+
const u = m ? obj(m.usage) : null;
|
|
60
|
+
if (!m || !u)
|
|
61
|
+
continue;
|
|
62
|
+
const tokens = {
|
|
63
|
+
input: num(u.input_tokens), output: num(u.output_tokens), cache_write: num(u.cache_creation_input_tokens),
|
|
64
|
+
cache_read: num(u.cache_read_input_tokens), reasoning: num(obj(u.output_tokens_details)?.thinking_tokens),
|
|
65
|
+
};
|
|
66
|
+
const nonzero = (v) => Object.values(obj(v) ?? {}).some((x) => typeof x === "number" && x > 0);
|
|
67
|
+
const rec = {
|
|
68
|
+
...base(line, "assistant", tokens),
|
|
69
|
+
agent_version: str(o.version), session_id: str(o.sessionId), message_id: str(m.id),
|
|
70
|
+
parent_id: str(o.parentUuid), is_sidechain: o.isSidechain === true, timestamp: str(o.timestamp),
|
|
71
|
+
model: str(m.model),
|
|
72
|
+
};
|
|
73
|
+
if (zeroedTop(tokens) && (nonzero(u.cache_creation) || nonzero(Array.isArray(u.iterations) ? u.iterations[0] : null)))
|
|
74
|
+
rec.zeroed_copy = true;
|
|
75
|
+
out.push(rec);
|
|
76
|
+
}
|
|
77
|
+
else if (agent === "codex") {
|
|
78
|
+
const p = obj(o.payload) ?? {};
|
|
79
|
+
if (o.type === "session_meta") {
|
|
80
|
+
// A forked session repeats the parent's session_meta after its own; only the first describes this file.
|
|
81
|
+
if (metaSeen)
|
|
82
|
+
continue;
|
|
83
|
+
metaSeen = true;
|
|
84
|
+
version = str(p.cli_version) ?? version;
|
|
85
|
+
session = str(p.id) ?? str(p.session_id) ?? session;
|
|
86
|
+
parentSession = str(p.parent_thread_id) ?? str(p.forked_from_id);
|
|
87
|
+
sidechain = obj(p.source)?.subagent !== undefined;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (o.type === "turn_context") {
|
|
91
|
+
model = str(p.model) ?? model;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const common = (raw, tokens, rec) => ({
|
|
95
|
+
...base(line, raw, tokens), agent_version: version,
|
|
96
|
+
session_id: str(rec.thread_id) ?? str(rec.session_id) ?? session, message_id: str(rec.response_id),
|
|
97
|
+
parent_id: str(rec.turn_id), parent_session_id: parentSession, is_sidechain: sidechain,
|
|
98
|
+
timestamp: str(o.timestamp), model,
|
|
99
|
+
});
|
|
100
|
+
if (o.type === "token_usage_record" && obj(p.usage)) {
|
|
101
|
+
out.push(common("token_usage_record", codexTokens(p.usage), p));
|
|
102
|
+
}
|
|
103
|
+
else if (o.type === "compacted") {
|
|
104
|
+
const r = obj(p.latest_token_usage_record);
|
|
105
|
+
// Copy of an earlier record: emitted so naive totals can be reproduced; usage() skips it when deduping.
|
|
106
|
+
if (r && obj(r.usage))
|
|
107
|
+
out.push(common("compacted/latest_token_usage_record", codexTokens(r.usage), r));
|
|
108
|
+
}
|
|
109
|
+
else if (p.type === "token_count" && obj(p.info)) {
|
|
110
|
+
const last = obj(p.info.last_token_usage);
|
|
111
|
+
if (!last)
|
|
112
|
+
continue;
|
|
113
|
+
const total = stable(p.info.total_token_usage);
|
|
114
|
+
out.push({ ...common("event_msg/token_count", codexTokens(last), p), total_changed: total !== prevTotal });
|
|
115
|
+
prevTotal = total;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
if (typeof o.input_tokens !== "number")
|
|
120
|
+
continue;
|
|
121
|
+
const sid = opts.sessionId ?? null;
|
|
122
|
+
out.push({
|
|
123
|
+
...base(line, str(o.type) ?? "", {
|
|
124
|
+
input: num(o.input_tokens), output: num(o.output_tokens), cache_write: null,
|
|
125
|
+
cache_read: num(o.cache_read_tokens), reasoning: null,
|
|
126
|
+
}),
|
|
127
|
+
session_id: sid, message_id: `${sid ?? "unknown"}:${o.step_index}`, timestamp: str(o.created_at),
|
|
128
|
+
model: str(o.model),
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
function sum(records) {
|
|
135
|
+
const t = { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 };
|
|
136
|
+
for (const r of records)
|
|
137
|
+
for (const k of FIELDS)
|
|
138
|
+
t[k] += r.tokens[k] ?? 0;
|
|
139
|
+
return t;
|
|
140
|
+
}
|
|
141
|
+
export function usage(agentIn, records, opts = {}) {
|
|
142
|
+
const agent = agentName(agentIn);
|
|
143
|
+
const dedup = opts.dedup ?? true;
|
|
144
|
+
if (agent === "codex") {
|
|
145
|
+
if (opts.source === "token_count") {
|
|
146
|
+
const tc = records.filter((r) => r.raw_type === "event_msg/token_count");
|
|
147
|
+
return sum(dedup ? tc.filter((r) => r.total_changed) : tc);
|
|
148
|
+
}
|
|
149
|
+
const recs = records.filter((r) => r.raw_type !== "event_msg/token_count");
|
|
150
|
+
if (!dedup)
|
|
151
|
+
return sum(recs); // naive: also counts compacted copies
|
|
152
|
+
const last = new Map();
|
|
153
|
+
for (const r of recs)
|
|
154
|
+
if (r.raw_type === "token_usage_record")
|
|
155
|
+
last.set(String(r.message_id), r);
|
|
156
|
+
return sum([...last.values()]);
|
|
157
|
+
}
|
|
158
|
+
if (agent === "claude") {
|
|
159
|
+
if (!dedup)
|
|
160
|
+
return sum(records);
|
|
161
|
+
const last = new Map();
|
|
162
|
+
for (const r of records)
|
|
163
|
+
if (!zeroedTop(r.tokens))
|
|
164
|
+
last.set(JSON.stringify([r.session_id, r.message_id]), r);
|
|
165
|
+
return sum([...last.values()]);
|
|
166
|
+
}
|
|
167
|
+
// agy: PLANNER_RESPONSE tokens are per call; other records with token fields (CHECKPOINT) are summaries.
|
|
168
|
+
return sum(dedup ? records.filter((r) => r.raw_type === "PLANNER_RESPONSE") : records);
|
|
169
|
+
}
|
|
170
|
+
export function report(agentIn, jsonlText, opts = {}) {
|
|
171
|
+
const agent = agentName(agentIn);
|
|
172
|
+
const recs = parse(agent, jsonlText, opts);
|
|
173
|
+
const res = {
|
|
174
|
+
agent, naive: usage(agent, recs, { dedup: false }), dedup: usage(agent, recs, { dedup: true }),
|
|
175
|
+
};
|
|
176
|
+
if (agent === "codex") {
|
|
177
|
+
res.token_count_naive = usage(agent, recs, { dedup: false, source: "token_count" });
|
|
178
|
+
res.token_count_dedup = usage(agent, recs, { dedup: true, source: "token_count" });
|
|
179
|
+
}
|
|
180
|
+
return res;
|
|
181
|
+
}
|
package/dist/logs.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type UsageRecord } from "./index.ts";
|
|
2
|
+
export type LogAgent = "claude" | "codex";
|
|
3
|
+
export declare const LOG_AGENTS: LogAgent[];
|
|
4
|
+
export declare const MAX_FILE_BYTES: number;
|
|
5
|
+
export declare function logRoots(agent: LogAgent, env?: NodeJS.ProcessEnv): string[];
|
|
6
|
+
export interface LogFile {
|
|
7
|
+
root: string;
|
|
8
|
+
path: string;
|
|
9
|
+
rel: string;
|
|
10
|
+
size: number;
|
|
11
|
+
mtimeMs: number;
|
|
12
|
+
}
|
|
13
|
+
export declare function logFiles(agent: LogAgent, env?: NodeJS.ProcessEnv): LogFile[];
|
|
14
|
+
export declare function readText(f: LogFile): string | null;
|
|
15
|
+
export declare function parseLenient(agent: LogAgent, text: string, sourceFile?: string): {
|
|
16
|
+
records: UsageRecord[];
|
|
17
|
+
bad: number;
|
|
18
|
+
};
|
|
19
|
+
export declare function progress(total: number): {
|
|
20
|
+
tick(n: number): void;
|
|
21
|
+
done(): void;
|
|
22
|
+
};
|
package/dist/logs.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Where agent logs live, and reading them without trusting them. Read-only: nothing here writes.
|
|
2
|
+
// Defaults (same on Windows, macOS and Linux, under the user's home):
|
|
3
|
+
// Claude Code: ~/.claude/projects and ~/.config/claude/projects; CLAUDE_CONFIG_DIR (comma-separated) overrides.
|
|
4
|
+
// Codex: ~/.codex/sessions (and archived_sessions); CODEX_HOME overrides ~/.codex.
|
|
5
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { join, relative } from "node:path";
|
|
8
|
+
import { parse } from "./index.js";
|
|
9
|
+
export const LOG_AGENTS = ["claude", "codex"];
|
|
10
|
+
// Files above this size are skipped by the scanners (counted as skipped); override with USAGEBENCH_MAX_FILE_MB.
|
|
11
|
+
export const MAX_FILE_BYTES = Number(process.env.USAGEBENCH_MAX_FILE_MB ?? 256) * 1024 * 1024;
|
|
12
|
+
export function logRoots(agent, env = process.env) {
|
|
13
|
+
const home = homedir(); // HOME on macOS/Linux, USERPROFILE on Windows
|
|
14
|
+
let dirs;
|
|
15
|
+
if (agent === "claude") {
|
|
16
|
+
const cfg = env.CLAUDE_CONFIG_DIR?.split(",").map((s) => s.trim()).filter(Boolean);
|
|
17
|
+
dirs = cfg?.length ? cfg.map((d) => join(d, "projects"))
|
|
18
|
+
: [join(home, ".claude", "projects"), join(home, ".config", "claude", "projects")];
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
const base = env.CODEX_HOME || join(home, ".codex");
|
|
22
|
+
dirs = [join(base, "sessions"), join(base, "archived_sessions")];
|
|
23
|
+
}
|
|
24
|
+
return dirs.filter((d) => existsSync(d));
|
|
25
|
+
}
|
|
26
|
+
// Every *.jsonl under the roots; unreadable directories and files are skipped silently.
|
|
27
|
+
// Symlinked directories and files are followed; a directory reached twice (symlink cycle) is walked once.
|
|
28
|
+
export function logFiles(agent, env = process.env) {
|
|
29
|
+
const out = [];
|
|
30
|
+
const seen = new Set();
|
|
31
|
+
for (const root of logRoots(agent, env)) {
|
|
32
|
+
const walk = (d) => {
|
|
33
|
+
let ents;
|
|
34
|
+
try {
|
|
35
|
+
const real = realpathSync(d);
|
|
36
|
+
if (seen.has(real))
|
|
37
|
+
return;
|
|
38
|
+
seen.add(real);
|
|
39
|
+
ents = readdirSync(d, { withFileTypes: true });
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
for (const e of ents) {
|
|
45
|
+
const p = join(d, e.name);
|
|
46
|
+
let isDir = e.isDirectory(), isFile = e.isFile();
|
|
47
|
+
if (e.isSymbolicLink()) {
|
|
48
|
+
try {
|
|
49
|
+
const s = statSync(p);
|
|
50
|
+
isDir = s.isDirectory();
|
|
51
|
+
isFile = s.isFile();
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
continue;
|
|
55
|
+
} // dangling link
|
|
56
|
+
}
|
|
57
|
+
if (isDir)
|
|
58
|
+
walk(p);
|
|
59
|
+
else if (isFile && e.name.endsWith(".jsonl")) {
|
|
60
|
+
try {
|
|
61
|
+
const s = statSync(p);
|
|
62
|
+
out.push({ root, path: p, rel: relative(root, p).replaceAll("\\", "/"), size: s.size, mtimeMs: s.mtimeMs });
|
|
63
|
+
}
|
|
64
|
+
catch { /* vanished or unreadable */ }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
walk(root);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
export function readText(f) {
|
|
73
|
+
if (f.size > MAX_FILE_BYTES)
|
|
74
|
+
return null;
|
|
75
|
+
try {
|
|
76
|
+
return readFileSync(f.path, "utf8");
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
// Lines that can carry usage; everything else is skipped before JSON parsing (big logs are mostly tool output).
|
|
83
|
+
const USAGE_HINT = {
|
|
84
|
+
claude: /"usage"/,
|
|
85
|
+
codex: /"(?:session_meta|turn_context|token_count|token_usage_record|compacted)"/,
|
|
86
|
+
};
|
|
87
|
+
// Parse a real log: lines that are not valid JSON (a truncated last line, a partial write) are dropped and counted.
|
|
88
|
+
export function parseLenient(agent, text, sourceFile = "") {
|
|
89
|
+
let bad = 0;
|
|
90
|
+
const good = [];
|
|
91
|
+
for (const l of text.split(/\r?\n/)) {
|
|
92
|
+
if (!l.trim() || !USAGE_HINT[agent].test(l)) {
|
|
93
|
+
good.push("");
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
JSON.parse(l);
|
|
98
|
+
good.push(l);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
bad++;
|
|
102
|
+
good.push("");
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { records: parse(agent, good.join("\n"), { sourceFile }), bad };
|
|
106
|
+
}
|
|
107
|
+
// Shows "scanned N/M files" on stderr only when a scan has run longer than 2 s and stderr is a terminal.
|
|
108
|
+
export function progress(total) {
|
|
109
|
+
const t0 = Date.now();
|
|
110
|
+
let last = 0;
|
|
111
|
+
return {
|
|
112
|
+
tick(n) {
|
|
113
|
+
const now = Date.now();
|
|
114
|
+
if (!process.stderr.isTTY || now - t0 < 2000 || now - last < 500)
|
|
115
|
+
return;
|
|
116
|
+
last = now;
|
|
117
|
+
process.stderr.write(`\rscanned ${n}/${total} files`);
|
|
118
|
+
},
|
|
119
|
+
done() { if (last)
|
|
120
|
+
process.stderr.write("\r" + " ".repeat(40) + "\r"); },
|
|
121
|
+
};
|
|
122
|
+
}
|
package/dist/repro.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function repro(args: string[]): number;
|
package/dist/repro.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// `usagebench repro [--session <id>|--latest] [--agent claude|codex] [--tracker <name>] [--out <dir>] [--max-kb 50]`
|
|
2
|
+
// Turns one local session into a small anonymized repro (same rules as tools/make_fixture.py; exit 3 when a secret,
|
|
3
|
+
// path or e-mail would survive), with expected totals and a ready-to-paste issue text.
|
|
4
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
|
+
import { logFiles, readText, LOG_AGENTS } from "./logs.js";
|
|
8
|
+
import { anonymize, expectedFor, Refused } from "./anon.js";
|
|
9
|
+
import { delta, expectedInToolTerms, homeEnv, installedTrackers, place } from "./compare.js";
|
|
10
|
+
// Lines that matter for usage totals; everything else (prompts, tool output) is dropped before anonymizing.
|
|
11
|
+
function relevant(agent, objs) {
|
|
12
|
+
if (agent === "claude")
|
|
13
|
+
return objs.filter((o) => o?.type === "assistant" && o.message?.usage);
|
|
14
|
+
let meta = false;
|
|
15
|
+
return objs.filter((o) => {
|
|
16
|
+
if (o?.type === "session_meta") {
|
|
17
|
+
if (meta)
|
|
18
|
+
return true;
|
|
19
|
+
meta = true;
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
if (o?.type === "turn_context" || o?.type === "token_usage_record")
|
|
23
|
+
return true;
|
|
24
|
+
if (o?.type === "compacted") {
|
|
25
|
+
if (o.payload)
|
|
26
|
+
delete o.payload.replacement_history;
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
return o?.payload?.type === "token_count";
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
// Keep a prefix of the relevant lines that fits in maxBytes, never splitting one Claude message's lines.
|
|
33
|
+
function trim(agent, lines, objs, maxBytes) {
|
|
34
|
+
let size = 0, cut = 0;
|
|
35
|
+
for (let i = 0; i < lines.length; i++) {
|
|
36
|
+
size += Buffer.byteLength(lines[i]) + 1;
|
|
37
|
+
const sameMsg = agent === "claude" && i + 1 < objs.length && objs[i + 1].message?.id === objs[i].message?.id;
|
|
38
|
+
if (size > maxBytes && cut > 0)
|
|
39
|
+
break;
|
|
40
|
+
if (!sameMsg)
|
|
41
|
+
cut = i + 1;
|
|
42
|
+
}
|
|
43
|
+
return cut || lines.length;
|
|
44
|
+
}
|
|
45
|
+
export function repro(args) {
|
|
46
|
+
const opt = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
|
|
47
|
+
const want = opt("--agent"), sid = opt("--session"), tracker = opt("--tracker");
|
|
48
|
+
const maxKb = Number(opt("--max-kb") ?? 50);
|
|
49
|
+
if (!Number.isFinite(maxKb) || maxKb <= 0) {
|
|
50
|
+
console.error("--max-kb must be a number > 0");
|
|
51
|
+
return 2;
|
|
52
|
+
}
|
|
53
|
+
const maxBytes = maxKb * 1024;
|
|
54
|
+
if (want && !LOG_AGENTS.includes(want)) {
|
|
55
|
+
console.error("--agent must be claude or codex");
|
|
56
|
+
return 2;
|
|
57
|
+
}
|
|
58
|
+
const cands = (want ? [want] : LOG_AGENTS)
|
|
59
|
+
.flatMap((a) => logFiles(a).map((f) => ({ ...f, agent: a })))
|
|
60
|
+
.filter((f) => !sid || f.rel.includes(sid))
|
|
61
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
62
|
+
const f = cands[0];
|
|
63
|
+
if (!f) {
|
|
64
|
+
console.error(sid ? `no log file name contains "${sid}"` : "no agent logs found (see `usagebench doctor`)");
|
|
65
|
+
return 2;
|
|
66
|
+
}
|
|
67
|
+
const text = readText(f);
|
|
68
|
+
if (text === null) {
|
|
69
|
+
console.error("log file is unreadable or above the size cap");
|
|
70
|
+
return 2;
|
|
71
|
+
}
|
|
72
|
+
const objs = [];
|
|
73
|
+
for (const l of text.split(/\r?\n/)) {
|
|
74
|
+
if (l.trim())
|
|
75
|
+
try {
|
|
76
|
+
objs.push(JSON.parse(l));
|
|
77
|
+
}
|
|
78
|
+
catch { /* invalid line */ }
|
|
79
|
+
}
|
|
80
|
+
const rel = relevant(f.agent, objs);
|
|
81
|
+
if (!rel.length) {
|
|
82
|
+
console.error("the session has no usage lines");
|
|
83
|
+
return 2;
|
|
84
|
+
}
|
|
85
|
+
let lines;
|
|
86
|
+
try {
|
|
87
|
+
lines = anonymize(rel);
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
if (e instanceof Refused) {
|
|
91
|
+
console.error(`REFUSED ${e.message} (a secret, path or e-mail would survive; nothing written)`);
|
|
92
|
+
return 3;
|
|
93
|
+
}
|
|
94
|
+
throw e;
|
|
95
|
+
}
|
|
96
|
+
const full = expectedFor(f.agent, lines.join("\n") + "\n");
|
|
97
|
+
const keep = trim(f.agent, lines, rel, maxBytes);
|
|
98
|
+
const outText = lines.slice(0, keep).join("\n") + "\n";
|
|
99
|
+
const exp = expectedFor(f.agent, outText);
|
|
100
|
+
const version = rel.map((o) => o.version ?? o.payload?.cli_version).find((v) => typeof v === "string") ?? "unknown";
|
|
101
|
+
const dir = resolve(opt("--out") ?? `usagebench-repro-${f.agent}`);
|
|
102
|
+
mkdirSync(dir, { recursive: true });
|
|
103
|
+
writeFileSync(join(dir, "repro.jsonl"), outText, "utf8");
|
|
104
|
+
writeFileSync(join(dir, "expected.json"), JSON.stringify(exp, null, 1) + "\n", "utf8");
|
|
105
|
+
let trackerLine = "";
|
|
106
|
+
if (tracker) {
|
|
107
|
+
const t = installedTrackers(args, tracker)[tracker];
|
|
108
|
+
if (!t)
|
|
109
|
+
trackerLine = `${tracker}: not found on PATH (pass --${tracker} <command>)`;
|
|
110
|
+
else {
|
|
111
|
+
const home = join(mkdtempSync(join(tmpdir(), "usagebench_repro_")), "home");
|
|
112
|
+
try {
|
|
113
|
+
place(f.agent, join(dir, "repro.jsonl"), home);
|
|
114
|
+
const e = expectedInToolTerms(f.agent, exp);
|
|
115
|
+
let r;
|
|
116
|
+
try {
|
|
117
|
+
r = delta(t.fn(f.agent, homeEnv(home)), e);
|
|
118
|
+
}
|
|
119
|
+
catch (x) {
|
|
120
|
+
r = `error: ${x.message}`;
|
|
121
|
+
}
|
|
122
|
+
trackerLine = `${t.ver.startsWith(tracker) ? t.ver : tracker + " " + t.ver}: ${r}`;
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
rmSync(join(home, ".."), { recursive: true, force: true });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const key = f.agent === "claude" ? "dedup" : "token_count_dedup";
|
|
130
|
+
const row = (o) => ["input", "output", "cache_write", "cache_read", "reasoning"].map((k) => o?.[k] ?? 0).join(" / ");
|
|
131
|
+
const issue = [
|
|
132
|
+
`### Token totals differ on a ${f.agent === "claude" ? "Claude Code" : "Codex"} ${version} session`,
|
|
133
|
+
"",
|
|
134
|
+
`- Agent: ${f.agent === "claude" ? "Claude Code" : "Codex CLI"} ${version}`,
|
|
135
|
+
tracker ? `- Tracker: ${trackerLine}` : "- Tracker: (name and version)",
|
|
136
|
+
`- Repro: attached \`repro.jsonl\` (${lines.slice(0, keep).length} lines, anonymized with usagebench; usage lines only)`,
|
|
137
|
+
"",
|
|
138
|
+
`Expected totals (input / output / cache_write / cache_read / reasoning, from \`expected.json\` \`${key}\`):`,
|
|
139
|
+
"",
|
|
140
|
+
` ${row(exp[key])}`,
|
|
141
|
+
"",
|
|
142
|
+
f.agent === "codex" ? "Codex `input` includes cached input; trackers that report uncached input should show input - cache_read.\n" : "",
|
|
143
|
+
"Reported by the tracker: (paste here)",
|
|
144
|
+
"",
|
|
145
|
+
"Generated by `usagebench repro` (https://github.com/logwright/usagebench).",
|
|
146
|
+
].join("\n");
|
|
147
|
+
writeFileSync(join(dir, "issue.md"), issue + "\n", "utf8");
|
|
148
|
+
console.log(`wrote ${dir}: repro.jsonl (${Buffer.byteLength(outText)} bytes, ${keep}/${lines.length} usage lines), expected.json, issue.md`);
|
|
149
|
+
if (keep < lines.length)
|
|
150
|
+
console.log(`trimmed to fit --max-kb; full-session ${key} output was ${full[key]?.output}, repro has ${exp[key]?.output}`);
|
|
151
|
+
if (trackerLine)
|
|
152
|
+
console.log(trackerLine);
|
|
153
|
+
return 0;
|
|
154
|
+
}
|