big-spender 0.3.0 → 0.6.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.
package/README.md CHANGED
@@ -9,6 +9,15 @@ snapshot into that device's stored history, adds the devices together, and serve
9
9
  JSON and as a plain HTML page. You can also embed the server side in your own app and draw the
10
10
  numbers however you like.
11
11
 
12
+ ![A 30-day bar chart of daily AI coding cost, each bar stacked by machine (MacBook, VPS, Home agent), with a $3,148 total](docs/usage-card.png)
13
+
14
+ The card above is on [jeffreyyvdb.com](https://jeffreyyvdb.com). The site mounts
15
+ `big-spender/server` and draws its own chart from the summary, here 30 days of daily cost stacked
16
+ by machine.
17
+
18
+ Cursor keeps usage on its servers, so one machine can also read your Cursor account's usage from
19
+ Cursor's API and send it as its own device. See [Cursor](#cursor).
20
+
12
21
  The collector has no dependencies and needs Node 20 or newer. The package depends on `zod` only.
13
22
 
14
23
  ## What leaves the machine
@@ -23,9 +32,19 @@ nothing is bucketed finer than a UTC day: 7, 30 and 90 days are per day, all tim
23
32
  (Monday UTC). Device ids are published only if you leave
24
33
  `unknownDevices` at its default, see [Device names and colours](#device-names-and-colours).
25
34
 
35
+ Usage limit windows (see [Usage limits](#usage-limits)) are sent as a window name, its reset time,
36
+ a peak percentage and, when a request was refused, the time of the first refusal. They never name a
37
+ device, and `/api/usage/limits` publishes them per UTC day only.
38
+
26
39
  Before the first send you can see exactly what would leave the machine with
27
40
  `big-spender push <device> --dry-run`.
28
41
 
42
+ With [Cursor](#cursor) set up, the collector also calls Cursor's API with your Cursor API key. It
43
+ sends Cursor only the key and a date range. From the answer it keeps model names, token counts,
44
+ cost and timestamps, the same as from local logs. Conversation ids are hashed on the device and
45
+ only counted, like session ids. Everything else in the answer, such as your Cursor user id, is
46
+ dropped.
47
+
29
48
  ## Quick start
30
49
 
31
50
  ### 1. Run the server
@@ -84,16 +103,59 @@ Remove the schedule with `big-spender uninstall`. The env file and the state are
84
103
 
85
104
  `big-spender status` prints the last 24 hours on this machine and sends nothing.
86
105
 
106
+ ### Cursor
107
+
108
+ Cursor keeps usage on its servers, per account, so the collector reads it from Cursor's API
109
+ instead of local files. The server must run the big-spender release that added Cursor, or newer.
110
+ An older one answers the `cursor` snapshot with `422`. Set it up on one machine only:
111
+
112
+ ```sh
113
+ npx big-spender install --device laptop --cursor
114
+ ```
115
+
116
+ Only the account's personal usage is read. Usage billed to a Cursor team is not read yet.
117
+
118
+ It asks for a Cursor user API key with a hidden prompt (or reads `BIG_SPENDER_CURSOR_API_KEY`) and
119
+ adds it to the env file. Create the key in your Cursor dashboard. Running `install` again without
120
+ `--cursor` keeps the key; with `--cursor` it asks for a new one.
121
+
122
+ Cursor usage is sent as its own device, `cursor`, not as the machine that reads it, because one
123
+ account covers every machine you use Cursor on. If you move the key to another machine, remove it
124
+ from the first one, or both would send the same usage. Add `cursor` to your
125
+ [devices file](#device-names-and-colours) to give it a name and colour.
126
+
127
+ The first run sends all of the account's history that has token counts. Cursor billed per request
128
+ until about June 2025 and reported no tokens for those events, so they are skipped. Later runs
129
+ send the last 90 days, and the server keeps the older days. The full history is sent again until a
130
+ server has stored it, so a failed first run, a new ingest URL or a new API key gets it on the next run.
131
+
132
+ Cost is Cursor's own price for each event (`totalCents`), not LiteLLM's. Cursor's model names
133
+ mostly don't match LiteLLM's, and models such as Composer have no API price at all. Cursor reports
134
+ one price per event, so the split over input, cache read, cache write and output uses fixed ratios
135
+ of 1, 0.1, 1.25 and 5. The total is Cursor's, up to rounding each part to a millionth of a dollar.
136
+
137
+ A Cursor failure, such as a revoked key, does not stop the machine's own snapshot. The run still
138
+ posts it, then exits with an error that names Cursor. That includes a Cursor answer with fewer
139
+ events than it counted: posting it would replace complete days on the server with partial ones. The
140
+ device id `cursor` is reserved for this snapshot, so no machine can report under it. To switch to
141
+ another Cursor account, stop the server, run `big-spender install --cursor` with the new key, remove
142
+ `cursor.json` from the server's data directory, and start the server again. The install's own first
143
+ run fails while the server is down, which is expected. The next run sends the new account's full
144
+ history. The server keeps snapshots in memory, and the old key keeps posting until it is replaced,
145
+ so in any other order the two accounts' histories can be merged. `big-spender push` never reads
146
+ Cursor.
147
+
87
148
  ## The server
88
149
 
89
150
  `big-spender serve` is a small `node:http` server:
90
151
 
91
- | Route | What it does |
92
- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
93
- | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
94
- | `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
95
- | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models. No JavaScript, no external assets, light and dark. |
96
- | `GET /healthz` | `ok`, for load balancers and Docker. |
152
+ | Route | What it does |
153
+ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
154
+ | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
155
+ | `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
156
+ | `GET /api/usage/limits` | Subscription limit hits per provider and window over the last 90 UTC days, per day, same cache header. See [Usage limits](#usage-limits). |
157
+ | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models, limit hits. No JavaScript, no external assets, light and dark. |
158
+ | `GET /healthz` | `ok`, for load balancers and Docker. |
97
159
 
98
160
  Configuration comes from flags or environment variables (flags win):
99
161
 
@@ -177,11 +239,52 @@ Next.js route handler (`export const POST = (request: Request) => bs.ingest(requ
177
239
  `{ ok, deviceId, rows, result: 'stored' | 'stale' }`).
178
240
  - `summary(now?)`: the merged totals for every range. The result is cached for five minutes and
179
241
  recomputed right after an ingest.
242
+ - `limits(now?)`: the [usage limit](#usage-limits) summary, cached the same way.
180
243
 
181
- The module also exports `summarize(snapshots, now, config)`, the snapshot schema
182
- (`usageSnapshotSchema`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
244
+ The module also exports `summarize(snapshots, now, config)`, `summarizeLimits(snapshots, now)`, the
245
+ snapshot schema (`usageSnapshotSchema`, `limitWindowSchema`, `MAX_LIMIT_WINDOWS`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
183
246
  own storage or charts.
184
247
 
248
+ ## Usage limits
249
+
250
+ Besides cost, the collector records when you run out of your Claude and Codex subscription
251
+ allowance, so you can judge whether a plan fits how you work. It reads only what the agents already
252
+ write to their local logs. It reads no credentials and makes no new network calls.
253
+
254
+ - **Claude Code.** A refused request is logged as an `assistant` line with `error: "rate_limit"`
255
+ and a `quotaLimits` object that names the window (`five_hour`, `seven_day`, a model-specific
256
+ weekly window such as `seven_day_opus`) and when it resets. Retries repeat the line, so one
257
+ blocked window becomes one record. Claude Code logs nothing when a request is allowed, so
258
+ utilisation below 100% is unknown for Claude.
259
+ - **Codex.** `token_count` events carry `rate_limits` with the used percentage and reset time of the
260
+ 5-hour window (`five_hour`, 300 minutes) and the weekly window (`seven_day`, 10080 minutes). Codex
261
+ is the only source of utilisation below 100%. A window counts as hit when its share reaches 100%.
262
+
263
+ A record is one window instance, identified by provider, window name and reset time rounded down
264
+ to the minute. Reports whose resets are at most two minutes apart are the same window, because one
265
+ window's reported reset can drift by a few seconds. It holds the peak percentage seen and the time of the first refusal. Limits belong
266
+ to the account, not the machine, so merging keeps the highest peak and the earliest refusal, and
267
+ two machines that report the same window count once. Records are kept for 90 days on the collector and up to 5,000 windows on the
268
+ server, like day rows.
269
+
270
+ `GET /api/usage/limits` returns, for each provider and window over the last 90 UTC days, how many
271
+ window instances were seen, how many were hit, the hours locked out (first refusal until reset),
272
+ the day of the last hit and a per-day series. Claude can move a window's reset later while you are
273
+ blocked, so a refusal before the previous reset extends that lockout instead of counting a new hit. A window counts on the day of its first refusal, or
274
+ of its reset when it was never refused; a window that is still open counts on today with its peak
275
+ so far. It follows the same privacy rule as the rest: nothing
276
+ finer than a UTC day, no device names, no report times. It is separate from `/api/usage`, whose
277
+ shape did not change. `big-spender status` also lists the limits hit in the last 7 days, to the
278
+ minute, because that output never leaves the machine.
279
+
280
+ Polling the Anthropic or OpenAI usage endpoints would show utilisation for Claude too, but it needs
281
+ your OAuth credentials, so it is not done. The record shape already has room for it: a polled
282
+ percentage is just another peak for the same window.
283
+
284
+ An older server rejects the unknown `limits` field with a 422. The collector and `push` then send
285
+ the snapshot again without it and print a warning on each run, so usage keeps arriving. Upgrade the server to store
286
+ limits.
287
+
185
288
  ## Push by hand
186
289
 
187
290
  For a machine that should only report now and then, or where you would rather not store a token:
@@ -207,6 +310,9 @@ big-spender status # last 24 hours on this machine, not
207
310
  node ~/.local/share/big-spender/collector.mjs --dry-run # the full snapshot JSON, nothing sent
208
311
  ```
209
312
 
313
+ With [Cursor](#cursor) set up, `--dry-run` reads Cursor too and prints the `cursor` snapshot after
314
+ this machine's.
315
+
210
316
  Compare with [ccusage](https://github.com/ryoppippi/ccusage) on the same machine. Use the `claude`
211
317
  subcommand: plain `npx ccusage` also adds other CLIs that the collector does not read. Claude Code
212
318
  tokens and cost should match per model:
@@ -221,24 +327,44 @@ about 15 to 20 percent less.
221
327
 
222
328
  ## How it counts
223
329
 
224
- | Source | Files | Notes |
225
- | ----------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
226
- | Claude Code | `~/.claude/projects/**/*.jsonl`, `~/.config/claude/projects`, `$CLAUDE_CONFIG_DIR/projects` | `assistant` lines; de-duplicated by `message.id` + `requestId` (one API response is logged once per content block, and resumed sessions copy history). `<synthetic>` skipped; subagent logs included. Some Claude Code versions (2.1.293 to 2.1.310) log a partial output count on a message's first line and the final count on a later line; a later line that reports more output adds the difference. |
227
- | Codex | `~/.codex/sessions/**/rollout-*.jsonl`, `$CODEX_HOME/sessions` | `event_msg` / `token_count` with `info.last_token_usage`; skipped when `total_token_usage` did not change. Model from the latest `turn_context`. `cached_input_tokens` is part of `input_tokens`; reasoning is part of `output_tokens`. |
228
-
229
- **Pricing.** LiteLLM `model_prices_and_context_window.json`, cached for 24 hours in
230
- `~/.cache/big-spender/`. Lookup tries the exact model, then `anthropic/` or `openai/` prefixes, then
231
- without a date suffix. Unknown models count with cost 0 and log a warning. Long-context tiers
330
+ | Source | Files | Notes |
331
+ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
332
+ | Claude Code | `~/.claude/projects/**/*.jsonl`, `~/.config/claude/projects`, `$CLAUDE_CONFIG_DIR/projects` | `assistant` lines; de-duplicated by `message.id` + `requestId` (one API response is logged once per content block, and resumed sessions copy history). `<synthetic>` skipped; subagent logs included. Some Claude Code versions (2.1.293 to 2.1.310) log a partial output count on a message's first line and the final count on a later line; a later line that reports more output adds the difference. |
333
+ | Codex | `~/.codex/sessions/**/rollout-*.jsonl`, `$CODEX_HOME/sessions` | `event_msg` / `token_count` with `info.last_token_usage`; skipped when `total_token_usage` did not change. Model from the latest `turn_context`. `cached_input_tokens` is part of `input_tokens`; reasoning is part of `output_tokens`. |
334
+ | Cursor | Cursor's API, `DashboardService/GetFilteredUsageEvents`, with `BIG_SPENDER_CURSOR_API_KEY` | Events with token counts only. Cost is Cursor's `totalCents`. Events have no unique id and pages can overlap, so a time window with more than 1,000 events is split in half instead of paged. `cacheWriteTokens` count as 5-minute cache writes. Sessions are hashed `conversationId`s. Model names are lowercased, and anything outside `a-z 0-9 . _ : @ -` becomes `-`. |
335
+ | pi | `~/.pi/agent/sessions/**/*.jsonl`, `$PI_CODING_AGENT_DIR/sessions`, `$PI_CODING_AGENT_SESSION_DIR`, `$PI_AGENT_DIR` (comma-separated, as in ccusage) | Assistant `message` entries with `usage`; `input` excludes cached tokens, reasoning is part of `output`, and `cacheWrite` counts as 5-minute writes except its `cacheWrite1h` part. Calls with no tokens (aborted, failed before a retry) are skipped, and a call with only `totalTokens` counts it as output. A fork's file starts with a copy of its parent's calls up to the fork; those leading calls are skipped when the parent file has them. ccusage looks only at the parent's current branch, so it counts the copy again once the parent moves to another branch. A model id that is a file path (absolute, a `file://` or `host:/` URL, or ending in `.gguf` and similar) is reduced to its file name. `subagent-artifacts/` transcripts are skipped. Cost is LiteLLM's, not the cost pi stores. |
336
+
337
+ **Pricing.** Claude Code, Codex and pi use LiteLLM `model_prices_and_context_window.json`, cached
338
+ for 24 hours in `~/.cache/big-spender/`. Each source lists the LiteLLM keys to try for a model. Claude
339
+ Code and Codex try the exact model, then the `anthropic/` or `openai/` prefix, then without a date
340
+ suffix. pi tries the LiteLLM prefixes of the providers pi supports too (`openrouter/`, `fireworks_ai/`,
341
+ `groq/` and others). For an OpenRouter id such as `anthropic/claude-sonnet-4.5` it then tries
342
+ `claude-sonnet-4.5` and `claude-sonnet-4-5`. Unknown models count with cost 0 and log a warning.
343
+ Long-context tiers
232
344
  (`*_above_<N>k_tokens`) are applied per request; 1-hour cache writes use
233
345
  `cache_creation_input_token_cost_above_1hr`. Cache savings are cache-read tokens times (input price
234
346
  minus cache-read price).
235
347
 
348
+ **Adding a provider.** Add an entry to `SOURCES` in `src/collector.mjs`, the provider id to
349
+ `PROVIDERS` in `src/schema.ts`, a row to the table above, and a test with a fixture log. The entry
350
+ says where the data lives, how it is read, and which LiteLLM keys price its models. Append-only JSONL
351
+ uses `jsonlReader`, which parses only new bytes. Other formats are read whole on every run and skip
352
+ what they counted before through `state.seen`. A SQLite file opens with `openSqlite`, which skips the
353
+ source with one warning on a Node without `node:sqlite`. Add the matching ccusage agent to `AGENTS`
354
+ in `scripts/parity-ccusage.mjs` and run `node scripts/parity-ccusage.mjs <provider>`: tokens must
355
+ match ccusage exactly. `node scripts/parity-ref.mjs` shows that the other providers did not change.
356
+ Deploy the server before the collectors, because a server rejects rows from a provider it does not
357
+ list.
358
+
236
359
  **Incremental.** `~/.cache/big-spender/state.json` keeps per-file byte offsets plus the hourly
237
360
  aggregates, so each run parses only new bytes but still sends the full 90-day snapshot. Rows older
238
361
  than 7 days are rolled up to daily rows. Because the aggregates live in the state file, usage stays
239
362
  counted even after Claude Code deletes old session logs. `--reset` rebuilds from the logs that still
240
363
  exist, so avoid it unless the state is corrupt.
241
364
 
365
+ Limit windows live in the same state file. The first run after the update re-reads every log once
366
+ to pick up limit lines older runs skipped; it adds no usage.
367
+
242
368
  State from an older collector is fixed in place on the first run of a newer one (for example, one
243
369
  re-read of the Claude logs to pick up missed output tokens), so updating never needs `--reset`.
244
370