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 +142 -16
- package/dist/collector.mjs +740 -91
- package/dist/history.js +6 -2
- package/dist/install.d.ts +1 -1
- package/dist/install.js +23 -5
- package/dist/limits.d.ts +48 -0
- package/dist/limits.js +140 -0
- package/dist/page.d.ts +2 -1
- package/dist/page.js +29 -2
- package/dist/push.d.ts +1 -1
- package/dist/push.js +32 -6
- package/dist/schema.d.ts +40 -1
- package/dist/schema.js +24 -5
- package/dist/serve.js +7 -1
- package/dist/server/index.d.ts +5 -1
- package/dist/server/index.js +12 -1
- 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/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,17 +118,25 @@ 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
|
-
*
|
|
128
|
+
* One subscription usage window instance; see limitWindowSchema in src/schema.ts.
|
|
129
|
+
* @typedef {{ provider: string, window: string, resetsAt: string, peakPercent: number, hitAt?: string }} Limit
|
|
130
|
+
* @typedef {{ version: number, files: Record<string, FileState>, seen: Record<string, Seen>, buckets: Record<string, Bucket>, limits?: Record<string, Limit>, fixes?: string[], rescan?: string[], cursorBackfills?: string[] }} State
|
|
131
|
+
* cursorBackfills holds a hash of each ingest URL and Cursor API key pair whose server stored the
|
|
132
|
+
* account's full history. Hashed, because an ingest URL can carry a credential.
|
|
109
133
|
*/
|
|
110
134
|
|
|
111
135
|
// One-time fixes to existing state. The state version stays the same so an older installed copy
|
|
112
136
|
// can still read the file instead of discarding it.
|
|
113
137
|
const FIX_CLAUDE_OUTPUT = 'claude-final-output';
|
|
138
|
+
// Limit windows are read from log lines older versions skipped, so those logs are re-read once.
|
|
139
|
+
const FIX_LIMITS = 'usage-limits';
|
|
114
140
|
|
|
115
141
|
/** @returns {Promise<State>} */
|
|
116
142
|
async function loadState() {
|
|
@@ -119,18 +145,24 @@ async function loadState() {
|
|
|
119
145
|
files: {},
|
|
120
146
|
seen: {},
|
|
121
147
|
buckets: {},
|
|
122
|
-
|
|
148
|
+
limits: {},
|
|
149
|
+
fixes: [FIX_CLAUDE_OUTPUT, FIX_LIMITS]
|
|
123
150
|
};
|
|
124
151
|
if (RESET) return empty;
|
|
125
152
|
try {
|
|
126
153
|
const s = JSON.parse(await readFile(STATE_PATH, 'utf8'));
|
|
127
154
|
if (s?.version !== STATE_VERSION) return empty;
|
|
128
155
|
s.fixes ??= [];
|
|
156
|
+
s.limits ??= {};
|
|
129
157
|
if (!s.fixes.includes(FIX_CLAUDE_OUTPUT)) {
|
|
130
158
|
// Older versions kept the first log line of a Claude message, whose output count can be
|
|
131
159
|
// partial. Re-read the Claude logs once so later lines add what was missed.
|
|
132
160
|
s.fixes.push(FIX_CLAUDE_OUTPUT);
|
|
133
|
-
s.
|
|
161
|
+
s.rescan = ['claude'];
|
|
162
|
+
}
|
|
163
|
+
if (!s.fixes.includes(FIX_LIMITS)) {
|
|
164
|
+
s.fixes.push(FIX_LIMITS);
|
|
165
|
+
s.rescan = [...new Set([...(s.rescan ?? []), 'claude', 'codex'])];
|
|
134
166
|
}
|
|
135
167
|
return s;
|
|
136
168
|
} catch {
|
|
@@ -182,6 +214,99 @@ function pruneState(state, cutoffMs) {
|
|
|
182
214
|
for (const [key, v] of Object.entries(state.seen)) {
|
|
183
215
|
if ((Array.isArray(v) ? v[0] : v) < cutoffMs) delete state.seen[key];
|
|
184
216
|
}
|
|
217
|
+
for (const [key, w] of Object.entries(state.limits ?? {})) {
|
|
218
|
+
if (Date.parse(w.resetsAt) < cutoffMs) delete state.limits[key];
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Same rule as mergeLimits in src/limits.ts (this file ships alone, so it cannot import it): one
|
|
223
|
+
// record per window instance, highest peak, earliest hit. Reports of one window can put its reset
|
|
224
|
+
// seconds apart, across a minute boundary, so a reset within RESET_SLACK_MS of a known one of the
|
|
225
|
+
// same window is that one, and the record keeps the earlier reset.
|
|
226
|
+
const MINUTE_MS = 60_000;
|
|
227
|
+
const RESET_SLACK_MS = 2 * MINUTE_MS;
|
|
228
|
+
// Times outside this range are malformed (milliseconds read as seconds, say) and are skipped,
|
|
229
|
+
// never thrown, so a bad limit line cannot stop the usage on the lines after it.
|
|
230
|
+
const LIMIT_TIMES_FROM = Date.parse('2020-01-01T00:00:00Z');
|
|
231
|
+
const LIMIT_TIMES_TO = Date.parse('2100-01-01T00:00:00Z');
|
|
232
|
+
const plausibleTime = (ms) => ms >= LIMIT_TIMES_FROM && ms < LIMIT_TIMES_TO;
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* @param {State} state
|
|
236
|
+
* @param {{ provider: string, window: string, resetsAtMs: number, percent: number, hitMs?: number }} w
|
|
237
|
+
*/
|
|
238
|
+
function addLimit(state, w) {
|
|
239
|
+
let resetsAtMs = Math.floor(w.resetsAtMs / MINUTE_MS) * MINUTE_MS;
|
|
240
|
+
if (!plausibleTime(resetsAtMs) || !/^[a-z0-9_]{1,40}$/.test(w.window)) return;
|
|
241
|
+
if (w.hitMs !== undefined && !plausibleTime(w.hitMs)) return;
|
|
242
|
+
state.limits ??= {};
|
|
243
|
+
let prev;
|
|
244
|
+
for (const [key, l] of Object.entries(state.limits)) {
|
|
245
|
+
const gap = Math.abs(Date.parse(l.resetsAt) - resetsAtMs);
|
|
246
|
+
if (l.provider !== w.provider || l.window !== w.window || gap > RESET_SLACK_MS) continue;
|
|
247
|
+
if (prev && gap >= Math.abs(Date.parse(prev[1].resetsAt) - resetsAtMs)) continue;
|
|
248
|
+
prev = [key, l];
|
|
249
|
+
}
|
|
250
|
+
if (prev) {
|
|
251
|
+
delete state.limits[prev[0]];
|
|
252
|
+
resetsAtMs = Math.min(resetsAtMs, Date.parse(prev[1].resetsAt));
|
|
253
|
+
}
|
|
254
|
+
const hits = [prev?.[1].hitAt && Date.parse(prev[1].hitAt), w.hitMs].filter(Number.isFinite);
|
|
255
|
+
const percent = Math.min(100, Math.max(0, w.percent));
|
|
256
|
+
state.limits[`${w.provider}|${w.window}|${resetsAtMs}`] = {
|
|
257
|
+
provider: w.provider,
|
|
258
|
+
window: w.window,
|
|
259
|
+
resetsAt: new Date(resetsAtMs).toISOString(),
|
|
260
|
+
peakPercent: Math.max(prev?.[1].peakPercent ?? 0, percent),
|
|
261
|
+
...(hits.length ? { hitAt: new Date(Math.min(...hits)).toISOString() } : {})
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Claude Code logs a refused request as a synthetic assistant line carrying quotaLimits.
|
|
266
|
+
// One blocked window repeats on every retry; the key makes the repeats one record.
|
|
267
|
+
function claudeLimit(state, o) {
|
|
268
|
+
const q = o.quotaLimits;
|
|
269
|
+
if (q?.status !== 'rejected' || typeof q.rateLimitType !== 'string') return;
|
|
270
|
+
const ts = Date.parse(o.timestamp);
|
|
271
|
+
if (!Number.isFinite(ts) || !(q.resetsAt > 0)) return;
|
|
272
|
+
addLimit(state, {
|
|
273
|
+
provider: 'claude',
|
|
274
|
+
window: q.rateLimitType
|
|
275
|
+
.toLowerCase()
|
|
276
|
+
.replace(/[^a-z0-9_]/g, '_')
|
|
277
|
+
.slice(0, 40),
|
|
278
|
+
resetsAtMs: q.resetsAt * 1000,
|
|
279
|
+
percent: 100,
|
|
280
|
+
hitMs: ts
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const CODEX_WINDOW_NAMES = { 300: 'five_hour', 10080: 'seven_day' };
|
|
285
|
+
|
|
286
|
+
// Codex token_count lines carry the account's rate limits; a window is null until it is in use.
|
|
287
|
+
function codexLimits(state, o, rateLimits) {
|
|
288
|
+
const ts = Date.parse(o.timestamp);
|
|
289
|
+
if (!Number.isFinite(ts) || !rateLimits) return;
|
|
290
|
+
for (const slot of ['primary', 'secondary']) {
|
|
291
|
+
const w = rateLimits[slot];
|
|
292
|
+
if (!w || typeof w.used_percent !== 'number') continue;
|
|
293
|
+
const minutes = Number(w.window_minutes);
|
|
294
|
+
const window = CODEX_WINDOW_NAMES[minutes] ?? `${minutes}m`;
|
|
295
|
+
const resetsAtMs =
|
|
296
|
+
typeof w.resets_at === 'number'
|
|
297
|
+
? w.resets_at * 1000
|
|
298
|
+
: typeof w.resets_in_seconds === 'number'
|
|
299
|
+
? ts + w.resets_in_seconds * 1000
|
|
300
|
+
: NaN;
|
|
301
|
+
const hit = w.used_percent >= 100;
|
|
302
|
+
addLimit(state, {
|
|
303
|
+
provider: 'codex',
|
|
304
|
+
window,
|
|
305
|
+
resetsAtMs,
|
|
306
|
+
percent: hit ? 100 : w.used_percent,
|
|
307
|
+
...(hit ? { hitMs: ts } : {})
|
|
308
|
+
});
|
|
309
|
+
}
|
|
185
310
|
}
|
|
186
311
|
|
|
187
312
|
// ---------------------------------------------------------------------------
|
|
@@ -212,7 +337,12 @@ async function loadPricing() {
|
|
|
212
337
|
}
|
|
213
338
|
}
|
|
214
339
|
|
|
215
|
-
|
|
340
|
+
const litellmKeys = (prefix) => (model) =>
|
|
341
|
+
[model, model.replace(/-\d{8}$/, ''), model.replace(/@.*$/, '')].flatMap((base) => [
|
|
342
|
+
base,
|
|
343
|
+
`${prefix}/${base}`
|
|
344
|
+
]);
|
|
345
|
+
|
|
216
346
|
function makePriceResolver(models) {
|
|
217
347
|
const memo = new Map();
|
|
218
348
|
const warned = new Set();
|
|
@@ -220,18 +350,8 @@ function makePriceResolver(models) {
|
|
|
220
350
|
return (provider, model) => {
|
|
221
351
|
const memoKey = `${provider}|${model}`;
|
|
222
352
|
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
|
-
}
|
|
353
|
+
const key = SOURCES[provider]?.priceKeys(model).find((k) => usable(models[k]));
|
|
354
|
+
const entry = key ? models[key] : null;
|
|
235
355
|
if (!entry && !warned.has(memoKey)) {
|
|
236
356
|
warned.add(memoKey);
|
|
237
357
|
log(`warning: no LiteLLM price for ${provider} model "${model}"; counting its cost as 0`);
|
|
@@ -267,7 +387,7 @@ function price(entry, base, tier) {
|
|
|
267
387
|
return typeof v === 'number' ? v : undefined;
|
|
268
388
|
}
|
|
269
389
|
|
|
270
|
-
/** Cost breakdown in USD for a bucket's tokens. */
|
|
390
|
+
/** Cost breakdown in USD for a bucket's tokens. @returns {Cost} */
|
|
271
391
|
function costOf(entry, tier, t) {
|
|
272
392
|
if (!entry) return { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, savings: 0 };
|
|
273
393
|
const inP = price(entry, 'input_cost_per_token', tier) ?? 0;
|
|
@@ -347,6 +467,7 @@ function claudeLineHandler(state, resolvePrice, cutoffMs) {
|
|
|
347
467
|
if (!line.includes('"assistant"')) return;
|
|
348
468
|
const o = parseJson(line);
|
|
349
469
|
if (!o || o.type !== 'assistant') return;
|
|
470
|
+
if (o.quotaLimits) claudeLimit(state, o);
|
|
350
471
|
const msg = o.message;
|
|
351
472
|
const usage = msg?.usage;
|
|
352
473
|
const model = msg?.model;
|
|
@@ -425,7 +546,9 @@ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSess
|
|
|
425
546
|
fileState.model = p.model;
|
|
426
547
|
return;
|
|
427
548
|
}
|
|
428
|
-
if (o.type !== 'event_msg' || p?.type !== 'token_count'
|
|
549
|
+
if (o.type !== 'event_msg' || p?.type !== 'token_count') return;
|
|
550
|
+
codexLimits(state, o, p.rate_limits);
|
|
551
|
+
if (!p.info) return;
|
|
429
552
|
const total = p.info.total_token_usage?.total_tokens;
|
|
430
553
|
if (typeof total === 'number') {
|
|
431
554
|
if (total === fileState.lastTotal) return;
|
|
@@ -459,27 +582,175 @@ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSess
|
|
|
459
582
|
};
|
|
460
583
|
}
|
|
461
584
|
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
585
|
+
const expandHome = (p) => (p === '~' || p.startsWith('~/') ? join(HOME, p.slice(1)) : p);
|
|
586
|
+
|
|
587
|
+
// pi's own env vars, then ccusage's PI_AGENT_DIR (a comma-separated list of sessions dirs).
|
|
588
|
+
const piEnvPaths = () => [
|
|
589
|
+
...(process.env.PI_CODING_AGENT_DIR
|
|
590
|
+
? [join(expandHome(process.env.PI_CODING_AGENT_DIR), 'sessions')]
|
|
591
|
+
: []),
|
|
592
|
+
...(process.env.PI_CODING_AGENT_SESSION_DIR
|
|
593
|
+
? [expandHome(process.env.PI_CODING_AGENT_SESSION_DIR)]
|
|
594
|
+
: []),
|
|
595
|
+
...(process.env.PI_AGENT_DIR ?? '')
|
|
596
|
+
.split(',')
|
|
597
|
+
.map((p) => p.trim())
|
|
598
|
+
.filter(Boolean)
|
|
599
|
+
];
|
|
600
|
+
const piPaths = () => [join(HOME, '.pi', 'agent', 'sessions'), ...piEnvPaths()];
|
|
601
|
+
|
|
602
|
+
// The pi-subagents extension writes debug copies of calls that a session file already has.
|
|
603
|
+
const isSubagentCopy = (path) => path.split(sep).includes('subagent-artifacts');
|
|
604
|
+
|
|
605
|
+
// pi's input excludes cached tokens and its output includes reasoning.
|
|
606
|
+
function piUsage(o) {
|
|
607
|
+
const msg = o.message;
|
|
608
|
+
if ((o.type !== undefined && o.type !== 'message') || msg?.role !== 'assistant') return null;
|
|
609
|
+
const u = msg.usage;
|
|
610
|
+
if (!u) return null;
|
|
611
|
+
const ts = Date.parse(o.timestamp);
|
|
612
|
+
if (!Number.isFinite(ts)) return null;
|
|
613
|
+
// Token counts are integers; ccusage reads anything else as 0, and the schema rejects it.
|
|
614
|
+
const count = (v) => (Number.isInteger(v) ? num(v) : 0);
|
|
615
|
+
const input = count(u.input);
|
|
616
|
+
const cacheRead = count(u.cacheRead);
|
|
617
|
+
const cacheWrite = count(u.cacheWrite);
|
|
618
|
+
// pi reports the part of cacheWrite written with 1-hour retention (Anthropic only).
|
|
619
|
+
const cacheWrite1h = Math.min(count(u.cacheWrite1h), cacheWrite);
|
|
620
|
+
let output = count(u.output);
|
|
621
|
+
const parts = input + output + cacheRead + cacheWrite;
|
|
622
|
+
const total = Math.max(parts, count(u.totalTokens));
|
|
623
|
+
if (total === 0) return null;
|
|
624
|
+
// When output is 0, tokens the total has beyond the parts count as output, as ccusage does.
|
|
625
|
+
if (output === 0) output = total - parts;
|
|
626
|
+
const model = typeof msg.model === 'string' && msg.model ? msg.model : 'unknown';
|
|
627
|
+
const fingerprint = [
|
|
628
|
+
ts,
|
|
629
|
+
model,
|
|
630
|
+
input,
|
|
631
|
+
output,
|
|
632
|
+
cacheRead,
|
|
633
|
+
cacheWrite,
|
|
634
|
+
total,
|
|
635
|
+
num(u.cost?.total)
|
|
636
|
+
].join('|');
|
|
637
|
+
return { ts, model, input, output, cacheRead, cacheWrite, cacheWrite1h, fingerprint };
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function piCallsIn(path, untilMs) {
|
|
641
|
+
const calls = [];
|
|
642
|
+
let text;
|
|
643
|
+
try {
|
|
644
|
+
text = readFileSync(path, 'utf8');
|
|
645
|
+
} catch {
|
|
646
|
+
return calls;
|
|
470
647
|
}
|
|
471
|
-
|
|
472
|
-
|
|
648
|
+
for (const line of text.split('\n')) {
|
|
649
|
+
if (!line.includes('"usage"')) continue;
|
|
650
|
+
const o = parseJson(line);
|
|
651
|
+
const u = o && piUsage(o);
|
|
652
|
+
if (u && u.ts <= untilMs) calls.push(shortHash(u.fingerprint));
|
|
473
653
|
}
|
|
654
|
+
return calls;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// LiteLLM's prefixes for the providers pi talks to.
|
|
658
|
+
const PI_PRICE_PREFIXES = [
|
|
659
|
+
'anthropic',
|
|
660
|
+
'openai',
|
|
661
|
+
'gemini',
|
|
662
|
+
'openrouter',
|
|
663
|
+
'xai',
|
|
664
|
+
'groq',
|
|
665
|
+
'cerebras',
|
|
666
|
+
'mistral',
|
|
667
|
+
'deepseek',
|
|
668
|
+
'fireworks_ai',
|
|
669
|
+
'together_ai',
|
|
670
|
+
'zai',
|
|
671
|
+
'moonshot',
|
|
672
|
+
'minimax'
|
|
673
|
+
];
|
|
474
674
|
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
675
|
+
// Local models can have a file path as their id; only the file name leaves the machine.
|
|
676
|
+
const piModel = (model) => {
|
|
677
|
+
const isPath =
|
|
678
|
+
/^([/~.]|[A-Za-z]:)|\\|:\/|\/\//.test(model) ||
|
|
679
|
+
/\.(gguf|ggml|bin|safetensors|pth?|onnx)$/i.test(model);
|
|
680
|
+
const name = isPath ? (model.split(/[/\\]/).filter(Boolean).at(-1) ?? 'unknown') : model;
|
|
681
|
+
return name.replace(/[^A-Za-z0-9._:/@-]/g, '-').slice(0, 100);
|
|
682
|
+
};
|
|
683
|
+
|
|
684
|
+
// A pi fork starts with a copy of its parent's calls up to the fork point. They are matched
|
|
685
|
+
// against every call in the parent up to then, not only its current branch, so the result does
|
|
686
|
+
// not depend on where the parent's leaf was when the fork was read.
|
|
687
|
+
function piLineHandler(state, file, path, resolvePrice, cutoffMs) {
|
|
688
|
+
if (isSubagentCopy(path)) return () => {};
|
|
689
|
+
/** @type {Set<string> | undefined} */
|
|
690
|
+
let parentCalls;
|
|
691
|
+
return (line) => {
|
|
692
|
+
if (!line.includes('"usage"') && !line.includes('"session"')) return;
|
|
693
|
+
const o = parseJson(line);
|
|
694
|
+
if (!o) return;
|
|
695
|
+
if (o.type === 'session') {
|
|
696
|
+
if (typeof o.id === 'string' && o.id) file.sessionId = o.id;
|
|
697
|
+
const forkMs = Date.parse(o.timestamp);
|
|
698
|
+
if (typeof o.parentSession !== 'string' || !o.parentSession || !Number.isFinite(forkMs)) {
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
const parent = resolve(dirname(path), o.parentSession);
|
|
702
|
+
const inStore = piPaths().some((root) => parent.startsWith(resolve(root) + sep));
|
|
703
|
+
if (parent === path || !inStore || isSubagentCopy(parent)) return;
|
|
704
|
+
// Kept in state, so a fork read across runs still matches if the parent changes or goes.
|
|
705
|
+
const calls = piCallsIn(parent, forkMs);
|
|
706
|
+
if (calls.length) file.forkCalls = calls;
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
const u = piUsage(o);
|
|
710
|
+
if (!u) return;
|
|
711
|
+
const session = file.sessionId ?? path;
|
|
712
|
+
// No entry ids in the key: pi rewrites a file in place when it migrates an older version.
|
|
713
|
+
const dedupe = `p:${shortHash(`${session}:${u.fingerprint}`)}`;
|
|
714
|
+
if (file.forkCalls) {
|
|
715
|
+
parentCalls ??= new Set(file.forkCalls);
|
|
716
|
+
if (parentCalls.has(shortHash(u.fingerprint))) {
|
|
717
|
+
// Seen, so a re-read after the fork is rewritten still skips it.
|
|
718
|
+
state.seen[dedupe] = u.ts;
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
delete file.forkCalls;
|
|
722
|
+
}
|
|
723
|
+
if (u.ts < cutoffMs) return;
|
|
724
|
+
if (state.seen[dedupe] !== undefined) return;
|
|
725
|
+
state.seen[dedupe] = u.ts;
|
|
726
|
+
const model = piModel(u.model);
|
|
727
|
+
addRecord(state, {
|
|
728
|
+
ts: u.ts,
|
|
729
|
+
provider: 'pi',
|
|
730
|
+
model,
|
|
731
|
+
tier: tierFor(resolvePrice('pi', model), u.input + u.cacheRead + u.cacheWrite),
|
|
732
|
+
session: shortHash(`pi:${session}`),
|
|
733
|
+
input: u.input,
|
|
734
|
+
cacheRead: u.cacheRead,
|
|
735
|
+
cacheWrite5m: u.cacheWrite - u.cacheWrite1h,
|
|
736
|
+
cacheWrite1h: u.cacheWrite1h,
|
|
737
|
+
output: u.output
|
|
738
|
+
});
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* A reader for JSONL logs that only grow: walks `*.jsonl` under each path and parses only the
|
|
744
|
+
* bytes added since the last run. `lines` builds the line handler for one file.
|
|
745
|
+
* @param {(ctx: ReadContext, file: FileState, path: string) => (line: string) => void} lines
|
|
746
|
+
*/
|
|
747
|
+
const jsonlReader = (lines) => async (paths, ctx, provider) => {
|
|
748
|
+
const { state } = ctx;
|
|
749
|
+
for (const dir of paths) {
|
|
479
750
|
if (!existsSync(dir)) continue;
|
|
480
751
|
for await (const path of walk(dir)) {
|
|
481
|
-
if (seenPaths.has(path)) continue;
|
|
482
|
-
seenPaths.add(path);
|
|
752
|
+
if (ctx.seenPaths.has(path)) continue;
|
|
753
|
+
ctx.seenPaths.add(path);
|
|
483
754
|
let st;
|
|
484
755
|
try {
|
|
485
756
|
st = await stat(path);
|
|
@@ -487,44 +758,131 @@ async function scan(state, resolvePrice, cutoffMs) {
|
|
|
487
758
|
continue;
|
|
488
759
|
}
|
|
489
760
|
// Untouched for longer than the window: nothing in it can count.
|
|
490
|
-
if (st.mtimeMs < cutoffMs) {
|
|
761
|
+
if (st.mtimeMs < ctx.cutoffMs) {
|
|
491
762
|
delete state.files[path];
|
|
492
763
|
continue;
|
|
493
764
|
}
|
|
494
|
-
const prev =
|
|
765
|
+
const prev = state.rescan?.includes(provider) ? undefined : state.files[path];
|
|
495
766
|
if (prev && prev.size === st.size && prev.mtimeMs === st.mtimeMs) continue;
|
|
496
767
|
// File shrank (rewritten/truncated): start over. Dedupe keys stop double counting.
|
|
497
768
|
/** @type {FileState} */
|
|
498
769
|
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
770
|
const start = fs.offset;
|
|
510
771
|
try {
|
|
511
|
-
fs.offset = await readLinesFrom(path, start,
|
|
772
|
+
fs.offset = await readLinesFrom(path, start, lines(ctx, fs, path));
|
|
512
773
|
} catch (err) {
|
|
513
774
|
log(`skipping unreadable file: ${err.message}`);
|
|
514
775
|
continue;
|
|
515
776
|
}
|
|
516
|
-
parsedBytes += fs.offset - start;
|
|
517
|
-
filesRead++;
|
|
777
|
+
ctx.parsedBytes += fs.offset - start;
|
|
778
|
+
ctx.filesRead++;
|
|
518
779
|
fs.size = st.size;
|
|
519
780
|
fs.mtimeMs = st.mtimeMs;
|
|
520
781
|
state.files[path] = fs;
|
|
521
782
|
}
|
|
522
783
|
}
|
|
784
|
+
};
|
|
785
|
+
|
|
786
|
+
/** @type {Promise<any> | undefined} */
|
|
787
|
+
let sqlite;
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* Opens a SQLite file read-only, or returns null when this runtime has no `node:sqlite` (Node
|
|
791
|
+
* 22.13+, or 22.5+ with --experimental-sqlite). Imported on first use, never at the top level,
|
|
792
|
+
* so the other sources still run on Node 20; the warning is logged once per run.
|
|
793
|
+
*/
|
|
794
|
+
async function openSqlite(path) {
|
|
795
|
+
sqlite ??= import('node:sqlite').catch(() => {
|
|
796
|
+
log('warning: this runtime has no node:sqlite (Node 22.13 or newer); skipping SQLite sources');
|
|
797
|
+
return null;
|
|
798
|
+
});
|
|
799
|
+
const mod = await sqlite;
|
|
800
|
+
return mod && new mod.DatabaseSync(path, { readOnly: true });
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
const fromEnv = (name, ...rest) => (process.env[name] ? [join(process.env[name], ...rest)] : []);
|
|
804
|
+
|
|
805
|
+
/**
|
|
806
|
+
* @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
|
|
807
|
+
* @typedef {{
|
|
808
|
+
* paths: string[],
|
|
809
|
+
* envPaths: () => string[],
|
|
810
|
+
* read: (paths: string[], ctx: ReadContext, provider: string) => Promise<void>,
|
|
811
|
+
* priceKeys: (model: string) => string[]
|
|
812
|
+
* }} Source
|
|
813
|
+
*/
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* Every agent the collector reads, keyed by the provider id its rows carry. Each id must also be
|
|
817
|
+
* in PROVIDERS in src/schema.ts, or the server rejects the snapshot.
|
|
818
|
+
*
|
|
819
|
+
* - `paths`: where its data lives by default.
|
|
820
|
+
* - `envPaths`: where env-var overrides point. Called after the env file is loaded.
|
|
821
|
+
* - `read`: adds the usage under the paths it is given with addRecord. scan calls it with
|
|
822
|
+
* `paths`, and once every source has read those, with `envPaths`, so a file two sources reach
|
|
823
|
+
* goes to the one it is a default of. `jsonlReader` reads append-only JSONL by byte offset.
|
|
824
|
+
* Any other reader (a SQLite file through openSqlite, a JSON file rewritten in place) reads its
|
|
825
|
+
* data whole on every run and skips what it counted before through `state.seen`, keyed with a
|
|
826
|
+
* provider prefix and valued with the record's timestamp so pruneState can drop it.
|
|
827
|
+
* - `priceKeys`: the LiteLLM keys to try for a model, in order.
|
|
828
|
+
*
|
|
829
|
+
* @type {Record<string, Source>}
|
|
830
|
+
*/
|
|
831
|
+
const SOURCES = {
|
|
832
|
+
claude: {
|
|
833
|
+
paths: [join(HOME, '.claude', 'projects'), join(HOME, '.config', 'claude', 'projects')],
|
|
834
|
+
envPaths: () => fromEnv('CLAUDE_CONFIG_DIR', 'projects'),
|
|
835
|
+
read: jsonlReader((ctx) => claudeLineHandler(ctx.state, ctx.resolvePrice, ctx.cutoffMs)),
|
|
836
|
+
priceKeys: litellmKeys('anthropic')
|
|
837
|
+
},
|
|
838
|
+
codex: {
|
|
839
|
+
paths: [join(HOME, '.codex', 'sessions')],
|
|
840
|
+
envPaths: () => fromEnv('CODEX_HOME', 'sessions'),
|
|
841
|
+
read: jsonlReader((ctx, file, path) =>
|
|
842
|
+
codexLineHandler(
|
|
843
|
+
ctx.state,
|
|
844
|
+
file,
|
|
845
|
+
ctx.resolvePrice,
|
|
846
|
+
ctx.cutoffMs,
|
|
847
|
+
path.match(/([0-9a-f-]{36})\.jsonl$/)?.[1] ?? path
|
|
848
|
+
)
|
|
849
|
+
),
|
|
850
|
+
priceKeys: litellmKeys('openai')
|
|
851
|
+
},
|
|
852
|
+
pi: {
|
|
853
|
+
paths: [join(HOME, '.pi', 'agent', 'sessions')],
|
|
854
|
+
envPaths: piEnvPaths,
|
|
855
|
+
read: jsonlReader((ctx, file, path) =>
|
|
856
|
+
piLineHandler(ctx.state, file, path, ctx.resolvePrice, ctx.cutoffMs)
|
|
857
|
+
),
|
|
858
|
+
// pi logs each backend's own model id. OpenRouter's carry a vendor and dotted versions
|
|
859
|
+
// (`anthropic/claude-sonnet-4.5`) that LiteLLM may only know as `claude-sonnet-4-5`.
|
|
860
|
+
priceKeys: (model) => {
|
|
861
|
+
const bare = model.replace(/^[^/]+\//, '');
|
|
862
|
+
return [
|
|
863
|
+
...new Set(
|
|
864
|
+
[model, bare, bare.replace(/(\d)\.(\d)/g, '$1-$2')].flatMap((m) =>
|
|
865
|
+
PI_PRICE_PREFIXES.flatMap((p) => litellmKeys(p)(m))
|
|
866
|
+
)
|
|
867
|
+
)
|
|
868
|
+
];
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
async function scan(state, resolvePrice, cutoffMs) {
|
|
874
|
+
/** @type {ReadContext} */
|
|
875
|
+
const ctx = { state, resolvePrice, cutoffMs, seenPaths: new Set(), filesRead: 0, parsedBytes: 0 };
|
|
876
|
+
const sources = Object.entries(SOURCES);
|
|
877
|
+
for (const [provider, source] of sources) await source.read(source.paths, ctx, provider);
|
|
878
|
+
for (const [provider, source] of sources) await source.read(source.envPaths(), ctx, provider);
|
|
523
879
|
for (const path of Object.keys(state.files)) {
|
|
524
|
-
if (!seenPaths.has(path)) delete state.files[path];
|
|
880
|
+
if (!ctx.seenPaths.has(path)) delete state.files[path];
|
|
525
881
|
}
|
|
526
|
-
delete state.
|
|
527
|
-
log(
|
|
882
|
+
delete state.rescan;
|
|
883
|
+
log(
|
|
884
|
+
`read ${ctx.filesRead} changed file(s), ${(ctx.parsedBytes / 1e6).toFixed(1)} MB of new log data`
|
|
885
|
+
);
|
|
528
886
|
}
|
|
529
887
|
|
|
530
888
|
// ---------------------------------------------------------------------------
|
|
@@ -532,18 +890,28 @@ async function scan(state, resolvePrice, cutoffMs) {
|
|
|
532
890
|
|
|
533
891
|
const round = (n, d = 6) => Math.round(n * 10 ** d) / 10 ** d;
|
|
534
892
|
|
|
535
|
-
|
|
893
|
+
/**
|
|
894
|
+
* @param {Record<string, Bucket>} buckets
|
|
895
|
+
* @param {(b: Bucket, provider: string, model: string, tier: number) => Cost} costFor
|
|
896
|
+
* @param {{ deviceId: string, pricingSource: string, providers: string[], nowMs: number, coverageStartMs: number, limits?: Record<string, Limit> }} meta
|
|
897
|
+
* `providers` names the session counts the snapshot carries.
|
|
898
|
+
*/
|
|
899
|
+
function buildSnapshot(
|
|
900
|
+
buckets,
|
|
901
|
+
costFor,
|
|
902
|
+
{ deviceId, pricingSource, providers, nowMs, coverageStartMs, limits: windows = {} }
|
|
903
|
+
) {
|
|
536
904
|
const hourlyCutoff = Math.floor((nowMs - HOURLY_DAYS * DAY_MS) / DAY_MS) * DAY_MS;
|
|
537
905
|
/** @type {Map<string, any>} */
|
|
538
906
|
const rows = new Map();
|
|
539
|
-
for (const [key, b] of Object.entries(
|
|
907
|
+
for (const [key, b] of Object.entries(buckets)) {
|
|
540
908
|
const [hourStr, provider, model, tierStr] = key.split('|');
|
|
541
909
|
const hourMs = Number(hourStr);
|
|
542
910
|
if (hourMs < coverageStartMs) continue;
|
|
543
911
|
const daily = hourMs < hourlyCutoff;
|
|
544
912
|
const start = daily ? Math.floor(hourMs / DAY_MS) * DAY_MS : hourMs;
|
|
545
913
|
const rowKey = `${start}|${daily ? 'd' : 'h'}|${provider}|${model}`;
|
|
546
|
-
const c =
|
|
914
|
+
const c = costFor(b, provider, model, Number(tierStr));
|
|
547
915
|
let row = rows.get(rowKey);
|
|
548
916
|
if (!row) {
|
|
549
917
|
row = {
|
|
@@ -604,20 +972,17 @@ function buildSnapshot(state, resolvePrice, pricing, nowMs, coverageStartMs) {
|
|
|
604
972
|
const all = new Set();
|
|
605
973
|
for (const [name, span] of Object.entries(ranges)) {
|
|
606
974
|
const from = currentHour + HOUR_MS - span;
|
|
607
|
-
const sets =
|
|
608
|
-
for (const [key, b] of Object.entries(
|
|
975
|
+
const sets = Object.fromEntries(providers.map((p) => [p, new Set()]));
|
|
976
|
+
for (const [key, b] of Object.entries(buckets)) {
|
|
609
977
|
const [hourStr, provider] = key.split('|');
|
|
610
978
|
const h = Number(hourStr);
|
|
611
979
|
if (h < from || h < coverageStartMs) continue;
|
|
612
980
|
for (const s of b.sessions) sets[provider]?.add(s);
|
|
613
981
|
}
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
codex: sets.codex.size,
|
|
617
|
-
all: sets.claude.size + sets.codex.size
|
|
618
|
-
};
|
|
982
|
+
const counts = Object.fromEntries(providers.map((p) => [p, sets[p].size]));
|
|
983
|
+
sessionCounts[name] = { ...counts, all: Object.values(counts).reduce((a, n) => a + n, 0) };
|
|
619
984
|
}
|
|
620
|
-
for (const [key, b] of Object.entries(
|
|
985
|
+
for (const [key, b] of Object.entries(buckets)) {
|
|
621
986
|
if (Number(key.split('|')[0]) >= coverageStartMs) for (const s of b.sessions) all.add(s);
|
|
622
987
|
}
|
|
623
988
|
|
|
@@ -625,17 +990,42 @@ function buildSnapshot(state, resolvePrice, pricing, nowMs, coverageStartMs) {
|
|
|
625
990
|
const { '24h': sessions24h, ...publicCounts } = sessionCounts;
|
|
626
991
|
const snapshot = {
|
|
627
992
|
schemaVersion: SCHEMA_VERSION,
|
|
628
|
-
deviceId
|
|
993
|
+
deviceId,
|
|
629
994
|
generatedAt: new Date(nowMs).toISOString(),
|
|
630
995
|
coverageStart: new Date(coverageStartMs).toISOString(),
|
|
631
|
-
pricingSource
|
|
996
|
+
pricingSource,
|
|
632
997
|
hourly,
|
|
633
998
|
sessionsTotal: all.size,
|
|
634
999
|
sessionCounts: publicCounts
|
|
635
1000
|
};
|
|
1001
|
+
const limits = Object.values(windows)
|
|
1002
|
+
.filter((w) => Date.parse(w.resetsAt) >= coverageStartMs)
|
|
1003
|
+
.sort(
|
|
1004
|
+
(a, b) =>
|
|
1005
|
+
a.resetsAt.localeCompare(b.resetsAt) ||
|
|
1006
|
+
a.provider.localeCompare(b.provider) ||
|
|
1007
|
+
a.window.localeCompare(b.window)
|
|
1008
|
+
);
|
|
1009
|
+
if (limits.length) snapshot.limits = limits;
|
|
636
1010
|
return { snapshot, sessions24h };
|
|
637
1011
|
}
|
|
638
1012
|
|
|
1013
|
+
// Local only (never posted), so hit times may be shown to the minute.
|
|
1014
|
+
function limitLines(snapshot, nowMs) {
|
|
1015
|
+
const from = nowMs - 7 * DAY_MS;
|
|
1016
|
+
const hits = new Map();
|
|
1017
|
+
for (const w of snapshot.limits ?? []) {
|
|
1018
|
+
if (!w.hitAt || Date.parse(w.hitAt) < from) continue;
|
|
1019
|
+
const key = `${w.provider} ${w.window}`;
|
|
1020
|
+
hits.set(key, [...(hits.get(key) ?? []), w.hitAt.slice(0, 16).replace('T', ' ')]);
|
|
1021
|
+
}
|
|
1022
|
+
if (!hits.size) return [];
|
|
1023
|
+
return [
|
|
1024
|
+
'Limits hit, last 7 days (UTC)',
|
|
1025
|
+
...[...hits].map(([key, times]) => ` ${key.padEnd(24)} ${times.length}x last ${times.at(-1)}`)
|
|
1026
|
+
];
|
|
1027
|
+
}
|
|
1028
|
+
|
|
639
1029
|
function printSummary(snapshot, sessions24h, nowMs) {
|
|
640
1030
|
const from = Math.floor(nowMs / HOUR_MS) * HOUR_MS + HOUR_MS - DAY_MS;
|
|
641
1031
|
const byModel = new Map();
|
|
@@ -675,26 +1065,231 @@ function printSummary(snapshot, sessions24h, nowMs) {
|
|
|
675
1065
|
([m, v]) =>
|
|
676
1066
|
` ${m.padEnd(28)} ${usd(v.cost).padStart(10)} ${(v.tokens / 1e6).toFixed(1)}M tok`
|
|
677
1067
|
),
|
|
678
|
-
|
|
1068
|
+
...limitLines(snapshot, nowMs),
|
|
1069
|
+
...(snapshot.pricingSource === 'cursor'
|
|
1070
|
+
? []
|
|
1071
|
+
: [`Compare with \`bunx ccusage claude daily\` (Claude Code only) for this device.`])
|
|
679
1072
|
];
|
|
680
1073
|
console.error(lines.join('\n'));
|
|
681
1074
|
}
|
|
682
1075
|
|
|
1076
|
+
// ---------------------------------------------------------------------------
|
|
1077
|
+
// Cursor
|
|
1078
|
+
//
|
|
1079
|
+
// Cursor keeps usage on its servers, per account, so it is read from Cursor's API instead of
|
|
1080
|
+
// local logs and sent under its own device id: the same account on two machines is one history.
|
|
1081
|
+
|
|
1082
|
+
async function cursorRequest(path, bearer, body, headers = {}) {
|
|
1083
|
+
const res = await fetch(`${cursorApiUrl(process.env.BIG_SPENDER_CURSOR_API_URL)}${path}`, {
|
|
1084
|
+
method: 'POST',
|
|
1085
|
+
headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json', ...headers },
|
|
1086
|
+
body: JSON.stringify(body),
|
|
1087
|
+
// Never forward the key or token to another host.
|
|
1088
|
+
redirect: 'error',
|
|
1089
|
+
signal: AbortSignal.timeout(30_000)
|
|
1090
|
+
});
|
|
1091
|
+
if (!res.ok) {
|
|
1092
|
+
const hint =
|
|
1093
|
+
res.status === 401 || res.status === 403 ? '; check BIG_SPENDER_CURSOR_API_KEY' : '';
|
|
1094
|
+
throw new Error(`Cursor ${path} answered HTTP ${res.status}${hint}`);
|
|
1095
|
+
}
|
|
1096
|
+
const json = await res.json().catch(() => null);
|
|
1097
|
+
if (!json || typeof json !== 'object' || Array.isArray(json)) {
|
|
1098
|
+
throw new Error(`Cursor ${path} answered with something other than a JSON object`);
|
|
1099
|
+
}
|
|
1100
|
+
return json;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/** Trades a Cursor user API key for the short-lived access token its dashboard RPCs accept. */
|
|
1104
|
+
async function cursorAccessToken(apiKey) {
|
|
1105
|
+
const { accessToken } = await cursorRequest('/auth/exchange_user_api_key', apiKey, {});
|
|
1106
|
+
if (typeof accessToken !== 'string' || !accessToken) {
|
|
1107
|
+
throw new Error('Cursor did not return an access token for BIG_SPENDER_CURSOR_API_KEY');
|
|
1108
|
+
}
|
|
1109
|
+
assertHeaderSafe(accessToken, "Cursor's access token");
|
|
1110
|
+
return accessToken;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* Raw usage events with fromMs <= timestamp < toMs. Cursor gives events no unique id and its pages
|
|
1115
|
+
* can overlap, so instead of paging, a window holding more than one page is split in two.
|
|
1116
|
+
*/
|
|
1117
|
+
async function cursorEvents(token, fromMs, toMs) {
|
|
1118
|
+
const body = await cursorRequest(
|
|
1119
|
+
'/aiserver.v1.DashboardService/GetFilteredUsageEvents',
|
|
1120
|
+
token,
|
|
1121
|
+
{
|
|
1122
|
+
page: 1,
|
|
1123
|
+
pageSize: CURSOR_PAGE_SIZE,
|
|
1124
|
+
startDate: String(fromMs),
|
|
1125
|
+
endDate: String(toMs - 1)
|
|
1126
|
+
},
|
|
1127
|
+
{ 'connect-protocol-version': '1' }
|
|
1128
|
+
);
|
|
1129
|
+
// A failed call can still answer 200, with an error body that would read as an empty window.
|
|
1130
|
+
if ('error' in body || 'code' in body || 'message' in body) {
|
|
1131
|
+
throw new Error('Cursor answered with an error instead of usage events');
|
|
1132
|
+
}
|
|
1133
|
+
// Connect leaves out empty fields, so a window without events answers {}.
|
|
1134
|
+
const total = Number(body.totalUsageEventsCount ?? 0);
|
|
1135
|
+
const events = body.usageEventsDisplay ?? [];
|
|
1136
|
+
if (!Number.isSafeInteger(total) || total < 0 || !Array.isArray(events)) {
|
|
1137
|
+
throw new Error('Cursor answered with a usage page in an unexpected shape');
|
|
1138
|
+
}
|
|
1139
|
+
let inside;
|
|
1140
|
+
if (total > CURSOR_PAGE_SIZE) {
|
|
1141
|
+
if (toMs - fromMs < 2)
|
|
1142
|
+
throw new Error(`Cursor listed ${total} usage events in one millisecond`);
|
|
1143
|
+
const mid = fromMs + Math.floor((toMs - fromMs) / 2);
|
|
1144
|
+
inside = [
|
|
1145
|
+
...(await cursorEvents(token, fromMs, mid)),
|
|
1146
|
+
...(await cursorEvents(token, mid, toMs))
|
|
1147
|
+
];
|
|
1148
|
+
} else {
|
|
1149
|
+
inside = events.filter((e) => {
|
|
1150
|
+
const ts = Number(e?.timestamp);
|
|
1151
|
+
return ts >= fromMs && ts < toMs;
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
// Posting a short window would replace complete days on the server with partial ones. Events
|
|
1155
|
+
// that arrive while the halves are read can make a split window longer, never shorter.
|
|
1156
|
+
if (inside.length < total || (total <= CURSOR_PAGE_SIZE && inside.length !== total)) {
|
|
1157
|
+
throw new Error(
|
|
1158
|
+
`Cursor counted ${total} usage events in a window but returned ${inside.length} inside it`
|
|
1159
|
+
);
|
|
1160
|
+
}
|
|
1161
|
+
return inside;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
const cursorCount = (v) => num(typeof v === 'string' ? Number(v) : v);
|
|
1165
|
+
|
|
1166
|
+
/** Cursor model names are free text ("Premium (Codex 5.3)"); the server accepts only slugs. */
|
|
1167
|
+
const cursorModel = (name) =>
|
|
1168
|
+
String(name ?? '')
|
|
1169
|
+
.toLowerCase()
|
|
1170
|
+
.replace(/[^a-z0-9._:@-]+/g, '-')
|
|
1171
|
+
.replace(/^-+|-+$/g, '')
|
|
1172
|
+
.slice(0, 100) || 'unknown';
|
|
1173
|
+
|
|
1174
|
+
/**
|
|
1175
|
+
* One usage event as tokens and Cursor's own price, or null for events without token counts:
|
|
1176
|
+
* Cursor billed per request before mid-2025, and some free-credit events report no tokens.
|
|
1177
|
+
*/
|
|
1178
|
+
function parseCursorEvent(raw) {
|
|
1179
|
+
const u = raw?.tokenUsage;
|
|
1180
|
+
if (!u || typeof u !== 'object') return null;
|
|
1181
|
+
const ts = Number(raw.timestamp);
|
|
1182
|
+
const t = {
|
|
1183
|
+
input: cursorCount(u.inputTokens),
|
|
1184
|
+
cacheRead: cursorCount(u.cacheReadTokens),
|
|
1185
|
+
cacheWrite: cursorCount(u.cacheWriteTokens),
|
|
1186
|
+
output: cursorCount(u.outputTokens)
|
|
1187
|
+
};
|
|
1188
|
+
if (!Number.isFinite(ts) || t.input + t.cacheRead + t.cacheWrite + t.output === 0) return null;
|
|
1189
|
+
const conversation = typeof raw.conversationId === 'string' ? raw.conversationId : '';
|
|
1190
|
+
return {
|
|
1191
|
+
ts,
|
|
1192
|
+
model: cursorModel(raw.model),
|
|
1193
|
+
session: conversation && conversation !== 'null' ? shortHash(`cursor:${conversation}`) : null,
|
|
1194
|
+
...t,
|
|
1195
|
+
usd: cursorCount(u.totalCents) / 100
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
// Cursor reports one price per event. It is split over the token types in these proportions
|
|
1200
|
+
// (typical API price ratios) so the cost-by-type breakdown has something to show; the total is
|
|
1201
|
+
// always Cursor's.
|
|
1202
|
+
const CURSOR_PRICE_RATIO = { input: 1, cacheRead: 0.1, cacheWrite: 1.25, output: 5 };
|
|
1203
|
+
|
|
1204
|
+
/** @returns {Record<string, Bucket>} */
|
|
1205
|
+
function cursorBuckets(events) {
|
|
1206
|
+
/** @type {Record<string, Bucket>} */
|
|
1207
|
+
const buckets = {};
|
|
1208
|
+
const w = CURSOR_PRICE_RATIO;
|
|
1209
|
+
for (const e of events) {
|
|
1210
|
+
const key = bucketKey(Math.floor(e.ts / HOUR_MS) * HOUR_MS, 'cursor', e.model, 0);
|
|
1211
|
+
const b = (buckets[key] ??= {
|
|
1212
|
+
input: 0,
|
|
1213
|
+
cacheRead: 0,
|
|
1214
|
+
cacheWrite5m: 0,
|
|
1215
|
+
cacheWrite1h: 0,
|
|
1216
|
+
output: 0,
|
|
1217
|
+
sessions: [],
|
|
1218
|
+
cost: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, savings: 0 }
|
|
1219
|
+
});
|
|
1220
|
+
b.input += e.input;
|
|
1221
|
+
b.cacheRead += e.cacheRead;
|
|
1222
|
+
b.cacheWrite5m += e.cacheWrite;
|
|
1223
|
+
b.output += e.output;
|
|
1224
|
+
if (e.session && !b.sessions.includes(e.session)) b.sessions.push(e.session);
|
|
1225
|
+
const unit =
|
|
1226
|
+
e.usd /
|
|
1227
|
+
(e.input * w.input +
|
|
1228
|
+
e.cacheRead * w.cacheRead +
|
|
1229
|
+
e.cacheWrite * w.cacheWrite +
|
|
1230
|
+
e.output * w.output);
|
|
1231
|
+
b.cost.input += e.input * w.input * unit;
|
|
1232
|
+
b.cost.cacheRead += e.cacheRead * w.cacheRead * unit;
|
|
1233
|
+
b.cost.cacheWrite += e.cacheWrite * w.cacheWrite * unit;
|
|
1234
|
+
b.cost.output += e.output * w.output * unit;
|
|
1235
|
+
b.cost.savings += e.cacheRead * (w.input - w.cacheRead) * unit;
|
|
1236
|
+
}
|
|
1237
|
+
return buckets;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
/**
|
|
1241
|
+
* The Cursor account's snapshot. Until a backfill has been posted it covers all history;
|
|
1242
|
+
* after that the same 90 days as the device snapshot, since the server keeps older days.
|
|
1243
|
+
*/
|
|
1244
|
+
async function cursorSnapshot(apiKey, backfill, nowMs, coverageStartMs) {
|
|
1245
|
+
const token = await cursorAccessToken(apiKey);
|
|
1246
|
+
const raw = await cursorEvents(token, backfill ? CURSOR_EARLIEST_MS : coverageStartMs, nowMs + 1);
|
|
1247
|
+
const events = raw.map(parseCursorEvent).filter((e) => e !== null);
|
|
1248
|
+
let firstMs = coverageStartMs;
|
|
1249
|
+
for (const e of events) firstMs = Math.min(firstMs, Math.floor(e.ts / DAY_MS) * DAY_MS);
|
|
1250
|
+
return buildSnapshot(cursorBuckets(events), (b) => b.cost, {
|
|
1251
|
+
deviceId: CURSOR_DEVICE_ID,
|
|
1252
|
+
pricingSource: 'cursor',
|
|
1253
|
+
providers: ['claude', 'codex', 'cursor'],
|
|
1254
|
+
nowMs,
|
|
1255
|
+
coverageStartMs: firstMs
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
|
|
683
1259
|
// ---------------------------------------------------------------------------
|
|
684
1260
|
// Upload
|
|
685
1261
|
|
|
1262
|
+
// fetch quotes the whole header in its error for some of these, which would print the secret.
|
|
1263
|
+
function assertHeaderSafe(secret, name) {
|
|
1264
|
+
if (!/^[\x21-\x7e]+$/.test(secret)) {
|
|
1265
|
+
throw new Error(
|
|
1266
|
+
`${name} contains characters that are not allowed in an HTTP header; check it for spaces or a stray newline`
|
|
1267
|
+
);
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// The 422 a server without limit support sends: its strict schema names the key it doesn't know.
|
|
1272
|
+
// Any other limits error is a real bug and must not silently drop the windows.
|
|
1273
|
+
const OLD_SERVER_422 = /Unrecognized key.{0,20}limits/;
|
|
1274
|
+
|
|
686
1275
|
async function post(snapshot) {
|
|
1276
|
+
try {
|
|
1277
|
+
return await postOnce(snapshot);
|
|
1278
|
+
} catch (err) {
|
|
1279
|
+
if (err.status !== 422 || !snapshot.limits || !OLD_SERVER_422.test(err.message)) throw err;
|
|
1280
|
+
log('warning: the server is too old to store limit data; sending usage without it');
|
|
1281
|
+
const { limits, ...usageOnly } = snapshot;
|
|
1282
|
+
return await postOnce(usageOnly);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
async function postOnce(snapshot) {
|
|
687
1287
|
const url = setting('INGEST_URL');
|
|
688
1288
|
const token = setting('INGEST_TOKEN').trim();
|
|
689
1289
|
if (!url || !token) {
|
|
690
1290
|
throw new Error('BIG_SPENDER_INGEST_URL and BIG_SPENDER_INGEST_TOKEN must be set');
|
|
691
1291
|
}
|
|
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
|
-
}
|
|
1292
|
+
assertHeaderSafe(token, 'the ingest token');
|
|
698
1293
|
const body = gzipSync(JSON.stringify(snapshot));
|
|
699
1294
|
let lastErr;
|
|
700
1295
|
for (let attempt = 1; attempt <= POST_ATTEMPTS; attempt++) {
|
|
@@ -709,12 +1304,15 @@ async function post(snapshot) {
|
|
|
709
1304
|
body,
|
|
710
1305
|
signal: AbortSignal.timeout(30_000)
|
|
711
1306
|
});
|
|
712
|
-
const
|
|
1307
|
+
const reply = await res.text();
|
|
1308
|
+
const text = reply.slice(0, 300);
|
|
713
1309
|
if (res.ok) {
|
|
714
|
-
log(
|
|
715
|
-
|
|
1310
|
+
log(
|
|
1311
|
+
`posted ${snapshot.hourly.length} rows for "${snapshot.deviceId}" (${body.length} bytes gzipped): ${text}`
|
|
1312
|
+
);
|
|
1313
|
+
return parseJson(reply)?.result;
|
|
716
1314
|
}
|
|
717
|
-
lastErr = new Error(`HTTP ${res.status}: ${text}`);
|
|
1315
|
+
lastErr = Object.assign(new Error(`HTTP ${res.status}: ${text}`), { status: res.status });
|
|
718
1316
|
// Client errors other than rate limiting won't fix themselves.
|
|
719
1317
|
if (res.status >= 400 && res.status < 500 && res.status !== 429) break;
|
|
720
1318
|
} catch (err) {
|
|
@@ -739,6 +1337,11 @@ async function main() {
|
|
|
739
1337
|
throw new Error('BIG_SPENDER_DEVICE_ID must be a lowercase slug like "laptop" or "desktop"');
|
|
740
1338
|
}
|
|
741
1339
|
}
|
|
1340
|
+
if (deviceId === CURSOR_DEVICE_ID) {
|
|
1341
|
+
throw new Error(
|
|
1342
|
+
`the device id "${CURSOR_DEVICE_ID}" is reserved for Cursor usage; rename this machine with big-spender install --device <id> --rename`
|
|
1343
|
+
);
|
|
1344
|
+
}
|
|
742
1345
|
const release = await acquireLock();
|
|
743
1346
|
if (!release) {
|
|
744
1347
|
log('another run is in progress; skipping');
|
|
@@ -755,19 +1358,65 @@ async function main() {
|
|
|
755
1358
|
await scan(state, resolvePrice, coverageStartMs);
|
|
756
1359
|
await saveState(state);
|
|
757
1360
|
|
|
758
|
-
const
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
1361
|
+
const used = new Set(Object.keys(state.buckets).map((k) => k.split('|')[1]));
|
|
1362
|
+
const device = buildSnapshot(
|
|
1363
|
+
state.buckets,
|
|
1364
|
+
(b, provider, model, tier) => costOf(resolvePrice(provider, model), tier, b),
|
|
1365
|
+
{
|
|
1366
|
+
deviceId: setting('DEVICE_ID'),
|
|
1367
|
+
pricingSource: `litellm@${new Date(pricing.fetchedAt).toISOString().slice(0, 10)}`,
|
|
1368
|
+
// Older servers require the claude and codex counts and reject any other key, so another
|
|
1369
|
+
// provider's count is sent only once this device has used it.
|
|
1370
|
+
providers: Object.keys(SOURCES).filter(
|
|
1371
|
+
(p) => p === 'claude' || p === 'codex' || used.has(p)
|
|
1372
|
+
),
|
|
1373
|
+
nowMs,
|
|
1374
|
+
coverageStartMs,
|
|
1375
|
+
limits: state.limits
|
|
1376
|
+
}
|
|
764
1377
|
);
|
|
765
|
-
if (
|
|
766
|
-
|
|
767
|
-
printSummary(snapshot, sessions24h, nowMs);
|
|
1378
|
+
if (SUMMARY_ONLY) {
|
|
1379
|
+
printSummary(device.snapshot, device.sessions24h, nowMs);
|
|
768
1380
|
return;
|
|
769
1381
|
}
|
|
770
|
-
|
|
1382
|
+
|
|
1383
|
+
// A Cursor failure is held until this device's snapshot is posted, so it never blocks it.
|
|
1384
|
+
const cursorKey = (process.env.BIG_SPENDER_CURSOR_API_KEY ?? '').trim();
|
|
1385
|
+
const backfillId = shortHash(`${setting('INGEST_URL')}\n${cursorKey}`);
|
|
1386
|
+
const backfill = !(state.cursorBackfills ?? []).includes(backfillId);
|
|
1387
|
+
let cursor = null;
|
|
1388
|
+
let cursorError = null;
|
|
1389
|
+
if (cursorKey) {
|
|
1390
|
+
try {
|
|
1391
|
+
assertHeaderSafe(cursorKey, 'BIG_SPENDER_CURSOR_API_KEY');
|
|
1392
|
+
cursor = await cursorSnapshot(cursorKey, backfill, nowMs, coverageStartMs);
|
|
1393
|
+
} catch (err) {
|
|
1394
|
+
cursorError = new Error(`Cursor: ${err?.message ?? err}`);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
if (DRY_RUN) {
|
|
1399
|
+
for (const built of [device, cursor]) {
|
|
1400
|
+
if (!built) continue;
|
|
1401
|
+
console.log(JSON.stringify(built.snapshot, null, 2));
|
|
1402
|
+
printSummary(built.snapshot, built.sessions24h, nowMs);
|
|
1403
|
+
}
|
|
1404
|
+
if (cursorError) throw cursorError;
|
|
1405
|
+
return;
|
|
1406
|
+
}
|
|
1407
|
+
await post(device.snapshot);
|
|
1408
|
+
if (cursorError) throw cursorError;
|
|
1409
|
+
if (cursor) {
|
|
1410
|
+
const result = await post(cursor.snapshot);
|
|
1411
|
+
if (backfill && result === 'stored') {
|
|
1412
|
+
(state.cursorBackfills ??= []).push(backfillId);
|
|
1413
|
+
await saveState(state);
|
|
1414
|
+
} else if (result !== 'stored') {
|
|
1415
|
+
log(
|
|
1416
|
+
`warning: the server kept a newer "${CURSOR_DEVICE_ID}" snapshot (${result}); is Cursor set up on two machines?`
|
|
1417
|
+
);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
771
1420
|
} finally {
|
|
772
1421
|
await release();
|
|
773
1422
|
}
|