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/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,252 @@
|
|
|
1
|
-
#
|
|
1
|
+
# usagebench
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Token-usage conformance tests for AI coding agent logs (Claude Code, Codex, Antigravity CLI).
|
|
4
|
+
|
|
5
|
+
Stop guessing when AI coding agents break your token parser.
|
|
6
|
+
|
|
7
|
+
usagebench is a test oracle for usage trackers that read Claude Code, Codex and antigravity-cli session logs:
|
|
8
|
+
anonymized real logs with pinned expected totals, a reference parser, and a record of every log-format change
|
|
9
|
+
that matters for token counting. The CLI has no network code and only reads your logs (the one exception,
|
|
10
|
+
`audit --fix --yes`, rewrites a file you choose to redact and keeps a backup).
|
|
11
|
+
|
|
12
|
+
What it gives you:
|
|
13
|
+
|
|
14
|
+
- **Conformance fixtures** with expected totals, cross-checked by the TypeScript parser, the Python fixture tool and an
|
|
15
|
+
independent third computation ([tools/verify_independent.py](tools/verify_independent.py)).
|
|
16
|
+
- **`usagebench doctor`**: how much a tracker that sums every usage line would overcount on your own logs.
|
|
17
|
+
- **`usagebench compare` / `diff`**: run ccusage, tokscale or splitrail against the fixtures, or against a temp copy
|
|
18
|
+
of your own recent logs, and see the per-field delta.
|
|
19
|
+
- **`usagebench repro`**: turn a session where a tracker is off into a small anonymized repro + expected totals +
|
|
20
|
+
issue text.
|
|
21
|
+
- **`usagebench audit`**: find plaintext API keys, private keys, DB passwords and seed phrases in your agent logs.
|
|
22
|
+
- **[FORMAT_CHANGES.md](FORMAT_CHANGES.md)**: the log-format radar, per agent version.
|
|
23
|
+
- **A Node-free fixtures tarball** on every release, for trackers written in Rust, Go or anything else.
|
|
24
|
+
|
|
25
|
+
Status: pre-release (0.x), schema draft.
|
|
26
|
+
|
|
27
|
+
## Try it in 5 seconds
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
npx usagebench doctor
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Log directories are found automatically on Windows, macOS and Linux (`~/.claude/projects`,
|
|
34
|
+
`~/.config/claude/projects`, `~/.codex/sessions`); `CLAUDE_CONFIG_DIR` and `CODEX_HOME` override them.
|
|
35
|
+
Output is counts and ratios only. On one maintainer machine (11,454 Claude Code session files, 77 Codex sessions)
|
|
36
|
+
it reported that summing every usage line would overstate Claude Code output tokens 4.19x and Codex output 1.09x.
|
|
37
|
+
|
|
38
|
+
## Tool compatibility
|
|
39
|
+
|
|
40
|
+
| tool | version | result | note |
|
|
41
|
+
|---|---|---|---|
|
|
42
|
+
| ccusage | 20.1.2 | 8/8 | |
|
|
43
|
+
| tokscale | 4.24.0 | 8/8 | |
|
|
44
|
+
| 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) |
|
|
45
|
+
|
|
46
|
+
10 Claude Code and Codex fixture files, 2 of them synthetic; the claude-code#95555 case is one case made of two files
|
|
47
|
+
(`.original` + `.continued`), each with its own `.expected.json`. The tool results above cover the 8 fixtures that
|
|
48
|
+
predate that case. agy is not compared because none of these tools reads its log format. Full numbers: [reports/tool-comparison.md](reports/tool-comparison.md).
|
|
49
|
+
|
|
50
|
+
### Upstream issues & PRs
|
|
51
|
+
|
|
52
|
+
- [anthropics/claude-code#95555](https://github.com/anthropics/claude-code/issues/95555): zeroed usage on compaction copies, reproduced on 2.1.321 and pinned as a fixture (open)
|
|
53
|
+
- [Piebald-AI/splitrail#314](https://github.com/Piebald-AI/splitrail/pull/314): Codex re-emitted `token_count` events (open)
|
|
54
|
+
- [Piebald-AI/splitrail#313](https://github.com/Piebald-AI/splitrail/pull/313): `cleanupPeriodDays` warning (open)
|
|
55
|
+
- [phuryn/claude-usage#191](https://github.com/phuryn/claude-usage/pull/191): retired Opus 4 / 4.1 pricing (open)
|
|
56
|
+
- [kenn-io/agentsview#3666](https://github.com/kenn-io/agentsview/pull/3666): Antigravity CLI headless nudge (open)
|
|
57
|
+
|
|
58
|
+
### Badge for trackers
|
|
59
|
+
|
|
60
|
+
A tracker that passes every fixture can show it:
|
|
61
|
+
|
|
62
|
+
```md
|
|
63
|
+
[](https://github.com/logwright/usagebench/blob/HEAD/reports/tool-comparison.md)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
[](reports/tool-comparison.md)
|
|
67
|
+
|
|
68
|
+
## Quick start
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
npx usagebench --help
|
|
72
|
+
npx usagebench doctor # naive vs deduplicated totals on your logs
|
|
73
|
+
npx usagebench audit # plaintext secrets in your logs, masked (exit 1 if any)
|
|
74
|
+
npx usagebench audit --fix # dry run; add --yes to redact (backup: <file>.usagebench.bak)
|
|
75
|
+
npx usagebench repro --latest --agent claude # repro.jsonl + expected.json + issue.md
|
|
76
|
+
npx usagebench compare # ccusage and tokscale vs the bundled fixtures (scorecard)
|
|
77
|
+
npx usagebench diff --ccusage "npx -y ccusage@latest" # a tracker vs usagebench on your last 7 days
|
|
78
|
+
npx usagebench codex path/to/rollout-....jsonl # totals for one file
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Every command above was run from the packed tarball in an empty folder before release
|
|
82
|
+
(`compare` and `diff` fetch the trackers through npx; usagebench itself does not go online).
|
|
83
|
+
`audit --fix` skips files modified in the last 10 minutes (a session may still be writing them) and re-scans each
|
|
84
|
+
file after redacting; JSON lines stay valid.
|
|
85
|
+
|
|
86
|
+
## Use the fixtures in your tracker's CI (no Node needed)
|
|
87
|
+
|
|
88
|
+
Each release (from 0.2.0) has `fixtures.tar.gz`: `fixtures/` plus `manifest.json` (path, agent, version, sha256 and
|
|
89
|
+
expected totals for every fixture).
|
|
90
|
+
|
|
91
|
+
```sh
|
|
92
|
+
curl -sL https://github.com/logwright/usagebench/releases/latest/download/fixtures.tar.gz | tar xz
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
GitHub Actions:
|
|
96
|
+
|
|
97
|
+
```yaml
|
|
98
|
+
usagebench:
|
|
99
|
+
runs-on: ubuntu-latest
|
|
100
|
+
steps:
|
|
101
|
+
- uses: actions/checkout@v4
|
|
102
|
+
- run: curl -sL https://github.com/logwright/usagebench/releases/latest/download/fixtures.tar.gz | tar xz -C /tmp
|
|
103
|
+
- run: | # place each fixture where your tool looks, run it, compare with manifest.json
|
|
104
|
+
jq -c '.fixtures[] | select(.agent != "agy")' /tmp/manifest.json | while read -r f; do
|
|
105
|
+
echo "$f" | jq -r '.path, .expected' # replace with: run your tracker on /tmp/<path>, compare
|
|
106
|
+
done
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Watch for log-format changes
|
|
110
|
+
|
|
111
|
+
[FORMAT_CHANGES.md](FORMAT_CHANGES.md) lists what changed per agent version. Watch this repo
|
|
112
|
+
(Watch → Custom → Releases) to get notified when a new entry or fixture lands.
|
|
113
|
+
|
|
114
|
+
## Contributing a fixture
|
|
115
|
+
|
|
116
|
+
```sh
|
|
117
|
+
npx usagebench repro --session <id> --agent claude --out my-repro # anonymized; exit 3 if a secret would survive
|
|
118
|
+
python tools/make_fixture.py claude <session.jsonl> fixtures/claude/<version>_<feature>.jsonl # from a clone
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Details in [CONTRIBUTING.md](CONTRIBUTING.md). Pull requests that add fixtures run the schema check, the leak scan
|
|
122
|
+
and the TS vs Python expected-total cross-check; a failure gets one comment saying which file and check failed.
|
|
123
|
+
|
|
124
|
+
## The problem
|
|
125
|
+
|
|
126
|
+
AI coding agents write session logs as JSONL, and those logs hold token usage. Adding up every usage
|
|
127
|
+
number you find gives the wrong answer, and the error is large:
|
|
128
|
+
|
|
129
|
+
- **Claude Code** writes one line per content block (thinking, text, tool call) of a single API response,
|
|
130
|
+
and copies the same `usage` object onto each line. Summing every line overstated output tokens 4.19x
|
|
131
|
+
and cache reads 4.24x in a full `usagebench doctor` run over 11,454 session files (an earlier 30-file sample,
|
|
132
|
+
used to write the dedup rules, gave 2.04x and 1.71x). The fix is to keep one line per
|
|
133
|
+
`(sessionId, message.id)`.
|
|
134
|
+
- **Codex** has two usage streams. `token_usage_record` holds per-response usage, but `compacted`
|
|
135
|
+
records carry a copy of the latest one, so counting both double counts. The older `token_count` events
|
|
136
|
+
carry a cumulative `total_token_usage` plus a per-response `last_token_usage`, and about a third of them
|
|
137
|
+
are re-emitted with an unchanged total; adding `last_token_usage` each time overcounts.
|
|
138
|
+
- **Antigravity CLI** (`agy`, Gemini family) writes per-call tokens on `PLANNER_RESPONSE` steps. It has no
|
|
139
|
+
session id, message id, version, cache-write or reasoning counts in the log.
|
|
140
|
+
|
|
141
|
+
Details and the measurements behind each rule are in [docs/schema_draft.md](docs/schema_draft.md).
|
|
142
|
+
Why two trackers report different totals for the same logs: [docs/why-usage-trackers-disagree.md](docs/why-usage-trackers-disagree.md).
|
|
143
|
+
How Claude Code records tokens (repeated usage blocks, cache pricing, zeroed rows, transcript retention): [docs/claude-code-token-accounting.md](docs/claude-code-token-accounting.md).
|
|
144
|
+
|
|
145
|
+
## What this repo provides
|
|
146
|
+
|
|
147
|
+
- `docs/schema_draft.md`: a draft normalized event schema (`usagebench/0`), one record per billable model
|
|
148
|
+
response, with a field mapping for each agent and the dedup rules.
|
|
149
|
+
- `fixtures/`: small anonymized real logs, each with an `.expected.json` holding naive and deduplicated totals
|
|
150
|
+
(format: [docs/expected.schema.json](docs/expected.schema.json)).
|
|
151
|
+
- `tools/make_fixture.py`: turns a real log into an anonymized fixture and computes its expected totals. It refuses
|
|
152
|
+
(exit 3, no output) when an id field or a kept value holds a key, a path or an e-mail address.
|
|
153
|
+
- `tools/check_leaks.py`: scans fixtures for user names, paths, e-mail addresses, URLs, API keys (Anthropic,
|
|
154
|
+
OpenAI, GitHub, AWS, Google, Slack), private keys, sentences and native ids. CI fails on any hit.
|
|
155
|
+
- `tools/compare_tools.py`: runs ccusage, tokscale and splitrail on every fixture in a throwaway home and writes
|
|
156
|
+
[reports/tool-comparison.md](reports/tool-comparison.md).
|
|
157
|
+
- `tools/build_fixtures.py`: rebuilds every fixture from pinned source paths and checks they come out byte-identical.
|
|
158
|
+
- `parser/`: a reference TypeScript parser with no runtime dependencies.
|
|
159
|
+
|
|
160
|
+
## Fixture format
|
|
161
|
+
|
|
162
|
+
A fixture is the first 200 lines of a real session log, anonymized: keys, record order, value types,
|
|
163
|
+
numbers, booleans, type enums, model names and version strings are kept; ids become consistent fake ids
|
|
164
|
+
(`id_fake000001`, `msg_fake000002`, ...); timestamps are shifted so the first one is `2026-01-01T00:00:00Z`;
|
|
165
|
+
every other string becomes `<redacted>`.
|
|
166
|
+
|
|
167
|
+
Next to each `name.jsonl` sits `name.expected.json`:
|
|
168
|
+
|
|
169
|
+
```json
|
|
170
|
+
{
|
|
171
|
+
"agent": "claude",
|
|
172
|
+
"usage_lines": 120,
|
|
173
|
+
"unique_messages": 61,
|
|
174
|
+
"rule": "claude_last_per_message_id",
|
|
175
|
+
"naive": {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0, "reasoning": 0},
|
|
176
|
+
"dedup": {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0, "reasoning": 0}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`naive` is what summing every usage line gives; `dedup` is the correct total. Codex fixtures also have
|
|
181
|
+
`compacted_copies`, `token_count_events`, `token_count_naive` and `token_count_dedup`. Fixture files are
|
|
182
|
+
named `<cli version>_<feature>.jsonl`; agy logs have no version, so its fixture is `transcript_basic.jsonl`.
|
|
183
|
+
|
|
184
|
+
| fixture | what it pins |
|
|
185
|
+
|---|---|
|
|
186
|
+
| `claude/2.1.334_main` | content blocks of one response repeat the same `usage` (dedup by `message.id`) |
|
|
187
|
+
| `claude/2.1.335_sidechain` | subagent file, `isSidechain: true` on every line |
|
|
188
|
+
| `claude/2.1.335_stream-abort-tool-error` | a response interrupted mid-stream (`stop_reason` null, partial usage) followed by a tool error |
|
|
189
|
+
| `claude/2.1.321_compaction-zeroed-usage.{original,continued}` | two-file case: the continued session repeats a response of the original with all four top-level usage counters 0 (real numbers only in `usage.cache_creation` / `usage.iterations[0]`, claude-code#95555); together they count the original once |
|
|
190
|
+
| `claude/synthetic_duplicate-id-partial-usage` | synthetic: first line of a message has a partial usage snapshot, the last one the final usage |
|
|
191
|
+
| `codex/0.160.0_compacted` | `compacted` copies of usage records; `token_count` events re-emitted with an unchanged total |
|
|
192
|
+
| `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 |
|
|
193
|
+
| `codex/0.173.0-alpha.4.1_basic` | plain session with `token_usage_record` and `token_count` |
|
|
194
|
+
| `codex/synthetic_total-reset` | synthetic: re-emitted event, `info: null`, and a cumulative total that goes down |
|
|
195
|
+
| `agy/transcript_basic` | antigravity-cli `PLANNER_RESPONSE` steps |
|
|
196
|
+
|
|
197
|
+
`synthetic_*` fixtures are hand-written because the case was not found in real logs; their `.expected.json`
|
|
198
|
+
says `"synthetic": true`. Everything else is cut from a real log.
|
|
199
|
+
|
|
200
|
+
## Using the fixtures in another tool's CI
|
|
201
|
+
|
|
202
|
+
Each fixture is a self-contained log. Copy it where your tool looks (for example
|
|
203
|
+
`$CLAUDE_CONFIG_DIR/projects/x/<sessionId>.jsonl` or `$CODEX_HOME/sessions/2026/01/01/rollout-...jsonl`), run
|
|
204
|
+
your tool, and compare with `dedup` (Claude) or `token_count_dedup` (Codex, if you read `token_count` events).
|
|
205
|
+
`tools/compare_tools.py` does exactly this for ccusage, tokscale and splitrail.
|
|
206
|
+
|
|
207
|
+
## Usage
|
|
208
|
+
|
|
209
|
+
From npm (the package is `usagebench`, the command is `usagebench`):
|
|
210
|
+
|
|
211
|
+
```sh
|
|
212
|
+
npx usagebench claude path/to/session.jsonl
|
|
213
|
+
npx usagebench codex path/to/rollout-....jsonl
|
|
214
|
+
npm install usagebench # then: import { parse, usage } from "usagebench"
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
From a clone, Node 23.6 or newer runs the TypeScript source directly (built-in type stripping):
|
|
218
|
+
|
|
219
|
+
```sh
|
|
220
|
+
cd parser
|
|
221
|
+
node src/cli.ts claude path/to/session.jsonl
|
|
222
|
+
node src/cli.ts codex path/to/rollout-....jsonl
|
|
223
|
+
node src/cli.ts agy path/to/transcript.jsonl
|
|
224
|
+
npm test # runs the parser on every fixture and compares with .expected.json
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
CI (`.github/workflows/ci.yml`) runs the build, `npm test`, `tools/check_leaks.py fixtures`,
|
|
228
|
+
`tools/test_tools.py` (fault injection for the scanner and the anonymizer) and `tools/verify_independent.py`.
|
|
229
|
+
|
|
230
|
+
From code:
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import { parse, usage } from "./parser/src/index.ts";
|
|
234
|
+
const records = parse("claude", text, { sourceFile: "session.jsonl" });
|
|
235
|
+
usage("claude", records, { dedup: true }); // {input, output, cache_write, cache_read, reasoning}
|
|
236
|
+
usage("codex", records, { dedup: true, source: "token_count" }); // Codex fallback path
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`npm test` writes `parser/e2e_result.json` with the result for each fixture.
|
|
240
|
+
|
|
241
|
+
## Known gaps
|
|
242
|
+
|
|
243
|
+
- Codex `tokens.input` is the raw `input_tokens`, which already includes `cache_read` (ccusage, tokscale and
|
|
244
|
+
splitrail all treat it that way; issue #1). Uncached input = `input - cache_read`.
|
|
245
|
+
- agy: whether `input_tokens` includes `cache_read_tokens` is unknown; the session id must be passed in
|
|
246
|
+
(it comes from the `brain/<id>` folder name).
|
|
247
|
+
- Fixtures cut at 200 lines can end on a `token_usage_record` whose matching `token_count` event was cut off,
|
|
248
|
+
so `dedup` and `token_count_dedup` differ slightly in `codex/0.160.0_compacted`.
|
|
249
|
+
|
|
250
|
+
## License
|
|
251
|
+
|
|
252
|
+
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,108 @@
|
|
|
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, zeroedTop } 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
|
+
// zeroed copies (claude-code#95555) bill nothing and are not counted as messages (as in make_fixture.py)
|
|
87
|
+
const keys = new Set(recs.filter((x) => !zeroedTop(x.tokens)).map((x) => JSON.stringify([x.session_id, x.message_id])));
|
|
88
|
+
Object.assign(res, { usage_lines: recs.length, unique_messages: keys.size, rule: "claude_last_per_message_id",
|
|
89
|
+
is_sidechain: recs.length > 0 && recs.every((x) => x.is_sidechain) });
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
const meta = text.split(/\r?\n/).filter((l) => l.trim()).map((l) => JSON.parse(l))
|
|
93
|
+
.find((o) => o.type === "session_meta")?.payload ?? {};
|
|
94
|
+
const tur = recs.filter((x) => x.raw_type === "token_usage_record");
|
|
95
|
+
Object.assign(res, {
|
|
96
|
+
is_sidechain: meta.source !== null && typeof meta.source === "object" && "subagent" in meta.source,
|
|
97
|
+
parent_session: Boolean(meta.parent_thread_id || meta.forked_from_id),
|
|
98
|
+
usage_lines: tur.length, unique_messages: new Set(tur.map((x) => x.message_id)).size,
|
|
99
|
+
compacted_copies: recs.filter((x) => x.raw_type.startsWith("compacted")).length,
|
|
100
|
+
rule: "codex_record_by_response_id",
|
|
101
|
+
token_count_events: recs.filter((x) => x.raw_type === "event_msg/token_count").length,
|
|
102
|
+
token_count_naive: r.token_count_naive, token_count_dedup: r.token_count_dedup,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
res.naive = r.naive;
|
|
106
|
+
res.dedup = r.dedup;
|
|
107
|
+
return res;
|
|
108
|
+
}
|
package/dist/audit.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function audit(args: string[]): number;
|
package/dist/audit.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
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
|
+
// Files are handled one at a time and read line by line (no size cap, no whole-file text kept in memory).
|
|
6
|
+
import { closeSync, copyFileSync, existsSync, openSync, readSync, renameSync, rmSync, writeSync } from "node:fs";
|
|
7
|
+
import { StringDecoder } from "node:string_decoder";
|
|
8
|
+
import { logFiles, progress, LOG_AGENTS } from "./logs.js";
|
|
9
|
+
import { findSecrets } from "./secrets.js";
|
|
10
|
+
const ACTIVE_MS = 10 * 60 * 1000; // a file written in the last 10 minutes may belong to a running session
|
|
11
|
+
// Lines of a file without the "\n" ("\r" stays on the line); `last` is true for a final line with no "\n".
|
|
12
|
+
function* lines(path) {
|
|
13
|
+
const fd = openSync(path, "r"), buf = Buffer.alloc(4 << 20), dec = new StringDecoder("utf8");
|
|
14
|
+
let rest = "";
|
|
15
|
+
try {
|
|
16
|
+
for (let n; (n = readSync(fd, buf, 0, buf.length, null)) > 0;) {
|
|
17
|
+
const parts = (rest + dec.write(buf.subarray(0, n))).split("\n");
|
|
18
|
+
rest = parts.pop();
|
|
19
|
+
for (const p of parts)
|
|
20
|
+
yield { text: p, last: false };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
closeSync(fd);
|
|
25
|
+
}
|
|
26
|
+
rest += dec.end();
|
|
27
|
+
if (rest)
|
|
28
|
+
yield { text: rest, last: true };
|
|
29
|
+
}
|
|
30
|
+
// Hits per line number (1-based); only lines with a real (non-placeholder) secret are kept.
|
|
31
|
+
function scan(path) {
|
|
32
|
+
const hits = new Map();
|
|
33
|
+
let placeholders = 0, ln = 0;
|
|
34
|
+
for (const { text } of lines(path)) {
|
|
35
|
+
ln++;
|
|
36
|
+
const all = findSecrets(text), real = all.filter((h) => !h.placeholder);
|
|
37
|
+
placeholders += all.length - real.length;
|
|
38
|
+
if (real.length)
|
|
39
|
+
hits.set(ln, real);
|
|
40
|
+
}
|
|
41
|
+
return { hits, placeholders };
|
|
42
|
+
}
|
|
43
|
+
// Replace each hit with [REDACTED:<type>], widened so it never cuts a JSON escape (\" \\ \n \uXXXX) in half;
|
|
44
|
+
// returns null if the line would stop being valid JSON.
|
|
45
|
+
function redactLine(line, hits) {
|
|
46
|
+
const esc = [...line.matchAll(/\\(?:u[0-9a-fA-F]{4}|[^])/g)].map((m) => [m.index, m.index + m[0].length]);
|
|
47
|
+
let out = line;
|
|
48
|
+
for (const h of [...hits].sort((a, b) => b.index - a.index)) {
|
|
49
|
+
let s = h.index, e = h.index + h.length;
|
|
50
|
+
for (const [a, b] of esc) {
|
|
51
|
+
if (a < s && s < b)
|
|
52
|
+
s = a;
|
|
53
|
+
if (a < e && e < b)
|
|
54
|
+
e = b;
|
|
55
|
+
}
|
|
56
|
+
out = out.slice(0, s) + `[REDACTED:${h.type}]` + out.slice(e);
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
JSON.parse(out);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
export function audit(args) {
|
|
67
|
+
const fix = args.includes("--fix"), yes = args.includes("--yes");
|
|
68
|
+
const files = LOG_AGENTS.flatMap((a) => logFiles(a).map((f) => ({ ...f, agent: a })));
|
|
69
|
+
console.log("usagebench audit: read-only scan" + (fix ? (yes ? " + redaction (--fix --yes)" : " (--fix dry run: nothing is written)") : "")
|
|
70
|
+
+ `; ${files.length} log files`);
|
|
71
|
+
const byType = new Map();
|
|
72
|
+
let placeholders = 0, skipped = 0, findings = 0, n = 0, fixed = 0, failed = 0;
|
|
73
|
+
const prog = progress(files.length);
|
|
74
|
+
for (const f of files) {
|
|
75
|
+
prog.tick(++n);
|
|
76
|
+
let r;
|
|
77
|
+
try {
|
|
78
|
+
r = scan(f.path);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
skipped++;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
placeholders += r.placeholders;
|
|
85
|
+
if (!r.hits.size)
|
|
86
|
+
continue;
|
|
87
|
+
let count = 0;
|
|
88
|
+
for (const [ln, hs] of r.hits)
|
|
89
|
+
for (const h of hs) {
|
|
90
|
+
count++;
|
|
91
|
+
findings++;
|
|
92
|
+
byType.set(h.type, (byType.get(h.type) ?? 0) + 1);
|
|
93
|
+
console.log(` ${f.agent}:${f.rel}:${ln} ${h.type} ${h.preview}`);
|
|
94
|
+
}
|
|
95
|
+
if (!fix)
|
|
96
|
+
continue;
|
|
97
|
+
// this file now, before the next one is read
|
|
98
|
+
const tag = `${f.rel}: ${count} secret(s)`;
|
|
99
|
+
if (Date.now() - f.mtimeMs < ACTIVE_MS) {
|
|
100
|
+
console.log(` skip (modified < 10 min ago, session may be active) ${tag}`);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const bak = f.path + ".usagebench.bak", tmp = f.path + ".usagebench.tmp";
|
|
104
|
+
if (existsSync(bak)) {
|
|
105
|
+
console.log(` skip (backup already exists) ${tag}`);
|
|
106
|
+
failed++;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
let broken = false, fd = null;
|
|
110
|
+
try {
|
|
111
|
+
if (yes)
|
|
112
|
+
fd = openSync(tmp, "w");
|
|
113
|
+
let ln = 0;
|
|
114
|
+
for (const { text, last } of lines(f.path)) {
|
|
115
|
+
const hs = r.hits.get(++ln);
|
|
116
|
+
const out = hs ? redactLine(text, hs) : text;
|
|
117
|
+
if (out === null) {
|
|
118
|
+
broken = true;
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
if (fd !== null)
|
|
122
|
+
writeSync(fd, last ? out : out + "\n");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch (e) {
|
|
126
|
+
if (fd !== null)
|
|
127
|
+
closeSync(fd);
|
|
128
|
+
rmSync(tmp, { force: true });
|
|
129
|
+
console.log(` failed ${tag}: ${e.message.split("\n")[0]}`);
|
|
130
|
+
failed++;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (fd !== null)
|
|
134
|
+
closeSync(fd);
|
|
135
|
+
if (broken) {
|
|
136
|
+
rmSync(tmp, { force: true });
|
|
137
|
+
console.log(` skip (redaction would break JSON) ${tag}`);
|
|
138
|
+
failed++;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (!yes) {
|
|
142
|
+
console.log(` would redact ${tag}`);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
copyFileSync(f.path, bak);
|
|
147
|
+
renameSync(tmp, f.path);
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
rmSync(tmp, { force: true });
|
|
151
|
+
console.log(` failed ${tag}: ${e.message.split("\n")[0]}`);
|
|
152
|
+
failed++;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const again = scan(f.path).hits.size;
|
|
156
|
+
if (again) {
|
|
157
|
+
copyFileSync(bak, f.path);
|
|
158
|
+
rmSync(bak, { force: true });
|
|
159
|
+
console.log(` restored original, re-scan still found secrets on ${again} line(s) ${tag}`);
|
|
160
|
+
failed++;
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
fixed++;
|
|
164
|
+
console.log(` redacted ${tag} (original kept at ${f.rel}.usagebench.bak; delete it once checked)`);
|
|
165
|
+
}
|
|
166
|
+
prog.done();
|
|
167
|
+
console.log(`\nfindings: ${findings}` + (findings ? ` (${[...byType].map(([t, c]) => `${t} ${c}`).join(", ")})` : "")
|
|
168
|
+
+ `; ignored as example/placeholder values: ${placeholders}` + (skipped ? `; files skipped (unreadable): ${skipped}` : ""));
|
|
169
|
+
if (!fix || !findings)
|
|
170
|
+
return findings ? 1 : 0;
|
|
171
|
+
console.log(yes ? `redacted files: ${fixed}, failed or skipped: ${failed}` : "dry run: rerun with --fix --yes to redact");
|
|
172
|
+
return 1;
|
|
173
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const BIP39_ENGLISH: string[];
|