big-spender 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +272 -2
- package/dist/cli.d.ts +10 -0
- package/dist/cli.js +106 -0
- package/dist/collector.mjs +779 -0
- package/dist/context.d.ts +22 -0
- package/dist/context.js +19 -0
- package/dist/devices.d.ts +22 -0
- package/dist/devices.js +24 -0
- package/dist/envfile.d.ts +12 -0
- package/dist/envfile.js +46 -0
- package/dist/history.d.ts +5 -0
- package/dist/history.js +85 -0
- package/dist/install.d.ts +5 -0
- package/dist/install.js +211 -0
- package/dist/page.d.ts +2 -0
- package/dist/page.js +88 -0
- package/dist/paths.d.ts +23 -0
- package/dist/paths.js +31 -0
- package/dist/prompt.d.ts +7 -0
- package/dist/prompt.js +38 -0
- package/dist/push.d.ts +3 -0
- package/dist/push.js +156 -0
- package/dist/scheduler.d.ts +24 -0
- package/dist/scheduler.js +153 -0
- package/dist/schema.d.ts +89 -0
- package/dist/schema.js +57 -0
- package/dist/serve.d.ts +14 -0
- package/dist/serve.js +138 -0
- package/dist/server/index.d.ts +19 -0
- package/dist/server/index.js +27 -0
- package/dist/server/ingest.d.ts +7 -0
- package/dist/server/ingest.js +93 -0
- package/dist/store.d.ts +7 -0
- package/dist/store.js +68 -0
- package/dist/summary.d.ts +87 -0
- package/dist/summary.js +150 -0
- package/package.json +65 -5
- package/templates/big-spender.service +14 -0
- package/templates/big-spender.timer +12 -0
- package/templates/env.example +9 -0
- package/templates/local.big-spender.plist +39 -0
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,273 @@
|
|
|
1
|
-
#
|
|
1
|
+
# big-spender
|
|
2
2
|
|
|
3
|
-
|
|
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 merges each
|
|
8
|
+
snapshot into that device's stored history, adds the devices together, and serves the totals as
|
|
9
|
+
JSON and as a plain HTML page. You can also embed the server side in your own app and draw the
|
|
10
|
+
numbers however you like.
|
|
11
|
+
|
|
12
|
+
The collector has no dependencies and needs Node 20 or newer. The package depends on `zod` only.
|
|
13
|
+
|
|
14
|
+
## What leaves the machine
|
|
15
|
+
|
|
16
|
+
Only numbers, model names, UTC timestamps, the device id and the pricing source. No paths, working
|
|
17
|
+
directories, prompts, session ids or git branches. Session ids are hashed on the device and only
|
|
18
|
+
their counts are sent. The server rejects any snapshot with extra fields, so nothing else can be
|
|
19
|
+
stored or served even by a modified collector.
|
|
20
|
+
|
|
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
|
|
23
|
+
`unknownDevices` at its default, see [Device names and colours](#device-names-and-colours).
|
|
24
|
+
|
|
25
|
+
Before the first send you can see exactly what would leave the machine with
|
|
26
|
+
`big-spender push <device> --dry-run`.
|
|
27
|
+
|
|
28
|
+
## Quick start
|
|
29
|
+
|
|
30
|
+
### 1. Run the server
|
|
31
|
+
|
|
32
|
+
With Docker:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
docker build -t big-spender .
|
|
36
|
+
docker run -d -p 8787:8787 \
|
|
37
|
+
-e BIG_SPENDER_INGEST_TOKEN="$(openssl rand -hex 32)" \
|
|
38
|
+
-v big-spender-data:/data \
|
|
39
|
+
big-spender
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Or with Node:
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
export BIG_SPENDER_INGEST_TOKEN="$(openssl rand -hex 32)"
|
|
46
|
+
npx big-spender serve --port 8787 --data ./data
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Keep the token: every collector needs it. Open `http://localhost:8787/` for the page and
|
|
50
|
+
`http://localhost:8787/api/usage` for the JSON. Without a token the server still runs, but ingest
|
|
51
|
+
answers `503`.
|
|
52
|
+
|
|
53
|
+
Put the server behind HTTPS (a reverse proxy is enough) before collectors on other machines post to
|
|
54
|
+
it. The token travels in an `Authorization` header.
|
|
55
|
+
|
|
56
|
+
### 2. Install the collector on each machine
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
npx big-spender install --device laptop --url https://example.com/api/usage/ingest
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
It asks for the token with a hidden prompt (or reads `BIG_SPENDER_INGEST_TOKEN` from the
|
|
63
|
+
environment, or the existing env file). There is deliberately no flag for it, so it never ends up
|
|
64
|
+
in your shell history or process list. Then it:
|
|
65
|
+
|
|
66
|
+
1. copies the collector to `~/.local/share/big-spender/collector.mjs`,
|
|
67
|
+
2. writes `~/.config/big-spender/env` (mode 600) with the device id, URL and token,
|
|
68
|
+
3. schedules it hourly, and runs it once.
|
|
69
|
+
|
|
70
|
+
The device id is a lowercase slug (`laptop`, `desktop`, `build-box`). Run the command again any
|
|
71
|
+
time to update the installed copy or change the URL; it converges to the same state.
|
|
72
|
+
|
|
73
|
+
The id is fixed once a machine has one. `install --device <other>` stops with an error, because the
|
|
74
|
+
server keeps the old id's `<id>.json` and would count the same 90 days again under the new id. If
|
|
75
|
+
you do mean to rename the device, pass `--rename` and delete the old device's file on the server.
|
|
76
|
+
|
|
77
|
+
| System | Schedule |
|
|
78
|
+
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
79
|
+
| 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. |
|
|
80
|
+
| 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`. |
|
|
81
|
+
|
|
82
|
+
Remove the schedule with `big-spender uninstall`. The env file and the state are kept.
|
|
83
|
+
|
|
84
|
+
`big-spender status` prints the last 24 hours on this machine and sends nothing.
|
|
85
|
+
|
|
86
|
+
## The server
|
|
87
|
+
|
|
88
|
+
`big-spender serve` is a small `node:http` server:
|
|
89
|
+
|
|
90
|
+
| Route | What it does |
|
|
91
|
+
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
92
|
+
| `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 /` | A plain server-rendered page: totals per range, devices with colour swatches, top models. No JavaScript, no external assets, light and dark. |
|
|
95
|
+
| `GET /healthz` | `ok`, for load balancers and Docker. |
|
|
96
|
+
|
|
97
|
+
Configuration comes from flags or environment variables (flags win):
|
|
98
|
+
|
|
99
|
+
| Flag | Environment | Default |
|
|
100
|
+
| ----------- | -------------------------- | ---------------------------------------------------- |
|
|
101
|
+
| `--port` | `PORT` | `8787` |
|
|
102
|
+
| `--host` | `HOST` | `0.0.0.0` |
|
|
103
|
+
| `--data` | `BIG_SPENDER_DATA_DIR` | `./data` (`/data` in the Docker image) |
|
|
104
|
+
| `--devices` | `BIG_SPENDER_DEVICES_FILE` | none: `{ "devices": {}, "unknownDevices": "by-id" }` |
|
|
105
|
+
| | `BIG_SPENDER_INGEST_TOKEN` | none: ingest is off and answers `503` |
|
|
106
|
+
|
|
107
|
+
The data directory holds one `<device>.json` file per device, written atomically. Put it on a
|
|
108
|
+
persistent volume. Each snapshot is merged into the device's stored history. A day the snapshot
|
|
109
|
+
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
|
|
112
|
+
and the server logs a warning. A snapshot older than the stored one is ignored (`"result":
|
|
113
|
+
"stale"`), so retries and duplicate posts are harmless. Files in the directory that are not valid snapshots are ignored with a warning.
|
|
114
|
+
|
|
115
|
+
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.
|
|
117
|
+
|
|
118
|
+
### Device names and colours
|
|
119
|
+
|
|
120
|
+
Collectors identify themselves by device id. The server maps each id to the name and colour it
|
|
121
|
+
publishes. Point `--devices` at a JSON file:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"devices": {
|
|
126
|
+
"laptop": { "name": "Laptop", "color": "#7fa034" },
|
|
127
|
+
"desktop": { "name": "Desktop", "color": "#3899e2" }
|
|
128
|
+
},
|
|
129
|
+
"unknownDevices": "by-id"
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Devices are listed in the order you write them. A device that is not listed is, by default,
|
|
134
|
+
shown under its own id with the next free colour. Set `"unknownDevices": "other"` to merge all
|
|
135
|
+
unlisted devices into one "Other" line instead, so no id is ever published. Use this when ids are
|
|
136
|
+
hostnames you would rather keep private.
|
|
137
|
+
|
|
138
|
+
## Embed it in your own app
|
|
139
|
+
|
|
140
|
+
`big-spender/server` is the same code the standalone server runs, behind web-standard `Request` and
|
|
141
|
+
`Response` objects, so any framework can mount it. SvelteKit:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// src/lib/server/usage.ts
|
|
145
|
+
import { createBigSpender } from 'big-spender/server';
|
|
146
|
+
import { env } from '$env/dynamic/private';
|
|
147
|
+
|
|
148
|
+
export const bs = createBigSpender({
|
|
149
|
+
dataDir: env.USAGE_DATA_DIR ?? 'data/usage',
|
|
150
|
+
ingestToken: env.USAGE_INGEST_TOKEN,
|
|
151
|
+
devices: { devices: { laptop: { name: 'Laptop', color: '#7fa034' } }, unknownDevices: 'other' }
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// src/routes/api/usage/ingest/+server.ts
|
|
155
|
+
import { bs } from '$lib/server/usage';
|
|
156
|
+
export const POST = ({ request }) => bs.ingest(request);
|
|
157
|
+
|
|
158
|
+
// src/routes/api/usage/+server.ts
|
|
159
|
+
import { json } from '@sveltejs/kit';
|
|
160
|
+
import { bs } from '$lib/server/usage';
|
|
161
|
+
export const GET = async ({ setHeaders }) => {
|
|
162
|
+
setHeaders({ 'cache-control': 'public, max-age=300, stale-while-revalidate=900' });
|
|
163
|
+
return json(await bs.summary());
|
|
164
|
+
};
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Hono is the same shape (`app.post('/api/usage/ingest', (c) => bs.ingest(c.req.raw))`), and so is a
|
|
168
|
+
Next.js route handler (`export const POST = (request: Request) => bs.ingest(request)`).
|
|
169
|
+
|
|
170
|
+
`createBigSpender({ dataDir, ingestToken, devices })` returns:
|
|
171
|
+
|
|
172
|
+
- `ingest(request)`: handles a collector's `POST` and returns a `Response` (`503` when
|
|
173
|
+
`ingestToken` is missing or empty, `401`, `413`, `415`, `422`, or `200` with
|
|
174
|
+
`{ ok, deviceId, rows, result: 'stored' | 'stale' }`).
|
|
175
|
+
- `summary(now?)`: the merged totals for every range. The result is cached for five minutes and
|
|
176
|
+
recomputed right after an ingest.
|
|
177
|
+
|
|
178
|
+
The module also exports `summarize(snapshots, now, config)`, the snapshot schema
|
|
179
|
+
(`usageSnapshotSchema`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
|
|
180
|
+
own storage or charts.
|
|
181
|
+
|
|
182
|
+
## Push by hand
|
|
183
|
+
|
|
184
|
+
For a machine that should only report now and then, or where you would rather not store a token:
|
|
185
|
+
|
|
186
|
+
```sh
|
|
187
|
+
big-spender push laptop --dry-run # review only: per-model overview, the exact JSON, never sends
|
|
188
|
+
big-spender push laptop # same review, then asks before sending
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
It builds the snapshot and lists the model names it would publish. It stops if a name looks like a
|
|
192
|
+
cloud resource id or gateway path (it contains `arn:` or `/`), such as a Bedrock inference-profile
|
|
193
|
+
ARN with an account id in it. It asks before sending, sends exactly the JSON it showed, and takes
|
|
194
|
+
the URL from `--url`, `BIG_SPENDER_INGEST_URL` or a prompt, and the token from
|
|
195
|
+
`BIG_SPENDER_INGEST_TOKEN` or a hidden prompt. Neither is stored. Nothing is scheduled, so the
|
|
196
|
+
server shows that device's usage as of its last push.
|
|
197
|
+
|
|
198
|
+
`--dry-run` writes the JSON that would be sent to `$TMPDIR/big-spender-snapshot-<device>.json`.
|
|
199
|
+
|
|
200
|
+
## Check the numbers
|
|
201
|
+
|
|
202
|
+
```sh
|
|
203
|
+
big-spender status # last 24 hours on this machine, nothing sent
|
|
204
|
+
node ~/.local/share/big-spender/collector.mjs --dry-run # the full snapshot JSON, nothing sent
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Compare with [ccusage](https://github.com/ryoppippi/ccusage) on the same machine. Use the `claude`
|
|
208
|
+
subcommand: plain `npx ccusage` also adds other CLIs that the collector does not read. Claude Code
|
|
209
|
+
tokens and cost should match per model:
|
|
210
|
+
|
|
211
|
+
```sh
|
|
212
|
+
npx ccusage@latest claude daily --since 20260819 --breakdown
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
ccusage groups by local date and the collector by UTC hour, so single days can shift a little at the
|
|
216
|
+
edges. Tools that price every cache write at the 5-minute rate and ignore long-context prices show
|
|
217
|
+
about 15 to 20 percent less.
|
|
218
|
+
|
|
219
|
+
## How it counts
|
|
220
|
+
|
|
221
|
+
| Source | Files | Notes |
|
|
222
|
+
| ----------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
223
|
+
| 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. |
|
|
224
|
+
| 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`. |
|
|
225
|
+
|
|
226
|
+
**Pricing.** LiteLLM `model_prices_and_context_window.json`, cached for 24 hours in
|
|
227
|
+
`~/.cache/big-spender/`. Lookup tries the exact model, then `anthropic/` or `openai/` prefixes, then
|
|
228
|
+
without a date suffix. Unknown models count with cost 0 and log a warning. Long-context tiers
|
|
229
|
+
(`*_above_<N>k_tokens`) are applied per request; 1-hour cache writes use
|
|
230
|
+
`cache_creation_input_token_cost_above_1hr`. Cache savings are cache-read tokens times (input price
|
|
231
|
+
minus cache-read price).
|
|
232
|
+
|
|
233
|
+
**Incremental.** `~/.cache/big-spender/state.json` keeps per-file byte offsets plus the hourly
|
|
234
|
+
aggregates, so each run parses only new bytes but still sends the full 90-day snapshot. Rows older
|
|
235
|
+
than 7 days are rolled up to daily rows. Because the aggregates live in the state file, usage stays
|
|
236
|
+
counted even after Claude Code deletes old session logs. `--reset` rebuilds from the logs that still
|
|
237
|
+
exist, so avoid it unless the state is corrupt.
|
|
238
|
+
|
|
239
|
+
State from an older collector is fixed in place on the first run of a newer one (for example, one
|
|
240
|
+
re-read of the Claude logs to pick up missed output tokens), so updating never needs `--reset`.
|
|
241
|
+
|
|
242
|
+
A machine that was off catches up on its next run. A failed post retries with backoff and exits
|
|
243
|
+
non-zero; the token is never logged. A token with a space, a control character or anything else an
|
|
244
|
+
HTTP header cannot carry fails at once, without a retry, in both the collector and `push`.
|
|
245
|
+
|
|
246
|
+
## Coming from the earlier standalone script
|
|
247
|
+
|
|
248
|
+
`big-spender install` migrates an install of the earlier `usage-collector` script in place: it
|
|
249
|
+
removes the old systemd units or LaunchAgent, moves its config and state (so history is kept byte
|
|
250
|
+
for byte), renames the `USAGE_*` keys in the env file to `BIG_SPENDER_*`, and deletes the old copy
|
|
251
|
+
of the script. If `status` or `push` already made a new cache, the old state replaces it only while
|
|
252
|
+
the old collector is still scheduled or wrote its state last; otherwise the old cache is left in
|
|
253
|
+
place and the newer one kept. If the old collector, or a `status` or `push` whose cache would be
|
|
254
|
+
replaced, is running at that moment, install changes nothing and asks you to run it again. The
|
|
255
|
+
collector still reads `USAGE_DEVICE_ID`, `USAGE_INGEST_URL` and `USAGE_INGEST_TOKEN` when the
|
|
256
|
+
`BIG_SPENDER_*` name is unset, so a machine you have not updated keeps working.
|
|
257
|
+
|
|
258
|
+
## Development
|
|
259
|
+
|
|
260
|
+
```sh
|
|
261
|
+
npm install
|
|
262
|
+
npm run build # tsc, then copies the collector into dist/
|
|
263
|
+
npm run check # type check
|
|
264
|
+
npm test # node:test; needs Node 22.18 or newer, which runs the TypeScript directly
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
The tests never call `systemctl` or `launchctl` and never touch your real config or cache:
|
|
268
|
+
`BIG_SPENDER_SCHEDULER=none` turns scheduler calls into no-ops, and each test runs in a throwaway
|
|
269
|
+
`HOME`.
|
|
270
|
+
|
|
271
|
+
## License
|
|
272
|
+
|
|
273
|
+
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
|
+
}
|