big-spender 0.8.0 → 0.10.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 +20 -3
- package/dist/collector.mjs +964 -23
- package/dist/history.js +7 -2
- package/dist/schema.d.ts +17 -1
- package/dist/schema.js +10 -1
- package/package.json +1 -1
- package/templates/env.example +3 -0
package/README.md
CHANGED
|
@@ -335,20 +335,37 @@ about 15 to 20 percent less.
|
|
|
335
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
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
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
|
+
| Gemini CLI (experimental) | `~/.gemini/tmp/**/*.json` and `*.jsonl`, `$GEMINI_DATA_DIR` (comma-separated) | **Experimental:** read only with `BIG_SPENDER_EXPERIMENTAL=gemini`; checked against ccusage on test fixtures, not yet against real Gemini CLI data. `gemini` chat messages with `tokens`, and saved headless `stats` (per model, or with the last model named, else `unknown`). A changed file is read whole and its counts replace what it counted before, as ccusage counts each file as it is; in JSONL the last copy of a message id counts. `input` excludes `cached` when the total shows it was inside (always in stats), and `tool` tokens count as input. Reasoning (`thoughts`) and any total beyond the parts count as output, as ccusage bills them, though its per-model output leaves reasoning out. A model id that is a file path is reduced to its file name. `$GEMINI_DATA_DIR` adds dirs to the default rather than replacing it. |
|
|
338
340
|
|
|
339
|
-
**Pricing.** Claude Code, Codex, pi, Grok Build
|
|
341
|
+
**Pricing.** Claude Code, Codex, pi, Grok Build, GitHub Copilot CLI, Antigravity and Gemini CLI use LiteLLM
|
|
340
342
|
`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
|
|
341
343
|
Code and Codex try the exact model, then the `anthropic/` or `openai/` prefix, then without a date
|
|
342
344
|
suffix. pi tries the LiteLLM prefixes of the providers pi supports too (`openrouter/`, `fireworks_ai/`,
|
|
343
345
|
`groq/` and others). For an OpenRouter id such as `anthropic/claude-sonnet-4.5` it then tries
|
|
344
346
|
`claude-sonnet-4.5` and `claude-sonnet-4-5`. Grok Build tries the model and its `xai/` key, then
|
|
345
|
-
both without a trailing `-build`.
|
|
347
|
+
both without a trailing `-build`. Antigravity tries the model, the model without an effort or `-thinking`
|
|
348
|
+
suffix, Anthropic's spelling of a Claude name (`claude-sonnet-4-5` for `claude-4.5-sonnet`) and the
|
|
349
|
+
`-preview` name, each bare and with the `google/`, `gemini/`, `vertex_ai/` and `openrouter/google/`
|
|
350
|
+
prefixes (a Claude name also with `vercel_ai_gateway/anthropic/`, which still lists retired models).
|
|
351
|
+
Gemini CLI tries `gemini/`, `vertex_ai/` and `openrouter/google/`, then the bare model. ccusage prices
|
|
352
|
+
Gemini from models.dev's `google/` entries first, and for `gemini-2.5-flash` that entry is $0.15
|
|
353
|
+
input and $1.25 output per million tokens, half of LiteLLM's (and models.dev's own `gemini/` entry)
|
|
354
|
+
$0.30 and $2.50. So ccusage shows about half the collector's cost for that model.
|
|
355
|
+
Unknown models count with cost 0 and log a warning.
|
|
346
356
|
Long-context tiers
|
|
347
|
-
(`*_above_<N>k_tokens`) are applied per request;
|
|
357
|
+
(`*_above_<N>k_tokens`) are applied per request; a missing cache price is derived from the base
|
|
358
|
+
input price, also above a tier, as ccusage does. 1-hour cache writes use
|
|
348
359
|
`cache_creation_input_token_cost_above_1hr`. Cache savings are cache-read tokens times (input price
|
|
349
360
|
minus cache-read price). Copilot also tries `github_copilot/<model>`, and swaps a dot between digits
|
|
350
361
|
for a dash in Claude model names (`claude-opus-4.6` is priced as `claude-opus-4-6`).
|
|
351
362
|
|
|
363
|
+
**Experimental sources.** A source whose counts match ccusage on test data but have not been checked
|
|
364
|
+
against real usage yet is marked `experimental` in `SOURCES`. The collector reads and sends it only
|
|
365
|
+
when `BIG_SPENDER_EXPERIMENTAL` (comma-separated provider ids, in the environment or the env file)
|
|
366
|
+
names it. Antigravity and Gemini CLI are gated this way. Removing it from the list stops sending its rows on the
|
|
367
|
+
next run; adding it back recounts them without counting anything twice.
|
|
368
|
+
|
|
352
369
|
**Adding a provider.** Add an entry to `SOURCES` in `src/collector.mjs`, the provider id to
|
|
353
370
|
`PROVIDERS` in `src/schema.ts`, a row to the table above, and a test with a fixture log. The entry
|
|
354
371
|
says where the data lives, how it is read, and which LiteLLM keys price its models. Append-only JSONL
|
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;
|
|
@@ -124,7 +134,9 @@ async function acquireLock() {
|
|
|
124
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
|
+
* Gemini keeps a file's counts under `gm:` and its path: [latest hour, counts]; see readGemini.
|
|
139
|
+
* @typedef {number | [number, number] | [number, string] | [number, number, string, ...(number | string)[]] | [number, Record<string, any>]} Seen
|
|
128
140
|
* One subscription usage window instance; see limitWindowSchema in src/schema.ts.
|
|
129
141
|
* @typedef {{ provider: string, window: string, resetsAt: string, peakPercent: number, hitAt?: string }} Limit
|
|
130
142
|
* @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 +195,16 @@ const shortHash = (s) => createHash('sha256').update(s).digest('base64url').slic
|
|
|
183
195
|
// Bucket key: hour start (ms) | provider | model | pricing tier (prompt-size threshold, 0 = base).
|
|
184
196
|
const bucketKey = (hourMs, provider, model, tier) => `${hourMs}|${provider}|${model}|${tier}`;
|
|
185
197
|
|
|
198
|
+
const BUCKET_COUNTS = ['input', 'cacheRead', 'cacheWrite5m', 'cacheWrite1h', 'output'];
|
|
199
|
+
const recordBucketKey = (r) =>
|
|
200
|
+
bucketKey(Math.floor(r.ts / HOUR_MS) * HOUR_MS, r.provider, r.model, r.tier);
|
|
201
|
+
|
|
186
202
|
/**
|
|
187
203
|
* @param {State} state
|
|
188
204
|
* @param {{ ts: number, provider: string, model: string, tier: number, session: string, input: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number, output: number }} r
|
|
189
205
|
*/
|
|
190
206
|
function addRecord(state, r) {
|
|
191
|
-
const
|
|
192
|
-
const key = bucketKey(hourMs, r.provider, r.model, r.tier);
|
|
193
|
-
const b = (state.buckets[key] ??= {
|
|
207
|
+
const b = (state.buckets[recordBucketKey(r)] ??= {
|
|
194
208
|
input: 0,
|
|
195
209
|
cacheRead: 0,
|
|
196
210
|
cacheWrite5m: 0,
|
|
@@ -198,14 +212,24 @@ function addRecord(state, r) {
|
|
|
198
212
|
output: 0,
|
|
199
213
|
sessions: []
|
|
200
214
|
});
|
|
201
|
-
b
|
|
202
|
-
b.cacheRead += r.cacheRead;
|
|
203
|
-
b.cacheWrite5m += r.cacheWrite5m;
|
|
204
|
-
b.cacheWrite1h += r.cacheWrite1h;
|
|
205
|
-
b.output += r.output;
|
|
215
|
+
for (const k of BUCKET_COUNTS) b[k] += r[k];
|
|
206
216
|
if (!b.sessions.includes(r.session)) b.sessions.push(r.session);
|
|
207
217
|
}
|
|
208
218
|
|
|
219
|
+
/**
|
|
220
|
+
* Takes back what addRecord added for `r`. Its session stays listed, since a bucket does not
|
|
221
|
+
* know which of its records named it, unless nothing is left of the bucket. An emptied bucket
|
|
222
|
+
* stays as a zero row until it ages out: the server keeps a day and model that a snapshot stops
|
|
223
|
+
* reporting, so only a zero row takes back what an earlier snapshot sent.
|
|
224
|
+
* @type {typeof addRecord}
|
|
225
|
+
*/
|
|
226
|
+
function removeRecord(state, r) {
|
|
227
|
+
const b = state.buckets[recordBucketKey(r)];
|
|
228
|
+
if (!b) return;
|
|
229
|
+
for (const k of BUCKET_COUNTS) b[k] = Math.max(0, b[k] - r[k]);
|
|
230
|
+
if (BUCKET_COUNTS.every((k) => b[k] === 0)) b.sessions = [];
|
|
231
|
+
}
|
|
232
|
+
|
|
209
233
|
/** @param {State} state @param {number} cutoffMs */
|
|
210
234
|
function pruneState(state, cutoffMs) {
|
|
211
235
|
for (const key of Object.keys(state.buckets)) {
|
|
@@ -392,8 +416,10 @@ function costOf(entry, tier, t) {
|
|
|
392
416
|
if (!entry) return { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, savings: 0 };
|
|
393
417
|
const inP = price(entry, 'input_cost_per_token', tier) ?? 0;
|
|
394
418
|
const outP = price(entry, 'output_cost_per_token', tier) ?? 0;
|
|
395
|
-
|
|
396
|
-
const
|
|
419
|
+
// A missing cache rate derives from the base input rate, also above a tier, as in ccusage.
|
|
420
|
+
const baseInP = price(entry, 'input_cost_per_token', 0) ?? 0;
|
|
421
|
+
const readP = price(entry, 'cache_read_input_token_cost', tier) ?? baseInP * 0.1;
|
|
422
|
+
const write5mP = price(entry, 'cache_creation_input_token_cost', tier) ?? baseInP * 1.25;
|
|
397
423
|
const write1hP = tier
|
|
398
424
|
? (entry[`cache_creation_input_token_cost_above_1hr_above_${tier / 1000}k_tokens`] ??
|
|
399
425
|
entry.cache_creation_input_token_cost_above_1hr ??
|
|
@@ -914,6 +940,214 @@ function copilotLineHandler(state, file, resolvePrice, cutoffMs, sessionDir) {
|
|
|
914
940
|
|
|
915
941
|
const allJsonl = (dir) => walk(dir, (name) => name.endsWith('.jsonl'));
|
|
916
942
|
|
|
943
|
+
// Gemini CLI keeps each chat under ~/.gemini/tmp/<project hash>/chats, as a JSON file it rewrites
|
|
944
|
+
// after every message or as JSONL it appends to, and headless runs can save their stats there too.
|
|
945
|
+
// Every .json and .jsonl file under it is read with ccusage's rules for these shapes.
|
|
946
|
+
|
|
947
|
+
const GEMINI_TOKEN_KEYS = {
|
|
948
|
+
input: ['input', 'prompt', 'input_tokens', 'prompt_tokens'],
|
|
949
|
+
output: ['output', 'candidates', 'output_tokens', 'candidates_tokens'],
|
|
950
|
+
cached: ['cached', 'cached_tokens'],
|
|
951
|
+
thoughts: ['thoughts', 'reasoning', 'thoughts_tokens', 'reasoning_tokens'],
|
|
952
|
+
tool: ['tool', 'tool_tokens']
|
|
953
|
+
};
|
|
954
|
+
const GEMINI_TIME =
|
|
955
|
+
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{3})?(Z|[+-]\d{2}:\d{2})$/;
|
|
956
|
+
// Gemini's context is a few million tokens, so a larger count is corrupt. Capping each record also
|
|
957
|
+
// keeps a bucket's sum under the snapshot schema's limit.
|
|
958
|
+
const GEMINI_MAX_TOKENS = 1e9;
|
|
959
|
+
|
|
960
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
961
|
+
const nonEmpty = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
|
|
962
|
+
// Date.parse would roll an hour of 24 or February 30 over to the next day; ccusage rejects them.
|
|
963
|
+
const geminiTime = (v) => {
|
|
964
|
+
const m = typeof v === 'string' ? GEMINI_TIME.exec(v) : null;
|
|
965
|
+
if (!m) return undefined;
|
|
966
|
+
const [, y, mo, d, h, mi, sec] = m.map(Number);
|
|
967
|
+
const day = new Date(Date.UTC(y, mo - 1, d));
|
|
968
|
+
if (day.getUTCMonth() !== mo - 1 || day.getUTCDate() !== d || h > 23 || mi > 59 || sec > 59) {
|
|
969
|
+
return undefined;
|
|
970
|
+
}
|
|
971
|
+
const ms = Date.parse(v);
|
|
972
|
+
return plausibleTime(ms) ? ms : undefined;
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* One request's tokens. Headless stats always count cached tokens inside `input`; a chat message
|
|
977
|
+
* does when its total equals the parts without them, as Gemini's totalTokenCount does. Reasoning
|
|
978
|
+
* and whatever the total has beyond the parts are billed as output.
|
|
979
|
+
*/
|
|
980
|
+
function geminiUsage(raw, cachedInInput) {
|
|
981
|
+
if (!isObject(raw)) return null;
|
|
982
|
+
const count = (v) => (typeof v === 'number' ? Math.trunc(Math.max(0, v)) : undefined);
|
|
983
|
+
const tokenKeys = [...Object.values(GEMINI_TOKEN_KEYS).flat(), 'total', 'total_tokens'];
|
|
984
|
+
if (tokenKeys.some((k) => typeof raw[k] === 'number' && !(raw[k] < GEMINI_MAX_TOKENS)))
|
|
985
|
+
return null;
|
|
986
|
+
const pick = (keys) => keys.map((k) => count(raw[k])).find((v) => v !== undefined) ?? 0;
|
|
987
|
+
const { input, output, cached, thoughts, tool } = Object.fromEntries(
|
|
988
|
+
Object.entries(GEMINI_TOKEN_KEYS).map(([name, keys]) => [name, pick(keys)])
|
|
989
|
+
);
|
|
990
|
+
const total = 'total' in raw ? count(raw.total) : count(raw.total_tokens);
|
|
991
|
+
const overlap = cachedInInput || (cached > 0 && total === input + output + thoughts + tool);
|
|
992
|
+
const prompt = (overlap ? input - Math.min(input, cached) : input) + tool;
|
|
993
|
+
const known = prompt + output + cached + thoughts;
|
|
994
|
+
const billedOutput = output + thoughts + Math.max(0, (total ?? known) - known);
|
|
995
|
+
if (!prompt && !cached && !billedOutput) return null;
|
|
996
|
+
return { input: prompt, cacheRead: cached, output: billedOutput };
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
/**
|
|
1000
|
+
* The usage events in one Gemini file, or null for a file that may be half written: JSON that
|
|
1001
|
+
* does not parse, or JSONL whose last line does not. `id` is the message id when the event has one. In JSONL a line's session id
|
|
1002
|
+
* and model carry over to the lines after it, and a message logged again with its id replaces
|
|
1003
|
+
* the earlier copy, as in ccusage.
|
|
1004
|
+
*/
|
|
1005
|
+
function geminiEvents(path, text, mtimeMs) {
|
|
1006
|
+
const events = [];
|
|
1007
|
+
let session = basename(path).replace(/\.jsonl?$/, '');
|
|
1008
|
+
const push = (raw, model, ts, cachedInInput, id) => {
|
|
1009
|
+
const u = model && geminiUsage(raw, cachedInInput);
|
|
1010
|
+
if (u) events.push({ ...u, model, ts, session, id });
|
|
1011
|
+
};
|
|
1012
|
+
const pushStats = (o, model, ts) => {
|
|
1013
|
+
const stats = o.stats ?? (isObject(o.result) ? o.result.stats : undefined);
|
|
1014
|
+
if (!isObject(stats)) return;
|
|
1015
|
+
const before = events.length;
|
|
1016
|
+
if (isObject(stats.models)) {
|
|
1017
|
+
for (const [name, m] of Object.entries(stats.models)) {
|
|
1018
|
+
if (isObject(m)) push(m.tokens, nonEmpty(name), ts, true);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (events.length === before) push(stats, model ?? 'unknown', ts, true);
|
|
1022
|
+
};
|
|
1023
|
+
const sessionOf = (o) => nonEmpty(o.sessionId) ?? nonEmpty(o.session_id) ?? session;
|
|
1024
|
+
const direct = (o, model, fallbackMs) =>
|
|
1025
|
+
push(
|
|
1026
|
+
o.tokens,
|
|
1027
|
+
model,
|
|
1028
|
+
geminiTime(o.timestamp) ?? geminiTime(o.created_at) ?? fallbackMs,
|
|
1029
|
+
false,
|
|
1030
|
+
nonEmpty(o.id)
|
|
1031
|
+
);
|
|
1032
|
+
|
|
1033
|
+
if (path.endsWith('.jsonl')) {
|
|
1034
|
+
let model;
|
|
1035
|
+
const byId = new Map();
|
|
1036
|
+
const lines = text.split('\n');
|
|
1037
|
+
const last = lines.findLast((line) => line.trim());
|
|
1038
|
+
if (last !== undefined && parseJson(last) === null) return null;
|
|
1039
|
+
for (const line of lines) {
|
|
1040
|
+
const o = parseJson(line);
|
|
1041
|
+
if (!isObject(o)) continue;
|
|
1042
|
+
session = sessionOf(o);
|
|
1043
|
+
model = nonEmpty(o.model) ?? model;
|
|
1044
|
+
if (o.type !== 'gemini') {
|
|
1045
|
+
pushStats(o, model, geminiTime(o.timestamp) ?? mtimeMs);
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
const n = events.length;
|
|
1049
|
+
direct(o, model, mtimeMs);
|
|
1050
|
+
const id = events[n]?.id;
|
|
1051
|
+
if (id === undefined) continue;
|
|
1052
|
+
if (byId.has(id)) events[byId.get(id)] = events.pop();
|
|
1053
|
+
else byId.set(id, n);
|
|
1054
|
+
}
|
|
1055
|
+
return events;
|
|
1056
|
+
}
|
|
1057
|
+
const o = parseJson(text);
|
|
1058
|
+
if (o === null) return null;
|
|
1059
|
+
if (!isObject(o)) return events;
|
|
1060
|
+
session = sessionOf(o);
|
|
1061
|
+
if (Array.isArray(o.messages)) {
|
|
1062
|
+
const start = geminiTime(o.startTime) ?? geminiTime(o.lastUpdated) ?? mtimeMs;
|
|
1063
|
+
for (const m of o.messages) {
|
|
1064
|
+
if (isObject(m) && m.type === 'gemini') direct(m, nonEmpty(m.model), start);
|
|
1065
|
+
}
|
|
1066
|
+
} else if (o.type === 'gemini') {
|
|
1067
|
+
direct(o, nonEmpty(o.model), mtimeMs);
|
|
1068
|
+
} else {
|
|
1069
|
+
pushStats(o, nonEmpty(o.model), geminiTime(o.timestamp) ?? mtimeMs);
|
|
1070
|
+
}
|
|
1071
|
+
return events;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/**
|
|
1075
|
+
* Gemini rewrites its files, so a changed file is read whole and what it counts now replaces
|
|
1076
|
+
* what it counted before, as ccusage counts each file as it is. `state.seen` keeps each file's
|
|
1077
|
+
* counts per hour, model, tier and session so they can be taken back, also after the file was
|
|
1078
|
+
* skipped for a while (an experimental source turned off). A message updated, corrected or
|
|
1079
|
+
* removed in the file changes the count with it, and an hour or model it leaves is sent as a
|
|
1080
|
+
* zero row.
|
|
1081
|
+
* @type {Source['read']}
|
|
1082
|
+
*/
|
|
1083
|
+
async function readGemini(paths, ctx, provider) {
|
|
1084
|
+
const { state, cutoffMs } = ctx;
|
|
1085
|
+
for (const dir of paths) {
|
|
1086
|
+
// A symlinked GEMINI_DATA_DIR reaches the same files as the default under another name.
|
|
1087
|
+
const root = await realpath(dir).catch(() => null);
|
|
1088
|
+
if (!root) continue;
|
|
1089
|
+
for await (const path of walk(root, (name) => /\.jsonl?$/.test(name))) {
|
|
1090
|
+
if (ctx.seenPaths.has(path)) continue;
|
|
1091
|
+
ctx.seenPaths.add(path);
|
|
1092
|
+
let st;
|
|
1093
|
+
let text;
|
|
1094
|
+
try {
|
|
1095
|
+
st = await stat(path);
|
|
1096
|
+
if (st.mtimeMs < cutoffMs) {
|
|
1097
|
+
delete state.files[path];
|
|
1098
|
+
continue;
|
|
1099
|
+
}
|
|
1100
|
+
const prev = state.files[path];
|
|
1101
|
+
const rescan = state.rescan?.includes(provider);
|
|
1102
|
+
if (!rescan && prev && prev.size === st.size && prev.mtimeMs === st.mtimeMs) continue;
|
|
1103
|
+
text = await readFile(path, 'utf8');
|
|
1104
|
+
} catch (err) {
|
|
1105
|
+
log(`skipping unreadable file: ${err.message}`);
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
ctx.filesRead++;
|
|
1109
|
+
ctx.parsedBytes += st.size;
|
|
1110
|
+
const events = geminiEvents(path, text, st.mtimeMs);
|
|
1111
|
+
state.files[path] = { size: st.size, mtimeMs: st.mtimeMs, offset: st.size };
|
|
1112
|
+
// Half written: keep what it counted until the write completes and changes the file.
|
|
1113
|
+
if (!events) continue;
|
|
1114
|
+
/** @type {Record<string, ReturnType<typeof geminiRecord>>} */
|
|
1115
|
+
const counts = {};
|
|
1116
|
+
for (const e of events) {
|
|
1117
|
+
if (e.ts < cutoffMs) continue;
|
|
1118
|
+
const model = localModelName(e.model) || 'unknown';
|
|
1119
|
+
const tier = tierFor(ctx.resolvePrice(provider, model), e.input + e.cacheRead);
|
|
1120
|
+
const r = geminiRecord(e.ts, model, tier, shortHash(`gemini:${e.session}`));
|
|
1121
|
+
const c = (counts[`${recordBucketKey(r)}|${r.session}`] ??= r);
|
|
1122
|
+
c.input += e.input;
|
|
1123
|
+
c.cacheRead += e.cacheRead;
|
|
1124
|
+
c.output += e.output;
|
|
1125
|
+
}
|
|
1126
|
+
const seenKey = `gm:${shortHash(path)}`;
|
|
1127
|
+
const before = state.seen[seenKey];
|
|
1128
|
+
for (const r of Object.values(Array.isArray(before) ? before[1] : {})) removeRecord(state, r);
|
|
1129
|
+
for (const r of Object.values(counts)) addRecord(state, r);
|
|
1130
|
+
const latest = Math.max(...Object.values(counts).map((r) => r.ts));
|
|
1131
|
+
if (Number.isFinite(latest)) state.seen[seenKey] = [latest, counts];
|
|
1132
|
+
else delete state.seen[seenKey];
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/** A Gemini count for one hour, model, tier and session, in the shape addRecord takes. */
|
|
1138
|
+
const geminiRecord = (ts, model, tier, session) => ({
|
|
1139
|
+
ts: Math.floor(ts / HOUR_MS) * HOUR_MS,
|
|
1140
|
+
provider: 'gemini',
|
|
1141
|
+
model,
|
|
1142
|
+
tier,
|
|
1143
|
+
session,
|
|
1144
|
+
input: 0,
|
|
1145
|
+
cacheRead: 0,
|
|
1146
|
+
cacheWrite5m: 0,
|
|
1147
|
+
cacheWrite1h: 0,
|
|
1148
|
+
output: 0
|
|
1149
|
+
});
|
|
1150
|
+
|
|
917
1151
|
/**
|
|
918
1152
|
* A reader for JSONL logs that only grow: reads the files `files` lists under each path (every
|
|
919
1153
|
* `*.jsonl` below it by default) and parses only the bytes added since the last run. `lines`
|
|
@@ -993,13 +1227,685 @@ async function* sessionEvents(dir) {
|
|
|
993
1227
|
|
|
994
1228
|
const fromEnv = (name, ...rest) => (process.env[name] ? [join(process.env[name], ...rest)] : []);
|
|
995
1229
|
|
|
1230
|
+
// One SQLite database per conversation; its blobs are protobuf. `gen_metadata` rows (one per model
|
|
1231
|
+
// call) and `steps` rows each carry a usage message plus the usage of earlier attempts. The same
|
|
1232
|
+
// response is written to several rows and to several databases, sometimes with partial counts, so
|
|
1233
|
+
// usage messages that share a response, provider or message id merge and keep the largest counts.
|
|
1234
|
+
// This follows ccusage's antigravity adapter (v20.0.51) read for read: the order of reads decides
|
|
1235
|
+
// which copy's timestamp and model win, and the numbers only match when it is the same.
|
|
1236
|
+
|
|
1237
|
+
const ANTIGRAVITY_ROOTS = [
|
|
1238
|
+
'.gemini/antigravity',
|
|
1239
|
+
'.gemini/antigravity-cli',
|
|
1240
|
+
'.gemini/antigravity-ide',
|
|
1241
|
+
'.gemini/antigravity-backup',
|
|
1242
|
+
'.gemini/antigravity-acp',
|
|
1243
|
+
'.config/antigravity'
|
|
1244
|
+
];
|
|
1245
|
+
const ANTIGRAVITY_DEFAULT_MODEL = 'gemini-internal-model';
|
|
1246
|
+
|
|
1247
|
+
const isDir = (path) => {
|
|
1248
|
+
try {
|
|
1249
|
+
return statSync(path).isDirectory();
|
|
1250
|
+
} catch {
|
|
1251
|
+
return false;
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1254
|
+
|
|
1255
|
+
const antigravityEnvDirs = () =>
|
|
1256
|
+
(process.env.ANTIGRAVITY_DATA_DIR ?? '')
|
|
1257
|
+
.split(',')
|
|
1258
|
+
.map((root) => root.trim())
|
|
1259
|
+
.filter(Boolean)
|
|
1260
|
+
.map((root) => (isDir(join(root, 'conversations')) ? join(root, 'conversations') : root));
|
|
1261
|
+
|
|
1262
|
+
function byPathComponents(a, b) {
|
|
1263
|
+
const x = a.split(sep);
|
|
1264
|
+
const y = b.split(sep);
|
|
1265
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
1266
|
+
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
|
1267
|
+
}
|
|
1268
|
+
return x.length - y.length;
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
/** @returns {Promise<{ path: string, real: string }[]>} */
|
|
1272
|
+
async function antigravityDatabases(dirs) {
|
|
1273
|
+
const byRealPath = new Map();
|
|
1274
|
+
for (const dir of dirs) {
|
|
1275
|
+
for await (const path of walk(dir, (name) => name.endsWith('.db'))) {
|
|
1276
|
+
const real = await realpath(path).catch(() => path);
|
|
1277
|
+
if (!byRealPath.has(real)) byRealPath.set(real, { path, real });
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
return [...byRealPath.values()].sort((a, b) => byPathComponents(a.path, b.path));
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
function pbVarint(buf, pos) {
|
|
1284
|
+
let value = 0;
|
|
1285
|
+
for (let i = 0; i < 10; i++) {
|
|
1286
|
+
if (pos.i >= buf.length) throw new Error('truncated protobuf varint');
|
|
1287
|
+
const byte = buf[pos.i++];
|
|
1288
|
+
const payload = byte & 0x7f;
|
|
1289
|
+
if (i === 9 && payload > 1) break;
|
|
1290
|
+
value += payload * 2 ** (7 * i);
|
|
1291
|
+
if (!(byte & 0x80)) return value;
|
|
1292
|
+
}
|
|
1293
|
+
throw new Error('protobuf varint overflow');
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/** @returns {{ number: number, varint?: number, bytes?: Uint8Array }[]} */
|
|
1297
|
+
function pbDecode(buf) {
|
|
1298
|
+
const fields = [];
|
|
1299
|
+
const pos = { i: 0 };
|
|
1300
|
+
while (pos.i < buf.length) {
|
|
1301
|
+
const tag = pbVarint(buf, pos);
|
|
1302
|
+
const number = Math.floor(tag / 8);
|
|
1303
|
+
if (number === 0) throw new Error('protobuf field number is zero');
|
|
1304
|
+
const wire = tag % 8;
|
|
1305
|
+
if (wire === 0) fields.push({ number, varint: pbVarint(buf, pos) });
|
|
1306
|
+
else if (wire === 1 || wire === 5 || wire === 2) {
|
|
1307
|
+
const length = wire === 1 ? 8 : wire === 5 ? 4 : pbVarint(buf, pos);
|
|
1308
|
+
if (buf.length - pos.i < length) throw new Error('truncated protobuf value');
|
|
1309
|
+
if (wire === 2) fields.push({ number, bytes: buf.subarray(pos.i, pos.i + length) });
|
|
1310
|
+
else fields.push({ number });
|
|
1311
|
+
pos.i += length;
|
|
1312
|
+
} else throw new Error('unsupported protobuf wire type');
|
|
1313
|
+
}
|
|
1314
|
+
return fields;
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
const pbLastVarint = (fields, n) =>
|
|
1318
|
+
fields.findLast((f) => f.number === n && f.varint !== undefined)?.varint;
|
|
1319
|
+
const pbFirstBytes = (fields, n) => fields.find((f) => f.number === n && f.bytes)?.bytes;
|
|
1320
|
+
const pbStrictUtf8 = new TextDecoder('utf-8', { fatal: true });
|
|
1321
|
+
function pbLastText(fields, n) {
|
|
1322
|
+
const bytes = fields.findLast((f) => f.number === n && f.bytes)?.bytes;
|
|
1323
|
+
if (!bytes) return undefined;
|
|
1324
|
+
try {
|
|
1325
|
+
const text = pbStrictUtf8.decode(bytes);
|
|
1326
|
+
return text.trim() ? text : undefined;
|
|
1327
|
+
} catch {
|
|
1328
|
+
return undefined;
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
const AG_COUNTS = ['input', 'totalOutput', 'cacheWrite', 'cacheRead', 'reasoning', 'visible'];
|
|
1333
|
+
|
|
1334
|
+
function agUsage(buf) {
|
|
1335
|
+
const f = pbDecode(buf);
|
|
1336
|
+
return {
|
|
1337
|
+
modelId: pbLastVarint(f, 1) || undefined,
|
|
1338
|
+
input: pbLastVarint(f, 2) ?? 0,
|
|
1339
|
+
totalOutput: pbLastVarint(f, 3) ?? 0,
|
|
1340
|
+
cacheWrite: pbLastVarint(f, 4) ?? 0,
|
|
1341
|
+
cacheRead: pbLastVarint(f, 5) ?? 0,
|
|
1342
|
+
reasoning: pbLastVarint(f, 9) ?? 0,
|
|
1343
|
+
visible: pbLastVarint(f, 10) ?? 0,
|
|
1344
|
+
messageId: pbLastText(f, 7),
|
|
1345
|
+
responseId: pbLastText(f, 11),
|
|
1346
|
+
providerMessageId: pbLastText(f, 12)
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
const agIdentities = (u) =>
|
|
1351
|
+
[
|
|
1352
|
+
u.responseId && `response:${u.responseId}`,
|
|
1353
|
+
u.providerMessageId && `provider:${u.providerMessageId}`,
|
|
1354
|
+
u.messageId && `message:${u.messageId}`
|
|
1355
|
+
].filter(Boolean);
|
|
1356
|
+
|
|
1357
|
+
/**
|
|
1358
|
+
* The usage of a row's earlier attempts. The list also repeats the attempt already reported as
|
|
1359
|
+
* the row's primary usage, so one entry equal to the primary is dropped.
|
|
1360
|
+
*/
|
|
1361
|
+
function agRetries(fields, n, primary) {
|
|
1362
|
+
const retries = fields
|
|
1363
|
+
.filter((f) => f.number === n && f.bytes)
|
|
1364
|
+
.map((f) => pbFirstBytes(pbDecode(f.bytes), 2))
|
|
1365
|
+
.filter(Boolean)
|
|
1366
|
+
.map(agUsage);
|
|
1367
|
+
if (!primary) return retries;
|
|
1368
|
+
const keys = agIdentities(primary);
|
|
1369
|
+
const mirror = retries.findIndex(
|
|
1370
|
+
(r) =>
|
|
1371
|
+
r.modelId === primary.modelId &&
|
|
1372
|
+
AG_COUNTS.every((k) => r[k] === primary[k]) &&
|
|
1373
|
+
agIdentities(r).every((id) => keys.includes(id))
|
|
1374
|
+
);
|
|
1375
|
+
if (mirror >= 0) retries.splice(mirror, 1);
|
|
1376
|
+
return retries;
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
function agTimestamp(buf) {
|
|
1380
|
+
if (!buf) return undefined;
|
|
1381
|
+
const f = pbDecode(buf);
|
|
1382
|
+
const seconds = pbLastVarint(f, 1);
|
|
1383
|
+
if (!seconds || seconds > Number.MAX_SAFE_INTEGER / 1000) return undefined;
|
|
1384
|
+
const nanos = Math.min(pbLastVarint(f, 2) ?? 0, 999_999_999);
|
|
1385
|
+
const ms = seconds * 1000 + Math.floor(nanos / 1e6);
|
|
1386
|
+
// An implausible time falls through to the next source, so it cannot put a row in year 58854.
|
|
1387
|
+
return plausibleTime(ms) ? ms : undefined;
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
function agStepIndices(root) {
|
|
1391
|
+
const out = [];
|
|
1392
|
+
for (const f of root) {
|
|
1393
|
+
if (f.number !== 2) continue;
|
|
1394
|
+
if (f.varint !== undefined) {
|
|
1395
|
+
if (f.varint <= Number.MAX_SAFE_INTEGER) out.push(f.varint);
|
|
1396
|
+
} else if (f.bytes) {
|
|
1397
|
+
const pos = { i: 0 };
|
|
1398
|
+
while (pos.i < f.bytes.length) {
|
|
1399
|
+
try {
|
|
1400
|
+
out.push(pbVarint(f.bytes, pos));
|
|
1401
|
+
} catch {
|
|
1402
|
+
break;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
return out;
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
function agGeneration(buf) {
|
|
1411
|
+
const root = pbDecode(buf);
|
|
1412
|
+
const chatBytes = pbFirstBytes(root, 1);
|
|
1413
|
+
if (!chatBytes) throw new Error('missing chat model field 1');
|
|
1414
|
+
const chat = pbDecode(chatBytes);
|
|
1415
|
+
const usageBytes = pbFirstBytes(chat, 4);
|
|
1416
|
+
const usage = usageBytes && agUsage(usageBytes);
|
|
1417
|
+
const info = pbFirstBytes(chat, 9);
|
|
1418
|
+
return {
|
|
1419
|
+
model: pbLastText(chat, 19) ?? pbLastText(chat, 21),
|
|
1420
|
+
modelId: pbLastVarint(chat, 3) || undefined,
|
|
1421
|
+
usage,
|
|
1422
|
+
retries: agRetries(chat, 17, usage),
|
|
1423
|
+
ts: agTimestamp(info && pbFirstBytes(pbDecode(info), 4)),
|
|
1424
|
+
steps: agStepIndices(root)
|
|
1425
|
+
};
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
function agStep(buf) {
|
|
1429
|
+
const f = pbDecode(buf);
|
|
1430
|
+
const usageBytes = pbFirstBytes(f, 9);
|
|
1431
|
+
const usage = usageBytes && agUsage(usageBytes);
|
|
1432
|
+
const infoBytes = pbFirstBytes(f, 24);
|
|
1433
|
+
const info = infoBytes ? pbDecode(infoBytes) : [];
|
|
1434
|
+
return {
|
|
1435
|
+
model: pbLastText(info, 12) ?? pbLastText(info, 8),
|
|
1436
|
+
modelId: pbLastVarint(info, 1) || undefined,
|
|
1437
|
+
usage,
|
|
1438
|
+
retries: agRetries(f, 28, usage),
|
|
1439
|
+
ts: agTimestamp(pbFirstBytes(f, 8) ?? pbFirstBytes(f, 1))
|
|
1440
|
+
};
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
const AG_ID_MODELS = {
|
|
1444
|
+
246: 'gemini-2.5-pro',
|
|
1445
|
+
312: 'gemini-2.5-flash',
|
|
1446
|
+
313: 'gemini-2.5-flash-thinking',
|
|
1447
|
+
329: 'gemini-2.5-flash-thinking',
|
|
1448
|
+
330: 'gemini-2.5-flash-lite',
|
|
1449
|
+
281: 'claude-4-sonnet',
|
|
1450
|
+
282: 'claude-4-sonnet',
|
|
1451
|
+
290: 'claude-4-opus',
|
|
1452
|
+
291: 'claude-4-opus',
|
|
1453
|
+
333: 'claude-4.5-sonnet',
|
|
1454
|
+
334: 'claude-4.5-sonnet',
|
|
1455
|
+
340: 'claude-4.5-haiku',
|
|
1456
|
+
341: 'claude-4.5-haiku',
|
|
1457
|
+
342: 'model_openai_gpt_oss_120b_medium',
|
|
1458
|
+
1318: 'gemini-3.8-flash-high',
|
|
1459
|
+
1319: 'gemini-3.8-flash-medium',
|
|
1460
|
+
1320: 'gemini-3.8-flash-low',
|
|
1461
|
+
1298: 'gemini-3.7-flash-high',
|
|
1462
|
+
1299: 'gemini-3.7-flash-medium',
|
|
1463
|
+
1300: 'gemini-3.7-flash-low',
|
|
1464
|
+
1071: 'gemini-3.6-flash-high',
|
|
1465
|
+
1072: 'gemini-3.6-flash-medium',
|
|
1466
|
+
1073: 'gemini-3.6-flash-low',
|
|
1467
|
+
1417: 'gemini-4-argon',
|
|
1468
|
+
1418: 'gemini-4-argon',
|
|
1469
|
+
1419: 'gemini-4-argon',
|
|
1470
|
+
1402: 'claude-opus-5-5',
|
|
1471
|
+
1050: 'gemini-3.1-flash-lite'
|
|
1472
|
+
};
|
|
1473
|
+
const AG_PLACEHOLDER = 'model_placeholder_m';
|
|
1474
|
+
const AG_UNRESOLVED_ID = 'antigravity-model-';
|
|
1475
|
+
const AG_EFFORT_NAME = /^gemini (3\.[678]) flash \((high|medium|low)\)$/;
|
|
1476
|
+
const AG_NAMES = {
|
|
1477
|
+
'gemini 3.8 flash': 'gemini-3.8-flash',
|
|
1478
|
+
'gemini 3.8 flash thinking': 'gemini-3.8-flash',
|
|
1479
|
+
'gemini 3.7 flash': 'gemini-3.7-flash',
|
|
1480
|
+
'gemini 3.7 flash thinking': 'gemini-3.7-flash',
|
|
1481
|
+
'gemini 3.7 pro': 'gemini-3.7-pro',
|
|
1482
|
+
'gemini 3.7 pro thinking': 'gemini-3.7-pro',
|
|
1483
|
+
'gemini 3.6 flash': 'gemini-3.6-flash',
|
|
1484
|
+
'gemini 3 flash': 'gemini-3.6-flash',
|
|
1485
|
+
'gemini 3.6 pro': 'gemini-3.6-pro',
|
|
1486
|
+
'gemini 3 pro': 'gemini-3-pro',
|
|
1487
|
+
'gemini 3 pro thinking': 'gemini-3-pro',
|
|
1488
|
+
'gemini 2.5 flash': 'gemini-2.5-flash',
|
|
1489
|
+
'gemini 2.5 pro': 'gemini-2.5-pro',
|
|
1490
|
+
'gemini 2.0 flash': 'gemini-2.0-flash',
|
|
1491
|
+
'gemini 2 flash': 'gemini-2.0-flash',
|
|
1492
|
+
'gemini 2.0 pro': 'gemini-2.0-pro',
|
|
1493
|
+
'gemini 1.5 flash': 'gemini-1.5-flash',
|
|
1494
|
+
'gemini 1.5 pro': 'gemini-1.5-pro',
|
|
1495
|
+
model_placeholder_m318: 'gemini-3.8-flash-high',
|
|
1496
|
+
model_placeholder_m319: 'gemini-3.8-flash-medium',
|
|
1497
|
+
model_placeholder_m320: 'gemini-3.8-flash-low',
|
|
1498
|
+
model_placeholder_m298: 'gemini-3.7-flash-high',
|
|
1499
|
+
model_placeholder_m299: 'gemini-3.7-flash-medium',
|
|
1500
|
+
model_placeholder_m300: 'gemini-3.7-flash-low',
|
|
1501
|
+
model_placeholder_m71: 'gemini-3.6-flash-high',
|
|
1502
|
+
model_placeholder_m72: 'gemini-3.6-flash-medium',
|
|
1503
|
+
model_placeholder_m73: 'gemini-3.6-flash-low',
|
|
1504
|
+
model_placeholder_m417: 'gemini-4-argon',
|
|
1505
|
+
model_placeholder_m418: 'gemini-4-argon',
|
|
1506
|
+
model_placeholder_m419: 'gemini-4-argon',
|
|
1507
|
+
model_placeholder_m402: 'claude-opus-5-5',
|
|
1508
|
+
model_placeholder_m50: 'gemini-3.1-flash-lite',
|
|
1509
|
+
model_placeholder_m26: 'claude-opus-4-6',
|
|
1510
|
+
model_placeholder_m35: 'claude-sonnet-4-6',
|
|
1511
|
+
model_placeholder_m36: 'gemini-3.1-pro',
|
|
1512
|
+
model_placeholder_m37: 'gemini-3.1-pro',
|
|
1513
|
+
model_placeholder_m16: 'gemini-3.1-pro',
|
|
1514
|
+
model_placeholder_m18: 'gemini-3-flash-preview',
|
|
1515
|
+
model_placeholder_m84: 'gemini-3-flash-preview',
|
|
1516
|
+
model_placeholder_m47: 'gemini-3-flash-preview',
|
|
1517
|
+
model_placeholder_m132: 'gemini-3.5-flash-high',
|
|
1518
|
+
model_placeholder_m133: 'gemini-3.5-flash-high',
|
|
1519
|
+
model_placeholder_m187: 'gemini-3.5-flash-extra-low',
|
|
1520
|
+
model_placeholder_m20: 'gemini-3.5-flash-medium',
|
|
1521
|
+
model_openai_gpt_oss_120b_medium: 'gpt-oss-120b-medium',
|
|
1522
|
+
'gemini-pro-default': 'gemini-3.1-pro',
|
|
1523
|
+
'gemini-pro-agent': 'gemini-3.1-pro',
|
|
1524
|
+
'gemini-3-flash-agent': 'gemini-3.5-flash-high',
|
|
1525
|
+
'gemini-3-flash-agent-a': 'gemini-3.5-flash-high',
|
|
1526
|
+
'gemini-3-flash-agent-b': 'gemini-3.5-flash-high',
|
|
1527
|
+
'gemini-3-flash-a': 'gemini-3.5-flash-high',
|
|
1528
|
+
'gemini-3-flash-b': 'gemini-3.5-flash-high',
|
|
1529
|
+
'gemini-3-flash-c': 'gemini-3-flash-preview',
|
|
1530
|
+
'gemini-3-flash': 'gemini-3-flash-preview',
|
|
1531
|
+
'gemini-3.5-flash-low': 'gemini-3.5-flash-medium',
|
|
1532
|
+
'gemini-3.1-pro-high': 'gemini-3.1-pro',
|
|
1533
|
+
'gemini-3.1-pro-low': 'gemini-3.1-pro',
|
|
1534
|
+
'gemini-3-pro-high': 'gemini-3-pro',
|
|
1535
|
+
'gemini-3-pro-low': 'gemini-3-pro',
|
|
1536
|
+
'claude 3.7 sonnet': 'claude-3-7-sonnet',
|
|
1537
|
+
'claude 3.7 sonnet thinking': 'claude-3-7-sonnet',
|
|
1538
|
+
'claude 3.5 sonnet': 'claude-3-5-sonnet',
|
|
1539
|
+
'claude 3.5 haiku': 'claude-3-5-haiku',
|
|
1540
|
+
'claude 3 opus': 'claude-3-opus'
|
|
1541
|
+
};
|
|
1542
|
+
|
|
1543
|
+
function agModelName(raw) {
|
|
1544
|
+
const trimmed = raw?.trim();
|
|
1545
|
+
if (!trimmed) return undefined;
|
|
1546
|
+
const lower = trimmed.toLowerCase();
|
|
1547
|
+
const effort = AG_EFFORT_NAME.exec(lower);
|
|
1548
|
+
if (effort) return `gemini-${effort[1]}-flash-${effort[2]}`;
|
|
1549
|
+
const paren = lower.indexOf('(');
|
|
1550
|
+
const base = paren >= 0 ? lower.slice(0, paren).trim() : lower;
|
|
1551
|
+
if (Object.hasOwn(AG_NAMES, base)) return AG_NAMES[base];
|
|
1552
|
+
const dashed = base.replaceAll(' ', '-');
|
|
1553
|
+
return /^(gemini|claude|gpt)-/.test(dashed) ? dashed : trimmed;
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
const agModelFromId = (id) =>
|
|
1557
|
+
id
|
|
1558
|
+
? agModelName(
|
|
1559
|
+
AG_ID_MODELS[id] ??
|
|
1560
|
+
(id >= 1000 ? `${AG_PLACEHOLDER}${id - 1000}` : `${AG_UNRESOLVED_ID}${id}`)
|
|
1561
|
+
)
|
|
1562
|
+
: undefined;
|
|
1563
|
+
|
|
1564
|
+
const AG_MODEL = { DEFAULT: 0, PLACEHOLDER: 1, RESOLVED: 2 };
|
|
1565
|
+
const agResolution = (model) =>
|
|
1566
|
+
model === ANTIGRAVITY_DEFAULT_MODEL
|
|
1567
|
+
? AG_MODEL.DEFAULT
|
|
1568
|
+
: model.startsWith(AG_PLACEHOLDER) || model.startsWith(AG_UNRESOLVED_ID)
|
|
1569
|
+
? AG_MODEL.PLACEHOLDER
|
|
1570
|
+
: AG_MODEL.RESOLVED;
|
|
1571
|
+
const agResolved = (model) =>
|
|
1572
|
+
model !== undefined && agResolution(model) === AG_MODEL.RESOLVED ? model : undefined;
|
|
1573
|
+
|
|
1574
|
+
// Where an event's timestamp came from; a merge keeps the better source.
|
|
1575
|
+
const AG_TS = { FILE_MTIME: 0, TRAJECTORY: 1, OWN_ROW: 3 };
|
|
1576
|
+
|
|
1577
|
+
/**
|
|
1578
|
+
* One response, or after a merge every copy of it. `mtimeOf` names the database whose modification
|
|
1579
|
+
* time is the timestamp (rank FILE_MTIME), and is empty for any other rank.
|
|
1580
|
+
* @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
|
|
1581
|
+
*/
|
|
1582
|
+
|
|
1583
|
+
/**
|
|
1584
|
+
* @param {AgEvent[]} events
|
|
1585
|
+
* @param {Map<string, [number, number]>} idTimestamps
|
|
1586
|
+
*/
|
|
1587
|
+
function agAppendEvent(events, idTimestamps, usage, row) {
|
|
1588
|
+
if (!AG_COUNTS.some((k) => usage[k] > 0)) return;
|
|
1589
|
+
let identities = agIdentities(usage);
|
|
1590
|
+
if (!identities.length) identities = row.fallbackIdentities;
|
|
1591
|
+
const [ts, rank] =
|
|
1592
|
+
row.ts !== undefined
|
|
1593
|
+
? [row.ts, AG_TS.OWN_ROW]
|
|
1594
|
+
: (identities.map((id) => idTimestamps.get(id)).find(Boolean) ??
|
|
1595
|
+
(row.trajectoryTs !== undefined
|
|
1596
|
+
? [row.trajectoryTs, AG_TS.TRAJECTORY]
|
|
1597
|
+
: [row.fallbackTs, AG_TS.FILE_MTIME]));
|
|
1598
|
+
const totalOutput = Math.max(usage.totalOutput, usage.visible + usage.reasoning);
|
|
1599
|
+
const output = Math.max(usage.visible, totalOutput - usage.reasoning);
|
|
1600
|
+
const fromId = agModelFromId(usage.modelId);
|
|
1601
|
+
const rowModel = agModelName(row.model);
|
|
1602
|
+
const model =
|
|
1603
|
+
agResolved(fromId) ??
|
|
1604
|
+
(row.modelId === usage.modelId ? agResolved(rowModel) : undefined) ??
|
|
1605
|
+
fromId ??
|
|
1606
|
+
rowModel ??
|
|
1607
|
+
ANTIGRAVITY_DEFAULT_MODEL;
|
|
1608
|
+
for (const id of identities) {
|
|
1609
|
+
const old = idTimestamps.get(id);
|
|
1610
|
+
if (!old || rank > old[1] || (rank === old[1] && ts < old[0])) idTimestamps.set(id, [ts, rank]);
|
|
1611
|
+
}
|
|
1612
|
+
events.push({
|
|
1613
|
+
ts,
|
|
1614
|
+
rank,
|
|
1615
|
+
mtimeOf: '',
|
|
1616
|
+
session: row.session,
|
|
1617
|
+
model,
|
|
1618
|
+
input: usage.input,
|
|
1619
|
+
output,
|
|
1620
|
+
cacheWrite: usage.cacheWrite,
|
|
1621
|
+
cacheRead: usage.cacheRead,
|
|
1622
|
+
reasoning: Math.max(usage.reasoning, totalOutput - output),
|
|
1623
|
+
totalOutput,
|
|
1624
|
+
identities: [...identities]
|
|
1625
|
+
});
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
/** @returns {AgEvent[]} */
|
|
1629
|
+
function agDatabaseEvents(db, path, fallbackTs) {
|
|
1630
|
+
const session = basename(path, extname(path));
|
|
1631
|
+
db.exec('BEGIN');
|
|
1632
|
+
if (db.prepare('PRAGMA page_count').get().page_count === 0) return [];
|
|
1633
|
+
const hasTable = (name) =>
|
|
1634
|
+
!!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1").get(name);
|
|
1635
|
+
// CAST keeps a blob stored as TEXT byte for byte; read as a string, its invalid UTF-8 is lost.
|
|
1636
|
+
const blob = (v) => (v instanceof Uint8Array ? v : new Uint8Array());
|
|
1637
|
+
|
|
1638
|
+
let trajectoryTs;
|
|
1639
|
+
if (hasTable('trajectory_metadata_blob')) {
|
|
1640
|
+
const rows = db
|
|
1641
|
+
.prepare('SELECT CAST(data AS BLOB) AS data FROM trajectory_metadata_blob ORDER BY rowid ASC')
|
|
1642
|
+
.all();
|
|
1643
|
+
for (const row of rows) {
|
|
1644
|
+
const ts = agTimestamp(pbFirstBytes(pbDecode(blob(row.data)), 2));
|
|
1645
|
+
trajectoryTs ??= ts;
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
const generations = db
|
|
1649
|
+
.prepare('SELECT idx, CAST(data AS BLOB) AS data FROM gen_metadata ORDER BY idx ASC')
|
|
1650
|
+
.all()
|
|
1651
|
+
.map((row) => [row.idx, agGeneration(blob(row.data))]);
|
|
1652
|
+
const steps = hasTable('steps')
|
|
1653
|
+
? db
|
|
1654
|
+
.prepare(
|
|
1655
|
+
'SELECT idx, CAST(metadata AS BLOB) AS metadata FROM steps WHERE metadata IS NOT NULL ORDER BY idx ASC'
|
|
1656
|
+
)
|
|
1657
|
+
.all()
|
|
1658
|
+
.map((row) => [row.idx, agStep(blob(row.metadata))])
|
|
1659
|
+
: [];
|
|
1660
|
+
const rowModel = (m) => agModelName(m.model) ?? agModelFromId(m.modelId);
|
|
1661
|
+
const lastGenerationModel = generations.map(([, m]) => rowModel(m)).findLast(Boolean);
|
|
1662
|
+
|
|
1663
|
+
/** @type {AgEvent[]} */
|
|
1664
|
+
const events = [];
|
|
1665
|
+
const idTimestamps = new Map();
|
|
1666
|
+
const append = (usage, row) =>
|
|
1667
|
+
agAppendEvent(events, idTimestamps, usage, { trajectoryTs, fallbackTs, session, ...row });
|
|
1668
|
+
const appendRow = (kind, idx, m, row, fallbackIdentities) => {
|
|
1669
|
+
if (m.usage) append(m.usage, { ...row, fallbackIdentities });
|
|
1670
|
+
m.retries.forEach((retry, n) =>
|
|
1671
|
+
append(retry, {
|
|
1672
|
+
...row,
|
|
1673
|
+
// ccusage never merges a retry without ids, so each database counts its own. Naming the
|
|
1674
|
+
// file keeps the identity unique and lets a later run find the retry it counted.
|
|
1675
|
+
fallbackIdentities: [`retry:${path}:${kind}:${idx}:${n}`]
|
|
1676
|
+
})
|
|
1677
|
+
);
|
|
1678
|
+
};
|
|
1679
|
+
for (const [idx, m] of steps) {
|
|
1680
|
+
const row = { model: rowModel(m) ?? lastGenerationModel, modelId: m.modelId, ts: m.ts };
|
|
1681
|
+
appendRow('step', idx, m, row, [`step:${session}:${idx}`]);
|
|
1682
|
+
}
|
|
1683
|
+
let current;
|
|
1684
|
+
for (const [idx, m] of generations) {
|
|
1685
|
+
current = rowModel(m) ?? agModelFromId(m.usage?.modelId) ?? current;
|
|
1686
|
+
const row = { model: current, modelId: m.modelId, ts: m.ts };
|
|
1687
|
+
const linked = m.steps.map((step) => `step:${session}:${step}`);
|
|
1688
|
+
appendRow('gen', idx, m, row, linked.length ? linked : [`gen:${session}:${idx}`]);
|
|
1689
|
+
}
|
|
1690
|
+
return events;
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
function agMergeInto(target, copy) {
|
|
1694
|
+
for (const k of ['input', 'output', 'cacheWrite', 'cacheRead', 'reasoning']) {
|
|
1695
|
+
target[k] = Math.max(target[k], copy[k]);
|
|
1696
|
+
}
|
|
1697
|
+
target.totalOutput = Math.max(
|
|
1698
|
+
target.totalOutput,
|
|
1699
|
+
copy.totalOutput,
|
|
1700
|
+
target.output + target.reasoning
|
|
1701
|
+
);
|
|
1702
|
+
if (agResolution(copy.model) > agResolution(target.model)) target.model = copy.model;
|
|
1703
|
+
if (copy.rank > target.rank || (copy.rank === target.rank && copy.ts < target.ts)) {
|
|
1704
|
+
target.ts = copy.ts;
|
|
1705
|
+
target.rank = copy.rank;
|
|
1706
|
+
target.mtimeOf = copy.mtimeOf;
|
|
1707
|
+
}
|
|
1708
|
+
for (const id of copy.identities) {
|
|
1709
|
+
if (!target.identities.includes(id)) target.identities.push(id);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
function agMergeEvents(events) {
|
|
1714
|
+
const slots = [];
|
|
1715
|
+
const slotOf = new Map();
|
|
1716
|
+
for (const event of events) {
|
|
1717
|
+
const hits = [
|
|
1718
|
+
...new Set(event.identities.map((id) => slotOf.get(id)).filter((i) => i !== undefined))
|
|
1719
|
+
].sort((a, b) => a - b);
|
|
1720
|
+
if (!hits.length) {
|
|
1721
|
+
for (const id of event.identities) slotOf.set(id, slots.length);
|
|
1722
|
+
slots.push(event);
|
|
1723
|
+
continue;
|
|
1724
|
+
}
|
|
1725
|
+
const target = slots[hits[0]];
|
|
1726
|
+
for (const i of hits.slice(1)) {
|
|
1727
|
+
if (slots[i]) agMergeInto(target, slots[i]);
|
|
1728
|
+
slots[i] = null;
|
|
1729
|
+
}
|
|
1730
|
+
agMergeInto(target, event);
|
|
1731
|
+
for (const id of target.identities) slotOf.set(id, hits[0]);
|
|
1732
|
+
}
|
|
1733
|
+
return slots.filter(Boolean);
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
// No Antigravity model name has a slash, so one that does may be a file path, which must not leave
|
|
1737
|
+
// the machine.
|
|
1738
|
+
const agSchemaModel = (model) =>
|
|
1739
|
+
(!/[\\/]/.test(model) &&
|
|
1740
|
+
model
|
|
1741
|
+
.replace(/[^A-Za-z0-9._:@-]+/g, '-')
|
|
1742
|
+
.replace(/^-+|-+$/g, '')
|
|
1743
|
+
.slice(0, 100)) ||
|
|
1744
|
+
ANTIGRAVITY_DEFAULT_MODEL;
|
|
1745
|
+
|
|
1746
|
+
const AG_STORED = [
|
|
1747
|
+
'ts',
|
|
1748
|
+
'rank',
|
|
1749
|
+
'model',
|
|
1750
|
+
'input',
|
|
1751
|
+
'output',
|
|
1752
|
+
'cacheWrite',
|
|
1753
|
+
'cacheRead',
|
|
1754
|
+
'reasoning',
|
|
1755
|
+
'totalOutput',
|
|
1756
|
+
'tier',
|
|
1757
|
+
'session',
|
|
1758
|
+
'mtimeOf'
|
|
1759
|
+
];
|
|
1760
|
+
|
|
1761
|
+
/**
|
|
1762
|
+
* Keeps a counted group in `seen` so a later run can merge new copies into it and replace what it
|
|
1763
|
+
* added to its bucket. The first identity holds the AG_STORED fields followed by the group's other
|
|
1764
|
+
* identities, and each of those holds [ts, first identity]. Every entry starts with the group's
|
|
1765
|
+
* timestamp, which is what pruneState reads.
|
|
1766
|
+
* @param {State['seen']} seen @param {AgEvent} group
|
|
1767
|
+
*/
|
|
1768
|
+
function agStoreGroup(seen, group) {
|
|
1769
|
+
const [first, ...others] = group.identities;
|
|
1770
|
+
seen[first] = [...AG_STORED.map((field) => group[field]), ...others];
|
|
1771
|
+
for (const key of others) seen[key] = [group.ts, first];
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/** @param {State['seen']} seen @param {string} key @returns {AgEvent | undefined} */
|
|
1775
|
+
function agStoredGroup(seen, key) {
|
|
1776
|
+
let record = seen[key];
|
|
1777
|
+
if (Array.isArray(record) && typeof record[1] === 'string') {
|
|
1778
|
+
key = record[1];
|
|
1779
|
+
record = seen[key];
|
|
1780
|
+
}
|
|
1781
|
+
if (!Array.isArray(record) || typeof record[2] !== 'string') return undefined;
|
|
1782
|
+
return {
|
|
1783
|
+
...Object.fromEntries(AG_STORED.map((field, i) => [field, record[i]])),
|
|
1784
|
+
identities: [key, ...record.slice(AG_STORED.length)]
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
const agBucketRecord = (provider, group) => ({
|
|
1789
|
+
ts: group.ts,
|
|
1790
|
+
provider,
|
|
1791
|
+
model: group.model,
|
|
1792
|
+
tier: group.tier,
|
|
1793
|
+
session: group.session,
|
|
1794
|
+
input: group.input,
|
|
1795
|
+
cacheRead: group.cacheRead,
|
|
1796
|
+
cacheWrite5m: group.cacheWrite,
|
|
1797
|
+
cacheWrite1h: 0,
|
|
1798
|
+
output: group.totalOutput
|
|
1799
|
+
});
|
|
1800
|
+
|
|
1801
|
+
/** @type {Source['read']} */
|
|
1802
|
+
async function readAntigravity(dirs, ctx, provider) {
|
|
1803
|
+
const { state } = ctx;
|
|
1804
|
+
/** @type {AgEvent[]} */
|
|
1805
|
+
const events = [];
|
|
1806
|
+
const read = new Set();
|
|
1807
|
+
// Keyed by the real path: a root in ANTIGRAVITY_DATA_DIR can be a link to a default one, which
|
|
1808
|
+
// scan reads in an earlier pass.
|
|
1809
|
+
for (const { real: path } of await antigravityDatabases(dirs)) {
|
|
1810
|
+
if (ctx.seenPaths.has(path)) continue;
|
|
1811
|
+
ctx.seenPaths.add(path);
|
|
1812
|
+
let st;
|
|
1813
|
+
try {
|
|
1814
|
+
// A write in WAL mode may leave the main file as it was.
|
|
1815
|
+
const [main, wal] = await Promise.all([stat(path), stat(`${path}-wal`).catch(() => null)]);
|
|
1816
|
+
st = {
|
|
1817
|
+
size: main.size + (wal?.size ?? 0),
|
|
1818
|
+
mtimeMs: Math.max(main.mtimeMs, wal?.mtimeMs ?? 0),
|
|
1819
|
+
mainMtimeMs: Math.floor(main.mtimeMs)
|
|
1820
|
+
};
|
|
1821
|
+
} catch {
|
|
1822
|
+
continue;
|
|
1823
|
+
}
|
|
1824
|
+
if (st.mtimeMs < ctx.cutoffMs) {
|
|
1825
|
+
delete state.files[path];
|
|
1826
|
+
continue;
|
|
1827
|
+
}
|
|
1828
|
+
const prev = state.rescan?.includes(provider) ? undefined : state.files[path];
|
|
1829
|
+
if (prev && prev.size === st.size && prev.mtimeMs === st.mtimeMs) continue;
|
|
1830
|
+
let db;
|
|
1831
|
+
try {
|
|
1832
|
+
db = await openSqlite(path);
|
|
1833
|
+
if (!db) return;
|
|
1834
|
+
const database = shortHash(`antigravity-db:${path}`);
|
|
1835
|
+
for (const e of agDatabaseEvents(db, path, st.mainMtimeMs)) {
|
|
1836
|
+
events.push({
|
|
1837
|
+
...e,
|
|
1838
|
+
model: agSchemaModel(e.model),
|
|
1839
|
+
mtimeOf: e.rank === AG_TS.FILE_MTIME ? database : '',
|
|
1840
|
+
session: shortHash(`antigravity:${e.session}`),
|
|
1841
|
+
identities: e.identities.map((id) => `ag:${shortHash(id)}`)
|
|
1842
|
+
});
|
|
1843
|
+
}
|
|
1844
|
+
read.add(database);
|
|
1845
|
+
state.files[path] = { size: st.size, mtimeMs: st.mtimeMs, offset: 0 };
|
|
1846
|
+
ctx.filesRead++;
|
|
1847
|
+
ctx.parsedBytes += st.size;
|
|
1848
|
+
} catch (err) {
|
|
1849
|
+
log(`skipping unreadable Antigravity database ${basename(path)}: ${err.message}`);
|
|
1850
|
+
} finally {
|
|
1851
|
+
db?.close();
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
// An unchanged database is not read again, so its copies are known only through the groups
|
|
1856
|
+
// earlier runs stored. Merging those first, as ccusage would have read them first, and counting
|
|
1857
|
+
// the result in their place gives what one scan of every database gives.
|
|
1858
|
+
/** @type {Map<string, AgEvent>} */
|
|
1859
|
+
const stored = new Map();
|
|
1860
|
+
for (const key of events.flatMap((e) => e.identities)) {
|
|
1861
|
+
const group = agStoredGroup(state.seen, key);
|
|
1862
|
+
if (group) stored.set(group.identities[0], group);
|
|
1863
|
+
}
|
|
1864
|
+
for (const group of stored.values()) {
|
|
1865
|
+
removeRecord(state, agBucketRecord(provider, group));
|
|
1866
|
+
for (const key of group.identities) delete state.seen[key];
|
|
1867
|
+
// Its timestamp was that database's modification time, which this read replaces.
|
|
1868
|
+
if (group.rank === AG_TS.FILE_MTIME && read.has(group.mtimeOf)) group.ts = Infinity;
|
|
1869
|
+
}
|
|
1870
|
+
for (const group of agMergeEvents([...stored.values(), ...events])) {
|
|
1871
|
+
if (group.ts < ctx.cutoffMs) continue;
|
|
1872
|
+
group.tier = tierFor(
|
|
1873
|
+
ctx.resolvePrice(provider, group.model),
|
|
1874
|
+
group.input + group.cacheRead + group.cacheWrite
|
|
1875
|
+
);
|
|
1876
|
+
agStoreGroup(state.seen, group);
|
|
1877
|
+
addRecord(state, agBucketRecord(provider, group));
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
const GOOGLE_PRICE_PREFIXES = ['google/', 'gemini/', 'vertex_ai/', 'openrouter/google/'];
|
|
1882
|
+
|
|
1883
|
+
/**
|
|
1884
|
+
* Antigravity's names are not LiteLLM's: `claude-4.5-sonnet` is LiteLLM's `claude-sonnet-4-5`, and
|
|
1885
|
+
* some Gemini models are listed only as `-preview`.
|
|
1886
|
+
*/
|
|
1887
|
+
function antigravityPriceKeys(model) {
|
|
1888
|
+
const base = model.replace(/-(?:extra-low|low|medium|high|thinking)$/, '');
|
|
1889
|
+
const claude = /^claude-(\d+(?:\.\d+)?)-(opus|sonnet|haiku)$/.exec(base);
|
|
1890
|
+
const names = new Set([model, base]);
|
|
1891
|
+
if (claude) names.add(`claude-${claude[2]}-${claude[1].replace('.', '-')}`);
|
|
1892
|
+
names.add(`${base}-preview`);
|
|
1893
|
+
// LiteLLM dropped Anthropic's own keys for retired Claude models; this gateway still lists them
|
|
1894
|
+
// at Anthropic's price, and it is the entry ccusage's lookup lands on.
|
|
1895
|
+
const prefixes = base.startsWith('claude-')
|
|
1896
|
+
? ['', 'vercel_ai_gateway/anthropic/', ...GOOGLE_PRICE_PREFIXES]
|
|
1897
|
+
: ['', ...GOOGLE_PRICE_PREFIXES];
|
|
1898
|
+
return [...names].flatMap((name) => prefixes.map((prefix) => prefix + name));
|
|
1899
|
+
}
|
|
1900
|
+
|
|
996
1901
|
/**
|
|
997
1902
|
* @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
|
|
998
1903
|
* @typedef {{
|
|
999
1904
|
* paths: string[],
|
|
1000
1905
|
* envPaths: () => string[],
|
|
1001
1906
|
* read: (paths: string[], ctx: ReadContext, provider: string) => Promise<void>,
|
|
1002
|
-
* priceKeys: (model: string) => string[]
|
|
1907
|
+
* priceKeys: (model: string) => string[],
|
|
1908
|
+
* experimental?: boolean
|
|
1003
1909
|
* }} Source
|
|
1004
1910
|
*/
|
|
1005
1911
|
|
|
@@ -1016,6 +1922,7 @@ const fromEnv = (name, ...rest) => (process.env[name] ? [join(process.env[name],
|
|
|
1016
1922
|
* data whole on every run and skips what it counted before through `state.seen`, keyed with a
|
|
1017
1923
|
* provider prefix and valued with the record's timestamp so pruneState can drop it.
|
|
1018
1924
|
* - `priceKeys`: the LiteLLM keys to try for a model, in order.
|
|
1925
|
+
* - `experimental`: read only when BIG_SPENDER_EXPERIMENTAL names it; see enabledSources.
|
|
1019
1926
|
*
|
|
1020
1927
|
* @type {Record<string, Source>}
|
|
1021
1928
|
*/
|
|
@@ -1090,13 +1997,44 @@ const SOURCES = {
|
|
|
1090
1997
|
const prefix = claude ? 'anthropic' : model.startsWith('gemini-') ? 'gemini' : 'openai';
|
|
1091
1998
|
return [...new Set([...litellmKeys(prefix)(name), `github_copilot/${model}`])];
|
|
1092
1999
|
}
|
|
2000
|
+
},
|
|
2001
|
+
antigravity: {
|
|
2002
|
+
experimental: true,
|
|
2003
|
+
paths: ANTIGRAVITY_ROOTS.map((root) => join(HOME, root, 'conversations')),
|
|
2004
|
+
envPaths: antigravityEnvDirs,
|
|
2005
|
+
read: readAntigravity,
|
|
2006
|
+
priceKeys: antigravityPriceKeys
|
|
2007
|
+
},
|
|
2008
|
+
gemini: {
|
|
2009
|
+
experimental: true,
|
|
2010
|
+
paths: [join(HOME, '.gemini', 'tmp')],
|
|
2011
|
+
envPaths: () =>
|
|
2012
|
+
(process.env.GEMINI_DATA_DIR ?? '')
|
|
2013
|
+
.split(',')
|
|
2014
|
+
.map((p) => p.trim())
|
|
2015
|
+
.filter(Boolean),
|
|
2016
|
+
read: readGemini,
|
|
2017
|
+
priceKeys: (model) => [
|
|
2018
|
+
...['gemini', 'vertex_ai', 'openrouter/google'].map((p) => `${p}/${model}`),
|
|
2019
|
+
model
|
|
2020
|
+
]
|
|
1093
2021
|
}
|
|
1094
2022
|
};
|
|
1095
2023
|
|
|
1096
|
-
|
|
2024
|
+
// An experimental source has not been checked against real usage yet, so it is read and sent only
|
|
2025
|
+
// when BIG_SPENDER_EXPERIMENTAL (comma-separated provider ids) names it. Turned off, its counted rows
|
|
2026
|
+
// stay in the state, so turning it on again replaces them instead of counting them twice.
|
|
2027
|
+
function enabledSources() {
|
|
2028
|
+
const optIn = new Set(
|
|
2029
|
+
(process.env.BIG_SPENDER_EXPERIMENTAL ?? '').split(',').map((id) => id.trim())
|
|
2030
|
+
);
|
|
2031
|
+
return Object.entries(SOURCES).filter(([id, source]) => !source.experimental || optIn.has(id));
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
/** @param {[string, Source][]} sources */
|
|
2035
|
+
async function scan(state, resolvePrice, cutoffMs, sources) {
|
|
1097
2036
|
/** @type {ReadContext} */
|
|
1098
2037
|
const ctx = { state, resolvePrice, cutoffMs, seenPaths: new Set(), filesRead: 0, parsedBytes: 0 };
|
|
1099
|
-
const sources = Object.entries(SOURCES);
|
|
1100
2038
|
for (const [provider, source] of sources) await source.read(source.paths, ctx, provider);
|
|
1101
2039
|
for (const [provider, source] of sources) await source.read(source.envPaths(), ctx, provider);
|
|
1102
2040
|
for (const path of Object.keys(state.files)) {
|
|
@@ -1578,21 +2516,24 @@ async function main() {
|
|
|
1578
2516
|
const resolvePrice = makePriceResolver(pricing.models);
|
|
1579
2517
|
const state = await loadState();
|
|
1580
2518
|
pruneState(state, coverageStartMs);
|
|
1581
|
-
|
|
2519
|
+
const sources = enabledSources();
|
|
2520
|
+
const enabled = new Set(sources.map(([id]) => id));
|
|
2521
|
+
await scan(state, resolvePrice, coverageStartMs, sources);
|
|
1582
2522
|
await saveState(state);
|
|
1583
2523
|
|
|
1584
|
-
const
|
|
2524
|
+
const buckets = Object.fromEntries(
|
|
2525
|
+
Object.entries(state.buckets).filter(([key]) => enabled.has(key.split('|')[1]))
|
|
2526
|
+
);
|
|
2527
|
+
const used = new Set(Object.keys(buckets).map((k) => k.split('|')[1]));
|
|
1585
2528
|
const device = buildSnapshot(
|
|
1586
|
-
|
|
2529
|
+
buckets,
|
|
1587
2530
|
(b, provider, model, tier) => costOf(resolvePrice(provider, model), tier, b),
|
|
1588
2531
|
{
|
|
1589
2532
|
deviceId: setting('DEVICE_ID'),
|
|
1590
2533
|
pricingSource: `litellm@${new Date(pricing.fetchedAt).toISOString().slice(0, 10)}`,
|
|
1591
2534
|
// Older servers require the claude and codex counts and reject any other key, so another
|
|
1592
2535
|
// provider's count is sent only once this device has used it.
|
|
1593
|
-
providers:
|
|
1594
|
-
(p) => p === 'claude' || p === 'codex' || used.has(p)
|
|
1595
|
-
),
|
|
2536
|
+
providers: [...enabled].filter((p) => p === 'claude' || p === 'codex' || used.has(p)),
|
|
1596
2537
|
nowMs,
|
|
1597
2538
|
coverageStartMs,
|
|
1598
2539
|
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', 'copilot'];
|
|
6
|
+
export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi', 'grok', 'copilot', 'antigravity', 'gemini'];
|
|
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,10 +12,12 @@ 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";
|
|
17
18
|
copilot: "copilot";
|
|
18
19
|
cursor: "cursor";
|
|
20
|
+
gemini: "gemini";
|
|
19
21
|
grok: "grok";
|
|
20
22
|
pi: "pi";
|
|
21
23
|
}>;
|
|
@@ -37,10 +39,12 @@ export declare const usageRowSchema: z.ZodObject<{
|
|
|
37
39
|
export declare const MAX_LIMIT_WINDOWS = 5000;
|
|
38
40
|
export declare const limitWindowSchema: z.ZodObject<{
|
|
39
41
|
provider: z.ZodEnum<{
|
|
42
|
+
antigravity: "antigravity";
|
|
40
43
|
claude: "claude";
|
|
41
44
|
codex: "codex";
|
|
42
45
|
copilot: "copilot";
|
|
43
46
|
cursor: "cursor";
|
|
47
|
+
gemini: "gemini";
|
|
44
48
|
grok: "grok";
|
|
45
49
|
pi: "pi";
|
|
46
50
|
}>;
|
|
@@ -62,10 +66,12 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
62
66
|
hour: "hour";
|
|
63
67
|
}>>;
|
|
64
68
|
provider: z.ZodEnum<{
|
|
69
|
+
antigravity: "antigravity";
|
|
65
70
|
claude: "claude";
|
|
66
71
|
codex: "codex";
|
|
67
72
|
copilot: "copilot";
|
|
68
73
|
cursor: "cursor";
|
|
74
|
+
gemini: "gemini";
|
|
69
75
|
grok: "grok";
|
|
70
76
|
pi: "pi";
|
|
71
77
|
}>;
|
|
@@ -90,8 +96,10 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
90
96
|
claude: z.ZodNumber;
|
|
91
97
|
codex: z.ZodNumber;
|
|
92
98
|
all: z.ZodNumber;
|
|
99
|
+
antigravity: z.ZodOptional<z.ZodNumber>;
|
|
93
100
|
copilot: z.ZodOptional<z.ZodNumber>;
|
|
94
101
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
102
|
+
gemini: z.ZodOptional<z.ZodNumber>;
|
|
95
103
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
96
104
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
97
105
|
}, z.core.$strict>>;
|
|
@@ -99,8 +107,10 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
99
107
|
claude: z.ZodNumber;
|
|
100
108
|
codex: z.ZodNumber;
|
|
101
109
|
all: z.ZodNumber;
|
|
110
|
+
antigravity: z.ZodOptional<z.ZodNumber>;
|
|
102
111
|
copilot: z.ZodOptional<z.ZodNumber>;
|
|
103
112
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
113
|
+
gemini: z.ZodOptional<z.ZodNumber>;
|
|
104
114
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
105
115
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
106
116
|
}, z.core.$strict>;
|
|
@@ -108,8 +118,10 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
108
118
|
claude: z.ZodNumber;
|
|
109
119
|
codex: z.ZodNumber;
|
|
110
120
|
all: z.ZodNumber;
|
|
121
|
+
antigravity: z.ZodOptional<z.ZodNumber>;
|
|
111
122
|
copilot: z.ZodOptional<z.ZodNumber>;
|
|
112
123
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
124
|
+
gemini: z.ZodOptional<z.ZodNumber>;
|
|
113
125
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
114
126
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
115
127
|
}, z.core.$strict>;
|
|
@@ -117,18 +129,22 @@ export declare const usageSnapshotSchema: z.ZodObject<{
|
|
|
117
129
|
claude: z.ZodNumber;
|
|
118
130
|
codex: z.ZodNumber;
|
|
119
131
|
all: z.ZodNumber;
|
|
132
|
+
antigravity: z.ZodOptional<z.ZodNumber>;
|
|
120
133
|
copilot: z.ZodOptional<z.ZodNumber>;
|
|
121
134
|
cursor: z.ZodOptional<z.ZodNumber>;
|
|
135
|
+
gemini: z.ZodOptional<z.ZodNumber>;
|
|
122
136
|
grok: z.ZodOptional<z.ZodNumber>;
|
|
123
137
|
pi: z.ZodOptional<z.ZodNumber>;
|
|
124
138
|
}, z.core.$strict>;
|
|
125
139
|
}, z.core.$strict>>;
|
|
126
140
|
limits: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
127
141
|
provider: z.ZodEnum<{
|
|
142
|
+
antigravity: "antigravity";
|
|
128
143
|
claude: "claude";
|
|
129
144
|
codex: "codex";
|
|
130
145
|
copilot: "copilot";
|
|
131
146
|
cursor: "cursor";
|
|
147
|
+
gemini: "gemini";
|
|
132
148
|
grok: "grok";
|
|
133
149
|
pi: "pi";
|
|
134
150
|
}>;
|
package/dist/schema.js
CHANGED
|
@@ -14,7 +14,16 @@ 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
|
+
'gemini'
|
|
26
|
+
];
|
|
18
27
|
// Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
|
|
19
28
|
// than a day: an hourly view would show when each machine is in use.
|
|
20
29
|
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, gemini.
|
|
15
|
+
# BIG_SPENDER_EXPERIMENTAL=antigravity
|