big-spender 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -149,13 +149,14 @@ Cursor.
149
149
 
150
150
  `big-spender serve` is a small `node:http` server:
151
151
 
152
- | Route | What it does |
153
- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
154
- | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
155
- | `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
156
- | `GET /api/usage/limits` | Subscription limit hits per provider and window over the last 90 UTC days, per day, same cache header. See [Usage limits](#usage-limits). |
157
- | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models, limit hits. No JavaScript, no external assets, light and dark. |
158
- | `GET /healthz` | `ok`, for load balancers and Docker. |
152
+ | Route | What it does |
153
+ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
154
+ | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
155
+ | `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
156
+ | `GET /api/usage/limits` | Subscription limit hits per provider and window over the last 90 UTC days, per day, same cache header. See [Usage limits](#usage-limits). |
157
+ | `GET /api/usage/limits/hits` | Admin only: bearer `BIG_SPENDER_ADMIN_TOKEN`. Every recorded limit hit with its exact time and the device ids that saw it, earliest first. `cache-control: no-store`. See [Usage limits](#usage-limits). |
158
+ | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models, limit hits. No JavaScript, no external assets, light and dark. |
159
+ | `GET /healthz` | `ok`, for load balancers and Docker. |
159
160
 
160
161
  Configuration comes from flags or environment variables (flags win):
161
162
 
@@ -166,6 +167,7 @@ Configuration comes from flags or environment variables (flags win):
166
167
  | `--data` | `BIG_SPENDER_DATA_DIR` | `./data` (`/data` in the Docker image) |
167
168
  | `--devices` | `BIG_SPENDER_DEVICES_FILE` | none: `{ "devices": {}, "unknownDevices": "by-id" }` |
168
169
  | | `BIG_SPENDER_INGEST_TOKEN` | none: ingest is off and answers `503` |
170
+ | | `BIG_SPENDER_ADMIN_TOKEN` | none: the hits endpoint is off and answers `503` |
169
171
 
170
172
  The data directory holds one `<device>.json` file per device, written atomically. Put it on a
171
173
  persistent volume. Each snapshot is merged into the device's stored history. A day the snapshot
@@ -232,7 +234,7 @@ export const GET = async ({ setHeaders }) => {
232
234
  Hono is the same shape (`app.post('/api/usage/ingest', (c) => bs.ingest(c.req.raw))`), and so is a
233
235
  Next.js route handler (`export const POST = (request: Request) => bs.ingest(request)`).
234
236
 
235
- `createBigSpender({ dataDir, ingestToken, devices })` returns:
237
+ `createBigSpender({ dataDir, ingestToken, adminToken?, devices })` returns:
236
238
 
237
239
  - `ingest(request)`: handles a collector's `POST` and returns a `Response` (`503` when
238
240
  `ingestToken` is missing or empty, `401`, `413`, `415`, `422`, or `200` with
@@ -240,8 +242,9 @@ Next.js route handler (`export const POST = (request: Request) => bs.ingest(requ
240
242
  - `summary(now?)`: the merged totals for every range. The result is cached for five minutes and
241
243
  recomputed right after an ingest.
242
244
  - `limits(now?)`: the [usage limit](#usage-limits) summary, cached the same way.
245
+ - `limitHits(request)`: the admin-only hit list as a `Response`. It answers `503` when `adminToken` is missing, empty or equal to `ingestToken`, `401` for a wrong bearer token, and `200` with `cache-control: no-store`. It is computed fresh on each call.
243
246
 
244
- The module also exports `summarize(snapshots, now, config)`, `summarizeLimits(snapshots, now)`, the
247
+ The module also exports `summarize(snapshots, now, config)`, `summarizeLimits(snapshots, now)`, `limitHits(snapshots, now)`, the
245
248
  snapshot schema (`usageSnapshotSchema`, `limitWindowSchema`, `MAX_LIMIT_WINDOWS`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
246
249
  own storage or charts.
247
250
 
@@ -288,6 +291,13 @@ finer than a UTC day, no device names, no report times. It is separate from `/ap
288
291
  shape did not change. `big-spender status` also lists the limits hit in the last 7 days, to the
289
292
  minute, because that output never leaves the machine.
290
293
 
294
+ `GET /api/usage/limits/hits` is the admin view. It needs `Authorization: Bearer <BIG_SPENDER_ADMIN_TOKEN>`
295
+ and returns every recorded hit with its exact `hitAt`, the window's reset and the devices that saw it,
296
+ earliest first. The public endpoint stays day-level with no devices. The admin token must differ from
297
+ the ingest token, because every collector machine holds that one. A hit found by polling carries the
298
+ poll time, not the exact refusal time. Two devices that show the same `hitAt` to the millisecond read
299
+ the same log line.
300
+
291
301
  ### Polling usage endpoints
292
302
 
293
303
  Logs only show a limit when a request is refused, which hides how much of a window you leave
@@ -364,8 +374,8 @@ about 15 to 20 percent less.
364
374
  | 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. |
365
375
  | 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. |
366
376
  | GitHub Copilot CLI (experimental) | `~/.copilot/session-state/*/events.jsonl`, `$COPILOT_HOME/session-state` | Experimental: so far compared with ccusage only on a few sessions from one machine and on ccusage's test fixtures, not on regular use. `session.usage_record` events (one per model call). Older versions log only `session.shutdown`; its cumulative `modelMetrics` count as the growth since the previous shutdown, and only when no per-call record came in that interval. `inputTokens` includes cache reads and writes, so input counts uncached tokens only. Reasoning is part of `outputTokens`. A `-1m` or `-1m-internal` model suffix is dropped. Only the top-level `events.jsonl` of each session is read, not the OpenTelemetry export or `session-store.db`. |
367
- | Antigravity (experimental) | `~/.gemini/antigravity*/conversations/**/*.db`, `~/.config/antigravity/conversations` | **Experimental:** read only with `BIG_SPENDER_EXPERIMENTAL=antigravity`; checked against ccusage on test fixtures, not yet against real Antigravity data. `antigravity*` is `antigravity` and its `-cli`, `-ide`, `-backup` and `-acp` variants; `$ANTIGRAVITY_DATA_DIR` (comma-separated) is read too. Read with `node:sqlite` (Node 22.13+, else skipped with a warning). Usage messages in `gen_metadata` and `steps`, retries included; copies sharing a response, provider or message id merge and keep the largest counts. A later copy can move a response to another day or model; the day and model it left are sent as a zero row, which takes them back on the server. A model name with a slash (possibly a path) becomes `gemini-internal-model`. Reasoning is part of output. |
368
- | Gemini CLI (experimental) | `~/.gemini/tmp/**/*.json` and `*.jsonl`, `$GEMINI_DATA_DIR` (comma-separated) | **Experimental:** read only with `BIG_SPENDER_EXPERIMENTAL=gemini`; checked against ccusage on test fixtures, not yet against real Gemini CLI data. `gemini` chat messages with `tokens`, and saved headless `stats` (per model, or with the last model named, else `unknown`). A changed file is read whole and its counts replace what it counted before, as ccusage counts each file as it is; in JSONL the last copy of a message id counts. `input` excludes `cached` when the total shows it was inside (always in stats), and `tool` tokens count as input. Reasoning (`thoughts`) and any total beyond the parts count as output, as ccusage bills them, though its per-model output leaves reasoning out. A model id that is a file path is reduced to its file name. `$GEMINI_DATA_DIR` adds dirs to the default rather than replacing it. |
377
+ | Antigravity (experimental) | `~/.gemini/antigravity*/conversations/**/*.db`, `~/.config/antigravity/conversations`, T3 Code profiles | **Experimental:** matches ccusage on test fixtures and one day of real CLI and T3 Code data. Every T3 Code profile, `~/.t3/{userdata,dev}/providers/antigravity/*/antigravity-acp`, is read, also under `$T3CODE_HOME`. `antigravity*` is `antigravity` and its `-cli`, `-ide`, `-backup` and `-acp` variants; `$ANTIGRAVITY_DATA_DIR` (comma-separated) is read too. Read with `node:sqlite` (Node 22.13+, else skipped with a warning). Usage messages in `gen_metadata` and `steps`, retries included; copies sharing a response, provider or message id merge and keep the largest counts. A later copy can move a response to another day or model; the day and model it left are sent as a zero row, which takes them back on the server. A model name with a slash (possibly a path) becomes `gemini-internal-model`. Reasoning is part of output. |
378
+ | Gemini CLI (experimental) | `~/.gemini/tmp/**/*.json` and `*.jsonl`, `$GEMINI_DATA_DIR` (comma-separated) | **Experimental:** checked against ccusage on test fixtures, not yet against real Gemini CLI data. `gemini` chat messages with `tokens`, and saved headless `stats` (per model, or with the last model named, else `unknown`). A changed file is read whole and its counts replace what it counted before, as ccusage counts each file as it is; in JSONL the last copy of a message id counts. `input` excludes `cached` when the total shows it was inside (always in stats), and `tool` tokens count as input. Reasoning (`thoughts`) and any total beyond the parts count as output, as ccusage bills them, though its per-model output leaves reasoning out. A model id that is a file path is reduced to its file name. `$GEMINI_DATA_DIR` adds dirs to the default rather than replacing it. |
369
379
 
370
380
  **Pricing.** Claude Code, Codex, pi, Grok Build, GitHub Copilot CLI, Antigravity, Gemini CLI and OpenCode use LiteLLM
371
381
  | OpenCode | `~/.local/share/opencode` (or `$XDG_DATA_HOME/opencode`), or `$OPENCODE_DATA_DIR` (comma-separated, replaces the default): `opencode.db` and pre-SQLite `storage/message/**/*.json` | Assistant messages, and `completed` compaction rows, from the 1.x `message` table, the 2.x `session_message` table and the JSON files. The first copy of a message id wins, because 2.x copies the 1.x rows; A 2.x fork's copies of its parent's rows keep the parent rows' times, so rows older than the fork are skipped, as OpenCode's own stats do; this holds after the parent is deleted, and a parent deleted before big-spender read it is not counted. Needs `node:sqlite` (Node 22.13+). OpenCode rewrites a running message, so each run reads the window again and adds what changed; an hour and model a message left are sent as a zero row, which takes them back on the server. Cache reads and writes are outside `input`. 1.x counts reasoning in `output`; 2.x does not, so it is added. `claude-agent` rows are skipped, because the Claude Code source counts them. A model id that is a file path, a URL, or ends in a model-file extension (`.gguf`, `.safetensors`, ...) is cut to its file name, without query or login; an address with no file name is sent as `local`. OpenCode's own `cost` is not used; a model is priced under the first upstream it was seen on. |
@@ -390,12 +400,6 @@ input price, also above a tier, as ccusage does. 1-hour cache writes use
390
400
  minus cache-read price). Copilot also tries `github_copilot/<model>`, and swaps a dot between digits
391
401
  for a dash in Claude model names (`claude-opus-4.6` is priced as `claude-opus-4-6`).
392
402
 
393
- **Experimental sources.** A source whose counts match ccusage on test data but have not been checked
394
- against real usage yet is marked `experimental` in `SOURCES`. The collector reads and sends it only
395
- when `BIG_SPENDER_EXPERIMENTAL` (comma-separated provider ids, in the environment or the env file)
396
- names it. Antigravity and Gemini CLI are gated this way. Removing it from the list stops sending its rows on the
397
- next run; adding it back recounts them without counting anything twice.
398
-
399
403
  **Adding a provider.** Add an entry to `SOURCES` in `src/collector.mjs`, the provider id to
400
404
  `PROVIDERS` in `src/schema.ts`, a row to the table above, and a test with a fixture log. The entry
401
405
  says where the data lives, how it is read, and which LiteLLM keys price its models. Append-only JSONL
@@ -18,12 +18,11 @@
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, BIG_SPENDER_EXPERIMENTAL and BIG_SPENDER_POLL_LIMITS=off (see
22
- // templates/env.example).
21
+ // BIG_SPENDER_CURSOR_API_KEY and BIG_SPENDER_POLL_LIMITS=off (see templates/env.example).
23
22
  // The older USAGE_* names are still read when the new one is unset.
24
23
 
25
24
  import { createHash } from 'node:crypto';
26
- import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
25
+ import { createReadStream, existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
27
26
  import {
28
27
  mkdir,
29
28
  open,
@@ -1360,10 +1359,9 @@ function geminiEvents(path, text, mtimeMs) {
1360
1359
  /**
1361
1360
  * Gemini rewrites its files, so a changed file is read whole and what it counts now replaces
1362
1361
  * what it counted before, as ccusage counts each file as it is. `state.seen` keeps each file's
1363
- * counts per hour, model, tier and session so they can be taken back, also after the file was
1364
- * skipped for a while (an experimental source turned off). A message updated, corrected or
1365
- * removed in the file changes the count with it, and an hour or model it leaves is sent as a
1366
- * zero row.
1362
+ * counts per hour, model, tier and session so they can be taken back. A message updated,
1363
+ * corrected or removed in the file changes the count with it, and an hour or model it leaves is
1364
+ * sent as a zero row.
1367
1365
  * @type {Source['read']}
1368
1366
  */
1369
1367
  async function readGemini(paths, ctx, provider) {
@@ -1530,6 +1528,23 @@ const ANTIGRAVITY_ROOTS = [
1530
1528
  ];
1531
1529
  const ANTIGRAVITY_DEFAULT_MODEL = 'gemini-internal-model';
1532
1530
 
1531
+ /**
1532
+ * T3 Code runs Antigravity with a profile per provider instance, named by the instance id's
1533
+ * SHA-256, under the state dir of its home: `userdata`, or `dev` for a development build.
1534
+ */
1535
+ function t3AntigravityDirs(t3Home) {
1536
+ return ['userdata', 'dev'].flatMap((stateDir) => {
1537
+ const profiles = join(t3Home, stateDir, 'providers', 'antigravity');
1538
+ let names;
1539
+ try {
1540
+ names = readdirSync(profiles);
1541
+ } catch {
1542
+ return [];
1543
+ }
1544
+ return names.map((name) => join(profiles, name, 'antigravity-acp', 'conversations'));
1545
+ });
1546
+ }
1547
+
1533
1548
  const isDir = (path) => {
1534
1549
  try {
1535
1550
  return statSync(path).isDirectory();
@@ -1538,12 +1553,14 @@ const isDir = (path) => {
1538
1553
  }
1539
1554
  };
1540
1555
 
1541
- const antigravityEnvDirs = () =>
1542
- (process.env.ANTIGRAVITY_DATA_DIR ?? '')
1556
+ const antigravityEnvDirs = () => [
1557
+ ...(process.env.ANTIGRAVITY_DATA_DIR ?? '')
1543
1558
  .split(',')
1544
1559
  .map((root) => root.trim())
1545
1560
  .filter(Boolean)
1546
- .map((root) => (isDir(join(root, 'conversations')) ? join(root, 'conversations') : root));
1561
+ .map((root) => (isDir(join(root, 'conversations')) ? join(root, 'conversations') : root)),
1562
+ ...(process.env.T3CODE_HOME?.trim() ? t3AntigravityDirs(process.env.T3CODE_HOME.trim()) : [])
1563
+ ];
1547
1564
 
1548
1565
  function byPathComponents(a, b) {
1549
1566
  const x = a.split(sep);
@@ -2433,8 +2450,7 @@ async function readOpenCode(paths, ctx, provider) {
2433
2450
  * paths: string[],
2434
2451
  * envPaths: () => string[],
2435
2452
  * read: (paths: string[], ctx: ReadContext, provider: string) => Promise<void>,
2436
- * priceKeys: (model: string) => string[],
2437
- * experimental?: boolean
2453
+ * priceKeys: (model: string) => string[]
2438
2454
  * }} Source
2439
2455
  */
2440
2456
 
@@ -2451,7 +2467,6 @@ async function readOpenCode(paths, ctx, provider) {
2451
2467
  * data whole on every run and skips what it counted before through `state.seen`, keyed with a
2452
2468
  * provider prefix and valued with the record's timestamp so pruneState can drop it.
2453
2469
  * - `priceKeys`: the LiteLLM keys to try for a model, in order.
2454
- * - `experimental`: read only when BIG_SPENDER_EXPERIMENTAL names it; see enabledSources.
2455
2470
  *
2456
2471
  * @type {Record<string, Source>}
2457
2472
  */
@@ -2529,14 +2544,15 @@ const SOURCES = {
2529
2544
  }
2530
2545
  },
2531
2546
  antigravity: {
2532
- experimental: true,
2533
- paths: ANTIGRAVITY_ROOTS.map((root) => join(HOME, root, 'conversations')),
2547
+ paths: [
2548
+ ...ANTIGRAVITY_ROOTS.map((root) => join(HOME, root, 'conversations')),
2549
+ ...t3AntigravityDirs(join(HOME, '.t3'))
2550
+ ],
2534
2551
  envPaths: antigravityEnvDirs,
2535
2552
  read: readAntigravity,
2536
2553
  priceKeys: antigravityPriceKeys
2537
2554
  },
2538
2555
  gemini: {
2539
- experimental: true,
2540
2556
  paths: [join(HOME, '.gemini', 'tmp')],
2541
2557
  envPaths: () =>
2542
2558
  (process.env.GEMINI_DATA_DIR ?? '')
@@ -2564,16 +2580,6 @@ const SOURCES = {
2564
2580
  }
2565
2581
  };
2566
2582
 
2567
- // An experimental source has not been checked against real usage yet, so it is read and sent only
2568
- // when BIG_SPENDER_EXPERIMENTAL (comma-separated provider ids) names it. Turned off, its counted rows
2569
- // stay in the state, so turning it on again replaces them instead of counting them twice.
2570
- function enabledSources() {
2571
- const optIn = new Set(
2572
- (process.env.BIG_SPENDER_EXPERIMENTAL ?? '').split(',').map((id) => id.trim())
2573
- );
2574
- return Object.entries(SOURCES).filter(([id, source]) => !source.experimental || optIn.has(id));
2575
- }
2576
-
2577
2583
  /** @param {[string, Source][]} sources */
2578
2584
  async function scan(state, resolvePrice, cutoffMs, sources, polled) {
2579
2585
  /** @type {ReadContext} */
@@ -3077,14 +3083,14 @@ async function main() {
3077
3083
  const resolvePrice = makePriceResolver(pricing.models);
3078
3084
  const state = await loadState();
3079
3085
  pruneState(state, coverageStartMs);
3080
- const sources = enabledSources();
3081
- const enabled = new Set(sources.map(([id]) => id));
3086
+ const sources = Object.entries(SOURCES);
3087
+ const known = new Set(Object.keys(SOURCES));
3082
3088
  const polled = await pollLimits(state, nowMs);
3083
3089
  await scan(state, resolvePrice, coverageStartMs, sources, polled);
3084
3090
  await saveState(state);
3085
3091
 
3086
3092
  const buckets = Object.fromEntries(
3087
- Object.entries(state.buckets).filter(([key]) => enabled.has(key.split('|')[1]))
3093
+ Object.entries(state.buckets).filter(([key]) => known.has(key.split('|')[1]))
3088
3094
  );
3089
3095
  const used = new Set(Object.keys(buckets).map((k) => k.split('|')[1]));
3090
3096
  const device = buildSnapshot(
@@ -3095,7 +3101,7 @@ async function main() {
3095
3101
  pricingSource: `litellm@${new Date(pricing.fetchedAt).toISOString().slice(0, 10)}`,
3096
3102
  // Older servers require the claude and codex counts and reject any other key, so another
3097
3103
  // provider's count is sent only once this device has used it.
3098
- providers: [...enabled].filter((p) => p === 'claude' || p === 'codex' || used.has(p)),
3104
+ providers: [...known].filter((p) => p === 'claude' || p === 'codex' || used.has(p)),
3099
3105
  nowMs,
3100
3106
  coverageStartMs,
3101
3107
  limits: state.limits
package/dist/limits.d.ts CHANGED
@@ -1,12 +1,35 @@
1
1
  import { type LimitWindow, type UsageProvider, type UsageSnapshot } from './schema.ts';
2
2
  /**
3
- * Merges window lists into one record per window instance: same provider and window, with resets
4
- * at most RESET_SLACK_MS after the earliest reset of the group (rounded down to the minute), which
5
- * the record keeps. A group keeps the highest peak and the earliest hit, so merging is idempotent
3
+ * Merges window lists into one record per window instance (see groupWindows), which keeps the
4
+ * earliest reset. A group keeps the highest peak and the earliest hit, so merging is idempotent
6
5
  * and one account's window reported by two devices counts once. Sorted by reset time; past the
7
6
  * cap the oldest are dropped.
8
7
  */
9
8
  export declare function mergeLimits(...lists: (LimitWindow[] | undefined)[]): LimitWindow[];
9
+ export type LimitHitDevice = {
10
+ deviceId: string;
11
+ hitAt: string;
12
+ peakPercent: number;
13
+ };
14
+ export type LimitHit = {
15
+ provider: UsageProvider;
16
+ window: string;
17
+ /** Earliest reset of the window instance, as mergeLimits keeps it. */
18
+ resetsAt: string;
19
+ /** Earliest hitAt across devices. */
20
+ hitAt: string;
21
+ /** Devices that recorded a hit for this instance, earliest first (ties by deviceId). */
22
+ devices: LimitHitDevice[];
23
+ };
24
+ export type LimitHitsReport = {
25
+ generatedAt: string;
26
+ hits: LimitHit[];
27
+ };
28
+ /**
29
+ * Every recorded limit hit with its exact time and the devices that saw it, earliest device
30
+ * first. Not public: it names devices.
31
+ */
32
+ export declare function limitHits(snapshots: UsageSnapshot[], now: number): LimitHitsReport;
10
33
  export type LimitsSeries = {
11
34
  hits: number[];
12
35
  lockedHours: number[];
package/dist/limits.js CHANGED
@@ -9,50 +9,94 @@ const minuteOf = (iso) => Math.floor(Date.parse(iso) / MINUTE_MS) * MINUTE_MS;
9
9
  // Reports of one window can put its reset seconds apart, across a minute boundary.
10
10
  const RESET_SLACK_MS = 2 * MINUTE_MS;
11
11
  /**
12
- * Merges window lists into one record per window instance: same provider and window, with resets
13
- * at most RESET_SLACK_MS after the earliest reset of the group (rounded down to the minute), which
14
- * the record keeps. A group keeps the highest peak and the earliest hit, so merging is idempotent
12
+ * Groups reports into window instances: same provider and window, with resets at most
13
+ * RESET_SLACK_MS after the earliest reset of the group (rounded down to the minute). Each member's
14
+ * `resetsAt` is rounded; the first member of a group carries the earliest.
15
+ */
16
+ function groupWindows(items) {
17
+ const sorted = items
18
+ .map(({ window: w, deviceId }) => ({
19
+ window: { ...w, resetsAt: new Date(minuteOf(w.resetsAt)).toISOString() },
20
+ deviceId
21
+ }))
22
+ .sort((a, b) => a.window.provider.localeCompare(b.window.provider) ||
23
+ a.window.window.localeCompare(b.window.window) ||
24
+ Date.parse(a.window.resetsAt) - Date.parse(b.window.resetsAt));
25
+ const groups = [];
26
+ for (const item of sorted) {
27
+ const group = groups.at(-1);
28
+ const first = group?.[0].window;
29
+ if (group &&
30
+ first &&
31
+ first.provider === item.window.provider &&
32
+ first.window === item.window.window &&
33
+ Date.parse(item.window.resetsAt) - Date.parse(first.resetsAt) <= RESET_SLACK_MS) {
34
+ group.push(item);
35
+ }
36
+ else {
37
+ groups.push([item]);
38
+ }
39
+ }
40
+ return groups;
41
+ }
42
+ const byTime = (a, b) => Date.parse(a) - Date.parse(b);
43
+ /**
44
+ * Merges window lists into one record per window instance (see groupWindows), which keeps the
45
+ * earliest reset. A group keeps the highest peak and the earliest hit, so merging is idempotent
15
46
  * and one account's window reported by two devices counts once. Sorted by reset time; past the
16
47
  * cap the oldest are dropped.
17
48
  */
18
49
  export function mergeLimits(...lists) {
19
- const all = lists
20
- .flatMap((list) => list ?? [])
21
- .map((w) => ({
22
- provider: w.provider,
23
- window: w.window,
24
- resetsAt: new Date(minuteOf(w.resetsAt)).toISOString(),
25
- peakPercent: w.peakPercent,
26
- ...(w.hitAt ? { hitAt: w.hitAt } : {})
27
- }))
28
- .sort((a, b) => a.provider.localeCompare(b.provider) ||
29
- a.window.localeCompare(b.window) ||
30
- Date.parse(a.resetsAt) - Date.parse(b.resetsAt));
31
- const merged = [];
32
- for (const w of all) {
33
- const group = merged.at(-1);
34
- if (!group ||
35
- group.provider !== w.provider ||
36
- group.window !== w.window ||
37
- Date.parse(w.resetsAt) - Date.parse(group.resetsAt) > RESET_SLACK_MS) {
38
- merged.push(w);
39
- continue;
40
- }
41
- const hits = [group.hitAt, w.hitAt].filter((t) => t !== undefined);
42
- const hitAt = hits.sort((a, b) => Date.parse(a) - Date.parse(b))[0];
43
- merged[merged.length - 1] = {
44
- provider: group.provider,
45
- window: group.window,
46
- resetsAt: group.resetsAt,
47
- peakPercent: Math.max(group.peakPercent, w.peakPercent),
50
+ const groups = groupWindows(lists.flatMap((list) => list ?? []).map((window) => ({ window })));
51
+ const merged = groups.map((group) => {
52
+ const { provider, window, resetsAt } = group[0].window;
53
+ const hitAt = group
54
+ .map((m) => m.window.hitAt)
55
+ .filter((t) => t !== undefined)
56
+ .sort(byTime)[0];
57
+ return {
58
+ provider,
59
+ window,
60
+ resetsAt,
61
+ peakPercent: Math.max(...group.map((m) => m.window.peakPercent)),
48
62
  ...(hitAt ? { hitAt } : {})
49
63
  };
50
- }
64
+ });
51
65
  const sorted = merged.sort((a, b) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt) ||
52
66
  a.provider.localeCompare(b.provider) ||
53
67
  a.window.localeCompare(b.window));
54
68
  return sorted.slice(Math.max(0, sorted.length - MAX_LIMIT_WINDOWS));
55
69
  }
70
+ /**
71
+ * Every recorded limit hit with its exact time and the devices that saw it, earliest device
72
+ * first. Not public: it names devices.
73
+ */
74
+ export function limitHits(snapshots, now) {
75
+ const groups = groupWindows(snapshots.flatMap((s) => (s.limits ?? []).map((window) => ({ window, deviceId: s.deviceId }))));
76
+ const hits = groups.flatMap((group) => {
77
+ const byDevice = new Map();
78
+ for (const { window: w, deviceId } of group) {
79
+ if (!w.hitAt || deviceId === undefined)
80
+ continue;
81
+ const seen = byDevice.get(deviceId);
82
+ byDevice.set(deviceId, {
83
+ deviceId,
84
+ hitAt: seen && byTime(seen.hitAt, w.hitAt) <= 0 ? seen.hitAt : w.hitAt,
85
+ peakPercent: Math.max(seen?.peakPercent ?? 0, w.peakPercent)
86
+ });
87
+ }
88
+ const devices = [...byDevice.values()].sort((a, b) => byTime(a.hitAt, b.hitAt) || a.deviceId.localeCompare(b.deviceId));
89
+ if (!devices.length)
90
+ return [];
91
+ const { provider, window, resetsAt } = group[0].window;
92
+ return [{ provider, window, resetsAt, hitAt: devices[0].hitAt, devices }];
93
+ });
94
+ hits.sort((a, b) => byTime(a.hitAt, b.hitAt) ||
95
+ a.provider.localeCompare(b.provider) ||
96
+ a.window.localeCompare(b.window) ||
97
+ byTime(a.resetsAt, b.resetsAt));
98
+ return { generatedAt: new Date(now).toISOString(), hits };
99
+ }
56
100
  const KNOWN_ORDER = ['five_hour', 'seven_day'];
57
101
  const rank = (w) => {
58
102
  const i = KNOWN_ORDER.indexOf(w);
package/dist/serve.d.ts CHANGED
@@ -6,9 +6,10 @@ export type ServeConfig = {
6
6
  host: string;
7
7
  dataDir: string;
8
8
  ingestToken: string | undefined;
9
+ adminToken: string | undefined;
9
10
  devices: DeviceConfig;
10
11
  };
11
- export declare const SERVE_USAGE = "Usage: big-spender serve [--port 8787] [--host 0.0.0.0] [--data ./data] [--devices devices.json]\n\nEnvironment:\n PORT, HOST listen address (flags win)\n BIG_SPENDER_DATA_DIR where per-device snapshots are stored (default ./data)\n BIG_SPENDER_INGEST_TOKEN bearer token collectors must send; ingest is off without it\n BIG_SPENDER_DEVICES_FILE JSON device names and colours (see the README)";
12
+ export declare const SERVE_USAGE = "Usage: big-spender serve [--port 8787] [--host 0.0.0.0] [--data ./data] [--devices devices.json]\n\nEnvironment:\n PORT, HOST listen address (flags win)\n BIG_SPENDER_DATA_DIR where per-device snapshots are stored (default ./data)\n BIG_SPENDER_INGEST_TOKEN bearer token collectors must send; ingest is off without it\n BIG_SPENDER_ADMIN_TOKEN bearer token for GET /api/usage/limits/hits; must differ from the ingest token; off without it\n BIG_SPENDER_DEVICES_FILE JSON device names and colours (see the README)";
12
13
  export declare function loadServeConfig(argv: string[], env?: NodeJS.ProcessEnv): Promise<ServeConfig>;
13
14
  export declare function createHttpServer(bs: BigSpender): Server;
14
15
  export declare function serve(argv: string[]): Promise<void>;
package/dist/serve.js CHANGED
@@ -16,6 +16,7 @@ Environment:
16
16
  PORT, HOST listen address (flags win)
17
17
  BIG_SPENDER_DATA_DIR where per-device snapshots are stored (default ./data)
18
18
  BIG_SPENDER_INGEST_TOKEN bearer token collectors must send; ingest is off without it
19
+ BIG_SPENDER_ADMIN_TOKEN bearer token for GET /api/usage/limits/hits; must differ from the ingest token; off without it
19
20
  BIG_SPENDER_DEVICES_FILE JSON device names and colours (see the README)`;
20
21
  export async function loadServeConfig(argv, env = process.env) {
21
22
  const { values } = parseArgs({
@@ -48,6 +49,7 @@ export async function loadServeConfig(argv, env = process.env) {
48
49
  host: values.host ?? env.HOST ?? '0.0.0.0',
49
50
  dataDir: values.data ?? env.BIG_SPENDER_DATA_DIR ?? './data',
50
51
  ingestToken: env.BIG_SPENDER_INGEST_TOKEN?.trim() || undefined,
52
+ adminToken: env.BIG_SPENDER_ADMIN_TOKEN?.trim() || undefined,
51
53
  devices
52
54
  };
53
55
  }
@@ -69,6 +71,10 @@ const routes = {
69
71
  headers: { 'cache-control': 'public, max-age=300, stale-while-revalidate=900' }
70
72
  })
71
73
  },
74
+ '/api/usage/limits/hits': {
75
+ methods: ['GET', 'HEAD'],
76
+ handle: (bs, request) => bs.limitHits(request)
77
+ },
72
78
  '/': {
73
79
  methods: ['GET', 'HEAD'],
74
80
  handle: async (bs) => new Response(renderPage(await bs.summary(), await bs.limits()), {
@@ -0,0 +1 @@
1
+ export declare function authorized(header: string | null, expected: string): boolean;
@@ -0,0 +1,9 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ const digest = (s) => createHash('sha256').update(s).digest();
3
+ export function authorized(header, expected) {
4
+ const match = /^Bearer (.+)$/.exec(header ?? '');
5
+ if (!match)
6
+ return false;
7
+ // Hash both sides so the comparison is constant-time regardless of length.
8
+ return timingSafeEqual(digest(match[1]), digest(expected));
9
+ }
@@ -2,7 +2,7 @@ import type { DeviceConfig } from '../devices.ts';
2
2
  import { type LimitsSummary } from '../limits.ts';
3
3
  import { type UsageSummary } from '../summary.ts';
4
4
  export { DEVICE_ID, MAX_LIMIT_WINDOWS, PROVIDERS, RANGES, limitWindowSchema, usageRowSchema, usageSnapshotSchema, type LimitWindow, type UsageProvider, type UsageRange, type UsageRow, type UsageSnapshot } from '../schema.ts';
5
- export { summarizeLimits, type LimitsSeries, type LimitsSummary, type LimitWindowSummary } from '../limits.ts';
5
+ export { limitHits, summarizeLimits, type LimitHit, type LimitHitDevice, type LimitHitsReport, type LimitsSeries, type LimitsSummary, type LimitWindowSummary } from '../limits.ts';
6
6
  export { OTHER, PALETTE, resolveDevices, type DeviceConfig, type DeviceInfo } from '../devices.ts';
7
7
  export { summarize, type Bucket, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
8
8
  export type BigSpenderOptions = {
@@ -10,6 +10,11 @@ export type BigSpenderOptions = {
10
10
  dataDir: string;
11
11
  /** Bearer token collectors must send. Missing or empty turns ingest off (503). */
12
12
  ingestToken: string | undefined;
13
+ /**
14
+ * Bearer token for `limitHits`. Missing or empty turns it off (503), and so does a token equal to
15
+ * `ingestToken`: every collector holds that one.
16
+ */
17
+ adminToken?: string | undefined;
13
18
  devices: DeviceConfig;
14
19
  };
15
20
  export type BigSpender = {
@@ -19,5 +24,7 @@ export type BigSpender = {
19
24
  summary(now?: number): Promise<UsageSummary>;
20
25
  /** Subscription limit hits over the last 90 UTC days, cached like `summary`. */
21
26
  limits(now?: number): Promise<LimitsSummary>;
27
+ /** Admin only: exact time and devices of every recorded limit hit. Never cached. */
28
+ limitHits(request: Request): Promise<Response>;
22
29
  };
23
- export declare function createBigSpender({ dataDir, ingestToken, devices }: BigSpenderOptions): BigSpender;
30
+ export declare function createBigSpender({ dataDir, ingestToken, adminToken, devices }: BigSpenderOptions): BigSpender;
@@ -1,13 +1,15 @@
1
1
  import { fileStore } from '../store.js';
2
- import { summarizeLimits } from '../limits.js';
2
+ import { limitHits, summarizeLimits } from '../limits.js';
3
3
  import { summarize } from '../summary.js';
4
+ import { authorized } from './auth.js';
4
5
  import { createIngest } from './ingest.js';
5
6
  export { DEVICE_ID, MAX_LIMIT_WINDOWS, PROVIDERS, RANGES, limitWindowSchema, usageRowSchema, usageSnapshotSchema } from '../schema.js';
6
- export { summarizeLimits } from '../limits.js';
7
+ export { limitHits, summarizeLimits } from '../limits.js';
7
8
  export { OTHER, PALETTE, resolveDevices } from '../devices.js';
8
9
  export { summarize } from '../summary.js';
9
10
  const SUMMARY_TTL_MS = 5 * 60 * 1000;
10
- export function createBigSpender({ dataDir, ingestToken, devices }) {
11
+ export function createBigSpender({ dataDir, ingestToken, adminToken, devices }) {
12
+ const admin = adminToken?.trim();
11
13
  const store = fileStore(dataDir);
12
14
  let cache = null;
13
15
  let limitsCache = null;
@@ -33,6 +35,19 @@ export function createBigSpender({ dataDir, ingestToken, devices }) {
33
35
  const value = summarizeLimits(await store.list(), now);
34
36
  limitsCache = { value, computedAt: now };
35
37
  return value;
38
+ },
39
+ async limitHits(request) {
40
+ if (!admin)
41
+ return Response.json({ error: 'admin is not configured' }, { status: 503 });
42
+ if (admin === ingestToken?.trim()) {
43
+ return Response.json({ error: 'admin token must differ from the ingest token' }, { status: 503 });
44
+ }
45
+ if (!authorized(request.headers.get('authorization'), admin)) {
46
+ return Response.json({ error: 'unauthorized' }, { status: 401 });
47
+ }
48
+ return Response.json(limitHits(await store.list(), Date.now()), {
49
+ headers: { 'cache-control': 'no-store' }
50
+ });
36
51
  }
37
52
  };
38
53
  }
@@ -1,16 +1,8 @@
1
- import { createHash, timingSafeEqual } from 'node:crypto';
2
1
  import { CURSOR_DEVICE_ID, usageSnapshotSchema } from '../schema.js';
2
+ import { authorized } from './auth.js';
3
3
  // Collectors POST one device's full snapshot here (optionally gzip-encoded).
4
4
  const MAX_BODY_BYTES = 2 * 1024 * 1024;
5
5
  const MAX_DECODED_BYTES = 16 * 1024 * 1024;
6
- const digest = (s) => createHash('sha256').update(s).digest();
7
- function authorized(header, expected) {
8
- const match = /^Bearer (.+)$/.exec(header ?? '');
9
- if (!match)
10
- return false;
11
- // Hash both sides so the comparison is constant-time regardless of length.
12
- return timingSafeEqual(digest(match[1]), digest(expected));
13
- }
14
6
  class TooLarge extends Error {
15
7
  }
16
8
  async function readCapped(stream, max) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "big-spender",
3
- "version": "0.12.0",
3
+ "version": "0.14.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",
@@ -10,9 +10,6 @@ BIG_SPENDER_INGEST_TOKEN=
10
10
  # Optional, on one machine only: a Cursor user API key. The collector then reads the account's
11
11
  # usage from Cursor's API and sends it as the device "cursor". Set by `big-spender install --cursor`.
12
12
  # BIG_SPENDER_CURSOR_API_KEY=
13
- # Optional: experimental sources to read too, comma-separated. Their counts match ccusage on test
14
- # data but have not been checked against real usage yet. Available: antigravity, gemini.
15
- # BIG_SPENDER_EXPERIMENTAL=antigravity
16
13
  # Optional: set to off to stop the collector asking Anthropic and OpenAI how full your Claude and
17
14
  # Codex limit windows are. It reads the agents' own login files read-only and only sends the token to
18
15
  # that provider.