big-spender 0.11.0 → 0.13.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
@@ -149,13 +149,14 @@ Cursor.
149
149
 
150
150
  `big-spender serve` is a small `node:http` server:
151
151
 
152
- | Route | What it does |
153
- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
154
- | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
155
- | `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`. |
156
- | `GET /api/usage/limits` | Subscription limit hits per provider and window over the last 90 UTC days, per day, same cache header. See [Usage limits](#usage-limits). |
157
- | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models, limit hits. No JavaScript, no external assets, light and dark. |
158
- | `GET /healthz` | `ok`, for load balancers and Docker. |
152
+ | Route | What it does |
153
+ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
154
+ | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
155
+ | `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`. |
156
+ | `GET /api/usage/limits` | Subscription limit hits per provider and window over the last 90 UTC days, per day, same cache header. See [Usage limits](#usage-limits). |
157
+ | `GET /api/usage/limits/hits` | Admin only: bearer `BIG_SPENDER_ADMIN_TOKEN`. Every recorded limit hit with its exact time and the device ids that saw it, earliest first. `cache-control: no-store`. See [Usage limits](#usage-limits). |
158
+ | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models, limit hits. No JavaScript, no external assets, light and dark. |
159
+ | `GET /healthz` | `ok`, for load balancers and Docker. |
159
160
 
160
161
  Configuration comes from flags or environment variables (flags win):
161
162
 
@@ -166,6 +167,7 @@ Configuration comes from flags or environment variables (flags win):
166
167
  | `--data` | `BIG_SPENDER_DATA_DIR` | `./data` (`/data` in the Docker image) |
167
168
  | `--devices` | `BIG_SPENDER_DEVICES_FILE` | none: `{ "devices": {}, "unknownDevices": "by-id" }` |
168
169
  | | `BIG_SPENDER_INGEST_TOKEN` | none: ingest is off and answers `503` |
170
+ | | `BIG_SPENDER_ADMIN_TOKEN` | none: the hits endpoint is off and answers `503` |
169
171
 
170
172
  The data directory holds one `<device>.json` file per device, written atomically. Put it on a
171
173
  persistent volume. Each snapshot is merged into the device's stored history. A day the snapshot
@@ -232,7 +234,7 @@ export const GET = async ({ setHeaders }) => {
232
234
  Hono is the same shape (`app.post('/api/usage/ingest', (c) => bs.ingest(c.req.raw))`), and so is a
233
235
  Next.js route handler (`export const POST = (request: Request) => bs.ingest(request)`).
234
236
 
235
- `createBigSpender({ dataDir, ingestToken, devices })` returns:
237
+ `createBigSpender({ dataDir, ingestToken, adminToken?, devices })` returns:
236
238
 
237
239
  - `ingest(request)`: handles a collector's `POST` and returns a `Response` (`503` when
238
240
  `ingestToken` is missing or empty, `401`, `413`, `415`, `422`, or `200` with
@@ -240,29 +242,41 @@ Next.js route handler (`export const POST = (request: Request) => bs.ingest(requ
240
242
  - `summary(now?)`: the merged totals for every range. The result is cached for five minutes and
241
243
  recomputed right after an ingest.
242
244
  - `limits(now?)`: the [usage limit](#usage-limits) summary, cached the same way.
245
+ - `limitHits(request)`: the admin-only hit list as a `Response`. It answers `503` when `adminToken` is missing, empty or equal to `ingestToken`, `401` for a wrong bearer token, and `200` with `cache-control: no-store`. It is computed fresh on each call.
243
246
 
244
- The module also exports `summarize(snapshots, now, config)`, `summarizeLimits(snapshots, now)`, the
247
+ The module also exports `summarize(snapshots, now, config)`, `summarizeLimits(snapshots, now)`, `limitHits(snapshots, now)`, the
245
248
  snapshot schema (`usageSnapshotSchema`, `limitWindowSchema`, `MAX_LIMIT_WINDOWS`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
246
249
  own storage or charts.
247
250
 
248
251
  ## Usage limits
249
252
 
250
253
  Besides cost, the collector records when you run out of your Claude and Codex subscription
251
- allowance, so you can judge whether a plan fits how you work. It reads only what the agents already
252
- write to their local logs. It reads no credentials and makes no new network calls.
254
+ allowance, so you can judge whether a plan fits how you work. It reads what the agents write to
255
+ their local logs, and it polls their usage endpoints (see [Polling](#polling-usage-endpoints)).
253
256
 
254
257
  - **Claude Code.** A refused request is logged as an `assistant` line with `error: "rate_limit"`
255
258
  and a `quotaLimits` object that names the window (`five_hour`, `seven_day`, a model-specific
256
259
  weekly window such as `seven_day_opus`) and when it resets. Retries repeat the line, so one
257
- blocked window becomes one record. Claude Code logs nothing when a request is allowed, so
258
- utilisation below 100% is unknown for Claude.
260
+ blocked window becomes one record. Claude Code logs nothing when a request is allowed, so the logs
261
+ alone say nothing about utilisation below 100%; polling fills that in.
259
262
  - **Codex.** `token_count` events carry `rate_limits` with the used percentage and reset time of the
260
- 5-hour window (`five_hour`, 300 minutes) and the weekly window (`seven_day`, 10080 minutes). Codex
261
- is the only source of utilisation below 100%. A window counts as hit when its share reaches 100%.
263
+ 5-hour window (`five_hour`, 300 minutes) and the weekly window (`seven_day`, 10080 minutes). A
264
+ window counts as hit when its share reaches 100%. A refused turn is logged too, but names no
265
+ window and no reset. It starts the lockout of each Codex window seen full (by a poll or any log
266
+ line) that was open at that moment, so the lockout begins at the first logged refusal instead of
267
+ at the next poll. When no open window was seen full, a lockout that began and
268
+ ended between two runs can still be placed by elimination. Usage in a window instance only rises
269
+ until it resets, so a poll that read an instance below 100% after the refusal proves it was not
270
+ the one blocking. This needs a successful poll in the same run that read both Codex windows, and
271
+ every limit it reports must have an instance on file that was open at the refusal. If exactly one open window is then left,
272
+ it gets the hit at the refusal. The gap that remains is a refusal whose window no reading ever
273
+ saw, one where several windows stay possible, and any refusal read while polling is off or
274
+ failing. These change nothing.
262
275
 
263
276
  A record is one window instance, identified by provider, window name and reset time rounded down
264
277
  to the minute. Reports whose resets are at most two minutes apart are the same window, because one
265
- window's reported reset can drift by a few seconds. It holds the peak percentage seen and the time of the first refusal. Limits belong
278
+ window's reported reset can drift by a few seconds. A push sends at most the 5,000 newest records,
279
+ the most the server accepts. It holds the peak percentage seen and the time of the first refusal. Limits belong
266
280
  to the account, not the machine, so merging keeps the highest peak and the earliest refusal, and
267
281
  two machines that report the same window count once. Records are kept for 90 days on the collector and up to 5,000 windows on the
268
282
  server, like day rows.
@@ -277,9 +291,34 @@ finer than a UTC day, no device names, no report times. It is separate from `/ap
277
291
  shape did not change. `big-spender status` also lists the limits hit in the last 7 days, to the
278
292
  minute, because that output never leaves the machine.
279
293
 
280
- Polling the Anthropic or OpenAI usage endpoints would show utilisation for Claude too, but it needs
281
- your OAuth credentials, so it is not done. The record shape already has room for it: a polled
282
- percentage is just another peak for the same window.
294
+ `GET /api/usage/limits/hits` is the admin view. It needs `Authorization: Bearer <BIG_SPENDER_ADMIN_TOKEN>`
295
+ and returns every recorded hit with its exact `hitAt`, the window's reset and the devices that saw it,
296
+ earliest first. The public endpoint stays day-level with no devices. The admin token must differ from
297
+ the ingest token, because every collector machine holds that one. A hit found by polling carries the
298
+ poll time, not the exact refusal time. Two devices that show the same `hitAt` to the millisecond read
299
+ the same log line.
300
+
301
+ ### Polling usage endpoints
302
+
303
+ Logs only show a limit when a request is refused, which hides how much of a window you leave
304
+ unused. So each run also asks Anthropic and OpenAI how full your windows are right now, the same
305
+ numbers `/usage` in Claude Code and Codex show. Claude is polled at `api.anthropic.com` and Codex at
306
+ `chatgpt.com`, with the login the agent already keeps: `~/.claude/.credentials.json`
307
+ (`$CLAUDE_CONFIG_DIR` if set) and `~/.codex/auth.json` (`$CODEX_HOME` if set). The collector opens
308
+ those files read-only, never refreshes them and sends the token only to that provider. If a token
309
+ has expired, that provider is skipped with one warning until you run the agent again. A missing
310
+ file means that provider is not polled, without a warning. A failed poll never fails the run.
311
+
312
+ Each reading is a peak for the same window record the logs feed. Windows are named `five_hour` and
313
+ `seven_day`, plus one `seven_day_<model>` per model-specific weekly (`seven_day_fable`,
314
+ `seven_day_opus`). Codex's extra limits become `<window>_<limit name>`. Only the window name, reset
315
+ time and percentage are stored or sent.
316
+
317
+ Claude Code logs a refusal of Fable's weekly as `seven_day_overage_included` and labels it "Fable
318
+ limit". The endpoint reports the same limit as `seven_day_fable`, so the collector records those
319
+ refusals as `seven_day_fable`, and they join the polled readings in one record.
320
+
321
+ To turn polling off, set `BIG_SPENDER_POLL_LIMITS=off` in the env file.
283
322
 
284
323
  An older server rejects the unknown `limits` field with a 422. The collector and `push` then send
285
324
  the snapshot again without it and print a warning on each run, so usage keeps arriving. Upgrade the server to store
@@ -18,7 +18,8 @@
18
18
  // node collector.mjs --reset # forget local state and rescan everything
19
19
  //
20
20
  // Env: BIG_SPENDER_DEVICE_ID, BIG_SPENDER_INGEST_URL, BIG_SPENDER_INGEST_TOKEN and optionally
21
- // BIG_SPENDER_CURSOR_API_KEY and BIG_SPENDER_EXPERIMENTAL (see templates/env.example).
21
+ // BIG_SPENDER_CURSOR_API_KEY, BIG_SPENDER_EXPERIMENTAL and BIG_SPENDER_POLL_LIMITS=off (see
22
+ // templates/env.example).
22
23
  // The older USAGE_* names are still read when the new one is unset.
23
24
 
24
25
  import { createHash } from 'node:crypto';
@@ -72,13 +73,14 @@ const ENV_FILE =
72
73
 
73
74
  const log = (...m) => console.error('[big-spender]', ...m);
74
75
 
75
- // The override exists for tests. It only points at this machine, so the Cursor API key and
76
- // access token can't be sent anywhere but Cursor.
77
- function cursorApiUrl(override) {
78
- if (!override) return 'https://api2.cursor.sh';
76
+ // The overrides exist for tests. They only point at this machine, so keys and tokens can't be
77
+ // sent anywhere but the service they belong to.
78
+ function localOverride(name, defaultUrl) {
79
+ const override = process.env[name];
80
+ if (!override) return defaultUrl;
79
81
  const { hostname } = new URL(override);
80
82
  if (!['127.0.0.1', 'localhost', '[::1]'].includes(hostname)) {
81
- throw new Error('BIG_SPENDER_CURSOR_API_URL may only point at this machine');
83
+ throw new Error(`${name} may only point at this machine`);
82
84
  }
83
85
  return override.replace(/\/$/, '');
84
86
  }
@@ -151,6 +153,8 @@ async function acquireLock() {
151
153
  const FIX_CLAUDE_OUTPUT = 'claude-final-output';
152
154
  // Limit windows are read from log lines older versions skipped, so those logs are re-read once.
153
155
  const FIX_LIMITS = 'usage-limits';
156
+ // Codex refusals are read from the logs too, so those logs are re-read once.
157
+ const FIX_CODEX_REFUSALS = 'codex-refusals';
154
158
 
155
159
  /** @returns {Promise<State>} */
156
160
  async function loadState() {
@@ -160,7 +164,7 @@ async function loadState() {
160
164
  seen: {},
161
165
  buckets: {},
162
166
  limits: {},
163
- fixes: [FIX_CLAUDE_OUTPUT, FIX_LIMITS]
167
+ fixes: [FIX_CLAUDE_OUTPUT, FIX_LIMITS, FIX_CODEX_REFUSALS]
164
168
  };
165
169
  if (RESET) return empty;
166
170
  try {
@@ -178,6 +182,10 @@ async function loadState() {
178
182
  s.fixes.push(FIX_LIMITS);
179
183
  s.rescan = [...new Set([...(s.rescan ?? []), 'claude', 'codex'])];
180
184
  }
185
+ if (!s.fixes.includes(FIX_CODEX_REFUSALS)) {
186
+ s.fixes.push(FIX_CODEX_REFUSALS);
187
+ s.rescan = [...new Set([...(s.rescan ?? []), 'codex'])];
188
+ }
181
189
  return s;
182
190
  } catch {
183
191
  return empty;
@@ -253,23 +261,28 @@ const MINUTE_MS = 60_000;
253
261
  const RESET_SLACK_MS = 2 * MINUTE_MS;
254
262
  // Times outside this range are malformed (milliseconds read as seconds, say) and are skipped,
255
263
  // never thrown, so a bad limit line cannot stop the usage on the lines after it.
264
+ // The server rejects a push with more limit records than this (MAX_LIMIT_WINDOWS in src/schema.ts),
265
+ // and it keeps the newest, so a push sends the newest.
266
+ const MAX_LIMIT_WINDOWS = 5_000;
256
267
  const LIMIT_TIMES_FROM = Date.parse('2020-01-01T00:00:00Z');
257
268
  const LIMIT_TIMES_TO = Date.parse('2100-01-01T00:00:00Z');
258
269
  const plausibleTime = (ms) => ms >= LIMIT_TIMES_FROM && ms < LIMIT_TIMES_TO;
259
270
 
260
271
  /**
272
+ * Returns the window name and reset time the record ended up with, or nothing when it was rejected.
261
273
  * @param {State} state
262
274
  * @param {{ provider: string, window: string, resetsAtMs: number, percent: number, hitMs?: number }} w
263
275
  */
264
276
  function addLimit(state, w) {
277
+ const { window } = w;
265
278
  let resetsAtMs = Math.floor(w.resetsAtMs / MINUTE_MS) * MINUTE_MS;
266
- if (!plausibleTime(resetsAtMs) || !/^[a-z0-9_]{1,40}$/.test(w.window)) return;
279
+ if (!plausibleTime(resetsAtMs) || !/^[a-z0-9_]{1,40}$/.test(window)) return;
267
280
  if (w.hitMs !== undefined && !plausibleTime(w.hitMs)) return;
268
281
  state.limits ??= {};
269
282
  let prev;
270
283
  for (const [key, l] of Object.entries(state.limits)) {
271
284
  const gap = Math.abs(Date.parse(l.resetsAt) - resetsAtMs);
272
- if (l.provider !== w.provider || l.window !== w.window || gap > RESET_SLACK_MS) continue;
285
+ if (l.provider !== w.provider || l.window !== window || gap > RESET_SLACK_MS) continue;
273
286
  if (prev && gap >= Math.abs(Date.parse(prev[1].resetsAt) - resetsAtMs)) continue;
274
287
  prev = [key, l];
275
288
  }
@@ -279,15 +292,21 @@ function addLimit(state, w) {
279
292
  }
280
293
  const hits = [prev?.[1].hitAt && Date.parse(prev[1].hitAt), w.hitMs].filter(Number.isFinite);
281
294
  const percent = Math.min(100, Math.max(0, w.percent));
282
- state.limits[`${w.provider}|${w.window}|${resetsAtMs}`] = {
295
+ state.limits[`${w.provider}|${window}|${resetsAtMs}`] = {
283
296
  provider: w.provider,
284
- window: w.window,
297
+ window,
285
298
  resetsAt: new Date(resetsAtMs).toISOString(),
286
299
  peakPercent: Math.max(prev?.[1].peakPercent ?? 0, percent),
287
300
  ...(hits.length ? { hitAt: new Date(Math.min(...hits)).toISOString() } : {})
288
301
  };
302
+ return { window, resetsAtMs };
289
303
  }
290
304
 
305
+ // Claude Code logs Fable's weekly as seven_day_overage_included and labels it "Fable limit". The
306
+ // usage endpoint calls the same limit seven_day_fable, and the server merges pushes by name, so the
307
+ // name has to be right when the record is created or the limit would show as two rows.
308
+ const CLAUDE_LOG_WINDOWS = { seven_day_overage_included: 'seven_day_fable' };
309
+
291
310
  // Claude Code logs a refused request as a synthetic assistant line carrying quotaLimits.
292
311
  // One blocked window repeats on every retry; the key makes the repeats one record.
293
312
  function claudeLimit(state, o) {
@@ -295,12 +314,13 @@ function claudeLimit(state, o) {
295
314
  if (q?.status !== 'rejected' || typeof q.rateLimitType !== 'string') return;
296
315
  const ts = Date.parse(o.timestamp);
297
316
  if (!Number.isFinite(ts) || !(q.resetsAt > 0)) return;
317
+ const raw = q.rateLimitType
318
+ .toLowerCase()
319
+ .replace(/[^a-z0-9_]/g, '_')
320
+ .slice(0, 40);
298
321
  addLimit(state, {
299
322
  provider: 'claude',
300
- window: q.rateLimitType
301
- .toLowerCase()
302
- .replace(/[^a-z0-9_]/g, '_')
303
- .slice(0, 40),
323
+ window: CLAUDE_LOG_WINDOWS[raw] ?? raw,
304
324
  resetsAtMs: q.resetsAt * 1000,
305
325
  percent: 100,
306
326
  hitMs: ts
@@ -335,6 +355,265 @@ function codexLimits(state, o, rateLimits) {
335
355
  }
336
356
  }
337
357
 
358
+ // A window's length in ms from its name: a CODEX_WINDOW_NAMES base or `<N>m`, then an optional
359
+ // `_<suffix>` for an additional limit.
360
+ function codexWindowMs(window) {
361
+ for (const [minutes, base] of Object.entries(CODEX_WINDOW_NAMES)) {
362
+ if (window === base || window.startsWith(`${base}_`)) return Number(minutes) * MINUTE_MS;
363
+ }
364
+ const m = /^(\d+)m(_|$)/.exec(window);
365
+ return m ? Number(m[1]) * MINUTE_MS : NaN;
366
+ }
367
+
368
+ // A refused Codex turn names no window and no reset, so it starts the lockout of every window
369
+ // already seen full that was open at the time. With none seen full, it falls to elimination.
370
+ // Usage within an instance only rises until its reset, so this run's poll reading below 100%
371
+ // (taken after the refusal) proves the instance was not full at ts. That only settles it when
372
+ // the poll read both Codex windows, every limit it reports had an instance on file at ts, and
373
+ // exactly one is not ruled out. polled holds this run's Codex poll readings; it is empty when
374
+ // the poll was off or failed. Runs after the whole scan, once every log reading is on file.
375
+ function codexRefusal(state, ts, polled) {
376
+ const open = Object.values(state.limits ?? {}).filter((l) => {
377
+ const resetsAtMs = Date.parse(l.resetsAt);
378
+ return l.provider === 'codex' && ts > resetsAtMs - codexWindowMs(l.window) && ts <= resetsAtMs;
379
+ });
380
+ const full = open.filter((l) => l.peakPercent >= 100);
381
+ const readBelowFull = (l) =>
382
+ polled.some(
383
+ (r) =>
384
+ r.percent < 100 &&
385
+ r.window === l.window &&
386
+ Math.abs(r.resetsAtMs - Date.parse(l.resetsAt)) <= RESET_SLACK_MS
387
+ );
388
+ // A window the poll reports as null (not in use now) may have blocked and reset since, so
389
+ // elimination needs a reading of both Codex windows.
390
+ const polledNames = new Set(polled.map((r) => r.window));
391
+ const accountedFor =
392
+ Object.values(CODEX_WINDOW_NAMES).every((n) => polledNames.has(n)) &&
393
+ [...polledNames].every((n) => open.some((l) => l.window === n));
394
+ const left = accountedFor ? open.filter((l) => !readBelowFull(l)) : [];
395
+ const blockers = full.length ? full : left.length === 1 ? left : [];
396
+ for (const l of blockers) {
397
+ addLimit(state, {
398
+ provider: 'codex',
399
+ window: l.window,
400
+ resetsAtMs: Date.parse(l.resetsAt),
401
+ percent: 100,
402
+ hitMs: ts
403
+ });
404
+ }
405
+ }
406
+
407
+ const isCodexRefusal = (p) => {
408
+ const err = p.type === 'task_complete' ? p.error : p.type === 'error' ? p : null;
409
+ if (!err || typeof err !== 'object') return false;
410
+ return (
411
+ err.codex_error_info === 'usage_limit_exceeded' ||
412
+ (typeof err.message === 'string' && /usage limit/i.test(err.message))
413
+ );
414
+ };
415
+
416
+ // ---------------------------------------------------------------------------
417
+ // Limit polling
418
+ //
419
+ // Logs only show a limit when a request is refused. Each provider's own usage endpoint also
420
+ // reports how full every window is right now, so polling it sees the unused part too. The login
421
+ // files the agents keep are opened read-only and never refreshed; the token goes to the
422
+ // provider's own host and nowhere else.
423
+
424
+ const slug = (s) =>
425
+ s
426
+ .toLowerCase()
427
+ .replace(/[^a-z0-9]+/g, '_')
428
+ .replace(/^_+|_+$/g, '');
429
+
430
+ const claudeResetMs = (resetsAt) => (typeof resetsAt === 'string' ? Date.parse(resetsAt) : NaN);
431
+
432
+ function claudeWindows(body) {
433
+ const out = [];
434
+ const add = (window, percent, resetsAtMs) => {
435
+ if (Number.isFinite(percent) && Number.isFinite(resetsAtMs)) {
436
+ out.push({ window: window.slice(0, 40), percent, resetsAtMs });
437
+ }
438
+ };
439
+ for (const [key, w] of Object.entries(body)) {
440
+ if (/^(five_hour|seven_day)(_[a-z0-9_]+)?$/.test(key) && w && typeof w === 'object') {
441
+ add(key, w.utilization, claudeResetMs(w.resets_at));
442
+ }
443
+ }
444
+ for (const l of Array.isArray(body.limits) ? body.limits : []) {
445
+ const model = l?.scope?.model?.display_name;
446
+ if (l?.kind === 'weekly_scoped' && typeof model === 'string' && slug(model)) {
447
+ add(`seven_day_${slug(model)}`, l.percent, claudeResetMs(l.resets_at));
448
+ }
449
+ }
450
+ return out;
451
+ }
452
+
453
+ const CODEX_SLOTS = ['primary_window', 'secondary_window'];
454
+
455
+ function codexWindows(body, nowMs) {
456
+ const out = [];
457
+ const add = (rateLimit, suffix) => {
458
+ for (const slot of CODEX_SLOTS) {
459
+ const w = rateLimit?.[slot];
460
+ if (!w || typeof w.used_percent !== 'number') continue;
461
+ const minutes = w.limit_window_seconds / 60;
462
+ const resetsAtMs =
463
+ w.reset_at > 0 ? w.reset_at * 1000 : nowMs + Number(w.reset_after_seconds) * 1000;
464
+ if (!Number.isFinite(minutes) || !Number.isFinite(resetsAtMs)) continue;
465
+ const base = CODEX_WINDOW_NAMES[minutes] ?? `${minutes}m`;
466
+ out.push({
467
+ window: (suffix ? `${base}_${suffix}` : base).slice(0, 40),
468
+ percent: w.used_percent,
469
+ resetsAtMs
470
+ });
471
+ }
472
+ };
473
+ add(body.rate_limit, '');
474
+ for (const extra of Array.isArray(body.additional_rate_limits)
475
+ ? body.additional_rate_limits
476
+ : []) {
477
+ const name = typeof extra?.limit_name === 'string' ? slug(extra.limit_name) : '';
478
+ if (name) add(extra.rate_limit, name);
479
+ }
480
+ return out;
481
+ }
482
+
483
+ // The access token is a JWT; its payload says when it expires. One that can't be decoded is sent
484
+ // anyway and the endpoint decides.
485
+ function jwtExpiresMs(token) {
486
+ try {
487
+ const exp = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()).exp;
488
+ return typeof exp === 'number' ? exp * 1000 : NaN;
489
+ } catch {
490
+ return NaN;
491
+ }
492
+ }
493
+
494
+ // headers() returns the request headers, or a string saying why this provider is skipped.
495
+ const LIMIT_POLLERS = {
496
+ claude: {
497
+ credentialsPath: () =>
498
+ join(process.env.CLAUDE_CONFIG_DIR || join(HOME, '.claude'), '.credentials.json'),
499
+ url: 'https://api.anthropic.com/api/oauth/usage?skip_spend=1',
500
+ urlEnv: 'BIG_SPENDER_CLAUDE_USAGE_URL',
501
+ headers: (creds, nowMs) => {
502
+ const oauth = creds?.claudeAiOauth;
503
+ if (typeof oauth?.accessToken !== 'string' || !oauth.accessToken) {
504
+ return 'not signed in with a Claude subscription';
505
+ }
506
+ if (typeof oauth.expiresAt === 'number' && oauth.expiresAt <= nowMs) {
507
+ return 'the login token expired; run Claude Code once to refresh it';
508
+ }
509
+ return {
510
+ authorization: `Bearer ${oauth.accessToken}`,
511
+ 'anthropic-beta': 'oauth-2025-04-20',
512
+ 'user-agent': 'big-spender'
513
+ };
514
+ },
515
+ windows: claudeWindows
516
+ },
517
+ codex: {
518
+ credentialsPath: () => join(process.env.CODEX_HOME || join(HOME, '.codex'), 'auth.json'),
519
+ url: 'https://chatgpt.com/backend-api/wham/usage',
520
+ urlEnv: 'BIG_SPENDER_CODEX_USAGE_URL',
521
+ headers: (creds, nowMs) => {
522
+ const { access_token: token, account_id: accountId } = creds?.tokens ?? {};
523
+ if (typeof token !== 'string' || !token) return 'not signed in with ChatGPT';
524
+ if (typeof accountId !== 'string' || !accountId) return 'no ChatGPT account id in the login';
525
+ if (jwtExpiresMs(token) <= nowMs) {
526
+ return 'the login token expired; run Codex once to refresh it';
527
+ }
528
+ return {
529
+ authorization: `Bearer ${token}`,
530
+ 'chatgpt-account-id': accountId,
531
+ 'user-agent': 'big-spender'
532
+ };
533
+ },
534
+ windows: codexWindows
535
+ }
536
+ };
537
+
538
+ async function pollLimit(state, provider, poller, nowMs, polled) {
539
+ const path = poller.credentialsPath();
540
+ if (!existsSync(path)) return;
541
+ let creds;
542
+ try {
543
+ creds = JSON.parse(readFileSync(path, 'utf8'));
544
+ } catch {
545
+ // JSON.parse quotes part of the text in its error, which here would be a token.
546
+ throw new Error('could not read the login file');
547
+ }
548
+ const headers = poller.headers(creds, nowMs);
549
+ if (typeof headers === 'string') throw new Error(headers);
550
+ for (const value of Object.values(headers))
551
+ assertHeaderSafe(value.replace(/^Bearer /, ''), `the ${provider} login token`);
552
+
553
+ let res;
554
+ try {
555
+ res = await fetch(localOverride(poller.urlEnv, poller.url), {
556
+ headers,
557
+ redirect: 'error',
558
+ signal: AbortSignal.timeout(10_000)
559
+ });
560
+ } catch (err) {
561
+ throw new Error(`request failed (${err?.name ?? 'error'})`);
562
+ }
563
+ if (!res.ok) {
564
+ const hint =
565
+ res.status === 401 || res.status === 403
566
+ ? '; the login token was refused, run the agent once to refresh it'
567
+ : '';
568
+ throw new Error(`HTTP ${res.status}${hint}`);
569
+ }
570
+ let body;
571
+ try {
572
+ body = await res.json();
573
+ } catch {
574
+ body = null;
575
+ }
576
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
577
+ throw new Error('the answer was not a JSON object');
578
+ }
579
+
580
+ const seen = [];
581
+ for (const w of poller.windows(body, nowMs)) {
582
+ const stored = addLimit(state, {
583
+ provider,
584
+ window: w.window,
585
+ // The Claude endpoint's reset time jitters by a fraction of a second (14:59:59.7 for a
586
+ // 15:00 reset), and addLimit floors and keeps the earliest, so round to the real minute.
587
+ resetsAtMs: Math.round(w.resetsAtMs / MINUTE_MS) * MINUTE_MS,
588
+ percent: w.percent,
589
+ ...(w.percent >= 100 ? { hitMs: nowMs } : {})
590
+ });
591
+ if (stored) polled.push({ ...stored, percent: w.percent });
592
+ seen.push(`${w.window} ${Math.round(w.percent)}%`);
593
+ }
594
+ log(`polled ${provider} usage: ${seen.join(', ') || 'no windows in use'}`);
595
+ }
596
+
597
+ /**
598
+ * A failed poll only costs a warning: it never fails the run or the push. Returns this run's
599
+ * Codex readings.
600
+ */
601
+ async function pollLimits(state, nowMs) {
602
+ /** @type {{ window: string, resetsAtMs: number, percent: number }[]} */
603
+ const polled = [];
604
+ if (['off', '0', 'false', 'no'].includes(setting('POLL_LIMITS').toLowerCase())) return polled;
605
+ for (const [provider, poller] of Object.entries(LIMIT_POLLERS)) {
606
+ const readings = [];
607
+ try {
608
+ await pollLimit(state, provider, poller, nowMs, readings);
609
+ if (provider === 'codex') polled.push(...readings);
610
+ } catch (err) {
611
+ log(`warning: ${provider} usage not polled: ${err?.message ?? 'failed'}`);
612
+ }
613
+ }
614
+ return polled;
615
+ }
616
+
338
617
  // ---------------------------------------------------------------------------
339
618
  // Pricing
340
619
 
@@ -561,7 +840,7 @@ function claudeLineHandler(state, resolvePrice, cutoffMs) {
561
840
 
562
841
  // Codex: token_count events carry per-request usage in info.last_token_usage.
563
842
  // input_tokens includes cached_input_tokens. output_tokens includes reasoning.
564
- function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSession) {
843
+ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSession, refusals) {
565
844
  return (line) => {
566
845
  const o = parseJson(line);
567
846
  if (!o) return;
@@ -574,6 +853,11 @@ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSess
574
853
  fileState.model = p.model;
575
854
  return;
576
855
  }
856
+ if (o.type === 'event_msg' && p && isCodexRefusal(p)) {
857
+ const ts = Date.parse(o.timestamp);
858
+ if (Number.isFinite(ts)) refusals.push(ts);
859
+ return;
860
+ }
577
861
  if (o.type !== 'event_msg' || p?.type !== 'token_count') return;
578
862
  codexLimits(state, o, p.rate_limits);
579
863
  if (!p.info) return;
@@ -2144,7 +2428,7 @@ async function readOpenCode(paths, ctx, provider) {
2144
2428
  }
2145
2429
 
2146
2430
  /**
2147
- * @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
2431
+ * @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, codexRefusals: number[], seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
2148
2432
  * @typedef {{
2149
2433
  * paths: string[],
2150
2434
  * envPaths: () => string[],
@@ -2187,7 +2471,8 @@ const SOURCES = {
2187
2471
  file,
2188
2472
  ctx.resolvePrice,
2189
2473
  ctx.cutoffMs,
2190
- path.match(/([0-9a-f-]{36})\.jsonl$/)?.[1] ?? path
2474
+ path.match(/([0-9a-f-]{36})\.jsonl$/)?.[1] ?? path,
2475
+ ctx.codexRefusals
2191
2476
  )
2192
2477
  ),
2193
2478
  priceKeys: litellmKeys('openai')
@@ -2290,11 +2575,21 @@ function enabledSources() {
2290
2575
  }
2291
2576
 
2292
2577
  /** @param {[string, Source][]} sources */
2293
- async function scan(state, resolvePrice, cutoffMs, sources) {
2578
+ async function scan(state, resolvePrice, cutoffMs, sources, polled) {
2294
2579
  /** @type {ReadContext} */
2295
- const ctx = { state, resolvePrice, cutoffMs, seenPaths: new Set(), filesRead: 0, parsedBytes: 0 };
2580
+ const ctx = {
2581
+ state,
2582
+ resolvePrice,
2583
+ cutoffMs,
2584
+ codexRefusals: [],
2585
+ seenPaths: new Set(),
2586
+ filesRead: 0,
2587
+ parsedBytes: 0
2588
+ };
2296
2589
  for (const [provider, source] of sources) await source.read(source.paths, ctx, provider);
2297
2590
  for (const [provider, source] of sources) await source.read(source.envPaths(), ctx, provider);
2591
+ // After every file: a full reading of the refused window can come later in the logs.
2592
+ for (const ts of ctx.codexRefusals) codexRefusal(state, ts, polled);
2298
2593
  for (const path of Object.keys(state.files)) {
2299
2594
  if (!ctx.seenPaths.has(path)) delete state.files[path];
2300
2595
  }
@@ -2424,7 +2719,8 @@ function buildSnapshot(
2424
2719
  a.resetsAt.localeCompare(b.resetsAt) ||
2425
2720
  a.provider.localeCompare(b.provider) ||
2426
2721
  a.window.localeCompare(b.window)
2427
- );
2722
+ )
2723
+ .slice(-MAX_LIMIT_WINDOWS);
2428
2724
  if (limits.length) snapshot.limits = limits;
2429
2725
  return { snapshot, sessions24h };
2430
2726
  }
@@ -2499,14 +2795,21 @@ function printSummary(snapshot, sessions24h, nowMs) {
2499
2795
  // local logs and sent under its own device id: the same account on two machines is one history.
2500
2796
 
2501
2797
  async function cursorRequest(path, bearer, body, headers = {}) {
2502
- const res = await fetch(`${cursorApiUrl(process.env.BIG_SPENDER_CURSOR_API_URL)}${path}`, {
2503
- method: 'POST',
2504
- headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json', ...headers },
2505
- body: JSON.stringify(body),
2506
- // Never forward the key or token to another host.
2507
- redirect: 'error',
2508
- signal: AbortSignal.timeout(30_000)
2509
- });
2798
+ const res = await fetch(
2799
+ `${localOverride('BIG_SPENDER_CURSOR_API_URL', 'https://api2.cursor.sh')}${path}`,
2800
+ {
2801
+ method: 'POST',
2802
+ headers: {
2803
+ authorization: `Bearer ${bearer}`,
2804
+ 'content-type': 'application/json',
2805
+ ...headers
2806
+ },
2807
+ body: JSON.stringify(body),
2808
+ // Never forward the key or token to another host.
2809
+ redirect: 'error',
2810
+ signal: AbortSignal.timeout(30_000)
2811
+ }
2812
+ );
2510
2813
  if (!res.ok) {
2511
2814
  const hint =
2512
2815
  res.status === 401 || res.status === 403 ? '; check BIG_SPENDER_CURSOR_API_KEY' : '';
@@ -2776,7 +3079,8 @@ async function main() {
2776
3079
  pruneState(state, coverageStartMs);
2777
3080
  const sources = enabledSources();
2778
3081
  const enabled = new Set(sources.map(([id]) => id));
2779
- await scan(state, resolvePrice, coverageStartMs, sources);
3082
+ const polled = await pollLimits(state, nowMs);
3083
+ await scan(state, resolvePrice, coverageStartMs, sources, polled);
2780
3084
  await saveState(state);
2781
3085
 
2782
3086
  const buckets = Object.fromEntries(
package/dist/limits.d.ts CHANGED
@@ -1,12 +1,35 @@
1
1
  import { type LimitWindow, type UsageProvider, type UsageSnapshot } from './schema.ts';
2
2
  /**
3
- * Merges window lists into one record per window instance: same provider and window, with resets
4
- * at most RESET_SLACK_MS after the earliest reset of the group (rounded down to the minute), which
5
- * the record keeps. A group keeps the highest peak and the earliest hit, so merging is idempotent
3
+ * Merges window lists into one record per window instance (see groupWindows), which keeps the
4
+ * earliest reset. A group keeps the highest peak and the earliest hit, so merging is idempotent
6
5
  * and one account's window reported by two devices counts once. Sorted by reset time; past the
7
6
  * cap the oldest are dropped.
8
7
  */
9
8
  export declare function mergeLimits(...lists: (LimitWindow[] | undefined)[]): LimitWindow[];
9
+ export type LimitHitDevice = {
10
+ deviceId: string;
11
+ hitAt: string;
12
+ peakPercent: number;
13
+ };
14
+ export type LimitHit = {
15
+ provider: UsageProvider;
16
+ window: string;
17
+ /** Earliest reset of the window instance, as mergeLimits keeps it. */
18
+ resetsAt: string;
19
+ /** Earliest hitAt across devices. */
20
+ hitAt: string;
21
+ /** Devices that recorded a hit for this instance, earliest first (ties by deviceId). */
22
+ devices: LimitHitDevice[];
23
+ };
24
+ export type LimitHitsReport = {
25
+ generatedAt: string;
26
+ hits: LimitHit[];
27
+ };
28
+ /**
29
+ * Every recorded limit hit with its exact time and the devices that saw it, earliest device
30
+ * first. Not public: it names devices.
31
+ */
32
+ export declare function limitHits(snapshots: UsageSnapshot[], now: number): LimitHitsReport;
10
33
  export type LimitsSeries = {
11
34
  hits: number[];
12
35
  lockedHours: number[];
package/dist/limits.js CHANGED
@@ -9,50 +9,94 @@ const minuteOf = (iso) => Math.floor(Date.parse(iso) / MINUTE_MS) * MINUTE_MS;
9
9
  // Reports of one window can put its reset seconds apart, across a minute boundary.
10
10
  const RESET_SLACK_MS = 2 * MINUTE_MS;
11
11
  /**
12
- * Merges window lists into one record per window instance: same provider and window, with resets
13
- * at most RESET_SLACK_MS after the earliest reset of the group (rounded down to the minute), which
14
- * the record keeps. A group keeps the highest peak and the earliest hit, so merging is idempotent
12
+ * Groups reports into window instances: same provider and window, with resets at most
13
+ * RESET_SLACK_MS after the earliest reset of the group (rounded down to the minute). Each member's
14
+ * `resetsAt` is rounded; the first member of a group carries the earliest.
15
+ */
16
+ function groupWindows(items) {
17
+ const sorted = items
18
+ .map(({ window: w, deviceId }) => ({
19
+ window: { ...w, resetsAt: new Date(minuteOf(w.resetsAt)).toISOString() },
20
+ deviceId
21
+ }))
22
+ .sort((a, b) => a.window.provider.localeCompare(b.window.provider) ||
23
+ a.window.window.localeCompare(b.window.window) ||
24
+ Date.parse(a.window.resetsAt) - Date.parse(b.window.resetsAt));
25
+ const groups = [];
26
+ for (const item of sorted) {
27
+ const group = groups.at(-1);
28
+ const first = group?.[0].window;
29
+ if (group &&
30
+ first &&
31
+ first.provider === item.window.provider &&
32
+ first.window === item.window.window &&
33
+ Date.parse(item.window.resetsAt) - Date.parse(first.resetsAt) <= RESET_SLACK_MS) {
34
+ group.push(item);
35
+ }
36
+ else {
37
+ groups.push([item]);
38
+ }
39
+ }
40
+ return groups;
41
+ }
42
+ const byTime = (a, b) => Date.parse(a) - Date.parse(b);
43
+ /**
44
+ * Merges window lists into one record per window instance (see groupWindows), which keeps the
45
+ * earliest reset. A group keeps the highest peak and the earliest hit, so merging is idempotent
15
46
  * and one account's window reported by two devices counts once. Sorted by reset time; past the
16
47
  * cap the oldest are dropped.
17
48
  */
18
49
  export function mergeLimits(...lists) {
19
- const all = lists
20
- .flatMap((list) => list ?? [])
21
- .map((w) => ({
22
- provider: w.provider,
23
- window: w.window,
24
- resetsAt: new Date(minuteOf(w.resetsAt)).toISOString(),
25
- peakPercent: w.peakPercent,
26
- ...(w.hitAt ? { hitAt: w.hitAt } : {})
27
- }))
28
- .sort((a, b) => a.provider.localeCompare(b.provider) ||
29
- a.window.localeCompare(b.window) ||
30
- Date.parse(a.resetsAt) - Date.parse(b.resetsAt));
31
- const merged = [];
32
- for (const w of all) {
33
- const group = merged.at(-1);
34
- if (!group ||
35
- group.provider !== w.provider ||
36
- group.window !== w.window ||
37
- Date.parse(w.resetsAt) - Date.parse(group.resetsAt) > RESET_SLACK_MS) {
38
- merged.push(w);
39
- continue;
40
- }
41
- const hits = [group.hitAt, w.hitAt].filter((t) => t !== undefined);
42
- const hitAt = hits.sort((a, b) => Date.parse(a) - Date.parse(b))[0];
43
- merged[merged.length - 1] = {
44
- provider: group.provider,
45
- window: group.window,
46
- resetsAt: group.resetsAt,
47
- peakPercent: Math.max(group.peakPercent, w.peakPercent),
50
+ const groups = groupWindows(lists.flatMap((list) => list ?? []).map((window) => ({ window })));
51
+ const merged = groups.map((group) => {
52
+ const { provider, window, resetsAt } = group[0].window;
53
+ const hitAt = group
54
+ .map((m) => m.window.hitAt)
55
+ .filter((t) => t !== undefined)
56
+ .sort(byTime)[0];
57
+ return {
58
+ provider,
59
+ window,
60
+ resetsAt,
61
+ peakPercent: Math.max(...group.map((m) => m.window.peakPercent)),
48
62
  ...(hitAt ? { hitAt } : {})
49
63
  };
50
- }
64
+ });
51
65
  const sorted = merged.sort((a, b) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt) ||
52
66
  a.provider.localeCompare(b.provider) ||
53
67
  a.window.localeCompare(b.window));
54
68
  return sorted.slice(Math.max(0, sorted.length - MAX_LIMIT_WINDOWS));
55
69
  }
70
+ /**
71
+ * Every recorded limit hit with its exact time and the devices that saw it, earliest device
72
+ * first. Not public: it names devices.
73
+ */
74
+ export function limitHits(snapshots, now) {
75
+ const groups = groupWindows(snapshots.flatMap((s) => (s.limits ?? []).map((window) => ({ window, deviceId: s.deviceId }))));
76
+ const hits = groups.flatMap((group) => {
77
+ const byDevice = new Map();
78
+ for (const { window: w, deviceId } of group) {
79
+ if (!w.hitAt || deviceId === undefined)
80
+ continue;
81
+ const seen = byDevice.get(deviceId);
82
+ byDevice.set(deviceId, {
83
+ deviceId,
84
+ hitAt: seen && byTime(seen.hitAt, w.hitAt) <= 0 ? seen.hitAt : w.hitAt,
85
+ peakPercent: Math.max(seen?.peakPercent ?? 0, w.peakPercent)
86
+ });
87
+ }
88
+ const devices = [...byDevice.values()].sort((a, b) => byTime(a.hitAt, b.hitAt) || a.deviceId.localeCompare(b.deviceId));
89
+ if (!devices.length)
90
+ return [];
91
+ const { provider, window, resetsAt } = group[0].window;
92
+ return [{ provider, window, resetsAt, hitAt: devices[0].hitAt, devices }];
93
+ });
94
+ hits.sort((a, b) => byTime(a.hitAt, b.hitAt) ||
95
+ a.provider.localeCompare(b.provider) ||
96
+ a.window.localeCompare(b.window) ||
97
+ byTime(a.resetsAt, b.resetsAt));
98
+ return { generatedAt: new Date(now).toISOString(), hits };
99
+ }
56
100
  const KNOWN_ORDER = ['five_hour', 'seven_day'];
57
101
  const rank = (w) => {
58
102
  const i = KNOWN_ORDER.indexOf(w);
package/dist/serve.d.ts CHANGED
@@ -6,9 +6,10 @@ export type ServeConfig = {
6
6
  host: string;
7
7
  dataDir: string;
8
8
  ingestToken: string | undefined;
9
+ adminToken: string | undefined;
9
10
  devices: DeviceConfig;
10
11
  };
11
- export declare const SERVE_USAGE = "Usage: big-spender serve [--port 8787] [--host 0.0.0.0] [--data ./data] [--devices devices.json]\n\nEnvironment:\n PORT, HOST listen address (flags win)\n BIG_SPENDER_DATA_DIR where per-device snapshots are stored (default ./data)\n BIG_SPENDER_INGEST_TOKEN bearer token collectors must send; ingest is off without it\n BIG_SPENDER_DEVICES_FILE JSON device names and colours (see the README)";
12
+ export declare const SERVE_USAGE = "Usage: big-spender serve [--port 8787] [--host 0.0.0.0] [--data ./data] [--devices devices.json]\n\nEnvironment:\n PORT, HOST listen address (flags win)\n BIG_SPENDER_DATA_DIR where per-device snapshots are stored (default ./data)\n BIG_SPENDER_INGEST_TOKEN bearer token collectors must send; ingest is off without it\n BIG_SPENDER_ADMIN_TOKEN bearer token for GET /api/usage/limits/hits; must differ from the ingest token; off without it\n BIG_SPENDER_DEVICES_FILE JSON device names and colours (see the README)";
12
13
  export declare function loadServeConfig(argv: string[], env?: NodeJS.ProcessEnv): Promise<ServeConfig>;
13
14
  export declare function createHttpServer(bs: BigSpender): Server;
14
15
  export declare function serve(argv: string[]): Promise<void>;
package/dist/serve.js CHANGED
@@ -16,6 +16,7 @@ Environment:
16
16
  PORT, HOST listen address (flags win)
17
17
  BIG_SPENDER_DATA_DIR where per-device snapshots are stored (default ./data)
18
18
  BIG_SPENDER_INGEST_TOKEN bearer token collectors must send; ingest is off without it
19
+ BIG_SPENDER_ADMIN_TOKEN bearer token for GET /api/usage/limits/hits; must differ from the ingest token; off without it
19
20
  BIG_SPENDER_DEVICES_FILE JSON device names and colours (see the README)`;
20
21
  export async function loadServeConfig(argv, env = process.env) {
21
22
  const { values } = parseArgs({
@@ -48,6 +49,7 @@ export async function loadServeConfig(argv, env = process.env) {
48
49
  host: values.host ?? env.HOST ?? '0.0.0.0',
49
50
  dataDir: values.data ?? env.BIG_SPENDER_DATA_DIR ?? './data',
50
51
  ingestToken: env.BIG_SPENDER_INGEST_TOKEN?.trim() || undefined,
52
+ adminToken: env.BIG_SPENDER_ADMIN_TOKEN?.trim() || undefined,
51
53
  devices
52
54
  };
53
55
  }
@@ -69,6 +71,10 @@ const routes = {
69
71
  headers: { 'cache-control': 'public, max-age=300, stale-while-revalidate=900' }
70
72
  })
71
73
  },
74
+ '/api/usage/limits/hits': {
75
+ methods: ['GET', 'HEAD'],
76
+ handle: (bs, request) => bs.limitHits(request)
77
+ },
72
78
  '/': {
73
79
  methods: ['GET', 'HEAD'],
74
80
  handle: async (bs) => new Response(renderPage(await bs.summary(), await bs.limits()), {
@@ -0,0 +1 @@
1
+ export declare function authorized(header: string | null, expected: string): boolean;
@@ -0,0 +1,9 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ const digest = (s) => createHash('sha256').update(s).digest();
3
+ export function authorized(header, expected) {
4
+ const match = /^Bearer (.+)$/.exec(header ?? '');
5
+ if (!match)
6
+ return false;
7
+ // Hash both sides so the comparison is constant-time regardless of length.
8
+ return timingSafeEqual(digest(match[1]), digest(expected));
9
+ }
@@ -2,7 +2,7 @@ import type { DeviceConfig } from '../devices.ts';
2
2
  import { type LimitsSummary } from '../limits.ts';
3
3
  import { type UsageSummary } from '../summary.ts';
4
4
  export { DEVICE_ID, MAX_LIMIT_WINDOWS, PROVIDERS, RANGES, limitWindowSchema, usageRowSchema, usageSnapshotSchema, type LimitWindow, type UsageProvider, type UsageRange, type UsageRow, type UsageSnapshot } from '../schema.ts';
5
- export { summarizeLimits, type LimitsSeries, type LimitsSummary, type LimitWindowSummary } from '../limits.ts';
5
+ export { limitHits, summarizeLimits, type LimitHit, type LimitHitDevice, type LimitHitsReport, type LimitsSeries, type LimitsSummary, type LimitWindowSummary } from '../limits.ts';
6
6
  export { OTHER, PALETTE, resolveDevices, type DeviceConfig, type DeviceInfo } from '../devices.ts';
7
7
  export { summarize, type Bucket, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
8
8
  export type BigSpenderOptions = {
@@ -10,6 +10,11 @@ export type BigSpenderOptions = {
10
10
  dataDir: string;
11
11
  /** Bearer token collectors must send. Missing or empty turns ingest off (503). */
12
12
  ingestToken: string | undefined;
13
+ /**
14
+ * Bearer token for `limitHits`. Missing or empty turns it off (503), and so does a token equal to
15
+ * `ingestToken`: every collector holds that one.
16
+ */
17
+ adminToken?: string | undefined;
13
18
  devices: DeviceConfig;
14
19
  };
15
20
  export type BigSpender = {
@@ -19,5 +24,7 @@ export type BigSpender = {
19
24
  summary(now?: number): Promise<UsageSummary>;
20
25
  /** Subscription limit hits over the last 90 UTC days, cached like `summary`. */
21
26
  limits(now?: number): Promise<LimitsSummary>;
27
+ /** Admin only: exact time and devices of every recorded limit hit. Never cached. */
28
+ limitHits(request: Request): Promise<Response>;
22
29
  };
23
- export declare function createBigSpender({ dataDir, ingestToken, devices }: BigSpenderOptions): BigSpender;
30
+ export declare function createBigSpender({ dataDir, ingestToken, adminToken, devices }: BigSpenderOptions): BigSpender;
@@ -1,13 +1,15 @@
1
1
  import { fileStore } from '../store.js';
2
- import { summarizeLimits } from '../limits.js';
2
+ import { limitHits, summarizeLimits } from '../limits.js';
3
3
  import { summarize } from '../summary.js';
4
+ import { authorized } from './auth.js';
4
5
  import { createIngest } from './ingest.js';
5
6
  export { DEVICE_ID, MAX_LIMIT_WINDOWS, PROVIDERS, RANGES, limitWindowSchema, usageRowSchema, usageSnapshotSchema } from '../schema.js';
6
- export { summarizeLimits } from '../limits.js';
7
+ export { limitHits, summarizeLimits } from '../limits.js';
7
8
  export { OTHER, PALETTE, resolveDevices } from '../devices.js';
8
9
  export { summarize } from '../summary.js';
9
10
  const SUMMARY_TTL_MS = 5 * 60 * 1000;
10
- export function createBigSpender({ dataDir, ingestToken, devices }) {
11
+ export function createBigSpender({ dataDir, ingestToken, adminToken, devices }) {
12
+ const admin = adminToken?.trim();
11
13
  const store = fileStore(dataDir);
12
14
  let cache = null;
13
15
  let limitsCache = null;
@@ -33,6 +35,19 @@ export function createBigSpender({ dataDir, ingestToken, devices }) {
33
35
  const value = summarizeLimits(await store.list(), now);
34
36
  limitsCache = { value, computedAt: now };
35
37
  return value;
38
+ },
39
+ async limitHits(request) {
40
+ if (!admin)
41
+ return Response.json({ error: 'admin is not configured' }, { status: 503 });
42
+ if (admin === ingestToken?.trim()) {
43
+ return Response.json({ error: 'admin token must differ from the ingest token' }, { status: 503 });
44
+ }
45
+ if (!authorized(request.headers.get('authorization'), admin)) {
46
+ return Response.json({ error: 'unauthorized' }, { status: 401 });
47
+ }
48
+ return Response.json(limitHits(await store.list(), Date.now()), {
49
+ headers: { 'cache-control': 'no-store' }
50
+ });
36
51
  }
37
52
  };
38
53
  }
@@ -1,16 +1,8 @@
1
- import { createHash, timingSafeEqual } from 'node:crypto';
2
1
  import { CURSOR_DEVICE_ID, usageSnapshotSchema } from '../schema.js';
2
+ import { authorized } from './auth.js';
3
3
  // Collectors POST one device's full snapshot here (optionally gzip-encoded).
4
4
  const MAX_BODY_BYTES = 2 * 1024 * 1024;
5
5
  const MAX_DECODED_BYTES = 16 * 1024 * 1024;
6
- const digest = (s) => createHash('sha256').update(s).digest();
7
- function authorized(header, expected) {
8
- const match = /^Bearer (.+)$/.exec(header ?? '');
9
- if (!match)
10
- return false;
11
- // Hash both sides so the comparison is constant-time regardless of length.
12
- return timingSafeEqual(digest(match[1]), digest(expected));
13
- }
14
6
  class TooLarge extends Error {
15
7
  }
16
8
  async function readCapped(stream, max) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "big-spender",
3
- "version": "0.11.0",
3
+ "version": "0.13.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",
@@ -13,3 +13,7 @@ BIG_SPENDER_INGEST_TOKEN=
13
13
  # Optional: experimental sources to read too, comma-separated. Their counts match ccusage on test
14
14
  # data but have not been checked against real usage yet. Available: antigravity, gemini.
15
15
  # BIG_SPENDER_EXPERIMENTAL=antigravity
16
+ # Optional: set to off to stop the collector asking Anthropic and OpenAI how full your Claude and
17
+ # Codex limit windows are. It reads the agents' own login files read-only and only sends the token to
18
+ # that provider.
19
+ # BIG_SPENDER_POLL_LIMITS=off