big-spender 0.0.0-stage → 0.2.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.
@@ -0,0 +1,779 @@
1
+ #!/usr/bin/env node
2
+ // big-spender collector.
3
+ //
4
+ // Reads this machine's Claude Code and Codex session logs, works out hourly
5
+ // token and cost aggregates (LiteLLM API prices), and POSTs one full snapshot
6
+ // to your big-spender server's ingest endpoint. Only numbers, model names, timestamps and the
7
+ // device id leave the machine: no paths, prompts, session ids or branches.
8
+ //
9
+ // Zero dependencies, Node >= 20 (or Bun). `big-spender install` copies this single file to
10
+ // ~/.local/share/big-spender/collector.mjs and schedules it. See the package README.
11
+ //
12
+ // Usage:
13
+ // node collector.mjs # parse new log bytes, POST the snapshot
14
+ // node collector.mjs --dry-run # print the snapshot + a 24h summary, no POST
15
+ // node collector.mjs --summary # print only the 24h summary
16
+ // node collector.mjs --reset # forget local state and rescan everything
17
+ //
18
+ // Env: BIG_SPENDER_DEVICE_ID, BIG_SPENDER_INGEST_URL, BIG_SPENDER_INGEST_TOKEN (see templates/env.example).
19
+ // The older USAGE_* names are still read when the new one is unset.
20
+
21
+ import { createHash } from 'node:crypto';
22
+ import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
23
+ import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
24
+ import { homedir } from 'node:os';
25
+ import { join } from 'node:path';
26
+ import { gzipSync } from 'node:zlib';
27
+
28
+ const SCHEMA_VERSION = 1;
29
+ const STATE_VERSION = 1;
30
+ const HOUR_MS = 3_600_000;
31
+ const DAY_MS = 24 * HOUR_MS;
32
+ const RETENTION_DAYS = 90;
33
+ // Rows older than this are rolled up into daily rows to keep the payload small.
34
+ const HOURLY_DAYS = 7;
35
+ const PRICING_URL =
36
+ 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
37
+ const PRICING_TTL_MS = DAY_MS;
38
+ const POST_ATTEMPTS = 4;
39
+
40
+ const args = new Set(process.argv.slice(2));
41
+ const DRY_RUN = args.has('--dry-run');
42
+ const SUMMARY_ONLY = args.has('--summary');
43
+ const RESET = args.has('--reset');
44
+
45
+ const HOME = homedir();
46
+ const CACHE_DIR = join(process.env.XDG_CACHE_HOME || join(HOME, '.cache'), 'big-spender');
47
+ const STATE_PATH = join(CACHE_DIR, 'state.json');
48
+ const PRICING_PATH = join(CACHE_DIR, 'litellm-prices.json');
49
+ const LOCK_PATH = join(CACHE_DIR, 'run.lock');
50
+ const LOCK_STALE_MS = 30 * 60 * 1000;
51
+ const ENV_FILE =
52
+ process.env.BIG_SPENDER_ENV_FILE ||
53
+ process.env.USAGE_ENV_FILE ||
54
+ join(process.env.XDG_CONFIG_HOME || join(HOME, '.config'), 'big-spender', 'env');
55
+
56
+ const log = (...m) => console.error('[big-spender]', ...m);
57
+
58
+ // Collectors installed before the rename have USAGE_* in their env file and scheduler units.
59
+ const setting = (name) => process.env[`BIG_SPENDER_${name}`] || process.env[`USAGE_${name}`] || '';
60
+
61
+ // KEY=value lines (optionally quoted). Variables already set in the environment win.
62
+ function loadEnvFile() {
63
+ let text;
64
+ try {
65
+ const st = statSync(ENV_FILE);
66
+ if (process.platform !== 'win32' && st.mode & 0o077) {
67
+ log(`warning: ${ENV_FILE} is readable by other users; run: chmod 600 ${ENV_FILE}`);
68
+ }
69
+ text = readFileSync(ENV_FILE, 'utf8');
70
+ } catch {
71
+ return;
72
+ }
73
+ for (const raw of text.split('\n')) {
74
+ const m = /^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*?)\s*$/.exec(raw);
75
+ if (!m || process.env[m[1]] !== undefined) continue;
76
+ process.env[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2');
77
+ }
78
+ }
79
+
80
+ // Hourly timers and RunAtLoad can overlap; only one run may touch the state file.
81
+ async function acquireLock() {
82
+ await mkdir(CACHE_DIR, { recursive: true });
83
+ for (let attempt = 0; attempt < 2; attempt++) {
84
+ try {
85
+ const fh = await open(LOCK_PATH, 'wx');
86
+ await fh.writeFile(String(process.pid));
87
+ await fh.close();
88
+ return () => rm(LOCK_PATH, { force: true });
89
+ } catch (err) {
90
+ if (err.code !== 'EEXIST') throw err;
91
+ const st = await stat(LOCK_PATH).catch(() => null);
92
+ if (st && Date.now() - st.mtimeMs < LOCK_STALE_MS) return null;
93
+ await rm(LOCK_PATH, { force: true });
94
+ }
95
+ }
96
+ return null;
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // State
101
+
102
+ /**
103
+ * @typedef {{ input: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number, output: number, sessions: string[] }} Bucket
104
+ * @typedef {{ size: number, mtimeMs: number, offset: number, model?: string, sessionId?: string, lastTotal?: number }} FileState
105
+ * A seen entry is the first timestamp, or for Claude [first timestamp, output tokens counted].
106
+ * A bare number on a Claude key means the counted output is unknown (state from an older version).
107
+ * @typedef {number | [number, number]} Seen
108
+ * @typedef {{ version: number, files: Record<string, FileState>, seen: Record<string, Seen>, buckets: Record<string, Bucket>, fixes?: string[], rescanClaude?: boolean }} State
109
+ */
110
+
111
+ // One-time fixes to existing state. The state version stays the same so an older installed copy
112
+ // can still read the file instead of discarding it.
113
+ const FIX_CLAUDE_OUTPUT = 'claude-final-output';
114
+
115
+ /** @returns {Promise<State>} */
116
+ async function loadState() {
117
+ const empty = {
118
+ version: STATE_VERSION,
119
+ files: {},
120
+ seen: {},
121
+ buckets: {},
122
+ fixes: [FIX_CLAUDE_OUTPUT]
123
+ };
124
+ if (RESET) return empty;
125
+ try {
126
+ const s = JSON.parse(await readFile(STATE_PATH, 'utf8'));
127
+ if (s?.version !== STATE_VERSION) return empty;
128
+ s.fixes ??= [];
129
+ if (!s.fixes.includes(FIX_CLAUDE_OUTPUT)) {
130
+ // Older versions kept the first log line of a Claude message, whose output count can be
131
+ // partial. Re-read the Claude logs once so later lines add what was missed.
132
+ s.fixes.push(FIX_CLAUDE_OUTPUT);
133
+ s.rescanClaude = true;
134
+ }
135
+ return s;
136
+ } catch {
137
+ return empty;
138
+ }
139
+ }
140
+
141
+ /** @param {State} state */
142
+ async function saveState(state) {
143
+ await mkdir(CACHE_DIR, { recursive: true });
144
+ const tmp = `${STATE_PATH}.${process.pid}.tmp`;
145
+ await writeFile(tmp, JSON.stringify(state));
146
+ await rename(tmp, STATE_PATH);
147
+ }
148
+
149
+ const shortHash = (s) => createHash('sha256').update(s).digest('base64url').slice(0, 16);
150
+
151
+ // Bucket key: hour start (ms) | provider | model | pricing tier (prompt-size threshold, 0 = base).
152
+ const bucketKey = (hourMs, provider, model, tier) => `${hourMs}|${provider}|${model}|${tier}`;
153
+
154
+ /**
155
+ * @param {State} state
156
+ * @param {{ ts: number, provider: string, model: string, tier: number, session: string, input: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number, output: number }} r
157
+ */
158
+ function addRecord(state, r) {
159
+ const hourMs = Math.floor(r.ts / HOUR_MS) * HOUR_MS;
160
+ const key = bucketKey(hourMs, r.provider, r.model, r.tier);
161
+ const b = (state.buckets[key] ??= {
162
+ input: 0,
163
+ cacheRead: 0,
164
+ cacheWrite5m: 0,
165
+ cacheWrite1h: 0,
166
+ output: 0,
167
+ sessions: []
168
+ });
169
+ b.input += r.input;
170
+ b.cacheRead += r.cacheRead;
171
+ b.cacheWrite5m += r.cacheWrite5m;
172
+ b.cacheWrite1h += r.cacheWrite1h;
173
+ b.output += r.output;
174
+ if (!b.sessions.includes(r.session)) b.sessions.push(r.session);
175
+ }
176
+
177
+ /** @param {State} state @param {number} cutoffMs */
178
+ function pruneState(state, cutoffMs) {
179
+ for (const key of Object.keys(state.buckets)) {
180
+ if (Number(key.split('|')[0]) < cutoffMs) delete state.buckets[key];
181
+ }
182
+ for (const [key, v] of Object.entries(state.seen)) {
183
+ if ((Array.isArray(v) ? v[0] : v) < cutoffMs) delete state.seen[key];
184
+ }
185
+ }
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // Pricing
189
+
190
+ async function loadPricing() {
191
+ let cached = null;
192
+ try {
193
+ cached = JSON.parse(await readFile(PRICING_PATH, 'utf8'));
194
+ } catch {
195
+ /* no cache yet */
196
+ }
197
+ if (cached && Date.now() - cached.fetchedAt < PRICING_TTL_MS) return cached;
198
+ try {
199
+ const res = await fetch(PRICING_URL, { signal: AbortSignal.timeout(30_000) });
200
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
201
+ const models = await res.json();
202
+ const fresh = { fetchedAt: Date.now(), models };
203
+ await mkdir(CACHE_DIR, { recursive: true });
204
+ await writeFile(PRICING_PATH, JSON.stringify(fresh));
205
+ return fresh;
206
+ } catch (err) {
207
+ if (cached) {
208
+ log(`pricing fetch failed (${err.message}); using cached copy`);
209
+ return cached;
210
+ }
211
+ throw new Error(`could not load LiteLLM pricing: ${err.message}`, { cause: err });
212
+ }
213
+ }
214
+
215
+ /** Builds a model -> price entry resolver over the LiteLLM document. */
216
+ function makePriceResolver(models) {
217
+ const memo = new Map();
218
+ const warned = new Set();
219
+ const usable = (e) => e && typeof e.input_cost_per_token === 'number';
220
+ return (provider, model) => {
221
+ const memoKey = `${provider}|${model}`;
222
+ if (memo.has(memoKey)) return memo.get(memoKey);
223
+ const prefix = provider === 'claude' ? 'anthropic' : 'openai';
224
+ const bases = [model, model.replace(/-\d{8}$/, ''), model.replace(/@.*$/, '')];
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
+ }
235
+ if (!entry && !warned.has(memoKey)) {
236
+ warned.add(memoKey);
237
+ log(`warning: no LiteLLM price for ${provider} model "${model}"; counting its cost as 0`);
238
+ }
239
+ memo.set(memoKey, entry);
240
+ return entry;
241
+ };
242
+ }
243
+
244
+ /** Prompt-size thresholds (in tokens) at which a model's price changes. */
245
+ function tierThresholds(entry) {
246
+ if (!entry) return [];
247
+ const out = [];
248
+ for (const key of Object.keys(entry)) {
249
+ const m = /^input_cost_per_token_above_(\d+)k_tokens$/.exec(key);
250
+ if (m) out.push(Number(m[1]) * 1000);
251
+ }
252
+ return out.sort((a, b) => b - a);
253
+ }
254
+
255
+ function tierFor(entry, promptTokens) {
256
+ for (const t of tierThresholds(entry)) if (promptTokens > t) return t;
257
+ return 0;
258
+ }
259
+
260
+ function price(entry, base, tier) {
261
+ if (!entry) return 0;
262
+ if (tier) {
263
+ const v = entry[`${base}_above_${tier / 1000}k_tokens`];
264
+ if (typeof v === 'number') return v;
265
+ }
266
+ const v = entry[base];
267
+ return typeof v === 'number' ? v : undefined;
268
+ }
269
+
270
+ /** Cost breakdown in USD for a bucket's tokens. */
271
+ function costOf(entry, tier, t) {
272
+ if (!entry) return { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, savings: 0 };
273
+ const inP = price(entry, 'input_cost_per_token', tier) ?? 0;
274
+ const outP = price(entry, 'output_cost_per_token', tier) ?? 0;
275
+ const readP = price(entry, 'cache_read_input_token_cost', tier) ?? inP * 0.1;
276
+ const write5mP = price(entry, 'cache_creation_input_token_cost', tier) ?? inP * 1.25;
277
+ const write1hP = tier
278
+ ? (entry[`cache_creation_input_token_cost_above_1hr_above_${tier / 1000}k_tokens`] ??
279
+ entry.cache_creation_input_token_cost_above_1hr ??
280
+ inP * 2)
281
+ : (entry.cache_creation_input_token_cost_above_1hr ?? inP * 2);
282
+ return {
283
+ input: t.input * inP,
284
+ cacheRead: t.cacheRead * readP,
285
+ cacheWrite: t.cacheWrite5m * write5mP + t.cacheWrite1h * write1hP,
286
+ output: t.output * outP,
287
+ savings: t.cacheRead * Math.max(0, inP - readP)
288
+ };
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // Log discovery + incremental reading
293
+
294
+ async function* walk(dir) {
295
+ let entries;
296
+ try {
297
+ entries = await readdir(dir, { withFileTypes: true });
298
+ } catch {
299
+ return;
300
+ }
301
+ for (const e of entries) {
302
+ const p = join(dir, e.name);
303
+ if (e.isDirectory()) yield* walk(p);
304
+ else if (e.isFile() && e.name.endsWith('.jsonl')) yield p;
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Streams complete lines from `offset`. Returns the byte offset just past the
310
+ * last complete line, so a half-written trailing line is re-read next run.
311
+ */
312
+ async function readLinesFrom(path, offset, onLine) {
313
+ let pos = offset;
314
+ let pending = Buffer.alloc(0);
315
+ for await (const chunk of createReadStream(path, { start: offset })) {
316
+ let buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
317
+ let start = 0;
318
+ let nl;
319
+ while ((nl = buf.indexOf(10, start)) !== -1) {
320
+ const line = buf.subarray(start, nl).toString('utf8');
321
+ pos += nl - start + 1;
322
+ start = nl + 1;
323
+ if (line.length > 1) onLine(line);
324
+ }
325
+ pending = buf.subarray(start);
326
+ }
327
+ return pos;
328
+ }
329
+
330
+ function parseJson(line) {
331
+ try {
332
+ return JSON.parse(line);
333
+ } catch {
334
+ return null;
335
+ }
336
+ }
337
+
338
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
339
+
340
+ // Claude Code: one assistant line per content block; the same API response is
341
+ // repeated, so de-duplicate by message.id + requestId (also across files, since
342
+ // resumed sessions copy earlier history). Some versions log a message's first
343
+ // line with a partial output count and a later line with the final one, so a
344
+ // repeat that reports more output adds the difference to the first line's hour.
345
+ function claudeLineHandler(state, resolvePrice, cutoffMs) {
346
+ return (line) => {
347
+ if (!line.includes('"assistant"')) return;
348
+ const o = parseJson(line);
349
+ if (!o || o.type !== 'assistant') return;
350
+ const msg = o.message;
351
+ const usage = msg?.usage;
352
+ const model = msg?.model;
353
+ if (!usage || !model || model === '<synthetic>') return;
354
+ const ts = Date.parse(o.timestamp);
355
+ if (!Number.isFinite(ts) || ts < cutoffMs) return;
356
+ const dedupe = `c:${shortHash(`${msg.id ?? ''}:${o.requestId ?? ''}`)}`;
357
+ if (!msg.id && !o.requestId) return;
358
+
359
+ const input = num(usage.input_tokens);
360
+ const cacheRead = num(usage.cache_read_input_tokens);
361
+ const cc = usage.cache_creation;
362
+ let cacheWrite5m = num(cc?.ephemeral_5m_input_tokens);
363
+ const cacheWrite1h = num(cc?.ephemeral_1h_input_tokens);
364
+ const ccTotal = num(usage.cache_creation_input_tokens);
365
+ // Older logs only have the total; treat it as 5-minute writes.
366
+ if (cacheWrite5m + cacheWrite1h < ccTotal) cacheWrite5m = ccTotal - cacheWrite1h;
367
+ const output = num(usage.output_tokens);
368
+ const tier = tierFor(
369
+ resolvePrice('claude', model),
370
+ input + cacheRead + cacheWrite5m + cacheWrite1h
371
+ );
372
+ const session = shortHash(`claude:${o.sessionId ?? 'unknown'}`);
373
+
374
+ const prev = state.seen[dedupe];
375
+ if (prev !== undefined) {
376
+ const [firstTs, counted] = Array.isArray(prev) ? prev : [prev, undefined];
377
+ // Unknown (counted by an older version, which kept the first line it read): the first line
378
+ // read again is what it counted.
379
+ if (counted === undefined) state.seen[dedupe] = [firstTs, output];
380
+ else if (output > counted) {
381
+ state.seen[dedupe] = [firstTs, output];
382
+ addRecord(state, {
383
+ ts: firstTs,
384
+ provider: 'claude',
385
+ model,
386
+ tier,
387
+ session,
388
+ input: 0,
389
+ cacheRead: 0,
390
+ cacheWrite5m: 0,
391
+ cacheWrite1h: 0,
392
+ output: output - counted
393
+ });
394
+ }
395
+ return;
396
+ }
397
+ state.seen[dedupe] = [ts, output];
398
+ addRecord(state, {
399
+ ts,
400
+ provider: 'claude',
401
+ model,
402
+ tier,
403
+ session,
404
+ input,
405
+ cacheRead,
406
+ cacheWrite5m,
407
+ cacheWrite1h,
408
+ output
409
+ });
410
+ };
411
+ }
412
+
413
+ // Codex: token_count events carry per-request usage in info.last_token_usage.
414
+ // input_tokens includes cached_input_tokens. output_tokens includes reasoning.
415
+ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSession) {
416
+ return (line) => {
417
+ const o = parseJson(line);
418
+ if (!o) return;
419
+ const p = o.payload;
420
+ if (o.type === 'session_meta' && p?.id) {
421
+ fileState.sessionId = String(p.id);
422
+ return;
423
+ }
424
+ if (o.type === 'turn_context' && typeof p?.model === 'string') {
425
+ fileState.model = p.model;
426
+ return;
427
+ }
428
+ if (o.type !== 'event_msg' || p?.type !== 'token_count' || !p.info) return;
429
+ const total = p.info.total_token_usage?.total_tokens;
430
+ if (typeof total === 'number') {
431
+ if (total === fileState.lastTotal) return;
432
+ fileState.lastTotal = total;
433
+ }
434
+ const last = p.info.last_token_usage;
435
+ if (!last) return;
436
+ const ts = Date.parse(o.timestamp);
437
+ if (!Number.isFinite(ts) || ts < cutoffMs) return;
438
+ const session = fileState.sessionId ?? fallbackSession;
439
+ const dedupe = `x:${shortHash(`${session}:${total}:${o.timestamp}`)}`;
440
+ if (state.seen[dedupe] !== undefined) return;
441
+ state.seen[dedupe] = ts;
442
+
443
+ const model = fileState.model ?? 'unknown';
444
+ const inputAll = num(last.input_tokens);
445
+ const cached = Math.min(num(last.cached_input_tokens), inputAll);
446
+ const entry = resolvePrice('codex', model);
447
+ addRecord(state, {
448
+ ts,
449
+ provider: 'codex',
450
+ model,
451
+ tier: tierFor(entry, inputAll),
452
+ session: shortHash(`codex:${session}`),
453
+ input: inputAll - cached,
454
+ cacheRead: cached,
455
+ cacheWrite5m: num(last.cache_write_input_tokens),
456
+ cacheWrite1h: 0,
457
+ output: num(last.output_tokens)
458
+ });
459
+ };
460
+ }
461
+
462
+ async function scan(state, resolvePrice, cutoffMs) {
463
+ const sources = [
464
+ { provider: 'claude', dir: join(HOME, '.claude', 'projects') },
465
+ { provider: 'claude', dir: join(HOME, '.config', 'claude', 'projects') },
466
+ { provider: 'codex', dir: join(HOME, '.codex', 'sessions') }
467
+ ];
468
+ if (process.env.CLAUDE_CONFIG_DIR) {
469
+ sources.push({ provider: 'claude', dir: join(process.env.CLAUDE_CONFIG_DIR, 'projects') });
470
+ }
471
+ if (process.env.CODEX_HOME) {
472
+ sources.push({ provider: 'codex', dir: join(process.env.CODEX_HOME, 'sessions') });
473
+ }
474
+
475
+ const seenPaths = new Set();
476
+ let parsedBytes = 0;
477
+ let filesRead = 0;
478
+ for (const { provider, dir } of sources) {
479
+ if (!existsSync(dir)) continue;
480
+ for await (const path of walk(dir)) {
481
+ if (seenPaths.has(path)) continue;
482
+ seenPaths.add(path);
483
+ let st;
484
+ try {
485
+ st = await stat(path);
486
+ } catch {
487
+ continue;
488
+ }
489
+ // Untouched for longer than the window: nothing in it can count.
490
+ if (st.mtimeMs < cutoffMs) {
491
+ delete state.files[path];
492
+ continue;
493
+ }
494
+ const prev = provider === 'claude' && state.rescanClaude ? undefined : state.files[path];
495
+ if (prev && prev.size === st.size && prev.mtimeMs === st.mtimeMs) continue;
496
+ // File shrank (rewritten/truncated): start over. Dedupe keys stop double counting.
497
+ /** @type {FileState} */
498
+ 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
+ const start = fs.offset;
510
+ try {
511
+ fs.offset = await readLinesFrom(path, start, handler);
512
+ } catch (err) {
513
+ log(`skipping unreadable file: ${err.message}`);
514
+ continue;
515
+ }
516
+ parsedBytes += fs.offset - start;
517
+ filesRead++;
518
+ fs.size = st.size;
519
+ fs.mtimeMs = st.mtimeMs;
520
+ state.files[path] = fs;
521
+ }
522
+ }
523
+ for (const path of Object.keys(state.files)) {
524
+ if (!seenPaths.has(path)) delete state.files[path];
525
+ }
526
+ delete state.rescanClaude;
527
+ log(`read ${filesRead} changed file(s), ${(parsedBytes / 1e6).toFixed(1)} MB of new log data`);
528
+ }
529
+
530
+ // ---------------------------------------------------------------------------
531
+ // Snapshot
532
+
533
+ const round = (n, d = 6) => Math.round(n * 10 ** d) / 10 ** d;
534
+
535
+ function buildSnapshot(state, resolvePrice, pricing, nowMs, coverageStartMs) {
536
+ const hourlyCutoff = Math.floor((nowMs - HOURLY_DAYS * DAY_MS) / DAY_MS) * DAY_MS;
537
+ /** @type {Map<string, any>} */
538
+ const rows = new Map();
539
+ for (const [key, b] of Object.entries(state.buckets)) {
540
+ const [hourStr, provider, model, tierStr] = key.split('|');
541
+ const hourMs = Number(hourStr);
542
+ if (hourMs < coverageStartMs) continue;
543
+ const daily = hourMs < hourlyCutoff;
544
+ const start = daily ? Math.floor(hourMs / DAY_MS) * DAY_MS : hourMs;
545
+ const rowKey = `${start}|${daily ? 'd' : 'h'}|${provider}|${model}`;
546
+ const c = costOf(resolvePrice(provider, model), Number(tierStr), b);
547
+ let row = rows.get(rowKey);
548
+ if (!row) {
549
+ row = {
550
+ hour: new Date(start).toISOString(),
551
+ ...(daily ? { granularity: 'day' } : {}),
552
+ provider,
553
+ model,
554
+ sessionSet: new Set(),
555
+ inputTokens: 0,
556
+ cacheReadTokens: 0,
557
+ cacheWrite5mTokens: 0,
558
+ cacheWrite1hTokens: 0,
559
+ outputTokens: 0,
560
+ costUsd: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
561
+ cacheSavingsUsd: 0
562
+ };
563
+ rows.set(rowKey, row);
564
+ }
565
+ for (const s of b.sessions) row.sessionSet.add(s);
566
+ row.inputTokens += b.input;
567
+ row.cacheReadTokens += b.cacheRead;
568
+ row.cacheWrite5mTokens += b.cacheWrite5m;
569
+ row.cacheWrite1hTokens += b.cacheWrite1h;
570
+ row.outputTokens += b.output;
571
+ row.costUsd.input += c.input;
572
+ row.costUsd.cacheRead += c.cacheRead;
573
+ row.costUsd.cacheWrite += c.cacheWrite;
574
+ row.costUsd.output += c.output;
575
+ row.cacheSavingsUsd += c.savings;
576
+ }
577
+
578
+ const hourly = [...rows.values()]
579
+ .sort((a, b) => a.hour.localeCompare(b.hour) || a.model.localeCompare(b.model))
580
+ .map(({ sessionSet, costUsd, cacheSavingsUsd, ...row }) => ({
581
+ hour: row.hour,
582
+ ...(row.granularity ? { granularity: row.granularity } : {}),
583
+ provider: row.provider,
584
+ model: row.model,
585
+ sessions: sessionSet.size,
586
+ inputTokens: row.inputTokens,
587
+ cacheReadTokens: row.cacheReadTokens,
588
+ cacheWrite5mTokens: row.cacheWrite5mTokens,
589
+ cacheWrite1hTokens: row.cacheWrite1hTokens,
590
+ outputTokens: row.outputTokens,
591
+ costUsd: {
592
+ input: round(costUsd.input),
593
+ cacheRead: round(costUsd.cacheRead),
594
+ cacheWrite: round(costUsd.cacheWrite),
595
+ output: round(costUsd.output)
596
+ },
597
+ cacheSavingsUsd: round(cacheSavingsUsd)
598
+ }));
599
+
600
+ // Distinct sessions per range, per provider. Session ids never leave the machine.
601
+ const ranges = { '24h': DAY_MS, '7d': 7 * DAY_MS, '30d': 30 * DAY_MS, '90d': 90 * DAY_MS };
602
+ const currentHour = Math.floor(nowMs / HOUR_MS) * HOUR_MS;
603
+ const sessionCounts = {};
604
+ const all = new Set();
605
+ for (const [name, span] of Object.entries(ranges)) {
606
+ const from = currentHour + HOUR_MS - span;
607
+ const sets = { claude: new Set(), codex: new Set() };
608
+ for (const [key, b] of Object.entries(state.buckets)) {
609
+ const [hourStr, provider] = key.split('|');
610
+ const h = Number(hourStr);
611
+ if (h < from || h < coverageStartMs) continue;
612
+ for (const s of b.sessions) sets[provider]?.add(s);
613
+ }
614
+ sessionCounts[name] = {
615
+ claude: sets.claude.size,
616
+ codex: sets.codex.size,
617
+ all: sets.claude.size + sets.codex.size
618
+ };
619
+ }
620
+ for (const [key, b] of Object.entries(state.buckets)) {
621
+ if (Number(key.split('|')[0]) >= coverageStartMs) for (const s of b.sessions) all.add(s);
622
+ }
623
+
624
+ // The 24h count is only for the local --summary; published ranges are day-granular.
625
+ const { '24h': sessions24h, ...publicCounts } = sessionCounts;
626
+ const snapshot = {
627
+ schemaVersion: SCHEMA_VERSION,
628
+ deviceId: setting('DEVICE_ID'),
629
+ generatedAt: new Date(nowMs).toISOString(),
630
+ coverageStart: new Date(coverageStartMs).toISOString(),
631
+ pricingSource: `litellm@${new Date(pricing.fetchedAt).toISOString().slice(0, 10)}`,
632
+ hourly,
633
+ sessionsTotal: all.size,
634
+ sessionCounts: publicCounts
635
+ };
636
+ return { snapshot, sessions24h };
637
+ }
638
+
639
+ function printSummary(snapshot, sessions24h, nowMs) {
640
+ const from = Math.floor(nowMs / HOUR_MS) * HOUR_MS + HOUR_MS - DAY_MS;
641
+ const byModel = new Map();
642
+ let total = 0;
643
+ let tokens = 0;
644
+ let savings = 0;
645
+ const byType = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
646
+ for (const r of snapshot.hourly) {
647
+ if (r.granularity === 'day' || Date.parse(r.hour) < from) continue;
648
+ const c = r.costUsd.input + r.costUsd.cacheRead + r.costUsd.cacheWrite + r.costUsd.output;
649
+ const t =
650
+ r.inputTokens +
651
+ r.cacheReadTokens +
652
+ r.cacheWrite5mTokens +
653
+ r.cacheWrite1hTokens +
654
+ r.outputTokens;
655
+ total += c;
656
+ tokens += t;
657
+ savings += r.cacheSavingsUsd;
658
+ for (const k of Object.keys(byType)) byType[k] += r.costUsd[k];
659
+ const m = byModel.get(r.model) ?? { cost: 0, tokens: 0 };
660
+ m.cost += c;
661
+ m.tokens += t;
662
+ byModel.set(r.model, m);
663
+ }
664
+ const usd = (n) => `$${n.toFixed(2)}`;
665
+ const lines = [
666
+ `Past 24h on "${snapshot.deviceId || '(no device id)'}" (API-price estimate, ${snapshot.pricingSource})`,
667
+ ` total cost ${usd(total)}`,
668
+ ` sessions ${sessions24h.all}`,
669
+ ` tokens ${(tokens / 1e6).toFixed(2)}M`,
670
+ ` cache savings ${usd(savings)}`,
671
+ ` by type input ${usd(byType.input)} · cache read ${usd(byType.cacheRead)} · cache write ${usd(byType.cacheWrite)} · output ${usd(byType.output)}`,
672
+ ...[...byModel.entries()]
673
+ .sort((a, b) => b[1].cost - a[1].cost)
674
+ .map(
675
+ ([m, v]) =>
676
+ ` ${m.padEnd(28)} ${usd(v.cost).padStart(10)} ${(v.tokens / 1e6).toFixed(1)}M tok`
677
+ ),
678
+ `Compare with \`bunx ccusage claude daily\` (Claude Code only) for this device.`
679
+ ];
680
+ console.error(lines.join('\n'));
681
+ }
682
+
683
+ // ---------------------------------------------------------------------------
684
+ // Upload
685
+
686
+ async function post(snapshot) {
687
+ const url = setting('INGEST_URL');
688
+ const token = setting('INGEST_TOKEN').trim();
689
+ if (!url || !token) {
690
+ throw new Error('BIG_SPENDER_INGEST_URL and BIG_SPENDER_INGEST_TOKEN must be set');
691
+ }
692
+ // fetch quotes the whole header in its error for some of these, which would print the token.
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
+ }
698
+ const body = gzipSync(JSON.stringify(snapshot));
699
+ let lastErr;
700
+ for (let attempt = 1; attempt <= POST_ATTEMPTS; attempt++) {
701
+ try {
702
+ const res = await fetch(url, {
703
+ method: 'POST',
704
+ headers: {
705
+ authorization: `Bearer ${token}`,
706
+ 'content-type': 'application/json',
707
+ 'content-encoding': 'gzip'
708
+ },
709
+ body,
710
+ signal: AbortSignal.timeout(30_000)
711
+ });
712
+ const text = (await res.text()).slice(0, 300);
713
+ if (res.ok) {
714
+ log(`posted ${snapshot.hourly.length} rows (${body.length} bytes gzipped): ${text}`);
715
+ return;
716
+ }
717
+ lastErr = new Error(`HTTP ${res.status}: ${text}`);
718
+ // Client errors other than rate limiting won't fix themselves.
719
+ if (res.status >= 400 && res.status < 500 && res.status !== 429) break;
720
+ } catch (err) {
721
+ lastErr = err;
722
+ }
723
+ if (attempt < POST_ATTEMPTS) {
724
+ const wait = 2 ** attempt * 1000;
725
+ log(`POST failed (${lastErr.message}); retrying in ${wait / 1000}s`);
726
+ await new Promise((r) => setTimeout(r, wait));
727
+ }
728
+ }
729
+ throw lastErr;
730
+ }
731
+
732
+ // ---------------------------------------------------------------------------
733
+
734
+ async function main() {
735
+ loadEnvFile();
736
+ const deviceId = setting('DEVICE_ID');
737
+ if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(deviceId)) {
738
+ if (!(DRY_RUN || SUMMARY_ONLY)) {
739
+ throw new Error('BIG_SPENDER_DEVICE_ID must be a lowercase slug like "laptop" or "desktop"');
740
+ }
741
+ }
742
+ const release = await acquireLock();
743
+ if (!release) {
744
+ log('another run is in progress; skipping');
745
+ return;
746
+ }
747
+ try {
748
+ const nowMs = Date.now();
749
+ const coverageStartMs = Math.floor((nowMs - RETENTION_DAYS * DAY_MS) / DAY_MS) * DAY_MS;
750
+
751
+ const pricing = await loadPricing();
752
+ const resolvePrice = makePriceResolver(pricing.models);
753
+ const state = await loadState();
754
+ pruneState(state, coverageStartMs);
755
+ await scan(state, resolvePrice, coverageStartMs);
756
+ await saveState(state);
757
+
758
+ const { snapshot, sessions24h } = buildSnapshot(
759
+ state,
760
+ resolvePrice,
761
+ pricing,
762
+ nowMs,
763
+ coverageStartMs
764
+ );
765
+ if (DRY_RUN) console.log(JSON.stringify(snapshot, null, 2));
766
+ if (DRY_RUN || SUMMARY_ONLY) {
767
+ printSummary(snapshot, sessions24h, nowMs);
768
+ return;
769
+ }
770
+ await post(snapshot);
771
+ } finally {
772
+ await release();
773
+ }
774
+ }
775
+
776
+ main().catch((err) => {
777
+ log(`error: ${err?.message ?? err}`);
778
+ process.exit(1);
779
+ });