big-spender 0.11.0 → 0.12.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
@@ -248,21 +248,32 @@ own storage or charts.
248
248
  ## Usage limits
249
249
 
250
250
  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.
251
+ allowance, so you can judge whether a plan fits how you work. It reads what the agents write to
252
+ their local logs, and it polls their usage endpoints (see [Polling](#polling-usage-endpoints)).
253
253
 
254
254
  - **Claude Code.** A refused request is logged as an `assistant` line with `error: "rate_limit"`
255
255
  and a `quotaLimits` object that names the window (`five_hour`, `seven_day`, a model-specific
256
256
  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.
257
+ blocked window becomes one record. Claude Code logs nothing when a request is allowed, so the logs
258
+ alone say nothing about utilisation below 100%; polling fills that in.
259
259
  - **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%.
260
+ 5-hour window (`five_hour`, 300 minutes) and the weekly window (`seven_day`, 10080 minutes). A
261
+ window counts as hit when its share reaches 100%. A refused turn is logged too, but names no
262
+ window and no reset. It starts the lockout of each Codex window seen full (by a poll or any log
263
+ line) that was open at that moment, so the lockout begins at the first logged refusal instead of
264
+ at the next poll. When no open window was seen full, a lockout that began and
265
+ ended between two runs can still be placed by elimination. Usage in a window instance only rises
266
+ until it resets, so a poll that read an instance below 100% after the refusal proves it was not
267
+ the one blocking. This needs a successful poll in the same run that read both Codex windows, and
268
+ every limit it reports must have an instance on file that was open at the refusal. If exactly one open window is then left,
269
+ it gets the hit at the refusal. The gap that remains is a refusal whose window no reading ever
270
+ saw, one where several windows stay possible, and any refusal read while polling is off or
271
+ failing. These change nothing.
262
272
 
263
273
  A record is one window instance, identified by provider, window name and reset time rounded down
264
274
  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
275
+ window's reported reset can drift by a few seconds. A push sends at most the 5,000 newest records,
276
+ the most the server accepts. It holds the peak percentage seen and the time of the first refusal. Limits belong
266
277
  to the account, not the machine, so merging keeps the highest peak and the earliest refusal, and
267
278
  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
279
  server, like day rows.
@@ -277,9 +288,27 @@ finer than a UTC day, no device names, no report times. It is separate from `/ap
277
288
  shape did not change. `big-spender status` also lists the limits hit in the last 7 days, to the
278
289
  minute, because that output never leaves the machine.
279
290
 
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.
291
+ ### Polling usage endpoints
292
+
293
+ Logs only show a limit when a request is refused, which hides how much of a window you leave
294
+ unused. So each run also asks Anthropic and OpenAI how full your windows are right now, the same
295
+ numbers `/usage` in Claude Code and Codex show. Claude is polled at `api.anthropic.com` and Codex at
296
+ `chatgpt.com`, with the login the agent already keeps: `~/.claude/.credentials.json`
297
+ (`$CLAUDE_CONFIG_DIR` if set) and `~/.codex/auth.json` (`$CODEX_HOME` if set). The collector opens
298
+ those files read-only, never refreshes them and sends the token only to that provider. If a token
299
+ has expired, that provider is skipped with one warning until you run the agent again. A missing
300
+ file means that provider is not polled, without a warning. A failed poll never fails the run.
301
+
302
+ Each reading is a peak for the same window record the logs feed. Windows are named `five_hour` and
303
+ `seven_day`, plus one `seven_day_<model>` per model-specific weekly (`seven_day_fable`,
304
+ `seven_day_opus`). Codex's extra limits become `<window>_<limit name>`. Only the window name, reset
305
+ time and percentage are stored or sent.
306
+
307
+ Claude Code logs a refusal of Fable's weekly as `seven_day_overage_included` and labels it "Fable
308
+ limit". The endpoint reports the same limit as `seven_day_fable`, so the collector records those
309
+ refusals as `seven_day_fable`, and they join the polled readings in one record.
310
+
311
+ To turn polling off, set `BIG_SPENDER_POLL_LIMITS=off` in the env file.
283
312
 
284
313
  An older server rejects the unknown `limits` field with a 422. The collector and `push` then send
285
314
  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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "big-spender",
3
- "version": "0.11.0",
3
+ "version": "0.12.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