big-spender 0.3.0 → 0.6.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/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
  }
package/dist/install.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Context } from './context.ts';
2
- export declare const INSTALL_USAGE = "Usage: big-spender install --device <id> [--url <ingest url>] [--rename]\n\nCopies the collector to ~/.local/share/big-spender, schedules it hourly (systemd user timer on\nLinux, launchd agent on macOS) and runs it once. The ingest token comes from the existing env\nfile, BIG_SPENDER_INGEST_TOKEN, or a hidden prompt. It is never taken from a flag.\nRe-running is safe. A usage-collector install from before the rename is migrated in place.\nA machine that already has a device id keeps it: --device with a different id needs --rename,\nbecause the server would count the same history twice, under the old id and the new one.";
2
+ export declare const INSTALL_USAGE = "Usage: big-spender install --device <id> [--url <ingest url>] [--rename] [--cursor]\n\nCopies the collector to ~/.local/share/big-spender, schedules it hourly (systemd user timer on\nLinux, launchd agent on macOS) and runs it once. The ingest token comes from the existing env\nfile, BIG_SPENDER_INGEST_TOKEN, or a hidden prompt. It is never taken from a flag.\nRe-running is safe. A usage-collector install from before the rename is migrated in place.\nA machine that already has a device id keeps it: --device with a different id needs --rename,\nbecause the server would count the same history twice, under the old id and the new one.\n--cursor also reads your Cursor account's usage from Cursor's API and sends it as the device\n\"cursor\". The Cursor API key comes from BIG_SPENDER_CURSOR_API_KEY or a hidden prompt. Set it up\non one machine only. Re-running install without --cursor keeps a key that is already set.";
3
3
  export declare function install(args: string[], ctx: Context): Promise<number>;
4
4
  export declare const UNINSTALL_USAGE = "Usage: big-spender uninstall\n\nRemoves the schedule. The env file and state are kept.";
5
5
  export declare function uninstall(args: string[], ctx: Context): Promise<number>;
package/dist/install.js CHANGED
@@ -4,7 +4,7 @@ import { delimiter, dirname, join } from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
5
  import { UsageError } from './context.js';
6
6
  import { parseEnv, renameLegacyKeys, setting, upsertEnv } from './envfile.js';
7
- import { DEVICE_ID } from './schema.js';
7
+ import { CURSOR_DEVICE_ID, DEVICE_ID } from './schema.js';
8
8
  import { pickScheduler } from './scheduler.js';
9
9
  // The collector removes its lock when it finishes, so one this young belongs to a live run.
10
10
  const LOCK_FRESH_MS = 30 * 60 * 1000;
@@ -118,21 +118,25 @@ async function existingSettings(ctx) {
118
118
  token: setting(vars, 'INGEST_TOKEN')
119
119
  };
120
120
  }
121
- export const INSTALL_USAGE = `Usage: big-spender install --device <id> [--url <ingest url>] [--rename]
121
+ export const INSTALL_USAGE = `Usage: big-spender install --device <id> [--url <ingest url>] [--rename] [--cursor]
122
122
 
123
123
  Copies the collector to ~/.local/share/big-spender, schedules it hourly (systemd user timer on
124
124
  Linux, launchd agent on macOS) and runs it once. The ingest token comes from the existing env
125
125
  file, BIG_SPENDER_INGEST_TOKEN, or a hidden prompt. It is never taken from a flag.
126
126
  Re-running is safe. A usage-collector install from before the rename is migrated in place.
127
127
  A machine that already has a device id keeps it: --device with a different id needs --rename,
