big-spender 0.10.0 → 0.12.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 +42 -12
- package/dist/collector.mjs +594 -32
- package/dist/history.js +10 -0
- package/dist/schema.d.ts +9 -1
- package/dist/schema.js +2 -1
- package/package.json +1 -1
- package/templates/env.example +4 -0
package/README.md
CHANGED
|
@@ -248,21 +248,32 @@ own storage or charts.
|
|
|
248
248
|
## Usage limits
|
|
249
249
|
|
|
250
250
|
Besides cost, the collector records when you run out of your Claude and Codex subscription
|
|
251
|
-
allowance, so you can judge whether a plan fits how you work. It reads
|
|
252
|
-
|
|
251
|
+
allowance, so you can judge whether a plan fits how you work. It reads what the agents write to
|
|
252
|
+
their local logs, and it polls their usage endpoints (see [Polling](#polling-usage-endpoints)).
|
|
253
253
|
|
|
254
254
|
- **Claude Code.** A refused request is logged as an `assistant` line with `error: "rate_limit"`
|
|
255
255
|
and a `quotaLimits` object that names the window (`five_hour`, `seven_day`, a model-specific
|
|
256
256
|
weekly window such as `seven_day_opus`) and when it resets. Retries repeat the line, so one
|
|
257
|
-
blocked window becomes one record. Claude Code logs nothing when a request is allowed, so
|
|
258
|
-
utilisation below 100
|
|
257
|
+
blocked window becomes one record. Claude Code logs nothing when a request is allowed, so the logs
|
|
258
|
+
alone say nothing about utilisation below 100%; polling fills that in.
|
|
259
259
|
- **Codex.** `token_count` events carry `rate_limits` with the used percentage and reset time of the
|
|
260
|
-
5-hour window (`five_hour`, 300 minutes) and the weekly window (`seven_day`, 10080 minutes).
|
|
261
|
-
|
|
260
|
+
5-hour window (`five_hour`, 300 minutes) and the weekly window (`seven_day`, 10080 minutes). A
|
|
261
|
+
window counts as hit when its share reaches 100%. A refused turn is logged too, but names no
|
|
262
|
+
window and no reset. It starts the lockout of each Codex window seen full (by a poll or any log
|
|
263
|
+
line) that was open at that moment, so the lockout begins at the first logged refusal instead of
|
|
264
|
+
at the next poll. When no open window was seen full, a lockout that began and
|
|
265
|
+
ended between two runs can still be placed by elimination. Usage in a window instance only rises
|
|
266
|
+
until it resets, so a poll that read an instance below 100% after the refusal proves it was not
|
|
267
|
+
the one blocking. This needs a successful poll in the same run that read both Codex windows, and
|
|
268
|
+
every limit it reports must have an instance on file that was open at the refusal. If exactly one open window is then left,
|
|
269
|
+
it gets the hit at the refusal. The gap that remains is a refusal whose window no reading ever
|
|
270
|
+
saw, one where several windows stay possible, and any refusal read while polling is off or
|
|
271
|
+
failing. These change nothing.
|
|
262
272
|
|
|
263
273
|
A record is one window instance, identified by provider, window name and reset time rounded down
|
|
264
274
|
to the minute. Reports whose resets are at most two minutes apart are the same window, because one
|
|
265
|
-
window's reported reset can drift by a few seconds.
|
|
275
|
+
window's reported reset can drift by a few seconds. A push sends at most the 5,000 newest records,
|
|
276
|
+
the most the server accepts. It holds the peak percentage seen and the time of the first refusal. Limits belong
|
|
266
277
|
to the account, not the machine, so merging keeps the highest peak and the earliest refusal, and
|
|
267
278
|
two machines that report the same window count once. Records are kept for 90 days on the collector and up to 5,000 windows on the
|
|
268
279
|
server, like day rows.
|
|
@@ -277,9 +288,27 @@ finer than a UTC day, no device names, no report times. It is separate from `/ap
|
|
|
277
288
|
shape did not change. `big-spender status` also lists the limits hit in the last 7 days, to the
|
|
278
289
|
minute, because that output never leaves the machine.
|
|
279
290
|
|
|
280
|
-
Polling
|
|
281
|
-
|
|
282
|
-
|
|
291
|
+
### Polling usage endpoints
|
|
292
|
+
|
|
293
|
+
Logs only show a limit when a request is refused, which hides how much of a window you leave
|
|
294
|
+
unused. So each run also asks Anthropic and OpenAI how full your windows are right now, the same
|
|
295
|
+
numbers `/usage` in Claude Code and Codex show. Claude is polled at `api.anthropic.com` and Codex at
|
|
296
|
+
`chatgpt.com`, with the login the agent already keeps: `~/.claude/.credentials.json`
|
|
297
|
+
(`$CLAUDE_CONFIG_DIR` if set) and `~/.codex/auth.json` (`$CODEX_HOME` if set). The collector opens
|
|
298
|
+
those files read-only, never refreshes them and sends the token only to that provider. If a token
|
|
299
|
+
has expired, that provider is skipped with one warning until you run the agent again. A missing
|
|
300
|
+
file means that provider is not polled, without a warning. A failed poll never fails the run.
|
|
301
|
+
|
|
302
|
+
Each reading is a peak for the same window record the logs feed. Windows are named `five_hour` and
|
|
303
|
+
`seven_day`, plus one `seven_day_<model>` per model-specific weekly (`seven_day_fable`,
|
|
304
|
+
`seven_day_opus`). Codex's extra limits become `<window>_<limit name>`. Only the window name, reset
|
|
305
|
+
time and percentage are stored or sent.
|
|
306
|
+
|
|
307
|
+
Claude Code logs a refusal of Fable's weekly as `seven_day_overage_included` and labels it "Fable
|
|
308
|
+
limit". The endpoint reports the same limit as `seven_day_fable`, so the collector records those
|
|
309
|
+
refusals as `seven_day_fable`, and they join the polled readings in one record.
|
|
310
|
+
|
|
311
|
+
To turn polling off, set `BIG_SPENDER_POLL_LIMITS=off` in the env file.
|
|
283
312
|
|
|
284
313
|
An older server rejects the unknown `limits` field with a 422. The collector and `push` then send
|
|
285
314
|
the snapshot again without it and print a warning on each run, so usage keeps arriving. Upgrade the server to store
|
|
@@ -338,7 +367,8 @@ about 15 to 20 percent less.
|
|
|
338
367
|
| Antigravity (experimental) | `~/.gemini/antigravity*/conversations/**/*.db`, `~/.config/antigravity/conversations` | **Experimental:** read only with `BIG_SPENDER_EXPERIMENTAL=antigravity`; checked against ccusage on test fixtures, not yet against real Antigravity data. `antigravity*` is `antigravity` and its `-cli`, `-ide`, `-backup` and `-acp` variants; `$ANTIGRAVITY_DATA_DIR` (comma-separated) is read too. Read with `node:sqlite` (Node 22.13+, else skipped with a warning). Usage messages in `gen_metadata` and `steps`, retries included; copies sharing a response, provider or message id merge and keep the largest counts. A later copy can move a response to another day or model; the day and model it left are sent as a zero row, which takes them back on the server. A model name with a slash (possibly a path) becomes `gemini-internal-model`. Reasoning is part of output. |
|
|
339
368
|
| Gemini CLI (experimental) | `~/.gemini/tmp/**/*.json` and `*.jsonl`, `$GEMINI_DATA_DIR` (comma-separated) | **Experimental:** read only with `BIG_SPENDER_EXPERIMENTAL=gemini`; checked against ccusage on test fixtures, not yet against real Gemini CLI data. `gemini` chat messages with `tokens`, and saved headless `stats` (per model, or with the last model named, else `unknown`). A changed file is read whole and its counts replace what it counted before, as ccusage counts each file as it is; in JSONL the last copy of a message id counts. `input` excludes `cached` when the total shows it was inside (always in stats), and `tool` tokens count as input. Reasoning (`thoughts`) and any total beyond the parts count as output, as ccusage bills them, though its per-model output leaves reasoning out. A model id that is a file path is reduced to its file name. `$GEMINI_DATA_DIR` adds dirs to the default rather than replacing it. |
|
|
340
369
|
|
|
341
|
-
**Pricing.** Claude Code, Codex, pi, Grok Build, GitHub Copilot CLI, Antigravity
|
|
370
|
+
**Pricing.** Claude Code, Codex, pi, Grok Build, GitHub Copilot CLI, Antigravity, Gemini CLI and OpenCode use LiteLLM
|
|
371
|
+
| OpenCode | `~/.local/share/opencode` (or `$XDG_DATA_HOME/opencode`), or `$OPENCODE_DATA_DIR` (comma-separated, replaces the default): `opencode.db` and pre-SQLite `storage/message/**/*.json` | Assistant messages, and `completed` compaction rows, from the 1.x `message` table, the 2.x `session_message` table and the JSON files. The first copy of a message id wins, because 2.x copies the 1.x rows; A 2.x fork's copies of its parent's rows keep the parent rows' times, so rows older than the fork are skipped, as OpenCode's own stats do; this holds after the parent is deleted, and a parent deleted before big-spender read it is not counted. Needs `node:sqlite` (Node 22.13+). OpenCode rewrites a running message, so each run reads the window again and adds what changed; an hour and model a message left are sent as a zero row, which takes them back on the server. Cache reads and writes are outside `input`. 1.x counts reasoning in `output`; 2.x does not, so it is added. `claude-agent` rows are skipped, because the Claude Code source counts them. A model id that is a file path, a URL, or ends in a model-file extension (`.gguf`, `.safetensors`, ...) is cut to its file name, without query or login; an address with no file name is sent as `local`. OpenCode's own `cost` is not used; a model is priced under the first upstream it was seen on. |
|
|
342
372
|
`model_prices_and_context_window.json`, cached for 24 hours in `~/.cache/big-spender/`. Each source lists the LiteLLM keys to try for a model. Claude
|
|
343
373
|
Code and Codex try the exact model, then the `anthropic/` or `openai/` prefix, then without a date
|
|
344
374
|
suffix. pi tries the LiteLLM prefixes of the providers pi supports too (`openrouter/`, `fireworks_ai/`,
|
|
@@ -352,7 +382,7 @@ Gemini CLI tries `gemini/`, `vertex_ai/` and `openrouter/google/`, then the bare
|
|
|
352
382
|
Gemini from models.dev's `google/` entries first, and for `gemini-2.5-flash` that entry is $0.15
|
|
353
383
|
input and $1.25 output per million tokens, half of LiteLLM's (and models.dev's own `gemini/` entry)
|
|
354
384
|
$0.30 and $2.50. So ccusage shows about half the collector's cost for that model.
|
|
355
|
-
Unknown models count with cost 0 and log a warning.
|
|
385
|
+
OpenCode tries the model, then under the upstream provider it ran on. Unknown models count with cost 0 and log a warning.
|
|
356
386
|
Long-context tiers
|
|
357
387
|
(`*_above_<N>k_tokens`) are applied per request; a missing cache price is derived from the base
|
|
358
388
|
input price, also above a tier, as ccusage does. 1-hour cache writes use
|
package/dist/collector.mjs
CHANGED
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
// node collector.mjs --reset # forget local state and rescan everything
|
|
19
19
|
//
|
|
20
20
|
// Env: BIG_SPENDER_DEVICE_ID, BIG_SPENDER_INGEST_URL, BIG_SPENDER_INGEST_TOKEN and optionally
|
|
21
|
-
// BIG_SPENDER_CURSOR_API_KEY and
|
|
21
|
+
// BIG_SPENDER_CURSOR_API_KEY, BIG_SPENDER_EXPERIMENTAL and BIG_SPENDER_POLL_LIMITS=off (see
|
|
22
|
+
// templates/env.example).
|
|
22
23
|
// The older USAGE_* names are still read when the new one is unset.
|
|
23
24
|
|
|
24
25
|
import { createHash } from 'node:crypto';
|
|
@@ -35,7 +36,7 @@ import {
|
|
|
35
36
|
writeFile
|
|
36
37
|
} from 'node:fs/promises';
|
|
37
38
|
import { homedir } from 'node:os';
|
|
38
|
-
import { basename, dirname, extname, join, resolve, sep } from 'node:path';
|
|
39
|
+
import { basename, dirname, extname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
39
40
|
import { gzipSync } from 'node:zlib';
|
|
40
41
|
|
|
41
42
|
const SCHEMA_VERSION = 1;
|
|
@@ -72,13 +73,14 @@ const ENV_FILE =
|
|
|
72
73
|
|
|
73
74
|
const log = (...m) => console.error('[big-spender]', ...m);
|
|
74
75
|
|
|
75
|
-
// The
|
|
76
|
-
//
|
|
77
|
-
function
|
|
78
|
-
|
|
76
|
+
// The overrides exist for tests. They only point at this machine, so keys and tokens can't be
|
|
77
|
+
// sent anywhere but the service they belong to.
|
|
78
|
+
function localOverride(name, defaultUrl) {
|
|
79
|
+
const override = process.env[name];
|
|
80
|
+
if (!override) return defaultUrl;
|
|
79
81
|
const { hostname } = new URL(override);
|
|
80
82
|
if (!['127.0.0.1', 'localhost', '[::1]'].includes(hostname)) {
|
|
81
|
-
throw new Error(
|
|
83
|
+
throw new Error(`${name} may only point at this machine`);
|
|
82
84
|
}
|
|
83
85
|
return override.replace(/\/$/, '');
|
|
84
86
|
}
|
|
@@ -136,7 +138,9 @@ async function acquireLock() {
|
|
|
136
138
|
* A bare number on a Claude key means the counted output is unknown (state from an older version).
|
|
137
139
|
* Antigravity keeps a merged response under each of its ids: see agStoreGroup.
|
|
138
140
|
* Gemini keeps a file's counts under `gm:` and its path: [latest hour, counts]; see readGemini.
|
|
139
|
-
*
|
|
141
|
+
* For OpenCode it is [timestamp, tier, input, output, cache read, cache write, model, upstream,
|
|
142
|
+
* session].
|
|
143
|
+
* @typedef {number | [number, number] | [number, string] | [number, number, string, ...(number | string)[]] | [number, Record<string, any>] | (number | string)[]} Seen
|
|
140
144
|
* One subscription usage window instance; see limitWindowSchema in src/schema.ts.
|
|
141
145
|
* @typedef {{ provider: string, window: string, resetsAt: string, peakPercent: number, hitAt?: string }} Limit
|
|
142
146
|
* @typedef {{ version: number, files: Record<string, FileState>, seen: Record<string, Seen>, buckets: Record<string, Bucket>, limits?: Record<string, Limit>, fixes?: string[], rescan?: string[], cursorBackfills?: string[] }} State
|
|
@@ -149,6 +153,8 @@ async function acquireLock() {
|
|
|
149
153
|
const FIX_CLAUDE_OUTPUT = 'claude-final-output';
|
|
150
154
|
// Limit windows are read from log lines older versions skipped, so those logs are re-read once.
|
|
151
155
|
const FIX_LIMITS = 'usage-limits';
|
|
156
|
+
// Codex refusals are read from the logs too, so those logs are re-read once.
|
|
157
|
+
const FIX_CODEX_REFUSALS = 'codex-refusals';
|
|
152
158
|
|
|
153
159
|
/** @returns {Promise<State>} */
|
|
154
160
|
async function loadState() {
|
|
@@ -158,7 +164,7 @@ async function loadState() {
|
|
|
158
164
|
seen: {},
|
|
159
165
|
buckets: {},
|
|
160
166
|
limits: {},
|
|
161
|
-
fixes: [FIX_CLAUDE_OUTPUT, FIX_LIMITS]
|
|
167
|
+
fixes: [FIX_CLAUDE_OUTPUT, FIX_LIMITS, FIX_CODEX_REFUSALS]
|
|
162
168
|
};
|
|
163
169
|
if (RESET) return empty;
|
|
164
170
|
try {
|
|
@@ -176,6 +182,10 @@ async function loadState() {
|
|
|
176
182
|
s.fixes.push(FIX_LIMITS);
|
|
177
183
|
s.rescan = [...new Set([...(s.rescan ?? []), 'claude', 'codex'])];
|
|
178
184
|
}
|
|
185
|
+
if (!s.fixes.includes(FIX_CODEX_REFUSALS)) {
|
|
186
|
+
s.fixes.push(FIX_CODEX_REFUSALS);
|
|
187
|
+
s.rescan = [...new Set([...(s.rescan ?? []), 'codex'])];
|
|
188
|
+
}
|
|
179
189
|
return s;
|
|
180
190
|
} catch {
|
|
181
191
|
return empty;
|
|
@@ -251,23 +261,28 @@ const MINUTE_MS = 60_000;
|
|
|
251
261
|
const RESET_SLACK_MS = 2 * MINUTE_MS;
|
|
252
262
|
// Times outside this range are malformed (milliseconds read as seconds, say) and are skipped,
|
|
253
263
|
// never thrown, so a bad limit line cannot stop the usage on the lines after it.
|
|
264
|
+
// The server rejects a push with more limit records than this (MAX_LIMIT_WINDOWS in src/schema.ts),
|
|
265
|
+
// and it keeps the newest, so a push sends the newest.
|
|
266
|
+
const MAX_LIMIT_WINDOWS = 5_000;
|
|
254
267
|
const LIMIT_TIMES_FROM = Date.parse('2020-01-01T00:00:00Z');
|
|
255
268
|
const LIMIT_TIMES_TO = Date.parse('2100-01-01T00:00:00Z');
|
|
256
269
|
const plausibleTime = (ms) => ms >= LIMIT_TIMES_FROM && ms < LIMIT_TIMES_TO;
|
|
257
270
|
|
|
258
271
|
/**
|
|
272
|
+
* Returns the window name and reset time the record ended up with, or nothing when it was rejected.
|
|
259
273
|
* @param {State} state
|
|
260
274
|
* @param {{ provider: string, window: string, resetsAtMs: number, percent: number, hitMs?: number }} w
|
|
261
275
|
*/
|
|
262
276
|
function addLimit(state, w) {
|
|
277
|
+
const { window } = w;
|
|
263
278
|
let resetsAtMs = Math.floor(w.resetsAtMs / MINUTE_MS) * MINUTE_MS;
|
|
264
|
-
if (!plausibleTime(resetsAtMs) || !/^[a-z0-9_]{1,40}$/.test(
|
|
279
|
+
if (!plausibleTime(resetsAtMs) || !/^[a-z0-9_]{1,40}$/.test(window)) return;
|
|
265
280
|
if (w.hitMs !== undefined && !plausibleTime(w.hitMs)) return;
|
|
266
281
|
state.limits ??= {};
|
|
267
282
|
let prev;
|
|
268
283
|
for (const [key, l] of Object.entries(state.limits)) {
|
|
269
284
|
const gap = Math.abs(Date.parse(l.resetsAt) - resetsAtMs);
|
|
270
|
-
if (l.provider !== w.provider || l.window !==
|
|
285
|
+
if (l.provider !== w.provider || l.window !== window || gap > RESET_SLACK_MS) continue;
|
|
271
286
|
if (prev && gap >= Math.abs(Date.parse(prev[1].resetsAt) - resetsAtMs)) continue;
|
|
272
287
|
prev = [key, l];
|
|
273
288
|
}
|
|
@@ -277,15 +292,21 @@ function addLimit(state, w) {
|
|
|
277
292
|
}
|
|
278
293
|
const hits = [prev?.[1].hitAt && Date.parse(prev[1].hitAt), w.hitMs].filter(Number.isFinite);
|
|
279
294
|
const percent = Math.min(100, Math.max(0, w.percent));
|
|
280
|
-
state.limits[`${w.provider}|${
|
|
295
|
+
state.limits[`${w.provider}|${window}|${resetsAtMs}`] = {
|
|
281
296
|
provider: w.provider,
|
|
282
|
-
window
|
|
297
|
+
window,
|
|
283
298
|
resetsAt: new Date(resetsAtMs).toISOString(),
|
|
284
299
|
peakPercent: Math.max(prev?.[1].peakPercent ?? 0, percent),
|
|
285
300
|
...(hits.length ? { hitAt: new Date(Math.min(...hits)).toISOString() } : {})
|
|
286
301
|
};
|
|
302
|
+
return { window, resetsAtMs };
|
|
287
303
|
}
|
|
288
304
|
|
|
305
|
+
// Claude Code logs Fable's weekly as seven_day_overage_included and labels it "Fable limit". The
|
|
306
|
+
// usage endpoint calls the same limit seven_day_fable, and the server merges pushes by name, so the
|
|
307
|
+
// name has to be right when the record is created or the limit would show as two rows.
|
|
308
|
+
const CLAUDE_LOG_WINDOWS = { seven_day_overage_included: 'seven_day_fable' };
|
|
309
|
+
|
|
289
310
|
// Claude Code logs a refused request as a synthetic assistant line carrying quotaLimits.
|
|
290
311
|
// One blocked window repeats on every retry; the key makes the repeats one record.
|
|
291
312
|
function claudeLimit(state, o) {
|
|
@@ -293,12 +314,13 @@ function claudeLimit(state, o) {
|
|
|
293
314
|
if (q?.status !== 'rejected' || typeof q.rateLimitType !== 'string') return;
|
|
294
315
|
const ts = Date.parse(o.timestamp);
|
|
295
316
|
if (!Number.isFinite(ts) || !(q.resetsAt > 0)) return;
|
|
317
|
+
const raw = q.rateLimitType
|
|
318
|
+
.toLowerCase()
|
|
319
|
+
.replace(/[^a-z0-9_]/g, '_')
|
|
320
|
+
.slice(0, 40);
|
|
296
321
|
addLimit(state, {
|
|
297
322
|
provider: 'claude',
|
|
298
|
-
window:
|
|
299
|
-
.toLowerCase()
|
|
300
|
-
.replace(/[^a-z0-9_]/g, '_')
|
|
301
|
-
.slice(0, 40),
|
|
323
|
+
window: CLAUDE_LOG_WINDOWS[raw] ?? raw,
|
|
302
324
|
resetsAtMs: q.resetsAt * 1000,
|
|
303
325
|
percent: 100,
|
|
304
326
|
hitMs: ts
|
|
@@ -333,6 +355,265 @@ function codexLimits(state, o, rateLimits) {
|
|
|
333
355
|
}
|
|
334
356
|
}
|
|
335
357
|
|
|
358
|
+
// A window's length in ms from its name: a CODEX_WINDOW_NAMES base or `<N>m`, then an optional
|
|
359
|
+
// `_<suffix>` for an additional limit.
|
|
360
|
+
function codexWindowMs(window) {
|
|
361
|
+
for (const [minutes, base] of Object.entries(CODEX_WINDOW_NAMES)) {
|
|
362
|
+
if (window === base || window.startsWith(`${base}_`)) return Number(minutes) * MINUTE_MS;
|
|
363
|
+
}
|
|
364
|
+
const m = /^(\d+)m(_|$)/.exec(window);
|
|
365
|
+
return m ? Number(m[1]) * MINUTE_MS : NaN;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// A refused Codex turn names no window and no reset, so it starts the lockout of every window
|
|
369
|
+
// already seen full that was open at the time. With none seen full, it falls to elimination.
|
|
370
|
+
// Usage within an instance only rises until its reset, so this run's poll reading below 100%
|
|
371
|
+
// (taken after the refusal) proves the instance was not full at ts. That only settles it when
|
|
372
|
+
// the poll read both Codex windows, every limit it reports had an instance on file at ts, and
|
|
373
|
+
// exactly one is not ruled out. polled holds this run's Codex poll readings; it is empty when
|
|
374
|
+
// the poll was off or failed. Runs after the whole scan, once every log reading is on file.
|
|
375
|
+
function codexRefusal(state, ts, polled) {
|
|
376
|
+
const open = Object.values(state.limits ?? {}).filter((l) => {
|
|
377
|
+
const resetsAtMs = Date.parse(l.resetsAt);
|
|
378
|
+
return l.provider === 'codex' && ts > resetsAtMs - codexWindowMs(l.window) && ts <= resetsAtMs;
|
|
379
|
+
});
|
|
380
|
+
const full = open.filter((l) => l.peakPercent >= 100);
|
|
381
|
+
const readBelowFull = (l) =>
|
|
382
|
+
polled.some(
|
|
383
|
+
(r) =>
|
|
384
|
+
r.percent < 100 &&
|
|
385
|
+
r.window === l.window &&
|
|
386
|
+
Math.abs(r.resetsAtMs - Date.parse(l.resetsAt)) <= RESET_SLACK_MS
|
|
387
|
+
);
|
|
388
|
+
// A window the poll reports as null (not in use now) may have blocked and reset since, so
|
|
389
|
+
// elimination needs a reading of both Codex windows.
|
|
390
|
+
const polledNames = new Set(polled.map((r) => r.window));
|
|
391
|
+
const accountedFor =
|
|
392
|
+
Object.values(CODEX_WINDOW_NAMES).every((n) => polledNames.has(n)) &&
|
|
393
|
+
[...polledNames].every((n) => open.some((l) => l.window === n));
|
|
394
|
+
const left = accountedFor ? open.filter((l) => !readBelowFull(l)) : [];
|
|
395
|
+
const blockers = full.length ? full : left.length === 1 ? left : [];
|
|
396
|
+
for (const l of blockers) {
|
|
397
|
+
addLimit(state, {
|
|
398
|
+
provider: 'codex',
|
|
399
|
+
window: l.window,
|
|
400
|
+
resetsAtMs: Date.parse(l.resetsAt),
|
|
401
|
+
percent: 100,
|
|
402
|
+
hitMs: ts
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const isCodexRefusal = (p) => {
|
|
408
|
+
const err = p.type === 'task_complete' ? p.error : p.type === 'error' ? p : null;
|
|
409
|
+
if (!err || typeof err !== 'object') return false;
|
|
410
|
+
return (
|
|
411
|
+
err.codex_error_info === 'usage_limit_exceeded' ||
|
|
412
|
+
(typeof err.message === 'string' && /usage limit/i.test(err.message))
|
|
413
|
+
);
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
// ---------------------------------------------------------------------------
|
|
417
|
+
// Limit polling
|
|
418
|
+
//
|
|
419
|
+
// Logs only show a limit when a request is refused. Each provider's own usage endpoint also
|
|
420
|
+
// reports how full every window is right now, so polling it sees the unused part too. The login
|
|
421
|
+
// files the agents keep are opened read-only and never refreshed; the token goes to the
|
|
422
|
+
// provider's own host and nowhere else.
|
|
423
|
+
|
|
424
|
+
const slug = (s) =>
|
|
425
|
+
s
|
|
426
|
+
.toLowerCase()
|
|
427
|
+
.replace(/[^a-z0-9]+/g, '_')
|
|
428
|
+
.replace(/^_+|_+$/g, '');
|
|
429
|
+
|
|
430
|
+
const claudeResetMs = (resetsAt) => (typeof resetsAt === 'string' ? Date.parse(resetsAt) : NaN);
|
|
431
|
+
|
|
432
|
+
function claudeWindows(body) {
|
|
433
|
+
const out = [];
|
|
434
|
+
const add = (window, percent, resetsAtMs) => {
|
|
435
|
+
if (Number.isFinite(percent) && Number.isFinite(resetsAtMs)) {
|
|
436
|
+
out.push({ window: window.slice(0, 40), percent, resetsAtMs });
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
for (const [key, w] of Object.entries(body)) {
|
|
440
|
+
if (/^(five_hour|seven_day)(_[a-z0-9_]+)?$/.test(key) && w && typeof w === 'object') {
|
|
441
|
+
add(key, w.utilization, claudeResetMs(w.resets_at));
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
for (const l of Array.isArray(body.limits) ? body.limits : []) {
|
|
445
|
+
const model = l?.scope?.model?.display_name;
|
|
446
|
+
if (l?.kind === 'weekly_scoped' && typeof model === 'string' && slug(model)) {
|
|
447
|
+
add(`seven_day_${slug(model)}`, l.percent, claudeResetMs(l.resets_at));
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const CODEX_SLOTS = ['primary_window', 'secondary_window'];
|
|
454
|
+
|
|
455
|
+
function codexWindows(body, nowMs) {
|
|
456
|
+
const out = [];
|
|
457
|
+
const add = (rateLimit, suffix) => {
|
|
458
|
+
for (const slot of CODEX_SLOTS) {
|
|
459
|
+
const w = rateLimit?.[slot];
|
|
460
|
+
if (!w || typeof w.used_percent !== 'number') continue;
|
|
461
|
+
const minutes = w.limit_window_seconds / 60;
|
|
462
|
+
const resetsAtMs =
|
|
463
|
+
w.reset_at > 0 ? w.reset_at * 1000 : nowMs + Number(w.reset_after_seconds) * 1000;
|
|
464
|
+
if (!Number.isFinite(minutes) || !Number.isFinite(resetsAtMs)) continue;
|
|
465
|
+
const base = CODEX_WINDOW_NAMES[minutes] ?? `${minutes}m`;
|
|
466
|
+
out.push({
|
|
467
|
+
window: (suffix ? `${base}_${suffix}` : base).slice(0, 40),
|
|
468
|
+
percent: w.used_percent,
|
|
469
|
+
resetsAtMs
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
add(body.rate_limit, '');
|
|
474
|
+
for (const extra of Array.isArray(body.additional_rate_limits)
|
|
475
|
+
? body.additional_rate_limits
|
|
476
|
+
: []) {
|
|
477
|
+
const name = typeof extra?.limit_name === 'string' ? slug(extra.limit_name) : '';
|
|
478
|
+
if (name) add(extra.rate_limit, name);
|
|
479
|
+
}
|
|
480
|
+
return out;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// The access token is a JWT; its payload says when it expires. One that can't be decoded is sent
|
|
484
|
+
// anyway and the endpoint decides.
|
|
485
|
+
function jwtExpiresMs(token) {
|
|
486
|
+
try {
|
|
487
|
+
const exp = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()).exp;
|
|
488
|
+
return typeof exp === 'number' ? exp * 1000 : NaN;
|
|
489
|
+
} catch {
|
|
490
|
+
return NaN;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// headers() returns the request headers, or a string saying why this provider is skipped.
|
|
495
|
+
const LIMIT_POLLERS = {
|
|
496
|
+
claude: {
|
|
497
|
+
credentialsPath: () =>
|
|
498
|
+
join(process.env.CLAUDE_CONFIG_DIR || join(HOME, '.claude'), '.credentials.json'),
|
|
499
|
+
url: 'https://api.anthropic.com/api/oauth/usage?skip_spend=1',
|
|
500
|
+
urlEnv: 'BIG_SPENDER_CLAUDE_USAGE_URL',
|
|
501
|
+
headers: (creds, nowMs) => {
|
|
502
|
+
const oauth = creds?.claudeAiOauth;
|
|
503
|
+
if (typeof oauth?.accessToken !== 'string' || !oauth.accessToken) {
|
|
504
|
+
return 'not signed in with a Claude subscription';
|
|
505
|
+
}
|
|
506
|
+
if (typeof oauth.expiresAt === 'number' && oauth.expiresAt <= nowMs) {
|
|
507
|
+
return 'the login token expired; run Claude Code once to refresh it';
|
|
508
|
+
}
|
|
509
|
+
return {
|
|
510
|
+
authorization: `Bearer ${oauth.accessToken}`,
|
|
511
|
+
'anthropic-beta': 'oauth-2025-04-20',
|
|
512
|
+
'user-agent': 'big-spender'
|
|
513
|
+
};
|
|
514
|
+
},
|
|
515
|
+
windows: claudeWindows
|
|
516
|
+
},
|
|
517
|
+
codex: {
|
|
518
|
+
credentialsPath: () => join(process.env.CODEX_HOME || join(HOME, '.codex'), 'auth.json'),
|
|
519
|
+
url: 'https://chatgpt.com/backend-api/wham/usage',
|
|
520
|
+
urlEnv: 'BIG_SPENDER_CODEX_USAGE_URL',
|
|
521
|
+
headers: (creds, nowMs) => {
|
|
522
|
+
const { access_token: token, account_id: accountId } = creds?.tokens ?? {};
|
|
523
|
+
if (typeof token !== 'string' || !token) return 'not signed in with ChatGPT';
|
|
524
|
+
if (typeof accountId !== 'string' || !accountId) return 'no ChatGPT account id in the login';
|
|
525
|
+
if (jwtExpiresMs(token) <= nowMs) {
|
|
526
|
+
return 'the login token expired; run Codex once to refresh it';
|
|
527
|
+
}
|
|
528
|
+
return {
|
|
529
|
+
authorization: `Bearer ${token}`,
|
|
530
|
+
'chatgpt-account-id': accountId,
|
|
531
|
+
'user-agent': 'big-spender'
|
|
532
|
+
};
|
|
533
|
+
},
|
|
534
|
+
windows: codexWindows
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
async function pollLimit(state, provider, poller, nowMs, polled) {
|
|
539
|
+
const path = poller.credentialsPath();
|
|
540
|
+
if (!existsSync(path)) return;
|
|
541
|
+
let creds;
|
|
542
|
+
try {
|
|
543
|
+
creds = JSON.parse(readFileSync(path, 'utf8'));
|
|
544
|
+
} catch {
|
|
545
|
+
// JSON.parse quotes part of the text in its error, which here would be a token.
|
|
546
|
+
throw new Error('could not read the login file');
|
|
547
|
+
}
|
|
548
|
+
const headers = poller.headers(creds, nowMs);
|
|
549
|
+
if (typeof headers === 'string') throw new Error(headers);
|
|
550
|
+
for (const value of Object.values(headers))
|
|
551
|
+
assertHeaderSafe(value.replace(/^Bearer /, ''), `the ${provider} login token`);
|
|
552
|
+
|
|
553
|
+
let res;
|
|
554
|
+
try {
|
|
555
|
+
res = await fetch(localOverride(poller.urlEnv, poller.url), {
|
|
556
|
+
headers,
|
|
557
|
+
redirect: 'error',
|
|
558
|
+
signal: AbortSignal.timeout(10_000)
|
|
559
|
+
});
|
|
560
|
+
} catch (err) {
|
|
561
|
+
throw new Error(`request failed (${err?.name ?? 'error'})`);
|
|
562
|
+
}
|
|
563
|
+
if (!res.ok) {
|
|
564
|
+
const hint =
|
|
565
|
+
res.status === 401 || res.status === 403
|
|
566
|
+
? '; the login token was refused, run the agent once to refresh it'
|
|
567
|
+
: '';
|
|
568
|
+
throw new Error(`HTTP ${res.status}${hint}`);
|
|
569
|
+
}
|
|
570
|
+
let body;
|
|
571
|
+
try {
|
|
572
|
+
body = await res.json();
|
|
573
|
+
} catch {
|
|
574
|
+
body = null;
|
|
575
|
+
}
|
|
576
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
577
|
+
throw new Error('the answer was not a JSON object');
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const seen = [];
|
|
581
|
+
for (const w of poller.windows(body, nowMs)) {
|
|
582
|
+
const stored = addLimit(state, {
|
|
583
|
+
provider,
|
|
584
|
+
window: w.window,
|
|
585
|
+
// The Claude endpoint's reset time jitters by a fraction of a second (14:59:59.7 for a
|
|
586
|
+
// 15:00 reset), and addLimit floors and keeps the earliest, so round to the real minute.
|
|
587
|
+
resetsAtMs: Math.round(w.resetsAtMs / MINUTE_MS) * MINUTE_MS,
|
|
588
|
+
percent: w.percent,
|
|
589
|
+
...(w.percent >= 100 ? { hitMs: nowMs } : {})
|
|
590
|
+
});
|
|
591
|
+
if (stored) polled.push({ ...stored, percent: w.percent });
|
|
592
|
+
seen.push(`${w.window} ${Math.round(w.percent)}%`);
|
|
593
|
+
}
|
|
594
|
+
log(`polled ${provider} usage: ${seen.join(', ') || 'no windows in use'}`);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* A failed poll only costs a warning: it never fails the run or the push. Returns this run's
|
|
599
|
+
* Codex readings.
|
|
600
|
+
*/
|
|
601
|
+
async function pollLimits(state, nowMs) {
|
|
602
|
+
/** @type {{ window: string, resetsAtMs: number, percent: number }[]} */
|
|
603
|
+
const polled = [];
|
|
604
|
+
if (['off', '0', 'false', 'no'].includes(setting('POLL_LIMITS').toLowerCase())) return polled;
|
|
605
|
+
for (const [provider, poller] of Object.entries(LIMIT_POLLERS)) {
|
|
606
|
+
const readings = [];
|
|
607
|
+
try {
|
|
608
|
+
await pollLimit(state, provider, poller, nowMs, readings);
|
|
609
|
+
if (provider === 'codex') polled.push(...readings);
|
|
610
|
+
} catch (err) {
|
|
611
|
+
log(`warning: ${provider} usage not polled: ${err?.message ?? 'failed'}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return polled;
|
|
615
|
+
}
|
|
616
|
+
|
|
336
617
|
// ---------------------------------------------------------------------------
|
|
337
618
|
// Pricing
|
|
338
619
|
|
|
@@ -559,7 +840,7 @@ function claudeLineHandler(state, resolvePrice, cutoffMs) {
|
|
|
559
840
|
|
|
560
841
|
// Codex: token_count events carry per-request usage in info.last_token_usage.
|
|
561
842
|
// input_tokens includes cached_input_tokens. output_tokens includes reasoning.
|
|
562
|
-
function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSession) {
|
|
843
|
+
function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSession, refusals) {
|
|
563
844
|
return (line) => {
|
|
564
845
|
const o = parseJson(line);
|
|
565
846
|
if (!o) return;
|
|
@@ -572,6 +853,11 @@ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSess
|
|
|
572
853
|
fileState.model = p.model;
|
|
573
854
|
return;
|
|
574
855
|
}
|
|
856
|
+
if (o.type === 'event_msg' && p && isCodexRefusal(p)) {
|
|
857
|
+
const ts = Date.parse(o.timestamp);
|
|
858
|
+
if (Number.isFinite(ts)) refusals.push(ts);
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
575
861
|
if (o.type !== 'event_msg' || p?.type !== 'token_count') return;
|
|
576
862
|
codexLimits(state, o, p.rate_limits);
|
|
577
863
|
if (!p.info) return;
|
|
@@ -1898,8 +2184,251 @@ function antigravityPriceKeys(model) {
|
|
|
1898
2184
|
return [...names].flatMap((name) => prefixes.map((prefix) => prefix + name));
|
|
1899
2185
|
}
|
|
1900
2186
|
|
|
2187
|
+
// OpenCode keeps one record per assistant message and rewrites it while the message runs: in
|
|
2188
|
+
// SQLite (`message` in 1.x; `session_message` from 2.0, which copies the 1.x rows under the same
|
|
2189
|
+
// ids) and, before SQLite, in `storage/message/<session>/<message>.json`. A message id counts
|
|
2190
|
+
// from the first store that has it, 1.x rows first, so every `session_message` row left was
|
|
2191
|
+
// written by 2.x.
|
|
2192
|
+
|
|
2193
|
+
/**
|
|
2194
|
+
* @typedef {{ id: string, session: string, ts: number, model: string, upstream: string, tokens: any, separateReasoning: boolean }} OpenCodeMessage
|
|
2195
|
+
*/
|
|
2196
|
+
|
|
2197
|
+
/** @type {Map<string, string>} */
|
|
2198
|
+
const opencodeUpstreams = new Map();
|
|
2199
|
+
|
|
2200
|
+
const OPENCODE_ALIASES = new Map([
|
|
2201
|
+
['gemini-3-pro-high', 'gemini-3-pro-preview'],
|
|
2202
|
+
['k2p6', 'kimi-k2.6']
|
|
2203
|
+
]);
|
|
2204
|
+
const CLAUDE_DOTTED = /^(claude-(?:haiku|opus|sonnet)-)(\d+)\.(\d)/;
|
|
2205
|
+
|
|
2206
|
+
function opencodePriceKeys(model) {
|
|
2207
|
+
const resolved = OPENCODE_ALIASES.get(model) ?? model;
|
|
2208
|
+
// LiteLLM spells claude-opus-4.5 and claude-opus-45 as claude-opus-4-5.
|
|
2209
|
+
const normalized = CLAUDE_DOTTED.test(resolved)
|
|
2210
|
+
? resolved.replace(CLAUDE_DOTTED, '$1$2-$3')
|
|
2211
|
+
: resolved.replace(/^(claude-(?:haiku|opus|sonnet)-\d)(\d)/, '$1-$2');
|
|
2212
|
+
const bases = [...new Set([resolved, normalized])];
|
|
2213
|
+
const upstream = opencodeUpstreams.get(model);
|
|
2214
|
+
// The upstream as ccusage spells it (zai_coding_plan), then its first word (zai).
|
|
2215
|
+
const prefixes = upstream
|
|
2216
|
+
? [...new Set([upstream.replaceAll('-', '_'), upstream.split('-')[0]])]
|
|
2217
|
+
: [];
|
|
2218
|
+
return [...bases, ...prefixes.flatMap((p) => bases.map((b) => `${p}/${b}`))];
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
/**
|
|
2222
|
+
* Cache reads and writes are outside `input`. OpenCode 1.x counts reasoning inside `output` and
|
|
2223
|
+
* records `total`. 2.x stores the visible output only (`output` minus reasoning) and no `total`,
|
|
2224
|
+
* so its reasoning is added back.
|
|
2225
|
+
*/
|
|
2226
|
+
function opencodeTokens(t, separateReasoning) {
|
|
2227
|
+
const input = num(t?.input);
|
|
2228
|
+
const cacheRead = num(t?.cache?.read);
|
|
2229
|
+
const cacheWrite = num(t?.cache?.write);
|
|
2230
|
+
let output = num(t?.output);
|
|
2231
|
+
const total = num(t?.total);
|
|
2232
|
+
if (total) output = Math.max(output, total - input - cacheRead - cacheWrite);
|
|
2233
|
+
else if (separateReasoning) output += num(t?.reasoning);
|
|
2234
|
+
return { input, output, cacheRead, cacheWrite };
|
|
2235
|
+
}
|
|
2236
|
+
|
|
2237
|
+
async function opencodeDbPath(dir) {
|
|
2238
|
+
if (existsSync(join(dir, 'opencode.db'))) return join(dir, 'opencode.db');
|
|
2239
|
+
const names = await readdir(dir).catch(() => []);
|
|
2240
|
+
const channel = names.filter((n) => /^opencode-[A-Za-z0-9_-]+\.db$/.test(n)).sort()[0];
|
|
2241
|
+
return channel ? join(dir, channel) : null;
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
function readOpenCodeDb(db, sinceMs, out) {
|
|
2245
|
+
const columns = (table) =>
|
|
2246
|
+
new Set(
|
|
2247
|
+
db
|
|
2248
|
+
.prepare('SELECT name FROM pragma_table_info(?)')
|
|
2249
|
+
.all(table)
|
|
2250
|
+
.map((r) => r.name)
|
|
2251
|
+
);
|
|
2252
|
+
const add = (r, separateReasoning) => {
|
|
2253
|
+
if (out.has(r.id)) return;
|
|
2254
|
+
out.set(r.id, { ...r, tokens: parseJson(r.tokens ?? 'null'), separateReasoning });
|
|
2255
|
+
};
|
|
2256
|
+
const v1 = columns('message');
|
|
2257
|
+
if (v1.has('data')) {
|
|
2258
|
+
const since = v1.has('time_created') ? 'time_created >= ? AND' : '';
|
|
2259
|
+
const rows = db
|
|
2260
|
+
.prepare(
|
|
2261
|
+
`SELECT id, session_id AS session, json_extract(data, '$.time.created') AS ts,
|
|
2262
|
+
json_extract(data, '$.modelID') AS model, json_extract(data, '$.providerID') AS upstream,
|
|
2263
|
+
json_extract(data, '$.tokens') AS tokens
|
|
2264
|
+
FROM message WHERE ${since} json_valid(data)`
|
|
2265
|
+
)
|
|
2266
|
+
.all(...(since ? [sinceMs] : []));
|
|
2267
|
+
for (const r of rows) add(r, false);
|
|
2268
|
+
}
|
|
2269
|
+
const v2 = columns('session_message');
|
|
2270
|
+
if (!v2.has('data') || !v2.has('type')) return;
|
|
2271
|
+
const sessions = columns('session_v2');
|
|
2272
|
+
// A 2.x fork starts with copies of its parent's rows, made when the fork is, that keep the
|
|
2273
|
+
// parent rows' time_created. OpenCode's own usage stats skip them the same way, and this needs
|
|
2274
|
+
// no parent row, so it holds after the parent is deleted.
|
|
2275
|
+
const forks =
|
|
2276
|
+
v2.has('time_created') && sessions.has('fork_session_id') && sessions.has('time_created');
|
|
2277
|
+
const since = v2.has('time_created') ? 'm.time_created >= ? AND' : '';
|
|
2278
|
+
const rows = db
|
|
2279
|
+
.prepare(
|
|
2280
|
+
`SELECT m.id, m.session_id AS session,
|
|
2281
|
+
coalesce(json_extract(m.data, '$.time.created'), ${v2.has('time_created') ? 'm.time_created' : 'NULL'}) AS ts,
|
|
2282
|
+
coalesce(json_extract(m.data, '$.model.id'), json_extract(m.data, '$.model.modelID'),
|
|
2283
|
+
json_extract(m.data, '$.modelID')) AS model,
|
|
2284
|
+
coalesce(json_extract(m.data, '$.model.providerID'), json_extract(m.data, '$.providerID')) AS upstream,
|
|
2285
|
+
json_extract(m.data, '$.tokens') AS tokens
|
|
2286
|
+
FROM session_message m
|
|
2287
|
+
${forks ? 'LEFT JOIN session_v2 s ON s.id = m.session_id' : ''}
|
|
2288
|
+
WHERE ${since} json_valid(m.data) AND (m.type = 'assistant'
|
|
2289
|
+
OR (m.type = 'compaction' AND json_extract(m.data, '$.status') = 'completed'))
|
|
2290
|
+
${forks ? 'AND (s.fork_session_id IS NULL OR m.time_created >= s.time_created)' : ''}`
|
|
2291
|
+
)
|
|
2292
|
+
.all(...(since ? [sinceMs] : []));
|
|
2293
|
+
for (const r of rows) add(r, true);
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
async function readOpenCodeFiles(dir, sinceMs, out) {
|
|
2297
|
+
for await (const path of walk(join(dir, 'storage', 'message'), (name) =>
|
|
2298
|
+
name.endsWith('.json')
|
|
2299
|
+
)) {
|
|
2300
|
+
if (out.has(basename(path, '.json'))) continue;
|
|
2301
|
+
const st = await stat(path).catch(() => null);
|
|
2302
|
+
if (!st || st.mtimeMs < sinceMs) continue;
|
|
2303
|
+
const o = parseJson(await readFile(path, 'utf8').catch(() => ''));
|
|
2304
|
+
const id = typeof o?.id === 'string' ? o.id : basename(path, '.json');
|
|
2305
|
+
if (!o || out.has(id)) continue;
|
|
2306
|
+
out.set(id, {
|
|
2307
|
+
id,
|
|
2308
|
+
session: o.sessionID,
|
|
2309
|
+
ts: o.time?.created,
|
|
2310
|
+
model: o.modelID,
|
|
2311
|
+
upstream: o.providerID,
|
|
2312
|
+
tokens: o.tokens,
|
|
2313
|
+
separateReasoning: false
|
|
2314
|
+
});
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
const MODEL_FILE = /\.(?:gguf|ggml|bin|safetensors|onnx|pt|pth|ckpt|llamafile)$/i;
|
|
2319
|
+
|
|
2320
|
+
/**
|
|
2321
|
+
* A local model can be named by its path or a URL, which can carry a login, a query or a folder
|
|
2322
|
+
* name. Only a file name leaves the machine; an address without one becomes `local`.
|
|
2323
|
+
*/
|
|
2324
|
+
function opencodeModelName(id) {
|
|
2325
|
+
const scheme = /^[A-Za-z][A-Za-z0-9+.-]*:/.exec(id)?.[0] ?? '';
|
|
2326
|
+
const rest = id.slice(scheme.length);
|
|
2327
|
+
// `scheme:/...`, `//host/...`, or anything with a query, fragment or login after a scheme.
|
|
2328
|
+
const address = /^[/\\]{2}/.test(rest) || (scheme !== '' && /^[/\\]|[?#@]/.test(rest));
|
|
2329
|
+
const path = address || /^[/~.\\]|\\/.test(rest) || (rest.includes('/') && MODEL_FILE.test(rest));
|
|
2330
|
+
const clean = (name) => name.replace(/[^A-Za-z0-9._:/@-]/g, '-').slice(0, 100);
|
|
2331
|
+
if (!path) return clean(id.replace(/[?#].*$/s, ''));
|
|
2332
|
+
const local = address ? rest.replace(/[?#].*$/s, '').replace(/^[/\\]{2}[^/\\]*/, '') : rest;
|
|
2333
|
+
const name = local
|
|
2334
|
+
.split(/[/\\]/)
|
|
2335
|
+
.pop()
|
|
2336
|
+
.replace(/[?#].*$/s, '');
|
|
2337
|
+
return clean(!name || name.includes('@') ? 'local' : name);
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
function countOpenCode(ctx, provider, m) {
|
|
2341
|
+
if (typeof m.model !== 'string' || !m.model || typeof m.upstream !== 'string') return;
|
|
2342
|
+
// Claude Code writes its own transcript of these turns, and the claude source reads it.
|
|
2343
|
+
if (m.upstream === 'claude-agent') return;
|
|
2344
|
+
const ts = Number(m.ts);
|
|
2345
|
+
if (!Number.isFinite(ts) || ts < ctx.cutoffMs) return;
|
|
2346
|
+
|
|
2347
|
+
const model = opencodeModelName(m.model);
|
|
2348
|
+
if (!opencodeUpstreams.has(model)) opencodeUpstreams.set(model, m.upstream);
|
|
2349
|
+
const t = opencodeTokens(m.tokens, m.separateReasoning);
|
|
2350
|
+
const session = shortHash(`opencode:${m.session ?? 'unknown'}`);
|
|
2351
|
+
const counted =
|
|
2352
|
+
t.input || t.output || t.cacheRead || t.cacheWrite
|
|
2353
|
+
? [
|
|
2354
|
+
ts,
|
|
2355
|
+
tierFor(ctx.resolvePrice(provider, model), t.input + t.cacheRead + t.cacheWrite),
|
|
2356
|
+
t.input,
|
|
2357
|
+
t.output,
|
|
2358
|
+
t.cacheRead,
|
|
2359
|
+
t.cacheWrite,
|
|
2360
|
+
model,
|
|
2361
|
+
m.upstream,
|
|
2362
|
+
session
|
|
2363
|
+
]
|
|
2364
|
+
: null;
|
|
2365
|
+
const key = `o:${shortHash(m.id)}`;
|
|
2366
|
+
const prev = Array.isArray(ctx.state.seen[key]) ? ctx.state.seen[key] : null;
|
|
2367
|
+
if (!prev ? !counted : counted?.every((v, i) => v === prev[i])) return;
|
|
2368
|
+
|
|
2369
|
+
const add = ([at, tier, input, output, cacheRead, cacheWrite, modelAt = model], sign) => {
|
|
2370
|
+
addRecord(ctx.state, {
|
|
2371
|
+
ts: at,
|
|
2372
|
+
provider,
|
|
2373
|
+
model: modelAt,
|
|
2374
|
+
tier,
|
|
2375
|
+
session,
|
|
2376
|
+
input: sign * input,
|
|
2377
|
+
cacheRead: sign * cacheRead,
|
|
2378
|
+
cacheWrite5m: sign * cacheWrite,
|
|
2379
|
+
cacheWrite1h: 0,
|
|
2380
|
+
output: sign * output
|
|
2381
|
+
});
|
|
2382
|
+
};
|
|
2383
|
+
if (prev) add(prev, -1);
|
|
2384
|
+
if (counted) {
|
|
2385
|
+
add(counted, 1);
|
|
2386
|
+
ctx.state.seen[key] = counted;
|
|
2387
|
+
} else delete ctx.state.seen[key];
|
|
2388
|
+
// The session leaves the bucket the message left, unless another of its messages is there.
|
|
2389
|
+
const bucketOf = (c) => bucketKey(Math.floor(c[0] / HOUR_MS) * HOUR_MS, provider, c[6], c[1]);
|
|
2390
|
+
const left = prev && bucketOf(prev);
|
|
2391
|
+
if (left && (!counted || bucketOf(counted) !== left) && ctx.state.buckets[left]) {
|
|
2392
|
+
const stays = Object.entries(ctx.state.seen).some(
|
|
2393
|
+
([k, v]) => k.startsWith('o:') && Array.isArray(v) && v[8] === session && bucketOf(v) === left
|
|
2394
|
+
);
|
|
2395
|
+
if (!stays) {
|
|
2396
|
+
const b = ctx.state.buckets[left];
|
|
2397
|
+
b.sessions = b.sessions.filter((s) => s !== session);
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
async function readOpenCode(paths, ctx, provider) {
|
|
2403
|
+
// Usage kept from messages no longer on disk still needs its upstream to be priced.
|
|
2404
|
+
for (const [key, v] of Object.entries(ctx.state.seen)) {
|
|
2405
|
+
if (key.startsWith('o:') && Array.isArray(v) && !opencodeUpstreams.has(v[6])) {
|
|
2406
|
+
if (typeof v[7] === 'string') opencodeUpstreams.set(v[6], v[7]);
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
if (!paths.length) return;
|
|
2410
|
+
/** @type {Map<string, OpenCodeMessage>} */
|
|
2411
|
+
const messages = new Map();
|
|
2412
|
+
for (const dir of new Set(paths.map((p) => resolve(p)))) {
|
|
2413
|
+
const file = await opencodeDbPath(dir);
|
|
2414
|
+
if (file) {
|
|
2415
|
+
let db;
|
|
2416
|
+
try {
|
|
2417
|
+
db = await openSqlite(file);
|
|
2418
|
+
if (db) readOpenCodeDb(db, ctx.cutoffMs, messages);
|
|
2419
|
+
} catch (err) {
|
|
2420
|
+
log(`skipping unreadable OpenCode database: ${err.message}`);
|
|
2421
|
+
} finally {
|
|
2422
|
+
db?.close();
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
await readOpenCodeFiles(dir, ctx.cutoffMs, messages);
|
|
2426
|
+
}
|
|
2427
|
+
for (const m of messages.values()) countOpenCode(ctx, provider, m);
|
|
2428
|
+
}
|
|
2429
|
+
|
|
1901
2430
|
/**
|
|
1902
|
-
* @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
|
|
2431
|
+
* @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, codexRefusals: number[], seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
|
|
1903
2432
|
* @typedef {{
|
|
1904
2433
|
* paths: string[],
|
|
1905
2434
|
* envPaths: () => string[],
|
|
@@ -1942,7 +2471,8 @@ const SOURCES = {
|
|
|
1942
2471
|
file,
|
|
1943
2472
|
ctx.resolvePrice,
|
|
1944
2473
|
ctx.cutoffMs,
|
|
1945
|
-
path.match(/([0-9a-f-]{36})\.jsonl$/)?.[1] ?? path
|
|
2474
|
+
path.match(/([0-9a-f-]{36})\.jsonl$/)?.[1] ?? path,
|
|
2475
|
+
ctx.codexRefusals
|
|
1946
2476
|
)
|
|
1947
2477
|
),
|
|
1948
2478
|
priceKeys: litellmKeys('openai')
|
|
@@ -2018,6 +2548,19 @@ const SOURCES = {
|
|
|
2018
2548
|
...['gemini', 'vertex_ai', 'openrouter/google'].map((p) => `${p}/${model}`),
|
|
2019
2549
|
model
|
|
2020
2550
|
]
|
|
2551
|
+
},
|
|
2552
|
+
opencode: {
|
|
2553
|
+
// Its default dir depends on XDG_DATA_HOME and, as in ccusage, OPENCODE_DATA_DIR
|
|
2554
|
+
// (comma-separated) replaces it, so both come from envPaths. No other source reads these files.
|
|
2555
|
+
paths: [],
|
|
2556
|
+
envPaths: () => {
|
|
2557
|
+
const dirs = process.env.OPENCODE_DATA_DIR?.split(',').map((p) => p.trim());
|
|
2558
|
+
if (dirs) return dirs.filter(Boolean);
|
|
2559
|
+
const xdg = process.env.XDG_DATA_HOME;
|
|
2560
|
+
return [join(xdg && isAbsolute(xdg) ? xdg : join(HOME, '.local', 'share'), 'opencode')];
|
|
2561
|
+
},
|
|
2562
|
+
read: readOpenCode,
|
|
2563
|
+
priceKeys: opencodePriceKeys
|
|
2021
2564
|
}
|
|
2022
2565
|
};
|
|
2023
2566
|
|
|
@@ -2032,11 +2575,21 @@ function enabledSources() {
|
|
|
2032
2575
|
}
|
|
2033
2576
|
|
|
2034
2577
|
/** @param {[string, Source][]} sources */
|
|
2035
|
-
async function scan(state, resolvePrice, cutoffMs, sources) {
|
|
2578
|
+
async function scan(state, resolvePrice, cutoffMs, sources, polled) {
|
|
2036
2579
|
/** @type {ReadContext} */
|
|
2037
|
-
const ctx = {
|
|
2580
|
+
const ctx = {
|
|
2581
|
+
state,
|
|
2582
|
+
resolvePrice,
|
|
2583
|
+
cutoffMs,
|
|
2584
|
+
codexRefusals: [],
|
|
2585
|
+
seenPaths: new Set(),
|
|
2586
|
+
filesRead: 0,
|
|
2587
|
+
parsedBytes: 0
|
|
2588
|
+
};
|
|
2038
2589
|
for (const [provider, source] of sources) await source.read(source.paths, ctx, provider);
|
|
2039
2590
|
for (const [provider, source] of sources) await source.read(source.envPaths(), ctx, provider);
|
|
2591
|
+
// After every file: a full reading of the refused window can come later in the logs.
|
|
2592
|
+
for (const ts of ctx.codexRefusals) codexRefusal(state, ts, polled);
|
|
2040
2593
|
for (const path of Object.keys(state.files)) {
|
|
2041
2594
|
if (!ctx.seenPaths.has(path)) delete state.files[path];
|
|
2042
2595
|
}
|
|
@@ -2166,7 +2719,8 @@ function buildSnapshot(
|
|
|
2166
2719
|
a.resetsAt.localeCompare(b.resetsAt) ||
|
|
2167
2720
|
a.provider.localeCompare(b.provider) ||
|
|
2168
2721
|
a.window.localeCompare(b.window)
|
|
2169
|
-
)
|
|
2722
|
+
)
|
|
2723
|
+
.slice(-MAX_LIMIT_WINDOWS);
|
|
2170
2724
|
if (limits.length) snapshot.limits = limits;
|
|
2171
2725
|
return { snapshot, sessions24h };
|
|
2172
2726
|
}
|
|
@@ -2241,14 +2795,21 @@ function printSummary(snapshot, sessions24h, nowMs) {
|
|
|
2241
2795
|
// local logs and sent under its own device id: the same account on two machines is one history.
|
|
2242
2796
|
|
|
2243
2797
|
async function cursorRequest(path, bearer, body, headers = {}) {
|
|
2244
|
-
const res = await fetch(
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2798
|
+
const res = await fetch(
|
|
2799
|
+
`${localOverride('BIG_SPENDER_CURSOR_API_URL', 'https://api2.cursor.sh')}${path}`,
|
|
2800
|
+
{
|
|
2801
|
+
method: 'POST',
|
|
2802
|
+
headers: {
|
|
2803
|
+
authorization: `Bearer ${bearer}`,
|
|
2804
|
+
'content-type': 'application/json',
|
|
2805
|
+
...headers
|
|
2806
|
+
},
|
|
2807
|
+
body: JSON.stringify(body),
|
|
2808
|
+
// Never forward the key or token to another host.
|
|
2809
|
+
redirect: 'error',
|
|
2810
|
+
signal: AbortSignal.timeout(30_000)
|
|
2811
|
+
}
|
|
2812
|
+
);
|
|
2252
2813
|
if (!res.ok) {
|
|
2253
2814
|
const hint =
|
|
2254
2815
|
res.status === 401 || res.status === 403 ? '; check BIG_SPENDER_CURSOR_API_KEY' : '';
|
|
@@ -2518,7 +3079,8 @@ async function main() {
|
|
|
2518
3079
|
pruneState(state, coverageStartMs);
|
|
2519
3080
|
const sources = enabledSources();
|
|
2520
3081
|
const enabled = new Set(sources.map(([id]) => id));
|
|
2521
|
-
await
|
|
3082
|
+
const polled = await pollLimits(state, nowMs);
|
|
3083
|
+
await scan(state, resolvePrice, coverageStartMs, sources, polled);
|
|
2522
3084
|
await saveState(state);
|
|
2523
3085
|
|
|
2524
3086
|
const buckets = Object.fromEntries(
|
package/dist/history.js
CHANGED
|
@@ -65,6 +65,16 @@ function dropOldestDays(rows, excess) {
|
|
|
65
65
|
}
|
|
66
66
|
return { rows: rows.slice(cut), days };
|
|
67
67
|
}
|
|
68
|
+
const isEmpty = (r) => !r.sessions &&
|
|
69
|
+
!r.inputTokens &&
|
|
70
|
+
!r.cacheReadTokens &&
|
|
71
|
+
!r.cacheWrite5mTokens &&
|
|
72
|
+
!r.cacheWrite1hTokens &&
|
|
73
|
+
!r.outputTokens &&
|
|
74
|
+
!r.costUsd.input &&
|
|
75
|
+
!r.costUsd.cacheRead &&
|
|
76
|
+
!r.costUsd.cacheWrite &&
|
|
77
|
+
!r.costUsd.output;
|
|
68
78
|
export function mergeSnapshots(stored, next) {
|
|
69
79
|
const sorted = [...next.hourly].sort(compareRows);
|
|
70
80
|
const fresh = sorted.filter(hasTokens);
|
package/dist/schema.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ 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
5
|
export declare const CURSOR_DEVICE_ID = "cursor";
|
|
6
|
-
export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi', 'grok', 'copilot', 'antigravity', 'gemini'];
|
|
6
|
+
export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi', 'grok', 'copilot', 'antigravity', 'gemini', 'opencode'];
|
|
7
7
|
export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
|
|
8
8
|
export declare const usageRowSchema: z.ZodObject<{
|
|
9
9
|
hour: z.ZodISODateTime;
|
|
@@ -19,6 +19,7 @@ export declare const usageRowSchema: z.ZodObject<{
|
|
|
19
19
|
cursor: "cursor";
|
|
20
20
|
gemini: "gemini";
|
|
21
21
|
grok: "grok";
|
|
22
|
+
opencode: "opencode";
|
|
22
23
|
pi: "pi";
|
|
23
24
|
}>;
|
|
24
25
|
model: z.ZodString;
|
|
@@ -46,6 +47,7 @@ export declare const limitWindowSchema: z.ZodObject<{
|
|
|
46
47
|
cursor: "cursor";
|
|
47
48
|
gemini: "gemini";
|
|
48
49
|
grok: "grok";
|
|
50
|
+
opencode: "opencode";
|
|
49
51
|
pi: "pi";
|
|
50
52
|
}>;
|
|
51
53
|
window: z.ZodString;
|
|
@@ -73,6 +75,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
73
75
|
cursor: "cursor";
|
|
74
76
|
gemini: "gemini";
|
|
75
77
|
grok: "grok";
|
|
78
|
+
opencode: "opencode";
|
|
76
79
|
pi: "pi";
|
|
77
80
|
}>;
|
|
78
81
|
model: z.ZodString;
|
|
@@ -101,6 +104,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
101
104
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
102
105
|
gemini: z.ZodOptional<z.ZodNumber>;
|
|
103
106
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
107
|
+
opencode: z.ZodOptional<z.ZodNumber>;
|
|
104
108
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
105
109
|
}, z.core.$strict>>;
|
|
106
110
|
'7d': z.ZodObject<{
|
|
@@ -112,6 +116,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
112
116
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
113
117
|
gemini: z.ZodOptional<z.ZodNumber>;
|
|
114
118
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
119
|
+
opencode: z.ZodOptional<z.ZodNumber>;
|
|
115
120
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
116
121
|
}, z.core.$strict>;
|
|
117
122
|
'30d': z.ZodObject<{
|
|
@@ -123,6 +128,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
123
128
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
124
129
|
gemini: z.ZodOptional<z.ZodNumber>;
|
|
125
130
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
131
|
+
opencode: z.ZodOptional<z.ZodNumber>;
|
|
126
132
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
127
133
|
}, z.core.$strict>;
|
|
128
134
|
'90d': z.ZodObject<{
|
|
@@ -134,6 +140,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
134
140
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
135
141
|
gemini: z.ZodOptional<z.ZodNumber>;
|
|
136
142
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
143
|
+
opencode: z.ZodOptional<z.ZodNumber>;
|
|
137
144
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
138
145
|
}, z.core.$strict>;
|
|
139
146
|
}, z.core.$strict>>;
|
|
@@ -146,6 +153,7 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
146
153
|
cursor: "cursor";
|
|
147
154
|
gemini: "gemini";
|
|
148
155
|
grok: "grok";
|
|
156
|
+
opencode: "opencode";
|
|
149
157
|
pi: "pi";
|
|
150
158
|
}>;
|
|
151
159
|
window: z.ZodString;
|
package/dist/schema.js
CHANGED
|
@@ -22,7 +22,8 @@ export const PROVIDERS = [
|
|
|
22
22
|
'grok',
|
|
23
23
|
'copilot',
|
|
24
24
|
'antigravity',
|
|
25
|
-
'gemini'
|
|
25
|
+
'gemini',
|
|
26
|
+
'opencode'
|
|
26
27
|
];
|
|
27
28
|
// Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
|
|
28
29
|
// than a day: an hourly view would show when each machine is in use.
|
package/package.json
CHANGED
package/templates/env.example
CHANGED
|
@@ -13,3 +13,7 @@ BIG_SPENDER_INGEST_TOKEN=
|
|
|
13
13
|
# Optional: experimental sources to read too, comma-separated. Their counts match ccusage on test
|
|
14
14
|
# data but have not been checked against real usage yet. Available: antigravity, gemini.
|
|
15
15
|
# BIG_SPENDER_EXPERIMENTAL=antigravity
|
|
16
|
+
# Optional: set to off to stop the collector asking Anthropic and OpenAI how full your Claude and
|
|
17
|
+
# Codex limit windows are. It reads the agents' own login files read-only and only sends the token to
|
|
18
|
+
# that provider.
|
|
19
|
+
# BIG_SPENDER_POLL_LIMITS=off
|