big-spender 0.2.0 → 0.3.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
@@ -19,7 +19,8 @@ their counts are sent. The server rejects any snapshot with extra fields, so not
19
19
  stored or served even by a modified collector.
20
20
 
21
21
  The server never publishes a device's report time (it would show when each machine is online), and
22
- every range is bucketed by UTC day, never by hour. Device ids are published only if you leave
22
+ nothing is bucketed finer than a UTC day: 7, 30 and 90 days are per day, all time is per ISO week
23
+ (Monday UTC). Device ids are published only if you leave
23
24
  `unknownDevices` at its default, see [Device names and colours](#device-names-and-colours).
24
25
 
25
26
  Before the first send you can see exactly what would leave the machine with
@@ -90,7 +91,7 @@ Remove the schedule with `big-spender uninstall`. The env file and the state are
90
91
  | Route | What it does |
91
92
  | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
92
93
  | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
93
- | `GET /api/usage` | Merged totals for 7, 30 and 90 days as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
94
+ | `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`. |
94
95
  | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models. No JavaScript, no external assets, light and dark. |
95
96
  | `GET /healthz` | `ok`, for load balancers and Docker. |
96
97
 
@@ -107,13 +108,15 @@ Configuration comes from flags or environment variables (flags win):
107
108
  The data directory holds one `<device>.json` file per device, written atomically. Put it on a
108
109
  persistent volume. Each snapshot is merged into the device's stored history. A day the snapshot
109
110
  reports replaces that day for each provider and model. Days it does not report are kept as day
110
- rows, so the server keeps usage from beyond the collector's 90-day window. The public ranges still
111
- end at 90 days. A device file holds at most 50,000 rows. Past that, the oldest kept days are dropped
111
+ rows, so the server keeps usage from beyond the collector's 90-day window, and the all-time range
112
+ shows it. All time has no session count (`sessions: null`): collectors count distinct sessions
113
+ on the device for 7, 30 and 90 days only. A device file holds at most 50,000 rows. Past that, the oldest kept days are dropped
112
114
  and the server logs a warning. A snapshot older than the stored one is ignored (`"result":
113
115
  "stale"`), so retries and duplicate posts are harmless. Files in the directory that are not valid snapshots are ignored with a warning.
114
116
 
115
117
  Ingest limits: request bodies up to 2 MB, 16 MB after decompression, `gzip` or `identity` encoding
116
- only. An invalid snapshot gets `422` with the first five problems.
118
+ only. An invalid snapshot gets `422` with the first five problems. Dates before 2020-01-01 are
119
+ invalid.
117
120
 
118
121
  ### Device names and colours
119
122
 
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/schema.d.ts CHANGED
@@ -1,8 +1,9 @@
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
5
  export declare const PROVIDERS: readonly ['claude', 'codex'];
5
- export declare const RANGES: readonly ['7d', '30d', '90d'];
6
+ export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
6
7
  export declare const usageRowSchema: z.ZodObject<{
7
8
  hour: z.ZodISODateTime;
8
9
  granularity: z.ZodOptional<z.ZodEnum<{
package/dist/schema.js CHANGED
@@ -4,12 +4,18 @@ 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
15
  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'];
16
+ // Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
17
+ // than a day: an hourly view would show when each machine is in use.
18
+ export const RANGES = ['7d', '30d', '90d', 'all'];
13
19
  export const usageRowSchema = z.strictObject({
14
20
  hour: isoDate,
15
21
  granularity: z.enum(['hour', 'day']).optional(),
@@ -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;
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;
@@ -120,13 +137,14 @@ function summarizeRange(range, snapshots, now, resolved) {
120
137
  range,
121
138
  from: new Date(w.from).toISOString(),
122
139
  to: new Date(w.to).toISOString(),
140
+ bucket: w.bucket,
123
141
  totalCost,
124
- sessions,
142
+ sessions: countsSessions ? sessions : null,
125
143
  tokens,
126
144
  cacheSavings,
127
145
  costByType,
128
146
  providers: [...providers.values()]
129
- .filter((p) => p.cost > 0 || p.tokens > 0 || p.sessions > 0)
147
+ .filter((p) => p.cost > 0 || p.tokens > 0 || (p.sessions ?? 0) > 0)
130
148
  .map((p) => ({ ...p, share: share(p.cost), tokenShare: tokenShare(p.tokens) }))
131
149
  .sort(byCost),
132
150
  models: [...models.values()]
@@ -144,7 +162,8 @@ export function summarize(snapshots, now, config) {
144
162
  ranges: {
145
163
  '7d': summarizeRange('7d', snapshots, now, resolved),
146
164
  '30d': summarizeRange('30d', snapshots, now, resolved),
147
- '90d': summarizeRange('90d', snapshots, now, resolved)
165
+ '90d': summarizeRange('90d', snapshots, now, resolved),
166
+ all: summarizeRange('all', snapshots, now, resolved)
148
167
  }
149
168
  };
150
169
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "big-spender",
3
- "version": "0.2.0",
3
+ "version": "0.3.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",