big-spender 0.2.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 +93 -13
- package/dist/collector.mjs +589 -88
- package/dist/install.d.ts +1 -1
- package/dist/install.js +23 -5
- package/dist/page.js +9 -4
- package/dist/push.d.ts +1 -1
- package/dist/push.js +7 -3
- package/dist/schema.d.ts +16 -2
- package/dist/schema.js +17 -7
- package/dist/server/index.d.ts +1 -1
- package/dist/server/ingest.js +9 -2
- package/dist/summary.d.ts +18 -6
- package/dist/summary.js +36 -16
- 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,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
|
}
|