big-spender 0.5.0 → 0.7.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
@@ -32,6 +32,10 @@ nothing is bucketed finer than a UTC day: 7, 30 and 90 days are per day, all tim
32
32
  (Monday UTC). Device ids are published only if you leave
33
33
  `unknownDevices` at its default, see [Device names and colours](#device-names-and-colours).
34
34
 
35
+ Usage limit windows (see [Usage limits](#usage-limits)) are sent as a window name, its reset time,
36
+ a peak percentage and, when a request was refused, the time of the first refusal. They never name a
37
+ device, and `/api/usage/limits` publishes them per UTC day only.
38
+
35
39
  Before the first send you can see exactly what would leave the machine with
36
40
  `big-spender push <device> --dry-run`.
37
41
 
@@ -145,12 +149,13 @@ Cursor.
145
149
 
146
150
  `big-spender serve` is a small `node:http` server:
147
151
 
148
- | Route | What it does |
149
- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
150
- | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
151
- | `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`. |
152
- | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models. No JavaScript, no external assets, light and dark. |
153
- | `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 /` | 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. |
154
159
 
155
160
  Configuration comes from flags or environment variables (flags win):
156
161
 
@@ -234,11 +239,52 @@ Next.js route handler (`export const POST = (request: Request) => bs.ingest(requ
234
239
  `{ ok, deviceId, rows, result: 'stored' | 'stale' }`).
235
240
  - `summary(now?)`: the merged totals for every range. The result is cached for five minutes and
236
241
  recomputed right after an ingest.
242
+ - `limits(now?)`: the [usage limit](#usage-limits) summary, cached the same way.
237
243
 
238
- The module also exports `summarize(snapshots, now, config)`, the snapshot schema
239
- (`usageSnapshotSchema`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
244
+ The module also exports `summarize(snapshots, now, config)`, `summarizeLimits(snapshots, now)`, the
245
+ snapshot schema (`usageSnapshotSchema`, `limitWindowSchema`, `MAX_LIMIT_WINDOWS`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
240
246
  own storage or charts.
241
247
 
248
+ ## Usage limits
249
+
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.
253
+
254
+ - **Claude Code.** A refused request is logged as an `assistant` line with `error: "rate_limit"`
255
+ and a `quotaLimits` object that names the window (`five_hour`, `seven_day`, a model-specific
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.
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%.
262
+
263
+ A record is one window instance, identified by provider, window name and reset time rounded down
264
+ 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
266
+ to the account, not the machine, so merging keeps the highest peak and the earliest refusal, and
267
+ 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
+ server, like day rows.
269
+
270
+ `GET /api/usage/limits` returns, for each provider and window over the last 90 UTC days, how many
271
+ window instances were seen, how many were hit, the hours locked out (first refusal until reset),
272
+ the day of the last hit and a per-day series. Claude can move a window's reset later while you are
273
+ blocked, so a refusal before the previous reset extends that lockout instead of counting a new hit. A window counts on the day of its first refusal, or
274
+ of its reset when it was never refused; a window that is still open counts on today with its peak
275
+ so far. It follows the same privacy rule as the rest: nothing
276
+ finer than a UTC day, no device names, no report times. It is separate from `/api/usage`, whose
277
+ shape did not change. `big-spender status` also lists the limits hit in the last 7 days, to the
278
+ minute, because that output never leaves the machine.
279
+
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.
283
+
284
+ An older server rejects the unknown `limits` field with a 422. The collector and `push` then send
285
+ the snapshot again without it and print a warning on each run, so usage keeps arriving. Upgrade the server to store
286
+ limits.
287
+
242
288
  ## Push by hand
243
289
 
244
290
  For a machine that should only report now and then, or where you would rather not store a token:
@@ -281,19 +327,21 @@ about 15 to 20 percent less.
281
327
 
282
328
  ## How it counts
283
329
 
284
- | Source | Files | Notes |
285
- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
286
- | Claude Code | `~/.claude/projects/**/*.jsonl`, `~/.config/claude/projects`, `$CLAUDE_CONFIG_DIR/projects` | `assistant` lines; de-duplicated by `message.id` + `requestId` (one API response is logged once per content block, and resumed sessions copy history). `<synthetic>` skipped; subagent logs included. Some Claude Code versions (2.1.293 to 2.1.310) log a partial output count on a message's first line and the final count on a later line; a later line that reports more output adds the difference. |
287
- | Codex | `~/.codex/sessions/**/rollout-*.jsonl`, `$CODEX_HOME/sessions` | `event_msg` / `token_count` with `info.last_token_usage`; skipped when `total_token_usage` did not change. Model from the latest `turn_context`. `cached_input_tokens` is part of `input_tokens`; reasoning is part of `output_tokens`. |
288
- | Cursor | Cursor's API, `DashboardService/GetFilteredUsageEvents`, with `BIG_SPENDER_CURSOR_API_KEY` | Events with token counts only. Cost is Cursor's `totalCents`. Events have no unique id and pages can overlap, so a time window with more than 1,000 events is split in half instead of paged. `cacheWriteTokens` count as 5-minute cache writes. Sessions are hashed `conversationId`s. Model names are lowercased, and anything outside `a-z 0-9 . _ : @ -` becomes `-`. |
289
- | pi | `~/.pi/agent/sessions/**/*.jsonl`, `$PI_CODING_AGENT_DIR/sessions`, `$PI_CODING_AGENT_SESSION_DIR`, `$PI_AGENT_DIR` (comma-separated, as in ccusage) | Assistant `message` entries with `usage`; `input` excludes cached tokens, reasoning is part of `output`, and `cacheWrite` counts as 5-minute writes except its `cacheWrite1h` part. Calls with no tokens (aborted, failed before a retry) are skipped, and a call with only `totalTokens` counts it as output. A fork's file starts with a copy of its parent's calls up to the fork; those leading calls are skipped when the parent file has them. ccusage looks only at the parent's current branch, so it counts the copy again once the parent moves to another branch. A model id that is a file path (absolute, a `file://` or `host:/` URL, or ending in `.gguf` and similar) is reduced to its file name. `subagent-artifacts/` transcripts are skipped. Cost is LiteLLM's, not the cost pi stores. |
330
+ | Source | Files | Notes |
331
+ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
332
+ | Claude Code | `~/.claude/projects/**/*.jsonl`, `~/.config/claude/projects`, `$CLAUDE_CONFIG_DIR/projects` | `assistant` lines; de-duplicated by `message.id` + `requestId` (one API response is logged once per content block, and resumed sessions copy history). `<synthetic>` skipped; subagent logs included. Some Claude Code versions (2.1.293 to 2.1.310) log a partial output count on a message's first line and the final count on a later line; a later line that reports more output adds the difference. |
333
+ | Codex | `~/.codex/sessions/**/rollout-*.jsonl`, `$CODEX_HOME/sessions` | `event_msg` / `token_count` with `info.last_token_usage`; skipped when `total_token_usage` did not change. Model from the latest `turn_context`. `cached_input_tokens` is part of `input_tokens`; reasoning is part of `output_tokens`. |
334
+ | Cursor | Cursor's API, `DashboardService/GetFilteredUsageEvents`, with `BIG_SPENDER_CURSOR_API_KEY` | Events with token counts only. Cost is Cursor's `totalCents`. Events have no unique id and pages can overlap, so a time window with more than 1,000 events is split in half instead of paged. `cacheWriteTokens` count as 5-minute cache writes. Sessions are hashed `conversationId`s. Model names are lowercased, and anything outside `a-z 0-9 . _ : @ -` becomes `-`. |
335
+ | pi | `~/.pi/agent/sessions/**/*.jsonl`, `$PI_CODING_AGENT_DIR/sessions`, `$PI_CODING_AGENT_SESSION_DIR`, `$PI_AGENT_DIR` (comma-separated, as in ccusage) | Assistant `message` entries with `usage`; `input` excludes cached tokens, reasoning is part of `output`, and `cacheWrite` counts as 5-minute writes except its `cacheWrite1h` part. Calls with no tokens (aborted, failed before a retry) are skipped, and a call with only `totalTokens` counts it as output. A fork's file starts with a copy of its parent's calls up to the fork; those leading calls are skipped when the parent file has them. ccusage looks only at the parent's current branch, so it counts the copy again once the parent moves to another branch. A model id that is a file path (absolute, a `file://` or `host:/` URL, or ending in `.gguf` and similar) is reduced to its file name. `subagent-artifacts/` transcripts are skipped. Cost is LiteLLM's, not the cost pi stores. |
336
+ | Grok Build (experimental) | `~/.grok/sessions/**/updates.jsonl`, `$GROK_HOME/sessions` | **Experimental:** checked against ccusage on test fixtures built from its Grok parser tests, not yet against real Grok Build logs. `turn_completed` lines, one row per model in `usage.modelUsage` (the top-level usage under `summary.json`'s `current_model_id` when that map is missing). De-duplicated by `eventId` + model, also across sessions, since one event can be exported into several; a row without `eventId` by its full content within its file. `cachedReadTokens` and `cacheCreationTokens` are part of `inputTokens`; reasoning is part of `outputTokens`. Always the base rate: a turn sums several API requests, so its total cannot pick the long-context tier; a request of its own above 200K tokens is under-priced. A model id that is a file path is reduced to its file name. A turn cut off before it completes is never logged, so it is not counted. |
290
337
 
291
- **Pricing.** Claude Code, Codex and pi use LiteLLM `model_prices_and_context_window.json`, cached
338
+ **Pricing.** Claude Code, Codex, pi and Grok Build use LiteLLM `model_prices_and_context_window.json`, cached
292
339
  for 24 hours in `~/.cache/big-spender/`. Each source lists the LiteLLM keys to try for a model. Claude
293
340
  Code and Codex try the exact model, then the `anthropic/` or `openai/` prefix, then without a date
294
341
  suffix. pi tries the LiteLLM prefixes of the providers pi supports too (`openrouter/`, `fireworks_ai/`,
295
342
  `groq/` and others). For an OpenRouter id such as `anthropic/claude-sonnet-4.5` it then tries
296
- `claude-sonnet-4.5` and `claude-sonnet-4-5`. Unknown models count with cost 0 and log a warning.
343
+ `claude-sonnet-4.5` and `claude-sonnet-4-5`. Grok Build tries the model and its `xai/` key, then
344
+ both without a trailing `-build`. Unknown models count with cost 0 and log a warning.
297
345
  Long-context tiers
298
346
  (`*_above_<N>k_tokens`) are applied per request; 1-hour cache writes use
299
347
  `cache_creation_input_token_cost_above_1hr`. Cache savings are cache-read tokens times (input price
@@ -316,6 +364,9 @@ than 7 days are rolled up to daily rows. Because the aggregates live in the stat
316
364
  counted even after Claude Code deletes old session logs. `--reset` rebuilds from the logs that still
317
365
  exist, so avoid it unless the state is corrupt.
318
366
 
367
+ Limit windows live in the same state file. The first run after the update re-reads every log once
368
+ to pick up limit lines older runs skipped; it adds no usage.
369
+
319
370
  State from an older collector is fixed in place on the first run of a newer one (for example, one
320
371
  re-read of the Claude logs to pick up missed output tokens), so updating never needs `--reset`.
321
372
 
@@ -25,7 +25,7 @@ import { createHash } from 'node:crypto';
25
25
  import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
26
26
  import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
27
27
  import { homedir } from 'node:os';
28
- import { dirname, join, resolve, sep } from 'node:path';
28
+ import { basename, dirname, join, resolve, sep } from 'node:path';
29
29
  import { gzipSync } from 'node:zlib';
30
30
 
31
31
  const SCHEMA_VERSION = 1;
@@ -125,7 +125,9 @@ async function acquireLock() {
125
125
  * A seen entry is the first timestamp, or for Claude [first timestamp, output tokens counted].
126
126
  * A bare number on a Claude key means the counted output is unknown (state from an older version).
127
127
  * @typedef {number | [number, number]} Seen
128
- * @typedef {{ version: number, files: Record<string, FileState>, seen: Record<string, Seen>, buckets: Record<string, Bucket>, fixes?: string[], rescan?: string[], cursorBackfills?: string[] }} State
128
+ * One subscription usage window instance; see limitWindowSchema in src/schema.ts.
129
+ * @typedef {{ provider: string, window: string, resetsAt: string, peakPercent: number, hitAt?: string }} Limit
130
+ * @typedef {{ version: number, files: Record<string, FileState>, seen: Record<string, Seen>, buckets: Record<string, Bucket>, limits?: Record<string, Limit>, fixes?: string[], rescan?: string[], cursorBackfills?: string[] }} State
129
131
  * cursorBackfills holds a hash of each ingest URL and Cursor API key pair whose server stored the
130
132
  * account's full history. Hashed, because an ingest URL can carry a credential.
131
133
  */
@@ -133,6 +135,8 @@ async function acquireLock() {
133
135
  // One-time fixes to existing state. The state version stays the same so an older installed copy
134
136
  // can still read the file instead of discarding it.
135
137
  const FIX_CLAUDE_OUTPUT = 'claude-final-output';
138
+ // Limit windows are read from log lines older versions skipped, so those logs are re-read once.
139
+ const FIX_LIMITS = 'usage-limits';
136
140
 
137
141
  /** @returns {Promise<State>} */
138
142
  async function loadState() {
@@ -141,19 +145,25 @@ async function loadState() {
141
145
  files: {},
142
146
  seen: {},
143
147
  buckets: {},
144
- fixes: [FIX_CLAUDE_OUTPUT]
148
+ limits: {},
149
+ fixes: [FIX_CLAUDE_OUTPUT, FIX_LIMITS]
145
150
  };
146
151
  if (RESET) return empty;
147
152
  try {
148
153
  const s = JSON.parse(await readFile(STATE_PATH, 'utf8'));
149
154
  if (s?.version !== STATE_VERSION) return empty;
150
155
  s.fixes ??= [];
156
+ s.limits ??= {};
151
157
  if (!s.fixes.includes(FIX_CLAUDE_OUTPUT)) {
152
158
  // Older versions kept the first log line of a Claude message, whose output count can be
153
159
  // partial. Re-read the Claude logs once so later lines add what was missed.
154
160
  s.fixes.push(FIX_CLAUDE_OUTPUT);
155
161
  s.rescan = ['claude'];
156
162
  }
163
+ if (!s.fixes.includes(FIX_LIMITS)) {
164
+ s.fixes.push(FIX_LIMITS);
165
+ s.rescan = [...new Set([...(s.rescan ?? []), 'claude', 'codex'])];
166
+ }
157
167
  return s;
158
168
  } catch {
159
169
  return empty;
@@ -204,6 +214,99 @@ function pruneState(state, cutoffMs) {
204
214
  for (const [key, v] of Object.entries(state.seen)) {
205
215
  if ((Array.isArray(v) ? v[0] : v) < cutoffMs) delete state.seen[key];
206
216
  }
217
+ for (const [key, w] of Object.entries(state.limits ?? {})) {
218
+ if (Date.parse(w.resetsAt) < cutoffMs) delete state.limits[key];
219
+ }
220
+ }
221
+
222
+ // Same rule as mergeLimits in src/limits.ts (this file ships alone, so it cannot import it): one
223
+ // record per window instance, highest peak, earliest hit. Reports of one window can put its reset
224
+ // seconds apart, across a minute boundary, so a reset within RESET_SLACK_MS of a known one of the
225
+ // same window is that one, and the record keeps the earlier reset.
226
+ const MINUTE_MS = 60_000;
227
+ const RESET_SLACK_MS = 2 * MINUTE_MS;
228
+ // Times outside this range are malformed (milliseconds read as seconds, say) and are skipped,
229
+ // never thrown, so a bad limit line cannot stop the usage on the lines after it.
230
+ const LIMIT_TIMES_FROM = Date.parse('2020-01-01T00:00:00Z');
231
+ const LIMIT_TIMES_TO = Date.parse('2100-01-01T00:00:00Z');
232
+ const plausibleTime = (ms) => ms >= LIMIT_TIMES_FROM && ms < LIMIT_TIMES_TO;
233
+
234
+ /**
235
+ * @param {State} state
236
+ * @param {{ provider: string, window: string, resetsAtMs: number, percent: number, hitMs?: number }} w
237
+ */
238
+ function addLimit(state, w) {
239
+ let resetsAtMs = Math.floor(w.resetsAtMs / MINUTE_MS) * MINUTE_MS;
240
+ if (!plausibleTime(resetsAtMs) || !/^[a-z0-9_]{1,40}$/.test(w.window)) return;
241
+ if (w.hitMs !== undefined && !plausibleTime(w.hitMs)) return;
242
+ state.limits ??= {};
243
+ let prev;
244
+ for (const [key, l] of Object.entries(state.limits)) {
245
+ const gap = Math.abs(Date.parse(l.resetsAt) - resetsAtMs);
246
+ if (l.provider !== w.provider || l.window !== w.window || gap > RESET_SLACK_MS) continue;
247
+ if (prev && gap >= Math.abs(Date.parse(prev[1].resetsAt) - resetsAtMs)) continue;
248
+ prev = [key, l];
249
+ }
250
+ if (prev) {
251
+ delete state.limits[prev[0]];
252
+ resetsAtMs = Math.min(resetsAtMs, Date.parse(prev[1].resetsAt));
253
+ }
254
+ const hits = [prev?.[1].hitAt && Date.parse(prev[1].hitAt), w.hitMs].filter(Number.isFinite);
255
+ const percent = Math.min(100, Math.max(0, w.percent));
256
+ state.limits[`${w.provider}|${w.window}|${resetsAtMs}`] = {
257
+ provider: w.provider,
258
+ window: w.window,
259
+ resetsAt: new Date(resetsAtMs).toISOString(),
260
+ peakPercent: Math.max(prev?.[1].peakPercent ?? 0, percent),
261
+ ...(hits.length ? { hitAt: new Date(Math.min(...hits)).toISOString() } : {})
262
+ };
263
+ }
264
+
265
+ // Claude Code logs a refused request as a synthetic assistant line carrying quotaLimits.
266
+ // One blocked window repeats on every retry; the key makes the repeats one record.
267
+ function claudeLimit(state, o) {
268
+ const q = o.quotaLimits;
269
+ if (q?.status !== 'rejected' || typeof q.rateLimitType !== 'string') return;
270
+ const ts = Date.parse(o.timestamp);
271
+ if (!Number.isFinite(ts) || !(q.resetsAt > 0)) return;
272
+ addLimit(state, {
273
+ provider: 'claude',
274
+ window: q.rateLimitType
275
+ .toLowerCase()
276
+ .replace(/[^a-z0-9_]/g, '_')
277
+ .slice(0, 40),
278
+ resetsAtMs: q.resetsAt * 1000,
279
+ percent: 100,
280
+ hitMs: ts
281
+ });
282
+ }
283
+
284
+ const CODEX_WINDOW_NAMES = { 300: 'five_hour', 10080: 'seven_day' };
285
+
286
+ // Codex token_count lines carry the account's rate limits; a window is null until it is in use.
287
+ function codexLimits(state, o, rateLimits) {
288
+ const ts = Date.parse(o.timestamp);
289
+ if (!Number.isFinite(ts) || !rateLimits) return;
290
+ for (const slot of ['primary', 'secondary']) {
291
+ const w = rateLimits[slot];
292
+ if (!w || typeof w.used_percent !== 'number') continue;
293
+ const minutes = Number(w.window_minutes);
294
+ const window = CODEX_WINDOW_NAMES[minutes] ?? `${minutes}m`;
295
+ const resetsAtMs =
296
+ typeof w.resets_at === 'number'
297
+ ? w.resets_at * 1000
298
+ : typeof w.resets_in_seconds === 'number'
299
+ ? ts + w.resets_in_seconds * 1000
300
+ : NaN;
301
+ const hit = w.used_percent >= 100;
302
+ addLimit(state, {
303
+ provider: 'codex',
304
+ window,
305
+ resetsAtMs,
306
+ percent: hit ? 100 : w.used_percent,
307
+ ...(hit ? { hitMs: ts } : {})
308
+ });
309
+ }
207
310
  }
208
311
 
209
312
  // ---------------------------------------------------------------------------
@@ -308,7 +411,7 @@ function costOf(entry, tier, t) {
308
411
  // ---------------------------------------------------------------------------
309
412
  // Log discovery + incremental reading
310
413
 
311
- async function* walk(dir) {
414
+ async function* walk(dir, keep) {
312
415
  let entries;
313
416
  try {
314
417
  entries = await readdir(dir, { withFileTypes: true });
@@ -317,8 +420,8 @@ async function* walk(dir) {
317
420
  }
318
421
  for (const e of entries) {
319
422
  const p = join(dir, e.name);
320
- if (e.isDirectory()) yield* walk(p);
321
- else if (e.isFile() && e.name.endsWith('.jsonl')) yield p;
423
+ if (e.isDirectory()) yield* walk(p, keep);
424
+ else if (e.isFile() && keep(e.name)) yield p;
322
425
  }
323
426
  }
324
427
 
@@ -364,6 +467,7 @@ function claudeLineHandler(state, resolvePrice, cutoffMs) {
364
467
  if (!line.includes('"assistant"')) return;
365
468
  const o = parseJson(line);
366
469
  if (!o || o.type !== 'assistant') return;
470
+ if (o.quotaLimits) claudeLimit(state, o);
367
471
  const msg = o.message;
368
472
  const usage = msg?.usage;
369
473
  const model = msg?.model;
@@ -442,7 +546,9 @@ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSess
442
546
  fileState.model = p.model;
443
547
  return;
444
548
  }
445
- if (o.type !== 'event_msg' || p?.type !== 'token_count' || !p.info) return;
549
+ if (o.type !== 'event_msg' || p?.type !== 'token_count') return;
550
+ codexLimits(state, o, p.rate_limits);
551
+ if (!p.info) return;
446
552
  const total = p.info.total_token_usage?.total_tokens;
447
553
  if (typeof total === 'number') {
448
554
  if (total === fileState.lastTotal) return;
@@ -567,7 +673,7 @@ const PI_PRICE_PREFIXES = [
567
673
  ];
568
674
 
569
675
  // Local models can have a file path as their id; only the file name leaves the machine.
570
- const piModel = (model) => {
676
+ const localModelName = (model) => {
571
677
  const isPath =
572
678
  /^([/~.]|[A-Za-z]:)|\\|:\/|\/\//.test(model) ||
573
679
  /\.(gguf|ggml|bin|safetensors|pth?|onnx)$/i.test(model);
@@ -617,7 +723,7 @@ function piLineHandler(state, file, path, resolvePrice, cutoffMs) {
617
723
  if (u.ts < cutoffMs) return;
618
724
  if (state.seen[dedupe] !== undefined) return;
619
725
  state.seen[dedupe] = u.ts;
620
- const model = piModel(u.model);
726
+ const model = localModelName(u.model);
621
727
  addRecord(state, {
622
728
  ts: u.ts,
623
729
  provider: 'pi',
@@ -633,16 +739,100 @@ function piLineHandler(state, file, path, resolvePrice, cutoffMs) {
633
739
  };
634
740
  }
635
741
 
742
+ /** A Grok model id as a snapshot model name: `[grok] ` dropped, a path reduced to its file name. */
743
+ const grokModelName = (raw) => localModelName(raw.replace(/^\[grok\] /, '').trim()) || 'unknown';
744
+
745
+ // Grok Build: a completed turn appends one `turn_completed` line whose usage sums the turn's API
746
+ // requests, split per model in `modelUsage` (top-level usage and the session's current model when
747
+ // that map is missing). inputTokens includes cache reads and cache writes; reasoningTokens is part
748
+ // of outputTokens. The same event can be exported into more than one session, so rows with an
749
+ // eventId are deduplicated by eventId and model, others by their full content within the file.
750
+ function grokLineHandler(state, cutoffMs, path) {
751
+ const sessionDir = basename(dirname(path));
752
+ let currentModel;
753
+ const summaryModel = () => {
754
+ if (currentModel === undefined) {
755
+ try {
756
+ const id = JSON.parse(
757
+ readFileSync(join(dirname(path), 'summary.json'), 'utf8')
758
+ )?.current_model_id;
759
+ currentModel = typeof id === 'string' && id ? id : 'unknown';
760
+ } catch {
761
+ currentModel = 'unknown';
762
+ }
763
+ }
764
+ return currentModel;
765
+ };
766
+ const str = (v) => (typeof v === 'string' && v ? v : undefined);
767
+ // Token counts are integers; ccusage reads anything else as 0, and the schema rejects it.
768
+ const count = (v) => (Number.isInteger(v) ? num(v) : 0);
769
+ return (line) => {
770
+ if (!line.includes('"turn_completed"')) return;
771
+ const o = parseJson(line);
772
+ const p = o?.params;
773
+ const usage = p?.update?.sessionUpdate === 'turn_completed' ? p.update.usage : undefined;
774
+ if (!usage || typeof usage !== 'object') return;
775
+ // agentTimestampMs is milliseconds; the envelope timestamp is Unix seconds.
776
+ const ts = num(p._meta?.agentTimestampMs) || num(o.timestamp) * 1000;
777
+ if (!ts || ts < cutoffMs) return;
778
+ const eventId = str(p._meta?.eventId);
779
+ const session = str(p.sessionId) ?? sessionDir;
780
+ const perModel =
781
+ usage.modelUsage &&
782
+ typeof usage.modelUsage === 'object' &&
783
+ Object.keys(usage.modelUsage).length;
784
+ // Top-level usage is keyed without its model: summary.json can appear or change between
785
+ // runs, and the same event must not count again under the new name.
786
+ const byModel = perModel
787
+ ? Object.entries(usage.modelUsage).map(([raw, u]) => [raw, raw, u])
788
+ : [[summaryModel(), '', usage]];
789
+ for (const [raw, keyModel, u] of byModel) {
790
+ const inputAll = count(u?.inputTokens);
791
+ const cacheRead = Math.min(count(u?.cachedReadTokens), inputAll);
792
+ const cacheWrite = Math.min(count(u?.cacheCreationTokens), inputAll - cacheRead);
793
+ const input = inputAll - cacheRead - cacheWrite;
794
+ const output = count(u?.outputTokens);
795
+ const reasoning = count(u?.reasoningTokens);
796
+ if (!input && !cacheRead && !cacheWrite && !output && !reasoning) continue;
797
+ // Without an eventId, identical rows count once per file, as in ccusage.
798
+ const id = eventId
799
+ ? `${eventId}|${keyModel}`
800
+ : `${path}|${ts}|${raw}|${input}|${output}|${cacheRead}|${cacheWrite}|${reasoning}`;
801
+ const dedupe = `g:${shortHash(id)}`;
802
+ if (state.seen[dedupe] !== undefined) continue;
803
+ state.seen[dedupe] = ts;
804
+ addRecord(state, {
805
+ ts,
806
+ provider: 'grok',
807
+ model: grokModelName(raw),
808
+ // xAI picks the long-context rate per request, and a turn sums several requests, so
809
+ // its total cannot pick a tier. Grok's own costUsdTicks bill such turns at base rate.
810
+ tier: 0,
811
+ session: shortHash(`grok:${session}`),
812
+ input,
813
+ cacheRead,
814
+ cacheWrite5m: cacheWrite,
815
+ cacheWrite1h: 0,
816
+ output
817
+ });
818
+ }
819
+ };
820
+ }
821
+
822
+ const isJsonl = (name) => name.endsWith('.jsonl');
823
+
636
824
  /**
637
- * A reader for JSONL logs that only grow: walks `*.jsonl` under each path and parses only the
638
- * bytes added since the last run. `lines` builds the line handler for one file.
825
+ * A reader for JSONL logs that only grow: walks the files under each path whose name `keep`
826
+ * accepts (any `*.jsonl` by default) and parses only the bytes added since the last run. `lines`
827
+ * builds the line handler for one file.
639
828
  * @param {(ctx: ReadContext, file: FileState, path: string) => (line: string) => void} lines
829
+ * @param {(name: string) => boolean} [keep]
640
830
  */
641
- const jsonlReader = (lines) => async (paths, ctx, provider) => {
831
+ const jsonlReader = (lines, keep) => async (paths, ctx, provider) => {
642
832
  const { state } = ctx;
643
833
  for (const dir of paths) {
644
834
  if (!existsSync(dir)) continue;
645
- for await (const path of walk(dir)) {
835
+ for await (const path of walk(dir, keep ?? isJsonl)) {
646
836
  if (ctx.seenPaths.has(path)) continue;
647
837
  ctx.seenPaths.add(path);
648
838
  let st;
@@ -761,6 +951,17 @@ const SOURCES = {
761
951
  )
762
952
  ];
763
953
  }
954
+ },
955
+ grok: {
956
+ paths: [join(HOME, '.grok', 'sessions')],
957
+ envPaths: () => fromEnv('GROK_HOME', 'sessions'),
958
+ read: jsonlReader(
959
+ (ctx, _file, path) => grokLineHandler(ctx.state, ctx.cutoffMs, path),
960
+ (name) => name === 'updates.jsonl'
961
+ ),
962
+ // Grok Build logs `grok-4.5-build`; LiteLLM prices it as `xai/grok-4.5`.
963
+ priceKeys: (model) =>
964
+ [model, model.replace(/-build$/, '')].flatMap((base) => [base, `xai/${base}`])
764
965
  }
765
966
  };
766
967
 
@@ -787,13 +988,13 @@ const round = (n, d = 6) => Math.round(n * 10 ** d) / 10 ** d;
787
988
  /**
788
989
  * @param {Record<string, Bucket>} buckets
789
990
  * @param {(b: Bucket, provider: string, model: string, tier: number) => Cost} costFor
790
- * @param {{ deviceId: string, pricingSource: string, providers: string[], nowMs: number, coverageStartMs: number }} meta
991
+ * @param {{ deviceId: string, pricingSource: string, providers: string[], nowMs: number, coverageStartMs: number, limits?: Record<string, Limit> }} meta
791
992
  * `providers` names the session counts the snapshot carries.
792
993
  */
793
994
  function buildSnapshot(
794
995
  buckets,
795
996
  costFor,
796
- { deviceId, pricingSource, providers, nowMs, coverageStartMs }
997
+ { deviceId, pricingSource, providers, nowMs, coverageStartMs, limits: windows = {} }
797
998
  ) {
798
999
  const hourlyCutoff = Math.floor((nowMs - HOURLY_DAYS * DAY_MS) / DAY_MS) * DAY_MS;
799
1000
  /** @type {Map<string, any>} */
@@ -892,9 +1093,34 @@ function buildSnapshot(
892
1093
  sessionsTotal: all.size,
893
1094
  sessionCounts: publicCounts
894
1095
  };
1096
+ const limits = Object.values(windows)
1097
+ .filter((w) => Date.parse(w.resetsAt) >= coverageStartMs)
1098
+ .sort(
1099
+ (a, b) =>
1100
+ a.resetsAt.localeCompare(b.resetsAt) ||
1101
+ a.provider.localeCompare(b.provider) ||
1102
+ a.window.localeCompare(b.window)
1103
+ );
1104
+ if (limits.length) snapshot.limits = limits;
895
1105
  return { snapshot, sessions24h };
896
1106
  }
897
1107
 
1108
+ // Local only (never posted), so hit times may be shown to the minute.
1109
+ function limitLines(snapshot, nowMs) {
1110
+ const from = nowMs - 7 * DAY_MS;
1111
+ const hits = new Map();
1112
+ for (const w of snapshot.limits ?? []) {
1113
+ if (!w.hitAt || Date.parse(w.hitAt) < from) continue;
1114
+ const key = `${w.provider} ${w.window}`;
1115
+ hits.set(key, [...(hits.get(key) ?? []), w.hitAt.slice(0, 16).replace('T', ' ')]);
1116
+ }
1117
+ if (!hits.size) return [];
1118
+ return [
1119
+ 'Limits hit, last 7 days (UTC)',
1120
+ ...[...hits].map(([key, times]) => ` ${key.padEnd(24)} ${times.length}x last ${times.at(-1)}`)
1121
+ ];
1122
+ }
1123
+
898
1124
  function printSummary(snapshot, sessions24h, nowMs) {
899
1125
  const from = Math.floor(nowMs / HOUR_MS) * HOUR_MS + HOUR_MS - DAY_MS;
900
1126
  const byModel = new Map();
@@ -934,6 +1160,7 @@ function printSummary(snapshot, sessions24h, nowMs) {
934
1160
  ([m, v]) =>
935
1161
  ` ${m.padEnd(28)} ${usd(v.cost).padStart(10)} ${(v.tokens / 1e6).toFixed(1)}M tok`
936
1162
  ),
1163
+ ...limitLines(snapshot, nowMs),
937
1164
  ...(snapshot.pricingSource === 'cursor'
938
1165
  ? []
939
1166
  : [`Compare with \`bunx ccusage claude daily\` (Claude Code only) for this device.`])
@@ -1136,7 +1363,22 @@ function assertHeaderSafe(secret, name) {
1136
1363
  }
1137
1364
  }
1138
1365
 
1366
+ // The 422 a server without limit support sends: its strict schema names the key it doesn't know.
1367
+ // Any other limits error is a real bug and must not silently drop the windows.
1368
+ const OLD_SERVER_422 = /Unrecognized key.{0,20}limits/;
1369
+
1139
1370
  async function post(snapshot) {
1371
+ try {
1372
+ return await postOnce(snapshot);
1373
+ } catch (err) {
1374
+ if (err.status !== 422 || !snapshot.limits || !OLD_SERVER_422.test(err.message)) throw err;
1375
+ log('warning: the server is too old to store limit data; sending usage without it');
1376
+ const { limits, ...usageOnly } = snapshot;
1377
+ return await postOnce(usageOnly);
1378
+ }
1379
+ }
1380
+
1381
+ async function postOnce(snapshot) {
1140
1382
  const url = setting('INGEST_URL');
1141
1383
  const token = setting('INGEST_TOKEN').trim();
1142
1384
  if (!url || !token) {
@@ -1165,7 +1407,7 @@ async function post(snapshot) {
1165
1407
  );
1166
1408
  return parseJson(reply)?.result;
1167
1409
  }
1168
- lastErr = new Error(`HTTP ${res.status}: ${text}`);
1410
+ lastErr = Object.assign(new Error(`HTTP ${res.status}: ${text}`), { status: res.status });
1169
1411
  // Client errors other than rate limiting won't fix themselves.
1170
1412
  if (res.status >= 400 && res.status < 500 && res.status !== 429) break;
1171
1413
  } catch (err) {
@@ -1224,7 +1466,8 @@ async function main() {
1224
1466
  (p) => p === 'claude' || p === 'codex' || used.has(p)
1225
1467
  ),
1226
1468
  nowMs,
1227
- coverageStartMs
1469
+ coverageStartMs,
1470
+ limits: state.limits
1228
1471
  }
1229
1472
  );
1230
1473
  if (SUMMARY_ONLY) {
package/dist/history.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { mergeLimits } from './limits.js';
1
2
  import { MAX_ROWS, usageRowSchema } from './schema.js';
2
3
  const DAY_MS = 86_400_000;
3
4
  const round = (n) => Math.round(n * 1e6) / 1e6;
@@ -62,8 +63,11 @@ function dropOldestDays(rows, excess) {
62
63
  }
63
64
  export function mergeSnapshots(stored, next) {
64
65
  const fresh = [...next.hourly].sort(compareRows);
66
+ const limits = mergeLimits(stored?.limits, next.limits);
67
+ const withLimits = limits.length ? { limits } : {};
68
+ const { limits: _, ...rest } = next;
65
69
  if (!stored)
66
- return { snapshot: { ...next, hourly: fresh }, droppedDays: 0 };
70
+ return { snapshot: { ...rest, hourly: fresh, ...withLimits }, droppedDays: 0 };
67
71
  const reported = new Set(fresh.map(keyOf));
68
72
  const kept = [...group(stored.hourly)]
69
73
  .filter(([key]) => !reported.has(key))
@@ -81,5 +85,5 @@ export function mergeSnapshots(stored, next) {
81
85
  if (latest > Date.parse(coverage))
82
86
  coverage = new Date(latest).toISOString();
83
87
  }
84
- return { snapshot: { ...next, coverageStart: coverage, hourly }, droppedDays };
88
+ return { snapshot: { ...rest, coverageStart: coverage, hourly, ...withLimits }, droppedDays };
85
89
  }
@@ -0,0 +1,48 @@
1
+ import { type LimitWindow, type UsageProvider, type UsageSnapshot } from './schema.ts';
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
6
+ * and one account's window reported by two devices counts once. Sorted by reset time; past the
7
+ * cap the oldest are dropped.
8
+ */
9
+ export declare function mergeLimits(...lists: (LimitWindow[] | undefined)[]): LimitWindow[];
10
+ export type LimitsSeries = {
11
+ hits: number[];
12
+ lockedHours: number[];
13
+ peakPercent: (number | null)[];
14
+ };
15
+ export type LimitWindowSummary = {
16
+ window: string;
17
+ /** Window instances seen in range, after de-duplicating across devices. */
18
+ observed: number;
19
+ /**
20
+ * Lockouts: instances where a request was blocked. A block before the previous lockout's reset
21
+ * extends that lockout (the provider moved its reset) instead of counting again.
22
+ */
23
+ hit: number;
24
+ /** Hours from the first block of each lockout to its last reset. */
25
+ lockedHours: number;
26
+ /** UTC day (YYYY-MM-DD) of the latest hit. */
27
+ lastHit: string | null;
28
+ /**
29
+ * One entry per UTC day from `from` to `to`. An instance belongs to the day of its first
30
+ * block, or of its reset when it was never blocked; a window still open belongs to today.
31
+ */
32
+ series: LimitsSeries;
33
+ };
34
+ export type LimitsSummary = {
35
+ generatedAt: string;
36
+ from: string;
37
+ to: string;
38
+ bucket: 'day';
39
+ providers: {
40
+ provider: UsageProvider;
41
+ windows: LimitWindowSummary[];
42
+ }[];
43
+ };
44
+ /**
45
+ * Limit hits over the last 90 UTC days, ending at the end of today (the 90d range window).
46
+ * Nothing finer than a UTC day is published and no device is named.
47
+ */
48
+ export declare function summarizeLimits(snapshots: UsageSnapshot[], now: number): LimitsSummary;
package/dist/limits.js ADDED
@@ -0,0 +1,140 @@
1
+ // Subscription usage-limit windows: merging them across reports and devices, and the public
2
+ // summary. Pure functions (no I/O).
3
+ import { MAX_LIMIT_WINDOWS, PROVIDERS } from './schema.js';
4
+ const MINUTE_MS = 60_000;
5
+ const HOUR_MS = 3_600_000;
6
+ const DAY_MS = 86_400_000;
7
+ const RANGE_DAYS = 90;
8
+ const minuteOf = (iso) => Math.floor(Date.parse(iso) / MINUTE_MS) * MINUTE_MS;
9
+ // Reports of one window can put its reset seconds apart, across a minute boundary.
10
+ const RESET_SLACK_MS = 2 * MINUTE_MS;
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
15
+ * and one account's window reported by two devices counts once. Sorted by reset time; past the
16
+ * cap the oldest are dropped.
17
+ */
18
+ 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),
48
+ ...(hitAt ? { hitAt } : {})
49
+ };
50
+ }
51
+ const sorted = merged.sort((a, b) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt) ||
52
+ a.provider.localeCompare(b.provider) ||
53
+ a.window.localeCompare(b.window));
54
+ return sorted.slice(Math.max(0, sorted.length - MAX_LIMIT_WINDOWS));
55
+ }
56
+ const KNOWN_ORDER = ['five_hour', 'seven_day'];
57
+ const rank = (w) => {
58
+ const i = KNOWN_ORDER.indexOf(w);
59
+ return i === -1 ? KNOWN_ORDER.length : i;
60
+ };
61
+ const tenth = (n) => Math.round(n * 10) / 10;
62
+ /**
63
+ * Limit hits over the last 90 UTC days, ending at the end of today (the 90d range window).
64
+ * Nothing finer than a UTC day is published and no device is named.
65
+ */
66
+ export function summarizeLimits(snapshots, now) {
67
+ const to = Math.floor(now / DAY_MS) * DAY_MS + DAY_MS;
68
+ const from = to - RANGE_DAYS * DAY_MS;
69
+ const windows = mergeLimits(...snapshots.map((s) => s.limits));
70
+ const anchor = (w) => Math.min(Date.parse(w.hitAt ?? w.resetsAt), now);
71
+ const providers = PROVIDERS.flatMap((provider) => {
72
+ const byWindow = new Map();
73
+ for (const w of windows) {
74
+ if (w.provider !== provider)
75
+ continue;
76
+ if (anchor(w) < from || anchor(w) >= to)
77
+ continue;
78
+ byWindow.set(w.window, [...(byWindow.get(w.window) ?? []), w]);
79
+ }
80
+ const summaries = [...byWindow]
81
+ .sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
82
+ .map(([window, list]) => {
83
+ const series = {
84
+ hits: Array(RANGE_DAYS).fill(0),
85
+ lockedHours: Array(RANGE_DAYS).fill(0),
86
+ peakPercent: Array(RANGE_DAYS).fill(null)
87
+ };
88
+ let lastHit = null;
89
+ let hit = 0;
90
+ let locked = 0;
91
+ let absorbed = 0;
92
+ // The lockout in progress: its day, and when it ends so far.
93
+ let lockout;
94
+ const byHit = list.sort((a, b) => Date.parse(a.hitAt ?? a.resetsAt) - Date.parse(b.hitAt ?? b.resetsAt));
95
+ for (const w of byHit) {
96
+ const day = Math.floor((anchor(w) - from) / DAY_MS);
97
+ series.peakPercent[day] = Math.max(series.peakPercent[day] ?? 0, w.peakPercent);
98
+ if (!w.hitAt)
99
+ continue;
100
+ const hitMs = Date.parse(w.hitAt);
101
+ const resetMs = Date.parse(w.resetsAt);
102
+ lastHit = Math.max(lastHit ?? 0, hitMs);
103
+ // A provider can move the reset of a window while it is blocked (Claude does: a
104
+ // refusal at 20:46 said 00:20, one at 22:23 said 01:40). A hit before the current
105
+ // lockout ends is that lockout running longer, not a second one.
106
+ if (lockout && hitMs < lockout.endMs) {
107
+ absorbed++;
108
+ const extra = Math.max(0, resetMs - lockout.endMs) / HOUR_MS;
109
+ lockout.endMs = Math.max(lockout.endMs, resetMs);
110
+ locked += extra;
111
+ series.lockedHours[lockout.day] += extra;
112
+ continue;
113
+ }
114
+ const hours = Math.max(0, resetMs - hitMs) / HOUR_MS;
115
+ lockout = { day, endMs: resetMs };
116
+ hit++;
117
+ locked += hours;
118
+ series.hits[day]++;
119
+ series.lockedHours[day] += hours;
120
+ }
121
+ series.lockedHours = series.lockedHours.map(tenth);
122
+ return {
123
+ window,
124
+ observed: list.length - absorbed,
125
+ hit,
126
+ lockedHours: tenth(locked),
127
+ lastHit: lastHit === null ? null : new Date(lastHit).toISOString().slice(0, 10),
128
+ series
129
+ };
130
+ });
131
+ return summaries.length ? [{ provider, windows: summaries }] : [];
132
+ });
133
+ return {
134
+ generatedAt: new Date(now).toISOString(),
135
+ from: new Date(from).toISOString(),
136
+ to: new Date(to).toISOString(),
137
+ bucket: 'day',
138
+ providers
139
+ };
140
+ }
package/dist/page.d.ts CHANGED
@@ -1,2 +1,3 @@
1
+ import type { LimitsSummary } from './limits.ts';
1
2
  import type { UsageSummary } from './summary.ts';
2
- export declare function renderPage(summary: UsageSummary): string;
3
+ export declare function renderPage(summary: UsageSummary, limits?: LimitsSummary): string;
package/dist/page.js CHANGED
@@ -38,6 +38,9 @@ th { color: var(--muted); font-weight: 500; font-size: 0.85rem; }
38
38
  .swatch { display: inline-block; width: 0.75rem; height: 0.75rem; margin-right: 0.5rem; border-radius: 50%; vertical-align: -0.05em; }
39
39
  .scroll { overflow-x: auto; }
40
40
  .empty { color: var(--muted); }
41
+ .days td, .days th { padding: 0.35rem 0.25rem; font-size: 0.8rem; text-align: center; }
42
+ .days td:first-child, .days th:first-child { padding-right: 0.75rem; text-align: left; }
43
+ .days .hit { color: #c0392b; font-weight: 600; }
41
44
  `;
42
45
  function totalsCard(r) {
43
46
  return `<section class="card"><h3>${LABELS[r.range]}</h3>
@@ -67,7 +70,31 @@ function modelsTable(r) {
67
70
  .map((m) => `<tr><td>${escapeHtml(m.model)}</td><td>${escapeHtml(m.provider)}</td><td>${usd(m.cost)}</td><td>${percent(m.share)}</td><td>${tokens(m.tokens)}</td></tr>`);
68
71
  return `<div class="scroll"><table><thead><tr><th>Model</th><th>Agent</th><th>Cost</th><th>Share</th><th>Tokens</th></tr></thead><tbody>${rows.join('')}</tbody></table></div>`;
69
72
  }
70
- export function renderPage(summary) {
73
+ const WINDOW_LABELS = {
74
+ five_hour: '5-hour session',
75
+ seven_day: 'Weekly'
76
+ };
77
+ const windowLabel = (w) => WINDOW_LABELS[w] ??
78
+ (w.startsWith('seven_day_') ? `Weekly · ${w.slice(10)}` : w).replace(/_/g, ' ');
79
+ const RECENT_DAYS = 14;
80
+ function limitsSection(limits) {
81
+ const rows = limits.providers.flatMap((p) => p.windows.map((w) => ({ provider: p.provider, w })));
82
+ if (!rows.length)
83
+ return '<p class="empty">No usage limit windows recorded in the last 90 days.</p>';
84
+ const totals = rows.map(({ provider, w }) => `<tr><td>${escapeHtml(provider)} · ${escapeHtml(windowLabel(w.window))}</td><td>${w.observed}</td><td>${w.hit}</td><td>${w.lockedHours.toFixed(1)}</td><td>${w.lastHit ?? '-'}</td></tr>`);
85
+ const first = Date.parse(limits.to) - RECENT_DAYS * 86_400_000;
86
+ const heads = Array.from({ length: RECENT_DAYS }, (_, i) => new Date(first + i * 86_400_000).toISOString().slice(8, 10));
87
+ const days = rows.map(({ provider, w }) => {
88
+ const cells = w.series.hits
89
+ .slice(-RECENT_DAYS)
90
+ .map((n) => (n ? `<td class="hit">${n}</td>` : '<td>·</td>'));
91
+ return `<tr><td>${escapeHtml(provider)} · ${escapeHtml(windowLabel(w.window))}</td>${cells.join('')}</tr>`;
92
+ });
93
+ return `<div class="scroll"><table><thead><tr><th>Window</th><th>Seen</th><th>Hit</th><th>Locked hours</th><th>Last hit</th></tr></thead><tbody>${totals.join('')}</tbody></table></div>
94
+ <p class="sub">Hits per day, last ${RECENT_DAYS} days (UTC day of month)</p>
95
+ <div class="scroll"><table class="days"><thead><tr><th>Window</th>${heads.map((d) => `<th>${d}</th>`).join('')}</tr></thead><tbody>${days.join('')}</tbody></table></div>`;
96
+ }
97
+ export function renderPage(summary, limits) {
71
98
  const updated = escapeHtml(summary.generatedAt);
72
99
  return `<!doctype html>
73
100
  <html lang="en">
@@ -86,7 +113,7 @@ export function renderPage(summary) {
86
113
  ${devicesTable(summary)}
87
114
  <h2>Top models, last 30 days</h2>
88
115
  ${modelsTable(summary.ranges['30d'])}
89
- </main>
116
+ ${limits ? `<h2>Usage limits, last 90 days</h2>\n${limitsSection(limits)}\n` : ''}</main>
90
117
  </body>
91
118
  </html>
92
119
  `;
package/dist/push.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { type Context } from './context.ts';
2
- export declare const PUSH_USAGE = "Usage: big-spender push <device> [--dry-run] [--url <ingest url>]\n\nOne-off push from a machine without a schedule. Builds the snapshot, shows what it would publish\nand stops if a model name looks like a cloud resource id (for example a Bedrock inference-profile\nARN, which contains an account id). Asks before sending. The URL comes from --url,\nBIG_SPENDER_INGEST_URL or a prompt, and the token from BIG_SPENDER_INGEST_TOKEN or a hidden\nprompt, so neither is written to this machine. Nothing is scheduled.\n\n--dry-run prints the overview, writes the exact JSON that would be sent to\n$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the\ncollector's local state in ~/.cache/big-spender (which logs were read), never anything remote.\nCursor usage is not part of a push: only the scheduled collector sends it.";
2
+ export declare const PUSH_USAGE = "Usage: big-spender push <device> [--dry-run] [--url <ingest url>]\n\nOne-off push from a machine without a schedule. Builds the snapshot, shows what it would publish\nand stops if a model name looks like a cloud resource id (for example a Bedrock inference-profile\nARN, which contains an account id). Asks before sending. The URL comes from --url,\nBIG_SPENDER_INGEST_URL or a prompt, and the token from BIG_SPENDER_INGEST_TOKEN or a hidden\nprompt, so neither is written to this machine. Nothing is scheduled.\n\n--dry-run prints the overview, writes the exact JSON that would be sent to\n$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the\ncollector's local state in ~/.cache/big-spender (which logs were read), never anything remote.\nA server too old to store usage-limit windows gets the snapshot again without them.\nCursor usage is not part of a push: only the scheduled collector sends it.";
3
3
  export declare function push(args: string[], ctx: Context): Promise<number>;
package/dist/push.js CHANGED
@@ -17,6 +17,7 @@ prompt, so neither is written to this machine. Nothing is scheduled.
17
17
  --dry-run prints the overview, writes the exact JSON that would be sent to
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
+ A server too old to store usage-limit windows gets the snapshot again without them.
20
21
  Cursor usage is not part of a push: only the scheduled collector sends it.`;
21
22
  const MAX_SNAPSHOT_BYTES = 512 * 1024 * 1024;
22
23
  const POST_ATTEMPTS = 4;
@@ -59,7 +60,13 @@ function overview(snapshot, gzipped) {
59
60
  '',
60
61
  ` ${'provider model'.padEnd(width)} ${'tokens'.padStart(10)} ${'cost'.padStart(10)}`,
61
62
  ...rows.map(([k, m]) => line(k, m.tokens, m.cost)),
62
- line('total', tokens, cost)
63
+ line('total', tokens, cost),
64
+ ...(snapshot.limits
65
+ ? [
66
+ '',
67
+ `${snapshot.limits.length} usage-limit windows (name, reset time, peak percent, first block time) are published too.`
68
+ ]
69
+ : [])
63
70
  ];
64
71
  }
65
72
  export async function push(args, ctx) {
@@ -120,8 +127,23 @@ export async function push(args, ctx) {
120
127
  if (!/^[\x21-\x7e]+$/.test(token)) {
121
128
  throw new Error('the ingest token contains characters that are not allowed in an HTTP header; check it for spaces or a stray newline');
122
129
  }
123
- const result = await send(ctx, url, token, body);
124
- ctx.out(`posted ${snapshot.hourly.length} rows (${body.length} bytes gzipped): ${result}`);
130
+ let sent = body;
131
+ let result;
132
+ try {
133
+ result = await send(ctx, url, token, body);
134
+ }
135
+ catch (err) {
136
+ // A server from before limits existed rejects the unknown key with a 422 naming it. Any
137
+ // other limits error is a real bug and must not silently drop the windows.
138
+ const message = err instanceof Error ? err.message : '';
139
+ if (!snapshot.limits || !/^HTTP 422\b.*Unrecognized key.{0,20}limits/.test(message))
140
+ throw err;
141
+ ctx.err('warning: the server is too old to store limit data; sending usage without it');
142
+ const { limits: _, ...usageOnly } = snapshot;
143
+ sent = gzipSync(JSON.stringify(usageOnly));
144
+ result = await send(ctx, url, token, sent);
145
+ }
146
+ ctx.out(`posted ${snapshot.hourly.length} rows (${sent.length} bytes gzipped): ${result}`);
125
147
  return 0;
126
148
  }
127
149
  /** POSTs the reviewed bytes with the collector's retry policy and returns the server's reply. */
package/dist/schema.d.ts CHANGED
@@ -3,7 +3,7 @@ export declare const EARLIEST_DATE = "2020-01-01T00:00:00Z";
3
3
  export declare const MAX_ROWS = 50000;
4
4
  export declare const DEVICE_ID: RegExp;
5
5
  export declare const CURSOR_DEVICE_ID = "cursor";
6
- export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi'];
6
+ export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi', 'grok'];
7
7
  export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
8
8
  export declare const usageRowSchema: z.ZodObject<{
9
9
  hour: z.ZodISODateTime;
@@ -15,6 +15,7 @@ export declare const usageRowSchema: z.ZodObject<{
15
15
  claude: "claude";
16
16
  codex: "codex";
17
17
  cursor: "cursor";
18
+ grok: "grok";
18
19
  pi: "pi";
19
20
  }>;
20
21
  model: z.ZodString;
@@ -32,6 +33,20 @@ export declare const usageRowSchema: z.ZodObject<{
32
33
  }, z.core.$strict>;
33
34
  cacheSavingsUsd: z.ZodNumber;
34
35
  }, z.core.$strict>;
36
+ export declare const MAX_LIMIT_WINDOWS = 5000;
37
+ export declare const limitWindowSchema: z.ZodObject<{
38
+ provider: z.ZodEnum<{
39
+ claude: "claude";
40
+ codex: "codex";
41
+ cursor: "cursor";
42
+ grok: "grok";
43
+ pi: "pi";
44
+ }>;
45
+ window: z.ZodString;
46
+ resetsAt: z.ZodISODateTime;
47
+ peakPercent: z.ZodNumber;
48
+ hitAt: z.ZodOptional<z.ZodISODateTime>;
49
+ }, z.core.$strict>;
35
50
  export declare const usageSnapshotSchema: z.ZodObject<{
36
51
  schemaVersion: z.ZodLiteral<1>;
37
52
  deviceId: z.ZodString;
@@ -48,6 +63,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
48
63
  claude: "claude";
49
64
  codex: "codex";
50
65
  cursor: "cursor";
66
+ grok: "grok";
51
67
  pi: "pi";
52
68
  }>;
53
69
  model: z.ZodString;
@@ -72,6 +88,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
72
88
  codex: z.ZodNumber;
73
89
  all: z.ZodNumber;
74
90
  cursor: z.ZodOptional<z.ZodNumber>;
91
+ grok: z.ZodOptional<z.ZodNumber>;
75
92
  pi: z.ZodOptional<z.ZodNumber>;
76
93
  }, z.core.$strict>>;
77
94
  '7d': z.ZodObject<{
@@ -79,6 +96,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
79
96
  codex: z.ZodNumber;
80
97
  all: z.ZodNumber;
81
98
  cursor: z.ZodOptional<z.ZodNumber>;
99
+ grok: z.ZodOptional<z.ZodNumber>;
82
100
  pi: z.ZodOptional<z.ZodNumber>;
83
101
  }, z.core.$strict>;
84
102
  '30d': z.ZodObject<{
@@ -86,6 +104,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
86
104
  codex: z.ZodNumber;
87
105
  all: z.ZodNumber;
88
106
  cursor: z.ZodOptional<z.ZodNumber>;
107
+ grok: z.ZodOptional<z.ZodNumber>;
89
108
  pi: z.ZodOptional<z.ZodNumber>;
90
109
  }, z.core.$strict>;
91
110
  '90d': z.ZodObject<{
@@ -93,10 +112,25 @@ export declare const usageSnapshotSchema: z.ZodObject<{
93
112
  codex: z.ZodNumber;
94
113
  all: z.ZodNumber;
95
114
  cursor: z.ZodOptional<z.ZodNumber>;
115
+ grok: z.ZodOptional<z.ZodNumber>;
96
116
  pi: z.ZodOptional<z.ZodNumber>;
97
117
  }, z.core.$strict>;
98
118
  }, z.core.$strict>>;
119
+ limits: z.ZodOptional<z.ZodArray<z.ZodObject<{
120
+ provider: z.ZodEnum<{
121
+ claude: "claude";
122
+ codex: "codex";
123
+ cursor: "cursor";
124
+ grok: "grok";
125
+ pi: "pi";
126
+ }>;
127
+ window: z.ZodString;
128
+ resetsAt: z.ZodISODateTime;
129
+ peakPercent: z.ZodNumber;
130
+ hitAt: z.ZodOptional<z.ZodISODateTime>;
131
+ }, z.core.$strict>>>;
99
132
  }, z.core.$strict>;
133
+ export type LimitWindow = z.infer<typeof limitWindowSchema>;
100
134
  export type UsageRow = z.infer<typeof usageRowSchema>;
101
135
  export type UsageSnapshot = z.infer<typeof usageSnapshotSchema>;
102
136
  export type UsageProvider = (typeof PROVIDERS)[number];
package/dist/schema.js CHANGED
@@ -14,7 +14,7 @@ export const MAX_ROWS = 50_000;
14
14
  export const DEVICE_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
15
15
  // Collectors send the Cursor account's usage under this id, so no machine may use it.
16
16
  export const CURSOR_DEVICE_ID = 'cursor';
17
- export const PROVIDERS = ['claude', 'codex', 'cursor', 'pi'];
17
+ export const PROVIDERS = ['claude', 'codex', 'cursor', 'pi', 'grok'];
18
18
  // Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
19
19
  // than a day: an hourly view would show when each machine is in use.
20
20
  export const RANGES = ['7d', '30d', '90d', 'all'];
@@ -36,6 +36,20 @@ export const usageRowSchema = z.strictObject({
36
36
  costUsd: z.strictObject({ input: usd, cacheRead: usd, cacheWrite: usd, output: usd }),
37
37
  cacheSavingsUsd: usd
38
38
  });
39
+ export const MAX_LIMIT_WINDOWS = 5_000;
40
+ // One subscription usage window (the 5-hour session, the weekly cap, ...) as it was observed.
41
+ // A window instance is identified by (provider, window, resetsAt rounded down to the minute).
42
+ export const limitWindowSchema = z.strictObject({
43
+ provider: z.enum(PROVIDERS),
44
+ // five_hour, seven_day, seven_day_opus, ...; Codex windows are named from window_minutes
45
+ // (300 -> five_hour, 10080 -> seven_day, otherwise `${minutes}m`).
46
+ window: z.string().regex(/^[a-z0-9_]{1,40}$/),
47
+ resetsAt: isoDate,
48
+ // Highest share of the window seen used, 0-100. A blocked request means 100.
49
+ peakPercent: z.number().min(0).max(100),
50
+ // First time a request was refused because this window was used up.
51
+ hitAt: isoDate.optional()
52
+ });
39
53
  const count = z.number().int().nonnegative();
40
54
  const sessionCount = z.strictObject({
41
55
  ...Object.fromEntries(PROVIDERS.map((p) => [p, count.optional()])),
@@ -63,5 +77,6 @@ export const usageSnapshotSchema = z.strictObject({
63
77
  '30d': sessionCount,
64
78
  '90d': sessionCount
65
79
  })
66
- .optional()
80
+ .optional(),
81
+ limits: z.array(limitWindowSchema).max(MAX_LIMIT_WINDOWS).optional()
67
82
  });
package/dist/serve.js CHANGED
@@ -63,9 +63,15 @@ const routes = {
63
63
  headers: { 'cache-control': 'public, max-age=300, stale-while-revalidate=900' }
64
64
  })
65
65
  },
66
+ '/api/usage/limits': {
67
+ methods: ['GET', 'HEAD'],
68
+ handle: async (bs) => Response.json(await bs.limits(), {
69
+ headers: { 'cache-control': 'public, max-age=300, stale-while-revalidate=900' }
70
+ })
71
+ },
66
72
  '/': {
67
73
  methods: ['GET', 'HEAD'],
68
- handle: async (bs) => new Response(renderPage(await bs.summary()), {
74
+ handle: async (bs) => new Response(renderPage(await bs.summary(), await bs.limits()), {
69
75
  headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' }
70
76
  })
71
77
  },
@@ -1,6 +1,8 @@
1
1
  import type { DeviceConfig } from '../devices.ts';
2
+ import { type LimitsSummary } from '../limits.ts';
2
3
  import { type UsageSummary } from '../summary.ts';
3
- export { DEVICE_ID, PROVIDERS, RANGES, usageRowSchema, usageSnapshotSchema, type UsageProvider, type UsageRange, type UsageRow, type UsageSnapshot } from '../schema.ts';
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';
4
6
  export { OTHER, PALETTE, resolveDevices, type DeviceConfig, type DeviceInfo } from '../devices.ts';
5
7
  export { summarize, type Bucket, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
6
8
  export type BigSpenderOptions = {
@@ -15,5 +17,7 @@ export type BigSpender = {
15
17
  ingest(request: Request): Promise<Response>;
16
18
  /** Merged totals for every range, recomputed at most every few minutes or after an ingest. */
17
19
  summary(now?: number): Promise<UsageSummary>;
20
+ /** Subscription limit hits over the last 90 UTC days, cached like `summary`. */
21
+ limits(now?: number): Promise<LimitsSummary>;
18
22
  };
19
23
  export declare function createBigSpender({ dataDir, ingestToken, devices }: BigSpenderOptions): BigSpender;
@@ -1,19 +1,23 @@
1
1
  import { fileStore } from '../store.js';
2
+ import { summarizeLimits } from '../limits.js';
2
3
  import { summarize } from '../summary.js';
3
4
  import { createIngest } from './ingest.js';
4
- export { DEVICE_ID, PROVIDERS, RANGES, usageRowSchema, usageSnapshotSchema } from '../schema.js';
5
+ export { DEVICE_ID, MAX_LIMIT_WINDOWS, PROVIDERS, RANGES, limitWindowSchema, usageRowSchema, usageSnapshotSchema } from '../schema.js';
6
+ export { summarizeLimits } from '../limits.js';
5
7
  export { OTHER, PALETTE, resolveDevices } from '../devices.js';
6
8
  export { summarize } from '../summary.js';
7
9
  const SUMMARY_TTL_MS = 5 * 60 * 1000;
8
10
  export function createBigSpender({ dataDir, ingestToken, devices }) {
9
11
  const store = fileStore(dataDir);
10
12
  let cache = null;
13
+ let limitsCache = null;
11
14
  return {
12
15
  ingest: createIngest({
13
16
  store,
14
17
  token: ingestToken,
15
18
  onStored: () => {
16
19
  cache = null;
20
+ limitsCache = null;
17
21
  }
18
22
  }),
19
23
  async summary(now = Date.now()) {
@@ -22,6 +26,13 @@ export function createBigSpender({ dataDir, ingestToken, devices }) {
22
26
  const value = summarize(await store.list(), now, devices);
23
27
  cache = { value, computedAt: now };
24
28
  return value;
29
+ },
30
+ async limits(now = Date.now()) {
31
+ if (limitsCache && now - limitsCache.computedAt < SUMMARY_TTL_MS)
32
+ return limitsCache.value;
33
+ const value = summarizeLimits(await store.list(), now);
34
+ limitsCache = { value, computedAt: now };
35
+ return value;
25
36
  }
26
37
  };
27
38
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "big-spender",
3
- "version": "0.5.0",
3
+ "version": "0.7.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",