big-spender 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,9 +4,10 @@ See what your AI coding agents would cost at API prices, summed across all your
4
4
 
5
5
  Each machine runs a small collector every hour. It reads that machine's Claude Code and Codex
6
6
  session logs, works out hourly token and cost totals at [LiteLLM](https://github.com/BerriAI/litellm)
7
- API prices, and posts one snapshot (the last 90 days) to a server you run. The server keeps the
8
- latest snapshot per device, adds the devices together, and serves the totals as JSON and as a plain
9
- HTML page. You can also embed the server side in your own app and draw the numbers however you like.
7
+ API prices, and posts one snapshot (the last 90 days) to a server you run. The server merges each
8
+ snapshot into that device's stored history, adds the devices together, and serves the totals as
9
+ JSON and as a plain HTML page. You can also embed the server side in your own app and draw the
10
+ numbers however you like.
10
11
 
11
12
  The collector has no dependencies and needs Node 20 or newer. The package depends on `zod` only.
12
13
 
@@ -18,7 +19,8 @@ their counts are sent. The server rejects any snapshot with extra fields, so not
18
19
  stored or served even by a modified collector.
19
20
 
20
21
  The server never publishes a device's report time (it would show when each machine is online), and
21
- every range is bucketed by UTC day, never by hour. Device ids are published only if you leave
22
+ nothing is bucketed finer than a UTC day: 7, 30 and 90 days are per day, all time is per ISO week
23
+ (Monday UTC). Device ids are published only if you leave
22
24
  `unknownDevices` at its default, see [Device names and colours](#device-names-and-colours).
23
25
 
24
26
  Before the first send you can see exactly what would leave the machine with
@@ -89,7 +91,7 @@ Remove the schedule with `big-spender uninstall`. The env file and the state are
89
91
  | Route | What it does |
90
92
  | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
91
93
  | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
92
- | `GET /api/usage` | Merged totals for 7, 30 and 90 days as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
94
+ | `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
93
95
  | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models. No JavaScript, no external assets, light and dark. |
94
96
  | `GET /healthz` | `ok`, for load balancers and Docker. |
95
97
 
@@ -104,12 +106,17 @@ Configuration comes from flags or environment variables (flags win):
104
106
  | | `BIG_SPENDER_INGEST_TOKEN` | none: ingest is off and answers `503` |
105
107
 
106
108
  The data directory holds one `<device>.json` file per device, written atomically. Put it on a
107
- persistent volume. A snapshot older than the stored one is ignored (`"result": "stale"`), so retries
108
- and duplicate posts are harmless. Files in the directory that are not valid snapshots are ignored
109
- with a warning.
109
+ persistent volume. Each snapshot is merged into the device's stored history. A day the snapshot
110
+ reports replaces that day for each provider and model. Days it does not report are kept as day
111
+ rows, so the server keeps usage from beyond the collector's 90-day window, and the all-time range
112
+ shows it. All time has no session count (`sessions: null`): collectors count distinct sessions
113
+ on the device for 7, 30 and 90 days only. A device file holds at most 50,000 rows. Past that, the oldest kept days are dropped
114
+ and the server logs a warning. A snapshot older than the stored one is ignored (`"result":
115
+ "stale"`), so retries and duplicate posts are harmless. Files in the directory that are not valid snapshots are ignored with a warning.
110
116
 
111
117
  Ingest limits: request bodies up to 2 MB, 16 MB after decompression, `gzip` or `identity` encoding
112
- only. An invalid snapshot gets `422` with the first five problems.
118
+ only. An invalid snapshot gets `422` with the first five problems. Dates before 2020-01-01 are
119
+ invalid.
113
120
 
114
121
  ### Device names and colours
115
122
 
@@ -186,10 +193,10 @@ big-spender push laptop # same review, then asks before sending
186
193
 
187
194
  It builds the snapshot and lists the model names it would publish. It stops if a name looks like a
188
195
  cloud resource id or gateway path (it contains `arn:` or `/`), such as a Bedrock inference-profile
189
- ARN with an account id in it. It asks before sending and takes the URL from `--url`,
190
- `BIG_SPENDER_INGEST_URL` or a prompt, and the token from `BIG_SPENDER_INGEST_TOKEN` or a hidden
191
- prompt. Neither is stored. Nothing is scheduled, so the server shows that device's usage as of its
192
- last push.
196
+ ARN with an account id in it. It asks before sending, sends exactly the JSON it showed, and takes
197
+ the URL from `--url`, `BIG_SPENDER_INGEST_URL` or a prompt, and the token from
198
+ `BIG_SPENDER_INGEST_TOKEN` or a hidden prompt. Neither is stored. Nothing is scheduled, so the
199
+ server shows that device's usage as of its last push.
193
200
 
194
201
  `--dry-run` writes the JSON that would be sent to `$TMPDIR/big-spender-snapshot-<device>.json`.
195
202
 
@@ -236,16 +243,20 @@ State from an older collector is fixed in place on the first run of a newer one
236
243
  re-read of the Claude logs to pick up missed output tokens), so updating never needs `--reset`.
237
244
 
238
245
  A machine that was off catches up on its next run. A failed post retries with backoff and exits
239
- non-zero; the token is never logged.
246
+ non-zero; the token is never logged. A token with a space, a control character or anything else an
247
+ HTTP header cannot carry fails at once, without a retry, in both the collector and `push`.
240
248
 
241
249
  ## Coming from the earlier standalone script
242
250
 
243
251
  `big-spender install` migrates an install of the earlier `usage-collector` script in place: it
244
- removes the old systemd units or LaunchAgent, moves its config and state (so history is kept
245
- byte for byte), renames the `USAGE_*` keys in the env file to `BIG_SPENDER_*`, and deletes the old
246
- copy of the script. If the old collector is running at that moment it waits for you to run install
247
- again. The collector still reads `USAGE_DEVICE_ID`, `USAGE_INGEST_URL` and `USAGE_INGEST_TOKEN`
248
- when the `BIG_SPENDER_*` name is unset, so a machine you have not updated keeps working.
252
+ removes the old systemd units or LaunchAgent, moves its config and state (so history is kept byte
253
+ for byte), renames the `USAGE_*` keys in the env file to `BIG_SPENDER_*`, and deletes the old copy
254
+ of the script. If `status` or `push` already made a new cache, the old state replaces it only while
255
+ the old collector is still scheduled or wrote its state last; otherwise the old cache is left in
256
+ place and the newer one kept. If the old collector, or a `status` or `push` whose cache would be
257
+ replaced, is running at that moment, install changes nothing and asks you to run it again. The
258
+ collector still reads `USAGE_DEVICE_ID`, `USAGE_INGEST_URL` and `USAGE_INGEST_TOKEN` when the
259
+ `BIG_SPENDER_*` name is unset, so a machine you have not updated keeps working.
249
260
 
250
261
  ## Development
251
262
 
@@ -685,10 +685,16 @@ function printSummary(snapshot, sessions24h, nowMs) {
685
685
 
686
686
  async function post(snapshot) {
687
687
  const url = setting('INGEST_URL');
688
- const token = setting('INGEST_TOKEN');
688
+ const token = setting('INGEST_TOKEN').trim();
689
689
  if (!url || !token) {
690
690
  throw new Error('BIG_SPENDER_INGEST_URL and BIG_SPENDER_INGEST_TOKEN must be set');
691
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
+ }
692
698
  const body = gzipSync(JSON.stringify(snapshot));
693
699
  let lastErr;
694
700
  for (let attempt = 1; attempt <= POST_ATTEMPTS; attempt++) {
@@ -0,0 +1,5 @@
1
+ import { type UsageSnapshot } from './schema.ts';
2
+ export declare function mergeSnapshots(stored: UsageSnapshot | undefined, next: UsageSnapshot): {
3
+ snapshot: UsageSnapshot;
4
+ droppedDays: number;
5
+ };
@@ -0,0 +1,85 @@
1
+ import { MAX_ROWS, usageRowSchema } from './schema.js';
2
+ const DAY_MS = 86_400_000;
3
+ const round = (n) => Math.round(n * 1e6) / 1e6;
4
+ const dayOf = (r) => Math.floor(Date.parse(r.hour) / DAY_MS);
5
+ const keyOf = (r) => `${dayOf(r)}|${r.provider}|${r.model}`;
6
+ function compareRows(a, b) {
7
+ return (Date.parse(a.hour) - Date.parse(b.hour) ||
8
+ a.provider.localeCompare(b.provider) ||
9
+ a.model.localeCompare(b.model) ||
10
+ (a.granularity ?? 'hour').localeCompare(b.granularity ?? 'hour'));
11
+ }
12
+ function group(rows) {
13
+ const out = new Map();
14
+ for (const r of rows) {
15
+ const key = keyOf(r);
16
+ const list = out.get(key);
17
+ if (list)
18
+ list.push(r);
19
+ else
20
+ out.set(key, [r]);
21
+ }
22
+ return out;
23
+ }
24
+ function rollUp(rows) {
25
+ const [first] = rows;
26
+ if (rows.length === 1 && first.granularity === 'day')
27
+ return rows;
28
+ const sum = (pick) => rows.reduce((total, r) => total + pick(r), 0);
29
+ const sessionsAtLeast = Math.max(...rows.map((r) => r.sessions));
30
+ const day = {
31
+ hour: new Date(dayOf(first) * DAY_MS).toISOString(),
32
+ granularity: 'day',
33
+ provider: first.provider,
34
+ model: first.model,
35
+ sessions: sessionsAtLeast,
36
+ inputTokens: sum((r) => r.inputTokens),
37
+ cacheReadTokens: sum((r) => r.cacheReadTokens),
38
+ cacheWrite5mTokens: sum((r) => r.cacheWrite5mTokens),
39
+ cacheWrite1hTokens: sum((r) => r.cacheWrite1hTokens),
40
+ outputTokens: sum((r) => r.outputTokens),
41
+ costUsd: {
42
+ input: round(sum((r) => r.costUsd.input)),
43
+ cacheRead: round(sum((r) => r.costUsd.cacheRead)),
44
+ cacheWrite: round(sum((r) => r.costUsd.cacheWrite)),
45
+ output: round(sum((r) => r.costUsd.output))
46
+ },
47
+ cacheSavingsUsd: round(sum((r) => r.cacheSavingsUsd))
48
+ };
49
+ // A sum can pass a field's cap, and a day can start outside the schema's date range.
50
+ return usageRowSchema.safeParse(day).success ? [day] : rows;
51
+ }
52
+ function dropOldestDays(rows, excess) {
53
+ let cut = 0;
54
+ let days = 0;
55
+ while (cut < excess) {
56
+ const day = dayOf(rows[cut]);
57
+ while (cut < rows.length && dayOf(rows[cut]) === day)
58
+ cut++;
59
+ days++;
60
+ }
61
+ return { rows: rows.slice(cut), days };
62
+ }
63
+ export function mergeSnapshots(stored, next) {
64
+ const fresh = [...next.hourly].sort(compareRows);
65
+ if (!stored)
66
+ return { snapshot: { ...next, hourly: fresh }, droppedDays: 0 };
67
+ const reported = new Set(fresh.map(keyOf));
68
+ const kept = [...group(stored.hourly)]
69
+ .filter(([key]) => !reported.has(key))
70
+ .flatMap(([, rows]) => rollUp(rows))
71
+ .sort(compareRows);
72
+ let coverage = Date.parse(stored.coverageStart) < Date.parse(next.coverageStart)
73
+ ? stored.coverageStart
74
+ : next.coverageStart;
75
+ const trimmed = dropOldestDays(kept, kept.length + fresh.length - MAX_ROWS);
76
+ const droppedDays = trimmed.days;
77
+ const hourly = [...trimmed.rows, ...fresh].sort(compareRows);
78
+ if (droppedDays > 0) {
79
+ const earliest = dayOf(hourly[0]) * DAY_MS;
80
+ const latest = Math.min(earliest, Date.parse(next.coverageStart));
81
+ if (latest > Date.parse(coverage))
82
+ coverage = new Date(latest).toISOString();
83
+ }
84
+ return { snapshot: { ...next, coverageStart: coverage, hourly }, droppedDays };
85
+ }
package/dist/install.js CHANGED
@@ -8,6 +8,9 @@ import { DEVICE_ID } from './schema.js';
8
8
  import { pickScheduler } from './scheduler.js';
9
9
  // The collector removes its lock when it finishes, so one this young belongs to a live run.
10
10
  const LOCK_FRESH_MS = 30 * 60 * 1000;
11
+ // Written into the old cache before its schedule is removed, so a rerun after a crash still knows
12
+ // the old collector was scheduled. Not the old share dir: old uninstalls left that behind.
13
+ const WAS_SCHEDULED = '.big-spender-was-scheduled';
11
14
  const exists = (path) => access(path).then(() => true, () => false);
12
15
  const readText = (path) => readFile(path, 'utf8').catch(() => undefined);
13
16
  async function writePrivate(path, text) {
@@ -57,23 +60,40 @@ async function migrateConfig(ctx, log) {
57
60
  }
58
61
  }
59
62
  /**
60
- * What to do with the old collector's cache. `status` and `push --dry-run` create a cache of
61
- * their own from the logs still on disk, which lacks the days only the old state.json kept, so
62
- * before the first install the old cache wins and the new one is set aside.
63
+ * What to do with the old collector's cache. `status` and `push` create a cache of their own
64
+ * from the logs still on disk, which lacks the days only the old state.json kept, so while the
65
+ * old collector is still scheduled, or wrote its state last, the old cache wins and the new one
66
+ * is set aside. Otherwise the new cache is the current one and the old one is left alone.
63
67
  */
64
- async function planCache(ctx) {
65
- const { paths } = ctx;
66
- if (!(await exists(paths.legacy.cacheDir)))
68
+ function planCache(f) {
69
+ if (!f.legacyCache)
67
70
  return 'none';
68
- if (!(await exists(paths.cacheDir)))
71
+ if (!f.newCache)
69
72
  return 'move';
70
- return (await exists(paths.collector)) ? 'keep' : 'replace';
73
+ if (f.installed)
74
+ return 'keep';
75
+ return f.legacyScheduled || f.legacyStateNewer ? 'replace' : 'keep-older';
76
+ }
77
+ const mtime = async (path) => (await stat(path).catch(() => null))?.mtimeMs ?? -Infinity;
78
+ async function cacheFacts(ctx, legacyScheduled) {
79
+ const { paths } = ctx;
80
+ return {
81
+ legacyCache: await exists(paths.legacy.cacheDir),
82
+ newCache: await exists(paths.cacheDir),
83
+ installed: await exists(paths.collector),
84
+ legacyScheduled,
85
+ legacyStateNewer: (await mtime(join(paths.legacy.cacheDir, 'state.json'))) >
86
+ (await mtime(join(paths.cacheDir, 'state.json')))
87
+ };
71
88
  }
72
89
  async function migrateCache(ctx, plan, log) {
73
90
  const { paths } = ctx;
74
91
  if (plan === 'keep') {
75
92
  log.push(`left ${paths.legacy.cacheDir} in place: ${paths.cacheDir} already exists, so the old state was not moved`);
76
93
  }
94
+ if (plan === 'keep-older') {
95
+ log.push(`left ${paths.legacy.cacheDir} in place: it has no newer state than ${paths.cacheDir}, which stays the current cache`);
96
+ }
77
97
  if (plan === 'replace') {
78
98
  const aside = `${paths.cacheDir}.pre-install-${new Date().toISOString().replace(/[:.]/g, '-')}`;
79
99
  await rename(paths.cacheDir, aside);
@@ -84,6 +104,7 @@ async function migrateCache(ctx, plan, log) {
84
104
  log.push(`moved ${paths.legacy.cacheDir} to ${paths.cacheDir}`);
85
105
  // The old units are stopped by now, so a lock that came along belongs to a dead run.
86
106
  await rm(paths.lock, { force: true });
107
+ await rm(join(paths.cacheDir, WAS_SCHEDULED), { force: true });
87
108
  }
88
109
  }
89
110
  /** Settings already on this machine, from the new env file or the one the old collector made. */
@@ -126,10 +147,16 @@ export async function install(args, ctx) {
126
147
  }
127
148
  const scheduler = pickScheduler(ctx.env, ctx.platform, paths, ctx.templatesDir, ctx.ctl);
128
149
  await scheduler.check();
129
- const cachePlan = await planCache(ctx);
150
+ const legacySchedule = await scheduler.findLegacy();
151
+ const wasScheduled = join(paths.legacy.cacheDir, WAS_SCHEDULED);
152
+ const legacyScheduled = legacySchedule.length > 0 || (await exists(wasScheduled));
153
+ const cachePlan = planCache(await cacheFacts(ctx, legacyScheduled));
130
154
  if ((cachePlan === 'move' || cachePlan === 'replace') && (await lockIsFresh(paths.legacy.lock))) {
131
155
  throw new UsageError(`the old collector is running (${paths.legacy.lock} is recent); wait for it to finish and run install again`);
132
156
  }
157
+ if (cachePlan === 'replace' && (await lockIsFresh(paths.lock))) {
158
+ throw new UsageError(`big-spender is running (${paths.lock} is recent), and install would move its cache aside; wait for it to finish and run install again`);
159
+ }
133
160
  let url = values.url ?? ctx.env.BIG_SPENDER_INGEST_URL ?? existing.url;
134
161
  let token = ctx.env.BIG_SPENDER_INGEST_TOKEN || existing.token;
135
162
  if (!url)
@@ -139,6 +166,9 @@ export async function install(args, ctx) {
139
166
  if (!url || !token)
140
167
  throw new UsageError('an ingest URL and token are required');
141
168
  const log = [];
169
+ if (legacySchedule.length > 0 && (cachePlan === 'move' || cachePlan === 'replace')) {
170
+ await writeFile(wasScheduled, '');
171
+ }
142
172
  for (const removed of await scheduler.removeLegacy())
143
173
  log.push(`removed old schedule ${removed}`);
144
174
  await migrateConfig(ctx, log);
package/dist/page.js CHANGED
@@ -8,7 +8,12 @@ const tokens = (n) => n >= 1e9
8
8
  ? `${(n / 1e6).toFixed(1)}M`
9
9
  : n.toLocaleString('en-US');
10
10
  const percent = (share) => `${(share * 100).toFixed(1)}%`;
11
- const LABELS = { '7d': '7 days', '30d': '30 days', '90d': '90 days' };
11
+ const LABELS = {
12
+ '7d': 'Last 7 days',
13
+ '30d': 'Last 30 days',
14
+ '90d': 'Last 90 days',
15
+ all: 'All time'
16
+ };
12
17
  const TOP_MODELS = 8;
13
18
  const STYLE = `
14
19
  :root { color-scheme: light dark; --bg: #fafaf7; --fg: #1b1f1c; --muted: #66706a; --card: #ffffff; --line: #dfe3dd; }
@@ -35,13 +40,13 @@ th { color: var(--muted); font-weight: 500; font-size: 0.85rem; }
35
40
  .empty { color: var(--muted); }
36
41
  `;
37
42
  function totalsCard(r) {
38
- return `<section class="card"><h3>Last ${LABELS[r.range]}</h3>
43
+ return `<section class="card"><h3>${LABELS[r.range]}</h3>
39
44
  <p class="cost">${usd(r.totalCost)}</p>
40
- <p>${r.sessions.toLocaleString('en-US')} sessions · ${tokens(r.tokens.processed)} tokens</p>
45
+ <p>${r.sessions === null ? '' : `${r.sessions.toLocaleString('en-US')} sessions · `}${tokens(r.tokens.processed)} tokens</p>
41
46
  <p>${usd(r.cacheSavings)} saved by caching</p></section>`;
42
47
  }
43
48
  function devicesTable(summary) {
44
- const widest = summary.ranges['90d'];
49
+ const widest = summary.ranges.all;
45
50
  if (!widest.devices.length)
46
51
  return '<p class="empty">No devices have reported yet.</p>';
47
52
  const rows = widest.devices.map((d) => {
package/dist/paths.d.ts CHANGED
@@ -3,6 +3,8 @@ export type Paths = {
3
3
  home: string;
4
4
  tmpDir: string;
5
5
  envFile: string;
6
+ /** The env file the collector reads: envFile, unless BIG_SPENDER_ENV_FILE or USAGE_ENV_FILE names another. */
7
+ collectorEnvFile: string;
6
8
  configDir: string;
7
9
  cacheDir: string;
8
10
  lock: string;
package/dist/paths.js CHANGED
@@ -7,10 +7,12 @@ export function resolvePaths(env = process.env, home = homedir()) {
7
7
  const configDir = join(config, 'big-spender');
8
8
  const shareDir = join(share, 'big-spender');
9
9
  const legacyCacheDir = join(cache, 'usage-collector');
10
+ const envFile = join(configDir, 'env');
10
11
  return {
11
12
  home,
12
13
  tmpDir: env.TMPDIR || env.TEMP || '/tmp',
13
- envFile: join(configDir, 'env'),
14
+ envFile,
15
+ collectorEnvFile: env.BIG_SPENDER_ENV_FILE || env.USAGE_ENV_FILE || envFile,
14
16
  configDir,
15
17
  cacheDir: join(cache, 'big-spender'),
16
18
  lock: join(cache, 'big-spender', 'run.lock'),
package/dist/push.js CHANGED
@@ -1,10 +1,10 @@
1
- import { execFile, spawn } from 'node:child_process';
2
- import { writeFile } from 'node:fs/promises';
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
5
  import { gzipSync } from 'node:zlib';
6
6
  import { UsageError } from './context.js';
7
- import { setting } from './envfile.js';
7
+ import { parseEnv, setting } from './envfile.js';
8
8
  import { DEVICE_ID } from './schema.js';
9
9
  export const PUSH_USAGE = `Usage: big-spender push <device> [--dry-run] [--url <ingest url>]
10
10
 
@@ -18,6 +18,7 @@ prompt, so neither is written to this machine. Nothing is scheduled.
18
18
  $TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the
19
19
  collector's local state in ~/.cache/big-spender (which logs were read), never anything remote.`;
20
20
  const MAX_SNAPSHOT_BYTES = 512 * 1024 * 1024;
21
+ const POST_ATTEMPTS = 4;
21
22
  function runCollector(ctx, extraEnv, args) {
22
23
  return new Promise((resolve) => {
23
24
  execFile(process.execPath, [ctx.collector, ...args], { env: { ...ctx.env, ...extraEnv }, maxBuffer: MAX_SNAPSHOT_BYTES }, (err, stdout, stderr) => {
@@ -26,7 +27,7 @@ function runCollector(ctx, extraEnv, args) {
26
27
  });
27
28
  });
28
29
  }
29
- function overview(snapshot) {
30
+ function overview(snapshot, gzipped) {
30
31
  const byModel = new Map();
31
32
  for (const r of snapshot.hourly) {
32
33
  const key = `${r.provider} ${r.model}`;
@@ -43,7 +44,6 @@ function overview(snapshot) {
43
44
  const rows = [...byModel].sort((a, b) => b[1].cost - a[1].cost);
44
45
  const width = Math.max(20, ...rows.map(([k]) => k.length));
45
46
  const days = snapshot.hourly.map((r) => r.hour.slice(0, 10)).sort();
46
- const gzipped = gzipSync(JSON.stringify(snapshot)).length;
47
47
  const line = (label, tokens, cost) => ` ${label.padEnd(width)} ${`${(tokens / 1e6).toFixed(1)}M`.padStart(10)} ${`$${cost.toFixed(2)}`.padStart(10)}`;
48
48
  let tokens = 0;
49
49
  let cost = 0;
@@ -81,7 +81,8 @@ export async function push(args, ctx) {
81
81
  if (/warning/i.test(line))
82
82
  ctx.err(line);
83
83
  const snapshot = JSON.parse(built.stdout);
84
- for (const line of overview(snapshot))
84
+ const body = gzipSync(built.stdout);
85
+ for (const line of overview(snapshot, body.length))
85
86
  ctx.out(line);
86
87
  const blocked = snapshot.hourly.some((r) => /arn:|\//i.test(r.model));
87
88
  if (blocked) {
@@ -101,21 +102,55 @@ export async function push(args, ctx) {
101
102
  ctx.out('Nothing sent.');
102
103
  return 0;
103
104
  }
105
+ const saved = parseEnv(await readFile(ctx.paths.collectorEnvFile, 'utf8').catch(() => ''));
104
106
  const url = values.url ??
105
107
  (setting(ctx.env, 'INGEST_URL') ||
106
- (await prompter.ask('Ingest URL (https://…/api/usage/ingest): ')));
107
- const token = setting(ctx.env, 'INGEST_TOKEN') || (await prompter.askHidden('Ingest token: '));
108
- // Pass only what was given, so an empty answer still lets the collector read its env file.
109
- const given = { BIG_SPENDER_DEVICE_ID: deviceId };
110
- if (url)
111
- given.BIG_SPENDER_INGEST_URL = url;
112
- if (token)
113
- given.BIG_SPENDER_INGEST_TOKEN = token;
114
- return new Promise((resolve) => {
115
- const child = spawn(process.execPath, [ctx.collector], {
116
- env: { ...ctx.env, ...given },
117
- stdio: ['ignore', 'inherit', 'inherit']
118
- });
119
- child.on('close', (code) => resolve(code ?? 1));
120
- });
108
+ (await prompter.ask('Ingest URL (https://…/api/usage/ingest): ')) ||
109
+ setting(saved, 'INGEST_URL'));
110
+ const token = (setting(ctx.env, 'INGEST_TOKEN') ||
111
+ (await prompter.askHidden('Ingest token: ')) ||
112
+ setting(saved, 'INGEST_TOKEN')).trim();
113
+ if (!url || !token)
114
+ throw new Error('an ingest URL and token are required');
115
+ // fetch quotes the whole header in its error for some of these, which would print the token.
116
+ if (!/^[\x21-\x7e]+$/.test(token)) {
117
+ throw new Error('the ingest token contains characters that are not allowed in an HTTP header; check it for spaces or a stray newline');
118
+ }
119
+ const result = await send(ctx, url, token, body);
120
+ ctx.out(`posted ${snapshot.hourly.length} rows (${body.length} bytes gzipped): ${result}`);
121
+ return 0;
122
+ }
123
+ /** POSTs the reviewed bytes with the collector's retry policy and returns the server's reply. */
124
+ async function send(ctx, url, token, body) {
125
+ let lastErr = new Error('not sent');
126
+ for (let attempt = 1; attempt <= POST_ATTEMPTS; attempt++) {
127
+ try {
128
+ const res = await fetch(url, {
129
+ method: 'POST',
130
+ headers: {
131
+ authorization: `Bearer ${token}`,
132
+ 'content-type': 'application/json',
133
+ 'content-encoding': 'gzip'
134
+ },
135
+ body,
136
+ signal: AbortSignal.timeout(30_000)
137
+ });
138
+ const text = (await res.text()).slice(0, 300);
139
+ if (res.ok)
140
+ return text;
141
+ lastErr = new Error(`HTTP ${res.status}: ${text}`);
142
+ // Client errors other than rate limiting won't fix themselves.
143
+ if (res.status >= 400 && res.status < 500 && res.status !== 429)
144
+ break;
145
+ }
146
+ catch (err) {
147
+ lastErr = err instanceof Error ? err : new Error(String(err));
148
+ }
149
+ if (attempt < POST_ATTEMPTS) {
150
+ const wait = 2 ** attempt * 1000;
151
+ ctx.err(`POST failed (${lastErr.message}); retrying in ${wait / 1000}s`);
152
+ await new Promise((r) => setTimeout(r, wait));
153
+ }
154
+ }
155
+ throw lastErr;
121
156
  }
@@ -2,6 +2,8 @@ import type { Paths } from './paths.ts';
2
2
  export type Scheduler = {
3
3
  /** Fails with a clear message if the schedule cannot be managed from here. Changes nothing. */
4
4
  check(): Promise<void>;
5
+ /** The schedule files the site's usage-collector installed that are still here. Changes nothing. */
6
+ findLegacy(): Promise<string[]>;
5
7
  /** Removes schedules the site's usage-collector installed. Returns what it removed. */
6
8
  removeLegacy(): Promise<string[]>;
7
9
  /** Writes the schedule from the templates and enables it. */
package/dist/scheduler.js CHANGED
@@ -2,7 +2,6 @@ import { execFile } from 'node:child_process';
2
2
  import { readdir, readFile, rm, copyFile, mkdir, writeFile, access } from 'node:fs/promises';
3
3
  import { basename, join } from 'node:path';
4
4
  import { promisify } from 'node:util';
5
- import { UsageError } from './context.js';
6
5
  const execFileAsync = promisify(execFile);
7
6
  const LEGACY_SCRIPT = '.local/share/usage-collector/collector.mjs';
8
7
  /**
@@ -38,17 +37,19 @@ async function requireManager(ctl) {
38
37
  await ctl('systemctl', ['--user', 'show-environment']);
39
38
  }
40
39
  catch {
41
- throw new UsageError('cannot reach the systemd user manager (systemctl --user failed). Run this from a login session, or enable lingering with `loginctl enable-linger $USER`, then run install again. Nothing was changed.');
40
+ throw new Error('cannot reach the systemd user manager (systemctl --user failed). Run this from a login session, or enable lingering with `loginctl enable-linger $USER`, then run install again. Nothing was changed.');
42
41
  }
43
42
  }
44
- function systemd(paths, templatesDir, ctl) {
43
+ function systemd(paths, templatesDir, ctl, xdg) {
45
44
  const user = ['--user'];
46
45
  const legacyFiles = ['usage-collector.service', 'usage-collector.timer'].map((f) => join(paths.systemdDir, f));
46
+ const findLegacy = async () => (await Promise.all(legacyFiles.map(async (f) => ((await exists(f)) ? f : null)))).filter((f) => f !== null);
47
47
  return {
48
48
  describe: 'systemd user timer (hourly). Log: journalctl --user -u big-spender',
49
49
  check: () => requireManager(ctl),
50
+ findLegacy,
50
51
  async removeLegacy() {
51
- const present = (await Promise.all(legacyFiles.map(async (f) => ((await exists(f)) ? f : null)))).filter((f) => f !== null);
52
+ const present = await findLegacy();
52
53
  await ctl('systemctl', [...user, 'disable', '--now', 'usage-collector.timer'], {
53
54
  tolerate: true
54
55
  });
@@ -63,7 +64,12 @@ function systemd(paths, templatesDir, ctl) {
63
64
  },
64
65
  async install(node) {
65
66
  await mkdir(paths.systemdDir, { recursive: true });
66
- await writeFile(join(paths.systemdDir, 'big-spender.service'), await render(templatesDir, 'big-spender.service', { __NODE__: node, __HOME__: paths.home }));
67
+ await writeFile(join(paths.systemdDir, 'big-spender.service'), await render(templatesDir, 'big-spender.service', {
68
+ __NODE__: node,
69
+ __HOME__: paths.home,
70
+ __ENV_FILE__: paths.envFile,
71
+ '__ENVIRONMENT__\n': xdg.map(([k, v]) => `Environment="${k}=${v}"\n`).join('')
72
+ }));
67
73
  await copyFile(join(templatesDir, 'big-spender.timer'), join(paths.systemdDir, 'big-spender.timer'));
68
74
  await ctl('systemctl', [...user, 'daemon-reload']);
69
75
  await ctl('systemctl', [...user, 'enable', '--now', 'big-spender.timer']);
@@ -81,35 +87,46 @@ function systemd(paths, templatesDir, ctl) {
81
87
  }
82
88
  };
83
89
  }
84
- function launchd(paths, templatesDir, ctl) {
90
+ function launchd(paths, templatesDir, ctl, xdg) {
85
91
  const label = 'local.big-spender';
86
92
  const plist = join(paths.launchAgentsDir, `${label}.plist`);
87
93
  const domain = `gui/${process.getuid?.() ?? 0}`;
88
94
  const bootout = (name) => ctl('launchctl', ['bootout', `${domain}/${name}`], { tolerate: true });
95
+ const findLegacy = async () => {
96
+ const found = [];
97
+ const names = await readdir(paths.launchAgentsDir).catch(() => []);
98
+ for (const name of names.filter((n) => n.endsWith('.usage-collector.plist'))) {
99
+ const file = join(paths.launchAgentsDir, name);
100
+ const isOurs = name === 'local.usage-collector.plist' ||
101
+ (await readFile(file, 'utf8').catch(() => '')).includes(LEGACY_SCRIPT);
102
+ if (isOurs)
103
+ found.push(file);
104
+ }
105
+ return found;
106
+ };
89
107
  return {
90
108
  check: async () => { },
91
109
  describe: `launchd agent (hourly + at login). Log: ${join(paths.logsDir, 'big-spender.log')}`,
110
+ findLegacy,
92
111
  async removeLegacy() {
93
- const removed = [];
94
- const names = await readdir(paths.launchAgentsDir).catch(() => []);
95
- for (const name of names.filter((n) => n.endsWith('.usage-collector.plist'))) {
96
- const file = join(paths.launchAgentsDir, name);
97
- const isOurs = name === 'local.usage-collector.plist' ||
98
- (await readFile(file, 'utf8').catch(() => '')).includes(LEGACY_SCRIPT);
99
- if (!isOurs)
100
- continue;
101
- await bootout(basename(name, '.plist'));
112
+ const found = await findLegacy();
113
+ for (const file of found) {
114
+ await bootout(basename(file, '.plist'));
102
115
  await rm(file, { force: true });
103
- removed.push(file);
104
116
  }
105
- return removed;
117
+ return found;
106
118
  },
107
119
  async install(node) {
108
120
  await mkdir(paths.launchAgentsDir, { recursive: true });
109
121
  await mkdir(paths.logsDir, { recursive: true });
110
122
  await writeFile(plist, await render(templatesDir, 'local.big-spender.plist', {
111
123
  __NODE__: node,
112
- __HOME__: paths.home
124
+ __HOME__: paths.home,
125
+ '__ENVIRONMENT__\n': xdg.length
126
+ ? `\t<key>EnvironmentVariables</key>\n\t<dict>\n${xdg
127
+ .map(([k, v]) => `\t\t<key>${k}</key>\n\t\t<string>${v}</string>\n`)
128
+ .join('')}\t</dict>\n`
129
+ : ''
113
130
  }));
114
131
  await bootout(label);
115
132
  await ctl('launchctl', ['bootstrap', domain, plist]);
@@ -124,9 +141,10 @@ function launchd(paths, templatesDir, ctl) {
124
141
  };
125
142
  }
126
143
  export function pickScheduler(env, platform, paths, templatesDir, ctl = makeCtl(env)) {
144
+ const xdg = ['XDG_CONFIG_HOME', 'XDG_CACHE_HOME'].flatMap((k) => env[k] ? [[k, env[k]]] : []);
127
145
  const table = {
128
- linux: () => systemd(paths, templatesDir, ctl),
129
- darwin: () => launchd(paths, templatesDir, ctl)
146
+ linux: () => systemd(paths, templatesDir, ctl, xdg),
147
+ darwin: () => launchd(paths, templatesDir, ctl, xdg)
130
148
  };
131
149
  const make = table[platform] ?? (env.BIG_SPENDER_SCHEDULER === 'none' ? table.linux : undefined);
132
150
  if (!make)
package/dist/schema.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { z } from 'zod';
2
+ export declare const EARLIEST_DATE = "2020-01-01T00:00:00Z";
3
+ export declare const MAX_ROWS = 50000;
2
4
  export declare const DEVICE_ID: RegExp;
3
5
  export declare const PROVIDERS: readonly ['claude', 'codex'];
4
- export declare const RANGES: readonly ['7d', '30d', '90d'];
6
+ export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
5
7
  export declare const usageRowSchema: z.ZodObject<{
6
8
  hour: z.ZodISODateTime;
7
9
  granularity: z.ZodOptional<z.ZodEnum<{
package/dist/schema.js CHANGED
@@ -4,11 +4,18 @@ import { z } from 'zod';
4
4
  // model names, timestamps and the device id can be stored or served.
5
5
  const tokens = z.number().int().nonnegative().max(1e15);
6
6
  const usd = z.number().nonnegative().max(1e9);
7
- const isoDate = z.iso.datetime({ offset: true });
7
+ // No AI coding agent usage predates 2020. The floor also bounds the all-time range: it is
8
+ // bucketed by week from the oldest date, so year 0 would mean 100,000+ points per series.
9
+ export const EARLIEST_DATE = '2020-01-01T00:00:00Z';
10
+ const isoDate = z.iso
11
+ .datetime({ offset: true })
12
+ .refine((s) => Date.parse(s) >= Date.parse(EARLIEST_DATE), `must be ${EARLIEST_DATE} or later`);
13
+ export const MAX_ROWS = 50_000;
8
14
  export const DEVICE_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
9
15
  export const PROVIDERS = ['claude', 'codex'];
10
- // Public ranges. All are day-granular: an hourly view would show when each machine is in use.
11
- export const RANGES = ['7d', '30d', '90d'];
16
+ // Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
17
+ // than a day: an hourly view would show when each machine is in use.
18
+ export const RANGES = ['7d', '30d', '90d', 'all'];
12
19
  export const usageRowSchema = z.strictObject({
13
20
  hour: isoDate,
14
21
  granularity: z.enum(['hour', 'day']).optional(),
@@ -41,7 +48,7 @@ export const usageSnapshotSchema = z.strictObject({
41
48
  .string()
42
49
  .max(80)
43
50
  .regex(/^[A-Za-z0-9@._:/-]+$/),
44
- hourly: z.array(usageRowSchema).max(50_000),
51
+ hourly: z.array(usageRowSchema).max(MAX_ROWS),
45
52
  sessionsTotal: z.number().int().nonnegative(),
46
53
  // Distinct sessions per range, counted on the device (session ids are never sent).
47
54
  sessionCounts: z
@@ -2,7 +2,7 @@ import type { DeviceConfig } from '../devices.ts';
2
2
  import { type UsageSummary } from '../summary.ts';
3
3
  export { DEVICE_ID, PROVIDERS, RANGES, usageRowSchema, usageSnapshotSchema, type UsageProvider, type UsageRange, type UsageRow, type UsageSnapshot } from '../schema.ts';
4
4
  export { OTHER, PALETTE, resolveDevices, type DeviceConfig, type DeviceInfo } from '../devices.ts';
5
- export { summarize, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
5
+ export { summarize, type Bucket, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
6
6
  export type BigSpenderOptions = {
7
7
  /** Directory for the per-device snapshot files. Use a persistent volume. */
8
8
  dataDir: string;
package/dist/store.d.ts CHANGED
@@ -2,11 +2,6 @@ import { type UsageSnapshot } from './schema.ts';
2
2
  export type SaveResult = 'stored' | 'stale';
3
3
  export type SnapshotStore = {
4
4
  list(): Promise<UsageSnapshot[]>;
5
- /**
6
- * Overwrites the device's snapshot. A snapshot older than the stored one is ignored, so
7
- * retries and duplicate posts are harmless.
8
- */
9
5
  save(snapshot: UsageSnapshot): Promise<SaveResult>;
10
6
  };
11
- /** Latest snapshot per device, one JSON file each, in `dir`. Put it on a persistent volume. */
12
7
  export declare function fileStore(dir: string): SnapshotStore;
package/dist/store.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
+ import { mergeSnapshots } from './history.js';
3
4
  import { DEVICE_ID, usageSnapshotSchema } from './schema.js';
4
5
  async function loadFromDisk(dir) {
5
6
  const out = new Map();
@@ -27,28 +28,41 @@ async function loadFromDisk(dir) {
27
28
  }
28
29
  return out;
29
30
  }
30
- /** Latest snapshot per device, one JSON file each, in `dir`. Put it on a persistent volume. */
31
31
  export function fileStore(dir) {
32
32
  const root = resolve(dir);
33
33
  let loading = null;
34
34
  const snapshots = () => (loading ??= loadFromDisk(root));
35
+ let previousSave = Promise.resolve();
35
36
  return {
36
37
  async list() {
37
38
  return [...(await snapshots()).values()];
38
39
  },
39
- async save(snap) {
40
- const all = await snapshots();
41
- const current = all.get(snap.deviceId);
42
- if (current && Date.parse(current.generatedAt) > Date.parse(snap.generatedAt)) {
43
- return 'stale';
44
- }
45
- await mkdir(root, { recursive: true });
46
- const file = join(root, `${snap.deviceId}.json`);
47
- const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
48
- await writeFile(tmp, JSON.stringify(snap));
49
- await rename(tmp, file);
50
- all.set(snap.deviceId, snap);
51
- return 'stored';
40
+ save(snap) {
41
+ const run = previousSave.then(() => save(snap));
42
+ previousSave = run.catch(() => { });
43
+ return run;
52
44
  }
53
45
  };
46
+ async function save(snap) {
47
+ const all = await snapshots();
48
+ const current = all.get(snap.deviceId);
49
+ if (current && Date.parse(current.generatedAt) > Date.parse(snap.generatedAt)) {
50
+ return 'stale';
51
+ }
52
+ const { snapshot, droppedDays } = mergeSnapshots(current, snap);
53
+ // loadFromDisk skips an invalid file, which would lose the whole history.
54
+ if (!usageSnapshotSchema.safeParse(snapshot).success) {
55
+ throw new Error(`${snap.deviceId}: merged history is invalid, the stored file is kept`);
56
+ }
57
+ if (droppedDays > 0) {
58
+ console.warn(`[big-spender] ${snap.deviceId}: history is full, dropped the oldest ${droppedDays} day(s)`);
59
+ }
60
+ await mkdir(root, { recursive: true });
61
+ const file = join(root, `${snap.deviceId}.json`);
62
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
63
+ await writeFile(tmp, JSON.stringify(snapshot));
64
+ await rename(tmp, file);
65
+ all.set(snap.deviceId, snapshot);
66
+ return 'stored';
67
+ }
54
68
  }
package/dist/summary.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { UsageProvider, UsageRange, UsageSnapshot } from './schema.ts';
2
2
  import { type DeviceConfig } from './devices.ts';
3
+ export type Bucket = 'day' | 'week';
3
4
  export type CostByType = {
4
5
  input: number;
5
6
  cacheRead: number;
@@ -29,8 +30,9 @@ export type ProviderLine = {
29
30
  tokens: number;
30
31
  /** Share of the range's processed tokens. */
31
32
  tokenShare: number;
32
- sessions: number;
33
- /** Cost and tokens per UTC day, aligned with the range's `series`. */
33
+ /** Distinct sessions; null for `all`, which collectors send no count for. */
34
+ sessions: number | null;
35
+ /** Cost and tokens per point, aligned with the range's `series`. */
34
36
  series: {
35
37
  cost: number[];
36
38
  tokens: number[];
@@ -53,8 +55,14 @@ export type RangeSummary = {
53
55
  range: UsageRange;
54
56
  from: string;
55
57
  to: string;
58
+ /** What one point of every series covers: a UTC day, or an ISO week starting Monday UTC. */
59
+ bucket: Bucket;
56
60
  totalCost: number;
57
- sessions: number;
61
+ /**
62
+ * Distinct sessions. Null for `all`: session ids never leave the device, and collectors
63
+ * only count sessions for 7d, 30d and 90d.
64
+ */
65
+ sessions: number | null;
58
66
  tokens: {
59
67
  processed: number;
60
68
  cachedInput: number;
@@ -76,12 +84,16 @@ export type UsageSummary = {
76
84
  type Window = {
77
85
  from: number;
78
86
  to: number;
87
+ step: number;
79
88
  points: number;
89
+ bucket: Bucket;
80
90
  };
81
91
  /**
82
- * Range windows end at the end of the current UTC day and are bucketed by day. Never by hour:
83
- * an hourly breakdown per device would show when each machine is in use.
92
+ * Range windows end at the end of the current UTC day. 7d, 30d and 90d are bucketed by day;
93
+ * `all` starts on the Monday on or before the oldest stored usage and is bucketed by ISO week,
94
+ * so its last point may be a partial week. Never by hour: an hourly breakdown per device would
95
+ * show when each machine is in use.
84
96
  */
85
- export declare function rangeWindow(range: UsageRange, now: number): Window;
97
+ export declare function rangeWindow(range: UsageRange, now: number, snapshots: UsageSnapshot[]): Window;
86
98
  export declare function summarize(snapshots: UsageSnapshot[], now: number, config: DeviceConfig): UsageSummary;
87
99
  export {};
package/dist/summary.js CHANGED
@@ -1,20 +1,36 @@
1
1
  import { resolveDevices } from './devices.js';
2
2
  const DAY_MS = 86_400_000;
3
+ const WEEK_MS = 7 * DAY_MS;
4
+ // 1970-01-01 was a Thursday, so ISO weeks (Monday 00:00 UTC) start 4 days after a multiple of WEEK_MS.
5
+ const MONDAY_OFFSET_MS = 4 * DAY_MS;
6
+ const mondayOnOrBefore = (t) => Math.floor((t - MONDAY_OFFSET_MS) / WEEK_MS) * WEEK_MS + MONDAY_OFFSET_MS;
3
7
  /**
4
- * Range windows end at the end of the current UTC day and are bucketed by day. Never by hour:
5
- * an hourly breakdown per device would show when each machine is in use.
8
+ * Range windows end at the end of the current UTC day. 7d, 30d and 90d are bucketed by day;
9
+ * `all` starts on the Monday on or before the oldest stored usage and is bucketed by ISO week,
10
+ * so its last point may be a partial week. Never by hour: an hourly breakdown per device would
11
+ * show when each machine is in use.
6
12
  */
7
- export function rangeWindow(range, now) {
8
- const days = range === '7d' ? 7 : range === '30d' ? 30 : 90;
13
+ export function rangeWindow(range, now, snapshots) {
9
14
  const to = Math.floor(now / DAY_MS) * DAY_MS + DAY_MS;
10
- return { from: to - days * DAY_MS, to, points: days };
15
+ if (range !== 'all') {
16
+ const days = range === '7d' ? 7 : range === '30d' ? 30 : 90;
17
+ return { from: to - days * DAY_MS, to, step: DAY_MS, points: days, bucket: 'day' };
18
+ }
19
+ let earliest = to - DAY_MS;
20
+ for (const snap of snapshots) {
21
+ earliest = Math.min(earliest, Date.parse(snap.coverageStart));
22
+ for (const r of snap.hourly)
23
+ earliest = Math.min(earliest, Date.parse(r.hour));
24
+ }
25
+ const from = mondayOnOrBefore(earliest);
26
+ return { from, to, step: WEEK_MS, points: Math.ceil((to - from) / WEEK_MS), bucket: 'week' };
11
27
  }
12
28
  const rowCost = (r) => r.costUsd.input + r.costUsd.cacheRead + r.costUsd.cacheWrite + r.costUsd.output;
13
29
  const rowTokens = (r) => r.inputTokens + r.cacheReadTokens + r.cacheWrite5mTokens + r.cacheWrite1hTokens + r.outputTokens;
14
30
  function summarizeRange(range, snapshots, now, resolved) {
15
- const w = rangeWindow(range, now);
31
+ const w = rangeWindow(range, now, snapshots);
16
32
  const series = Array.from({ length: w.points }, (_, i) => ({
17
- start: new Date(w.from + i * DAY_MS).toISOString(),
33
+ start: new Date(w.from + i * w.step).toISOString(),
18
34
  cost: 0,
19
35
  tokens: 0
20
36
  }));
@@ -24,6 +40,7 @@ function summarizeRange(range, snapshots, now, resolved) {
24
40
  const providers = new Map();
25
41
  const devices = new Map();
26
42
  let cacheSavings = 0;
43
+ const countsSessions = range !== 'all';
27
44
  let sessions = 0;
28
45
  const provider = (id) => {
29
46
  let p = providers.get(id);
@@ -34,7 +51,7 @@ function summarizeRange(range, snapshots, now, resolved) {
34
51
  share: 0,
35
52
  tokens: 0,
36
53
  tokenShare: 0,
37
- sessions: 0,
54
+ sessions: countsSessions ? 0 : null,
38
55
  series: {
39
56
  cost: new Array(w.points).fill(0),
40
57
  tokens: new Array(w.points).fill(0)
@@ -56,7 +73,7 @@ function summarizeRange(range, snapshots, now, resolved) {
56
73
  };
57
74
  devices.set(name, device);
58
75
  const active = new Set();
59
- const counts = snap.sessionCounts?.[range];
76
+ const counts = range === 'all' ? undefined : snap.sessionCounts?.[range];
60
77
  for (const r of snap.hourly) {
61
78
  const start = Date.parse(r.hour);
62
79
  if (start < w.from || start >= w.to)
@@ -65,7 +82,7 @@ function summarizeRange(range, snapshots, now, resolved) {
65
82
  const tok = rowTokens(r);
66
83
  if (tok > 0)
67
84
  active.add(r.provider);
68
- const idx = Math.floor((start - w.from) / DAY_MS);
85
+ const idx = Math.floor((start - w.from) / w.step);
69
86
  device.cost += cost;
70
87
  device.series[idx] += cost;
71
88
  series[idx].cost += cost;
@@ -120,13 +137,14 @@ function summarizeRange(range, snapshots, now, resolved) {
120
137
  range,
121
138
  from: new Date(w.from).toISOString(),
122
139
  to: new Date(w.to).toISOString(),
140
+ bucket: w.bucket,
123
141
  totalCost,
124
- sessions,
142
+ sessions: countsSessions ? sessions : null,
125
143
  tokens,
126
144
  cacheSavings,
127
145
  costByType,
128
146
  providers: [...providers.values()]
129
- .filter((p) => p.cost > 0 || p.tokens > 0 || p.sessions > 0)
147
+ .filter((p) => p.cost > 0 || p.tokens > 0 || (p.sessions ?? 0) > 0)
130
148
  .map((p) => ({ ...p, share: share(p.cost), tokenShare: tokenShare(p.tokens) }))
131
149
  .sort(byCost),
132
150
  models: [...models.values()]
@@ -144,7 +162,8 @@ export function summarize(snapshots, now, config) {
144
162
  ranges: {
145
163
  '7d': summarizeRange('7d', snapshots, now, resolved),
146
164
  '30d': summarizeRange('30d', snapshots, now, resolved),
147
- '90d': summarizeRange('90d', snapshots, now, resolved)
165
+ '90d': summarizeRange('90d', snapshots, now, resolved),
166
+ all: summarizeRange('all', snapshots, now, resolved)
148
167
  }
149
168
  };
150
169
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "big-spender",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Track what your AI coding agents would cost at API prices, across all your machines.",
5
5
  "keywords": [
6
6
  "ai",
@@ -53,8 +53,14 @@
53
53
  "zod": "^4.6.7"
54
54
  },
55
55
  "devDependencies": {
56
+ "@semantic-release/commit-analyzer": "^13.0.1",
57
+ "@semantic-release/github": "^12.0.11",
58
+ "@semantic-release/npm": "^13.2.0",
59
+ "@semantic-release/release-notes-generator": "^14.1.1",
56
60
  "@types/node": "^22.20.5",
61
+ "conventional-changelog-conventionalcommits": "^9.3.1",
57
62
  "prettier": "^3.10.1",
63
+ "semantic-release": "^25.0.9",
58
64
  "typescript": "^7.0.2"
59
65
  }
60
66
  }
@@ -7,7 +7,8 @@ After=network-online.target
7
7
  [Service]
8
8
  Type=oneshot
9
9
  # Also read by the collector itself; listed here so `systemctl --user show` reflects it.
10
- EnvironmentFile=%h/.config/big-spender/env
10
+ EnvironmentFile=__ENV_FILE__
11
+ __ENVIRONMENT__
11
12
  ExecStart=__NODE__ %h/.local/share/big-spender/collector.mjs
12
13
  Nice=10
13
14
  IOSchedulingClass=idle
@@ -2,8 +2,8 @@
2
2
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
3
  <!--
4
4
  ~/Library/LaunchAgents/local.big-spender.plist
5
- `big-spender install` replaces __HOME__ and __NODE__. Secrets live in ~/.config/big-spender/env
6
- (chmod 600), not in this file.
5
+ `big-spender install` replaces __HOME__ and __NODE__. Secrets live in the env file
6
+ (~/.config/big-spender/env by default, chmod 600), not in this file.
7
7
  -->
8
8
  <plist version="1.0">
9
9
  <dict>
@@ -14,6 +14,7 @@
14
14
  <string>__NODE__</string>
15
15
  <string>__HOME__/.local/share/big-spender/collector.mjs</string>
16
16
  </array>
17
+ __ENVIRONMENT__
17
18
  <!--
18
19
  Wall-clock schedule, not StartInterval: StartInterval counts only awake time, so a laptop
19
20
  that sleeps with the lid closed can go hours without a run. A calendar slot missed during