big-spender 0.7.0 → 0.9.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 +27 -13
- package/dist/collector.mjs +878 -32
- package/dist/history.js +7 -2
- package/dist/schema.d.ts +17 -1
- package/dist/schema.js +9 -1
- package/package.json +1 -1
- package/templates/env.example +3 -0
package/README.md
CHANGED
|
@@ -327,25 +327,39 @@ about 15 to 20 percent less.
|
|
|
327
327
|
|
|
328
328
|
## How it counts
|
|
329
329
|
|
|
330
|
-
| Source
|
|
331
|
-
|
|
|
332
|
-
| Claude Code
|
|
333
|
-
| Codex
|
|
334
|
-
| Cursor
|
|
335
|
-
| pi
|
|
336
|
-
| Grok Build (experimental)
|
|
337
|
-
|
|
338
|
-
**
|
|
339
|
-
|
|
330
|
+
| Source | Files | Notes |
|
|
331
|
+
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
332
|
+
| Claude Code | `~/.claude/projects/**/*.jsonl`, `~/.config/claude/projects`, `$CLAUDE_CONFIG_DIR/projects` | `assistant` lines; de-duplicated by `message.id` + `requestId` (one API response is logged once per content block, and resumed sessions copy history). `<synthetic>` skipped; subagent logs included. Some Claude Code versions (2.1.293 to 2.1.310) log a partial output count on a message's first line and the final count on a later line; a later line that reports more output adds the difference. |
|
|
333
|
+
| Codex | `~/.codex/sessions/**/rollout-*.jsonl`, `$CODEX_HOME/sessions` | `event_msg` / `token_count` with `info.last_token_usage`; skipped when `total_token_usage` did not change. Model from the latest `turn_context`. `cached_input_tokens` is part of `input_tokens`; reasoning is part of `output_tokens`. |
|
|
334
|
+
| Cursor | Cursor's API, `DashboardService/GetFilteredUsageEvents`, with `BIG_SPENDER_CURSOR_API_KEY` | Events with token counts only. Cost is Cursor's `totalCents`. Events have no unique id and pages can overlap, so a time window with more than 1,000 events is split in half instead of paged. `cacheWriteTokens` count as 5-minute cache writes. Sessions are hashed `conversationId`s. Model names are lowercased, and anything outside `a-z 0-9 . _ : @ -` becomes `-`. |
|
|
335
|
+
| pi | `~/.pi/agent/sessions/**/*.jsonl`, `$PI_CODING_AGENT_DIR/sessions`, `$PI_CODING_AGENT_SESSION_DIR`, `$PI_AGENT_DIR` (comma-separated, as in ccusage) | Assistant `message` entries with `usage`; `input` excludes cached tokens, reasoning is part of `output`, and `cacheWrite` counts as 5-minute writes except its `cacheWrite1h` part. Calls with no tokens (aborted, failed before a retry) are skipped, and a call with only `totalTokens` counts it as output. A fork's file starts with a copy of its parent's calls up to the fork; those leading calls are skipped when the parent file has them. ccusage looks only at the parent's current branch, so it counts the copy again once the parent moves to another branch. A model id that is a file path (absolute, a `file://` or `host:/` URL, or ending in `.gguf` and similar) is reduced to its file name. `subagent-artifacts/` transcripts are skipped. Cost is LiteLLM's, not the cost pi stores. |
|
|
336
|
+
| Grok Build (experimental) | `~/.grok/sessions/**/updates.jsonl`, `$GROK_HOME/sessions` | **Experimental:** checked against ccusage on test fixtures built from its Grok parser tests, not yet against real Grok Build logs. `turn_completed` lines, one row per model in `usage.modelUsage` (the top-level usage under `summary.json`'s `current_model_id` when that map is missing). De-duplicated by `eventId` + model, also across sessions, since one event can be exported into several; a row without `eventId` by its full content within its file. `cachedReadTokens` and `cacheCreationTokens` are part of `inputTokens`; reasoning is part of `outputTokens`. Always the base rate: a turn sums several API requests, so its total cannot pick the long-context tier; a request of its own above 200K tokens is under-priced. A model id that is a file path is reduced to its file name. A turn cut off before it completes is never logged, so it is not counted. |
|
|
337
|
+
| GitHub Copilot CLI (experimental) | `~/.copilot/session-state/*/events.jsonl`, `$COPILOT_HOME/session-state` | Experimental: so far compared with ccusage only on a few sessions from one machine and on ccusage's test fixtures, not on regular use. `session.usage_record` events (one per model call). Older versions log only `session.shutdown`; its cumulative `modelMetrics` count as the growth since the previous shutdown, and only when no per-call record came in that interval. `inputTokens` includes cache reads and writes, so input counts uncached tokens only. Reasoning is part of `outputTokens`. A `-1m` or `-1m-internal` model suffix is dropped. Only the top-level `events.jsonl` of each session is read, not the OpenTelemetry export or `session-store.db`. |
|
|
338
|
+
| 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
|
+
|
|
340
|
+
**Pricing.** Claude Code, Codex, pi, Grok Build, GitHub Copilot CLI and Antigravity use LiteLLM
|
|
341
|
+
`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
|
|
340
342
|
Code and Codex try the exact model, then the `anthropic/` or `openai/` prefix, then without a date
|
|
341
343
|
suffix. pi tries the LiteLLM prefixes of the providers pi supports too (`openrouter/`, `fireworks_ai/`,
|
|
342
344
|
`groq/` and others). For an OpenRouter id such as `anthropic/claude-sonnet-4.5` it then tries
|
|
343
345
|
`claude-sonnet-4.5` and `claude-sonnet-4-5`. Grok Build tries the model and its `xai/` key, then
|
|
344
|
-
both without a trailing `-build`.
|
|
346
|
+
both without a trailing `-build`. Antigravity tries the model, the model without an effort or `-thinking`
|
|
347
|
+
suffix, Anthropic's spelling of a Claude name (`claude-sonnet-4-5` for `claude-4.5-sonnet`) and the
|
|
348
|
+
`-preview` name, each bare and with the `google/`, `gemini/`, `vertex_ai/` and `openrouter/google/`
|
|
349
|
+
prefixes (a Claude name also with `vercel_ai_gateway/anthropic/`, which still lists retired models).
|
|
350
|
+
Unknown models count with cost 0 and log a warning.
|
|
345
351
|
Long-context tiers
|
|
346
|
-
(`*_above_<N>k_tokens`) are applied per request;
|
|
352
|
+
(`*_above_<N>k_tokens`) are applied per request; a missing cache price is derived from the base
|
|
353
|
+
input price, also above a tier, as ccusage does. 1-hour cache writes use
|
|
347
354
|
`cache_creation_input_token_cost_above_1hr`. Cache savings are cache-read tokens times (input price
|
|
348
|
-
minus cache-read price).
|
|
355
|
+
minus cache-read price). Copilot also tries `github_copilot/<model>`, and swaps a dot between digits
|
|
356
|
+
for a dash in Claude model names (`claude-opus-4.6` is priced as `claude-opus-4-6`).
|
|
357
|
+
|
|
358
|
+
**Experimental sources.** A source whose counts match ccusage on test data but have not been checked
|
|
359
|
+
against real usage yet is marked `experimental` in `SOURCES`. The collector reads and sends it only
|
|
360
|
+
when `BIG_SPENDER_EXPERIMENTAL` (comma-separated provider ids, in the environment or the env file)
|
|
361
|
+
names it. Antigravity is the only source gated this way. Removing it from the list stops sending its rows on the
|
|
362
|
+
next run; adding it back recounts them without counting anything twice.
|
|
349
363
|
|
|
350
364
|
**Adding a provider.** Add an entry to `SOURCES` in `src/collector.mjs`, the provider id to
|
|
351
365
|
`PROVIDERS` in `src/schema.ts`, a row to the table above, and a test with a fixture log. The entry
|
package/dist/collector.mjs
CHANGED
|
@@ -18,14 +18,24 @@
|
|
|
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 (see templates/env.example).
|
|
21
|
+
// BIG_SPENDER_CURSOR_API_KEY and BIG_SPENDER_EXPERIMENTAL (see templates/env.example).
|
|
22
22
|
// The older USAGE_* names are still read when the new one is unset.
|
|
23
23
|
|
|
24
24
|
import { createHash } from 'node:crypto';
|
|
25
25
|
import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
|
|
26
|
-
import {
|
|
26
|
+
import {
|
|
27
|
+
mkdir,
|
|
28
|
+
open,
|
|
29
|
+
readdir,
|
|
30
|
+
readFile,
|
|
31
|
+
realpath,
|
|
32
|
+
rename,
|
|
33
|
+
rm,
|
|
34
|
+
stat,
|
|
35
|
+
writeFile
|
|
36
|
+
} from 'node:fs/promises';
|
|
27
37
|
import { homedir } from 'node:os';
|
|
28
|
-
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
38
|
+
import { basename, dirname, extname, join, resolve, sep } from 'node:path';
|
|
29
39
|
import { gzipSync } from 'node:zlib';
|
|
30
40
|
|
|
31
41
|
const SCHEMA_VERSION = 1;
|
|
@@ -120,11 +130,12 @@ async function acquireLock() {
|
|
|
120
130
|
/**
|
|
121
131
|
* @typedef {{ input: number, cacheRead: number, cacheWrite: number, output: number, savings: number }} Cost
|
|
122
132
|
* @typedef {{ input: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number, output: number, sessions: string[], cost?: Cost }} Bucket
|
|
123
|
-
* A JSONL file's read position. Readers may keep their own fields on it (Codex: model, sessionId, lastTotal; pi: forkCalls).
|
|
124
|
-
* @typedef {{ size: number, mtimeMs: number, offset: number, model?: string, sessionId?: string, lastTotal?: number, forkCalls?: string[] }} FileState
|
|
133
|
+
* A JSONL file's read position. Readers may keep their own fields on it (Codex: model, sessionId, lastTotal; pi: forkCalls; Copilot: models, callsSinceShutdown).
|
|
134
|
+
* @typedef {{ size: number, mtimeMs: number, offset: number, model?: string, sessionId?: string, lastTotal?: number, forkCalls?: string[], models?: Record<string, { input: number, cacheRead: number, cacheWrite: number, output: number, requests?: number }>, callsSinceShutdown?: boolean }} FileState
|
|
125
135
|
* A seen entry is the first timestamp, or for Claude [first timestamp, output tokens counted].
|
|
126
136
|
* A bare number on a Claude key means the counted output is unknown (state from an older version).
|
|
127
|
-
*
|
|
137
|
+
* Antigravity keeps a merged response under each of its ids: see agStoreGroup.
|
|
138
|
+
* @typedef {number | [number, number] | [number, string] | [number, number, string, ...(number | string)[]]} Seen
|
|
128
139
|
* One subscription usage window instance; see limitWindowSchema in src/schema.ts.
|
|
129
140
|
* @typedef {{ provider: string, window: string, resetsAt: string, peakPercent: number, hitAt?: string }} Limit
|
|
130
141
|
* @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
|
|
@@ -183,14 +194,16 @@ const shortHash = (s) => createHash('sha256').update(s).digest('base64url').slic
|
|
|
183
194
|
// Bucket key: hour start (ms) | provider | model | pricing tier (prompt-size threshold, 0 = base).
|
|
184
195
|
const bucketKey = (hourMs, provider, model, tier) => `${hourMs}|${provider}|${model}|${tier}`;
|
|
185
196
|
|
|
197
|
+
const BUCKET_COUNTS = ['input', 'cacheRead', 'cacheWrite5m', 'cacheWrite1h', 'output'];
|
|
198
|
+
const recordBucketKey = (r) =>
|
|
199
|
+
bucketKey(Math.floor(r.ts / HOUR_MS) * HOUR_MS, r.provider, r.model, r.tier);
|
|
200
|
+
|
|
186
201
|
/**
|
|
187
202
|
* @param {State} state
|
|
188
203
|
* @param {{ ts: number, provider: string, model: string, tier: number, session: string, input: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number, output: number }} r
|
|
189
204
|
*/
|
|
190
205
|
function addRecord(state, r) {
|
|
191
|
-
const
|
|
192
|
-
const key = bucketKey(hourMs, r.provider, r.model, r.tier);
|
|
193
|
-
const b = (state.buckets[key] ??= {
|
|
206
|
+
const b = (state.buckets[recordBucketKey(r)] ??= {
|
|
194
207
|
input: 0,
|
|
195
208
|
cacheRead: 0,
|
|
196
209
|
cacheWrite5m: 0,
|
|
@@ -198,14 +211,24 @@ function addRecord(state, r) {
|
|
|
198
211
|
output: 0,
|
|
199
212
|
sessions: []
|
|
200
213
|
});
|
|
201
|
-
b
|
|
202
|
-
b.cacheRead += r.cacheRead;
|
|
203
|
-
b.cacheWrite5m += r.cacheWrite5m;
|
|
204
|
-
b.cacheWrite1h += r.cacheWrite1h;
|
|
205
|
-
b.output += r.output;
|
|
214
|
+
for (const k of BUCKET_COUNTS) b[k] += r[k];
|
|
206
215
|
if (!b.sessions.includes(r.session)) b.sessions.push(r.session);
|
|
207
216
|
}
|
|
208
217
|
|
|
218
|
+
/**
|
|
219
|
+
* Takes back what addRecord added for `r`. Its session stays listed, since a bucket does not
|
|
220
|
+
* know which of its records named it, unless nothing is left of the bucket. An emptied bucket
|
|
221
|
+
* stays as a zero row until it ages out: the server keeps a day and model that a snapshot stops
|
|
222
|
+
* reporting, so only a zero row takes back what an earlier snapshot sent.
|
|
223
|
+
* @type {typeof addRecord}
|
|
224
|
+
*/
|
|
225
|
+
function removeRecord(state, r) {
|
|
226
|
+
const b = state.buckets[recordBucketKey(r)];
|
|
227
|
+
if (!b) return;
|
|
228
|
+
for (const k of BUCKET_COUNTS) b[k] = Math.max(0, b[k] - r[k]);
|
|
229
|
+
if (BUCKET_COUNTS.every((k) => b[k] === 0)) b.sessions = [];
|
|
230
|
+
}
|
|
231
|
+
|
|
209
232
|
/** @param {State} state @param {number} cutoffMs */
|
|
210
233
|
function pruneState(state, cutoffMs) {
|
|
211
234
|
for (const key of Object.keys(state.buckets)) {
|
|
@@ -392,8 +415,10 @@ function costOf(entry, tier, t) {
|
|
|
392
415
|
if (!entry) return { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, savings: 0 };
|
|
393
416
|
const inP = price(entry, 'input_cost_per_token', tier) ?? 0;
|
|
394
417
|
const outP = price(entry, 'output_cost_per_token', tier) ?? 0;
|
|
395
|
-
|
|
396
|
-
const
|
|
418
|
+
// A missing cache rate derives from the base input rate, also above a tier, as in ccusage.
|
|
419
|
+
const baseInP = price(entry, 'input_cost_per_token', 0) ?? 0;
|
|
420
|
+
const readP = price(entry, 'cache_read_input_token_cost', tier) ?? baseInP * 0.1;
|
|
421
|
+
const write5mP = price(entry, 'cache_creation_input_token_cost', tier) ?? baseInP * 1.25;
|
|
397
422
|
const write1hP = tier
|
|
398
423
|
? (entry[`cache_creation_input_token_cost_above_1hr_above_${tier / 1000}k_tokens`] ??
|
|
399
424
|
entry.cache_creation_input_token_cost_above_1hr ??
|
|
@@ -819,20 +844,113 @@ function grokLineHandler(state, cutoffMs, path) {
|
|
|
819
844
|
};
|
|
820
845
|
}
|
|
821
846
|
|
|
822
|
-
|
|
847
|
+
// Copilot CLI versions without session.usage_record log usage only in session.shutdown. Like
|
|
848
|
+
// ccusage, a shutdown counts as cumulative per model since the session began, which older
|
|
849
|
+
// versions may not hold to (issue #11). inputTokens includes cache reads and writes.
|
|
850
|
+
// reasoningTokens is part of outputTokens.
|
|
851
|
+
// A bring-your-own-key model can be a cloud resource id or gateway URL, which may carry an
|
|
852
|
+
// account id, so only its last path segment leaves the machine.
|
|
853
|
+
const copilotModelName = (raw) => {
|
|
854
|
+
const name = String(raw ?? '')
|
|
855
|
+
.trim()
|
|
856
|
+
.split(/[?#]/)[0]
|
|
857
|
+
.split('/')
|
|
858
|
+
.pop();
|
|
859
|
+
return (/^arn:/i.test(name) ? name.split(':').pop() : name)
|
|
860
|
+
.replace(/-1m(-internal)?$/, '')
|
|
861
|
+
.replace(/[^A-Za-z0-9._:@-]/g, '-')
|
|
862
|
+
.slice(0, 100);
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
function copilotLineHandler(state, file, resolvePrice, cutoffMs, sessionDir) {
|
|
866
|
+
const session = shortHash(`copilot:${sessionDir}`);
|
|
867
|
+
const count = (u, requests) => ({
|
|
868
|
+
input: num(u?.inputTokens),
|
|
869
|
+
cacheRead: num(u?.cacheReadTokens),
|
|
870
|
+
cacheWrite: num(u?.cacheWriteTokens),
|
|
871
|
+
output: num(u?.outputTokens),
|
|
872
|
+
requests: num(requests)
|
|
873
|
+
});
|
|
874
|
+
const add = (ts, model, t, tier) =>
|
|
875
|
+
addRecord(state, {
|
|
876
|
+
ts,
|
|
877
|
+
provider: 'copilot',
|
|
878
|
+
model,
|
|
879
|
+
tier,
|
|
880
|
+
session,
|
|
881
|
+
input: Math.max(0, t.input - t.cacheRead - t.cacheWrite),
|
|
882
|
+
cacheRead: t.cacheRead,
|
|
883
|
+
cacheWrite5m: t.cacheWrite,
|
|
884
|
+
cacheWrite1h: 0,
|
|
885
|
+
output: t.output
|
|
886
|
+
});
|
|
887
|
+
return (line) => {
|
|
888
|
+
const isCall = line.includes('"session.usage_record"');
|
|
889
|
+
if (!isCall && !line.includes('"session.shutdown"')) return;
|
|
890
|
+
const o = parseJson(line);
|
|
891
|
+
if (!o || o.type !== (isCall ? 'session.usage_record' : 'session.shutdown')) return;
|
|
892
|
+
const ts = Date.parse(o.timestamp);
|
|
893
|
+
if (!Number.isFinite(ts)) return;
|
|
894
|
+
const id = o.id ?? o.timestamp;
|
|
895
|
+
if (isCall) {
|
|
896
|
+
file.callsSinceShutdown = true;
|
|
897
|
+
const model = copilotModelName(o.data?.usage?.model);
|
|
898
|
+
const key = `p:${shortHash(`${sessionDir}:${id}`)}`;
|
|
899
|
+
if (!model || ts < cutoffMs || state.seen[key] !== undefined) return;
|
|
900
|
+
state.seen[key] = ts;
|
|
901
|
+
const t = count(o.data.usage);
|
|
902
|
+
add(ts, model, t, tierFor(resolvePrice('copilot', model), t.input));
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
// Names that normalise to one model (`gpt-5.2` and `gpt-5.2-1m`) are added up before the
|
|
906
|
+
// previous shutdown is subtracted.
|
|
907
|
+
/** @type {Record<string, ReturnType<typeof count>>} */
|
|
908
|
+
const totals = {};
|
|
909
|
+
for (const [rawModel, metrics] of Object.entries(o.data?.modelMetrics ?? {})) {
|
|
910
|
+
const model = copilotModelName(rawModel);
|
|
911
|
+
if (!metrics?.usage || !model) continue;
|
|
912
|
+
const t = count(metrics.usage, metrics.requests?.count);
|
|
913
|
+
const sum = (totals[model] ??= count());
|
|
914
|
+
for (const k of Object.keys(t)) sum[k] += t[k];
|
|
915
|
+
}
|
|
916
|
+
file.models ??= {};
|
|
917
|
+
for (const [model, now] of Object.entries(totals)) {
|
|
918
|
+
const was = file.models[model] ?? {};
|
|
919
|
+
file.models[model] = now;
|
|
920
|
+
const delta = count();
|
|
921
|
+
for (const k of Object.keys(delta)) delta[k] = Math.max(0, now[k] - num(was[k]));
|
|
922
|
+
const key = `p:${shortHash(`${sessionDir}:${id}:${model}`)}`;
|
|
923
|
+
if (
|
|
924
|
+
file.callsSinceShutdown ||
|
|
925
|
+
ts < cutoffMs ||
|
|
926
|
+
!(delta.input || delta.cacheRead || delta.cacheWrite || delta.output) ||
|
|
927
|
+
state.seen[key] !== undefined
|
|
928
|
+
) {
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
931
|
+
state.seen[key] = ts;
|
|
932
|
+
// An interval of one request is one prompt, so only then can it reach a long-context tier.
|
|
933
|
+
const tier = delta.requests === 1 ? tierFor(resolvePrice('copilot', model), delta.input) : 0;
|
|
934
|
+
add(ts, model, delta, tier);
|
|
935
|
+
}
|
|
936
|
+
file.callsSinceShutdown = false;
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
const allJsonl = (dir) => walk(dir, (name) => name.endsWith('.jsonl'));
|
|
823
941
|
|
|
824
942
|
/**
|
|
825
|
-
* A reader for JSONL logs that only grow:
|
|
826
|
-
*
|
|
943
|
+
* A reader for JSONL logs that only grow: reads the files `files` lists under each path (every
|
|
944
|
+
* `*.jsonl` below it by default) and parses only the bytes added since the last run. `lines`
|
|
827
945
|
* builds the line handler for one file.
|
|
828
946
|
* @param {(ctx: ReadContext, file: FileState, path: string) => (line: string) => void} lines
|
|
829
|
-
* @param {(
|
|
947
|
+
* @param {(dir: string) => AsyncIterable<string>} [files]
|
|
830
948
|
*/
|
|
831
|
-
const jsonlReader = (lines,
|
|
949
|
+
const jsonlReader = (lines, files) => async (paths, ctx, provider) => {
|
|
832
950
|
const { state } = ctx;
|
|
833
951
|
for (const dir of paths) {
|
|
834
952
|
if (!existsSync(dir)) continue;
|
|
835
|
-
for await (const path of
|
|
953
|
+
for await (const path of (files ?? allJsonl)(dir)) {
|
|
836
954
|
if (ctx.seenPaths.has(path)) continue;
|
|
837
955
|
ctx.seenPaths.add(path);
|
|
838
956
|
let st;
|
|
@@ -884,15 +1002,701 @@ async function openSqlite(path) {
|
|
|
884
1002
|
return mod && new mod.DatabaseSync(path, { readOnly: true });
|
|
885
1003
|
}
|
|
886
1004
|
|
|
1005
|
+
/** Copilot keeps user files in other session subfolders, so only `<session>/events.jsonl` counts. */
|
|
1006
|
+
async function* sessionEvents(dir) {
|
|
1007
|
+
let entries;
|
|
1008
|
+
try {
|
|
1009
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
1010
|
+
} catch {
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
for (const e of entries) {
|
|
1014
|
+
const p = join(dir, e.name, 'events.jsonl');
|
|
1015
|
+
if (e.isDirectory() && existsSync(p)) yield p;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
887
1019
|
const fromEnv = (name, ...rest) => (process.env[name] ? [join(process.env[name], ...rest)] : []);
|
|
888
1020
|
|
|
1021
|
+
// One SQLite database per conversation; its blobs are protobuf. `gen_metadata` rows (one per model
|
|
1022
|
+
// call) and `steps` rows each carry a usage message plus the usage of earlier attempts. The same
|
|
1023
|
+
// response is written to several rows and to several databases, sometimes with partial counts, so
|
|
1024
|
+
// usage messages that share a response, provider or message id merge and keep the largest counts.
|
|
1025
|
+
// This follows ccusage's antigravity adapter (v20.0.51) read for read: the order of reads decides
|
|
1026
|
+
// which copy's timestamp and model win, and the numbers only match when it is the same.
|
|
1027
|
+
|
|
1028
|
+
const ANTIGRAVITY_ROOTS = [
|
|
1029
|
+
'.gemini/antigravity',
|
|
1030
|
+
'.gemini/antigravity-cli',
|
|
1031
|
+
'.gemini/antigravity-ide',
|
|
1032
|
+
'.gemini/antigravity-backup',
|
|
1033
|
+
'.gemini/antigravity-acp',
|
|
1034
|
+
'.config/antigravity'
|
|
1035
|
+
];
|
|
1036
|
+
const ANTIGRAVITY_DEFAULT_MODEL = 'gemini-internal-model';
|
|
1037
|
+
|
|
1038
|
+
const isDir = (path) => {
|
|
1039
|
+
try {
|
|
1040
|
+
return statSync(path).isDirectory();
|
|
1041
|
+
} catch {
|
|
1042
|
+
return false;
|
|
1043
|
+
}
|
|
1044
|
+
};
|
|
1045
|
+
|
|
1046
|
+
const antigravityEnvDirs = () =>
|
|
1047
|
+
(process.env.ANTIGRAVITY_DATA_DIR ?? '')
|
|
1048
|
+
.split(',')
|
|
1049
|
+
.map((root) => root.trim())
|
|
1050
|
+
.filter(Boolean)
|
|
1051
|
+
.map((root) => (isDir(join(root, 'conversations')) ? join(root, 'conversations') : root));
|
|
1052
|
+
|
|
1053
|
+
function byPathComponents(a, b) {
|
|
1054
|
+
const x = a.split(sep);
|
|
1055
|
+
const y = b.split(sep);
|
|
1056
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
1057
|
+
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
|
1058
|
+
}
|
|
1059
|
+
return x.length - y.length;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
/** @returns {Promise<{ path: string, real: string }[]>} */
|
|
1063
|
+
async function antigravityDatabases(dirs) {
|
|
1064
|
+
const byRealPath = new Map();
|
|
1065
|
+
for (const dir of dirs) {
|
|
1066
|
+
for await (const path of walk(dir, (name) => name.endsWith('.db'))) {
|
|
1067
|
+
const real = await realpath(path).catch(() => path);
|
|
1068
|
+
if (!byRealPath.has(real)) byRealPath.set(real, { path, real });
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
return [...byRealPath.values()].sort((a, b) => byPathComponents(a.path, b.path));
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function pbVarint(buf, pos) {
|
|
1075
|
+
let value = 0;
|
|
1076
|
+
for (let i = 0; i < 10; i++) {
|
|
1077
|
+
if (pos.i >= buf.length) throw new Error('truncated protobuf varint');
|
|
1078
|
+
const byte = buf[pos.i++];
|
|
1079
|
+
const payload = byte & 0x7f;
|
|
1080
|
+
if (i === 9 && payload > 1) break;
|
|
1081
|
+
value += payload * 2 ** (7 * i);
|
|
1082
|
+
if (!(byte & 0x80)) return value;
|
|
1083
|
+
}
|
|
1084
|
+
throw new Error('protobuf varint overflow');
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/** @returns {{ number: number, varint?: number, bytes?: Uint8Array }[]} */
|
|
1088
|
+
function pbDecode(buf) {
|
|
1089
|
+
const fields = [];
|
|
1090
|
+
const pos = { i: 0 };
|
|
1091
|
+
while (pos.i < buf.length) {
|
|
1092
|
+
const tag = pbVarint(buf, pos);
|
|
1093
|
+
const number = Math.floor(tag / 8);
|
|
1094
|
+
if (number === 0) throw new Error('protobuf field number is zero');
|
|
1095
|
+
const wire = tag % 8;
|
|
1096
|
+
if (wire === 0) fields.push({ number, varint: pbVarint(buf, pos) });
|
|
1097
|
+
else if (wire === 1 || wire === 5 || wire === 2) {
|
|
1098
|
+
const length = wire === 1 ? 8 : wire === 5 ? 4 : pbVarint(buf, pos);
|
|
1099
|
+
if (buf.length - pos.i < length) throw new Error('truncated protobuf value');
|
|
1100
|
+
if (wire === 2) fields.push({ number, bytes: buf.subarray(pos.i, pos.i + length) });
|
|
1101
|
+
else fields.push({ number });
|
|
1102
|
+
pos.i += length;
|
|
1103
|
+
} else throw new Error('unsupported protobuf wire type');
|
|
1104
|
+
}
|
|
1105
|
+
return fields;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
const pbLastVarint = (fields, n) =>
|
|
1109
|
+
fields.findLast((f) => f.number === n && f.varint !== undefined)?.varint;
|
|
1110
|
+
const pbFirstBytes = (fields, n) => fields.find((f) => f.number === n && f.bytes)?.bytes;
|
|
1111
|
+
const pbStrictUtf8 = new TextDecoder('utf-8', { fatal: true });
|
|
1112
|
+
function pbLastText(fields, n) {
|
|
1113
|
+
const bytes = fields.findLast((f) => f.number === n && f.bytes)?.bytes;
|
|
1114
|
+
if (!bytes) return undefined;
|
|
1115
|
+
try {
|
|
1116
|
+
const text = pbStrictUtf8.decode(bytes);
|
|
1117
|
+
return text.trim() ? text : undefined;
|
|
1118
|
+
} catch {
|
|
1119
|
+
return undefined;
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
const AG_COUNTS = ['input', 'totalOutput', 'cacheWrite', 'cacheRead', 'reasoning', 'visible'];
|
|
1124
|
+
|
|
1125
|
+
function agUsage(buf) {
|
|
1126
|
+
const f = pbDecode(buf);
|
|
1127
|
+
return {
|
|
1128
|
+
modelId: pbLastVarint(f, 1) || undefined,
|
|
1129
|
+
input: pbLastVarint(f, 2) ?? 0,
|
|
1130
|
+
totalOutput: pbLastVarint(f, 3) ?? 0,
|
|
1131
|
+
cacheWrite: pbLastVarint(f, 4) ?? 0,
|
|
1132
|
+
cacheRead: pbLastVarint(f, 5) ?? 0,
|
|
1133
|
+
reasoning: pbLastVarint(f, 9) ?? 0,
|
|
1134
|
+
visible: pbLastVarint(f, 10) ?? 0,
|
|
1135
|
+
messageId: pbLastText(f, 7),
|
|
1136
|
+
responseId: pbLastText(f, 11),
|
|
1137
|
+
providerMessageId: pbLastText(f, 12)
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
const agIdentities = (u) =>
|
|
1142
|
+
[
|
|
1143
|
+
u.responseId && `response:${u.responseId}`,
|
|
1144
|
+
u.providerMessageId && `provider:${u.providerMessageId}`,
|
|
1145
|
+
u.messageId && `message:${u.messageId}`
|
|
1146
|
+
].filter(Boolean);
|
|
1147
|
+
|
|
1148
|
+
/**
|
|
1149
|
+
* The usage of a row's earlier attempts. The list also repeats the attempt already reported as
|
|
1150
|
+
* the row's primary usage, so one entry equal to the primary is dropped.
|
|
1151
|
+
*/
|
|
1152
|
+
function agRetries(fields, n, primary) {
|
|
1153
|
+
const retries = fields
|
|
1154
|
+
.filter((f) => f.number === n && f.bytes)
|
|
1155
|
+
.map((f) => pbFirstBytes(pbDecode(f.bytes), 2))
|
|
1156
|
+
.filter(Boolean)
|
|
1157
|
+
.map(agUsage);
|
|
1158
|
+
if (!primary) return retries;
|
|
1159
|
+
const keys = agIdentities(primary);
|
|
1160
|
+
const mirror = retries.findIndex(
|
|
1161
|
+
(r) =>
|
|
1162
|
+
r.modelId === primary.modelId &&
|
|
1163
|
+
AG_COUNTS.every((k) => r[k] === primary[k]) &&
|
|
1164
|
+
agIdentities(r).every((id) => keys.includes(id))
|
|
1165
|
+
);
|
|
1166
|
+
if (mirror >= 0) retries.splice(mirror, 1);
|
|
1167
|
+
return retries;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
function agTimestamp(buf) {
|
|
1171
|
+
if (!buf) return undefined;
|
|
1172
|
+
const f = pbDecode(buf);
|
|
1173
|
+
const seconds = pbLastVarint(f, 1);
|
|
1174
|
+
if (!seconds || seconds > Number.MAX_SAFE_INTEGER / 1000) return undefined;
|
|
1175
|
+
const nanos = Math.min(pbLastVarint(f, 2) ?? 0, 999_999_999);
|
|
1176
|
+
const ms = seconds * 1000 + Math.floor(nanos / 1e6);
|
|
1177
|
+
// An implausible time falls through to the next source, so it cannot put a row in year 58854.
|
|
1178
|
+
return plausibleTime(ms) ? ms : undefined;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
function agStepIndices(root) {
|
|
1182
|
+
const out = [];
|
|
1183
|
+
for (const f of root) {
|
|
1184
|
+
if (f.number !== 2) continue;
|
|
1185
|
+
if (f.varint !== undefined) {
|
|
1186
|
+
if (f.varint <= Number.MAX_SAFE_INTEGER) out.push(f.varint);
|
|
1187
|
+
} else if (f.bytes) {
|
|
1188
|
+
const pos = { i: 0 };
|
|
1189
|
+
while (pos.i < f.bytes.length) {
|
|
1190
|
+
try {
|
|
1191
|
+
out.push(pbVarint(f.bytes, pos));
|
|
1192
|
+
} catch {
|
|
1193
|
+
break;
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
return out;
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
function agGeneration(buf) {
|
|
1202
|
+
const root = pbDecode(buf);
|
|
1203
|
+
const chatBytes = pbFirstBytes(root, 1);
|
|
1204
|
+
if (!chatBytes) throw new Error('missing chat model field 1');
|
|
1205
|
+
const chat = pbDecode(chatBytes);
|
|
1206
|
+
const usageBytes = pbFirstBytes(chat, 4);
|
|
1207
|
+
const usage = usageBytes && agUsage(usageBytes);
|
|
1208
|
+
const info = pbFirstBytes(chat, 9);
|
|
1209
|
+
return {
|
|
1210
|
+
model: pbLastText(chat, 19) ?? pbLastText(chat, 21),
|
|
1211
|
+
modelId: pbLastVarint(chat, 3) || undefined,
|
|
1212
|
+
usage,
|
|
1213
|
+
retries: agRetries(chat, 17, usage),
|
|
1214
|
+
ts: agTimestamp(info && pbFirstBytes(pbDecode(info), 4)),
|
|
1215
|
+
steps: agStepIndices(root)
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
function agStep(buf) {
|
|
1220
|
+
const f = pbDecode(buf);
|
|
1221
|
+
const usageBytes = pbFirstBytes(f, 9);
|
|
1222
|
+
const usage = usageBytes && agUsage(usageBytes);
|
|
1223
|
+
const infoBytes = pbFirstBytes(f, 24);
|
|
1224
|
+
const info = infoBytes ? pbDecode(infoBytes) : [];
|
|
1225
|
+
return {
|
|
1226
|
+
model: pbLastText(info, 12) ?? pbLastText(info, 8),
|
|
1227
|
+
modelId: pbLastVarint(info, 1) || undefined,
|
|
1228
|
+
usage,
|
|
1229
|
+
retries: agRetries(f, 28, usage),
|
|
1230
|
+
ts: agTimestamp(pbFirstBytes(f, 8) ?? pbFirstBytes(f, 1))
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
const AG_ID_MODELS = {
|
|
1235
|
+
246: 'gemini-2.5-pro',
|
|
1236
|
+
312: 'gemini-2.5-flash',
|
|
1237
|
+
313: 'gemini-2.5-flash-thinking',
|
|
1238
|
+
329: 'gemini-2.5-flash-thinking',
|
|
1239
|
+
330: 'gemini-2.5-flash-lite',
|
|
1240
|
+
281: 'claude-4-sonnet',
|
|
1241
|
+
282: 'claude-4-sonnet',
|
|
1242
|
+
290: 'claude-4-opus',
|
|
1243
|
+
291: 'claude-4-opus',
|
|
1244
|
+
333: 'claude-4.5-sonnet',
|
|
1245
|
+
334: 'claude-4.5-sonnet',
|
|
1246
|
+
340: 'claude-4.5-haiku',
|
|
1247
|
+
341: 'claude-4.5-haiku',
|
|
1248
|
+
342: 'model_openai_gpt_oss_120b_medium',
|
|
1249
|
+
1318: 'gemini-3.8-flash-high',
|
|
1250
|
+
1319: 'gemini-3.8-flash-medium',
|
|
1251
|
+
1320: 'gemini-3.8-flash-low',
|
|
1252
|
+
1298: 'gemini-3.7-flash-high',
|
|
1253
|
+
1299: 'gemini-3.7-flash-medium',
|
|
1254
|
+
1300: 'gemini-3.7-flash-low',
|
|
1255
|
+
1071: 'gemini-3.6-flash-high',
|
|
1256
|
+
1072: 'gemini-3.6-flash-medium',
|
|
1257
|
+
1073: 'gemini-3.6-flash-low',
|
|
1258
|
+
1417: 'gemini-4-argon',
|
|
1259
|
+
1418: 'gemini-4-argon',
|
|
1260
|
+
1419: 'gemini-4-argon',
|
|
1261
|
+
1402: 'claude-opus-5-5',
|
|
1262
|
+
1050: 'gemini-3.1-flash-lite'
|
|
1263
|
+
};
|
|
1264
|
+
const AG_PLACEHOLDER = 'model_placeholder_m';
|
|
1265
|
+
const AG_UNRESOLVED_ID = 'antigravity-model-';
|
|
1266
|
+
const AG_EFFORT_NAME = /^gemini (3\.[678]) flash \((high|medium|low)\)$/;
|
|
1267
|
+
const AG_NAMES = {
|
|
1268
|
+
'gemini 3.8 flash': 'gemini-3.8-flash',
|
|
1269
|
+
'gemini 3.8 flash thinking': 'gemini-3.8-flash',
|
|
1270
|
+
'gemini 3.7 flash': 'gemini-3.7-flash',
|
|
1271
|
+
'gemini 3.7 flash thinking': 'gemini-3.7-flash',
|
|
1272
|
+
'gemini 3.7 pro': 'gemini-3.7-pro',
|
|
1273
|
+
'gemini 3.7 pro thinking': 'gemini-3.7-pro',
|
|
1274
|
+
'gemini 3.6 flash': 'gemini-3.6-flash',
|
|
1275
|
+
'gemini 3 flash': 'gemini-3.6-flash',
|
|
1276
|
+
'gemini 3.6 pro': 'gemini-3.6-pro',
|
|
1277
|
+
'gemini 3 pro': 'gemini-3-pro',
|
|
1278
|
+
'gemini 3 pro thinking': 'gemini-3-pro',
|
|
1279
|
+
'gemini 2.5 flash': 'gemini-2.5-flash',
|
|
1280
|
+
'gemini 2.5 pro': 'gemini-2.5-pro',
|
|
1281
|
+
'gemini 2.0 flash': 'gemini-2.0-flash',
|
|
1282
|
+
'gemini 2 flash': 'gemini-2.0-flash',
|
|
1283
|
+
'gemini 2.0 pro': 'gemini-2.0-pro',
|
|
1284
|
+
'gemini 1.5 flash': 'gemini-1.5-flash',
|
|
1285
|
+
'gemini 1.5 pro': 'gemini-1.5-pro',
|
|
1286
|
+
model_placeholder_m318: 'gemini-3.8-flash-high',
|
|
1287
|
+
model_placeholder_m319: 'gemini-3.8-flash-medium',
|
|
1288
|
+
model_placeholder_m320: 'gemini-3.8-flash-low',
|
|
1289
|
+
model_placeholder_m298: 'gemini-3.7-flash-high',
|
|
1290
|
+
model_placeholder_m299: 'gemini-3.7-flash-medium',
|
|
1291
|
+
model_placeholder_m300: 'gemini-3.7-flash-low',
|
|
1292
|
+
model_placeholder_m71: 'gemini-3.6-flash-high',
|
|
1293
|
+
model_placeholder_m72: 'gemini-3.6-flash-medium',
|
|
1294
|
+
model_placeholder_m73: 'gemini-3.6-flash-low',
|
|
1295
|
+
model_placeholder_m417: 'gemini-4-argon',
|
|
1296
|
+
model_placeholder_m418: 'gemini-4-argon',
|
|
1297
|
+
model_placeholder_m419: 'gemini-4-argon',
|
|
1298
|
+
model_placeholder_m402: 'claude-opus-5-5',
|
|
1299
|
+
model_placeholder_m50: 'gemini-3.1-flash-lite',
|
|
1300
|
+
model_placeholder_m26: 'claude-opus-4-6',
|
|
1301
|
+
model_placeholder_m35: 'claude-sonnet-4-6',
|
|
1302
|
+
model_placeholder_m36: 'gemini-3.1-pro',
|
|
1303
|
+
model_placeholder_m37: 'gemini-3.1-pro',
|
|
1304
|
+
model_placeholder_m16: 'gemini-3.1-pro',
|
|
1305
|
+
model_placeholder_m18: 'gemini-3-flash-preview',
|
|
1306
|
+
model_placeholder_m84: 'gemini-3-flash-preview',
|
|
1307
|
+
model_placeholder_m47: 'gemini-3-flash-preview',
|
|
1308
|
+
model_placeholder_m132: 'gemini-3.5-flash-high',
|
|
1309
|
+
model_placeholder_m133: 'gemini-3.5-flash-high',
|
|
1310
|
+
model_placeholder_m187: 'gemini-3.5-flash-extra-low',
|
|
1311
|
+
model_placeholder_m20: 'gemini-3.5-flash-medium',
|
|
1312
|
+
model_openai_gpt_oss_120b_medium: 'gpt-oss-120b-medium',
|
|
1313
|
+
'gemini-pro-default': 'gemini-3.1-pro',
|
|
1314
|
+
'gemini-pro-agent': 'gemini-3.1-pro',
|
|
1315
|
+
'gemini-3-flash-agent': 'gemini-3.5-flash-high',
|
|
1316
|
+
'gemini-3-flash-agent-a': 'gemini-3.5-flash-high',
|
|
1317
|
+
'gemini-3-flash-agent-b': 'gemini-3.5-flash-high',
|
|
1318
|
+
'gemini-3-flash-a': 'gemini-3.5-flash-high',
|
|
1319
|
+
'gemini-3-flash-b': 'gemini-3.5-flash-high',
|
|
1320
|
+
'gemini-3-flash-c': 'gemini-3-flash-preview',
|
|
1321
|
+
'gemini-3-flash': 'gemini-3-flash-preview',
|
|
1322
|
+
'gemini-3.5-flash-low': 'gemini-3.5-flash-medium',
|
|
1323
|
+
'gemini-3.1-pro-high': 'gemini-3.1-pro',
|
|
1324
|
+
'gemini-3.1-pro-low': 'gemini-3.1-pro',
|
|
1325
|
+
'gemini-3-pro-high': 'gemini-3-pro',
|
|
1326
|
+
'gemini-3-pro-low': 'gemini-3-pro',
|
|
1327
|
+
'claude 3.7 sonnet': 'claude-3-7-sonnet',
|
|
1328
|
+
'claude 3.7 sonnet thinking': 'claude-3-7-sonnet',
|
|
1329
|
+
'claude 3.5 sonnet': 'claude-3-5-sonnet',
|
|
1330
|
+
'claude 3.5 haiku': 'claude-3-5-haiku',
|
|
1331
|
+
'claude 3 opus': 'claude-3-opus'
|
|
1332
|
+
};
|
|
1333
|
+
|
|
1334
|
+
function agModelName(raw) {
|
|
1335
|
+
const trimmed = raw?.trim();
|
|
1336
|
+
if (!trimmed) return undefined;
|
|
1337
|
+
const lower = trimmed.toLowerCase();
|
|
1338
|
+
const effort = AG_EFFORT_NAME.exec(lower);
|
|
1339
|
+
if (effort) return `gemini-${effort[1]}-flash-${effort[2]}`;
|
|
1340
|
+
const paren = lower.indexOf('(');
|
|
1341
|
+
const base = paren >= 0 ? lower.slice(0, paren).trim() : lower;
|
|
1342
|
+
if (Object.hasOwn(AG_NAMES, base)) return AG_NAMES[base];
|
|
1343
|
+
const dashed = base.replaceAll(' ', '-');
|
|
1344
|
+
return /^(gemini|claude|gpt)-/.test(dashed) ? dashed : trimmed;
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
const agModelFromId = (id) =>
|
|
1348
|
+
id
|
|
1349
|
+
? agModelName(
|
|
1350
|
+
AG_ID_MODELS[id] ??
|
|
1351
|
+
(id >= 1000 ? `${AG_PLACEHOLDER}${id - 1000}` : `${AG_UNRESOLVED_ID}${id}`)
|
|
1352
|
+
)
|
|
1353
|
+
: undefined;
|
|
1354
|
+
|
|
1355
|
+
const AG_MODEL = { DEFAULT: 0, PLACEHOLDER: 1, RESOLVED: 2 };
|
|
1356
|
+
const agResolution = (model) =>
|
|
1357
|
+
model === ANTIGRAVITY_DEFAULT_MODEL
|
|
1358
|
+
? AG_MODEL.DEFAULT
|
|
1359
|
+
: model.startsWith(AG_PLACEHOLDER) || model.startsWith(AG_UNRESOLVED_ID)
|
|
1360
|
+
? AG_MODEL.PLACEHOLDER
|
|
1361
|
+
: AG_MODEL.RESOLVED;
|
|
1362
|
+
const agResolved = (model) =>
|
|
1363
|
+
model !== undefined && agResolution(model) === AG_MODEL.RESOLVED ? model : undefined;
|
|
1364
|
+
|
|
1365
|
+
// Where an event's timestamp came from; a merge keeps the better source.
|
|
1366
|
+
const AG_TS = { FILE_MTIME: 0, TRAJECTORY: 1, OWN_ROW: 3 };
|
|
1367
|
+
|
|
1368
|
+
/**
|
|
1369
|
+
* One response, or after a merge every copy of it. `mtimeOf` names the database whose modification
|
|
1370
|
+
* time is the timestamp (rank FILE_MTIME), and is empty for any other rank.
|
|
1371
|
+
* @typedef {{ ts: number, rank: number, mtimeOf: string, session: string, model: string, input: number, output: number, cacheWrite: number, cacheRead: number, reasoning: number, totalOutput: number, identities: string[], tier?: number }} AgEvent
|
|
1372
|
+
*/
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* @param {AgEvent[]} events
|
|
1376
|
+
* @param {Map<string, [number, number]>} idTimestamps
|
|
1377
|
+
*/
|
|
1378
|
+
function agAppendEvent(events, idTimestamps, usage, row) {
|
|
1379
|
+
if (!AG_COUNTS.some((k) => usage[k] > 0)) return;
|
|
1380
|
+
let identities = agIdentities(usage);
|
|
1381
|
+
if (!identities.length) identities = row.fallbackIdentities;
|
|
1382
|
+
const [ts, rank] =
|
|
1383
|
+
row.ts !== undefined
|
|
1384
|
+
? [row.ts, AG_TS.OWN_ROW]
|
|
1385
|
+
: (identities.map((id) => idTimestamps.get(id)).find(Boolean) ??
|
|
1386
|
+
(row.trajectoryTs !== undefined
|
|
1387
|
+
? [row.trajectoryTs, AG_TS.TRAJECTORY]
|
|
1388
|
+
: [row.fallbackTs, AG_TS.FILE_MTIME]));
|
|
1389
|
+
const totalOutput = Math.max(usage.totalOutput, usage.visible + usage.reasoning);
|
|
1390
|
+
const output = Math.max(usage.visible, totalOutput - usage.reasoning);
|
|
1391
|
+
const fromId = agModelFromId(usage.modelId);
|
|
1392
|
+
const rowModel = agModelName(row.model);
|
|
1393
|
+
const model =
|
|
1394
|
+
agResolved(fromId) ??
|
|
1395
|
+
(row.modelId === usage.modelId ? agResolved(rowModel) : undefined) ??
|
|
1396
|
+
fromId ??
|
|
1397
|
+
rowModel ??
|
|
1398
|
+
ANTIGRAVITY_DEFAULT_MODEL;
|
|
1399
|
+
for (const id of identities) {
|
|
1400
|
+
const old = idTimestamps.get(id);
|
|
1401
|
+
if (!old || rank > old[1] || (rank === old[1] && ts < old[0])) idTimestamps.set(id, [ts, rank]);
|
|
1402
|
+
}
|
|
1403
|
+
events.push({
|
|
1404
|
+
ts,
|
|
1405
|
+
rank,
|
|
1406
|
+
mtimeOf: '',
|
|
1407
|
+
session: row.session,
|
|
1408
|
+
model,
|
|
1409
|
+
input: usage.input,
|
|
1410
|
+
output,
|
|
1411
|
+
cacheWrite: usage.cacheWrite,
|
|
1412
|
+
cacheRead: usage.cacheRead,
|
|
1413
|
+
reasoning: Math.max(usage.reasoning, totalOutput - output),
|
|
1414
|
+
totalOutput,
|
|
1415
|
+
identities: [...identities]
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
/** @returns {AgEvent[]} */
|
|
1420
|
+
function agDatabaseEvents(db, path, fallbackTs) {
|
|
1421
|
+
const session = basename(path, extname(path));
|
|
1422
|
+
db.exec('BEGIN');
|
|
1423
|
+
if (db.prepare('PRAGMA page_count').get().page_count === 0) return [];
|
|
1424
|
+
const hasTable = (name) =>
|
|
1425
|
+
!!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1").get(name);
|
|
1426
|
+
// CAST keeps a blob stored as TEXT byte for byte; read as a string, its invalid UTF-8 is lost.
|
|
1427
|
+
const blob = (v) => (v instanceof Uint8Array ? v : new Uint8Array());
|
|
1428
|
+
|
|
1429
|
+
let trajectoryTs;
|
|
1430
|
+
if (hasTable('trajectory_metadata_blob')) {
|
|
1431
|
+
const rows = db
|
|
1432
|
+
.prepare('SELECT CAST(data AS BLOB) AS data FROM trajectory_metadata_blob ORDER BY rowid ASC')
|
|
1433
|
+
.all();
|
|
1434
|
+
for (const row of rows) {
|
|
1435
|
+
const ts = agTimestamp(pbFirstBytes(pbDecode(blob(row.data)), 2));
|
|
1436
|
+
trajectoryTs ??= ts;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
const generations = db
|
|
1440
|
+
.prepare('SELECT idx, CAST(data AS BLOB) AS data FROM gen_metadata ORDER BY idx ASC')
|
|
1441
|
+
.all()
|
|
1442
|
+
.map((row) => [row.idx, agGeneration(blob(row.data))]);
|
|
1443
|
+
const steps = hasTable('steps')
|
|
1444
|
+
? db
|
|
1445
|
+
.prepare(
|
|
1446
|
+
'SELECT idx, CAST(metadata AS BLOB) AS metadata FROM steps WHERE metadata IS NOT NULL ORDER BY idx ASC'
|
|
1447
|
+
)
|
|
1448
|
+
.all()
|
|
1449
|
+
.map((row) => [row.idx, agStep(blob(row.metadata))])
|
|
1450
|
+
: [];
|
|
1451
|
+
const rowModel = (m) => agModelName(m.model) ?? agModelFromId(m.modelId);
|
|
1452
|
+
const lastGenerationModel = generations.map(([, m]) => rowModel(m)).findLast(Boolean);
|
|
1453
|
+
|
|
1454
|
+
/** @type {AgEvent[]} */
|
|
1455
|
+
const events = [];
|
|
1456
|
+
const idTimestamps = new Map();
|
|
1457
|
+
const append = (usage, row) =>
|
|
1458
|
+
agAppendEvent(events, idTimestamps, usage, { trajectoryTs, fallbackTs, session, ...row });
|
|
1459
|
+
const appendRow = (kind, idx, m, row, fallbackIdentities) => {
|
|
1460
|
+
if (m.usage) append(m.usage, { ...row, fallbackIdentities });
|
|
1461
|
+
m.retries.forEach((retry, n) =>
|
|
1462
|
+
append(retry, {
|
|
1463
|
+
...row,
|
|
1464
|
+
// ccusage never merges a retry without ids, so each database counts its own. Naming the
|
|
1465
|
+
// file keeps the identity unique and lets a later run find the retry it counted.
|
|
1466
|
+
fallbackIdentities: [`retry:${path}:${kind}:${idx}:${n}`]
|
|
1467
|
+
})
|
|
1468
|
+
);
|
|
1469
|
+
};
|
|
1470
|
+
for (const [idx, m] of steps) {
|
|
1471
|
+
const row = { model: rowModel(m) ?? lastGenerationModel, modelId: m.modelId, ts: m.ts };
|
|
1472
|
+
appendRow('step', idx, m, row, [`step:${session}:${idx}`]);
|
|
1473
|
+
}
|
|
1474
|
+
let current;
|
|
1475
|
+
for (const [idx, m] of generations) {
|
|
1476
|
+
current = rowModel(m) ?? agModelFromId(m.usage?.modelId) ?? current;
|
|
1477
|
+
const row = { model: current, modelId: m.modelId, ts: m.ts };
|
|
1478
|
+
const linked = m.steps.map((step) => `step:${session}:${step}`);
|
|
1479
|
+
appendRow('gen', idx, m, row, linked.length ? linked : [`gen:${session}:${idx}`]);
|
|
1480
|
+
}
|
|
1481
|
+
return events;
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
function agMergeInto(target, copy) {
|
|
1485
|
+
for (const k of ['input', 'output', 'cacheWrite', 'cacheRead', 'reasoning']) {
|
|
1486
|
+
target[k] = Math.max(target[k], copy[k]);
|
|
1487
|
+
}
|
|
1488
|
+
target.totalOutput = Math.max(
|
|
1489
|
+
target.totalOutput,
|
|
1490
|
+
copy.totalOutput,
|
|
1491
|
+
target.output + target.reasoning
|
|
1492
|
+
);
|
|
1493
|
+
if (agResolution(copy.model) > agResolution(target.model)) target.model = copy.model;
|
|
1494
|
+
if (copy.rank > target.rank || (copy.rank === target.rank && copy.ts < target.ts)) {
|
|
1495
|
+
target.ts = copy.ts;
|
|
1496
|
+
target.rank = copy.rank;
|
|
1497
|
+
target.mtimeOf = copy.mtimeOf;
|
|
1498
|
+
}
|
|
1499
|
+
for (const id of copy.identities) {
|
|
1500
|
+
if (!target.identities.includes(id)) target.identities.push(id);
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
function agMergeEvents(events) {
|
|
1505
|
+
const slots = [];
|
|
1506
|
+
const slotOf = new Map();
|
|
1507
|
+
for (const event of events) {
|
|
1508
|
+
const hits = [
|
|
1509
|
+
...new Set(event.identities.map((id) => slotOf.get(id)).filter((i) => i !== undefined))
|
|
1510
|
+
].sort((a, b) => a - b);
|
|
1511
|
+
if (!hits.length) {
|
|
1512
|
+
for (const id of event.identities) slotOf.set(id, slots.length);
|
|
1513
|
+
slots.push(event);
|
|
1514
|
+
continue;
|
|
1515
|
+
}
|
|
1516
|
+
const target = slots[hits[0]];
|
|
1517
|
+
for (const i of hits.slice(1)) {
|
|
1518
|
+
if (slots[i]) agMergeInto(target, slots[i]);
|
|
1519
|
+
slots[i] = null;
|
|
1520
|
+
}
|
|
1521
|
+
agMergeInto(target, event);
|
|
1522
|
+
for (const id of target.identities) slotOf.set(id, hits[0]);
|
|
1523
|
+
}
|
|
1524
|
+
return slots.filter(Boolean);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
// No Antigravity model name has a slash, so one that does may be a file path, which must not leave
|
|
1528
|
+
// the machine.
|
|
1529
|
+
const agSchemaModel = (model) =>
|
|
1530
|
+
(!/[\\/]/.test(model) &&
|
|
1531
|
+
model
|
|
1532
|
+
.replace(/[^A-Za-z0-9._:@-]+/g, '-')
|
|
1533
|
+
.replace(/^-+|-+$/g, '')
|
|
1534
|
+
.slice(0, 100)) ||
|
|
1535
|
+
ANTIGRAVITY_DEFAULT_MODEL;
|
|
1536
|
+
|
|
1537
|
+
const AG_STORED = [
|
|
1538
|
+
'ts',
|
|
1539
|
+
'rank',
|
|
1540
|
+
'model',
|
|
1541
|
+
'input',
|
|
1542
|
+
'output',
|
|
1543
|
+
'cacheWrite',
|
|
1544
|
+
'cacheRead',
|
|
1545
|
+
'reasoning',
|
|
1546
|
+
'totalOutput',
|
|
1547
|
+
'tier',
|
|
1548
|
+
'session',
|
|
1549
|
+
'mtimeOf'
|
|
1550
|
+
];
|
|
1551
|
+
|
|
1552
|
+
/**
|
|
1553
|
+
* Keeps a counted group in `seen` so a later run can merge new copies into it and replace what it
|
|
1554
|
+
* added to its bucket. The first identity holds the AG_STORED fields followed by the group's other
|
|
1555
|
+
* identities, and each of those holds [ts, first identity]. Every entry starts with the group's
|
|
1556
|
+
* timestamp, which is what pruneState reads.
|
|
1557
|
+
* @param {State['seen']} seen @param {AgEvent} group
|
|
1558
|
+
*/
|
|
1559
|
+
function agStoreGroup(seen, group) {
|
|
1560
|
+
const [first, ...others] = group.identities;
|
|
1561
|
+
seen[first] = [...AG_STORED.map((field) => group[field]), ...others];
|
|
1562
|
+
for (const key of others) seen[key] = [group.ts, first];
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
/** @param {State['seen']} seen @param {string} key @returns {AgEvent | undefined} */
|
|
1566
|
+
function agStoredGroup(seen, key) {
|
|
1567
|
+
let record = seen[key];
|
|
1568
|
+
if (Array.isArray(record) && typeof record[1] === 'string') {
|
|
1569
|
+
key = record[1];
|
|
1570
|
+
record = seen[key];
|
|
1571
|
+
}
|
|
1572
|
+
if (!Array.isArray(record) || typeof record[2] !== 'string') return undefined;
|
|
1573
|
+
return {
|
|
1574
|
+
...Object.fromEntries(AG_STORED.map((field, i) => [field, record[i]])),
|
|
1575
|
+
identities: [key, ...record.slice(AG_STORED.length)]
|
|
1576
|
+
};
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
const agBucketRecord = (provider, group) => ({
|
|
1580
|
+
ts: group.ts,
|
|
1581
|
+
provider,
|
|
1582
|
+
model: group.model,
|
|
1583
|
+
tier: group.tier,
|
|
1584
|
+
session: group.session,
|
|
1585
|
+
input: group.input,
|
|
1586
|
+
cacheRead: group.cacheRead,
|
|
1587
|
+
cacheWrite5m: group.cacheWrite,
|
|
1588
|
+
cacheWrite1h: 0,
|
|
1589
|
+
output: group.totalOutput
|
|
1590
|
+
});
|
|
1591
|
+
|
|
1592
|
+
/** @type {Source['read']} */
|
|
1593
|
+
async function readAntigravity(dirs, ctx, provider) {
|
|
1594
|
+
const { state } = ctx;
|
|
1595
|
+
/** @type {AgEvent[]} */
|
|
1596
|
+
const events = [];
|
|
1597
|
+
const read = new Set();
|
|
1598
|
+
// Keyed by the real path: a root in ANTIGRAVITY_DATA_DIR can be a link to a default one, which
|
|
1599
|
+
// scan reads in an earlier pass.
|
|
1600
|
+
for (const { real: path } of await antigravityDatabases(dirs)) {
|
|
1601
|
+
if (ctx.seenPaths.has(path)) continue;
|
|
1602
|
+
ctx.seenPaths.add(path);
|
|
1603
|
+
let st;
|
|
1604
|
+
try {
|
|
1605
|
+
// A write in WAL mode may leave the main file as it was.
|
|
1606
|
+
const [main, wal] = await Promise.all([stat(path), stat(`${path}-wal`).catch(() => null)]);
|
|
1607
|
+
st = {
|
|
1608
|
+
size: main.size + (wal?.size ?? 0),
|
|
1609
|
+
mtimeMs: Math.max(main.mtimeMs, wal?.mtimeMs ?? 0),
|
|
1610
|
+
mainMtimeMs: Math.floor(main.mtimeMs)
|
|
1611
|
+
};
|
|
1612
|
+
} catch {
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
if (st.mtimeMs < ctx.cutoffMs) {
|
|
1616
|
+
delete state.files[path];
|
|
1617
|
+
continue;
|
|
1618
|
+
}
|
|
1619
|
+
const prev = state.rescan?.includes(provider) ? undefined : state.files[path];
|
|
1620
|
+
if (prev && prev.size === st.size && prev.mtimeMs === st.mtimeMs) continue;
|
|
1621
|
+
let db;
|
|
1622
|
+
try {
|
|
1623
|
+
db = await openSqlite(path);
|
|
1624
|
+
if (!db) return;
|
|
1625
|
+
const database = shortHash(`antigravity-db:${path}`);
|
|
1626
|
+
for (const e of agDatabaseEvents(db, path, st.mainMtimeMs)) {
|
|
1627
|
+
events.push({
|
|
1628
|
+
...e,
|
|
1629
|
+
model: agSchemaModel(e.model),
|
|
1630
|
+
mtimeOf: e.rank === AG_TS.FILE_MTIME ? database : '',
|
|
1631
|
+
session: shortHash(`antigravity:${e.session}`),
|
|
1632
|
+
identities: e.identities.map((id) => `ag:${shortHash(id)}`)
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
read.add(database);
|
|
1636
|
+
state.files[path] = { size: st.size, mtimeMs: st.mtimeMs, offset: 0 };
|
|
1637
|
+
ctx.filesRead++;
|
|
1638
|
+
ctx.parsedBytes += st.size;
|
|
1639
|
+
} catch (err) {
|
|
1640
|
+
log(`skipping unreadable Antigravity database ${basename(path)}: ${err.message}`);
|
|
1641
|
+
} finally {
|
|
1642
|
+
db?.close();
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
// An unchanged database is not read again, so its copies are known only through the groups
|
|
1647
|
+
// earlier runs stored. Merging those first, as ccusage would have read them first, and counting
|
|
1648
|
+
// the result in their place gives what one scan of every database gives.
|
|
1649
|
+
/** @type {Map<string, AgEvent>} */
|
|
1650
|
+
const stored = new Map();
|
|
1651
|
+
for (const key of events.flatMap((e) => e.identities)) {
|
|
1652
|
+
const group = agStoredGroup(state.seen, key);
|
|
1653
|
+
if (group) stored.set(group.identities[0], group);
|
|
1654
|
+
}
|
|
1655
|
+
for (const group of stored.values()) {
|
|
1656
|
+
removeRecord(state, agBucketRecord(provider, group));
|
|
1657
|
+
for (const key of group.identities) delete state.seen[key];
|
|
1658
|
+
// Its timestamp was that database's modification time, which this read replaces.
|
|
1659
|
+
if (group.rank === AG_TS.FILE_MTIME && read.has(group.mtimeOf)) group.ts = Infinity;
|
|
1660
|
+
}
|
|
1661
|
+
for (const group of agMergeEvents([...stored.values(), ...events])) {
|
|
1662
|
+
if (group.ts < ctx.cutoffMs) continue;
|
|
1663
|
+
group.tier = tierFor(
|
|
1664
|
+
ctx.resolvePrice(provider, group.model),
|
|
1665
|
+
group.input + group.cacheRead + group.cacheWrite
|
|
1666
|
+
);
|
|
1667
|
+
agStoreGroup(state.seen, group);
|
|
1668
|
+
addRecord(state, agBucketRecord(provider, group));
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
const GOOGLE_PRICE_PREFIXES = ['google/', 'gemini/', 'vertex_ai/', 'openrouter/google/'];
|
|
1673
|
+
|
|
1674
|
+
/**
|
|
1675
|
+
* Antigravity's names are not LiteLLM's: `claude-4.5-sonnet` is LiteLLM's `claude-sonnet-4-5`, and
|
|
1676
|
+
* some Gemini models are listed only as `-preview`.
|
|
1677
|
+
*/
|
|
1678
|
+
function antigravityPriceKeys(model) {
|
|
1679
|
+
const base = model.replace(/-(?:extra-low|low|medium|high|thinking)$/, '');
|
|
1680
|
+
const claude = /^claude-(\d+(?:\.\d+)?)-(opus|sonnet|haiku)$/.exec(base);
|
|
1681
|
+
const names = new Set([model, base]);
|
|
1682
|
+
if (claude) names.add(`claude-${claude[2]}-${claude[1].replace('.', '-')}`);
|
|
1683
|
+
names.add(`${base}-preview`);
|
|
1684
|
+
// LiteLLM dropped Anthropic's own keys for retired Claude models; this gateway still lists them
|
|
1685
|
+
// at Anthropic's price, and it is the entry ccusage's lookup lands on.
|
|
1686
|
+
const prefixes = base.startsWith('claude-')
|
|
1687
|
+
? ['', 'vercel_ai_gateway/anthropic/', ...GOOGLE_PRICE_PREFIXES]
|
|
1688
|
+
: ['', ...GOOGLE_PRICE_PREFIXES];
|
|
1689
|
+
return [...names].flatMap((name) => prefixes.map((prefix) => prefix + name));
|
|
1690
|
+
}
|
|
1691
|
+
|
|
889
1692
|
/**
|
|
890
1693
|
* @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
|
|
891
1694
|
* @typedef {{
|
|
892
1695
|
* paths: string[],
|
|
893
1696
|
* envPaths: () => string[],
|
|
894
1697
|
* read: (paths: string[], ctx: ReadContext, provider: string) => Promise<void>,
|
|
895
|
-
* priceKeys: (model: string) => string[]
|
|
1698
|
+
* priceKeys: (model: string) => string[],
|
|
1699
|
+
* experimental?: boolean
|
|
896
1700
|
* }} Source
|
|
897
1701
|
*/
|
|
898
1702
|
|
|
@@ -909,6 +1713,7 @@ const fromEnv = (name, ...rest) => (process.env[name] ? [join(process.env[name],
|
|
|
909
1713
|
* data whole on every run and skips what it counted before through `state.seen`, keyed with a
|
|
910
1714
|
* provider prefix and valued with the record's timestamp so pruneState can drop it.
|
|
911
1715
|
* - `priceKeys`: the LiteLLM keys to try for a model, in order.
|
|
1716
|
+
* - `experimental`: read only when BIG_SPENDER_EXPERIMENTAL names it; see enabledSources.
|
|
912
1717
|
*
|
|
913
1718
|
* @type {Record<string, Source>}
|
|
914
1719
|
*/
|
|
@@ -957,18 +1762,56 @@ const SOURCES = {
|
|
|
957
1762
|
envPaths: () => fromEnv('GROK_HOME', 'sessions'),
|
|
958
1763
|
read: jsonlReader(
|
|
959
1764
|
(ctx, _file, path) => grokLineHandler(ctx.state, ctx.cutoffMs, path),
|
|
960
|
-
(name) => name === 'updates.jsonl'
|
|
1765
|
+
(dir) => walk(dir, (name) => name === 'updates.jsonl')
|
|
961
1766
|
),
|
|
962
1767
|
// Grok Build logs `grok-4.5-build`; LiteLLM prices it as `xai/grok-4.5`.
|
|
963
1768
|
priceKeys: (model) =>
|
|
964
1769
|
[model, model.replace(/-build$/, '')].flatMap((base) => [base, `xai/${base}`])
|
|
1770
|
+
},
|
|
1771
|
+
copilot: {
|
|
1772
|
+
paths: [join(HOME, '.copilot', 'session-state')],
|
|
1773
|
+
envPaths: () => fromEnv('COPILOT_HOME', 'session-state'),
|
|
1774
|
+
read: jsonlReader(
|
|
1775
|
+
(ctx, file, path) =>
|
|
1776
|
+
copilotLineHandler(
|
|
1777
|
+
ctx.state,
|
|
1778
|
+
file,
|
|
1779
|
+
ctx.resolvePrice,
|
|
1780
|
+
ctx.cutoffMs,
|
|
1781
|
+
basename(dirname(path))
|
|
1782
|
+
),
|
|
1783
|
+
sessionEvents
|
|
1784
|
+
),
|
|
1785
|
+
priceKeys: (model) => {
|
|
1786
|
+
const claude = model.startsWith('claude-');
|
|
1787
|
+
const name = claude ? model.replace(/(\d)\.(\d)/g, '$1-$2') : model;
|
|
1788
|
+
const prefix = claude ? 'anthropic' : model.startsWith('gemini-') ? 'gemini' : 'openai';
|
|
1789
|
+
return [...new Set([...litellmKeys(prefix)(name), `github_copilot/${model}`])];
|
|
1790
|
+
}
|
|
1791
|
+
},
|
|
1792
|
+
antigravity: {
|
|
1793
|
+
experimental: true,
|
|
1794
|
+
paths: ANTIGRAVITY_ROOTS.map((root) => join(HOME, root, 'conversations')),
|
|
1795
|
+
envPaths: antigravityEnvDirs,
|
|
1796
|
+
read: readAntigravity,
|
|
1797
|
+
priceKeys: antigravityPriceKeys
|
|
965
1798
|
}
|
|
966
1799
|
};
|
|
967
1800
|
|
|
968
|
-
|
|
1801
|
+
// An experimental source has not been checked against real usage yet, so it is read and sent only
|
|
1802
|
+
// when BIG_SPENDER_EXPERIMENTAL (comma-separated provider ids) names it. Turned off, its counted rows
|
|
1803
|
+
// stay in the state, so turning it on again replaces them instead of counting them twice.
|
|
1804
|
+
function enabledSources() {
|
|
1805
|
+
const optIn = new Set(
|
|
1806
|
+
(process.env.BIG_SPENDER_EXPERIMENTAL ?? '').split(',').map((id) => id.trim())
|
|
1807
|
+
);
|
|
1808
|
+
return Object.entries(SOURCES).filter(([id, source]) => !source.experimental || optIn.has(id));
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
/** @param {[string, Source][]} sources */
|
|
1812
|
+
async function scan(state, resolvePrice, cutoffMs, sources) {
|
|
969
1813
|
/** @type {ReadContext} */
|
|
970
1814
|
const ctx = { state, resolvePrice, cutoffMs, seenPaths: new Set(), filesRead: 0, parsedBytes: 0 };
|
|
971
|
-
const sources = Object.entries(SOURCES);
|
|
972
1815
|
for (const [provider, source] of sources) await source.read(source.paths, ctx, provider);
|
|
973
1816
|
for (const [provider, source] of sources) await source.read(source.envPaths(), ctx, provider);
|
|
974
1817
|
for (const path of Object.keys(state.files)) {
|
|
@@ -1450,21 +2293,24 @@ async function main() {
|
|
|
1450
2293
|
const resolvePrice = makePriceResolver(pricing.models);
|
|
1451
2294
|
const state = await loadState();
|
|
1452
2295
|
pruneState(state, coverageStartMs);
|
|
1453
|
-
|
|
2296
|
+
const sources = enabledSources();
|
|
2297
|
+
const enabled = new Set(sources.map(([id]) => id));
|
|
2298
|
+
await scan(state, resolvePrice, coverageStartMs, sources);
|
|
1454
2299
|
await saveState(state);
|
|
1455
2300
|
|
|
1456
|
-
const
|
|
2301
|
+
const buckets = Object.fromEntries(
|
|
2302
|
+
Object.entries(state.buckets).filter(([key]) => enabled.has(key.split('|')[1]))
|
|
2303
|
+
);
|
|
2304
|
+
const used = new Set(Object.keys(buckets).map((k) => k.split('|')[1]));
|
|
1457
2305
|
const device = buildSnapshot(
|
|
1458
|
-
|
|
2306
|
+
buckets,
|
|
1459
2307
|
(b, provider, model, tier) => costOf(resolvePrice(provider, model), tier, b),
|
|
1460
2308
|
{
|
|
1461
2309
|
deviceId: setting('DEVICE_ID'),
|
|
1462
2310
|
pricingSource: `litellm@${new Date(pricing.fetchedAt).toISOString().slice(0, 10)}`,
|
|
1463
2311
|
// Older servers require the claude and codex counts and reject any other key, so another
|
|
1464
2312
|
// provider's count is sent only once this device has used it.
|
|
1465
|
-
providers:
|
|
1466
|
-
(p) => p === 'claude' || p === 'codex' || used.has(p)
|
|
1467
|
-
),
|
|
2313
|
+
providers: [...enabled].filter((p) => p === 'claude' || p === 'codex' || used.has(p)),
|
|
1468
2314
|
nowMs,
|
|
1469
2315
|
coverageStartMs,
|
|
1470
2316
|
limits: state.limits
|
package/dist/history.js
CHANGED
|
@@ -4,6 +4,10 @@ const DAY_MS = 86_400_000;
|
|
|
4
4
|
const round = (n) => Math.round(n * 1e6) / 1e6;
|
|
5
5
|
const dayOf = (r) => Math.floor(Date.parse(r.hour) / DAY_MS);
|
|
6
6
|
const keyOf = (r) => `${dayOf(r)}|${r.provider}|${r.model}`;
|
|
7
|
+
// A collector sends a zero row to take back a day and model it reported before (a response it
|
|
8
|
+
// moved to another day or model). The row replaces the stored ones and is not kept itself.
|
|
9
|
+
const hasTokens = (r) => r.inputTokens + r.cacheReadTokens + r.cacheWrite5mTokens + r.cacheWrite1hTokens + r.outputTokens >
|
|
10
|
+
0;
|
|
7
11
|
function compareRows(a, b) {
|
|
8
12
|
return (Date.parse(a.hour) - Date.parse(b.hour) ||
|
|
9
13
|
a.provider.localeCompare(b.provider) ||
|
|
@@ -62,13 +66,14 @@ function dropOldestDays(rows, excess) {
|
|
|
62
66
|
return { rows: rows.slice(cut), days };
|
|
63
67
|
}
|
|
64
68
|
export function mergeSnapshots(stored, next) {
|
|
65
|
-
const
|
|
69
|
+
const sorted = [...next.hourly].sort(compareRows);
|
|
70
|
+
const fresh = sorted.filter(hasTokens);
|
|
66
71
|
const limits = mergeLimits(stored?.limits, next.limits);
|
|
67
72
|
const withLimits = limits.length ? { limits } : {};
|
|
68
73
|
const { limits: _, ...rest } = next;
|
|
69
74
|
if (!stored)
|
|
70
75
|
return { snapshot: { ...rest, hourly: fresh, ...withLimits }, droppedDays: 0 };
|
|
71
|
-
const reported = new Set(
|
|
76
|
+
const reported = new Set(sorted.map(keyOf));
|
|
72
77
|
const kept = [...group(stored.hourly)]
|
|
73
78
|
.filter(([key]) => !reported.has(key))
|
|
74
79
|
.flatMap(([, rows]) => rollUp(rows))
|
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'];
|
|
6
|
+
export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi', 'grok', 'copilot', 'antigravity'];
|
|
7
7
|
export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
|
|
8
8
|
export declare const usageRowSchema: z.ZodObject<{
|
|
9
9
|
hour: z.ZodISODateTime;
|
|
@@ -12,8 +12,10 @@ export declare const usageRowSchema: z.ZodObject<{
|
|
|
12
12
|
hour: "hour";
|
|
13
13
|
}>>;
|
|
14
14
|
provider: z.ZodEnum<{
|
|
15
|
+
antigravity: "antigravity";
|
|
15
16
|
claude: "claude";
|
|
16
17
|
codex: "codex";
|
|
18
|
+
copilot: "copilot";
|
|
17
19
|
cursor: "cursor";
|
|
18
20
|
grok: "grok";
|
|
19
21
|
pi: "pi";
|
|
@@ -36,8 +38,10 @@ export declare const usageRowSchema: z.ZodObject<{
|
|
|
36
38
|
export declare const MAX_LIMIT_WINDOWS = 5000;
|
|
37
39
|
export declare const limitWindowSchema: z.ZodObject<{
|
|
38
40
|
provider: z.ZodEnum<{
|
|
41
|
+
antigravity: "antigravity";
|
|
39
42
|
claude: "claude";
|
|
40
43
|
codex: "codex";
|
|
44
|
+
copilot: "copilot";
|
|
41
45
|
cursor: "cursor";
|
|
42
46
|
grok: "grok";
|
|
43
47
|
pi: "pi";
|
|
@@ -60,8 +64,10 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
60
64
|
hour: "hour";
|
|
61
65
|
}>>;
|
|
62
66
|
provider: z.ZodEnum<{
|
|
67
|
+
antigravity: "antigravity";
|
|
63
68
|
claude: "claude";
|
|
64
69
|
codex: "codex";
|
|
70
|
+
copilot: "copilot";
|
|
65
71
|
cursor: "cursor";
|
|
66
72
|
grok: "grok";
|
|
67
73
|
pi: "pi";
|
|
@@ -87,6 +93,8 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
87
93
|
claude: z.ZodNumber;
|
|
88
94
|
codex: z.ZodNumber;
|
|
89
95
|
all: z.ZodNumber;
|
|
96
|
+
antigravity: z.ZodOptional<z.ZodNumber>;
|
|
97
|
+
copilot: z.ZodOptional<z.ZodNumber>;
|
|
90
98
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
91
99
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
92
100
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
@@ -95,6 +103,8 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
95
103
|
claude: z.ZodNumber;
|
|
96
104
|
codex: z.ZodNumber;
|
|
97
105
|
all: z.ZodNumber;
|
|
106
|
+
antigravity: z.ZodOptional<z.ZodNumber>;
|
|
107
|
+
copilot: z.ZodOptional<z.ZodNumber>;
|
|
98
108
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
99
109
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
100
110
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
@@ -103,6 +113,8 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
103
113
|
claude: z.ZodNumber;
|
|
104
114
|
codex: z.ZodNumber;
|
|
105
115
|
all: z.ZodNumber;
|
|
116
|
+
antigravity: z.ZodOptional<z.ZodNumber>;
|
|
117
|
+
copilot: z.ZodOptional<z.ZodNumber>;
|
|
106
118
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
107
119
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
108
120
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
@@ -111,6 +123,8 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
111
123
|
claude: z.ZodNumber;
|
|
112
124
|
codex: z.ZodNumber;
|
|
113
125
|
all: z.ZodNumber;
|
|
126
|
+
antigravity: z.ZodOptional<z.ZodNumber>;
|
|
127
|
+
copilot: z.ZodOptional<z.ZodNumber>;
|
|
114
128
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
115
129
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
116
130
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
@@ -118,8 +132,10 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
118
132
|
}, z.core.$strict>>;
|
|
119
133
|
limits: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
120
134
|
provider: z.ZodEnum<{
|
|
135
|
+
antigravity: "antigravity";
|
|
121
136
|
claude: "claude";
|
|
122
137
|
codex: "codex";
|
|
138
|
+
copilot: "copilot";
|
|
123
139
|
cursor: "cursor";
|
|
124
140
|
grok: "grok";
|
|
125
141
|
pi: "pi";
|
package/dist/schema.js
CHANGED
|
@@ -14,7 +14,15 @@ export const MAX_ROWS = 50_000;
|
|
|
14
14
|
export const DEVICE_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
15
15
|
// Collectors send the Cursor account's usage under this id, so no machine may use it.
|
|
16
16
|
export const CURSOR_DEVICE_ID = 'cursor';
|
|
17
|
-
export const PROVIDERS = [
|
|
17
|
+
export const PROVIDERS = [
|
|
18
|
+
'claude',
|
|
19
|
+
'codex',
|
|
20
|
+
'cursor',
|
|
21
|
+
'pi',
|
|
22
|
+
'grok',
|
|
23
|
+
'copilot',
|
|
24
|
+
'antigravity'
|
|
25
|
+
];
|
|
18
26
|
// Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
|
|
19
27
|
// than a day: an hourly view would show when each machine is in use.
|
|
20
28
|
export const RANGES = ['7d', '30d', '90d', 'all'];
|
package/package.json
CHANGED
package/templates/env.example
CHANGED
|
@@ -10,3 +10,6 @@ BIG_SPENDER_INGEST_TOKEN=
|
|
|
10
10
|
# Optional, on one machine only: a Cursor user API key. The collector then reads the account's
|
|
11
11
|
# usage from Cursor's API and sends it as the device "cursor". Set by `big-spender install --cursor`.
|
|
12
12
|
# BIG_SPENDER_CURSOR_API_KEY=
|
|
13
|
+
# Optional: experimental sources to read too, comma-separated. Their counts match ccusage on test
|
|
14
|
+
# data but have not been checked against real usage yet. Available: antigravity.
|
|
15
|
+
# BIG_SPENDER_EXPERIMENTAL=antigravity
|