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/index.js ADDED
@@ -0,0 +1,171 @@
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
+ export function agentName(name) {
9
+ const a = AGENT_NAMES[name];
10
+ if (!a)
11
+ throw new Error(`unknown agent "${name}" (use claude, codex or agy)`);
12
+ return a;
13
+ }
14
+ const num = (v) => (typeof v === "number" ? v : null);
15
+ const str = (v) => (typeof v === "string" ? v : null);
16
+ const obj = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
17
+ // Same key-order-insensitive equality Python uses for dicts.
18
+ function stable(v) {
19
+ if (Array.isArray(v))
20
+ return `[${v.map(stable).join(",")}]`;
21
+ const o = obj(v);
22
+ if (o)
23
+ return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${stable(o[k])}`).join(",")}}`;
24
+ return JSON.stringify(v ?? null);
25
+ }
26
+ function codexTokens(u) {
27
+ // tokens.input is the raw input_tokens; whether it includes cached_input_tokens is an open question.
28
+ return {
29
+ input: num(u.input_tokens), output: num(u.output_tokens), cache_write: num(u.cache_write_input_tokens),
30
+ cache_read: num(u.cached_input_tokens), reasoning: num(u.reasoning_output_tokens),
31
+ };
32
+ }
33
+ export function parse(agentIn, jsonlText, opts = {}) {
34
+ const agent = agentName(agentIn);
35
+ const out = [];
36
+ const base = (line, raw_type, tokens) => ({
37
+ schema: "usagebench/0", agent: NORMALIZED[agent], agent_version: null,
38
+ session_id: null, message_id: null, parent_id: null,
39
+ parent_session_id: null, is_sidechain: false, timestamp: null,
40
+ model: null, tokens, source_file: opts.sourceFile ?? "", source_line: line, raw_type,
41
+ });
42
+ // Codex state carried forward through the file.
43
+ let version = null, session = null, parentSession = null;
44
+ let sidechain = false, model = null, prevTotal = null, metaSeen = false;
45
+ const lines = jsonlText.split(/\r?\n/);
46
+ for (let i = 0; i < lines.length; i++) {
47
+ if (!lines[i].trim())
48
+ continue;
49
+ const o = obj(JSON.parse(lines[i]));
50
+ if (!o)
51
+ continue;
52
+ const line = i + 1;
53
+ if (agent === "claude") {
54
+ const m = o.type === "assistant" ? obj(o.message) : null;
55
+ const u = m ? obj(m.usage) : null;
56
+ if (!m || !u)
57
+ continue;
58
+ out.push({
59
+ ...base(line, "assistant", {
60
+ input: num(u.input_tokens), output: num(u.output_tokens), cache_write: num(u.cache_creation_input_tokens),
61
+ cache_read: num(u.cache_read_input_tokens), reasoning: num(obj(u.output_tokens_details)?.thinking_tokens),
62
+ }),
63
+ agent_version: str(o.version), session_id: str(o.sessionId), message_id: str(m.id),
64
+ parent_id: str(o.parentUuid), is_sidechain: o.isSidechain === true, timestamp: str(o.timestamp),
65
+ model: str(m.model),
66
+ });
67
+ }
68
+ else if (agent === "codex") {
69
+ const p = obj(o.payload) ?? {};
70
+ if (o.type === "session_meta") {
71
+ // A forked session repeats the parent's session_meta after its own; only the first describes this file.
72
+ if (metaSeen)
73
+ continue;
74
+ metaSeen = true;
75
+ version = str(p.cli_version) ?? version;
76
+ session = str(p.id) ?? str(p.session_id) ?? session;
77
+ parentSession = str(p.parent_thread_id) ?? str(p.forked_from_id);
78
+ sidechain = obj(p.source)?.subagent !== undefined;
79
+ continue;
80
+ }
81
+ if (o.type === "turn_context") {
82
+ model = str(p.model) ?? model;
83
+ continue;
84
+ }
85
+ const common = (raw, tokens, rec) => ({
86
+ ...base(line, raw, tokens), agent_version: version,
87
+ session_id: str(rec.thread_id) ?? str(rec.session_id) ?? session, message_id: str(rec.response_id),
88
+ parent_id: str(rec.turn_id), parent_session_id: parentSession, is_sidechain: sidechain,
89
+ timestamp: str(o.timestamp), model,
90
+ });
91
+ if (o.type === "token_usage_record" && obj(p.usage)) {
92
+ out.push(common("token_usage_record", codexTokens(p.usage), p));
93
+ }
94
+ else if (o.type === "compacted") {
95
+ const r = obj(p.latest_token_usage_record);
96
+ // Copy of an earlier record: emitted so naive totals can be reproduced; usage() skips it when deduping.
97
+ if (r && obj(r.usage))
98
+ out.push(common("compacted/latest_token_usage_record", codexTokens(r.usage), r));
99
+ }
100
+ else if (p.type === "token_count" && obj(p.info)) {
101
+ const last = obj(p.info.last_token_usage);
102
+ if (!last)
103
+ continue;
104
+ const total = stable(p.info.total_token_usage);
105
+ out.push({ ...common("event_msg/token_count", codexTokens(last), p), total_changed: total !== prevTotal });
106
+ prevTotal = total;
107
+ }
108
+ }
109
+ else {
110
+ if (typeof o.input_tokens !== "number")
111
+ continue;
112
+ const sid = opts.sessionId ?? null;
113
+ out.push({
114
+ ...base(line, str(o.type) ?? "", {
115
+ input: num(o.input_tokens), output: num(o.output_tokens), cache_write: null,
116
+ cache_read: num(o.cache_read_tokens), reasoning: null,
117
+ }),
118
+ session_id: sid, message_id: `${sid ?? "unknown"}:${o.step_index}`, timestamp: str(o.created_at),
119
+ model: str(o.model),
120
+ });
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ function sum(records) {
126
+ const t = { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 };
127
+ for (const r of records)
128
+ for (const k of FIELDS)
129
+ t[k] += r.tokens[k] ?? 0;
130
+ return t;
131
+ }
132
+ export function usage(agentIn, records, opts = {}) {
133
+ const agent = agentName(agentIn);
134
+ const dedup = opts.dedup ?? true;
135
+ if (agent === "codex") {
136
+ if (opts.source === "token_count") {
137
+ const tc = records.filter((r) => r.raw_type === "event_msg/token_count");
138
+ return sum(dedup ? tc.filter((r) => r.total_changed) : tc);
139
+ }
140
+ const recs = records.filter((r) => r.raw_type !== "event_msg/token_count");
141
+ if (!dedup)
142
+ return sum(recs); // naive: also counts compacted copies
143
+ const last = new Map();
144
+ for (const r of recs)
145
+ if (r.raw_type === "token_usage_record")
146
+ last.set(String(r.message_id), r);
147
+ return sum([...last.values()]);
148
+ }
149
+ if (agent === "claude") {
150
+ if (!dedup)
151
+ return sum(records);
152
+ const last = new Map();
153
+ for (const r of records)
154
+ last.set(JSON.stringify([r.session_id, r.message_id]), r);
155
+ return sum([...last.values()]);
156
+ }
157
+ // agy: PLANNER_RESPONSE tokens are per call; other records with token fields (CHECKPOINT) are summaries.
158
+ return sum(dedup ? records.filter((r) => r.raw_type === "PLANNER_RESPONSE") : records);
159
+ }
160
+ export function report(agentIn, jsonlText, opts = {}) {
161
+ const agent = agentName(agentIn);
162
+ const recs = parse(agent, jsonlText, opts);
163
+ const res = {
164
+ agent, naive: usage(agent, recs, { dedup: false }), dedup: usage(agent, recs, { dedup: true }),
165
+ };
166
+ if (agent === "codex") {
167
+ res.token_count_naive = usage(agent, recs, { dedup: false, source: "token_count" });
168
+ res.token_count_dedup = usage(agent, recs, { dedup: true, source: "token_count" });
169
+ }
170
+ return res;
171
+ }
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,105 @@
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, 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
+ export function logFiles(agent, env = process.env) {
28
+ const out = [];
29
+ for (const root of logRoots(agent, env)) {
30
+ const walk = (d) => {
31
+ let ents;
32
+ try {
33
+ ents = readdirSync(d, { withFileTypes: true });
34
+ }
35
+ catch {
36
+ return;
37
+ }
38
+ for (const e of ents) {
39
+ const p = join(d, e.name);
40
+ if (e.isDirectory())
41
+ walk(p);
42
+ else if (e.isFile() && e.name.endsWith(".jsonl")) {
43
+ try {
44
+ const s = statSync(p);
45
+ out.push({ root, path: p, rel: relative(root, p).replaceAll("\\", "/"), size: s.size, mtimeMs: s.mtimeMs });
46
+ }
47
+ catch { /* vanished or unreadable */ }
48
+ }
49
+ }
50
+ };
51
+ walk(root);
52
+ }
53
+ return out;
54
+ }
55
+ export function readText(f) {
56
+ if (f.size > MAX_FILE_BYTES)
57
+ return null;
58
+ try {
59
+ return readFileSync(f.path, "utf8");
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ // Lines that can carry usage; everything else is skipped before JSON parsing (big logs are mostly tool output).
66
+ const USAGE_HINT = {
67
+ claude: /"usage"/,
68
+ codex: /"(?:session_meta|turn_context|token_count|token_usage_record|compacted)"/,
69
+ };
70
+ // Parse a real log: lines that are not valid JSON (a truncated last line, a partial write) are dropped and counted.
71
+ export function parseLenient(agent, text, sourceFile = "") {
72
+ let bad = 0;
73
+ const good = [];
74
+ for (const l of text.split(/\r?\n/)) {
75
+ if (!l.trim() || !USAGE_HINT[agent].test(l)) {
76
+ good.push("");
77
+ continue;
78
+ }
79
+ try {
80
+ JSON.parse(l);
81
+ good.push(l);
82
+ }
83
+ catch {
84
+ bad++;
85
+ good.push("");
86
+ }
87
+ }
88
+ return { records: parse(agent, good.join("\n"), { sourceFile }), bad };
89
+ }
90
+ // Shows "scanned N/M files" on stderr only when a scan has run longer than 2 s and stderr is a terminal.
91
+ export function progress(total) {
92
+ const t0 = Date.now();
93
+ let last = 0;
94
+ return {
95
+ tick(n) {
96
+ const now = Date.now();
97
+ if (!process.stderr.isTTY || now - t0 < 2000 || now - last < 500)
98
+ return;
99
+ last = now;
100
+ process.stderr.write(`\rscanned ${n}/${total} files`);
101
+ },
102
+ done() { if (last)
103
+ process.stderr.write("\r" + " ".repeat(40) + "\r"); },
104
+ };
105
+ }
@@ -0,0 +1 @@
1
+ export declare function repro(args: string[]): number;
package/dist/repro.js ADDED
@@ -0,0 +1,149 @@
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 maxBytes = Number(opt("--max-kb") ?? 50) * 1024;
49
+ if (want && !LOG_AGENTS.includes(want)) {
50
+ console.error("--agent must be claude or codex");
51
+ return 2;
52
+ }
53
+ const cands = (want ? [want] : LOG_AGENTS)
54
+ .flatMap((a) => logFiles(a).map((f) => ({ ...f, agent: a })))
55
+ .filter((f) => !sid || f.rel.includes(sid))
56
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
57
+ const f = cands[0];
58
+ if (!f) {
59
+ console.error(sid ? `no log file name contains "${sid}"` : "no agent logs found (see `usagebench doctor`)");
60
+ return 2;
61
+ }
62
+ const text = readText(f);
63
+ if (text === null) {
64
+ console.error("log file is unreadable or above the size cap");
65
+ return 2;
66
+ }
67
+ const objs = [];
68
+ for (const l of text.split(/\r?\n/)) {
69
+ if (l.trim())
70
+ try {
71
+ objs.push(JSON.parse(l));
72
+ }
73
+ catch { /* invalid line */ }
74
+ }
75
+ const rel = relevant(f.agent, objs);
76
+ if (!rel.length) {
77
+ console.error("the session has no usage lines");
78
+ return 2;
79
+ }
80
+ let lines;
81
+ try {
82
+ lines = anonymize(rel);
83
+ }
84
+ catch (e) {
85
+ if (e instanceof Refused) {
86
+ console.error(`REFUSED ${e.message} (a secret, path or e-mail would survive; nothing written)`);
87
+ return 3;
88
+ }
89
+ throw e;
90
+ }
91
+ const full = expectedFor(f.agent, lines.join("\n") + "\n");
92
+ const keep = trim(f.agent, lines, rel, maxBytes);
93
+ const outText = lines.slice(0, keep).join("\n") + "\n";
94
+ const exp = expectedFor(f.agent, outText);
95
+ const version = rel.map((o) => o.version ?? o.payload?.cli_version).find((v) => typeof v === "string") ?? "unknown";
96
+ const dir = resolve(opt("--out") ?? `usagebench-repro-${f.agent}`);
97
+ mkdirSync(dir, { recursive: true });
98
+ writeFileSync(join(dir, "repro.jsonl"), outText, "utf8");
99
+ writeFileSync(join(dir, "expected.json"), JSON.stringify(exp, null, 1) + "\n", "utf8");
100
+ let trackerLine = "";
101
+ if (tracker) {
102
+ const t = installedTrackers(args, tracker)[tracker];
103
+ if (!t)
104
+ trackerLine = `${tracker}: not found on PATH (pass --${tracker} <command>)`;
105
+ else {
106
+ const home = join(mkdtempSync(join(tmpdir(), "usagebench_repro_")), "home");
107
+ try {
108
+ place(f.agent, join(dir, "repro.jsonl"), home);
109
+ const e = expectedInToolTerms(f.agent, exp);
110
+ let r;
111
+ try {
112
+ r = delta(t.fn(f.agent, homeEnv(home)), e);
113
+ }
114
+ catch (x) {
115
+ r = `error: ${x.message}`;
116
+ }
117
+ trackerLine = `${t.ver.startsWith(tracker) ? t.ver : tracker + " " + t.ver}: ${r}`;
118
+ }
119
+ finally {
120
+ rmSync(join(home, ".."), { recursive: true, force: true });
121
+ }
122
+ }
123
+ }
124
+ const key = f.agent === "claude" ? "dedup" : "token_count_dedup";
125
+ const row = (o) => ["input", "output", "cache_write", "cache_read", "reasoning"].map((k) => o?.[k] ?? 0).join(" / ");
126
+ const issue = [
127
+ `### Token totals differ on a ${f.agent === "claude" ? "Claude Code" : "Codex"} ${version} session`,
128
+ "",
129
+ `- Agent: ${f.agent === "claude" ? "Claude Code" : "Codex CLI"} ${version}`,
130
+ tracker ? `- Tracker: ${trackerLine}` : "- Tracker: (name and version)",
131
+ `- Repro: attached \`repro.jsonl\` (${lines.slice(0, keep).length} lines, anonymized with usagebench; usage lines only)`,
132
+ "",
133
+ `Expected totals (input / output / cache_write / cache_read / reasoning, from \`expected.json\` \`${key}\`):`,
134
+ "",
135
+ ` ${row(exp[key])}`,
136
+ "",
137
+ f.agent === "codex" ? "Codex `input` includes cached input; trackers that report uncached input should show input - cache_read.\n" : "",
138
+ "Reported by the tracker: (paste here)",
139
+ "",
140
+ "Generated by `usagebench repro` (https://github.com/logwright/usagebench).",
141
+ ].join("\n");
142
+ writeFileSync(join(dir, "issue.md"), issue + "\n", "utf8");
143
+ console.log(`wrote ${dir}: repro.jsonl (${Buffer.byteLength(outText)} bytes, ${keep}/${lines.length} usage lines), expected.json, issue.md`);
144
+ if (keep < lines.length)
145
+ console.log(`trimmed to fit --max-kb; full-session ${key} output was ${full[key]?.output}, repro has ${exp[key]?.output}`);
146
+ if (trackerLine)
147
+ console.log(trackerLine);
148
+ return 0;
149
+ }
@@ -0,0 +1,11 @@
1
+ export declare const SENSITIVE: Record<string, RegExp>;
2
+ export declare function sensitive(text: string): string[];
3
+ export interface Hit {
4
+ type: string;
5
+ index: number;
6
+ length: number;
7
+ preview: string;
8
+ placeholder: boolean;
9
+ }
10
+ export declare const mask: (s: string) => string;
11
+ export declare function findSecrets(line: string): Hit[];
@@ -0,0 +1,100 @@
1
+ // Secret detectors. SENSITIVE is the same set tools/check_leaks.py uses (make_fixture refuses on it);
2
+ // AUDIT adds the patterns `usagebench audit` looks for in raw logs. Callers only ever get a type name, a position
3
+ // and a length back; matched text never leaves this module except for in-place redaction by `audit --fix`.
4
+ import { createHash } from "node:crypto";
5
+ import { BIP39_ENGLISH } from "./bip39_english.js";
6
+ export const SENSITIVE = {
7
+ drive_path: /[A-Za-z]:\\|[A-Za-z]:\//,
8
+ unc_path: /\\\\[\w.$-]+\\/,
9
+ unix_home: /\/Users\/|\/home\/|\/root\//,
10
+ email: /[\w.+-]+@[\w-]+\.[\w.]+/,
11
+ anthropic_key: /sk-ant-[A-Za-z0-9_\-]{20,}/,
12
+ openai_key: /sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_\-]{20,}/,
13
+ github_token: /\bgh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}/,
14
+ aws_key: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,
15
+ google_key: /AIza[0-9A-Za-z_\-]{30,}/,
16
+ slack_token: /\bxox[abposr]-[A-Za-z0-9-]{10,}/,
17
+ private_key: /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
18
+ };
19
+ export function sensitive(text) {
20
+ return Object.entries(SENSITIVE).filter(([, rx]) => rx.test(text)).map(([k]) => k);
21
+ }
22
+ // Exchange API keys (Binance, Upbit, ...) have no documented distinctive format (plain 64/40-char alphanumerics),
23
+ // so they are not detected: a pattern for them would flag every hash in a log.
24
+ const AUDIT = {
25
+ anthropic_key: /sk-ant-[A-Za-z0-9_\-]{20,}/g,
26
+ openai_key: /\bsk-(?!ant-)(?:proj-|svcacct-|admin-)?[A-Za-z0-9_\-]{20,}/g,
27
+ github_token: /\bgh[pousr]_[A-Za-z0-9]{36,}|\bgithub_pat_[A-Za-z0-9_]{22,}/g,
28
+ aws_access_key_id: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
29
+ aws_secret_access_key: /(?<=aws_secret_access_key\W{1,6})[A-Za-z0-9/+]{40}(?![A-Za-z0-9/+])/gi,
30
+ google_api_key: /\bAIza[0-9A-Za-z_\-]{35}/g,
31
+ google_oauth_token: /\bya29\.[0-9A-Za-z_\-]{20,}/g,
32
+ slack_token: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g,
33
+ // PEM block; in a JSONL line its newlines are the two characters \n.
34
+ private_key: /-----BEGIN [A-Z ]*PRIVATE KEY-----(?:[A-Za-z0-9+\/=: \t-]|\\[nr])*?(?:-----END [A-Z ]*PRIVATE KEY-----|(?=\\[^nr]|[^A-Za-z0-9+\/=: \t\\-]|$))/g,
35
+ // scheme://user:password@host — the match is the password only.
36
+ db_url_password: /(?<=\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|rediss?|amqps?|mssql|sqlserver):\/\/[^\s:\/@"'\\]*:)[^\s@\/"'\\]+(?=@)/gi,
37
+ };
38
+ // Values that are documentation examples or templates, not secrets.
39
+ const PLACEHOLDER = /EXAMPLE|\[REDACTED:|x{4,}|X{4,}|\*{3,}|\.{3}|your[_-]?|<|>|\$\{|\{\{|(.)\1{7,}|^(?:pass(?:word)?|secret|changeme|admin|root|test|user|pwd)$/i;
40
+ export const mask = (s) => `${s.slice(0, 4)}…(${s.length})`;
41
+ const WORDS = new Map(BIP39_ENGLISH.map((w, i) => [w, i]));
42
+ function bip39Valid(words) {
43
+ const idx = words.map((w) => WORDS.get(w));
44
+ if (idx.some((i) => i === undefined))
45
+ return false;
46
+ const bits = idx.map((i) => i.toString(2).padStart(11, "0")).join("");
47
+ const ent = (bits.length * 32) / 33, cs = bits.length - ent;
48
+ const bytes = Buffer.alloc(ent / 8);
49
+ for (let i = 0; i < bytes.length; i++)
50
+ bytes[i] = parseInt(bits.slice(i * 8, i * 8 + 8), 2);
51
+ const h = createHash("sha256").update(bytes).digest();
52
+ const hbits = [...h].map((b) => b.toString(2).padStart(8, "0")).join("").slice(0, cs);
53
+ return hbits === bits.slice(ent);
54
+ }
55
+ // 12/15/18/21/24 consecutive wordlist words (single spaces) whose checksum is valid.
56
+ function seedPhrases(line) {
57
+ const out = [];
58
+ for (const m of line.matchAll(/\b[a-z]{3,8}(?: [a-z]{3,8}){11,}\b/g)) {
59
+ const words = m[0].split(" ");
60
+ const starts = [];
61
+ let p = 0;
62
+ for (const w of words) {
63
+ starts.push(p);
64
+ p += w.length + 1;
65
+ }
66
+ let i = 0;
67
+ outer: while (i + 12 <= words.length) {
68
+ for (const n of [24, 21, 18, 15, 12]) {
69
+ if (i + n > words.length)
70
+ continue;
71
+ const win = words.slice(i, i + n);
72
+ if (bip39Valid(win)) {
73
+ const text = win.join(" ");
74
+ out.push({ type: "bip39_seed_phrase", index: m.index + starts[i], length: text.length,
75
+ preview: `${text.slice(0, 4)}…(${n} words)`, placeholder: false });
76
+ i += n;
77
+ continue outer;
78
+ }
79
+ }
80
+ i++;
81
+ }
82
+ }
83
+ return out;
84
+ }
85
+ export function findSecrets(line) {
86
+ const hits = [];
87
+ for (const [type, rx] of Object.entries(AUDIT)) {
88
+ for (const m of line.matchAll(rx)) {
89
+ // A PEM header with no real key body (code or docs that mention the format) is not a key.
90
+ const noBody = type === "private_key" && (m[0].replace(/-----[A-Z ]+-----|\\[nr]|\s/g, "").match(/[A-Za-z0-9+\/=]/g)?.length ?? 0) < 64;
91
+ hits.push({ type, index: m.index, length: m[0].length, preview: mask(m[0]), placeholder: noBody || PLACEHOLDER.test(m[0]) });
92
+ }
93
+ }
94
+ if (/[a-z]{3,8}(?: [a-z]{3,8}){11}/.test(line))
95
+ hits.push(...seedPhrases(line));
96
+ // Drop hits that sit inside a longer hit (e.g. an AWS key id inside a PEM body).
97
+ hits.sort((a, b) => a.index - b.index || b.length - a.length);
98
+ return hits.filter((h, i) => !hits.some((o, j) => j !== i && o.index <= h.index && o.index + o.length >= h.index + h.length
99
+ && (o.length > h.length || j < i)));
100
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "agent": "claude",
3
+ "usage_lines": 13,
4
+ "unique_messages": 7,
5
+ "rule": "claude_last_per_message_id",
6
+ "is_sidechain": false,
7
+ "naive": {
8
+ "input": 26,
9
+ "output": 7650,
10
+ "cache_write": 369996,
11
+ "cache_read": 1308765,
12
+ "reasoning": 830
13
+ },
14
+ "dedup": {
15
+ "input": 14,
16
+ "output": 4039,
17
+ "cache_write": 186687,
18
+ "cache_read": 730509,
19
+ "reasoning": 415
20
+ }
21
+ }