big-spender 0.2.0 → 0.5.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/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);
package/dist/page.js CHANGED
@@ -8,7 +8,12 @@ const tokens = (n) => n >= 1e9
8
8
  ? `${(n / 1e6).toFixed(1)}M`
9
9
  : n.toLocaleString('en-US');
10
10
  const percent = (share) => `${(share * 100).toFixed(1)}%`;
11
- const LABELS = { '7d': '7 days', '30d': '30 days', '90d': '90 days' };
11
+ const LABELS = {
12
+ '7d': 'Last 7 days',
13
+ '30d': 'Last 30 days',
14
+ '90d': 'Last 90 days',
15
+ all: 'All time'
16
+ };
12
17
  const TOP_MODELS = 8;
13
18
  const STYLE = `
14
19
  :root { color-scheme: light dark; --bg: #fafaf7; --fg: #1b1f1c; --muted: #66706a; --card: #ffffff; --line: #dfe3dd; }
@@ -35,13 +40,13 @@ th { color: var(--muted); font-weight: 500; font-size: 0.85rem; }
35
40
  .empty { color: var(--muted); }
36
41
  `;
37
42
  function totalsCard(r) {
38
- return `<section class="card"><h3>Last ${LABELS[r.range]}</h3>
43
+ return `<section class="card"><h3>${LABELS[r.range]}</h3>
39
44
  <p class="cost">${usd(r.totalCost)}</p>
40
- <p>${r.sessions.toLocaleString('en-US')} sessions · ${tokens(r.tokens.processed)} tokens</p>
45
+ <p>${r.sessions === null ? '' : `${r.sessions.toLocaleString('en-US')} sessions · `}${tokens(r.tokens.processed)} tokens</p>
41
46
  <p>${usd(r.cacheSavings)} saved by caching</p></section>`;
42
47
  }
43
48
  function devicesTable(summary) {
44
- const widest = summary.ranges['90d'];
49
+ const widest = summary.ranges.all;
45
50
  if (!widest.devices.length)
46
51
  return '<p class="empty">No devices have reported yet.</p>';
47
52
  const rows = widest.devices.map((d) => {
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.\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,8 @@ 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
+ Cursor usage is not part of a push: only the scheduled collector sends it.`;
20
21
  const MAX_SNAPSHOT_BYTES = 512 * 1024 * 1024;
21
22
  const POST_ATTEMPTS = 4;
22
23
  function runCollector(ctx, extraEnv, args) {
@@ -72,7 +73,10 @@ export async function push(args, ctx) {
72
73
  if (positionals.length !== 1 || !DEVICE_ID.test(deviceId)) {
73
74
  throw new UsageError('<device> must be a lowercase slug such as laptop or desktop');
74
75
  }
75
- const built = await runCollector(ctx, { BIG_SPENDER_DEVICE_ID: deviceId }, ['--dry-run']);
76
+ if (deviceId === CURSOR_DEVICE_ID) {
77
+ throw new UsageError(`the device id "${CURSOR_DEVICE_ID}" is reserved for Cursor usage`);
78
+ }
79
+ const built = await runCollector(ctx, { BIG_SPENDER_DEVICE_ID: deviceId, BIG_SPENDER_CURSOR_API_KEY: '' }, ['--dry-run']);
76
80
  if (built.code !== 0) {
77
81
  ctx.err(built.stderr.trimEnd());
78
82
  return 1;
package/dist/schema.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import { z } from 'zod';
2
+ export declare const EARLIEST_DATE = "2020-01-01T00:00:00Z";
2
3
  export declare const MAX_ROWS = 50000;
3
4
  export declare const DEVICE_ID: RegExp;
4
- export declare const PROVIDERS: readonly ['claude', 'codex'];
5
- export declare const RANGES: readonly ['7d', '30d', '90d'];
5
+ export declare const CURSOR_DEVICE_ID = "cursor";
6
+ export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi'];
7
+ export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
6
8
  export declare const usageRowSchema: z.ZodObject<{
7
9
  hour: z.ZodISODateTime;
8
10
  granularity: z.ZodOptional<z.ZodEnum<{
@@ -12,6 +14,8 @@ export declare const usageRowSchema: z.ZodObject<{
12
14
  provider: z.ZodEnum<{
13
15
  claude: "claude";
14
16
  codex: "codex";
17
+ cursor: "cursor";
18
+ pi: "pi";
15
19
  }>;
16
20
  model: z.ZodString;
17
21
  sessions: z.ZodNumber;
@@ -43,6 +47,8 @@ export declare const usageSnapshotSchema: z.ZodObject<{
43
47
  provider: z.ZodEnum<{
44
48
  claude: "claude";
45
49
  codex: "codex";
50
+ cursor: "cursor";
51
+ pi: "pi";
46
52
  }>;
47
53
  model: z.ZodString;
48
54
  sessions: z.ZodNumber;
@@ -65,21 +71,29 @@ export declare const usageSnapshotSchema: z.ZodObject<{
65
71
  claude: z.ZodNumber;
66
72
  codex: z.ZodNumber;
67
73
  all: z.ZodNumber;
74
+ cursor: z.ZodOptional<z.ZodNumber>;
75
+ pi: z.ZodOptional<z.ZodNumber>;
68
76
  }, z.core.$strict>>;
69
77
  '7d': z.ZodObject<{
70
78
  claude: z.ZodNumber;
71
79
  codex: z.ZodNumber;
72
80
  all: z.ZodNumber;
81
+ cursor: z.ZodOptional<z.ZodNumber>;
82
+ pi: z.ZodOptional<z.ZodNumber>;
73
83
  }, z.core.$strict>;
74
84
  '30d': z.ZodObject<{
75
85
  claude: z.ZodNumber;
76
86
  codex: z.ZodNumber;
77
87
  all: z.ZodNumber;
88
+ cursor: z.ZodOptional<z.ZodNumber>;
89
+ pi: z.ZodOptional<z.ZodNumber>;
78
90
  }, z.core.$strict>;
79
91
  '90d': z.ZodObject<{
80
92
  claude: z.ZodNumber;
81
93
  codex: z.ZodNumber;
82
94
  all: z.ZodNumber;
95
+ cursor: z.ZodOptional<z.ZodNumber>;
96
+ pi: z.ZodOptional<z.ZodNumber>;
83
97
  }, z.core.$strict>;
84
98
  }, z.core.$strict>>;
85
99
  }, z.core.$strict>;
package/dist/schema.js CHANGED
@@ -4,12 +4,20 @@ import { z } from 'zod';
4
4
  // model names, timestamps and the device id can be stored or served.
5
5
  const tokens = z.number().int().nonnegative().max(1e15);
6
6
  const usd = z.number().nonnegative().max(1e9);
7
- const isoDate = z.iso.datetime({ offset: true });
7
+ // No AI coding agent usage predates 2020. The floor also bounds the all-time range: it is
8
+ // bucketed by week from the oldest date, so year 0 would mean 100,000+ points per series.
9
+ export const EARLIEST_DATE = '2020-01-01T00:00:00Z';
10
+ const isoDate = z.iso
11
+ .datetime({ offset: true })
12
+ .refine((s) => Date.parse(s) >= Date.parse(EARLIEST_DATE), `must be ${EARLIEST_DATE} or later`);
8
13
  export const MAX_ROWS = 50_000;
9
14
  export const DEVICE_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
10
- export const PROVIDERS = ['claude', 'codex'];
11
- // Public ranges. All are day-granular: an hourly view would show when each machine is in use.
12
- export const RANGES = ['7d', '30d', '90d'];
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'];
18
+ // Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
19
+ // than a day: an hourly view would show when each machine is in use.
20
+ export const RANGES = ['7d', '30d', '90d', 'all'];
13
21
  export const usageRowSchema = z.strictObject({
14
22
  hour: isoDate,
15
23
  granularity: z.enum(['hour', 'day']).optional(),
@@ -28,10 +36,12 @@ export const usageRowSchema = z.strictObject({
28
36
  costUsd: z.strictObject({ input: usd, cacheRead: usd, cacheWrite: usd, output: usd }),
29
37
  cacheSavingsUsd: usd
30
38
  });
39
+ const count = z.number().int().nonnegative();
31
40
  const sessionCount = z.strictObject({
32
- claude: z.number().int().nonnegative(),
33
- codex: z.number().int().nonnegative(),
34
- all: z.number().int().nonnegative()
41
+ ...Object.fromEntries(PROVIDERS.map((p) => [p, count.optional()])),
42
+ claude: count,
43
+ codex: count,
44
+ all: count
35
45
  });
36
46
  export const usageSnapshotSchema = z.strictObject({
37
47
  schemaVersion: z.literal(1),
@@ -2,7 +2,7 @@ import type { DeviceConfig } from '../devices.ts';
2
2
  import { type UsageSummary } from '../summary.ts';
3
3
  export { DEVICE_ID, PROVIDERS, RANGES, usageRowSchema, usageSnapshotSchema, type UsageProvider, type UsageRange, type UsageRow, type UsageSnapshot } from '../schema.ts';
4
4
  export { OTHER, PALETTE, resolveDevices, type DeviceConfig, type DeviceInfo } from '../devices.ts';
5
- export { summarize, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
5
+ export { summarize, type Bucket, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
6
6
  export type BigSpenderOptions = {
7
7
  /** Directory for the per-device snapshot files. Use a persistent volume. */
8
8
  dataDir: string;
@@ -1,5 +1,5 @@
1
1
  import { createHash, timingSafeEqual } from 'node:crypto';
2
- import { usageSnapshotSchema } from '../schema.js';
2
+ import { CURSOR_DEVICE_ID, usageSnapshotSchema } from '../schema.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;
@@ -80,7 +80,14 @@ export function createIngest({ store, token, onStored }) {
80
80
  .map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);
81
81
  return Response.json({ error: 'invalid snapshot', issues }, { status: 422 });
82
82
  }
83
- const result = await store.save(parsed.data);
83
+ // Checked here, not in the schema: a stored file from before the reservation must still load.
84
+ const snap = parsed.data;
85
+ if (snap.deviceId === CURSOR_DEVICE_ID &&
86
+ (snap.pricingSource !== 'cursor' || snap.hourly.some((r) => r.provider !== 'cursor'))) {
87
+ const issues = [`deviceId: "${CURSOR_DEVICE_ID}" is reserved for Cursor usage`];
88
+ return Response.json({ error: 'invalid snapshot', issues }, { status: 422 });
89
+ }
90
+ const result = await store.save(snap);
84
91
  if (result === 'stored')
85
92
  onStored();
86
93
  return Response.json({
package/dist/summary.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { UsageProvider, UsageRange, UsageSnapshot } from './schema.ts';
2
2
  import { type DeviceConfig } from './devices.ts';
3
+ export type Bucket = 'day' | 'week';
3
4
  export type CostByType = {
4
5
  input: number;
5
6
  cacheRead: number;
@@ -29,8 +30,9 @@ export type ProviderLine = {
29
30
  tokens: number;
30
31
  /** Share of the range's processed tokens. */
31
32
  tokenShare: number;
32
- sessions: number;
33
- /** Cost and tokens per UTC day, aligned with the range's `series`. */
33
+ /** Distinct sessions; null for `all`, which collectors send no count for. */
34
+ sessions: number | null;
35
+ /** Cost and tokens per point, aligned with the range's `series`. */
34
36
  series: {
35
37
  cost: number[];
36
38
  tokens: number[];
@@ -53,8 +55,14 @@ export type RangeSummary = {
53
55
  range: UsageRange;
54
56
  from: string;
55
57
  to: string;
58
+ /** What one point of every series covers: a UTC day, or an ISO week starting Monday UTC. */
59
+ bucket: Bucket;
56
60
  totalCost: number;
57
- sessions: number;
61
+ /**
62
+ * Distinct sessions. Null for `all`: session ids never leave the device, and collectors
63
+ * only count sessions for 7d, 30d and 90d.
64
+ */
65
+ sessions: number | null;
58
66
  tokens: {
59
67
  processed: number;
60
68
  cachedInput: number;
@@ -76,12 +84,16 @@ export type UsageSummary = {
76
84
  type Window = {
77
85
  from: number;
78
86
  to: number;
87
+ step: number;
79
88
  points: number;
89
+ bucket: Bucket;
80
90
  };
81
91
  /**
82
- * Range windows end at the end of the current UTC day and are bucketed by day. Never by hour:
83
- * an hourly breakdown per device would show when each machine is in use.
92
+ * Range windows end at the end of the current UTC day. 7d, 30d and 90d are bucketed by day;
93
+ * `all` starts on the Monday on or before the oldest stored usage and is bucketed by ISO week,
94
+ * so its last point may be a partial week. Never by hour: an hourly breakdown per device would
95
+ * show when each machine is in use.
84
96
  */
85
- export declare function rangeWindow(range: UsageRange, now: number): Window;
97
+ export declare function rangeWindow(range: UsageRange, now: number, snapshots: UsageSnapshot[]): Window;
86
98
  export declare function summarize(snapshots: UsageSnapshot[], now: number, config: DeviceConfig): UsageSummary;
87
99
  export {};
package/dist/summary.js CHANGED
@@ -1,20 +1,36 @@
1
1
  import { resolveDevices } from './devices.js';
2
2
  const DAY_MS = 86_400_000;
3
+ const WEEK_MS = 7 * DAY_MS;
4
+ // 1970-01-01 was a Thursday, so ISO weeks (Monday 00:00 UTC) start 4 days after a multiple of WEEK_MS.
5
+ const MONDAY_OFFSET_MS = 4 * DAY_MS;
6
+ const mondayOnOrBefore = (t) => Math.floor((t - MONDAY_OFFSET_MS) / WEEK_MS) * WEEK_MS + MONDAY_OFFSET_MS;
3
7
  /**
4
- * Range windows end at the end of the current UTC day and are bucketed by day. Never by hour:
5
- * an hourly breakdown per device would show when each machine is in use.
8
+ * Range windows end at the end of the current UTC day. 7d, 30d and 90d are bucketed by day;
9
+ * `all` starts on the Monday on or before the oldest stored usage and is bucketed by ISO week,
10
+ * so its last point may be a partial week. Never by hour: an hourly breakdown per device would
11
+ * show when each machine is in use.
6
12
  */
7
- export function rangeWindow(range, now) {
8
- const days = range === '7d' ? 7 : range === '30d' ? 30 : 90;
13
+ export function rangeWindow(range, now, snapshots) {
9
14
  const to = Math.floor(now / DAY_MS) * DAY_MS + DAY_MS;
10
- return { from: to - days * DAY_MS, to, points: days };
15
+ if (range !== 'all') {
16
+ const days = range === '7d' ? 7 : range === '30d' ? 30 : 90;
17
+ return { from: to - days * DAY_MS, to, step: DAY_MS, points: days, bucket: 'day' };
18
+ }
19
+ let earliest = to - DAY_MS;
20
+ for (const snap of snapshots) {
21
+ earliest = Math.min(earliest, Date.parse(snap.coverageStart));
22
+ for (const r of snap.hourly)
23
+ earliest = Math.min(earliest, Date.parse(r.hour));
24
+ }
25
+ const from = mondayOnOrBefore(earliest);
26
+ return { from, to, step: WEEK_MS, points: Math.ceil((to - from) / WEEK_MS), bucket: 'week' };
11
27
  }
12
28
  const rowCost = (r) => r.costUsd.input + r.costUsd.cacheRead + r.costUsd.cacheWrite + r.costUsd.output;
13
29
  const rowTokens = (r) => r.inputTokens + r.cacheReadTokens + r.cacheWrite5mTokens + r.cacheWrite1hTokens + r.outputTokens;
14
30
  function summarizeRange(range, snapshots, now, resolved) {
15
- const w = rangeWindow(range, now);
31
+ const w = rangeWindow(range, now, snapshots);
16
32
  const series = Array.from({ length: w.points }, (_, i) => ({
17
- start: new Date(w.from + i * DAY_MS).toISOString(),
33
+ start: new Date(w.from + i * w.step).toISOString(),
18
34
  cost: 0,
19
35
  tokens: 0
20
36
  }));
@@ -24,6 +40,7 @@ function summarizeRange(range, snapshots, now, resolved) {
24
40
  const providers = new Map();
25
41
  const devices = new Map();
26
42
  let cacheSavings = 0;
43
+ const countsSessions = range !== 'all';
27
44
  let sessions = 0;
28
45
  const provider = (id) => {
29
46
  let p = providers.get(id);
@@ -34,7 +51,7 @@ function summarizeRange(range, snapshots, now, resolved) {
34
51
  share: 0,
35
52
  tokens: 0,
36
53
  tokenShare: 0,
37
- sessions: 0,
54
+ sessions: countsSessions ? 0 : null,
38
55
  series: {
39
56
  cost: new Array(w.points).fill(0),
40
57
  tokens: new Array(w.points).fill(0)
@@ -56,7 +73,7 @@ function summarizeRange(range, snapshots, now, resolved) {
56
73
  };
57
74
  devices.set(name, device);
58
75
  const active = new Set();
59
- const counts = snap.sessionCounts?.[range];
76
+ const counts = range === 'all' ? undefined : snap.sessionCounts?.[range];
60
77
  for (const r of snap.hourly) {
61
78
  const start = Date.parse(r.hour);
62
79
  if (start < w.from || start >= w.to)
@@ -65,7 +82,7 @@ function summarizeRange(range, snapshots, now, resolved) {
65
82
  const tok = rowTokens(r);
66
83
  if (tok > 0)
67
84
  active.add(r.provider);
68
- const idx = Math.floor((start - w.from) / DAY_MS);
85
+ const idx = Math.floor((start - w.from) / w.step);
69
86
  device.cost += cost;
70
87
  device.series[idx] += cost;
71
88
  series[idx].cost += cost;
@@ -102,10 +119,11 @@ function summarizeRange(range, snapshots, now, resolved) {
102
119
  // that has usage inside this window, so an offline device's old sessions drop out.
103
120
  if (counts) {
104
121
  for (const id of active) {
105
- if (!counts[id])
122
+ const n = counts[id];
123
+ if (!n)
106
124
  continue;
107
- sessions += counts[id];
108
- provider(id).sessions += counts[id];
125
+ sessions += n;
126
+ provider(id).sessions += n;
109
127
  }
110
128
  }
111
129
  }
@@ -120,13 +138,14 @@ function summarizeRange(range, snapshots, now, resolved) {
120
138
  range,
121
139
  from: new Date(w.from).toISOString(),
122
140
  to: new Date(w.to).toISOString(),
141
+ bucket: w.bucket,
123
142
  totalCost,
124
- sessions,
143
+ sessions: countsSessions ? sessions : null,
125
144
  tokens,
126
145
  cacheSavings,
127
146
  costByType,
128
147
  providers: [...providers.values()]
129
- .filter((p) => p.cost > 0 || p.tokens > 0 || p.sessions > 0)
148
+ .filter((p) => p.cost > 0 || p.tokens > 0 || (p.sessions ?? 0) > 0)
130
149
  .map((p) => ({ ...p, share: share(p.cost), tokenShare: tokenShare(p.tokens) }))
131
150
  .sort(byCost),
132
151
  models: [...models.values()]
@@ -144,7 +163,8 @@ export function summarize(snapshots, now, config) {
144
163
  ranges: {
145
164
  '7d': summarizeRange('7d', snapshots, now, resolved),
146
165
  '30d': summarizeRange('30d', snapshots, now, resolved),
147
- '90d': summarizeRange('90d', snapshots, now, resolved)
166
+ '90d': summarizeRange('90d', snapshots, now, resolved),
167
+ all: summarizeRange('all', snapshots, now, resolved)
148
168
  }
149
169
  };
150
170
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "big-spender",
3
- "version": "0.2.0",
3
+ "version": "0.5.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",
@@ -7,3 +7,6 @@ BIG_SPENDER_DEVICE_ID=
7
7
  BIG_SPENDER_INGEST_URL=
8
8
  # Same value as BIG_SPENDER_INGEST_TOKEN on the server.
9
9
  BIG_SPENDER_INGEST_TOKEN=
10
+ # Optional, on one machine only: a Cursor user API key. The collector then reads the account's
11
+ # usage from Cursor's API and sends it as the device "cursor". Set by `big-spender install --cursor`.
12
+ # BIG_SPENDER_CURSOR_API_KEY=