128
- because the server would count the same history twice, under the old id and the new one.`;
128
+ because the server would count the same history twice, under the old id and the new one.
129
+ --cursor also reads your Cursor account's usage from Cursor's API and sends it as the device
130
+ "cursor". The Cursor API key comes from BIG_SPENDER_CURSOR_API_KEY or a hidden prompt. Set it up
131
+ on one machine only. Re-running install without --cursor keeps a key that is already set.`;
129
132
  export async function install(args, ctx) {
130
133
  const { values } = parseArgs({
131
134
  args,
132
135
  options: {
133
136
  device: { type: 'string' },
134
137
  url: { type: 'string' },
135
- rename: { type: 'boolean' }
138
+ rename: { type: 'boolean' },
139
+ cursor: { type: 'boolean' }
136
140
  },
137
141
  strict: true
138
142
  });
@@ -142,6 +146,9 @@ export async function install(args, ctx) {
142
146
  if (!DEVICE_ID.test(deviceId)) {
143
147
  throw new UsageError('--device must be a lowercase slug such as laptop or desktop');
144
148
  }
149
+ if (deviceId === CURSOR_DEVICE_ID) {
150
+ throw new UsageError(`the device id "${CURSOR_DEVICE_ID}" is reserved for Cursor usage`);
151
+ }
145
152
  if (existing.deviceId && deviceId !== existing.deviceId && !values.rename) {
146
153
  throw new UsageError(`this machine already reports as "${existing.deviceId}", not "${deviceId}". Under a new id the server would count the same usage twice, because ${existing.deviceId}.json stays on the server next to the new one. Keep "${existing.deviceId}", or pass --rename if you mean to change it and will remove the old device's data on the server`);
147
154
  }
@@ -165,6 +172,16 @@ export async function install(args, ctx) {
165
172
  token = await ctx.prompter().askHidden('Ingest token: ');
166
173
  if (!url || !token)
167
174
  throw new UsageError('an ingest URL and token are required');
175
+ let cursorKey = '';
176
+ if (values.cursor) {
177
+ cursorKey = (ctx.env.BIG_SPENDER_CURSOR_API_KEY || (await ctx.prompter().askHidden('Cursor API key: '))).trim();
178
+ if (!cursorKey)
179
+ throw new UsageError('--cursor needs a Cursor API key');
180
+ // A newline would end the env file line and start another setting.
181
+ if (!/^[\x21-\x7e]+$/.test(cursorKey)) {
182
+ throw new UsageError('the Cursor API key contains spaces, line breaks or other characters it cannot have');
183
+ }
184
+ }
168
185
  const log = [];
169
186
  if (legacySchedule.length > 0 && (cachePlan === 'move' || cachePlan === 'replace')) {
170
187
  await writeFile(wasScheduled, '');
@@ -183,7 +200,8 @@ export async function install(args, ctx) {
183
200
  await writePrivate(paths.envFile, upsertEnv(base, {
184
201
  BIG_SPENDER_DEVICE_ID: deviceId,
185
202
  BIG_SPENDER_INGEST_URL: url,
186
- BIG_SPENDER_INGEST_TOKEN: token
203
+ BIG_SPENDER_INGEST_TOKEN: token,
204
+ ...(cursorKey ? { BIG_SPENDER_CURSOR_API_KEY: cursorKey } : {})
187
205
  }));
188
206
  await mkdir(paths.shareDir, { recursive: true });
189
207
  await copyFile(ctx.collector, paths.collector);
@@ -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.";
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
@@ -5,7 +5,7 @@ import { parseArgs } from 'node:util';
5
5
  import { gzipSync } from 'node:zlib';
6
6
  import { UsageError } from './context.js';
7
7
  import { parseEnv, setting } from './envfile.js';
8
- import { DEVICE_ID } from './schema.js';
8
+ import { CURSOR_DEVICE_ID, DEVICE_ID } from './schema.js';
9
9
  export const PUSH_USAGE = `Usage: big-spender push <device> [--dry-run] [--url <ingest url>]
10
10
 
11
11
  One-off push from a machine without a schedule. Builds the snapshot, shows what it would publish
@@ -16,7 +16,9 @@ prompt, so neither is written to this machine. Nothing is scheduled.
16
16
 
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
- collector's local state in ~/.cache/big-spender (which logs were read), never anything remote.`;
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.
21
+ Cursor usage is not part of a push: only the scheduled collector sends it.`;
20
22
  const MAX_SNAPSHOT_BYTES = 512 * 1024 * 1024;
21
23
  const POST_ATTEMPTS = 4;
22
24
  function runCollector(ctx, extraEnv, args) {
@@ -58,7 +60,13 @@ function overview(snapshot, gzipped) {
58
60
  '',
59
61
  ` ${'provider model'.padEnd(width)} ${'tokens'.padStart(10)} ${'cost'.padStart(10)}`,
60
62
  ...rows.map(([k, m]) => line(k, m.tokens, m.cost)),
61
- 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
+ : [])
62
70
  ];
63
71
  }
64
72
  export async function push(args, ctx) {
@@ -72,7 +80,10 @@ export async function push(args, ctx) {
72
80
  if (positionals.length !== 1 || !DEVICE_ID.test(deviceId)) {
73
81
  throw new UsageError('<device> must be a lowercase slug such as laptop or desktop');
74
82
  }
75
- const built = await runCollector(ctx, { BIG_SPENDER_DEVICE_ID: deviceId }, ['--dry-run']);
83
+ if (deviceId === CURSOR_DEVICE_ID) {
84
+ throw new UsageError(`the device id "${CURSOR_DEVICE_ID}" is reserved for Cursor usage`);
85
+ }
86
+ const built = await runCollector(ctx, { BIG_SPENDER_DEVICE_ID: deviceId, BIG_SPENDER_CURSOR_API_KEY: '' }, ['--dry-run']);
76
87
  if (built.code !== 0) {
77
88
  ctx.err(built.stderr.trimEnd());
78
89
  return 1;
@@ -116,8 +127,23 @@ export async function push(args, ctx) {
116
127
  if (!/^[\x21-\x7e]+$/.test(token)) {
117
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');
118
129
  }
119
- const result = await send(ctx, url, token, body);
120
- 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}`);
121
147
  return 0;
122
148
  }
123
149
  /** POSTs the reviewed bytes with the collector's retry policy and returns the server's reply. */
package/dist/schema.d.ts CHANGED
@@ -2,7 +2,8 @@ import { z } from 'zod';
2
2
  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
- export declare const PROVIDERS: readonly ['claude', 'codex'];
5
+ export declare const CURSOR_DEVICE_ID = "cursor";
6
+ export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi'];
6
7
  export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
7
8
  export declare const usageRowSchema: z.ZodObject<{
8
9
  hour: z.ZodISODateTime;
@@ -13,6 +14,8 @@ export declare const usageRowSchema: z.ZodObject<{
13
14
  provider: z.ZodEnum<{
14
15
  claude: "claude";
15
16
  codex: "codex";
17
+ cursor: "cursor";
18
+ pi: "pi";
16
19
  }>;
17
20
  model: z.ZodString;
18
21
  sessions: z.ZodNumber;
@@ -29,6 +32,19 @@ export declare const usageRowSchema: z.ZodObject<{
29
32
  }, z.core.$strict>;
30
33
  cacheSavingsUsd: z.ZodNumber;
31
34
  }, z.core.$strict>;
35
+ export declare const MAX_LIMIT_WINDOWS = 5000;
36
+ export declare const limitWindowSchema: z.ZodObject<{
37
+ provider: z.ZodEnum<{
38
+ claude: "claude";
39
+ codex: "codex";
40
+ cursor: "cursor";
41
+ pi: "pi";
42
+ }>;
43
+ window: z.ZodString;
44
+ resetsAt: z.ZodISODateTime;
45
+ peakPercent: z.ZodNumber;
46
+ hitAt: z.ZodOptional<z.ZodISODateTime>;
47
+ }, z.core.$strict>;
32
48
  export declare const usageSnapshotSchema: z.ZodObject<{
33
49
  schemaVersion: z.ZodLiteral<1>;
34
50
  deviceId: z.ZodString;
@@ -44,6 +60,8 @@ export declare const usageSnapshotSchema: z.ZodObject<{
44
60
  provider: z.ZodEnum<{
45
61
  claude: "claude";
46
62
  codex: "codex";
63
+ cursor: "cursor";
64
+ pi: "pi";
47
65
  }>;
48
66
  model: z.ZodString;
49
67
  sessions: z.ZodNumber;
@@ -66,24 +84,45 @@ export declare const usageSnapshotSchema: z.ZodObject<{
66
84
  claude: z.ZodNumber;
67
85
  codex: z.ZodNumber;
68
86
  all: z.ZodNumber;
87
+ cursor: z.ZodOptional<z.ZodNumber>;
88
+ pi: z.ZodOptional<z.ZodNumber>;
69
89
  }, z.core.$strict>>;
70
90
  '7d': z.ZodObject<{
71
91
  claude: z.ZodNumber;
72
92
  codex: z.ZodNumber;
73
93
  all: z.ZodNumber;
94
+ cursor: z.ZodOptional<z.ZodNumber>;
95
+ pi: z.ZodOptional<z.ZodNumber>;
74
96
  }, z.core.$strict>;
75
97
  '30d': z.ZodObject<{
76
98
  claude: z.ZodNumber;
77
99
  codex: z.ZodNumber;
78
100
  all: z.ZodNumber;
101
+ cursor: z.ZodOptional<z.ZodNumber>;
102
+ pi: z.ZodOptional<z.ZodNumber>;
79
103
  }, z.core.$strict>;
80
104
  '90d': z.ZodObject<{
81
105
  claude: z.ZodNumber;
82
106
  codex: z.ZodNumber;
83
107
  all: z.ZodNumber;
108
+ cursor: z.ZodOptional<z.ZodNumber>;
109
+ pi: z.ZodOptional<z.ZodNumber>;
84
110
  }, z.core.$strict>;
85
111
  }, z.core.$strict>>;
112
+ limits: z.ZodOptional<z.ZodArray<z.ZodObject<{
113
+ provider: z.ZodEnum<{
114
+ claude: "claude";
115
+ codex: "codex";
116
+ cursor: "cursor";
117
+ pi: "pi";
118
+ }>;
119
+ window: z.ZodString;
120
+ resetsAt: z.ZodISODateTime;
121
+ peakPercent: z.ZodNumber;
122
+ hitAt: z.ZodOptional<z.ZodISODateTime>;
123
+ }, z.core.$strict>>>;
86
124
  }, z.core.$strict>;
125
+ export type LimitWindow = z.infer<typeof limitWindowSchema>;
87
126
  export type UsageRow = z.infer<typeof usageRowSchema>;
88
127
  export type UsageSnapshot = z.infer<typeof usageSnapshotSchema>;
89
128
  export type UsageProvider = (typeof PROVIDERS)[number];
package/dist/schema.js CHANGED
@@ -12,7 +12,9 @@ const isoDate = z.iso
12
12
  .refine((s) => Date.parse(s) >= Date.parse(EARLIEST_DATE), `must be ${EARLIEST_DATE} or later`);
13
13
  export const MAX_ROWS = 50_000;
14
14
  export const DEVICE_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
15
- export const PROVIDERS = ['claude', 'codex'];
15
+ // Collectors send the Cursor account's usage under this id, so no machine may use it.
16
+ export const CURSOR_DEVICE_ID = 'cursor';
17
+ export const PROVIDERS = ['claude', 'codex', 'cursor', 'pi'];
16
18
  // Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
17
19
  // than a day: an hourly view would show when each machine is in use.
18
20
  export const RANGES = ['7d', '30d', '90d', 'all'];
@@ -34,10 +36,26 @@ export const usageRowSchema = z.strictObject({
34
36
  costUsd: z.strictObject({ input: usd, cacheRead: usd, cacheWrite: usd, output: usd }),
35
37
  cacheSavingsUsd: usd
36
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
+ });
53
+ const count = z.number().int().nonnegative();
37
54
  const sessionCount = z.strictObject({
38
- claude: z.number().int().nonnegative(),
39
- codex: z.number().int().nonnegative(),
40
- all: z.number().int().nonnegative()
55
+ ...Object.fromEntries(PROVIDERS.map((p) => [p, count.optional()])),
56
+ claude: count,
57
+ codex: count,
58
+ all: count
41
59
  });
42
60
  export const usageSnapshotSchema = z.strictObject({
43
61
  schemaVersion: z.literal(1),
@@ -59,5 +77,6 @@ export const usageSnapshotSchema = z.strictObject({
59
77
  '30d': sessionCount,
60
78
  '90d': sessionCount
61
79
  })
62
- .optional()
80
+ .optional(),
81
+ limits: z.array(limitWindowSchema).max(MAX_LIMIT_WINDOWS).optional()
63
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
  }