big-spender 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -149,13 +149,14 @@ Cursor.
149
149
 
150
150
  `big-spender serve` is a small `node:http` server:
151
151
 
152
- | Route | What it does |
153
- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
154
- | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
155
- | `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
156
- | `GET /api/usage/limits` | Subscription limit hits per provider and window over the last 90 UTC days, per day, same cache header. See [Usage limits](#usage-limits). |
157
- | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models, limit hits. No JavaScript, no external assets, light and dark. |
158
- | `GET /healthz` | `ok`, for load balancers and Docker. |
152
+ | Route | What it does |
153
+ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
154
+ | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
155
+ | `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
156
+ | `GET /api/usage/limits` | Subscription limit hits per provider and window over the last 90 UTC days, per day, same cache header. See [Usage limits](#usage-limits). |
157
+ | `GET /api/usage/limits/hits` | Admin only: bearer `BIG_SPENDER_ADMIN_TOKEN`. Every recorded limit hit with its exact time and the device ids that saw it, earliest first. `cache-control: no-store`. See [Usage limits](#usage-limits). |
158
+ | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models, limit hits. No JavaScript, no external assets, light and dark. |
159
+ | `GET /healthz` | `ok`, for load balancers and Docker. |
159
160
 
160
161
  Configuration comes from flags or environment variables (flags win):
161
162
 
@@ -166,6 +167,7 @@ Configuration comes from flags or environment variables (flags win):
166
167
  | `--data` | `BIG_SPENDER_DATA_DIR` | `./data` (`/data` in the Docker image) |
167
168
  | `--devices` | `BIG_SPENDER_DEVICES_FILE` | none: `{ "devices": {}, "unknownDevices": "by-id" }` |
168
169
  | | `BIG_SPENDER_INGEST_TOKEN` | none: ingest is off and answers `503` |
170
+ | | `BIG_SPENDER_ADMIN_TOKEN` | none: the hits endpoint is off and answers `503` |
169
171
 
170
172
  The data directory holds one `<device>.json` file per device, written atomically. Put it on a
171
173
  persistent volume. Each snapshot is merged into the device's stored history. A day the snapshot
@@ -232,7 +234,7 @@ export const GET = async ({ setHeaders }) => {
232
234
  Hono is the same shape (`app.post('/api/usage/ingest', (c) => bs.ingest(c.req.raw))`), and so is a
233
235
  Next.js route handler (`export const POST = (request: Request) => bs.ingest(request)`).
234
236
 
235
- `createBigSpender({ dataDir, ingestToken, devices })` returns:
237
+ `createBigSpender({ dataDir, ingestToken, adminToken?, devices })` returns:
236
238
 
237
239
  - `ingest(request)`: handles a collector's `POST` and returns a `Response` (`503` when
238
240
  `ingestToken` is missing or empty, `401`, `413`, `415`, `422`, or `200` with
@@ -240,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
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.13.0",
4
4
  "description": "Track what your AI coding agents would cost at API prices, across all your machines.",
5
5
  "keywords": [
6
6
  "ai",