big-spender 0.3.0 → 0.5.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 +85 -8
- package/dist/collector.mjs +589 -88
- package/dist/install.d.ts +1 -1
- package/dist/install.js +23 -5
- package/dist/push.d.ts +1 -1
- package/dist/push.js +7 -3
- package/dist/schema.d.ts +14 -1
- package/dist/schema.js +8 -4
- package/dist/server/ingest.js +9 -2
- package/dist/summary.js +4 -3
- package/package.json +1 -1
- package/templates/env.example +3 -0
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
|
+

|
|
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
|
|
@@ -26,6 +35,12 @@ nothing is bucketed finer than a UTC day: 7, 30 and 90 days are per day, all tim
|
|
|
26
35
|
Before the first send you can see exactly what would leave the machine with
|
|
27
36
|
`big-spender push <device> --dry-run`.
|
|
28
37
|
|
|
38
|
+
With [Cursor](#cursor) set up, the collector also calls Cursor's API with your Cursor API key. It
|
|
39
|
+
sends Cursor only the key and a date range. From the answer it keeps model names, token counts,
|
|
40
|
+
cost and timestamps, the same as from local logs. Conversation ids are hashed on the device and
|
|
41
|
+
only counted, like session ids. Everything else in the answer, such as your Cursor user id, is
|
|
42
|
+
dropped.
|
|
43
|
+
|
|
29
44
|
## Quick start
|
|
30
45
|
|
|
31
46
|
### 1. Run the server
|
|
@@ -84,6 +99,48 @@ Remove the schedule with `big-spender uninstall`. The env file and the state are
|
|
|
84
99
|
|
|
85
100
|
`big-spender status` prints the last 24 hours on this machine and sends nothing.
|
|
86
101
|
|
|
102
|
+
### Cursor
|
|
103
|
+
|
|
104
|
+
Cursor keeps usage on its servers, per account, so the collector reads it from Cursor's API
|
|
105
|
+
instead of local files. The server must run the big-spender release that added Cursor, or newer.
|
|
106
|
+
An older one answers the `cursor` snapshot with `422`. Set it up on one machine only:
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
npx big-spender install --device laptop --cursor
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Only the account's personal usage is read. Usage billed to a Cursor team is not read yet.
|
|
113
|
+
|
|
114
|
+
It asks for a Cursor user API key with a hidden prompt (or reads `BIG_SPENDER_CURSOR_API_KEY`) and
|
|
115
|
+
adds it to the env file. Create the key in your Cursor dashboard. Running `install` again without
|
|
116
|
+
`--cursor` keeps the key; with `--cursor` it asks for a new one.
|
|
117
|
+
|
|
118
|
+
Cursor usage is sent as its own device, `cursor`, not as the machine that reads it, because one
|
|
119
|
+
account covers every machine you use Cursor on. If you move the key to another machine, remove it
|
|
120
|
+
from the first one, or both would send the same usage. Add `cursor` to your
|
|
121
|
+
[devices file](#device-names-and-colours) to give it a name and colour.
|
|
122
|
+
|
|
123
|
+
The first run sends all of the account's history that has token counts. Cursor billed per request
|
|
124
|
+
until about June 2025 and reported no tokens for those events, so they are skipped. Later runs
|
|
125
|
+
send the last 90 days, and the server keeps the older days. The full history is sent again until a
|
|
126
|
+
server has stored it, so a failed first run, a new ingest URL or a new API key gets it on the next run.
|
|
127
|
+
|
|
128
|
+
Cost is Cursor's own price for each event (`totalCents`), not LiteLLM's. Cursor's model names
|
|
129
|
+
mostly don't match LiteLLM's, and models such as Composer have no API price at all. Cursor reports
|
|
130
|
+
one price per event, so the split over input, cache read, cache write and output uses fixed ratios
|
|
131
|
+
of 1, 0.1, 1.25 and 5. The total is Cursor's, up to rounding each part to a millionth of a dollar.
|
|
132
|
+
|
|
133
|
+
A Cursor failure, such as a revoked key, does not stop the machine's own snapshot. The run still
|
|
134
|
+
posts it, then exits with an error that names Cursor. That includes a Cursor answer with fewer
|
|
135
|
+
events than it counted: posting it would replace complete days on the server with partial ones. The
|
|
136
|
+
device id `cursor` is reserved for this snapshot, so no machine can report under it. To switch to
|
|
137
|
+
another Cursor account, stop the server, run `big-spender install --cursor` with the new key, remove
|
|
138
|
+
`cursor.json` from the server's data directory, and start the server again. The install's own first
|
|
139
|
+
run fails while the server is down, which is expected. The next run sends the new account's full
|
|
140
|
+
history. The server keeps snapshots in memory, and the old key keeps posting until it is replaced,
|
|
141
|
+
so in any other order the two accounts' histories can be merged. `big-spender push` never reads
|
|
142
|
+
Cursor.
|
|
143
|
+
|
|
87
144
|
## The server
|
|
88
145
|
|
|
89
146
|
`big-spender serve` is a small `node:http` server:
|
|
@@ -207,6 +264,9 @@ big-spender status # last 24 hours on this machine, not
|
|
|
207
264
|
node ~/.local/share/big-spender/collector.mjs --dry-run # the full snapshot JSON, nothing sent
|
|
208
265
|
```
|
|
209
266
|
|
|
267
|
+
With [Cursor](#cursor) set up, `--dry-run` reads Cursor too and prints the `cursor` snapshot after
|
|
268
|
+
this machine's.
|
|
269
|
+
|
|
210
270
|
Compare with [ccusage](https://github.com/ryoppippi/ccusage) on the same machine. Use the `claude`
|
|
211
271
|
subcommand: plain `npx ccusage` also adds other CLIs that the collector does not read. Claude Code
|
|
212
272
|
tokens and cost should match per model:
|
|
@@ -221,18 +281,35 @@ about 15 to 20 percent less.
|
|
|
221
281
|
|
|
222
282
|
## How it counts
|
|
223
283
|
|
|
224
|
-
| Source | Files
|
|
225
|
-
| ----------- |
|
|
226
|
-
| Claude Code | `~/.claude/projects/**/*.jsonl`, `~/.config/claude/projects`, `$CLAUDE_CONFIG_DIR/projects`
|
|
227
|
-
| Codex | `~/.codex/sessions/**/rollout-*.jsonl`, `$CODEX_HOME/sessions`
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
284
|
+
| Source | Files | Notes |
|
|
285
|
+
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
286
|
+
| 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. |
|
|
287
|
+
| 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`. |
|
|
288
|
+
| 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 `-`. |
|
|
289
|
+
| 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. |
|
|
290
|
+
|
|
291
|
+
**Pricing.** Claude Code, Codex and pi use LiteLLM `model_prices_and_context_window.json`, cached
|
|
292
|
+
for 24 hours in `~/.cache/big-spender/`. Each source lists the LiteLLM keys to try for a model. Claude
|
|
293
|
+
Code and Codex try the exact model, then the `anthropic/` or `openai/` prefix, then without a date
|
|
294
|
+
suffix. pi tries the LiteLLM prefixes of the providers pi supports too (`openrouter/`, `fireworks_ai/`,
|
|
295
|
+
`groq/` and others). For an OpenRouter id such as `anthropic/claude-sonnet-4.5` it then tries
|
|
296
|
+
`claude-sonnet-4.5` and `claude-sonnet-4-5`. Unknown models count with cost 0 and log a warning.
|
|
297
|
+
Long-context tiers
|
|
232
298
|
(`*_above_<N>k_tokens`) are applied per request; 1-hour cache writes use
|
|
233
299
|
`cache_creation_input_token_cost_above_1hr`. Cache savings are cache-read tokens times (input price
|
|
234
300
|
minus cache-read price).
|
|
235
301
|
|
|
302
|
+
**Adding a provider.** Add an entry to `SOURCES` in `src/collector.mjs`, the provider id to
|
|
303
|
+
`PROVIDERS` in `src/schema.ts`, a row to the table above, and a test with a fixture log. The entry
|
|
304
|
+
says where the data lives, how it is read, and which LiteLLM keys price its models. Append-only JSONL
|
|
305
|
+
uses `jsonlReader`, which parses only new bytes. Other formats are read whole on every run and skip
|
|
306
|
+
what they counted before through `state.seen`. A SQLite file opens with `openSqlite`, which skips the
|
|
307
|
+
source with one warning on a Node without `node:sqlite`. Add the matching ccusage agent to `AGENTS`
|
|
308
|
+
in `scripts/parity-ccusage.mjs` and run `node scripts/parity-ccusage.mjs <provider>`: tokens must
|
|
309
|
+
match ccusage exactly. `node scripts/parity-ref.mjs` shows that the other providers did not change.
|
|
310
|
+
Deploy the server before the collectors, because a server rejects rows from a provider it does not
|
|
311
|
+
list.
|
|
312
|
+
|
|
236
313
|
**Incremental.** `~/.cache/big-spender/state.json` keeps per-file byte offsets plus the hourly
|
|
237
314
|
aggregates, so each run parses only new bytes but still sends the full 90-day snapshot. Rows older
|
|
238
315
|
than 7 days are rolled up to daily rows. Because the aggregates live in the state file, usage stays
|
package/dist/collector.mjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// big-spender collector.
|
|
3
3
|
//
|
|
4
|
-
// Reads
|
|
4
|
+
// Reads the usage logs of the coding agents listed in SOURCES, works out hourly
|
|
5
5
|
// token and cost aggregates (LiteLLM API prices), and POSTs one full snapshot
|
|
6
6
|
// to your big-spender server's ingest endpoint. Only numbers, model names, timestamps and the
|
|
7
7
|
// device id leave the machine: no paths, prompts, session ids or branches.
|
|
8
|
+
// With BIG_SPENDER_CURSOR_API_KEY set it also reads the Cursor account's usage from Cursor's API
|
|
9
|
+
// and POSTs it as a second snapshot under the device id "cursor".
|
|
8
10
|
//
|
|
9
11
|
// Zero dependencies, Node >= 20 (or Bun). `big-spender install` copies this single file to
|
|
10
12
|
// ~/.local/share/big-spender/collector.mjs and schedules it. See the package README.
|
|
@@ -15,14 +17,15 @@
|
|
|
15
17
|
// node collector.mjs --summary # print only the 24h summary
|
|
16
18
|
// node collector.mjs --reset # forget local state and rescan everything
|
|
17
19
|
//
|
|
18
|
-
// Env: BIG_SPENDER_DEVICE_ID, BIG_SPENDER_INGEST_URL, BIG_SPENDER_INGEST_TOKEN
|
|
20
|
+
// Env: BIG_SPENDER_DEVICE_ID, BIG_SPENDER_INGEST_URL, BIG_SPENDER_INGEST_TOKEN and optionally
|
|
21
|
+
// BIG_SPENDER_CURSOR_API_KEY (see templates/env.example).
|
|
19
22
|
// The older USAGE_* names are still read when the new one is unset.
|
|
20
23
|
|
|
21
24
|
import { createHash } from 'node:crypto';
|
|
22
25
|
import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
|
|
23
26
|
import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
24
27
|
import { homedir } from 'node:os';
|
|
25
|
-
import { join } from 'node:path';
|
|
28
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
26
29
|
import { gzipSync } from 'node:zlib';
|
|
27
30
|
|
|
28
31
|
const SCHEMA_VERSION = 1;
|
|
@@ -36,6 +39,10 @@ const PRICING_URL =
|
|
|
36
39
|
'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
|
|
37
40
|
const PRICING_TTL_MS = DAY_MS;
|
|
38
41
|
const POST_ATTEMPTS = 4;
|
|
42
|
+
const CURSOR_DEVICE_ID = 'cursor';
|
|
43
|
+
const CURSOR_PAGE_SIZE = 1000;
|
|
44
|
+
// The server's date floor (EARLIEST_DATE in schema.ts); the backfill reads from here.
|
|
45
|
+
const CURSOR_EARLIEST_MS = Date.parse('2020-01-01T00:00:00Z');
|
|
39
46
|
|
|
40
47
|
const args = new Set(process.argv.slice(2));
|
|
41
48
|
const DRY_RUN = args.has('--dry-run');
|
|
@@ -55,6 +62,17 @@ const ENV_FILE =
|
|
|
55
62
|
|
|
56
63
|
const log = (...m) => console.error('[big-spender]', ...m);
|
|
57
64
|
|
|
65
|
+
// The override exists for tests. It only points at this machine, so the Cursor API key and
|
|
66
|
+
// access token can't be sent anywhere but Cursor.
|
|
67
|
+
function cursorApiUrl(override) {
|
|
68
|
+
if (!override) return 'https://api2.cursor.sh';
|
|
69
|
+
const { hostname } = new URL(override);
|
|
70
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(hostname)) {
|
|
71
|
+
throw new Error('BIG_SPENDER_CURSOR_API_URL may only point at this machine');
|
|
72
|
+
}
|
|
73
|
+
return override.replace(/\/$/, '');
|
|
74
|
+
}
|
|
75
|
+
|
|
58
76
|
// Collectors installed before the rename have USAGE_* in their env file and scheduler units.
|
|
59
77
|
const setting = (name) => process.env[`BIG_SPENDER_${name}`] || process.env[`USAGE_${name}`] || '';
|
|
60
78
|
|
|
@@ -100,12 +118,16 @@ async function acquireLock() {
|
|
|
100
118
|
// State
|
|
101
119
|
|
|
102
120
|
/**
|
|
103
|
-
* @typedef {{ input: number, cacheRead: number,
|
|
104
|
-
* @typedef {{
|
|
121
|
+
* @typedef {{ input: number, cacheRead: number, cacheWrite: number, output: number, savings: number }} Cost
|
|
122
|
+
* @typedef {{ input: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number, output: number, sessions: string[], cost?: Cost }} Bucket
|
|
123
|
+
* A JSONL file's read position. Readers may keep their own fields on it (Codex: model, sessionId, lastTotal; pi: forkCalls).
|
|
124
|
+
* @typedef {{ size: number, mtimeMs: number, offset: number, model?: string, sessionId?: string, lastTotal?: number, forkCalls?: string[] }} FileState
|
|
105
125
|
* A seen entry is the first timestamp, or for Claude [first timestamp, output tokens counted].
|
|
106
126
|
* A bare number on a Claude key means the counted output is unknown (state from an older version).
|
|
107
127
|
* @typedef {number | [number, number]} Seen
|
|
108
|
-
* @typedef {{ version: number, files: Record<string, FileState>, seen: Record<string, Seen>, buckets: Record<string, Bucket>, fixes?: string[],
|
|
128
|
+
* @typedef {{ version: number, files: Record<string, FileState>, seen: Record<string, Seen>, buckets: Record<string, Bucket>, fixes?: string[], rescan?: string[], cursorBackfills?: string[] }} State
|
|
129
|
+
* cursorBackfills holds a hash of each ingest URL and Cursor API key pair whose server stored the
|
|
130
|
+
* account's full history. Hashed, because an ingest URL can carry a credential.
|
|
109
131
|
*/
|
|
110
132
|
|
|
111
133
|
// One-time fixes to existing state. The state version stays the same so an older installed copy
|
|
@@ -130,7 +152,7 @@ async function loadState() {
|
|
|
130
152
|
// Older versions kept the first log line of a Claude message, whose output count can be
|
|
131
153
|
// partial. Re-read the Claude logs once so later lines add what was missed.
|
|
132
154
|
s.fixes.push(FIX_CLAUDE_OUTPUT);
|
|
133
|
-
s.
|
|
155
|
+
s.rescan = ['claude'];
|
|
134
156
|
}
|
|
135
157
|
return s;
|
|
136
158
|
} catch {
|
|
@@ -212,7 +234,12 @@ async function loadPricing() {
|
|
|
212
234
|
}
|
|
213
235
|
}
|
|
214
236
|
|
|
215
|
-
|
|
237
|
+
const litellmKeys = (prefix) => (model) =>
|
|
238
|
+
[model, model.replace(/-\d{8}$/, ''), model.replace(/@.*$/, '')].flatMap((base) => [
|
|
239
|
+
base,
|
|
240
|
+
`${prefix}/${base}`
|
|
241
|
+
]);
|
|
242
|
+
|
|
216
243
|
function makePriceResolver(models) {
|
|
217
244
|
const memo = new Map();
|
|
218
245
|
const warned = new Set();
|
|
@@ -220,18 +247,8 @@ function makePriceResolver(models) {
|
|
|
220
247
|
return (provider, model) => {
|
|
221
248
|
const memoKey = `${provider}|${model}`;
|
|
222
249
|
if (memo.has(memoKey)) return memo.get(memoKey);
|
|
223
|
-
const
|
|
224
|
-
const
|
|
225
|
-
let entry = null;
|
|
226
|
-
for (const base of bases) {
|
|
227
|
-
for (const key of [base, `${prefix}/${base}`]) {
|
|
228
|
-
if (usable(models[key])) {
|
|
229
|
-
entry = models[key];
|
|
230
|
-
break;
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
if (entry) break;
|
|
234
|
-
}
|
|
250
|
+
const key = SOURCES[provider]?.priceKeys(model).find((k) => usable(models[k]));
|
|
251
|
+
const entry = key ? models[key] : null;
|
|
235
252
|
if (!entry && !warned.has(memoKey)) {
|
|
236
253
|
warned.add(memoKey);
|
|
237
254
|
log(`warning: no LiteLLM price for ${provider} model "${model}"; counting its cost as 0`);
|
|
@@ -267,7 +284,7 @@ function price(entry, base, tier) {
|
|
|
267
284
|
return typeof v === 'number' ? v : undefined;
|
|
268
285
|
}
|
|
269
286
|
|
|
270
|
-
/** Cost breakdown in USD for a bucket's tokens. */
|
|
287
|
+
/** Cost breakdown in USD for a bucket's tokens. @returns {Cost} */
|
|
271
288
|
function costOf(entry, tier, t) {
|
|
272
289
|
if (!entry) return { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, savings: 0 };
|
|
273
290
|
const inP = price(entry, 'input_cost_per_token', tier) ?? 0;
|
|
@@ -459,27 +476,175 @@ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSess
|
|
|
459
476
|
};
|
|
460
477
|
}
|
|
461
478
|
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
479
|
+
const expandHome = (p) => (p === '~' || p.startsWith('~/') ? join(HOME, p.slice(1)) : p);
|
|
480
|
+
|
|
481
|
+
// pi's own env vars, then ccusage's PI_AGENT_DIR (a comma-separated list of sessions dirs).
|
|
482
|
+
const piEnvPaths = () => [
|
|
483
|
+
...(process.env.PI_CODING_AGENT_DIR
|
|
484
|
+
? [join(expandHome(process.env.PI_CODING_AGENT_DIR), 'sessions')]
|
|
485
|
+
: []),
|
|
486
|
+
...(process.env.PI_CODING_AGENT_SESSION_DIR
|
|
487
|
+
? [expandHome(process.env.PI_CODING_AGENT_SESSION_DIR)]
|
|
488
|
+
: []),
|
|
489
|
+
...(process.env.PI_AGENT_DIR ?? '')
|
|
490
|
+
.split(',')
|
|
491
|
+
.map((p) => p.trim())
|
|
492
|
+
.filter(Boolean)
|
|
493
|
+
];
|
|
494
|
+
const piPaths = () => [join(HOME, '.pi', 'agent', 'sessions'), ...piEnvPaths()];
|
|
495
|
+
|
|
496
|
+
// The pi-subagents extension writes debug copies of calls that a session file already has.
|
|
497
|
+
const isSubagentCopy = (path) => path.split(sep).includes('subagent-artifacts');
|
|
498
|
+
|
|
499
|
+
// pi's input excludes cached tokens and its output includes reasoning.
|
|
500
|
+
function piUsage(o) {
|
|
501
|
+
const msg = o.message;
|
|
502
|
+
if ((o.type !== undefined && o.type !== 'message') || msg?.role !== 'assistant') return null;
|
|
503
|
+
const u = msg.usage;
|
|
504
|
+
if (!u) return null;
|
|
505
|
+
const ts = Date.parse(o.timestamp);
|
|
506
|
+
if (!Number.isFinite(ts)) return null;
|
|
507
|
+
// Token counts are integers; ccusage reads anything else as 0, and the schema rejects it.
|
|
508
|
+
const count = (v) => (Number.isInteger(v) ? num(v) : 0);
|
|
509
|
+
const input = count(u.input);
|
|
510
|
+
const cacheRead = count(u.cacheRead);
|
|
511
|
+
const cacheWrite = count(u.cacheWrite);
|
|
512
|
+
// pi reports the part of cacheWrite written with 1-hour retention (Anthropic only).
|
|
513
|
+
const cacheWrite1h = Math.min(count(u.cacheWrite1h), cacheWrite);
|
|
514
|
+
let output = count(u.output);
|
|
515
|
+
const parts = input + output + cacheRead + cacheWrite;
|
|
516
|
+
const total = Math.max(parts, count(u.totalTokens));
|
|
517
|
+
if (total === 0) return null;
|
|
518
|
+
// When output is 0, tokens the total has beyond the parts count as output, as ccusage does.
|
|
519
|
+
if (output === 0) output = total - parts;
|
|
520
|
+
const model = typeof msg.model === 'string' && msg.model ? msg.model : 'unknown';
|
|
521
|
+
const fingerprint = [
|
|
522
|
+
ts,
|
|
523
|
+
model,
|
|
524
|
+
input,
|
|
525
|
+
output,
|
|
526
|
+
cacheRead,
|
|
527
|
+
cacheWrite,
|
|
528
|
+
total,
|
|
529
|
+
num(u.cost?.total)
|
|
530
|
+
].join('|');
|
|
531
|
+
return { ts, model, input, output, cacheRead, cacheWrite, cacheWrite1h, fingerprint };
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function piCallsIn(path, untilMs) {
|
|
535
|
+
const calls = [];
|
|
536
|
+
let text;
|
|
537
|
+
try {
|
|
538
|
+
text = readFileSync(path, 'utf8');
|
|
539
|
+
} catch {
|
|
540
|
+
return calls;
|
|
470
541
|
}
|
|
471
|
-
|
|
472
|
-
|
|
542
|
+
for (const line of text.split('\n')) {
|
|
543
|
+
if (!line.includes('"usage"')) continue;
|
|
544
|
+
const o = parseJson(line);
|
|
545
|
+
const u = o && piUsage(o);
|
|
546
|
+
if (u && u.ts <= untilMs) calls.push(shortHash(u.fingerprint));
|
|
473
547
|
}
|
|
548
|
+
return calls;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// LiteLLM's prefixes for the providers pi talks to.
|
|
552
|
+
const PI_PRICE_PREFIXES = [
|
|
553
|
+
'anthropic',
|
|
554
|
+
'openai',
|
|
555
|
+
'gemini',
|
|
556
|
+
'openrouter',
|
|
557
|
+
'xai',
|
|
558
|
+
'groq',
|
|
559
|
+
'cerebras',
|
|
560
|
+
'mistral',
|
|
561
|
+
'deepseek',
|
|
562
|
+
'fireworks_ai',
|
|
563
|
+
'together_ai',
|
|
564
|
+
'zai',
|
|
565
|
+
'moonshot',
|
|
566
|
+
'minimax'
|
|
567
|
+
];
|
|
568
|
+
|
|
569
|
+
// Local models can have a file path as their id; only the file name leaves the machine.
|
|
570
|
+
const piModel = (model) => {
|
|
571
|
+
const isPath =
|
|
572
|
+
/^([/~.]|[A-Za-z]:)|\\|:\/|\/\//.test(model) ||
|
|
573
|
+
/\.(gguf|ggml|bin|safetensors|pth?|onnx)$/i.test(model);
|
|
574
|
+
const name = isPath ? (model.split(/[/\\]/).filter(Boolean).at(-1) ?? 'unknown') : model;
|
|
575
|
+
return name.replace(/[^A-Za-z0-9._:/@-]/g, '-').slice(0, 100);
|
|
576
|
+
};
|
|
474
577
|
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
578
|
+
// A pi fork starts with a copy of its parent's calls up to the fork point. They are matched
|
|
579
|
+
// against every call in the parent up to then, not only its current branch, so the result does
|
|
580
|
+
// not depend on where the parent's leaf was when the fork was read.
|
|
581
|
+
function piLineHandler(state, file, path, resolvePrice, cutoffMs) {
|
|
582
|
+
if (isSubagentCopy(path)) return () => {};
|
|
583
|
+
/** @type {Set<string> | undefined} */
|
|
584
|
+
let parentCalls;
|
|
585
|
+
return (line) => {
|
|
586
|
+
if (!line.includes('"usage"') && !line.includes('"session"')) return;
|
|
587
|
+
const o = parseJson(line);
|
|
588
|
+
if (!o) return;
|
|
589
|
+
if (o.type === 'session') {
|
|
590
|
+
if (typeof o.id === 'string' && o.id) file.sessionId = o.id;
|
|
591
|
+
const forkMs = Date.parse(o.timestamp);
|
|
592
|
+
if (typeof o.parentSession !== 'string' || !o.parentSession || !Number.isFinite(forkMs)) {
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
const parent = resolve(dirname(path), o.parentSession);
|
|
596
|
+
const inStore = piPaths().some((root) => parent.startsWith(resolve(root) + sep));
|
|
597
|
+
if (parent === path || !inStore || isSubagentCopy(parent)) return;
|
|
598
|
+
// Kept in state, so a fork read across runs still matches if the parent changes or goes.
|
|
599
|
+
const calls = piCallsIn(parent, forkMs);
|
|
600
|
+
if (calls.length) file.forkCalls = calls;
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
const u = piUsage(o);
|
|
604
|
+
if (!u) return;
|
|
605
|
+
const session = file.sessionId ?? path;
|
|
606
|
+
// No entry ids in the key: pi rewrites a file in place when it migrates an older version.
|
|
607
|
+
const dedupe = `p:${shortHash(`${session}:${u.fingerprint}`)}`;
|
|
608
|
+
if (file.forkCalls) {
|
|
609
|
+
parentCalls ??= new Set(file.forkCalls);
|
|
610
|
+
if (parentCalls.has(shortHash(u.fingerprint))) {
|
|
611
|
+
// Seen, so a re-read after the fork is rewritten still skips it.
|
|
612
|
+
state.seen[dedupe] = u.ts;
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
delete file.forkCalls;
|
|
616
|
+
}
|
|
617
|
+
if (u.ts < cutoffMs) return;
|
|
618
|
+
if (state.seen[dedupe] !== undefined) return;
|
|
619
|
+
state.seen[dedupe] = u.ts;
|
|
620
|
+
const model = piModel(u.model);
|
|
621
|
+
addRecord(state, {
|
|
622
|
+
ts: u.ts,
|
|
623
|
+
provider: 'pi',
|
|
624
|
+
model,
|
|
625
|
+
tier: tierFor(resolvePrice('pi', model), u.input + u.cacheRead + u.cacheWrite),
|
|
626
|
+
session: shortHash(`pi:${session}`),
|
|
627
|
+
input: u.input,
|
|
628
|
+
cacheRead: u.cacheRead,
|
|
629
|
+
cacheWrite5m: u.cacheWrite - u.cacheWrite1h,
|
|
630
|
+
cacheWrite1h: u.cacheWrite1h,
|
|
631
|
+
output: u.output
|
|
632
|
+
});
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* A reader for JSONL logs that only grow: walks `*.jsonl` under each path and parses only the
|
|
638
|
+
* bytes added since the last run. `lines` builds the line handler for one file.
|
|
639
|
+
* @param {(ctx: ReadContext, file: FileState, path: string) => (line: string) => void} lines
|
|
640
|
+
*/
|
|
641
|
+
const jsonlReader = (lines) => async (paths, ctx, provider) => {
|
|
642
|
+
const { state } = ctx;
|
|
643
|
+
for (const dir of paths) {
|
|
479
644
|
if (!existsSync(dir)) continue;
|
|
480
645
|
for await (const path of walk(dir)) {
|
|
481
|
-
if (seenPaths.has(path)) continue;
|
|
482
|
-
seenPaths.add(path);
|
|
646
|
+
if (ctx.seenPaths.has(path)) continue;
|
|
647
|
+
ctx.seenPaths.add(path);
|
|
483
648
|
let st;
|
|
484
649
|
try {
|
|
485
650
|
st = await stat(path);
|
|
@@ -487,44 +652,131 @@ async function scan(state, resolvePrice, cutoffMs) {
|
|
|
487
652
|
continue;
|
|
488
653
|
}
|
|
489
654
|
// Untouched for longer than the window: nothing in it can count.
|
|
490
|
-
if (st.mtimeMs < cutoffMs) {
|
|
655
|
+
if (st.mtimeMs < ctx.cutoffMs) {
|
|
491
656
|
delete state.files[path];
|
|
492
657
|
continue;
|
|
493
658
|
}
|
|
494
|
-
const prev =
|
|
659
|
+
const prev = state.rescan?.includes(provider) ? undefined : state.files[path];
|
|
495
660
|
if (prev && prev.size === st.size && prev.mtimeMs === st.mtimeMs) continue;
|
|
496
661
|
// File shrank (rewritten/truncated): start over. Dedupe keys stop double counting.
|
|
497
662
|
/** @type {FileState} */
|
|
498
663
|
const fs = prev && st.size >= prev.offset ? { ...prev } : { size: 0, mtimeMs: 0, offset: 0 };
|
|
499
|
-
const handler =
|
|
500
|
-
provider === 'claude'
|
|
501
|
-
? claudeLineHandler(state, resolvePrice, cutoffMs)
|
|
502
|
-
: codexLineHandler(
|
|
503
|
-
state,
|
|
504
|
-
fs,
|
|
505
|
-
resolvePrice,
|
|
506
|
-
cutoffMs,
|
|
507
|
-
path.match(/([0-9a-f-]{36})\.jsonl$/)?.[1] ?? path
|
|
508
|
-
);
|
|
509
664
|
const start = fs.offset;
|
|
510
665
|
try {
|
|
511
|
-
fs.offset = await readLinesFrom(path, start,
|
|
666
|
+
fs.offset = await readLinesFrom(path, start, lines(ctx, fs, path));
|
|
512
667
|
} catch (err) {
|
|
513
668
|
log(`skipping unreadable file: ${err.message}`);
|
|
514
669
|
continue;
|
|
515
670
|
}
|
|
516
|
-
parsedBytes += fs.offset - start;
|
|
517
|
-
filesRead++;
|
|
671
|
+
ctx.parsedBytes += fs.offset - start;
|
|
672
|
+
ctx.filesRead++;
|
|
518
673
|
fs.size = st.size;
|
|
519
674
|
fs.mtimeMs = st.mtimeMs;
|
|
520
675
|
state.files[path] = fs;
|
|
521
676
|
}
|
|
522
677
|
}
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
/** @type {Promise<any> | undefined} */
|
|
681
|
+
let sqlite;
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* Opens a SQLite file read-only, or returns null when this runtime has no `node:sqlite` (Node
|
|
685
|
+
* 22.13+, or 22.5+ with --experimental-sqlite). Imported on first use, never at the top level,
|
|
686
|
+
* so the other sources still run on Node 20; the warning is logged once per run.
|
|
687
|
+
*/
|
|
688
|
+
async function openSqlite(path) {
|
|
689
|
+
sqlite ??= import('node:sqlite').catch(() => {
|
|
690
|
+
log('warning: this runtime has no node:sqlite (Node 22.13 or newer); skipping SQLite sources');
|
|
691
|
+
return null;
|
|
692
|
+
});
|
|
693
|
+
const mod = await sqlite;
|
|
694
|
+
return mod && new mod.DatabaseSync(path, { readOnly: true });
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const fromEnv = (name, ...rest) => (process.env[name] ? [join(process.env[name], ...rest)] : []);
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
|
|
701
|
+
* @typedef {{
|
|
702
|
+
* paths: string[],
|
|
703
|
+
* envPaths: () => string[],
|
|
704
|
+
* read: (paths: string[], ctx: ReadContext, provider: string) => Promise<void>,
|
|
705
|
+
* priceKeys: (model: string) => string[]
|
|
706
|
+
* }} Source
|
|
707
|
+
*/
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* Every agent the collector reads, keyed by the provider id its rows carry. Each id must also be
|
|
711
|
+
* in PROVIDERS in src/schema.ts, or the server rejects the snapshot.
|
|
712
|
+
*
|
|
713
|
+
* - `paths`: where its data lives by default.
|
|
714
|
+
* - `envPaths`: where env-var overrides point. Called after the env file is loaded.
|
|
715
|
+
* - `read`: adds the usage under the paths it is given with addRecord. scan calls it with
|
|
716
|
+
* `paths`, and once every source has read those, with `envPaths`, so a file two sources reach
|
|
717
|
+
* goes to the one it is a default of. `jsonlReader` reads append-only JSONL by byte offset.
|
|
718
|
+
* Any other reader (a SQLite file through openSqlite, a JSON file rewritten in place) reads its
|
|
719
|
+
* data whole on every run and skips what it counted before through `state.seen`, keyed with a
|
|
720
|
+
* provider prefix and valued with the record's timestamp so pruneState can drop it.
|
|
721
|
+
* - `priceKeys`: the LiteLLM keys to try for a model, in order.
|
|
722
|
+
*
|
|
723
|
+
* @type {Record<string, Source>}
|
|
724
|
+
*/
|
|
725
|
+
const SOURCES = {
|
|
726
|
+
claude: {
|
|
727
|
+
paths: [join(HOME, '.claude', 'projects'), join(HOME, '.config', 'claude', 'projects')],
|
|
728
|
+
envPaths: () => fromEnv('CLAUDE_CONFIG_DIR', 'projects'),
|
|
729
|
+
read: jsonlReader((ctx) => claudeLineHandler(ctx.state, ctx.resolvePrice, ctx.cutoffMs)),
|
|
730
|
+
priceKeys: litellmKeys('anthropic')
|
|
731
|
+
},
|
|
732
|
+
codex: {
|
|
733
|
+
paths: [join(HOME, '.codex', 'sessions')],
|
|
734
|
+
envPaths: () => fromEnv('CODEX_HOME', 'sessions'),
|
|
735
|
+
read: jsonlReader((ctx, file, path) =>
|
|
736
|
+
codexLineHandler(
|
|
737
|
+
ctx.state,
|
|
738
|
+
file,
|
|
739
|
+
ctx.resolvePrice,
|
|
740
|
+
ctx.cutoffMs,
|
|
741
|
+
path.match(/([0-9a-f-]{36})\.jsonl$/)?.[1] ?? path
|
|
742
|
+
)
|
|
743
|
+
),
|
|
744
|
+
priceKeys: litellmKeys('openai')
|
|
745
|
+
},
|
|
746
|
+
pi: {
|
|
747
|
+
paths: [join(HOME, '.pi', 'agent', 'sessions')],
|
|
748
|
+
envPaths: piEnvPaths,
|
|
749
|
+
read: jsonlReader((ctx, file, path) =>
|
|
750
|
+
piLineHandler(ctx.state, file, path, ctx.resolvePrice, ctx.cutoffMs)
|
|
751
|
+
),
|
|
752
|
+
// pi logs each backend's own model id. OpenRouter's carry a vendor and dotted versions
|
|
753
|
+
// (`anthropic/claude-sonnet-4.5`) that LiteLLM may only know as `claude-sonnet-4-5`.
|
|
754
|
+
priceKeys: (model) => {
|
|
755
|
+
const bare = model.replace(/^[^/]+\//, '');
|
|
756
|
+
return [
|
|
757
|
+
...new Set(
|
|
758
|
+
[model, bare, bare.replace(/(\d)\.(\d)/g, '$1-$2')].flatMap((m) =>
|
|
759
|
+
PI_PRICE_PREFIXES.flatMap((p) => litellmKeys(p)(m))
|
|
760
|
+
)
|
|
761
|
+
)
|
|
762
|
+
];
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
|
|
767
|
+
async function scan(state, resolvePrice, cutoffMs) {
|
|
768
|
+
/** @type {ReadContext} */
|
|
769
|
+
const ctx = { state, resolvePrice, cutoffMs, seenPaths: new Set(), filesRead: 0, parsedBytes: 0 };
|
|
770
|
+
const sources = Object.entries(SOURCES);
|
|
771
|
+
for (const [provider, source] of sources) await source.read(source.paths, ctx, provider);
|
|
772
|
+
for (const [provider, source] of sources) await source.read(source.envPaths(), ctx, provider);
|
|
523
773
|
for (const path of Object.keys(state.files)) {
|
|
524
|
-
if (!seenPaths.has(path)) delete state.files[path];
|
|
774
|
+
if (!ctx.seenPaths.has(path)) delete state.files[path];
|
|
525
775
|
}
|
|
526
|
-
delete state.
|
|
527
|
-
log(
|
|
776
|
+
delete state.rescan;
|
|
777
|
+
log(
|
|
778
|
+
`read ${ctx.filesRead} changed file(s), ${(ctx.parsedBytes / 1e6).toFixed(1)} MB of new log data`
|
|
779
|
+
);
|
|
528
780
|
}
|
|
529
781
|
|
|
530
782
|
// ---------------------------------------------------------------------------
|
|
@@ -532,18 +784,28 @@ async function scan(state, resolvePrice, cutoffMs) {
|
|
|
532
784
|
|
|
533
785
|
const round = (n, d = 6) => Math.round(n * 10 ** d) / 10 ** d;
|
|
534
786
|
|
|
535
|
-
|
|
787
|
+
/**
|
|
788
|
+
* @param {Record<string, Bucket>} buckets
|
|
789
|
+
* @param {(b: Bucket, provider: string, model: string, tier: number) => Cost} costFor
|
|
790
|
+
* @param {{ deviceId: string, pricingSource: string, providers: string[], nowMs: number, coverageStartMs: number }} meta
|
|
791
|
+
* `providers` names the session counts the snapshot carries.
|
|
792
|
+
*/
|
|
793
|
+
function buildSnapshot(
|
|
794
|
+
buckets,
|
|
795
|
+
costFor,
|
|
796
|
+
{ deviceId, pricingSource, providers, nowMs, coverageStartMs }
|
|
797
|
+
) {
|
|
536
798
|
const hourlyCutoff = Math.floor((nowMs - HOURLY_DAYS * DAY_MS) / DAY_MS) * DAY_MS;
|
|
537
799
|
/** @type {Map<string, any>} */
|
|
538
800
|
const rows = new Map();
|
|
539
|
-
for (const [key, b] of Object.entries(
|
|
801
|
+
for (const [key, b] of Object.entries(buckets)) {
|
|
540
802
|
const [hourStr, provider, model, tierStr] = key.split('|');
|
|
541
803
|
const hourMs = Number(hourStr);
|
|
542
804
|
if (hourMs < coverageStartMs) continue;
|
|
543
805
|
const daily = hourMs < hourlyCutoff;
|
|
544
806
|
const start = daily ? Math.floor(hourMs / DAY_MS) * DAY_MS : hourMs;
|
|
545
807
|
const rowKey = `${start}|${daily ? 'd' : 'h'}|${provider}|${model}`;
|
|
546
|
-
const c =
|
|
808
|
+
const c = costFor(b, provider, model, Number(tierStr));
|
|
547
809
|
let row = rows.get(rowKey);
|
|
548
810
|
if (!row) {
|
|
549
811
|
row = {
|
|
@@ -604,20 +866,17 @@ function buildSnapshot(state, resolvePrice, pricing, nowMs, coverageStartMs) {
|
|
|
604
866
|
const all = new Set();
|
|
605
867
|
for (const [name, span] of Object.entries(ranges)) {
|
|
606
868
|
const from = currentHour + HOUR_MS - span;
|
|
607
|
-
const sets =
|
|
608
|
-
for (const [key, b] of Object.entries(
|
|
869
|
+
const sets = Object.fromEntries(providers.map((p) => [p, new Set()]));
|
|
870
|
+
for (const [key, b] of Object.entries(buckets)) {
|
|
609
871
|
const [hourStr, provider] = key.split('|');
|
|
610
872
|
const h = Number(hourStr);
|
|
611
873
|
if (h < from || h < coverageStartMs) continue;
|
|
612
874
|
for (const s of b.sessions) sets[provider]?.add(s);
|
|
613
875
|
}
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
codex: sets.codex.size,
|
|
617
|
-
all: sets.claude.size + sets.codex.size
|
|
618
|
-
};
|
|
876
|
+
const counts = Object.fromEntries(providers.map((p) => [p, sets[p].size]));
|
|
877
|
+
sessionCounts[name] = { ...counts, all: Object.values(counts).reduce((a, n) => a + n, 0) };
|
|
619
878
|
}
|
|
620
|
-
for (const [key, b] of Object.entries(
|
|
879
|
+
for (const [key, b] of Object.entries(buckets)) {
|
|
621
880
|
if (Number(key.split('|')[0]) >= coverageStartMs) for (const s of b.sessions) all.add(s);
|
|
622
881
|
}
|
|
623
882
|
|
|
@@ -625,10 +884,10 @@ function buildSnapshot(state, resolvePrice, pricing, nowMs, coverageStartMs) {
|
|
|
625
884
|
const { '24h': sessions24h, ...publicCounts } = sessionCounts;
|
|
626
885
|
const snapshot = {
|
|
627
886
|
schemaVersion: SCHEMA_VERSION,
|
|
628
|
-
deviceId
|
|
887
|
+
deviceId,
|
|
629
888
|
generatedAt: new Date(nowMs).toISOString(),
|
|
630
889
|
coverageStart: new Date(coverageStartMs).toISOString(),
|
|
631
|
-
pricingSource
|
|
890
|
+
pricingSource,
|
|
632
891
|
hourly,
|
|
633
892
|
sessionsTotal: all.size,
|
|
634
893
|
sessionCounts: publicCounts
|
|
@@ -675,26 +934,215 @@ function printSummary(snapshot, sessions24h, nowMs) {
|
|
|
675
934
|
([m, v]) =>
|
|
676
935
|
` ${m.padEnd(28)} ${usd(v.cost).padStart(10)} ${(v.tokens / 1e6).toFixed(1)}M tok`
|
|
677
936
|
),
|
|
678
|
-
|
|
937
|
+
...(snapshot.pricingSource === 'cursor'
|
|
938
|
+
? []
|
|
939
|
+
: [`Compare with \`bunx ccusage claude daily\` (Claude Code only) for this device.`])
|
|
679
940
|
];
|
|
680
941
|
console.error(lines.join('\n'));
|
|
681
942
|
}
|
|
682
943
|
|
|
944
|
+
// ---------------------------------------------------------------------------
|
|
945
|
+
// Cursor
|
|
946
|
+
//
|
|
947
|
+
// Cursor keeps usage on its servers, per account, so it is read from Cursor's API instead of
|
|
948
|
+
// local logs and sent under its own device id: the same account on two machines is one history.
|
|
949
|
+
|
|
950
|
+
async function cursorRequest(path, bearer, body, headers = {}) {
|
|
951
|
+
const res = await fetch(`${cursorApiUrl(process.env.BIG_SPENDER_CURSOR_API_URL)}${path}`, {
|
|
952
|
+
method: 'POST',
|
|
953
|
+
headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json', ...headers },
|
|
954
|
+
body: JSON.stringify(body),
|
|
955
|
+
// Never forward the key or token to another host.
|
|
956
|
+
redirect: 'error',
|
|
957
|
+
signal: AbortSignal.timeout(30_000)
|
|
958
|
+
});
|
|
959
|
+
if (!res.ok) {
|
|
960
|
+
const hint =
|
|
961
|
+
res.status === 401 || res.status === 403 ? '; check BIG_SPENDER_CURSOR_API_KEY' : '';
|
|
962
|
+
throw new Error(`Cursor ${path} answered HTTP ${res.status}${hint}`);
|
|
963
|
+
}
|
|
964
|
+
const json = await res.json().catch(() => null);
|
|
965
|
+
if (!json || typeof json !== 'object' || Array.isArray(json)) {
|
|
966
|
+
throw new Error(`Cursor ${path} answered with something other than a JSON object`);
|
|
967
|
+
}
|
|
968
|
+
return json;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/** Trades a Cursor user API key for the short-lived access token its dashboard RPCs accept. */
|
|
972
|
+
async function cursorAccessToken(apiKey) {
|
|
973
|
+
const { accessToken } = await cursorRequest('/auth/exchange_user_api_key', apiKey, {});
|
|
974
|
+
if (typeof accessToken !== 'string' || !accessToken) {
|
|
975
|
+
throw new Error('Cursor did not return an access token for BIG_SPENDER_CURSOR_API_KEY');
|
|
976
|
+
}
|
|
977
|
+
assertHeaderSafe(accessToken, "Cursor's access token");
|
|
978
|
+
return accessToken;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/**
|
|
982
|
+
* Raw usage events with fromMs <= timestamp < toMs. Cursor gives events no unique id and its pages
|
|
983
|
+
* can overlap, so instead of paging, a window holding more than one page is split in two.
|
|
984
|
+
*/
|
|
985
|
+
async function cursorEvents(token, fromMs, toMs) {
|
|
986
|
+
const body = await cursorRequest(
|
|
987
|
+
'/aiserver.v1.DashboardService/GetFilteredUsageEvents',
|
|
988
|
+
token,
|
|
989
|
+
{
|
|
990
|
+
page: 1,
|
|
991
|
+
pageSize: CURSOR_PAGE_SIZE,
|
|
992
|
+
startDate: String(fromMs),
|
|
993
|
+
endDate: String(toMs - 1)
|
|
994
|
+
},
|
|
995
|
+
{ 'connect-protocol-version': '1' }
|
|
996
|
+
);
|
|
997
|
+
// A failed call can still answer 200, with an error body that would read as an empty window.
|
|
998
|
+
if ('error' in body || 'code' in body || 'message' in body) {
|
|
999
|
+
throw new Error('Cursor answered with an error instead of usage events');
|
|
1000
|
+
}
|
|
1001
|
+
// Connect leaves out empty fields, so a window without events answers {}.
|
|
1002
|
+
const total = Number(body.totalUsageEventsCount ?? 0);
|
|
1003
|
+
const events = body.usageEventsDisplay ?? [];
|
|
1004
|
+
if (!Number.isSafeInteger(total) || total < 0 || !Array.isArray(events)) {
|
|
1005
|
+
throw new Error('Cursor answered with a usage page in an unexpected shape');
|
|
1006
|
+
}
|
|
1007
|
+
let inside;
|
|
1008
|
+
if (total > CURSOR_PAGE_SIZE) {
|
|
1009
|
+
if (toMs - fromMs < 2)
|
|
1010
|
+
throw new Error(`Cursor listed ${total} usage events in one millisecond`);
|
|
1011
|
+
const mid = fromMs + Math.floor((toMs - fromMs) / 2);
|
|
1012
|
+
inside = [
|
|
1013
|
+
...(await cursorEvents(token, fromMs, mid)),
|
|
1014
|
+
...(await cursorEvents(token, mid, toMs))
|
|
1015
|
+
];
|
|
1016
|
+
} else {
|
|
1017
|
+
inside = events.filter((e) => {
|
|
1018
|
+
const ts = Number(e?.timestamp);
|
|
1019
|
+
return ts >= fromMs && ts < toMs;
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
1022
|
+
// Posting a short window would replace complete days on the server with partial ones. Events
|
|
1023
|
+
// that arrive while the halves are read can make a split window longer, never shorter.
|
|
1024
|
+
if (inside.length < total || (total <= CURSOR_PAGE_SIZE && inside.length !== total)) {
|
|
1025
|
+
throw new Error(
|
|
1026
|
+
`Cursor counted ${total} usage events in a window but returned ${inside.length} inside it`
|
|
1027
|
+
);
|
|
1028
|
+
}
|
|
1029
|
+
return inside;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
const cursorCount = (v) => num(typeof v === 'string' ? Number(v) : v);
|
|
1033
|
+
|
|
1034
|
+
/** Cursor model names are free text ("Premium (Codex 5.3)"); the server accepts only slugs. */
|
|
1035
|
+
const cursorModel = (name) =>
|
|
1036
|
+
String(name ?? '')
|
|
1037
|
+
.toLowerCase()
|
|
1038
|
+
.replace(/[^a-z0-9._:@-]+/g, '-')
|
|
1039
|
+
.replace(/^-+|-+$/g, '')
|
|
1040
|
+
.slice(0, 100) || 'unknown';
|
|
1041
|
+
|
|
1042
|
+
/**
|
|
1043
|
+
* One usage event as tokens and Cursor's own price, or null for events without token counts:
|
|
1044
|
+
* Cursor billed per request before mid-2025, and some free-credit events report no tokens.
|
|
1045
|
+
*/
|
|
1046
|
+
function parseCursorEvent(raw) {
|
|
1047
|
+
const u = raw?.tokenUsage;
|
|
1048
|
+
if (!u || typeof u !== 'object') return null;
|
|
1049
|
+
const ts = Number(raw.timestamp);
|
|
1050
|
+
const t = {
|
|
1051
|
+
input: cursorCount(u.inputTokens),
|
|
1052
|
+
cacheRead: cursorCount(u.cacheReadTokens),
|
|
1053
|
+
cacheWrite: cursorCount(u.cacheWriteTokens),
|
|
1054
|
+
output: cursorCount(u.outputTokens)
|
|
1055
|
+
};
|
|
1056
|
+
if (!Number.isFinite(ts) || t.input + t.cacheRead + t.cacheWrite + t.output === 0) return null;
|
|
1057
|
+
const conversation = typeof raw.conversationId === 'string' ? raw.conversationId : '';
|
|
1058
|
+
return {
|
|
1059
|
+
ts,
|
|
1060
|
+
model: cursorModel(raw.model),
|
|
1061
|
+
session: conversation && conversation !== 'null' ? shortHash(`cursor:${conversation}`) : null,
|
|
1062
|
+
...t,
|
|
1063
|
+
usd: cursorCount(u.totalCents) / 100
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
// Cursor reports one price per event. It is split over the token types in these proportions
|
|
1068
|
+
// (typical API price ratios) so the cost-by-type breakdown has something to show; the total is
|
|
1069
|
+
// always Cursor's.
|
|
1070
|
+
const CURSOR_PRICE_RATIO = { input: 1, cacheRead: 0.1, cacheWrite: 1.25, output: 5 };
|
|
1071
|
+
|
|
1072
|
+
/** @returns {Record<string, Bucket>} */
|
|
1073
|
+
function cursorBuckets(events) {
|
|
1074
|
+
/** @type {Record<string, Bucket>} */
|
|
1075
|
+
const buckets = {};
|
|
1076
|
+
const w = CURSOR_PRICE_RATIO;
|
|
1077
|
+
for (const e of events) {
|
|
1078
|
+
const key = bucketKey(Math.floor(e.ts / HOUR_MS) * HOUR_MS, 'cursor', e.model, 0);
|
|
1079
|
+
const b = (buckets[key] ??= {
|
|
1080
|
+
input: 0,
|
|
1081
|
+
cacheRead: 0,
|
|
1082
|
+
cacheWrite5m: 0,
|
|
1083
|
+
cacheWrite1h: 0,
|
|
1084
|
+
output: 0,
|
|
1085
|
+
sessions: [],
|
|
1086
|
+
cost: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, savings: 0 }
|
|
1087
|
+
});
|
|
1088
|
+
b.input += e.input;
|
|
1089
|
+
b.cacheRead += e.cacheRead;
|
|
1090
|
+
b.cacheWrite5m += e.cacheWrite;
|
|
1091
|
+
b.output += e.output;
|
|
1092
|
+
if (e.session && !b.sessions.includes(e.session)) b.sessions.push(e.session);
|
|
1093
|
+
const unit =
|
|
1094
|
+
e.usd /
|
|
1095
|
+
(e.input * w.input +
|
|
1096
|
+
e.cacheRead * w.cacheRead +
|
|
1097
|
+
e.cacheWrite * w.cacheWrite +
|
|
1098
|
+
e.output * w.output);
|
|
1099
|
+
b.cost.input += e.input * w.input * unit;
|
|
1100
|
+
b.cost.cacheRead += e.cacheRead * w.cacheRead * unit;
|
|
1101
|
+
b.cost.cacheWrite += e.cacheWrite * w.cacheWrite * unit;
|
|
1102
|
+
b.cost.output += e.output * w.output * unit;
|
|
1103
|
+
b.cost.savings += e.cacheRead * (w.input - w.cacheRead) * unit;
|
|
1104
|
+
}
|
|
1105
|
+
return buckets;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
/**
|
|
1109
|
+
* The Cursor account's snapshot. Until a backfill has been posted it covers all history;
|
|
1110
|
+
* after that the same 90 days as the device snapshot, since the server keeps older days.
|
|
1111
|
+
*/
|
|
1112
|
+
async function cursorSnapshot(apiKey, backfill, nowMs, coverageStartMs) {
|
|
1113
|
+
const token = await cursorAccessToken(apiKey);
|
|
1114
|
+
const raw = await cursorEvents(token, backfill ? CURSOR_EARLIEST_MS : coverageStartMs, nowMs + 1);
|
|
1115
|
+
const events = raw.map(parseCursorEvent).filter((e) => e !== null);
|
|
1116
|
+
let firstMs = coverageStartMs;
|
|
1117
|
+
for (const e of events) firstMs = Math.min(firstMs, Math.floor(e.ts / DAY_MS) * DAY_MS);
|
|
1118
|
+
return buildSnapshot(cursorBuckets(events), (b) => b.cost, {
|
|
1119
|
+
deviceId: CURSOR_DEVICE_ID,
|
|
1120
|
+
pricingSource: 'cursor',
|
|
1121
|
+
providers: ['claude', 'codex', 'cursor'],
|
|
1122
|
+
nowMs,
|
|
1123
|
+
coverageStartMs: firstMs
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
|
|
683
1127
|
// ---------------------------------------------------------------------------
|
|
684
1128
|
// Upload
|
|
685
1129
|
|
|
1130
|
+
// fetch quotes the whole header in its error for some of these, which would print the secret.
|
|
1131
|
+
function assertHeaderSafe(secret, name) {
|
|
1132
|
+
if (!/^[\x21-\x7e]+$/.test(secret)) {
|
|
1133
|
+
throw new Error(
|
|
1134
|
+
`${name} contains characters that are not allowed in an HTTP header; check it for spaces or a stray newline`
|
|
1135
|
+
);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
|
|
686
1139
|
async function post(snapshot) {
|
|
687
1140
|
const url = setting('INGEST_URL');
|
|
688
1141
|
const token = setting('INGEST_TOKEN').trim();
|
|
689
1142
|
if (!url || !token) {
|
|
690
1143
|
throw new Error('BIG_SPENDER_INGEST_URL and BIG_SPENDER_INGEST_TOKEN must be set');
|
|
691
1144
|
}
|
|
692
|
-
|
|
693
|
-
if (!/^[\x21-\x7e]+$/.test(token)) {
|
|
694
|
-
throw new Error(
|
|
695
|
-
'the ingest token contains characters that are not allowed in an HTTP header; check it for spaces or a stray newline'
|
|
696
|
-
);
|
|
697
|
-
}
|
|
1145
|
+
assertHeaderSafe(token, 'the ingest token');
|
|
698
1146
|
const body = gzipSync(JSON.stringify(snapshot));
|
|
699
1147
|
let lastErr;
|
|
700
1148
|
for (let attempt = 1; attempt <= POST_ATTEMPTS; attempt++) {
|
|
@@ -709,10 +1157,13 @@ async function post(snapshot) {
|
|
|
709
1157
|
body,
|
|
710
1158
|
signal: AbortSignal.timeout(30_000)
|
|
711
1159
|
});
|
|
712
|
-
const
|
|
1160
|
+
const reply = await res.text();
|
|
1161
|
+
const text = reply.slice(0, 300);
|
|
713
1162
|
if (res.ok) {
|
|
714
|
-
log(
|
|
715
|
-
|
|
1163
|
+
log(
|
|
1164
|
+
`posted ${snapshot.hourly.length} rows for "${snapshot.deviceId}" (${body.length} bytes gzipped): ${text}`
|
|
1165
|
+
);
|
|
1166
|
+
return parseJson(reply)?.result;
|
|
716
1167
|
}
|
|
717
1168
|
lastErr = new Error(`HTTP ${res.status}: ${text}`);
|
|
718
1169
|
// Client errors other than rate limiting won't fix themselves.
|
|
@@ -739,6 +1190,11 @@ async function main() {
|
|
|
739
1190
|
throw new Error('BIG_SPENDER_DEVICE_ID must be a lowercase slug like "laptop" or "desktop"');
|
|
740
1191
|
}
|
|
741
1192
|
}
|
|
1193
|
+
if (deviceId === CURSOR_DEVICE_ID) {
|
|
1194
|
+
throw new Error(
|
|
1195
|
+
`the device id "${CURSOR_DEVICE_ID}" is reserved for Cursor usage; rename this machine with big-spender install --device <id> --rename`
|
|
1196
|
+
);
|
|
1197
|
+
}
|
|
742
1198
|
const release = await acquireLock();
|
|
743
1199
|
if (!release) {
|
|
744
1200
|
log('another run is in progress; skipping');
|
|
@@ -755,19 +1211,64 @@ async function main() {
|
|
|
755
1211
|
await scan(state, resolvePrice, coverageStartMs);
|
|
756
1212
|
await saveState(state);
|
|
757
1213
|
|
|
758
|
-
const
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
1214
|
+
const used = new Set(Object.keys(state.buckets).map((k) => k.split('|')[1]));
|
|
1215
|
+
const device = buildSnapshot(
|
|
1216
|
+
state.buckets,
|
|
1217
|
+
(b, provider, model, tier) => costOf(resolvePrice(provider, model), tier, b),
|
|
1218
|
+
{
|
|
1219
|
+
deviceId: setting('DEVICE_ID'),
|
|
1220
|
+
pricingSource: `litellm@${new Date(pricing.fetchedAt).toISOString().slice(0, 10)}`,
|
|
1221
|
+
// Older servers require the claude and codex counts and reject any other key, so another
|
|
1222
|
+
// provider's count is sent only once this device has used it.
|
|
1223
|
+
providers: Object.keys(SOURCES).filter(
|
|
1224
|
+
(p) => p === 'claude' || p === 'codex' || used.has(p)
|
|
1225
|
+
),
|
|
1226
|
+
nowMs,
|
|
1227
|
+
coverageStartMs
|
|
1228
|
+
}
|
|
764
1229
|
);
|
|
765
|
-
if (
|
|
766
|
-
|
|
767
|
-
printSummary(snapshot, sessions24h, nowMs);
|
|
1230
|
+
if (SUMMARY_ONLY) {
|
|
1231
|
+
printSummary(device.snapshot, device.sessions24h, nowMs);
|
|
768
1232
|
return;
|
|
769
1233
|
}
|
|
770
|
-
|
|
1234
|
+
|
|
1235
|
+
// A Cursor failure is held until this device's snapshot is posted, so it never blocks it.
|
|
1236
|
+
const cursorKey = (process.env.BIG_SPENDER_CURSOR_API_KEY ?? '').trim();
|
|
1237
|
+
const backfillId = shortHash(`${setting('INGEST_URL')}\n${cursorKey}`);
|
|
1238
|
+
const backfill = !(state.cursorBackfills ?? []).includes(backfillId);
|
|
1239
|
+
let cursor = null;
|
|
1240
|
+
let cursorError = null;
|
|
1241
|
+
if (cursorKey) {
|
|
1242
|
+
try {
|
|
1243
|
+
assertHeaderSafe(cursorKey, 'BIG_SPENDER_CURSOR_API_KEY');
|
|
1244
|
+
cursor = await cursorSnapshot(cursorKey, backfill, nowMs, coverageStartMs);
|
|
1245
|
+
} catch (err) {
|
|
1246
|
+
cursorError = new Error(`Cursor: ${err?.message ?? err}`);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
if (DRY_RUN) {
|
|
1251
|
+
for (const built of [device, cursor]) {
|
|
1252
|
+
if (!built) continue;
|
|
1253
|
+
console.log(JSON.stringify(built.snapshot, null, 2));
|
|
1254
|
+
printSummary(built.snapshot, built.sessions24h, nowMs);
|
|
1255
|
+
}
|
|
1256
|
+
if (cursorError) throw cursorError;
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
await post(device.snapshot);
|
|
1260
|
+
if (cursorError) throw cursorError;
|
|
1261
|
+
if (cursor) {
|
|
1262
|
+
const result = await post(cursor.snapshot);
|
|
1263
|
+
if (backfill && result === 'stored') {
|
|
1264
|
+
(state.cursorBackfills ??= []).push(backfillId);
|
|
1265
|
+
await saveState(state);
|
|
1266
|
+
} else if (result !== 'stored') {
|
|
1267
|
+
log(
|
|
1268
|
+
`warning: the server kept a newer "${CURSOR_DEVICE_ID}" snapshot (${result}); is Cursor set up on two machines?`
|
|
1269
|
+
);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
771
1272
|
} finally {
|
|
772
1273
|
await release();
|
|
773
1274
|
}
|
package/dist/install.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Context } from './context.ts';
|
|
2
|
-
export declare const INSTALL_USAGE = "Usage: big-spender install --device <id> [--url <ingest url>] [--rename]\n\nCopies the collector to ~/.local/share/big-spender, schedules it hourly (systemd user timer on\nLinux, launchd agent on macOS) and runs it once. The ingest token comes from the existing env\nfile, BIG_SPENDER_INGEST_TOKEN, or a hidden prompt. It is never taken from a flag.\nRe-running is safe. A usage-collector install from before the rename is migrated in place.\nA machine that already has a device id keeps it: --device with a different id needs --rename,\nbecause the server would count the same history twice, under the old id and the new one.";
|
|
2
|
+
export declare const INSTALL_USAGE = "Usage: big-spender install --device <id> [--url <ingest url>] [--rename] [--cursor]\n\nCopies the collector to ~/.local/share/big-spender, schedules it hourly (systemd user timer on\nLinux, launchd agent on macOS) and runs it once. The ingest token comes from the existing env\nfile, BIG_SPENDER_INGEST_TOKEN, or a hidden prompt. It is never taken from a flag.\nRe-running is safe. A usage-collector install from before the rename is migrated in place.\nA machine that already has a device id keeps it: --device with a different id needs --rename,\nbecause the server would count the same history twice, under the old id and the new one.\n--cursor also reads your Cursor account's usage from Cursor's API and sends it as the device\n\"cursor\". The Cursor API key comes from BIG_SPENDER_CURSOR_API_KEY or a hidden prompt. Set it up\non one machine only. Re-running install without --cursor keeps a key that is already set.";
|
|
3
3
|
export declare function install(args: string[], ctx: Context): Promise<number>;
|
|
4
4
|
export declare const UNINSTALL_USAGE = "Usage: big-spender uninstall\n\nRemoves the schedule. The env file and state are kept.";
|
|
5
5
|
export declare function uninstall(args: string[], ctx: Context): Promise<number>;
|
package/dist/install.js
CHANGED
|
@@ -4,7 +4,7 @@ import { delimiter, dirname, join } from 'node:path';
|
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
5
|
import { UsageError } from './context.js';
|
|
6
6
|
import { parseEnv, renameLegacyKeys, setting, upsertEnv } from './envfile.js';
|
|
7
|
-
import { DEVICE_ID } from './schema.js';
|
|
7
|
+
import { CURSOR_DEVICE_ID, DEVICE_ID } from './schema.js';
|
|
8
8
|
import { pickScheduler } from './scheduler.js';
|
|
9
9
|
// The collector removes its lock when it finishes, so one this young belongs to a live run.
|
|
10
10
|
const LOCK_FRESH_MS = 30 * 60 * 1000;
|
|
@@ -118,21 +118,25 @@ async function existingSettings(ctx) {
|
|
|
118
118
|
token: setting(vars, 'INGEST_TOKEN')
|
|
119
119
|
};
|
|
120
120
|
}
|
|
121
|
-
export const INSTALL_USAGE = `Usage: big-spender install --device <id> [--url <ingest url>] [--rename]
|
|
121
|
+
export const INSTALL_USAGE = `Usage: big-spender install --device <id> [--url <ingest url>] [--rename] [--cursor]
|
|
122
122
|
|
|
123
123
|
Copies the collector to ~/.local/share/big-spender, schedules it hourly (systemd user timer on
|
|
124
124
|
Linux, launchd agent on macOS) and runs it once. The ingest token comes from the existing env
|
|
125
125
|
file, BIG_SPENDER_INGEST_TOKEN, or a hidden prompt. It is never taken from a flag.
|
|
126
126
|
Re-running is safe. A usage-collector install from before the rename is migrated in place.
|
|
127
127
|
A machine that already has a device id keeps it: --device with a different id needs --rename,
|
|
128
|
-
because the server would count the same history twice, under the old id and the new one
|
|
128
|
+
because the server would count the same history twice, under the old id and the new one.
|
|
129
|
+
--cursor also reads your Cursor account's usage from Cursor's API and sends it as the device
|
|
130
|
+
"cursor". The Cursor API key comes from BIG_SPENDER_CURSOR_API_KEY or a hidden prompt. Set it up
|
|
131
|
+
on one machine only. Re-running install without --cursor keeps a key that is already set.`;
|
|
129
132
|
export async function install(args, ctx) {
|
|
130
133
|
const { values } = parseArgs({
|
|
131
134
|
args,
|
|
132
135
|
options: {
|
|
133
136
|
device: { type: 'string' },
|
|
134
137
|
url: { type: 'string' },
|
|
135
|
-
rename: { type: 'boolean' }
|
|
138
|
+
rename: { type: 'boolean' },
|
|
139
|
+
cursor: { type: 'boolean' }
|
|
136
140
|
},
|
|
137
141
|
strict: true
|
|
138
142
|
});
|
|
@@ -142,6 +146,9 @@ export async function install(args, ctx) {
|
|
|
142
146
|
if (!DEVICE_ID.test(deviceId)) {
|
|
143
147
|
throw new UsageError('--device must be a lowercase slug such as laptop or desktop');
|
|
144
148
|
}
|
|
149
|
+
if (deviceId === CURSOR_DEVICE_ID) {
|
|
150
|
+
throw new UsageError(`the device id "${CURSOR_DEVICE_ID}" is reserved for Cursor usage`);
|
|
151
|
+
}
|
|
145
152
|
if (existing.deviceId && deviceId !== existing.deviceId && !values.rename) {
|
|
146
153
|
throw new UsageError(`this machine already reports as "${existing.deviceId}", not "${deviceId}". Under a new id the server would count the same usage twice, because ${existing.deviceId}.json stays on the server next to the new one. Keep "${existing.deviceId}", or pass --rename if you mean to change it and will remove the old device's data on the server`);
|
|
147
154
|
}
|
|
@@ -165,6 +172,16 @@ export async function install(args, ctx) {
|
|
|
165
172
|
token = await ctx.prompter().askHidden('Ingest token: ');
|
|
166
173
|
if (!url || !token)
|
|
167
174
|
throw new UsageError('an ingest URL and token are required');
|
|
175
|
+
let cursorKey = '';
|
|
176
|
+
if (values.cursor) {
|
|
177
|
+
cursorKey = (ctx.env.BIG_SPENDER_CURSOR_API_KEY || (await ctx.prompter().askHidden('Cursor API key: '))).trim();
|
|
178
|
+
if (!cursorKey)
|
|
179
|
+
throw new UsageError('--cursor needs a Cursor API key');
|
|
180
|
+
// A newline would end the env file line and start another setting.
|
|
181
|
+
if (!/^[\x21-\x7e]+$/.test(cursorKey)) {
|
|
182
|
+
throw new UsageError('the Cursor API key contains spaces, line breaks or other characters it cannot have');
|
|
183
|
+
}
|
|
184
|
+
}
|
|
168
185
|
const log = [];
|
|
169
186
|
if (legacySchedule.length > 0 && (cachePlan === 'move' || cachePlan === 'replace')) {
|
|
170
187
|
await writeFile(wasScheduled, '');
|
|
@@ -183,7 +200,8 @@ export async function install(args, ctx) {
|
|
|
183
200
|
await writePrivate(paths.envFile, upsertEnv(base, {
|
|
184
201
|
BIG_SPENDER_DEVICE_ID: deviceId,
|
|
185
202
|
BIG_SPENDER_INGEST_URL: url,
|
|
186
|
-
BIG_SPENDER_INGEST_TOKEN: token
|
|
203
|
+
BIG_SPENDER_INGEST_TOKEN: token,
|
|
204
|
+
...(cursorKey ? { BIG_SPENDER_CURSOR_API_KEY: cursorKey } : {})
|
|
187
205
|
}));
|
|
188
206
|
await mkdir(paths.shareDir, { recursive: true });
|
|
189
207
|
await copyFile(ctx.collector, paths.collector);
|
package/dist/push.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { type Context } from './context.ts';
|
|
2
|
-
export declare const PUSH_USAGE = "Usage: big-spender push <device> [--dry-run] [--url <ingest url>]\n\nOne-off push from a machine without a schedule. Builds the snapshot, shows what it would publish\nand stops if a model name looks like a cloud resource id (for example a Bedrock inference-profile\nARN, which contains an account id). Asks before sending. The URL comes from --url,\nBIG_SPENDER_INGEST_URL or a prompt, and the token from BIG_SPENDER_INGEST_TOKEN or a hidden\nprompt, so neither is written to this machine. Nothing is scheduled.\n\n--dry-run prints the overview, writes the exact JSON that would be sent to\n$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the\ncollector's local state in ~/.cache/big-spender (which logs were read), never anything remote.";
|
|
2
|
+
export declare const PUSH_USAGE = "Usage: big-spender push <device> [--dry-run] [--url <ingest url>]\n\nOne-off push from a machine without a schedule. Builds the snapshot, shows what it would publish\nand stops if a model name looks like a cloud resource id (for example a Bedrock inference-profile\nARN, which contains an account id). Asks before sending. The URL comes from --url,\nBIG_SPENDER_INGEST_URL or a prompt, and the token from BIG_SPENDER_INGEST_TOKEN or a hidden\nprompt, so neither is written to this machine. Nothing is scheduled.\n\n--dry-run prints the overview, writes the exact JSON that would be sent to\n$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the\ncollector's local state in ~/.cache/big-spender (which logs were read), never anything remote.\nCursor usage is not part of a push: only the scheduled collector sends it.";
|
|
3
3
|
export declare function push(args: string[], ctx: Context): Promise<number>;
|
package/dist/push.js
CHANGED
|
@@ -5,7 +5,7 @@ import { parseArgs } from 'node:util';
|
|
|
5
5
|
import { gzipSync } from 'node:zlib';
|
|
6
6
|
import { UsageError } from './context.js';
|
|
7
7
|
import { parseEnv, setting } from './envfile.js';
|
|
8
|
-
import { DEVICE_ID } from './schema.js';
|
|
8
|
+
import { CURSOR_DEVICE_ID, DEVICE_ID } from './schema.js';
|
|
9
9
|
export const PUSH_USAGE = `Usage: big-spender push <device> [--dry-run] [--url <ingest url>]
|
|
10
10
|
|
|
11
11
|
One-off push from a machine without a schedule. Builds the snapshot, shows what it would publish
|
|
@@ -16,7 +16,8 @@ prompt, so neither is written to this machine. Nothing is scheduled.
|
|
|
16
16
|
|
|
17
17
|
--dry-run prints the overview, writes the exact JSON that would be sent to
|
|
18
18
|
$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the
|
|
19
|
-
collector's local state in ~/.cache/big-spender (which logs were read), never anything remote
|
|
19
|
+
collector's local state in ~/.cache/big-spender (which logs were read), never anything remote.
|
|
20
|
+
Cursor usage is not part of a push: only the scheduled collector sends it.`;
|
|
20
21
|
const MAX_SNAPSHOT_BYTES = 512 * 1024 * 1024;
|
|
21
22
|
const POST_ATTEMPTS = 4;
|
|
22
23
|
function runCollector(ctx, extraEnv, args) {
|
|
@@ -72,7 +73,10 @@ export async function push(args, ctx) {
|
|
|
72
73
|
if (positionals.length !== 1 || !DEVICE_ID.test(deviceId)) {
|
|
73
74
|
throw new UsageError('<device> must be a lowercase slug such as laptop or desktop');
|
|
74
75
|
}
|
|
75
|
-
|
|
76
|
+
if (deviceId === CURSOR_DEVICE_ID) {
|
|
77
|
+
throw new UsageError(`the device id "${CURSOR_DEVICE_ID}" is reserved for Cursor usage`);
|
|
78
|
+
}
|
|
79
|
+
const built = await runCollector(ctx, { BIG_SPENDER_DEVICE_ID: deviceId, BIG_SPENDER_CURSOR_API_KEY: '' }, ['--dry-run']);
|
|
76
80
|
if (built.code !== 0) {
|
|
77
81
|
ctx.err(built.stderr.trimEnd());
|
|
78
82
|
return 1;
|
package/dist/schema.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { z } from 'zod';
|
|
|
2
2
|
export declare const EARLIEST_DATE = "2020-01-01T00:00:00Z";
|
|
3
3
|
export declare const MAX_ROWS = 50000;
|
|
4
4
|
export declare const DEVICE_ID: RegExp;
|
|
5
|
-
export declare const
|
|
5
|
+
export declare const CURSOR_DEVICE_ID = "cursor";
|
|
6
|
+
export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi'];
|
|
6
7
|
export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
|
|
7
8
|
export declare const usageRowSchema: z.ZodObject<{
|
|
8
9
|
hour: z.ZodISODateTime;
|
|
@@ -13,6 +14,8 @@ export declare const usageRowSchema: z.ZodObject<{
|
|
|
13
14
|
provider: z.ZodEnum<{
|
|
14
15
|
claude: "claude";
|
|
15
16
|
codex: "codex";
|
|
17
|
+
cursor: "cursor";
|
|
18
|
+
pi: "pi";
|
|
16
19
|
}>;
|
|
17
20
|
model: z.ZodString;
|
|
18
21
|
sessions: z.ZodNumber;
|
|
@@ -44,6 +47,8 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
44
47
|
provider: z.ZodEnum<{
|
|
45
48
|
claude: "claude";
|
|
46
49
|
codex: "codex";
|
|
50
|
+
cursor: "cursor";
|
|
51
|
+
pi: "pi";
|
|
47
52
|
}>;
|
|
48
53
|
model: z.ZodString;
|
|
49
54
|
sessions: z.ZodNumber;
|
|
@@ -66,21 +71,29 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
66
71
|
claude: z.ZodNumber;
|
|
67
72
|
codex: z.ZodNumber;
|
|
68
73
|
all: z.ZodNumber;
|
|
74
|
+
cursor: z.ZodOptional<z.ZodNumber>;
|
|
75
|
+
pi: z.ZodOptional<z.ZodNumber>;
|
|
69
76
|
}, z.core.$strict>>;
|
|
70
77
|
'7d': z.ZodObject<{
|
|
71
78
|
claude: z.ZodNumber;
|
|
72
79
|
codex: z.ZodNumber;
|
|
73
80
|
all: z.ZodNumber;
|
|
81
|
+
cursor: z.ZodOptional<z.ZodNumber>;
|
|
82
|
+
pi: z.ZodOptional<z.ZodNumber>;
|
|
74
83
|
}, z.core.$strict>;
|
|
75
84
|
'30d': z.ZodObject<{
|
|
76
85
|
claude: z.ZodNumber;
|
|
77
86
|
codex: z.ZodNumber;
|
|
78
87
|
all: z.ZodNumber;
|
|
88
|
+
cursor: z.ZodOptional<z.ZodNumber>;
|
|
89
|
+
pi: z.ZodOptional<z.ZodNumber>;
|
|
79
90
|
}, z.core.$strict>;
|
|
80
91
|
'90d': z.ZodObject<{
|
|
81
92
|
claude: z.ZodNumber;
|
|
82
93
|
codex: z.ZodNumber;
|
|
83
94
|
all: z.ZodNumber;
|
|
95
|
+
cursor: z.ZodOptional<z.ZodNumber>;
|
|
96
|
+
pi: z.ZodOptional<z.ZodNumber>;
|
|
84
97
|
}, z.core.$strict>;
|
|
85
98
|
}, z.core.$strict>>;
|
|
86
99
|
}, z.core.$strict>;
|
package/dist/schema.js
CHANGED
|
@@ -12,7 +12,9 @@ const isoDate = z.iso
|
|
|
12
12
|
.refine((s) => Date.parse(s) >= Date.parse(EARLIEST_DATE), `must be ${EARLIEST_DATE} or later`);
|
|
13
13
|
export const MAX_ROWS = 50_000;
|
|
14
14
|
export const DEVICE_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
15
|
-
|
|
15
|
+
// Collectors send the Cursor account's usage under this id, so no machine may use it.
|
|
16
|
+
export const CURSOR_DEVICE_ID = 'cursor';
|
|
17
|
+
export const PROVIDERS = ['claude', 'codex', 'cursor', 'pi'];
|
|
16
18
|
// Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
|
|
17
19
|
// than a day: an hourly view would show when each machine is in use.
|
|
18
20
|
export const RANGES = ['7d', '30d', '90d', 'all'];
|
|
@@ -34,10 +36,12 @@ export const usageRowSchema = z.strictObject({
|
|
|
34
36
|
costUsd: z.strictObject({ input: usd, cacheRead: usd, cacheWrite: usd, output: usd }),
|
|
35
37
|
cacheSavingsUsd: usd
|
|
36
38
|
});
|
|
39
|
+
const count = z.number().int().nonnegative();
|
|
37
40
|
const sessionCount = z.strictObject({
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
+
...Object.fromEntries(PROVIDERS.map((p) => [p, count.optional()])),
|
|
42
|
+
claude: count,
|
|
43
|
+
codex: count,
|
|
44
|
+
all: count
|
|
41
45
|
});
|
|
42
46
|
export const usageSnapshotSchema = z.strictObject({
|
|
43
47
|
schemaVersion: z.literal(1),
|
package/dist/server/ingest.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
-
import { usageSnapshotSchema } from '../schema.js';
|
|
2
|
+
import { CURSOR_DEVICE_ID, usageSnapshotSchema } from '../schema.js';
|
|
3
3
|
// Collectors POST one device's full snapshot here (optionally gzip-encoded).
|
|
4
4
|
const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
|
5
5
|
const MAX_DECODED_BYTES = 16 * 1024 * 1024;
|
|
@@ -80,7 +80,14 @@ export function createIngest({ store, token, onStored }) {
|
|
|
80
80
|
.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);
|
|
81
81
|
return Response.json({ error: 'invalid snapshot', issues }, { status: 422 });
|
|
82
82
|
}
|
|
83
|
-
|
|
83
|
+
// Checked here, not in the schema: a stored file from before the reservation must still load.
|
|
84
|
+
const snap = parsed.data;
|
|
85
|
+
if (snap.deviceId === CURSOR_DEVICE_ID &&
|
|
86
|
+
(snap.pricingSource !== 'cursor' || snap.hourly.some((r) => r.provider !== 'cursor'))) {
|
|
87
|
+
const issues = [`deviceId: "${CURSOR_DEVICE_ID}" is reserved for Cursor usage`];
|
|
88
|
+
return Response.json({ error: 'invalid snapshot', issues }, { status: 422 });
|
|
89
|
+
}
|
|
90
|
+
const result = await store.save(snap);
|
|
84
91
|
if (result === 'stored')
|
|
85
92
|
onStored();
|
|
86
93
|
return Response.json({
|
package/dist/summary.js
CHANGED
|
@@ -119,10 +119,11 @@ function summarizeRange(range, snapshots, now, resolved) {
|
|
|
119
119
|
// that has usage inside this window, so an offline device's old sessions drop out.
|
|
120
120
|
if (counts) {
|
|
121
121
|
for (const id of active) {
|
|
122
|
-
|
|
122
|
+
const n = counts[id];
|
|
123
|
+
if (!n)
|
|
123
124
|
continue;
|
|
124
|
-
sessions +=
|
|
125
|
-
provider(id).sessions +=
|
|
125
|
+
sessions += n;
|
|
126
|
+
provider(id).sessions += n;
|
|
126
127
|
}
|
|
127
128
|
}
|
|
128
129
|
}
|
package/package.json
CHANGED
package/templates/env.example
CHANGED
|
@@ -7,3 +7,6 @@ BIG_SPENDER_DEVICE_ID=
|
|
|
7
7
|
BIG_SPENDER_INGEST_URL=
|
|
8
8
|
# Same value as BIG_SPENDER_INGEST_TOKEN on the server.
|
|
9
9
|
BIG_SPENDER_INGEST_TOKEN=
|
|
10
|
+
# Optional, on one machine only: a Cursor user API key. The collector then reads the account's
|
|
11
|
+
# usage from Cursor's API and sends it as the device "cursor". Set by `big-spender install --cursor`.
|
|
12
|
+
# BIG_SPENDER_CURSOR_API_KEY=
|