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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 usagebench contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,237 @@
1
- # Temporary Holding Version
1
+ # usagebench
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Stop guessing when AI coding agents break your token parser.
4
+
5
+ usagebench is a test oracle for usage trackers that read Claude Code, Codex and antigravity-cli session logs:
6
+ anonymized real logs with pinned expected totals, a reference parser, and a record of every log-format change
7
+ that matters for token counting. The CLI has no network code and only reads your logs (the one exception,
8
+ `audit --fix --yes`, rewrites a file you choose to redact and keeps a backup).
9
+
10
+ What it gives you:
11
+
12
+ - **Conformance fixtures** with expected totals, cross-checked by the TypeScript parser, the Python fixture tool and an
13
+ independent third computation ([tools/verify_independent.py](tools/verify_independent.py)).
14
+ - **`usagebench doctor`**: how much a tracker that sums every usage line would overcount on your own logs.
15
+ - **`usagebench compare` / `diff`**: run ccusage, tokscale or splitrail against the fixtures, or against a temp copy
16
+ of your own recent logs, and see the per-field delta.
17
+ - **`usagebench repro`**: turn a session where a tracker is off into a small anonymized repro + expected totals +
18
+ issue text.
19
+ - **`usagebench audit`**: find plaintext API keys, private keys, DB passwords and seed phrases in your agent logs.
20
+ - **[FORMAT_CHANGES.md](FORMAT_CHANGES.md)**: the log-format radar, per agent version.
21
+ - **A Node-free fixtures tarball** on every release, for trackers written in Rust, Go or anything else.
22
+
23
+ Status: pre-release (0.x), schema draft.
24
+
25
+ ## Try it in 5 seconds
26
+
27
+ ```sh
28
+ npx usagebench doctor
29
+ ```
30
+
31
+ Log directories are found automatically on Windows, macOS and Linux (`~/.claude/projects`,
32
+ `~/.config/claude/projects`, `~/.codex/sessions`); `CLAUDE_CONFIG_DIR` and `CODEX_HOME` override them.
33
+ Output is counts and ratios only. On one maintainer machine (11,454 Claude Code session files, 77 Codex sessions)
34
+ it reported that summing every usage line would overstate Claude Code output tokens 4.19x and Codex output 1.09x.
35
+
36
+ ## Tool compatibility
37
+
38
+ | tool | version | result | note |
39
+ |---|---|---|---|
40
+ | ccusage | 20.1.2 | 8/8 | |
41
+ | tokscale | 4.24.0 | 8/8 | |
42
+ | splitrail | 3.13.1 | | edge case found in 3.13.1; fix proposed in [Piebald-AI/splitrail#314](https://github.com/Piebald-AI/splitrail/pull/314) (in review) |
43
+
44
+ 8 Claude Code and Codex fixtures, 2 of them synthetic; agy is not compared because none of these tools reads its
45
+ log format. Full numbers: [reports/tool-comparison.md](reports/tool-comparison.md).
46
+
47
+ ### Badge for trackers
48
+
49
+ A tracker that passes every fixture can show it:
50
+
51
+ ```md
52
+ [![usagebench](https://img.shields.io/badge/usagebench-8%2F8%20fixtures-brightgreen)](https://github.com/logwright/usagebench/blob/master/reports/tool-comparison.md)
53
+ ```
54
+
55
+ [![usagebench](https://img.shields.io/badge/usagebench-8%2F8%20fixtures-brightgreen)](reports/tool-comparison.md)
56
+
57
+ ## Quick start
58
+
59
+ ```sh
60
+ npx usagebench --help
61
+ npx usagebench doctor # naive vs deduplicated totals on your logs
62
+ npx usagebench audit # plaintext secrets in your logs, masked (exit 1 if any)
63
+ npx usagebench audit --fix # dry run; add --yes to redact (backup: <file>.usagebench.bak)
64
+ npx usagebench repro --latest --agent claude # repro.jsonl + expected.json + issue.md
65
+ npx usagebench compare # ccusage and tokscale vs the bundled fixtures (scorecard)
66
+ npx usagebench diff --ccusage "npx -y ccusage@latest" # a tracker vs usagebench on your last 7 days
67
+ npx usagebench codex path/to/rollout-....jsonl # totals for one file
68
+ ```
69
+
70
+ Every command above was run from the packed tarball in an empty folder before release
71
+ (`compare` and `diff` fetch the trackers through npx; usagebench itself does not go online).
72
+ `audit --fix` skips files modified in the last 10 minutes (a session may still be writing them) and re-scans each
73
+ file after redacting; JSON lines stay valid.
74
+
75
+ ## Use the fixtures in your tracker's CI (no Node needed)
76
+
77
+ Each release (from 0.2.0) has `fixtures.tar.gz`: `fixtures/` plus `manifest.json` (path, agent, version, sha256 and
78
+ expected totals for every fixture).
79
+
80
+ ```sh
81
+ curl -sL https://github.com/logwright/usagebench/releases/latest/download/fixtures.tar.gz | tar xz
82
+ ```
83
+
84
+ GitHub Actions:
85
+
86
+ ```yaml
87
+ usagebench:
88
+ runs-on: ubuntu-latest
89
+ steps:
90
+ - uses: actions/checkout@v4
91
+ - run: curl -sL https://github.com/logwright/usagebench/releases/latest/download/fixtures.tar.gz | tar xz -C /tmp
92
+ - run: | # place each fixture where your tool looks, run it, compare with manifest.json
93
+ jq -c '.fixtures[] | select(.agent != "agy")' /tmp/manifest.json | while read -r f; do
94
+ echo "$f" | jq -r '.path, .expected' # replace with: run your tracker on /tmp/<path>, compare
95
+ done
96
+ ```
97
+
98
+ ## Watch for log-format changes
99
+
100
+ [FORMAT_CHANGES.md](FORMAT_CHANGES.md) lists what changed per agent version. Watch this repo
101
+ (Watch → Custom → Releases) to get notified when a new entry or fixture lands.
102
+
103
+ ## Contributing a fixture
104
+
105
+ ```sh
106
+ npx usagebench repro --session <id> --agent claude --out my-repro # anonymized; exit 3 if a secret would survive
107
+ python tools/make_fixture.py claude <session.jsonl> fixtures/claude/<version>_<feature>.jsonl # from a clone
108
+ ```
109
+
110
+ Details in [CONTRIBUTING.md](CONTRIBUTING.md). Pull requests that add fixtures run the schema check, the leak scan
111
+ and the TS vs Python expected-total cross-check; a failure gets one comment saying which file and check failed.
112
+
113
+ ## The problem
114
+
115
+ AI coding agents write session logs as JSONL, and those logs hold token usage. Adding up every usage
116
+ number you find gives the wrong answer, and the error is large:
117
+
118
+ - **Claude Code** writes one line per content block (thinking, text, tool call) of a single API response,
119
+ and copies the same `usage` object onto each line. Summing every line overstated output tokens about
120
+ 2x (2.04x) and cache reads 1.71x on the logs we measured. The fix is to keep one line per
121
+ `(sessionId, message.id)`.
122
+ - **Codex** has two usage streams. `token_usage_record` holds per-response usage, but `compacted`
123
+ records carry a copy of the latest one, so counting both double counts. The older `token_count` events
124
+ carry a cumulative `total_token_usage` plus a per-response `last_token_usage`, and about a third of them
125
+ are re-emitted with an unchanged total; adding `last_token_usage` each time overcounts.
126
+ - **Antigravity CLI** (`agy`, Gemini family) writes per-call tokens on `PLANNER_RESPONSE` steps. It has no
127
+ session id, message id, version, cache-write or reasoning counts in the log.
128
+
129
+ Details and the measurements behind each rule are in [docs/schema_draft.md](docs/schema_draft.md).
130
+
131
+ ## What this repo provides
132
+
133
+ - `docs/schema_draft.md`: a draft normalized event schema (`usagebench/0`), one record per billable model
134
+ response, with a field mapping for each agent and the dedup rules.
135
+ - `fixtures/`: small anonymized real logs, each with an `.expected.json` holding naive and deduplicated totals
136
+ (format: [docs/expected.schema.json](docs/expected.schema.json)).
137
+ - `tools/make_fixture.py`: turns a real log into an anonymized fixture and computes its expected totals. It refuses
138
+ (exit 3, no output) when an id field or a kept value holds a key, a path or an e-mail address.
139
+ - `tools/check_leaks.py`: scans fixtures for user names, paths, e-mail addresses, URLs, API keys (Anthropic,
140
+ OpenAI, GitHub, AWS, Google, Slack), private keys, sentences and native ids. CI fails on any hit.
141
+ - `tools/compare_tools.py`: runs ccusage, tokscale and splitrail on every fixture in a throwaway home and writes
142
+ [reports/tool-comparison.md](reports/tool-comparison.md).
143
+ - `tools/build_fixtures.py`: rebuilds every fixture from pinned source paths and checks they come out byte-identical.
144
+ - `parser/`: a reference TypeScript parser with no runtime dependencies.
145
+
146
+ ## Fixture format
147
+
148
+ A fixture is the first 200 lines of a real session log, anonymized: keys, record order, value types,
149
+ numbers, booleans, type enums, model names and version strings are kept; ids become consistent fake ids
150
+ (`id_fake000001`, `msg_fake000002`, ...); timestamps are shifted so the first one is `2026-01-01T00:00:00Z`;
151
+ every other string becomes `<redacted>`.
152
+
153
+ Next to each `name.jsonl` sits `name.expected.json`:
154
+
155
+ ```json
156
+ {
157
+ "agent": "claude",
158
+ "usage_lines": 120,
159
+ "unique_messages": 61,
160
+ "rule": "claude_last_per_message_id",
161
+ "naive": {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0, "reasoning": 0},
162
+ "dedup": {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0, "reasoning": 0}
163
+ }
164
+ ```
165
+
166
+ `naive` is what summing every usage line gives; `dedup` is the correct total. Codex fixtures also have
167
+ `compacted_copies`, `token_count_events`, `token_count_naive` and `token_count_dedup`. Fixture files are
168
+ named `<cli version>_<feature>.jsonl`; agy logs have no version, so its fixture is `transcript_basic.jsonl`.
169
+
170
+ | fixture | what it pins |
171
+ |---|---|
172
+ | `claude/2.1.334_main` | content blocks of one response repeat the same `usage` (dedup by `message.id`) |
173
+ | `claude/2.1.335_sidechain` | subagent file, `isSidechain: true` on every line |
174
+ | `claude/2.1.335_stream-abort-tool-error` | a response interrupted mid-stream (`stop_reason` null, partial usage) followed by a tool error |
175
+ | `claude/synthetic_duplicate-id-partial-usage` | synthetic: first line of a message has a partial usage snapshot, the last one the final usage |
176
+ | `codex/0.160.0_compacted` | `compacted` copies of usage records; `token_count` events re-emitted with an unchanged total |
177
+ | `codex/0.171.0-alpha.13.2_subagent-forked` | forked subagent: the parent's `session_meta` repeated on line 2 must not replace the file's own |
178
+ | `codex/0.173.0-alpha.4.1_basic` | plain session with `token_usage_record` and `token_count` |
179
+ | `codex/synthetic_total-reset` | synthetic: re-emitted event, `info: null`, and a cumulative total that goes down |
180
+ | `agy/transcript_basic` | antigravity-cli `PLANNER_RESPONSE` steps |
181
+
182
+ `synthetic_*` fixtures are hand-written because the case was not found in real logs; their `.expected.json`
183
+ says `"synthetic": true`. Everything else is cut from a real log.
184
+
185
+ ## Using the fixtures in another tool's CI
186
+
187
+ Each fixture is a self-contained log. Copy it where your tool looks (for example
188
+ `$CLAUDE_CONFIG_DIR/projects/x/<sessionId>.jsonl` or `$CODEX_HOME/sessions/2026/01/01/rollout-...jsonl`), run
189
+ your tool, and compare with `dedup` (Claude) or `token_count_dedup` (Codex, if you read `token_count` events).
190
+ `tools/compare_tools.py` does exactly this for ccusage, tokscale and splitrail.
191
+
192
+ ## Usage
193
+
194
+ From npm (the package is `usagebench`, the command is `usagebench`):
195
+
196
+ ```sh
197
+ npx usagebench claude path/to/session.jsonl
198
+ npx usagebench codex path/to/rollout-....jsonl
199
+ npm install usagebench # then: import { parse, usage } from "usagebench"
200
+ ```
201
+
202
+ From a clone, Node 23.6 or newer runs the TypeScript source directly (built-in type stripping):
203
+
204
+ ```sh
205
+ cd parser
206
+ node src/cli.ts claude path/to/session.jsonl
207
+ node src/cli.ts codex path/to/rollout-....jsonl
208
+ node src/cli.ts agy path/to/transcript.jsonl
209
+ npm test # runs the parser on every fixture and compares with .expected.json
210
+ ```
211
+
212
+ CI (`.github/workflows/ci.yml`) runs the build, `npm test`, `tools/check_leaks.py fixtures`,
213
+ `tools/test_tools.py` (fault injection for the scanner and the anonymizer) and `tools/verify_independent.py`.
214
+
215
+ From code:
216
+
217
+ ```ts
218
+ import { parse, usage } from "./parser/src/index.ts";
219
+ const records = parse("claude", text, { sourceFile: "session.jsonl" });
220
+ usage("claude", records, { dedup: true }); // {input, output, cache_write, cache_read, reasoning}
221
+ usage("codex", records, { dedup: true, source: "token_count" }); // Codex fallback path
222
+ ```
223
+
224
+ `npm test` writes `parser/e2e_result.json` with the result for each fixture.
225
+
226
+ ## Known gaps
227
+
228
+ - Codex `tokens.input` is the raw `input_tokens`, which already includes `cache_read` (ccusage, tokscale and
229
+ splitrail all treat it that way; issue #1). Uncached input = `input - cache_read`.
230
+ - agy: whether `input_tokens` includes `cache_read_tokens` is unknown; the session id must be passed in
231
+ (it comes from the `brain/<id>` folder name).
232
+ - Fixtures cut at 200 lines can end on a `token_usage_record` whose matching `token_count` event was cut off,
233
+ so `dedup` and `token_count_dedup` differ slightly in `codex/0.160.0_compacted`.
234
+
235
+ ## License
236
+
237
+ MIT, see [LICENSE](LICENSE).
package/dist/anon.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export declare class Refused extends Error {
2
+ }
3
+ export declare class Anon {
4
+ ids: Map<string, string>;
5
+ shift: number | null;
6
+ fakeId(s: string, field?: string): string;
7
+ time(s: string): string;
8
+ val(v: unknown, key?: string): unknown;
9
+ }
10
+ export declare function anonymize(lines: unknown[]): string[];
11
+ export declare function expectedFor(agent: "claude" | "codex", text: string): Record<string, unknown>;
package/dist/anon.js ADDED
@@ -0,0 +1,107 @@
1
+ // TypeScript port of tools/make_fixture.py: the same anonymization rules and the same expected-totals file,
2
+ // so `usagebench repro` output can go straight into fixtures/. Keep both in step.
3
+ import { sensitive } from "./secrets.js";
4
+ import { parse, report } from "./index.js";
5
+ const ENUM_KEYS = new Set(["type", "subtype", "role", "stop_reason", "model", "requestedModel", "advisorModel",
6
+ "version", "cli_version", "source", "originator", "model_provider", "service_tier", "userType", "level", "status",
7
+ "plan_type", "speed", "inference_geo", "reasoning_effort", "effort", "approval_policy"]);
8
+ const ENUM_OK = /^[A-Za-z0-9][A-Za-z0-9_.\-+]{0,39}$/;
9
+ const KEY_OK = /^[A-Za-z_][A-Za-z0-9_\-]{0,40}$/;
10
+ const ID_KEY = /(id|ids|uuid)$/i;
11
+ const UUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
12
+ const PREFIX_ID = /^([a-z]{2,8}_)[A-Za-z0-9]{10,}$/;
13
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
14
+ const BASE = Date.UTC(2026, 0, 1);
15
+ const RED = "<redacted>";
16
+ export class Refused extends Error {
17
+ }
18
+ function guard(field, s) {
19
+ const hits = sensitive(s);
20
+ if (hits.length)
21
+ throw new Refused(`${field}: ${hits.join(",")}`); // field and check name only, never the value
22
+ return s;
23
+ }
24
+ export class Anon {
25
+ ids = new Map();
26
+ shift = null;
27
+ fakeId(s, field = "id") {
28
+ if (!this.ids.has(s)) {
29
+ guard(field, s);
30
+ const m = PREFIX_ID.exec(s);
31
+ this.ids.set(s, `${m ? m[1] : "id_"}fake${String(this.ids.size + 1).padStart(6, "0")}`);
32
+ }
33
+ return this.ids.get(s);
34
+ }
35
+ time(s) {
36
+ const t = Date.parse(s);
37
+ if (Number.isNaN(t))
38
+ return RED;
39
+ if (this.shift === null)
40
+ this.shift = BASE - t;
41
+ const iso = new Date(t + this.shift).toISOString(); // always .sss
42
+ return s.includes(".") ? iso : iso.replace(/\.\d{3}Z$/, "Z");
43
+ }
44
+ val(v, key = "") {
45
+ if (Array.isArray(v))
46
+ return v.map((x) => this.val(x, key));
47
+ if (v !== null && typeof v === "object") {
48
+ const out = {};
49
+ let n = 0;
50
+ for (const [k, x] of Object.entries(v)) {
51
+ let nk;
52
+ if (UUID.test(k) || PREFIX_ID.test(k))
53
+ nk = this.fakeId(k, "<id key>");
54
+ else if (!KEY_OK.test(k) || k.startsWith("mcp__"))
55
+ nk = `<k${++n}>`;
56
+ else
57
+ nk = guard("<key>", k);
58
+ out[nk] = this.val(x, k);
59
+ }
60
+ return out;
61
+ }
62
+ if (typeof v !== "string" || v === "")
63
+ return v;
64
+ if (ISO.test(v))
65
+ return this.time(v);
66
+ if (ID_KEY.test(key) || UUID.test(v) || PREFIX_ID.test(v))
67
+ return this.fakeId(v, key);
68
+ if (ENUM_KEYS.has(key) && ENUM_OK.test(v))
69
+ return guard(key, v);
70
+ return RED;
71
+ }
72
+ }
73
+ // Anonymize parsed lines; throws Refused if anything sensitive would survive.
74
+ export function anonymize(lines) {
75
+ const a = new Anon();
76
+ const out = lines.map((o) => JSON.stringify(a.val(o)));
77
+ guard("<output>", out.join("\n"));
78
+ return out;
79
+ }
80
+ // Same content as `make_fixture.py --expected` (key order aside).
81
+ export function expectedFor(agent, text) {
82
+ const recs = parse(agent, text);
83
+ const r = report(agent, text);
84
+ const res = { agent };
85
+ if (agent === "claude") {
86
+ const keys = new Set(recs.map((x) => JSON.stringify([x.session_id, x.message_id])));
87
+ Object.assign(res, { usage_lines: recs.length, unique_messages: keys.size, rule: "claude_last_per_message_id",
88
+ is_sidechain: recs.length > 0 && recs.every((x) => x.is_sidechain) });
89
+ }
90
+ else {
91
+ const meta = text.split(/\r?\n/).filter((l) => l.trim()).map((l) => JSON.parse(l))
92
+ .find((o) => o.type === "session_meta")?.payload ?? {};
93
+ const tur = recs.filter((x) => x.raw_type === "token_usage_record");
94
+ Object.assign(res, {
95
+ is_sidechain: meta.source !== null && typeof meta.source === "object" && "subagent" in meta.source,
96
+ parent_session: Boolean(meta.parent_thread_id || meta.forked_from_id),
97
+ usage_lines: tur.length, unique_messages: new Set(tur.map((x) => x.message_id)).size,
98
+ compacted_copies: recs.filter((x) => x.raw_type.startsWith("compacted")).length,
99
+ rule: "codex_record_by_response_id",
100
+ token_count_events: recs.filter((x) => x.raw_type === "event_msg/token_count").length,
101
+ token_count_naive: r.token_count_naive, token_count_dedup: r.token_count_dedup,
102
+ });
103
+ }
104
+ res.naive = r.naive;
105
+ res.dedup = r.dedup;
106
+ return res;
107
+ }
@@ -0,0 +1 @@
1
+ export declare function audit(args: string[]): number;
package/dist/audit.js ADDED
@@ -0,0 +1,127 @@
1
+ // `usagebench audit [--fix [--yes]]`: look for plaintext secrets in the local agent logs.
2
+ // Prints type, file (relative to the log root), line and a masked preview (first 4 chars + length), never a value.
3
+ // Without --fix nothing is written. --fix is a dry run unless --yes is given; with --yes each affected file is
4
+ // copied to <file>.usagebench.bak, rewritten through a temp file + rename, and re-scanned.
5
+ import { copyFileSync, existsSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { logFiles, progress, readText, LOG_AGENTS } from "./logs.js";
7
+ import { findSecrets } from "./secrets.js";
8
+ const ACTIVE_MS = 10 * 60 * 1000; // a file written in the last 10 minutes may belong to a running session
9
+ function lineStarts(text) {
10
+ const s = [0];
11
+ for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1))
12
+ s.push(i + 1);
13
+ return s;
14
+ }
15
+ function lineOf(starts, index) {
16
+ let lo = 0, hi = starts.length - 1;
17
+ while (lo < hi) {
18
+ const mid = (lo + hi + 1) >> 1;
19
+ if (starts[mid] <= index)
20
+ lo = mid;
21
+ else
22
+ hi = mid - 1;
23
+ }
24
+ return lo + 1;
25
+ }
26
+ // Replace each hit with [REDACTED:<type>]; returns null if any touched line would stop being valid JSON.
27
+ function redact(text, hits) {
28
+ let out = text;
29
+ for (const h of [...hits].sort((a, b) => b.index - a.index))
30
+ out = out.slice(0, h.index) + `[REDACTED:${h.type}]` + out.slice(h.index + h.length);
31
+ const before = new Set(text.split("\n"));
32
+ for (const l of out.split("\n")) {
33
+ if (!l.trim() || before.has(l))
34
+ continue;
35
+ try {
36
+ JSON.parse(l);
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+ export function audit(args) {
45
+ const fix = args.includes("--fix"), yes = args.includes("--yes");
46
+ const files = LOG_AGENTS.flatMap((a) => logFiles(a).map((f) => ({ ...f, agent: a })));
47
+ console.log("usagebench audit: read-only scan" + (fix ? (yes ? " + redaction (--fix --yes)" : " (--fix dry run: nothing is written)") : "")
48
+ + `; ${files.length} log files`);
49
+ const byType = new Map();
50
+ let placeholders = 0, skipped = 0, findings = 0, n = 0;
51
+ const fixPlan = [];
52
+ const prog = progress(files.length);
53
+ for (const f of files) {
54
+ prog.tick(++n);
55
+ const text = readText(f);
56
+ if (text === null) {
57
+ skipped++;
58
+ continue;
59
+ }
60
+ const all = findSecrets(text);
61
+ const hits = all.filter((h) => !h.placeholder);
62
+ placeholders += all.length - hits.length;
63
+ if (!hits.length)
64
+ continue;
65
+ const starts = lineStarts(text);
66
+ for (const h of hits) {
67
+ findings++;
68
+ byType.set(h.type, (byType.get(h.type) ?? 0) + 1);
69
+ console.log(` ${f.agent}:${f.rel}:${lineOf(starts, h.index)} ${h.type} ${h.preview}`);
70
+ }
71
+ if (fix)
72
+ fixPlan.push({ f, text, hits });
73
+ }
74
+ prog.done();
75
+ console.log(`\nfindings: ${findings}` + (findings ? ` (${[...byType].map(([t, c]) => `${t} ${c}`).join(", ")})` : "")
76
+ + `; ignored as example/placeholder values: ${placeholders}` + (skipped ? `; files skipped (unreadable or > size cap): ${skipped}` : ""));
77
+ if (!fix || !findings)
78
+ return findings ? 1 : 0;
79
+ let fixed = 0, failed = 0;
80
+ for (const { f, text, hits } of fixPlan) {
81
+ const tag = `${f.rel}: ${hits.length} secret(s)`;
82
+ if (Date.now() - f.mtimeMs < ACTIVE_MS) {
83
+ console.log(` skip (modified < 10 min ago, session may be active) ${tag}`);
84
+ continue;
85
+ }
86
+ const bak = f.path + ".usagebench.bak";
87
+ if (existsSync(bak)) {
88
+ console.log(` skip (backup already exists) ${tag}`);
89
+ failed++;
90
+ continue;
91
+ }
92
+ const out = redact(text, hits);
93
+ if (out === null) {
94
+ console.log(` skip (redaction would break JSON) ${tag}`);
95
+ failed++;
96
+ continue;
97
+ }
98
+ if (!yes) {
99
+ console.log(` would redact ${tag}`);
100
+ continue;
101
+ }
102
+ const tmp = f.path + ".usagebench.tmp";
103
+ try {
104
+ copyFileSync(f.path, bak);
105
+ writeFileSync(tmp, out, "utf8");
106
+ renameSync(tmp, f.path);
107
+ }
108
+ catch (e) {
109
+ rmSync(tmp, { force: true });
110
+ console.log(` failed ${tag}: ${e.message.split("\n")[0]}`);
111
+ failed++;
112
+ continue;
113
+ }
114
+ const again = findSecrets(readText({ ...f, size: 0 }) ?? "").filter((h) => !h.placeholder);
115
+ if (again.length) {
116
+ copyFileSync(bak, f.path);
117
+ rmSync(bak, { force: true });
118
+ console.log(` restored original, re-scan still found ${again.length} ${tag}`);
119
+ failed++;
120
+ continue;
121
+ }
122
+ fixed++;
123
+ console.log(` redacted ${tag} (original kept at ${f.rel}.usagebench.bak; delete it once checked)`);
124
+ }
125
+ console.log(yes ? `\nredacted files: ${fixed}, failed or skipped: ${failed}` : "\ndry run: rerun with --fix --yes to redact");
126
+ return 1;
127
+ }
@@ -0,0 +1 @@
1
+ export declare const BIP39_ENGLISH: string[];
@@ -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 {};