big-spender 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jeffreyyvdb
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,265 @@
1
- # Temporary Holding Version
1
+ # big-spender
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ See what your AI coding agents would cost at API prices, summed across all your machines.
4
+
5
+ Each machine runs a small collector every hour. It reads that machine's Claude Code and Codex
6
+ session logs, works out hourly token and cost totals at [LiteLLM](https://github.com/BerriAI/litellm)
7
+ API prices, and posts one snapshot (the last 90 days) to a server you run. The server keeps the
8
+ latest snapshot per device, adds the devices together, and serves the totals as JSON and as a plain
9
+ HTML page. You can also embed the server side in your own app and draw the numbers however you like.
10
+
11
+ The collector has no dependencies and needs Node 20 or newer. The package depends on `zod` only.
12
+
13
+ ## What leaves the machine
14
+
15
+ Only numbers, model names, UTC timestamps, the device id and the pricing source. No paths, working
16
+ directories, prompts, session ids or git branches. Session ids are hashed on the device and only
17
+ their counts are sent. The server rejects any snapshot with extra fields, so nothing else can be
18
+ stored or served even by a modified collector.
19
+
20
+ The server never publishes a device's report time (it would show when each machine is online), and
21
+ every range is bucketed by UTC day, never by hour. Device ids are published only if you leave
22
+ `unknownDevices` at its default, see [Device names and colours](#device-names-and-colours).
23
+
24
+ Before the first send you can see exactly what would leave the machine with
25
+ `big-spender push <device> --dry-run`.
26
+
27
+ ## Quick start
28
+
29
+ ### 1. Run the server
30
+
31
+ With Docker:
32
+
33
+ ```sh
34
+ docker build -t big-spender .
35
+ docker run -d -p 8787:8787 \
36
+ -e BIG_SPENDER_INGEST_TOKEN="$(openssl rand -hex 32)" \
37
+ -v big-spender-data:/data \
38
+ big-spender
39
+ ```
40
+
41
+ Or with Node:
42
+
43
+ ```sh
44
+ export BIG_SPENDER_INGEST_TOKEN="$(openssl rand -hex 32)"
45
+ npx big-spender serve --port 8787 --data ./data
46
+ ```
47
+
48
+ Keep the token: every collector needs it. Open `http://localhost:8787/` for the page and
49
+ `http://localhost:8787/api/usage` for the JSON. Without a token the server still runs, but ingest
50
+ answers `503`.
51
+
52
+ Put the server behind HTTPS (a reverse proxy is enough) before collectors on other machines post to
53
+ it. The token travels in an `Authorization` header.
54
+
55
+ ### 2. Install the collector on each machine
56
+
57
+ ```sh
58
+ npx big-spender install --device laptop --url https://example.com/api/usage/ingest
59
+ ```
60
+
61
+ It asks for the token with a hidden prompt (or reads `BIG_SPENDER_INGEST_TOKEN` from the
62
+ environment, or the existing env file). There is deliberately no flag for it, so it never ends up
63
+ in your shell history or process list. Then it:
64
+
65
+ 1. copies the collector to `~/.local/share/big-spender/collector.mjs`,
66
+ 2. writes `~/.config/big-spender/env` (mode 600) with the device id, URL and token,
67
+ 3. schedules it hourly, and runs it once.
68
+
69
+ The device id is a lowercase slug (`laptop`, `desktop`, `build-box`). Run the command again any
70
+ time to update the installed copy or change the URL; it converges to the same state.
71
+
72
+ The id is fixed once a machine has one. `install --device <other>` stops with an error, because the
73
+ server keeps the old id's `<id>.json` and would count the same 90 days again under the new id. If
74
+ you do mean to rename the device, pass `--rename` and delete the old device's file on the server.
75
+
76
+ | System | Schedule |
77
+ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
78
+ | Linux | systemd user units `big-spender.service` and `big-spender.timer` (`OnCalendar=hourly`, `Persistent=true`). Log: `journalctl --user -u big-spender`. On a headless box, `loginctl enable-linger $USER` keeps the timer running while logged out. |
79
+ | macOS | LaunchAgent `~/Library/LaunchAgents/local.big-spender.plist` (minute 0 of every hour, and at login; a run missed during sleep fires on wake). Log: `~/Library/Logs/big-spender.log`. |
80
+
81
+ Remove the schedule with `big-spender uninstall`. The env file and the state are kept.
82
+
83
+ `big-spender status` prints the last 24 hours on this machine and sends nothing.
84
+
85
+ ## The server
86
+
87
+ `big-spender serve` is a small `node:http` server:
88
+
89
+ | Route | What it does |
90
+ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
91
+ | `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
92
+ | `GET /api/usage` | Merged totals for 7, 30 and 90 days as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
93
+ | `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models. No JavaScript, no external assets, light and dark. |
94
+ | `GET /healthz` | `ok`, for load balancers and Docker. |
95
+
96
+ Configuration comes from flags or environment variables (flags win):
97
+
98
+ | Flag | Environment | Default |
99
+ | ----------- | -------------------------- | ---------------------------------------------------- |
100
+ | `--port` | `PORT` | `8787` |
101
+ | `--host` | `HOST` | `0.0.0.0` |
102
+ | `--data` | `BIG_SPENDER_DATA_DIR` | `./data` (`/data` in the Docker image) |
103
+ | `--devices` | `BIG_SPENDER_DEVICES_FILE` | none: `{ "devices": {}, "unknownDevices": "by-id" }` |
104
+ | | `BIG_SPENDER_INGEST_TOKEN` | none: ingest is off and answers `503` |
105
+
106
+ The data directory holds one `<device>.json` file per device, written atomically. Put it on a
107
+ persistent volume. A snapshot older than the stored one is ignored (`"result": "stale"`), so retries
108
+ and duplicate posts are harmless. Files in the directory that are not valid snapshots are ignored
109
+ with a warning.
110
+
111
+ Ingest limits: request bodies up to 2 MB, 16 MB after decompression, `gzip` or `identity` encoding
112
+ only. An invalid snapshot gets `422` with the first five problems.
113
+
114
+ ### Device names and colours
115
+
116
+ Collectors identify themselves by device id. The server maps each id to the name and colour it
117
+ publishes. Point `--devices` at a JSON file:
118
+
119
+ ```json
120
+ {
121
+ "devices": {
122
+ "laptop": { "name": "Laptop", "color": "#7fa034" },
123
+ "desktop": { "name": "Desktop", "color": "#3899e2" }
124
+ },
125
+ "unknownDevices": "by-id"
126
+ }
127
+ ```
128
+
129
+ Devices are listed in the order you write them. A device that is not listed is, by default,
130
+ shown under its own id with the next free colour. Set `"unknownDevices": "other"` to merge all
131
+ unlisted devices into one "Other" line instead, so no id is ever published. Use this when ids are
132
+ hostnames you would rather keep private.
133
+
134
+ ## Embed it in your own app
135
+
136
+ `big-spender/server` is the same code the standalone server runs, behind web-standard `Request` and
137
+ `Response` objects, so any framework can mount it. SvelteKit:
138
+
139
+ ```ts
140
+ // src/lib/server/usage.ts
141
+ import { createBigSpender } from 'big-spender/server';
142
+ import { env } from '$env/dynamic/private';
143
+
144
+ export const bs = createBigSpender({
145
+ dataDir: env.USAGE_DATA_DIR ?? 'data/usage',
146
+ ingestToken: env.USAGE_INGEST_TOKEN,
147
+ devices: { devices: { laptop: { name: 'Laptop', color: '#7fa034' } }, unknownDevices: 'other' }
148
+ });
149
+
150
+ // src/routes/api/usage/ingest/+server.ts
151
+ import { bs } from '$lib/server/usage';
152
+ export const POST = ({ request }) => bs.ingest(request);
153
+
154
+ // src/routes/api/usage/+server.ts
155
+ import { json } from '@sveltejs/kit';
156
+ import { bs } from '$lib/server/usage';
157
+ export const GET = async ({ setHeaders }) => {
158
+ setHeaders({ 'cache-control': 'public, max-age=300, stale-while-revalidate=900' });
159
+ return json(await bs.summary());
160
+ };
161
+ ```
162
+
163
+ Hono is the same shape (`app.post('/api/usage/ingest', (c) => bs.ingest(c.req.raw))`), and so is a
164
+ Next.js route handler (`export const POST = (request: Request) => bs.ingest(request)`).
165
+
166
+ `createBigSpender({ dataDir, ingestToken, devices })` returns:
167
+
168
+ - `ingest(request)`: handles a collector's `POST` and returns a `Response` (`503` when
169
+ `ingestToken` is missing or empty, `401`, `413`, `415`, `422`, or `200` with
170
+ `{ ok, deviceId, rows, result: 'stored' | 'stale' }`).
171
+ - `summary(now?)`: the merged totals for every range. The result is cached for five minutes and
172
+ recomputed right after an ingest.
173
+
174
+ The module also exports `summarize(snapshots, now, config)`, the snapshot schema
175
+ (`usageSnapshotSchema`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
176
+ own storage or charts.
177
+
178
+ ## Push by hand
179
+
180
+ For a machine that should only report now and then, or where you would rather not store a token:
181
+
182
+ ```sh
183
+ big-spender push laptop --dry-run # review only: per-model overview, the exact JSON, never sends
184
+ big-spender push laptop # same review, then asks before sending
185
+ ```
186
+
187
+ It builds the snapshot and lists the model names it would publish. It stops if a name looks like a
188
+ cloud resource id or gateway path (it contains `arn:` or `/`), such as a Bedrock inference-profile
189
+ ARN with an account id in it. It asks before sending and takes the URL from `--url`,
190
+ `BIG_SPENDER_INGEST_URL` or a prompt, and the token from `BIG_SPENDER_INGEST_TOKEN` or a hidden
191
+ prompt. Neither is stored. Nothing is scheduled, so the server shows that device's usage as of its
192
+ last push.
193
+
194
+ `--dry-run` writes the JSON that would be sent to `$TMPDIR/big-spender-snapshot-<device>.json`.
195
+
196
+ ## Check the numbers
197
+
198
+ ```sh
199
+ big-spender status # last 24 hours on this machine, nothing sent
200
+ node ~/.local/share/big-spender/collector.mjs --dry-run # the full snapshot JSON, nothing sent
201
+ ```
202
+
203
+ Compare with [ccusage](https://github.com/ryoppippi/ccusage) on the same machine. Use the `claude`
204
+ subcommand: plain `npx ccusage` also adds other CLIs that the collector does not read. Claude Code
205
+ tokens and cost should match per model:
206
+
207
+ ```sh
208
+ npx ccusage@latest claude daily --since 20260819 --breakdown
209
+ ```
210
+
211
+ ccusage groups by local date and the collector by UTC hour, so single days can shift a little at the
212
+ edges. Tools that price every cache write at the 5-minute rate and ignore long-context prices show
213
+ about 15 to 20 percent less.
214
+
215
+ ## How it counts
216
+
217
+ | Source | Files | Notes |
218
+ | ----------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
219
+ | Claude Code | `~/.claude/projects/**/*.jsonl`, `~/.config/claude/projects`, `$CLAUDE_CONFIG_DIR/projects` | `assistant` lines; de-duplicated by `message.id` + `requestId` (one API response is logged once per content block, and resumed sessions copy history). `<synthetic>` skipped; subagent logs included. Some Claude Code versions (2.1.293 to 2.1.310) log a partial output count on a message's first line and the final count on a later line; a later line that reports more output adds the difference. |
220
+ | Codex | `~/.codex/sessions/**/rollout-*.jsonl`, `$CODEX_HOME/sessions` | `event_msg` / `token_count` with `info.last_token_usage`; skipped when `total_token_usage` did not change. Model from the latest `turn_context`. `cached_input_tokens` is part of `input_tokens`; reasoning is part of `output_tokens`. |
221
+
222
+ **Pricing.** LiteLLM `model_prices_and_context_window.json`, cached for 24 hours in
223
+ `~/.cache/big-spender/`. Lookup tries the exact model, then `anthropic/` or `openai/` prefixes, then
224
+ without a date suffix. Unknown models count with cost 0 and log a warning. Long-context tiers
225
+ (`*_above_<N>k_tokens`) are applied per request; 1-hour cache writes use
226
+ `cache_creation_input_token_cost_above_1hr`. Cache savings are cache-read tokens times (input price
227
+ minus cache-read price).
228
+
229
+ **Incremental.** `~/.cache/big-spender/state.json` keeps per-file byte offsets plus the hourly
230
+ aggregates, so each run parses only new bytes but still sends the full 90-day snapshot. Rows older
231
+ than 7 days are rolled up to daily rows. Because the aggregates live in the state file, usage stays
232
+ counted even after Claude Code deletes old session logs. `--reset` rebuilds from the logs that still
233
+ exist, so avoid it unless the state is corrupt.
234
+
235
+ State from an older collector is fixed in place on the first run of a newer one (for example, one
236
+ re-read of the Claude logs to pick up missed output tokens), so updating never needs `--reset`.
237
+
238
+ A machine that was off catches up on its next run. A failed post retries with backoff and exits
239
+ non-zero; the token is never logged.
240
+
241
+ ## Coming from the earlier standalone script
242
+
243
+ `big-spender install` migrates an install of the earlier `usage-collector` script in place: it
244
+ removes the old systemd units or LaunchAgent, moves its config and state (so history is kept
245
+ byte for byte), renames the `USAGE_*` keys in the env file to `BIG_SPENDER_*`, and deletes the old
246
+ copy of the script. If the old collector is running at that moment it waits for you to run install
247
+ again. The collector still reads `USAGE_DEVICE_ID`, `USAGE_INGEST_URL` and `USAGE_INGEST_TOKEN`
248
+ when the `BIG_SPENDER_*` name is unset, so a machine you have not updated keeps working.
249
+
250
+ ## Development
251
+
252
+ ```sh
253
+ npm install
254
+ npm run build # tsc, then copies the collector into dist/
255
+ npm run check # type check
256
+ npm test # node:test; needs Node 22.18 or newer, which runs the TypeScript directly
257
+ ```
258
+
259
+ The tests never call `systemctl` or `launchctl` and never touch your real config or cache:
260
+ `BIG_SPENDER_SCHEDULER=none` turns scheduler calls into no-ops, and each test runs in a throwaway
261
+ `HOME`.
262
+
263
+ ## License
264
+
265
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { type Context } from './context.ts';
3
+ type Command = {
4
+ summary: string;
5
+ usage: string;
6
+ run(args: string[], ctx: Context): Promise<number>;
7
+ };
8
+ export declare const commands: Record<string, Command>;
9
+ export declare function main(argv: string[], ctx: Context): Promise<number>;
10
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { realpathSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { defaultContext, UsageError } from './context.js';
6
+ import { install, INSTALL_USAGE, uninstall, UNINSTALL_USAGE } from './install.js';
7
+ import { push, PUSH_USAGE } from './push.js';
8
+ import { serve, SERVE_USAGE } from './serve.js';
9
+ const status = {
10
+ summary: "Print this machine's 24h usage summary. Sends nothing.",
11
+ usage: 'Usage: big-spender status',
12
+ run: (_args, ctx) => new Promise((resolve) => {
13
+ const child = spawn(process.execPath, [ctx.collector, '--summary'], {
14
+ env: ctx.env,
15
+ stdio: 'inherit'
16
+ });
17
+ child.on('close', (code) => resolve(code ?? 1));
18
+ })
19
+ };
20
+ export const commands = {
21
+ install: {
22
+ summary: 'Schedule the collector on this machine and run it once.',
23
+ usage: INSTALL_USAGE,
24
+ run: install
25
+ },
26
+ uninstall: {
27
+ summary: 'Remove the schedule. Keeps the env file and state.',
28
+ usage: UNINSTALL_USAGE,
29
+ run: uninstall
30
+ },
31
+ push: {
32
+ summary: 'Review and send one snapshot by hand, without a schedule.',
33
+ usage: PUSH_USAGE,
34
+ run: push
35
+ },
36
+ status,
37
+ serve: {
38
+ summary: 'Run the server: ingest, JSON API and a plain HTML page.',
39
+ usage: SERVE_USAGE,
40
+ run: async (args) => {
41
+ await serve(args);
42
+ return 0;
43
+ }
44
+ },
45
+ help: {
46
+ summary: 'Show this help, or help for one command.',
47
+ usage: 'Usage: big-spender help [command]',
48
+ run: async (args, ctx) => {
49
+ const [name] = args;
50
+ if (name && Object.hasOwn(commands, name))
51
+ ctx.out(commands[name].usage);
52
+ else
53
+ ctx.out(helpText());
54
+ return 0;
55
+ }
56
+ }
57
+ };
58
+ function helpText() {
59
+ const width = Math.max(...Object.keys(commands).map((n) => n.length));
60
+ return [
61
+ 'big-spender: track what your AI coding agents would cost at API prices.',
62
+ '',
63
+ 'Usage: big-spender <command> [options]',
64
+ '',
65
+ ...Object.entries(commands).map(([name, c]) => ` ${name.padEnd(width)} ${c.summary}`),
66
+ '',
67
+ "Run `big-spender help <command>` for a command's options."
68
+ ].join('\n');
69
+ }
70
+ export async function main(argv, ctx) {
71
+ const [name, ...args] = argv;
72
+ if (!name || name === '--help' || name === '-h') {
73
+ ctx.out(helpText());
74
+ return name ? 0 : 2;
75
+ }
76
+ if (!Object.hasOwn(commands, name)) {
77
+ ctx.err(`unknown command "${name}"\n\n${helpText()}`);
78
+ return 2;
79
+ }
80
+ const command = commands[name];
81
+ if (args.includes('--help') || args.includes('-h')) {
82
+ ctx.out(command.usage);
83
+ return 0;
84
+ }
85
+ try {
86
+ return await command.run(args, ctx);
87
+ }
88
+ catch (err) {
89
+ const message = err instanceof Error ? err.message : String(err);
90
+ const isUsage = err instanceof UsageError || err.code?.startsWith('ERR_PARSE_ARGS');
91
+ ctx.err(`big-spender ${name}: ${message}`);
92
+ if (isUsage)
93
+ ctx.err(`\n${command.usage}`);
94
+ return isUsage ? 2 : 1;
95
+ }
96
+ finally {
97
+ if (name !== 'serve')
98
+ ctx.dispose();
99
+ }
100
+ }
101
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
102
+ main(process.argv.slice(2), defaultContext()).then((code) => {
103
+ if (code !== 0)
104
+ process.exitCode = code;
105
+ });
106
+ }