big-spender 0.5.0 → 0.6.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 +57 -8
- package/dist/collector.mjs +155 -7
- package/dist/history.js +6 -2
- package/dist/limits.d.ts +48 -0
- package/dist/limits.js +140 -0
- package/dist/page.d.ts +2 -1
- package/dist/page.js +29 -2
- package/dist/push.d.ts +1 -1
- package/dist/push.js +25 -3
- package/dist/schema.d.ts +26 -0
- package/dist/schema.js +16 -1
- package/dist/serve.js +7 -1
- package/dist/server/index.d.ts +5 -1
- package/dist/server/index.js +12 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -32,6 +32,10 @@ nothing is bucketed finer than a UTC day: 7, 30 and 90 days are per day, all tim
|
|
|
32
32
|
(Monday UTC). Device ids are published only if you leave
|
|
33
33
|
`unknownDevices` at its default, see [Device names and colours](#device-names-and-colours).
|
|
34
34
|
|
|
35
|
+
Usage limit windows (see [Usage limits](#usage-limits)) are sent as a window name, its reset time,
|
|
36
|
+
a peak percentage and, when a request was refused, the time of the first refusal. They never name a
|
|
37
|
+
device, and `/api/usage/limits` publishes them per UTC day only.
|
|
38
|
+
|
|
35
39
|
Before the first send you can see exactly what would leave the machine with
|
|
36
40
|
`big-spender push <device> --dry-run`.
|
|
37
41
|
|
|
@@ -145,12 +149,13 @@ Cursor.
|
|
|
145
149
|
|
|
146
150
|
`big-spender serve` is a small `node:http` server:
|
|
147
151
|
|
|
148
|
-
| Route | What it does
|
|
149
|
-
| ------------------------ |
|
|
150
|
-
| `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token).
|
|
151
|
-
| `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`.
|
|
152
|
-
| `GET
|
|
153
|
-
| `GET
|
|
152
|
+
| Route | What it does |
|
|
153
|
+
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
154
|
+
| `POST /api/usage/ingest` | Collectors post a snapshot here (gzip or plain JSON, bearer token). |
|
|
155
|
+
| `GET /api/usage` | Merged totals for 7, 30 and 90 days and all time as JSON, with `cache-control: public, max-age=300, stale-while-revalidate=900`. |
|
|
156
|
+
| `GET /api/usage/limits` | Subscription limit hits per provider and window over the last 90 UTC days, per day, same cache header. See [Usage limits](#usage-limits). |
|
|
157
|
+
| `GET /` | A plain server-rendered page: totals per range, devices with colour swatches, top models, limit hits. No JavaScript, no external assets, light and dark. |
|
|
158
|
+
| `GET /healthz` | `ok`, for load balancers and Docker. |
|
|
154
159
|
|
|
155
160
|
Configuration comes from flags or environment variables (flags win):
|
|
156
161
|
|
|
@@ -234,11 +239,52 @@ Next.js route handler (`export const POST = (request: Request) => bs.ingest(requ
|
|
|
234
239
|
`{ ok, deviceId, rows, result: 'stored' | 'stale' }`).
|
|
235
240
|
- `summary(now?)`: the merged totals for every range. The result is cached for five minutes and
|
|
236
241
|
recomputed right after an ingest.
|
|
242
|
+
- `limits(now?)`: the [usage limit](#usage-limits) summary, cached the same way.
|
|
237
243
|
|
|
238
|
-
The module also exports `summarize(snapshots, now, config)`,
|
|
239
|
-
(`usageSnapshotSchema`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
|
|
244
|
+
The module also exports `summarize(snapshots, now, config)`, `summarizeLimits(snapshots, now)`, the
|
|
245
|
+
snapshot schema (`usageSnapshotSchema`, `limitWindowSchema`, `MAX_LIMIT_WINDOWS`), `resolveDevices`, `RANGES`, `PROVIDERS` and the types, for building your
|
|
240
246
|
own storage or charts.
|
|
241
247
|
|
|
248
|
+
## Usage limits
|
|
249
|
+
|
|
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 only what the agents already
|
|
252
|
+
write to their local logs. It reads no credentials and makes no new network calls.
|
|
253
|
+
|
|
254
|
+
- **Claude Code.** A refused request is logged as an `assistant` line with `error: "rate_limit"`
|
|
255
|
+
and a `quotaLimits` object that names the window (`five_hour`, `seven_day`, a model-specific
|
|
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% is unknown for Claude.
|
|
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). Codex
|
|
261
|
+
is the only source of utilisation below 100%. A window counts as hit when its share reaches 100%.
|
|
262
|
+
|
|
263
|
+
A record is one window instance, identified by provider, window name and reset time rounded down
|
|
264
|
+
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. It holds the peak percentage seen and the time of the first refusal. Limits belong
|
|
266
|
+
to the account, not the machine, so merging keeps the highest peak and the earliest refusal, and
|
|
267
|
+
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
|
+
server, like day rows.
|
|
269
|
+
|
|
270
|
+
`GET /api/usage/limits` returns, for each provider and window over the last 90 UTC days, how many
|
|
271
|
+
window instances were seen, how many were hit, the hours locked out (first refusal until reset),
|
|
272
|
+
the day of the last hit and a per-day series. Claude can move a window's reset later while you are
|
|
273
|
+
blocked, so a refusal before the previous reset extends that lockout instead of counting a new hit. A window counts on the day of its first refusal, or
|
|
274
|
+
of its reset when it was never refused; a window that is still open counts on today with its peak
|
|
275
|
+
so far. It follows the same privacy rule as the rest: nothing
|
|
276
|
+
finer than a UTC day, no device names, no report times. It is separate from `/api/usage`, whose
|
|
277
|
+
shape did not change. `big-spender status` also lists the limits hit in the last 7 days, to the
|
|
278
|
+
minute, because that output never leaves the machine.
|
|
279
|
+
|
|
280
|
+
Polling the Anthropic or OpenAI usage endpoints would show utilisation for Claude too, but it needs
|
|
281
|
+
your OAuth credentials, so it is not done. The record shape already has room for it: a polled
|
|
282
|
+
percentage is just another peak for the same window.
|
|
283
|
+
|
|
284
|
+
An older server rejects the unknown `limits` field with a 422. The collector and `push` then send
|
|
285
|
+
the snapshot again without it and print a warning on each run, so usage keeps arriving. Upgrade the server to store
|
|
286
|
+
limits.
|
|
287
|
+
|
|
242
288
|
## Push by hand
|
|
243
289
|
|
|
244
290
|
For a machine that should only report now and then, or where you would rather not store a token:
|
|
@@ -316,6 +362,9 @@ than 7 days are rolled up to daily rows. Because the aggregates live in the stat
|
|
|
316
362
|
counted even after Claude Code deletes old session logs. `--reset` rebuilds from the logs that still
|
|
317
363
|
exist, so avoid it unless the state is corrupt.
|
|
318
364
|
|
|
365
|
+
Limit windows live in the same state file. The first run after the update re-reads every log once
|
|
366
|
+
to pick up limit lines older runs skipped; it adds no usage.
|
|
367
|
+
|
|
319
368
|
State from an older collector is fixed in place on the first run of a newer one (for example, one
|
|
320
369
|
re-read of the Claude logs to pick up missed output tokens), so updating never needs `--reset`.
|
|
321
370
|
|
package/dist/collector.mjs
CHANGED
|
@@ -125,7 +125,9 @@ async function acquireLock() {
|
|
|
125
125
|
* A seen entry is the first timestamp, or for Claude [first timestamp, output tokens counted].
|
|
126
126
|
* A bare number on a Claude key means the counted output is unknown (state from an older version).
|
|
127
127
|
* @typedef {number | [number, number]} Seen
|
|
128
|
-
*
|
|
128
|
+
* One subscription usage window instance; see limitWindowSchema in src/schema.ts.
|
|
129
|
+
* @typedef {{ provider: string, window: string, resetsAt: string, peakPercent: number, hitAt?: string }} Limit
|
|
130
|
+
* @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
|
|
129
131
|
* cursorBackfills holds a hash of each ingest URL and Cursor API key pair whose server stored the
|
|
130
132
|
* account's full history. Hashed, because an ingest URL can carry a credential.
|
|
131
133
|
*/
|
|
@@ -133,6 +135,8 @@ async function acquireLock() {
|
|
|
133
135
|
// One-time fixes to existing state. The state version stays the same so an older installed copy
|
|
134
136
|
// can still read the file instead of discarding it.
|
|
135
137
|
const FIX_CLAUDE_OUTPUT = 'claude-final-output';
|
|
138
|
+
// Limit windows are read from log lines older versions skipped, so those logs are re-read once.
|
|
139
|
+
const FIX_LIMITS = 'usage-limits';
|
|
136
140
|
|
|
137
141
|
/** @returns {Promise<State>} */
|
|
138
142
|
async function loadState() {
|
|
@@ -141,19 +145,25 @@ async function loadState() {
|
|
|
141
145
|
files: {},
|
|
142
146
|
seen: {},
|
|
143
147
|
buckets: {},
|
|
144
|
-
|
|
148
|
+
limits: {},
|
|
149
|
+
fixes: [FIX_CLAUDE_OUTPUT, FIX_LIMITS]
|
|
145
150
|
};
|
|
146
151
|
if (RESET) return empty;
|
|
147
152
|
try {
|
|
148
153
|
const s = JSON.parse(await readFile(STATE_PATH, 'utf8'));
|
|
149
154
|
if (s?.version !== STATE_VERSION) return empty;
|
|
150
155
|
s.fixes ??= [];
|
|
156
|
+
s.limits ??= {};
|
|
151
157
|
if (!s.fixes.includes(FIX_CLAUDE_OUTPUT)) {
|
|
152
158
|
// Older versions kept the first log line of a Claude message, whose output count can be
|
|
153
159
|
// partial. Re-read the Claude logs once so later lines add what was missed.
|
|
154
160
|
s.fixes.push(FIX_CLAUDE_OUTPUT);
|
|
155
161
|
s.rescan = ['claude'];
|
|
156
162
|
}
|
|
163
|
+
if (!s.fixes.includes(FIX_LIMITS)) {
|
|
164
|
+
s.fixes.push(FIX_LIMITS);
|
|
165
|
+
s.rescan = [...new Set([...(s.rescan ?? []), 'claude', 'codex'])];
|
|
166
|
+
}
|
|
157
167
|
return s;
|
|
158
168
|
} catch {
|
|
159
169
|
return empty;
|
|
@@ -204,6 +214,99 @@ function pruneState(state, cutoffMs) {
|
|
|
204
214
|
for (const [key, v] of Object.entries(state.seen)) {
|
|
205
215
|
if ((Array.isArray(v) ? v[0] : v) < cutoffMs) delete state.seen[key];
|
|
206
216
|
}
|
|
217
|
+
for (const [key, w] of Object.entries(state.limits ?? {})) {
|
|
218
|
+
if (Date.parse(w.resetsAt) < cutoffMs) delete state.limits[key];
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Same rule as mergeLimits in src/limits.ts (this file ships alone, so it cannot import it): one
|
|
223
|
+
// record per window instance, highest peak, earliest hit. Reports of one window can put its reset
|
|
224
|
+
// seconds apart, across a minute boundary, so a reset within RESET_SLACK_MS of a known one of the
|
|
225
|
+
// same window is that one, and the record keeps the earlier reset.
|
|
226
|
+
const MINUTE_MS = 60_000;
|
|
227
|
+
const RESET_SLACK_MS = 2 * MINUTE_MS;
|
|
228
|
+
// Times outside this range are malformed (milliseconds read as seconds, say) and are skipped,
|
|
229
|
+
// never thrown, so a bad limit line cannot stop the usage on the lines after it.
|
|
230
|
+
const LIMIT_TIMES_FROM = Date.parse('2020-01-01T00:00:00Z');
|
|
231
|
+
const LIMIT_TIMES_TO = Date.parse('2100-01-01T00:00:00Z');
|
|
232
|
+
const plausibleTime = (ms) => ms >= LIMIT_TIMES_FROM && ms < LIMIT_TIMES_TO;
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* @param {State} state
|
|
236
|
+
* @param {{ provider: string, window: string, resetsAtMs: number, percent: number, hitMs?: number }} w
|
|
237
|
+
*/
|
|
238
|
+
function addLimit(state, w) {
|
|
239
|
+
let resetsAtMs = Math.floor(w.resetsAtMs / MINUTE_MS) * MINUTE_MS;
|
|
240
|
+
if (!plausibleTime(resetsAtMs) || !/^[a-z0-9_]{1,40}$/.test(w.window)) return;
|
|
241
|
+
if (w.hitMs !== undefined && !plausibleTime(w.hitMs)) return;
|
|
242
|
+
state.limits ??= {};
|
|
243
|
+
let prev;
|
|
244
|
+
for (const [key, l] of Object.entries(state.limits)) {
|
|
245
|
+
const gap = Math.abs(Date.parse(l.resetsAt) - resetsAtMs);
|
|
246
|
+
if (l.provider !== w.provider || l.window !== w.window || gap > RESET_SLACK_MS) continue;
|
|
247
|
+
if (prev && gap >= Math.abs(Date.parse(prev[1].resetsAt) - resetsAtMs)) continue;
|
|
248
|
+
prev = [key, l];
|
|
249
|
+
}
|
|
250
|
+
if (prev) {
|
|
251
|
+
delete state.limits[prev[0]];
|
|
252
|
+
resetsAtMs = Math.min(resetsAtMs, Date.parse(prev[1].resetsAt));
|
|
253
|
+
}
|
|
254
|
+
const hits = [prev?.[1].hitAt && Date.parse(prev[1].hitAt), w.hitMs].filter(Number.isFinite);
|
|
255
|
+
const percent = Math.min(100, Math.max(0, w.percent));
|
|
256
|
+
state.limits[`${w.provider}|${w.window}|${resetsAtMs}`] = {
|
|
257
|
+
provider: w.provider,
|
|
258
|
+
window: w.window,
|
|
259
|
+
resetsAt: new Date(resetsAtMs).toISOString(),
|
|
260
|
+
peakPercent: Math.max(prev?.[1].peakPercent ?? 0, percent),
|
|
261
|
+
...(hits.length ? { hitAt: new Date(Math.min(...hits)).toISOString() } : {})
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Claude Code logs a refused request as a synthetic assistant line carrying quotaLimits.
|
|
266
|
+
// One blocked window repeats on every retry; the key makes the repeats one record.
|
|
267
|
+
function claudeLimit(state, o) {
|
|
268
|
+
const q = o.quotaLimits;
|
|
269
|
+
if (q?.status !== 'rejected' || typeof q.rateLimitType !== 'string') return;
|
|
270
|
+
const ts = Date.parse(o.timestamp);
|
|
271
|
+
if (!Number.isFinite(ts) || !(q.resetsAt > 0)) return;
|
|
272
|
+
addLimit(state, {
|
|
273
|
+
provider: 'claude',
|
|
274
|
+
window: q.rateLimitType
|
|
275
|
+
.toLowerCase()
|
|
276
|
+
.replace(/[^a-z0-9_]/g, '_')
|
|
277
|
+
.slice(0, 40),
|
|
278
|
+
resetsAtMs: q.resetsAt * 1000,
|
|
279
|
+
percent: 100,
|
|
280
|
+
hitMs: ts
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const CODEX_WINDOW_NAMES = { 300: 'five_hour', 10080: 'seven_day' };
|
|
285
|
+
|
|
286
|
+
// Codex token_count lines carry the account's rate limits; a window is null until it is in use.
|
|
287
|
+
function codexLimits(state, o, rateLimits) {
|
|
288
|
+
const ts = Date.parse(o.timestamp);
|
|
289
|
+
if (!Number.isFinite(ts) || !rateLimits) return;
|
|
290
|
+
for (const slot of ['primary', 'secondary']) {
|
|
291
|
+
const w = rateLimits[slot];
|
|
292
|
+
if (!w || typeof w.used_percent !== 'number') continue;
|
|
293
|
+
const minutes = Number(w.window_minutes);
|
|
294
|
+
const window = CODEX_WINDOW_NAMES[minutes] ?? `${minutes}m`;
|
|
295
|
+
const resetsAtMs =
|
|
296
|
+
typeof w.resets_at === 'number'
|
|
297
|
+
? w.resets_at * 1000
|
|
298
|
+
: typeof w.resets_in_seconds === 'number'
|
|
299
|
+
? ts + w.resets_in_seconds * 1000
|
|
300
|
+
: NaN;
|
|
301
|
+
const hit = w.used_percent >= 100;
|
|
302
|
+
addLimit(state, {
|
|
303
|
+
provider: 'codex',
|
|
304
|
+
window,
|
|
305
|
+
resetsAtMs,
|
|
306
|
+
percent: hit ? 100 : w.used_percent,
|
|
307
|
+
...(hit ? { hitMs: ts } : {})
|
|
308
|
+
});
|
|
309
|
+
}
|
|
207
310
|
}
|
|
208
311
|
|
|
209
312
|
// ---------------------------------------------------------------------------
|
|
@@ -364,6 +467,7 @@ function claudeLineHandler(state, resolvePrice, cutoffMs) {
|
|
|
364
467
|
if (!line.includes('"assistant"')) return;
|
|
365
468
|
const o = parseJson(line);
|
|
366
469
|
if (!o || o.type !== 'assistant') return;
|
|
470
|
+
if (o.quotaLimits) claudeLimit(state, o);
|
|
367
471
|
const msg = o.message;
|
|
368
472
|
const usage = msg?.usage;
|
|
369
473
|
const model = msg?.model;
|
|
@@ -442,7 +546,9 @@ function codexLineHandler(state, fileState, resolvePrice, cutoffMs, fallbackSess
|
|
|
442
546
|
fileState.model = p.model;
|
|
443
547
|
return;
|
|
444
548
|
}
|
|
445
|
-
if (o.type !== 'event_msg' || p?.type !== 'token_count'
|
|
549
|
+
if (o.type !== 'event_msg' || p?.type !== 'token_count') return;
|
|
550
|
+
codexLimits(state, o, p.rate_limits);
|
|
551
|
+
if (!p.info) return;
|
|
446
552
|
const total = p.info.total_token_usage?.total_tokens;
|
|
447
553
|
if (typeof total === 'number') {
|
|
448
554
|
if (total === fileState.lastTotal) return;
|
|
@@ -787,13 +893,13 @@ const round = (n, d = 6) => Math.round(n * 10 ** d) / 10 ** d;
|
|
|
787
893
|
/**
|
|
788
894
|
* @param {Record<string, Bucket>} buckets
|
|
789
895
|
* @param {(b: Bucket, provider: string, model: string, tier: number) => Cost} costFor
|
|
790
|
-
* @param {{ deviceId: string, pricingSource: string, providers: string[], nowMs: number, coverageStartMs: number }} meta
|
|
896
|
+
* @param {{ deviceId: string, pricingSource: string, providers: string[], nowMs: number, coverageStartMs: number, limits?: Record<string, Limit> }} meta
|
|
791
897
|
* `providers` names the session counts the snapshot carries.
|
|
792
898
|
*/
|
|
793
899
|
function buildSnapshot(
|
|
794
900
|
buckets,
|
|
795
901
|
costFor,
|
|
796
|
-
{ deviceId, pricingSource, providers, nowMs, coverageStartMs }
|
|
902
|
+
{ deviceId, pricingSource, providers, nowMs, coverageStartMs, limits: windows = {} }
|
|
797
903
|
) {
|
|
798
904
|
const hourlyCutoff = Math.floor((nowMs - HOURLY_DAYS * DAY_MS) / DAY_MS) * DAY_MS;
|
|
799
905
|
/** @type {Map<string, any>} */
|
|
@@ -892,9 +998,34 @@ function buildSnapshot(
|
|
|
892
998
|
sessionsTotal: all.size,
|
|
893
999
|
sessionCounts: publicCounts
|
|
894
1000
|
};
|
|
1001
|
+
const limits = Object.values(windows)
|
|
1002
|
+
.filter((w) => Date.parse(w.resetsAt) >= coverageStartMs)
|
|
1003
|
+
.sort(
|
|
1004
|
+
(a, b) =>
|
|
1005
|
+
a.resetsAt.localeCompare(b.resetsAt) ||
|
|
1006
|
+
a.provider.localeCompare(b.provider) ||
|
|
1007
|
+
a.window.localeCompare(b.window)
|
|
1008
|
+
);
|
|
1009
|
+
if (limits.length) snapshot.limits = limits;
|
|
895
1010
|
return { snapshot, sessions24h };
|
|
896
1011
|
}
|
|
897
1012
|
|
|
1013
|
+
// Local only (never posted), so hit times may be shown to the minute.
|
|
1014
|
+
function limitLines(snapshot, nowMs) {
|
|
1015
|
+
const from = nowMs - 7 * DAY_MS;
|
|
1016
|
+
const hits = new Map();
|
|
1017
|
+
for (const w of snapshot.limits ?? []) {
|
|
1018
|
+
if (!w.hitAt || Date.parse(w.hitAt) < from) continue;
|
|
1019
|
+
const key = `${w.provider} ${w.window}`;
|
|
1020
|
+
hits.set(key, [...(hits.get(key) ?? []), w.hitAt.slice(0, 16).replace('T', ' ')]);
|
|
1021
|
+
}
|
|
1022
|
+
if (!hits.size) return [];
|
|
1023
|
+
return [
|
|
1024
|
+
'Limits hit, last 7 days (UTC)',
|
|
1025
|
+
...[...hits].map(([key, times]) => ` ${key.padEnd(24)} ${times.length}x last ${times.at(-1)}`)
|
|
1026
|
+
];
|
|
1027
|
+
}
|
|
1028
|
+
|
|
898
1029
|
function printSummary(snapshot, sessions24h, nowMs) {
|
|
899
1030
|
const from = Math.floor(nowMs / HOUR_MS) * HOUR_MS + HOUR_MS - DAY_MS;
|
|
900
1031
|
const byModel = new Map();
|
|
@@ -934,6 +1065,7 @@ function printSummary(snapshot, sessions24h, nowMs) {
|
|
|
934
1065
|
([m, v]) =>
|
|
935
1066
|
` ${m.padEnd(28)} ${usd(v.cost).padStart(10)} ${(v.tokens / 1e6).toFixed(1)}M tok`
|
|
936
1067
|
),
|
|
1068
|
+
...limitLines(snapshot, nowMs),
|
|
937
1069
|
...(snapshot.pricingSource === 'cursor'
|
|
938
1070
|
? []
|
|
939
1071
|
: [`Compare with \`bunx ccusage claude daily\` (Claude Code only) for this device.`])
|
|
@@ -1136,7 +1268,22 @@ function assertHeaderSafe(secret, name) {
|
|
|
1136
1268
|
}
|
|
1137
1269
|
}
|
|
1138
1270
|
|
|
1271
|
+
// The 422 a server without limit support sends: its strict schema names the key it doesn't know.
|
|
1272
|
+
// Any other limits error is a real bug and must not silently drop the windows.
|
|
1273
|
+
const OLD_SERVER_422 = /Unrecognized key.{0,20}limits/;
|
|
1274
|
+
|
|
1139
1275
|
async function post(snapshot) {
|
|
1276
|
+
try {
|
|
1277
|
+
return await postOnce(snapshot);
|
|
1278
|
+
} catch (err) {
|
|
1279
|
+
if (err.status !== 422 || !snapshot.limits || !OLD_SERVER_422.test(err.message)) throw err;
|
|
1280
|
+
log('warning: the server is too old to store limit data; sending usage without it');
|
|
1281
|
+
const { limits, ...usageOnly } = snapshot;
|
|
1282
|
+
return await postOnce(usageOnly);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
async function postOnce(snapshot) {
|
|
1140
1287
|
const url = setting('INGEST_URL');
|
|
1141
1288
|
const token = setting('INGEST_TOKEN').trim();
|
|
1142
1289
|
if (!url || !token) {
|
|
@@ -1165,7 +1312,7 @@ async function post(snapshot) {
|
|
|
1165
1312
|
);
|
|
1166
1313
|
return parseJson(reply)?.result;
|
|
1167
1314
|
}
|
|
1168
|
-
lastErr = new Error(`HTTP ${res.status}: ${text}`);
|
|
1315
|
+
lastErr = Object.assign(new Error(`HTTP ${res.status}: ${text}`), { status: res.status });
|
|
1169
1316
|
// Client errors other than rate limiting won't fix themselves.
|
|
1170
1317
|
if (res.status >= 400 && res.status < 500 && res.status !== 429) break;
|
|
1171
1318
|
} catch (err) {
|
|
@@ -1224,7 +1371,8 @@ async function main() {
|
|
|
1224
1371
|
(p) => p === 'claude' || p === 'codex' || used.has(p)
|
|
1225
1372
|
),
|
|
1226
1373
|
nowMs,
|
|
1227
|
-
coverageStartMs
|
|
1374
|
+
coverageStartMs,
|
|
1375
|
+
limits: state.limits
|
|
1228
1376
|
}
|
|
1229
1377
|
);
|
|
1230
1378
|
if (SUMMARY_ONLY) {
|
package/dist/history.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { mergeLimits } from './limits.js';
|
|
1
2
|
import { MAX_ROWS, usageRowSchema } from './schema.js';
|
|
2
3
|
const DAY_MS = 86_400_000;
|
|
3
4
|
const round = (n) => Math.round(n * 1e6) / 1e6;
|
|
@@ -62,8 +63,11 @@ function dropOldestDays(rows, excess) {
|
|
|
62
63
|
}
|
|
63
64
|
export function mergeSnapshots(stored, next) {
|
|
64
65
|
const fresh = [...next.hourly].sort(compareRows);
|
|
66
|
+
const limits = mergeLimits(stored?.limits, next.limits);
|
|
67
|
+
const withLimits = limits.length ? { limits } : {};
|
|
68
|
+
const { limits: _, ...rest } = next;
|
|
65
69
|
if (!stored)
|
|
66
|
-
return { snapshot: { ...
|
|
70
|
+
return { snapshot: { ...rest, hourly: fresh, ...withLimits }, droppedDays: 0 };
|
|
67
71
|
const reported = new Set(fresh.map(keyOf));
|
|
68
72
|
const kept = [...group(stored.hourly)]
|
|
69
73
|
.filter(([key]) => !reported.has(key))
|
|
@@ -81,5 +85,5 @@ export function mergeSnapshots(stored, next) {
|
|
|
81
85
|
if (latest > Date.parse(coverage))
|
|
82
86
|
coverage = new Date(latest).toISOString();
|
|
83
87
|
}
|
|
84
|
-
return { snapshot: { ...
|
|
88
|
+
return { snapshot: { ...rest, coverageStart: coverage, hourly, ...withLimits }, droppedDays };
|
|
85
89
|
}
|
package/dist/limits.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type LimitWindow, type UsageProvider, type UsageSnapshot } from './schema.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Merges window lists into one record per window instance: same provider and window, with resets
|
|
4
|
+
* at most RESET_SLACK_MS after the earliest reset of the group (rounded down to the minute), which
|
|
5
|
+
* the record keeps. A group keeps the highest peak and the earliest hit, so merging is idempotent
|
|
6
|
+
* and one account's window reported by two devices counts once. Sorted by reset time; past the
|
|
7
|
+
* cap the oldest are dropped.
|
|
8
|
+
*/
|
|
9
|
+
export declare function mergeLimits(...lists: (LimitWindow[] | undefined)[]): LimitWindow[];
|
|
10
|
+
export type LimitsSeries = {
|
|
11
|
+
hits: number[];
|
|
12
|
+
lockedHours: number[];
|
|
13
|
+
peakPercent: (number | null)[];
|
|
14
|
+
};
|
|
15
|
+
export type LimitWindowSummary = {
|
|
16
|
+
window: string;
|
|
17
|
+
/** Window instances seen in range, after de-duplicating across devices. */
|
|
18
|
+
observed: number;
|
|
19
|
+
/**
|
|
20
|
+
* Lockouts: instances where a request was blocked. A block before the previous lockout's reset
|
|
21
|
+
* extends that lockout (the provider moved its reset) instead of counting again.
|
|
22
|
+
*/
|
|
23
|
+
hit: number;
|
|
24
|
+
/** Hours from the first block of each lockout to its last reset. */
|
|
25
|
+
lockedHours: number;
|
|
26
|
+
/** UTC day (YYYY-MM-DD) of the latest hit. */
|
|
27
|
+
lastHit: string | null;
|
|
28
|
+
/**
|
|
29
|
+
* One entry per UTC day from `from` to `to`. An instance belongs to the day of its first
|
|
30
|
+
* block, or of its reset when it was never blocked; a window still open belongs to today.
|
|
31
|
+
*/
|
|
32
|
+
series: LimitsSeries;
|
|
33
|
+
};
|
|
34
|
+
export type LimitsSummary = {
|
|
35
|
+
generatedAt: string;
|
|
36
|
+
from: string;
|
|
37
|
+
to: string;
|
|
38
|
+
bucket: 'day';
|
|
39
|
+
providers: {
|
|
40
|
+
provider: UsageProvider;
|
|
41
|
+
windows: LimitWindowSummary[];
|
|
42
|
+
}[];
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Limit hits over the last 90 UTC days, ending at the end of today (the 90d range window).
|
|
46
|
+
* Nothing finer than a UTC day is published and no device is named.
|
|
47
|
+
*/
|
|
48
|
+
export declare function summarizeLimits(snapshots: UsageSnapshot[], now: number): LimitsSummary;
|
package/dist/limits.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Subscription usage-limit windows: merging them across reports and devices, and the public
|
|
2
|
+
// summary. Pure functions (no I/O).
|
|
3
|
+
import { MAX_LIMIT_WINDOWS, PROVIDERS } from './schema.js';
|
|
4
|
+
const MINUTE_MS = 60_000;
|
|
5
|
+
const HOUR_MS = 3_600_000;
|
|
6
|
+
const DAY_MS = 86_400_000;
|
|
7
|
+
const RANGE_DAYS = 90;
|
|
8
|
+
const minuteOf = (iso) => Math.floor(Date.parse(iso) / MINUTE_MS) * MINUTE_MS;
|
|
9
|
+
// Reports of one window can put its reset seconds apart, across a minute boundary.
|
|
10
|
+
const RESET_SLACK_MS = 2 * MINUTE_MS;
|
|
11
|
+
/**
|
|
12
|
+
* Merges window lists into one record per window instance: same provider and window, with resets
|
|
13
|
+
* at most RESET_SLACK_MS after the earliest reset of the group (rounded down to the minute), which
|
|
14
|
+
* the record keeps. A group keeps the highest peak and the earliest hit, so merging is idempotent
|
|
15
|
+
* and one account's window reported by two devices counts once. Sorted by reset time; past the
|
|
16
|
+
* cap the oldest are dropped.
|
|
17
|
+
*/
|
|
18
|
+
export function mergeLimits(...lists) {
|
|
19
|
+
const all = lists
|
|
20
|
+
.flatMap((list) => list ?? [])
|
|
21
|
+
.map((w) => ({
|
|
22
|
+
provider: w.provider,
|
|
23
|
+
window: w.window,
|
|
24
|
+
resetsAt: new Date(minuteOf(w.resetsAt)).toISOString(),
|
|
25
|
+
peakPercent: w.peakPercent,
|
|
26
|
+
...(w.hitAt ? { hitAt: w.hitAt } : {})
|
|
27
|
+
}))
|
|
28
|
+
.sort((a, b) => a.provider.localeCompare(b.provider) ||
|
|
29
|
+
a.window.localeCompare(b.window) ||
|
|
30
|
+
Date.parse(a.resetsAt) - Date.parse(b.resetsAt));
|
|
31
|
+
const merged = [];
|
|
32
|
+
for (const w of all) {
|
|
33
|
+
const group = merged.at(-1);
|
|
34
|
+
if (!group ||
|
|
35
|
+
group.provider !== w.provider ||
|
|
36
|
+
group.window !== w.window ||
|
|
37
|
+
Date.parse(w.resetsAt) - Date.parse(group.resetsAt) > RESET_SLACK_MS) {
|
|
38
|
+
merged.push(w);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const hits = [group.hitAt, w.hitAt].filter((t) => t !== undefined);
|
|
42
|
+
const hitAt = hits.sort((a, b) => Date.parse(a) - Date.parse(b))[0];
|
|
43
|
+
merged[merged.length - 1] = {
|
|
44
|
+
provider: group.provider,
|
|
45
|
+
window: group.window,
|
|
46
|
+
resetsAt: group.resetsAt,
|
|
47
|
+
peakPercent: Math.max(group.peakPercent, w.peakPercent),
|
|
48
|
+
...(hitAt ? { hitAt } : {})
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
const sorted = merged.sort((a, b) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt) ||
|
|
52
|
+
a.provider.localeCompare(b.provider) ||
|
|
53
|
+
a.window.localeCompare(b.window));
|
|
54
|
+
return sorted.slice(Math.max(0, sorted.length - MAX_LIMIT_WINDOWS));
|
|
55
|
+
}
|
|
56
|
+
const KNOWN_ORDER = ['five_hour', 'seven_day'];
|
|
57
|
+
const rank = (w) => {
|
|
58
|
+
const i = KNOWN_ORDER.indexOf(w);
|
|
59
|
+
return i === -1 ? KNOWN_ORDER.length : i;
|
|
60
|
+
};
|
|
61
|
+
const tenth = (n) => Math.round(n * 10) / 10;
|
|
62
|
+
/**
|
|
63
|
+
* Limit hits over the last 90 UTC days, ending at the end of today (the 90d range window).
|
|
64
|
+
* Nothing finer than a UTC day is published and no device is named.
|
|
65
|
+
*/
|
|
66
|
+
export function summarizeLimits(snapshots, now) {
|
|
67
|
+
const to = Math.floor(now / DAY_MS) * DAY_MS + DAY_MS;
|
|
68
|
+
const from = to - RANGE_DAYS * DAY_MS;
|
|
69
|
+
const windows = mergeLimits(...snapshots.map((s) => s.limits));
|
|
70
|
+
const anchor = (w) => Math.min(Date.parse(w.hitAt ?? w.resetsAt), now);
|
|
71
|
+
const providers = PROVIDERS.flatMap((provider) => {
|
|
72
|
+
const byWindow = new Map();
|
|
73
|
+
for (const w of windows) {
|
|
74
|
+
if (w.provider !== provider)
|
|
75
|
+
continue;
|
|
76
|
+
if (anchor(w) < from || anchor(w) >= to)
|
|
77
|
+
continue;
|
|
78
|
+
byWindow.set(w.window, [...(byWindow.get(w.window) ?? []), w]);
|
|
79
|
+
}
|
|
80
|
+
const summaries = [...byWindow]
|
|
81
|
+
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
|
|
82
|
+
.map(([window, list]) => {
|
|
83
|
+
const series = {
|
|
84
|
+
hits: Array(RANGE_DAYS).fill(0),
|
|
85
|
+
lockedHours: Array(RANGE_DAYS).fill(0),
|
|
86
|
+
peakPercent: Array(RANGE_DAYS).fill(null)
|
|
87
|
+
};
|
|
88
|
+
let lastHit = null;
|
|
89
|
+
let hit = 0;
|
|
90
|
+
let locked = 0;
|
|
91
|
+
let absorbed = 0;
|
|
92
|
+
// The lockout in progress: its day, and when it ends so far.
|
|
93
|
+
let lockout;
|
|
94
|
+
const byHit = list.sort((a, b) => Date.parse(a.hitAt ?? a.resetsAt) - Date.parse(b.hitAt ?? b.resetsAt));
|
|
95
|
+
for (const w of byHit) {
|
|
96
|
+
const day = Math.floor((anchor(w) - from) / DAY_MS);
|
|
97
|
+
series.peakPercent[day] = Math.max(series.peakPercent[day] ?? 0, w.peakPercent);
|
|
98
|
+
if (!w.hitAt)
|
|
99
|
+
continue;
|
|
100
|
+
const hitMs = Date.parse(w.hitAt);
|
|
101
|
+
const resetMs = Date.parse(w.resetsAt);
|
|
102
|
+
lastHit = Math.max(lastHit ?? 0, hitMs);
|
|
103
|
+
// A provider can move the reset of a window while it is blocked (Claude does: a
|
|
104
|
+
// refusal at 20:46 said 00:20, one at 22:23 said 01:40). A hit before the current
|
|
105
|
+
// lockout ends is that lockout running longer, not a second one.
|
|
106
|
+
if (lockout && hitMs < lockout.endMs) {
|
|
107
|
+
absorbed++;
|
|
108
|
+
const extra = Math.max(0, resetMs - lockout.endMs) / HOUR_MS;
|
|
109
|
+
lockout.endMs = Math.max(lockout.endMs, resetMs);
|
|
110
|
+
locked += extra;
|
|
111
|
+
series.lockedHours[lockout.day] += extra;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const hours = Math.max(0, resetMs - hitMs) / HOUR_MS;
|
|
115
|
+
lockout = { day, endMs: resetMs };
|
|
116
|
+
hit++;
|
|
117
|
+
locked += hours;
|
|
118
|
+
series.hits[day]++;
|
|
119
|
+
series.lockedHours[day] += hours;
|
|
120
|
+
}
|
|
121
|
+
series.lockedHours = series.lockedHours.map(tenth);
|
|
122
|
+
return {
|
|
123
|
+
window,
|
|
124
|
+
observed: list.length - absorbed,
|
|
125
|
+
hit,
|
|
126
|
+
lockedHours: tenth(locked),
|
|
127
|
+
lastHit: lastHit === null ? null : new Date(lastHit).toISOString().slice(0, 10),
|
|
128
|
+
series
|
|
129
|
+
};
|
|
130
|
+
});
|
|
131
|
+
return summaries.length ? [{ provider, windows: summaries }] : [];
|
|
132
|
+
});
|
|
133
|
+
return {
|
|
134
|
+
generatedAt: new Date(now).toISOString(),
|
|
135
|
+
from: new Date(from).toISOString(),
|
|
136
|
+
to: new Date(to).toISOString(),
|
|
137
|
+
bucket: 'day',
|
|
138
|
+
providers
|
|
139
|
+
};
|
|
140
|
+
}
|
package/dist/page.d.ts
CHANGED
package/dist/page.js
CHANGED
|
@@ -38,6 +38,9 @@ th { color: var(--muted); font-weight: 500; font-size: 0.85rem; }
|
|
|
38
38
|
.swatch { display: inline-block; width: 0.75rem; height: 0.75rem; margin-right: 0.5rem; border-radius: 50%; vertical-align: -0.05em; }
|
|
39
39
|
.scroll { overflow-x: auto; }
|
|
40
40
|
.empty { color: var(--muted); }
|
|
41
|
+
.days td, .days th { padding: 0.35rem 0.25rem; font-size: 0.8rem; text-align: center; }
|
|
42
|
+
.days td:first-child, .days th:first-child { padding-right: 0.75rem; text-align: left; }
|
|
43
|
+
.days .hit { color: #c0392b; font-weight: 600; }
|
|
41
44
|
`;
|
|
42
45
|
function totalsCard(r) {
|
|
43
46
|
return `<section class="card"><h3>${LABELS[r.range]}</h3>
|
|
@@ -67,7 +70,31 @@ function modelsTable(r) {
|
|
|
67
70
|
.map((m) => `<tr><td>${escapeHtml(m.model)}</td><td>${escapeHtml(m.provider)}</td><td>${usd(m.cost)}</td><td>${percent(m.share)}</td><td>${tokens(m.tokens)}</td></tr>`);
|
|
68
71
|
return `<div class="scroll"><table><thead><tr><th>Model</th><th>Agent</th><th>Cost</th><th>Share</th><th>Tokens</th></tr></thead><tbody>${rows.join('')}</tbody></table></div>`;
|
|
69
72
|
}
|
|
70
|
-
|
|
73
|
+
const WINDOW_LABELS = {
|
|
74
|
+
five_hour: '5-hour session',
|
|
75
|
+
seven_day: 'Weekly'
|
|
76
|
+
};
|
|
77
|
+
const windowLabel = (w) => WINDOW_LABELS[w] ??
|
|
78
|
+
(w.startsWith('seven_day_') ? `Weekly · ${w.slice(10)}` : w).replace(/_/g, ' ');
|
|
79
|
+
const RECENT_DAYS = 14;
|
|
80
|
+
function limitsSection(limits) {
|
|
81
|
+
const rows = limits.providers.flatMap((p) => p.windows.map((w) => ({ provider: p.provider, w })));
|
|
82
|
+
if (!rows.length)
|
|
83
|
+
return '<p class="empty">No usage limit windows recorded in the last 90 days.</p>';
|
|
84
|
+
const totals = rows.map(({ provider, w }) => `<tr><td>${escapeHtml(provider)} · ${escapeHtml(windowLabel(w.window))}</td><td>${w.observed}</td><td>${w.hit}</td><td>${w.lockedHours.toFixed(1)}</td><td>${w.lastHit ?? '-'}</td></tr>`);
|
|
85
|
+
const first = Date.parse(limits.to) - RECENT_DAYS * 86_400_000;
|
|
86
|
+
const heads = Array.from({ length: RECENT_DAYS }, (_, i) => new Date(first + i * 86_400_000).toISOString().slice(8, 10));
|
|
87
|
+
const days = rows.map(({ provider, w }) => {
|
|
88
|
+
const cells = w.series.hits
|
|
89
|
+
.slice(-RECENT_DAYS)
|
|
90
|
+
.map((n) => (n ? `<td class="hit">${n}</td>` : '<td>·</td>'));
|
|
91
|
+
return `<tr><td>${escapeHtml(provider)} · ${escapeHtml(windowLabel(w.window))}</td>${cells.join('')}</tr>`;
|
|
92
|
+
});
|
|
93
|
+
return `<div class="scroll"><table><thead><tr><th>Window</th><th>Seen</th><th>Hit</th><th>Locked hours</th><th>Last hit</th></tr></thead><tbody>${totals.join('')}</tbody></table></div>
|
|
94
|
+
<p class="sub">Hits per day, last ${RECENT_DAYS} days (UTC day of month)</p>
|
|
95
|
+
<div class="scroll"><table class="days"><thead><tr><th>Window</th>${heads.map((d) => `<th>${d}</th>`).join('')}</tr></thead><tbody>${days.join('')}</tbody></table></div>`;
|
|
96
|
+
}
|
|
97
|
+
export function renderPage(summary, limits) {
|
|
71
98
|
const updated = escapeHtml(summary.generatedAt);
|
|
72
99
|
return `<!doctype html>
|
|
73
100
|
<html lang="en">
|
|
@@ -86,7 +113,7 @@ export function renderPage(summary) {
|
|
|
86
113
|
${devicesTable(summary)}
|
|
87
114
|
<h2>Top models, last 30 days</h2>
|
|
88
115
|
${modelsTable(summary.ranges['30d'])}
|
|
89
|
-
</main>
|
|
116
|
+
${limits ? `<h2>Usage limits, last 90 days</h2>\n${limitsSection(limits)}\n` : ''}</main>
|
|
90
117
|
</body>
|
|
91
118
|
</html>
|
|
92
119
|
`;
|
package/dist/push.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { type Context } from './context.ts';
|
|
2
|
-
export declare const PUSH_USAGE = "Usage: big-spender push <device> [--dry-run] [--url <ingest url>]\n\nOne-off push from a machine without a schedule. Builds the snapshot, shows what it would publish\nand stops if a model name looks like a cloud resource id (for example a Bedrock inference-profile\nARN, which contains an account id). Asks before sending. The URL comes from --url,\nBIG_SPENDER_INGEST_URL or a prompt, and the token from BIG_SPENDER_INGEST_TOKEN or a hidden\nprompt, so neither is written to this machine. Nothing is scheduled.\n\n--dry-run prints the overview, writes the exact JSON that would be sent to\n$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the\ncollector's local state in ~/.cache/big-spender (which logs were read), never anything remote.\nCursor usage is not part of a push: only the scheduled collector sends it.";
|
|
2
|
+
export declare const PUSH_USAGE = "Usage: big-spender push <device> [--dry-run] [--url <ingest url>]\n\nOne-off push from a machine without a schedule. Builds the snapshot, shows what it would publish\nand stops if a model name looks like a cloud resource id (for example a Bedrock inference-profile\nARN, which contains an account id). Asks before sending. The URL comes from --url,\nBIG_SPENDER_INGEST_URL or a prompt, and the token from BIG_SPENDER_INGEST_TOKEN or a hidden\nprompt, so neither is written to this machine. Nothing is scheduled.\n\n--dry-run prints the overview, writes the exact JSON that would be sent to\n$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the\ncollector's local state in ~/.cache/big-spender (which logs were read), never anything remote.\nA server too old to store usage-limit windows gets the snapshot again without them.\nCursor usage is not part of a push: only the scheduled collector sends it.";
|
|
3
3
|
export declare function push(args: string[], ctx: Context): Promise<number>;
|
package/dist/push.js
CHANGED
|
@@ -17,6 +17,7 @@ prompt, so neither is written to this machine. Nothing is scheduled.
|
|
|
17
17
|
--dry-run prints the overview, writes the exact JSON that would be sent to
|
|
18
18
|
$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the
|
|
19
19
|
collector's local state in ~/.cache/big-spender (which logs were read), never anything remote.
|
|
20
|
+
A server too old to store usage-limit windows gets the snapshot again without them.
|
|
20
21
|
Cursor usage is not part of a push: only the scheduled collector sends it.`;
|
|
21
22
|
const MAX_SNAPSHOT_BYTES = 512 * 1024 * 1024;
|
|
22
23
|
const POST_ATTEMPTS = 4;
|
|
@@ -59,7 +60,13 @@ function overview(snapshot, gzipped) {
|
|
|
59
60
|
'',
|
|
60
61
|
` ${'provider model'.padEnd(width)} ${'tokens'.padStart(10)} ${'cost'.padStart(10)}`,
|
|
61
62
|
...rows.map(([k, m]) => line(k, m.tokens, m.cost)),
|
|
62
|
-
line('total', tokens, cost)
|
|
63
|
+
line('total', tokens, cost),
|
|
64
|
+
...(snapshot.limits
|
|
65
|
+
? [
|
|
66
|
+
'',
|
|
67
|
+
`${snapshot.limits.length} usage-limit windows (name, reset time, peak percent, first block time) are published too.`
|
|
68
|
+
]
|
|
69
|
+
: [])
|
|
63
70
|
];
|
|
64
71
|
}
|
|
65
72
|
export async function push(args, ctx) {
|
|
@@ -120,8 +127,23 @@ export async function push(args, ctx) {
|
|
|
120
127
|
if (!/^[\x21-\x7e]+$/.test(token)) {
|
|
121
128
|
throw new Error('the ingest token contains characters that are not allowed in an HTTP header; check it for spaces or a stray newline');
|
|
122
129
|
}
|
|
123
|
-
|
|
124
|
-
|
|
130
|
+
let sent = body;
|
|
131
|
+
let result;
|
|
132
|
+
try {
|
|
133
|
+
result = await send(ctx, url, token, body);
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
// A server from before limits existed rejects the unknown key with a 422 naming it. Any
|
|
137
|
+
// other limits error is a real bug and must not silently drop the windows.
|
|
138
|
+
const message = err instanceof Error ? err.message : '';
|
|
139
|
+
if (!snapshot.limits || !/^HTTP 422\b.*Unrecognized key.{0,20}limits/.test(message))
|
|
140
|
+
throw err;
|
|
141
|
+
ctx.err('warning: the server is too old to store limit data; sending usage without it');
|
|
142
|
+
const { limits: _, ...usageOnly } = snapshot;
|
|
143
|
+
sent = gzipSync(JSON.stringify(usageOnly));
|
|
144
|
+
result = await send(ctx, url, token, sent);
|
|
145
|
+
}
|
|
146
|
+
ctx.out(`posted ${snapshot.hourly.length} rows (${sent.length} bytes gzipped): ${result}`);
|
|
125
147
|
return 0;
|
|
126
148
|
}
|
|
127
149
|
/** POSTs the reviewed bytes with the collector's retry policy and returns the server's reply. */
|
package/dist/schema.d.ts
CHANGED
|
@@ -32,6 +32,19 @@ export declare const usageRowSchema: z.ZodObject<{
|
|
|
32
32
|
}, z.core.$strict>;
|
|
33
33
|
cacheSavingsUsd: z.ZodNumber;
|
|
34
34
|
}, z.core.$strict>;
|
|
35
|
+
export declare const MAX_LIMIT_WINDOWS = 5000;
|
|
36
|
+
export declare const limitWindowSchema: z.ZodObject<{
|
|
37
|
+
provider: z.ZodEnum<{
|
|
38
|
+
claude: "claude";
|
|
39
|
+
codex: "codex";
|
|
40
|
+
cursor: "cursor";
|
|
41
|
+
pi: "pi";
|
|
42
|
+
}>;
|
|
43
|
+
window: z.ZodString;
|
|
44
|
+
resetsAt: z.ZodISODateTime;
|
|
45
|
+
peakPercent: z.ZodNumber;
|
|
46
|
+
hitAt: z.ZodOptional<z.ZodISODateTime>;
|
|
47
|
+
}, z.core.$strict>;
|
|
35
48
|
export declare const usageSnapshotSchema: z.ZodObject<{
|
|
36
49
|
schemaVersion: z.ZodLiteral<1>;
|
|
37
50
|
deviceId: z.ZodString;
|
|
@@ -96,7 +109,20 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
96
109
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
97
110
|
}, z.core.$strict>;
|
|
98
111
|
}, z.core.$strict>>;
|
|
112
|
+
limits: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
113
|
+
provider: z.ZodEnum<{
|
|
114
|
+
claude: "claude";
|
|
115
|
+
codex: "codex";
|
|
116
|
+
cursor: "cursor";
|
|
117
|
+
pi: "pi";
|
|
118
|
+
}>;
|
|
119
|
+
window: z.ZodString;
|
|
120
|
+
resetsAt: z.ZodISODateTime;
|
|
121
|
+
peakPercent: z.ZodNumber;
|
|
122
|
+
hitAt: z.ZodOptional<z.ZodISODateTime>;
|
|
123
|
+
}, z.core.$strict>>>;
|
|
99
124
|
}, z.core.$strict>;
|
|
125
|
+
export type LimitWindow = z.infer<typeof limitWindowSchema>;
|
|
100
126
|
export type UsageRow = z.infer<typeof usageRowSchema>;
|
|
101
127
|
export type UsageSnapshot = z.infer<typeof usageSnapshotSchema>;
|
|
102
128
|
export type UsageProvider = (typeof PROVIDERS)[number];
|
package/dist/schema.js
CHANGED
|
@@ -36,6 +36,20 @@ export const usageRowSchema = z.strictObject({
|
|
|
36
36
|
costUsd: z.strictObject({ input: usd, cacheRead: usd, cacheWrite: usd, output: usd }),
|
|
37
37
|
cacheSavingsUsd: usd
|
|
38
38
|
});
|
|
39
|
+
export const MAX_LIMIT_WINDOWS = 5_000;
|
|
40
|
+
// One subscription usage window (the 5-hour session, the weekly cap, ...) as it was observed.
|
|
41
|
+
// A window instance is identified by (provider, window, resetsAt rounded down to the minute).
|
|
42
|
+
export const limitWindowSchema = z.strictObject({
|
|
43
|
+
provider: z.enum(PROVIDERS),
|
|
44
|
+
// five_hour, seven_day, seven_day_opus, ...; Codex windows are named from window_minutes
|
|
45
|
+
// (300 -> five_hour, 10080 -> seven_day, otherwise `${minutes}m`).
|
|
46
|
+
window: z.string().regex(/^[a-z0-9_]{1,40}$/),
|
|
47
|
+
resetsAt: isoDate,
|
|
48
|
+
// Highest share of the window seen used, 0-100. A blocked request means 100.
|
|
49
|
+
peakPercent: z.number().min(0).max(100),
|
|
50
|
+
// First time a request was refused because this window was used up.
|
|
51
|
+
hitAt: isoDate.optional()
|
|
52
|
+
});
|
|
39
53
|
const count = z.number().int().nonnegative();
|
|
40
54
|
const sessionCount = z.strictObject({
|
|
41
55
|
...Object.fromEntries(PROVIDERS.map((p) => [p, count.optional()])),
|
|
@@ -63,5 +77,6 @@ export const usageSnapshotSchema = z.strictObject({
|
|
|
63
77
|
'30d': sessionCount,
|
|
64
78
|
'90d': sessionCount
|
|
65
79
|
})
|
|
66
|
-
.optional()
|
|
80
|
+
.optional(),
|
|
81
|
+
limits: z.array(limitWindowSchema).max(MAX_LIMIT_WINDOWS).optional()
|
|
67
82
|
});
|
package/dist/serve.js
CHANGED
|
@@ -63,9 +63,15 @@ const routes = {
|
|
|
63
63
|
headers: { 'cache-control': 'public, max-age=300, stale-while-revalidate=900' }
|
|
64
64
|
})
|
|
65
65
|
},
|
|
66
|
+
'/api/usage/limits': {
|
|
67
|
+
methods: ['GET', 'HEAD'],
|
|
68
|
+
handle: async (bs) => Response.json(await bs.limits(), {
|
|
69
|
+
headers: { 'cache-control': 'public, max-age=300, stale-while-revalidate=900' }
|
|
70
|
+
})
|
|
71
|
+
},
|
|
66
72
|
'/': {
|
|
67
73
|
methods: ['GET', 'HEAD'],
|
|
68
|
-
handle: async (bs) => new Response(renderPage(await bs.summary()), {
|
|
74
|
+
handle: async (bs) => new Response(renderPage(await bs.summary(), await bs.limits()), {
|
|
69
75
|
headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' }
|
|
70
76
|
})
|
|
71
77
|
},
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { DeviceConfig } from '../devices.ts';
|
|
2
|
+
import { type LimitsSummary } from '../limits.ts';
|
|
2
3
|
import { type UsageSummary } from '../summary.ts';
|
|
3
|
-
export { DEVICE_ID, PROVIDERS, RANGES, usageRowSchema, usageSnapshotSchema, type UsageProvider, type UsageRange, type UsageRow, type UsageSnapshot } from '../schema.ts';
|
|
4
|
+
export { DEVICE_ID, MAX_LIMIT_WINDOWS, PROVIDERS, RANGES, limitWindowSchema, usageRowSchema, usageSnapshotSchema, type LimitWindow, type UsageProvider, type UsageRange, type UsageRow, type UsageSnapshot } from '../schema.ts';
|
|
5
|
+
export { summarizeLimits, type LimitsSeries, type LimitsSummary, type LimitWindowSummary } from '../limits.ts';
|
|
4
6
|
export { OTHER, PALETTE, resolveDevices, type DeviceConfig, type DeviceInfo } from '../devices.ts';
|
|
5
7
|
export { summarize, type Bucket, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
|
|
6
8
|
export type BigSpenderOptions = {
|
|
@@ -15,5 +17,7 @@ export type BigSpender = {
|
|
|
15
17
|
ingest(request: Request): Promise<Response>;
|
|
16
18
|
/** Merged totals for every range, recomputed at most every few minutes or after an ingest. */
|
|
17
19
|
summary(now?: number): Promise<UsageSummary>;
|
|
20
|
+
/** Subscription limit hits over the last 90 UTC days, cached like `summary`. */
|
|
21
|
+
limits(now?: number): Promise<LimitsSummary>;
|
|
18
22
|
};
|
|
19
23
|
export declare function createBigSpender({ dataDir, ingestToken, devices }: BigSpenderOptions): BigSpender;
|
package/dist/server/index.js
CHANGED
|
@@ -1,19 +1,23 @@
|
|
|
1
1
|
import { fileStore } from '../store.js';
|
|
2
|
+
import { summarizeLimits } from '../limits.js';
|
|
2
3
|
import { summarize } from '../summary.js';
|
|
3
4
|
import { createIngest } from './ingest.js';
|
|
4
|
-
export { DEVICE_ID, PROVIDERS, RANGES, usageRowSchema, usageSnapshotSchema } from '../schema.js';
|
|
5
|
+
export { DEVICE_ID, MAX_LIMIT_WINDOWS, PROVIDERS, RANGES, limitWindowSchema, usageRowSchema, usageSnapshotSchema } from '../schema.js';
|
|
6
|
+
export { summarizeLimits } from '../limits.js';
|
|
5
7
|
export { OTHER, PALETTE, resolveDevices } from '../devices.js';
|
|
6
8
|
export { summarize } from '../summary.js';
|
|
7
9
|
const SUMMARY_TTL_MS = 5 * 60 * 1000;
|
|
8
10
|
export function createBigSpender({ dataDir, ingestToken, devices }) {
|
|
9
11
|
const store = fileStore(dataDir);
|
|
10
12
|
let cache = null;
|
|
13
|
+
let limitsCache = null;
|
|
11
14
|
return {
|
|
12
15
|
ingest: createIngest({
|
|
13
16
|
store,
|
|
14
17
|
token: ingestToken,
|
|
15
18
|
onStored: () => {
|
|
16
19
|
cache = null;
|
|
20
|
+
limitsCache = null;
|
|
17
21
|
}
|
|
18
22
|
}),
|
|
19
23
|
async summary(now = Date.now()) {
|
|
@@ -22,6 +26,13 @@ export function createBigSpender({ dataDir, ingestToken, devices }) {
|
|
|
22
26
|
const value = summarize(await store.list(), now, devices);
|
|
23
27
|
cache = { value, computedAt: now };
|
|
24
28
|
return value;
|
|
29
|
+
},
|
|
30
|
+
async limits(now = Date.now()) {
|
|
31
|
+
if (limitsCache && now - limitsCache.computedAt < SUMMARY_TTL_MS)
|
|
32
|
+
return limitsCache.value;
|
|
33
|
+
const value = summarizeLimits(await store.list(), now);
|
|
34
|
+
limitsCache = { value, computedAt: now };
|
|
35
|
+
return value;
|
|
25
36
|
}
|
|
26
37
|
};
|
|
27
38
|
}
|