big-spender 0.9.0 → 0.11.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 CHANGED
@@ -336,8 +336,10 @@ about 15 to 20 percent less.
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
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. |
339
340
 
340
- **Pricing.** Claude Code, Codex, pi, Grok Build, GitHub Copilot CLI and Antigravity use LiteLLM
341
+ **Pricing.** Claude Code, Codex, pi, Grok Build, GitHub Copilot CLI, Antigravity, Gemini CLI and OpenCode use LiteLLM
342
+ | OpenCode | `~/.local/share/opencode` (or `$XDG_DATA_HOME/opencode`), or `$OPENCODE_DATA_DIR` (comma-separated, replaces the default): `opencode.db` and pre-SQLite `storage/message/**/*.json` | Assistant messages, and `completed` compaction rows, from the 1.x `message` table, the 2.x `session_message` table and the JSON files. The first copy of a message id wins, because 2.x copies the 1.x rows; A 2.x fork's copies of its parent's rows keep the parent rows' times, so rows older than the fork are skipped, as OpenCode's own stats do; this holds after the parent is deleted, and a parent deleted before big-spender read it is not counted. Needs `node:sqlite` (Node 22.13+). OpenCode rewrites a running message, so each run reads the window again and adds what changed; an hour and model a message left are sent as a zero row, which takes them back on the server. Cache reads and writes are outside `input`. 1.x counts reasoning in `output`; 2.x does not, so it is added. `claude-agent` rows are skipped, because the Claude Code source counts them. A model id that is a file path, a URL, or ends in a model-file extension (`.gguf`, `.safetensors`, ...) is cut to its file name, without query or login; an address with no file name is sent as `local`. OpenCode's own `cost` is not used; a model is priced under the first upstream it was seen on. |
341
343
  `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
342
344
  Code and Codex try the exact model, then the `anthropic/` or `openai/` prefix, then without a date
343
345
  suffix. pi tries the LiteLLM prefixes of the providers pi supports too (`openrouter/`, `fireworks_ai/`,
@@ -347,7 +349,11 @@ both without a trailing `-build`. Antigravity tries the model, the model without
347
349
  suffix, Anthropic's spelling of a Claude name (`claude-sonnet-4-5` for `claude-4.5-sonnet`) and the
348
350
  `-preview` name, each bare and with the `google/`, `gemini/`, `vertex_ai/` and `openrouter/google/`
349
351
  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.
352
+ Gemini CLI tries `gemini/`, `vertex_ai/` and `openrouter/google/`, then the bare model. ccusage prices
353
+ Gemini from models.dev's `google/` entries first, and for `gemini-2.5-flash` that entry is $0.15
354
+ input and $1.25 output per million tokens, half of LiteLLM's (and models.dev's own `gemini/` entry)
355
+ $0.30 and $2.50. So ccusage shows about half the collector's cost for that model.
356
+ OpenCode tries the model, then under the upstream provider it ran on. Unknown models count with cost 0 and log a warning.
351
357
  Long-context tiers
352
358
  (`*_above_<N>k_tokens`) are applied per request; a missing cache price is derived from the base
353
359
  input price, also above a tier, as ccusage does. 1-hour cache writes use
@@ -358,7 +364,7 @@ for a dash in Claude model names (`claude-opus-4.6` is priced as `claude-opus-4-
358
364
  **Experimental sources.** A source whose counts match ccusage on test data but have not been checked
359
365
  against real usage yet is marked `experimental` in `SOURCES`. The collector reads and sends it only
360
366
  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
367
+ names it. Antigravity and Gemini CLI are gated this way. Removing it from the list stops sending its rows on the
362
368
  next run; adding it back recounts them without counting anything twice.
363
369
 
364
370
  **Adding a provider.** Add an entry to `SOURCES` in `src/collector.mjs`, the provider id to
@@ -35,7 +35,7 @@ import {
35
35
  writeFile
36
36
  } from 'node:fs/promises';
37
37
  import { homedir } from 'node:os';
38
- import { basename, dirname, extname, join, resolve, sep } from 'node:path';
38
+ import { basename, dirname, extname, isAbsolute, join, resolve, sep } from 'node:path';
39
39
  import { gzipSync } from 'node:zlib';
40
40
 
41
41
  const SCHEMA_VERSION = 1;
@@ -135,7 +135,10 @@ async function acquireLock() {
135
135
  * A seen entry is the first timestamp, or for Claude [first timestamp, output tokens counted].
136
136
  * A bare number on a Claude key means the counted output is unknown (state from an older version).
137
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
138
+ * Gemini keeps a file's counts under `gm:` and its path: [latest hour, counts]; see readGemini.
139
+ * For OpenCode it is [timestamp, tier, input, output, cache read, cache write, model, upstream,
140
+ * session].
141
+ * @typedef {number | [number, number] | [number, string] | [number, number, string, ...(number | string)[]] | [number, Record<string, any>] | (number | string)[]} Seen
139
142
  * One subscription usage window instance; see limitWindowSchema in src/schema.ts.
140
143
  * @typedef {{ provider: string, window: string, resetsAt: string, peakPercent: number, hitAt?: string }} Limit
141
144
  * @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
@@ -939,6 +942,214 @@ function copilotLineHandler(state, file, resolvePrice, cutoffMs, sessionDir) {
939
942
 
940
943
  const allJsonl = (dir) => walk(dir, (name) => name.endsWith('.jsonl'));
941
944
 
945
+ // Gemini CLI keeps each chat under ~/.gemini/tmp/<project hash>/chats, as a JSON file it rewrites
946
+ // after every message or as JSONL it appends to, and headless runs can save their stats there too.
947
+ // Every .json and .jsonl file under it is read with ccusage's rules for these shapes.
948
+
949
+ const GEMINI_TOKEN_KEYS = {
950
+ input: ['input', 'prompt', 'input_tokens', 'prompt_tokens'],
951
+ output: ['output', 'candidates', 'output_tokens', 'candidates_tokens'],
952
+ cached: ['cached', 'cached_tokens'],
953
+ thoughts: ['thoughts', 'reasoning', 'thoughts_tokens', 'reasoning_tokens'],
954
+ tool: ['tool', 'tool_tokens']
955
+ };
956
+ const GEMINI_TIME =
957
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{3})?(Z|[+-]\d{2}:\d{2})$/;
958
+ // Gemini's context is a few million tokens, so a larger count is corrupt. Capping each record also
959
+ // keeps a bucket's sum under the snapshot schema's limit.
960
+ const GEMINI_MAX_TOKENS = 1e9;
961
+
962
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
963
+ const nonEmpty = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
964
+ // Date.parse would roll an hour of 24 or February 30 over to the next day; ccusage rejects them.
965
+ const geminiTime = (v) => {
966
+ const m = typeof v === 'string' ? GEMINI_TIME.exec(v) : null;
967
+ if (!m) return undefined;
968
+ const [, y, mo, d, h, mi, sec] = m.map(Number);
969
+ const day = new Date(Date.UTC(y, mo - 1, d));
970
+ if (day.getUTCMonth() !== mo - 1 || day.getUTCDate() !== d || h > 23 || mi > 59 || sec > 59) {
971
+ return undefined;
972
+ }
973
+ const ms = Date.parse(v);
974
+ return plausibleTime(ms) ? ms : undefined;
975
+ };
976
+
977
+ /**
978
+ * One request's tokens. Headless stats always count cached tokens inside `input`; a chat message
979
+ * does when its total equals the parts without them, as Gemini's totalTokenCount does. Reasoning
980
+ * and whatever the total has beyond the parts are billed as output.
981
+ */
982
+ function geminiUsage(raw, cachedInInput) {
983
+ if (!isObject(raw)) return null;
984
+ const count = (v) => (typeof v === 'number' ? Math.trunc(Math.max(0, v)) : undefined);
985
+ const tokenKeys = [...Object.values(GEMINI_TOKEN_KEYS).flat(), 'total', 'total_tokens'];
986
+ if (tokenKeys.some((k) => typeof raw[k] === 'number' && !(raw[k] < GEMINI_MAX_TOKENS)))
987
+ return null;
988
+ const pick = (keys) => keys.map((k) => count(raw[k])).find((v) => v !== undefined) ?? 0;
989
+ const { input, output, cached, thoughts, tool } = Object.fromEntries(
990
+ Object.entries(GEMINI_TOKEN_KEYS).map(([name, keys]) => [name, pick(keys)])
991
+ );
992
+ const total = 'total' in raw ? count(raw.total) : count(raw.total_tokens);
993
+ const overlap = cachedInInput || (cached > 0 && total === input + output + thoughts + tool);
994
+ const prompt = (overlap ? input - Math.min(input, cached) : input) + tool;
995
+ const known = prompt + output + cached + thoughts;
996
+ const billedOutput = output + thoughts + Math.max(0, (total ?? known) - known);
997
+ if (!prompt && !cached && !billedOutput) return null;
998
+ return { input: prompt, cacheRead: cached, output: billedOutput };
999
+ }
1000
+
1001
+ /**
1002
+ * The usage events in one Gemini file, or null for a file that may be half written: JSON that
1003
+ * 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
1004
+ * and model carry over to the lines after it, and a message logged again with its id replaces
1005
+ * the earlier copy, as in ccusage.
1006
+ */
1007
+ function geminiEvents(path, text, mtimeMs) {
1008
+ const events = [];
1009
+ let session = basename(path).replace(/\.jsonl?$/, '');
1010
+ const push = (raw, model, ts, cachedInInput, id) => {
1011
+ const u = model && geminiUsage(raw, cachedInInput);
1012
+ if (u) events.push({ ...u, model, ts, session, id });
1013
+ };
1014
+ const pushStats = (o, model, ts) => {
1015
+ const stats = o.stats ?? (isObject(o.result) ? o.result.stats : undefined);
1016
+ if (!isObject(stats)) return;
1017
+ const before = events.length;
1018
+ if (isObject(stats.models)) {
1019
+ for (const [name, m] of Object.entries(stats.models)) {
1020
+ if (isObject(m)) push(m.tokens, nonEmpty(name), ts, true);
1021
+ }
1022
+ }
1023
+ if (events.length === before) push(stats, model ?? 'unknown', ts, true);
1024
+ };
1025
+ const sessionOf = (o) => nonEmpty(o.sessionId) ?? nonEmpty(o.session_id) ?? session;
1026
+ const direct = (o, model, fallbackMs) =>
1027
+ push(
1028
+ o.tokens,
1029
+ model,
1030
+ geminiTime(o.timestamp) ?? geminiTime(o.created_at) ?? fallbackMs,
1031
+ false,
1032
+ nonEmpty(o.id)
1033
+ );
1034
+
1035
+ if (path.endsWith('.jsonl')) {
1036
+ let model;
1037
+ const byId = new Map();
1038
+ const lines = text.split('\n');
1039
+ const last = lines.findLast((line) => line.trim());
1040
+ if (last !== undefined && parseJson(last) === null) return null;
1041
+ for (const line of lines) {
1042
+ const o = parseJson(line);
1043
+ if (!isObject(o)) continue;
1044
+ session = sessionOf(o);
1045
+ model = nonEmpty(o.model) ?? model;
1046
+ if (o.type !== 'gemini') {
1047
+ pushStats(o, model, geminiTime(o.timestamp) ?? mtimeMs);
1048
+ continue;
1049
+ }
1050
+ const n = events.length;
1051
+ direct(o, model, mtimeMs);
1052
+ const id = events[n]?.id;
1053
+ if (id === undefined) continue;
1054
+ if (byId.has(id)) events[byId.get(id)] = events.pop();
1055
+ else byId.set(id, n);
1056
+ }
1057
+ return events;
1058
+ }
1059
+ const o = parseJson(text);
1060
+ if (o === null) return null;
1061
+ if (!isObject(o)) return events;
1062
+ session = sessionOf(o);
1063
+ if (Array.isArray(o.messages)) {
1064
+ const start = geminiTime(o.startTime) ?? geminiTime(o.lastUpdated) ?? mtimeMs;
1065
+ for (const m of o.messages) {
1066
+ if (isObject(m) && m.type === 'gemini') direct(m, nonEmpty(m.model), start);
1067
+ }
1068
+ } else if (o.type === 'gemini') {
1069
+ direct(o, nonEmpty(o.model), mtimeMs);
1070
+ } else {
1071
+ pushStats(o, nonEmpty(o.model), geminiTime(o.timestamp) ?? mtimeMs);
1072
+ }
1073
+ return events;
1074
+ }
1075
+
1076
+ /**
1077
+ * Gemini rewrites its files, so a changed file is read whole and what it counts now replaces
1078
+ * what it counted before, as ccusage counts each file as it is. `state.seen` keeps each file's
1079
+ * counts per hour, model, tier and session so they can be taken back, also after the file was
1080
+ * skipped for a while (an experimental source turned off). A message updated, corrected or
1081
+ * removed in the file changes the count with it, and an hour or model it leaves is sent as a
1082
+ * zero row.
1083
+ * @type {Source['read']}
1084
+ */
1085
+ async function readGemini(paths, ctx, provider) {
1086
+ const { state, cutoffMs } = ctx;
1087
+ for (const dir of paths) {
1088
+ // A symlinked GEMINI_DATA_DIR reaches the same files as the default under another name.
1089
+ const root = await realpath(dir).catch(() => null);
1090
+ if (!root) continue;
1091
+ for await (const path of walk(root, (name) => /\.jsonl?$/.test(name))) {
1092
+ if (ctx.seenPaths.has(path)) continue;
1093
+ ctx.seenPaths.add(path);
1094
+ let st;
1095
+ let text;
1096
+ try {
1097
+ st = await stat(path);
1098
+ if (st.mtimeMs < cutoffMs) {
1099
+ delete state.files[path];
1100
+ continue;
1101
+ }
1102
+ const prev = state.files[path];
1103
+ const rescan = state.rescan?.includes(provider);
1104
+ if (!rescan && prev && prev.size === st.size && prev.mtimeMs === st.mtimeMs) continue;
1105
+ text = await readFile(path, 'utf8');
1106
+ } catch (err) {
1107
+ log(`skipping unreadable file: ${err.message}`);
1108
+ continue;
1109
+ }
1110
+ ctx.filesRead++;
1111
+ ctx.parsedBytes += st.size;
1112
+ const events = geminiEvents(path, text, st.mtimeMs);
1113
+ state.files[path] = { size: st.size, mtimeMs: st.mtimeMs, offset: st.size };
1114
+ // Half written: keep what it counted until the write completes and changes the file.
1115
+ if (!events) continue;
1116
+ /** @type {Record<string, ReturnType<typeof geminiRecord>>} */
1117
+ const counts = {};
1118
+ for (const e of events) {
1119
+ if (e.ts < cutoffMs) continue;
1120
+ const model = localModelName(e.model) || 'unknown';
1121
+ const tier = tierFor(ctx.resolvePrice(provider, model), e.input + e.cacheRead);
1122
+ const r = geminiRecord(e.ts, model, tier, shortHash(`gemini:${e.session}`));
1123
+ const c = (counts[`${recordBucketKey(r)}|${r.session}`] ??= r);
1124
+ c.input += e.input;
1125
+ c.cacheRead += e.cacheRead;
1126
+ c.output += e.output;
1127
+ }
1128
+ const seenKey = `gm:${shortHash(path)}`;
1129
+ const before = state.seen[seenKey];
1130
+ for (const r of Object.values(Array.isArray(before) ? before[1] : {})) removeRecord(state, r);
1131
+ for (const r of Object.values(counts)) addRecord(state, r);
1132
+ const latest = Math.max(...Object.values(counts).map((r) => r.ts));
1133
+ if (Number.isFinite(latest)) state.seen[seenKey] = [latest, counts];
1134
+ else delete state.seen[seenKey];
1135
+ }
1136
+ }
1137
+ }
1138
+
1139
+ /** A Gemini count for one hour, model, tier and session, in the shape addRecord takes. */
1140
+ const geminiRecord = (ts, model, tier, session) => ({
1141
+ ts: Math.floor(ts / HOUR_MS) * HOUR_MS,
1142
+ provider: 'gemini',
1143
+ model,
1144
+ tier,
1145
+ session,
1146
+ input: 0,
1147
+ cacheRead: 0,
1148
+ cacheWrite5m: 0,
1149
+ cacheWrite1h: 0,
1150
+ output: 0
1151
+ });
1152
+
942
1153
  /**
943
1154
  * A reader for JSONL logs that only grow: reads the files `files` lists under each path (every
944
1155
  * `*.jsonl` below it by default) and parses only the bytes added since the last run. `lines`
@@ -1689,6 +1900,249 @@ function antigravityPriceKeys(model) {
1689
1900
  return [...names].flatMap((name) => prefixes.map((prefix) => prefix + name));
1690
1901
  }
1691
1902
 
1903
+ // OpenCode keeps one record per assistant message and rewrites it while the message runs: in
1904
+ // SQLite (`message` in 1.x; `session_message` from 2.0, which copies the 1.x rows under the same
1905
+ // ids) and, before SQLite, in `storage/message/<session>/<message>.json`. A message id counts
1906
+ // from the first store that has it, 1.x rows first, so every `session_message` row left was
1907
+ // written by 2.x.
1908
+
1909
+ /**
1910
+ * @typedef {{ id: string, session: string, ts: number, model: string, upstream: string, tokens: any, separateReasoning: boolean }} OpenCodeMessage
1911
+ */
1912
+
1913
+ /** @type {Map<string, string>} */
1914
+ const opencodeUpstreams = new Map();
1915
+
1916
+ const OPENCODE_ALIASES = new Map([
1917
+ ['gemini-3-pro-high', 'gemini-3-pro-preview'],
1918
+ ['k2p6', 'kimi-k2.6']
1919
+ ]);
1920
+ const CLAUDE_DOTTED = /^(claude-(?:haiku|opus|sonnet)-)(\d+)\.(\d)/;
1921
+
1922
+ function opencodePriceKeys(model) {
1923
+ const resolved = OPENCODE_ALIASES.get(model) ?? model;
1924
+ // LiteLLM spells claude-opus-4.5 and claude-opus-45 as claude-opus-4-5.
1925
+ const normalized = CLAUDE_DOTTED.test(resolved)
1926
+ ? resolved.replace(CLAUDE_DOTTED, '$1$2-$3')
1927
+ : resolved.replace(/^(claude-(?:haiku|opus|sonnet)-\d)(\d)/, '$1-$2');
1928
+ const bases = [...new Set([resolved, normalized])];
1929
+ const upstream = opencodeUpstreams.get(model);
1930
+ // The upstream as ccusage spells it (zai_coding_plan), then its first word (zai).
1931
+ const prefixes = upstream
1932
+ ? [...new Set([upstream.replaceAll('-', '_'), upstream.split('-')[0]])]
1933
+ : [];
1934
+ return [...bases, ...prefixes.flatMap((p) => bases.map((b) => `${p}/${b}`))];
1935
+ }
1936
+
1937
+ /**
1938
+ * Cache reads and writes are outside `input`. OpenCode 1.x counts reasoning inside `output` and
1939
+ * records `total`. 2.x stores the visible output only (`output` minus reasoning) and no `total`,
1940
+ * so its reasoning is added back.
1941
+ */
1942
+ function opencodeTokens(t, separateReasoning) {
1943
+ const input = num(t?.input);
1944
+ const cacheRead = num(t?.cache?.read);
1945
+ const cacheWrite = num(t?.cache?.write);
1946
+ let output = num(t?.output);
1947
+ const total = num(t?.total);
1948
+ if (total) output = Math.max(output, total - input - cacheRead - cacheWrite);
1949
+ else if (separateReasoning) output += num(t?.reasoning);
1950
+ return { input, output, cacheRead, cacheWrite };
1951
+ }
1952
+
1953
+ async function opencodeDbPath(dir) {
1954
+ if (existsSync(join(dir, 'opencode.db'))) return join(dir, 'opencode.db');
1955
+ const names = await readdir(dir).catch(() => []);
1956
+ const channel = names.filter((n) => /^opencode-[A-Za-z0-9_-]+\.db$/.test(n)).sort()[0];
1957
+ return channel ? join(dir, channel) : null;
1958
+ }
1959
+
1960
+ function readOpenCodeDb(db, sinceMs, out) {
1961
+ const columns = (table) =>
1962
+ new Set(
1963
+ db
1964
+ .prepare('SELECT name FROM pragma_table_info(?)')
1965
+ .all(table)
1966
+ .map((r) => r.name)
1967
+ );
1968
+ const add = (r, separateReasoning) => {
1969
+ if (out.has(r.id)) return;
1970
+ out.set(r.id, { ...r, tokens: parseJson(r.tokens ?? 'null'), separateReasoning });
1971
+ };
1972
+ const v1 = columns('message');
1973
+ if (v1.has('data')) {
1974
+ const since = v1.has('time_created') ? 'time_created >= ? AND' : '';
1975
+ const rows = db
1976
+ .prepare(
1977
+ `SELECT id, session_id AS session, json_extract(data, '$.time.created') AS ts,
1978
+ json_extract(data, '$.modelID') AS model, json_extract(data, '$.providerID') AS upstream,
1979
+ json_extract(data, '$.tokens') AS tokens
1980
+ FROM message WHERE ${since} json_valid(data)`
1981
+ )
1982
+ .all(...(since ? [sinceMs] : []));
1983
+ for (const r of rows) add(r, false);
1984
+ }
1985
+ const v2 = columns('session_message');
1986
+ if (!v2.has('data') || !v2.has('type')) return;
1987
+ const sessions = columns('session_v2');
1988
+ // A 2.x fork starts with copies of its parent's rows, made when the fork is, that keep the
1989
+ // parent rows' time_created. OpenCode's own usage stats skip them the same way, and this needs
1990
+ // no parent row, so it holds after the parent is deleted.
1991
+ const forks =
1992
+ v2.has('time_created') && sessions.has('fork_session_id') && sessions.has('time_created');
1993
+ const since = v2.has('time_created') ? 'm.time_created >= ? AND' : '';
1994
+ const rows = db
1995
+ .prepare(
1996
+ `SELECT m.id, m.session_id AS session,
1997
+ coalesce(json_extract(m.data, '$.time.created'), ${v2.has('time_created') ? 'm.time_created' : 'NULL'}) AS ts,
1998
+ coalesce(json_extract(m.data, '$.model.id'), json_extract(m.data, '$.model.modelID'),
1999
+ json_extract(m.data, '$.modelID')) AS model,
2000
+ coalesce(json_extract(m.data, '$.model.providerID'), json_extract(m.data, '$.providerID')) AS upstream,
2001
+ json_extract(m.data, '$.tokens') AS tokens
2002
+ FROM session_message m
2003
+ ${forks ? 'LEFT JOIN session_v2 s ON s.id = m.session_id' : ''}
2004
+ WHERE ${since} json_valid(m.data) AND (m.type = 'assistant'
2005
+ OR (m.type = 'compaction' AND json_extract(m.data, '$.status') = 'completed'))
2006
+ ${forks ? 'AND (s.fork_session_id IS NULL OR m.time_created >= s.time_created)' : ''}`
2007
+ )
2008
+ .all(...(since ? [sinceMs] : []));
2009
+ for (const r of rows) add(r, true);
2010
+ }
2011
+
2012
+ async function readOpenCodeFiles(dir, sinceMs, out) {
2013
+ for await (const path of walk(join(dir, 'storage', 'message'), (name) =>
2014
+ name.endsWith('.json')
2015
+ )) {
2016
+ if (out.has(basename(path, '.json'))) continue;
2017
+ const st = await stat(path).catch(() => null);
2018
+ if (!st || st.mtimeMs < sinceMs) continue;
2019
+ const o = parseJson(await readFile(path, 'utf8').catch(() => ''));
2020
+ const id = typeof o?.id === 'string' ? o.id : basename(path, '.json');
2021
+ if (!o || out.has(id)) continue;
2022
+ out.set(id, {
2023
+ id,
2024
+ session: o.sessionID,
2025
+ ts: o.time?.created,
2026
+ model: o.modelID,
2027
+ upstream: o.providerID,
2028
+ tokens: o.tokens,
2029
+ separateReasoning: false
2030
+ });
2031
+ }
2032
+ }
2033
+
2034
+ const MODEL_FILE = /\.(?:gguf|ggml|bin|safetensors|onnx|pt|pth|ckpt|llamafile)$/i;
2035
+
2036
+ /**
2037
+ * A local model can be named by its path or a URL, which can carry a login, a query or a folder
2038
+ * name. Only a file name leaves the machine; an address without one becomes `local`.
2039
+ */
2040
+ function opencodeModelName(id) {
2041
+ const scheme = /^[A-Za-z][A-Za-z0-9+.-]*:/.exec(id)?.[0] ?? '';
2042
+ const rest = id.slice(scheme.length);
2043
+ // `scheme:/...`, `//host/...`, or anything with a query, fragment or login after a scheme.
2044
+ const address = /^[/\\]{2}/.test(rest) || (scheme !== '' && /^[/\\]|[?#@]/.test(rest));
2045
+ const path = address || /^[/~.\\]|\\/.test(rest) || (rest.includes('/') && MODEL_FILE.test(rest));
2046
+ const clean = (name) => name.replace(/[^A-Za-z0-9._:/@-]/g, '-').slice(0, 100);
2047
+ if (!path) return clean(id.replace(/[?#].*$/s, ''));
2048
+ const local = address ? rest.replace(/[?#].*$/s, '').replace(/^[/\\]{2}[^/\\]*/, '') : rest;
2049
+ const name = local
2050
+ .split(/[/\\]/)
2051
+ .pop()
2052
+ .replace(/[?#].*$/s, '');
2053
+ return clean(!name || name.includes('@') ? 'local' : name);
2054
+ }
2055
+
2056
+ function countOpenCode(ctx, provider, m) {
2057
+ if (typeof m.model !== 'string' || !m.model || typeof m.upstream !== 'string') return;
2058
+ // Claude Code writes its own transcript of these turns, and the claude source reads it.
2059
+ if (m.upstream === 'claude-agent') return;
2060
+ const ts = Number(m.ts);
2061
+ if (!Number.isFinite(ts) || ts < ctx.cutoffMs) return;
2062
+
2063
+ const model = opencodeModelName(m.model);
2064
+ if (!opencodeUpstreams.has(model)) opencodeUpstreams.set(model, m.upstream);
2065
+ const t = opencodeTokens(m.tokens, m.separateReasoning);
2066
+ const session = shortHash(`opencode:${m.session ?? 'unknown'}`);
2067
+ const counted =
2068
+ t.input || t.output || t.cacheRead || t.cacheWrite
2069
+ ? [
2070
+ ts,
2071
+ tierFor(ctx.resolvePrice(provider, model), t.input + t.cacheRead + t.cacheWrite),
2072
+ t.input,
2073
+ t.output,
2074
+ t.cacheRead,
2075
+ t.cacheWrite,
2076
+ model,
2077
+ m.upstream,
2078
+ session
2079
+ ]
2080
+ : null;
2081
+ const key = `o:${shortHash(m.id)}`;
2082
+ const prev = Array.isArray(ctx.state.seen[key]) ? ctx.state.seen[key] : null;
2083
+ if (!prev ? !counted : counted?.every((v, i) => v === prev[i])) return;
2084
+
2085
+ const add = ([at, tier, input, output, cacheRead, cacheWrite, modelAt = model], sign) => {
2086
+ addRecord(ctx.state, {
2087
+ ts: at,
2088
+ provider,
2089
+ model: modelAt,
2090
+ tier,
2091
+ session,
2092
+ input: sign * input,
2093
+ cacheRead: sign * cacheRead,
2094
+ cacheWrite5m: sign * cacheWrite,
2095
+ cacheWrite1h: 0,
2096
+ output: sign * output
2097
+ });
2098
+ };
2099
+ if (prev) add(prev, -1);
2100
+ if (counted) {
2101
+ add(counted, 1);
2102
+ ctx.state.seen[key] = counted;
2103
+ } else delete ctx.state.seen[key];
2104
+ // The session leaves the bucket the message left, unless another of its messages is there.
2105
+ const bucketOf = (c) => bucketKey(Math.floor(c[0] / HOUR_MS) * HOUR_MS, provider, c[6], c[1]);
2106
+ const left = prev && bucketOf(prev);
2107
+ if (left && (!counted || bucketOf(counted) !== left) && ctx.state.buckets[left]) {
2108
+ const stays = Object.entries(ctx.state.seen).some(
2109
+ ([k, v]) => k.startsWith('o:') && Array.isArray(v) && v[8] === session && bucketOf(v) === left
2110
+ );
2111
+ if (!stays) {
2112
+ const b = ctx.state.buckets[left];
2113
+ b.sessions = b.sessions.filter((s) => s !== session);
2114
+ }
2115
+ }
2116
+ }
2117
+
2118
+ async function readOpenCode(paths, ctx, provider) {
2119
+ // Usage kept from messages no longer on disk still needs its upstream to be priced.
2120
+ for (const [key, v] of Object.entries(ctx.state.seen)) {
2121
+ if (key.startsWith('o:') && Array.isArray(v) && !opencodeUpstreams.has(v[6])) {
2122
+ if (typeof v[7] === 'string') opencodeUpstreams.set(v[6], v[7]);
2123
+ }
2124
+ }
2125
+ if (!paths.length) return;
2126
+ /** @type {Map<string, OpenCodeMessage>} */
2127
+ const messages = new Map();
2128
+ for (const dir of new Set(paths.map((p) => resolve(p)))) {
2129
+ const file = await opencodeDbPath(dir);
2130
+ if (file) {
2131
+ let db;
2132
+ try {
2133
+ db = await openSqlite(file);
2134
+ if (db) readOpenCodeDb(db, ctx.cutoffMs, messages);
2135
+ } catch (err) {
2136
+ log(`skipping unreadable OpenCode database: ${err.message}`);
2137
+ } finally {
2138
+ db?.close();
2139
+ }
2140
+ }
2141
+ await readOpenCodeFiles(dir, ctx.cutoffMs, messages);
2142
+ }
2143
+ for (const m of messages.values()) countOpenCode(ctx, provider, m);
2144
+ }
2145
+
1692
2146
  /**
1693
2147
  * @typedef {{ state: State, resolvePrice: (provider: string, model: string) => any, cutoffMs: number, seenPaths: Set<string>, filesRead: number, parsedBytes: number }} ReadContext
1694
2148
  * @typedef {{
@@ -1795,6 +2249,33 @@ const SOURCES = {
1795
2249
  envPaths: antigravityEnvDirs,
1796
2250
  read: readAntigravity,
1797
2251
  priceKeys: antigravityPriceKeys
2252
+ },
2253
+ gemini: {
2254
+ experimental: true,
2255
+ paths: [join(HOME, '.gemini', 'tmp')],
2256
+ envPaths: () =>
2257
+ (process.env.GEMINI_DATA_DIR ?? '')
2258
+ .split(',')
2259
+ .map((p) => p.trim())
2260
+ .filter(Boolean),
2261
+ read: readGemini,
2262
+ priceKeys: (model) => [
2263
+ ...['gemini', 'vertex_ai', 'openrouter/google'].map((p) => `${p}/${model}`),
2264
+ model
2265
+ ]
2266
+ },
2267
+ opencode: {
2268
+ // Its default dir depends on XDG_DATA_HOME and, as in ccusage, OPENCODE_DATA_DIR
2269
+ // (comma-separated) replaces it, so both come from envPaths. No other source reads these files.
2270
+ paths: [],
2271
+ envPaths: () => {
2272
+ const dirs = process.env.OPENCODE_DATA_DIR?.split(',').map((p) => p.trim());
2273
+ if (dirs) return dirs.filter(Boolean);
2274
+ const xdg = process.env.XDG_DATA_HOME;
2275
+ return [join(xdg && isAbsolute(xdg) ? xdg : join(HOME, '.local', 'share'), 'opencode')];
2276
+ },
2277
+ read: readOpenCode,
2278
+ priceKeys: opencodePriceKeys
1798
2279
  }
1799
2280
  };
1800
2281
 
package/dist/history.js CHANGED
@@ -65,6 +65,16 @@ function dropOldestDays(rows, excess) {
65
65
  }
66
66
  return { rows: rows.slice(cut), days };
67
67
  }
68
+ const isEmpty = (r) => !r.sessions &&
69
+ !r.inputTokens &&
70
+ !r.cacheReadTokens &&
71
+ !r.cacheWrite5mTokens &&
72
+ !r.cacheWrite1hTokens &&
73
+ !r.outputTokens &&
74
+ !r.costUsd.input &&
75
+ !r.costUsd.cacheRead &&
76
+ !r.costUsd.cacheWrite &&
77
+ !r.costUsd.output;
68
78
  export function mergeSnapshots(stored, next) {
69
79
  const sorted = [...next.hourly].sort(compareRows);
70
80
  const fresh = sorted.filter(hasTokens);
package/dist/schema.d.ts CHANGED
@@ -3,7 +3,7 @@ export declare const EARLIEST_DATE = "2020-01-01T00:00:00Z";
3
3
  export declare const MAX_ROWS = 50000;
4
4
  export declare const DEVICE_ID: RegExp;
5
5
  export declare const CURSOR_DEVICE_ID = "cursor";
6
- export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi', 'grok', 'copilot', 'antigravity'];
6
+ export declare const PROVIDERS: readonly ['claude', 'codex', 'cursor', 'pi', 'grok', 'copilot', 'antigravity', 'gemini', 'opencode'];
7
7
  export declare const RANGES: readonly ['7d', '30d', '90d', 'all'];
8
8
  export declare const usageRowSchema: z.ZodObject<{
9
9
  hour: z.ZodISODateTime;
@@ -17,7 +17,9 @@ export declare const usageRowSchema: z.ZodObject<{
17
17
  codex: "codex";
18
18
  copilot: "copilot";
19
19
  cursor: "cursor";
20
+ gemini: "gemini";
20
21
  grok: "grok";
22
+ opencode: "opencode";
21
23
  pi: "pi";
22
24
  }>;
23
25
  model: z.ZodString;
@@ -43,7 +45,9 @@ export declare const limitWindowSchema: z.ZodObject<{
43
45
  codex: "codex";
44
46
  copilot: "copilot";
45
47
  cursor: "cursor";
48
+ gemini: "gemini";
46
49
  grok: "grok";
50
+ opencode: "opencode";
47
51
  pi: "pi";
48
52
  }>;
49
53
  window: z.ZodString;
@@ -69,7 +73,9 @@ export declare const usageSnapshotSchema: z.ZodObject<{
69
73
  codex: "codex";
70
74
  copilot: "copilot";
71
75
  cursor: "cursor";
76
+ gemini: "gemini";
72
77
  grok: "grok";
78
+ opencode: "opencode";
73
79
  pi: "pi";
74
80
  }>;
75
81
  model: z.ZodString;
@@ -96,7 +102,9 @@ export declare const usageSnapshotSchema: z.ZodObject<{
96
102
  antigravity: z.ZodOptional<z.ZodNumber>;
97
103
  copilot: z.ZodOptional<z.ZodNumber>;
98
104
  cursor: z.ZodOptional<z.ZodNumber>;
105
+ gemini: z.ZodOptional<z.ZodNumber>;
99
106
  grok: z.ZodOptional<z.ZodNumber>;
107
+ opencode: z.ZodOptional<z.ZodNumber>;
100
108
  pi: z.ZodOptional<z.ZodNumber>;
101
109
  }, z.core.$strict>>;
102
110
  '7d': z.ZodObject<{
@@ -106,7 +114,9 @@ export declare const usageSnapshotSchema: z.ZodObject<{
106
114
  antigravity: z.ZodOptional<z.ZodNumber>;
107
115
  copilot: z.ZodOptional<z.ZodNumber>;
108
116
  cursor: z.ZodOptional<z.ZodNumber>;
117
+ gemini: z.ZodOptional<z.ZodNumber>;
109
118
  grok: z.ZodOptional<z.ZodNumber>;
119
+ opencode: z.ZodOptional<z.ZodNumber>;
110
120
  pi: z.ZodOptional<z.ZodNumber>;
111
121
  }, z.core.$strict>;
112
122
  '30d': z.ZodObject<{
@@ -116,7 +126,9 @@ export declare const usageSnapshotSchema: z.ZodObject<{
116
126
  antigravity: z.ZodOptional<z.ZodNumber>;
117
127
  copilot: z.ZodOptional<z.ZodNumber>;
118
128
  cursor: z.ZodOptional<z.ZodNumber>;
129
+ gemini: z.ZodOptional<z.ZodNumber>;
119
130
  grok: z.ZodOptional<z.ZodNumber>;
131
+ opencode: z.ZodOptional<z.ZodNumber>;
120
132
  pi: z.ZodOptional<z.ZodNumber>;
121
133
  }, z.core.$strict>;
122
134
  '90d': z.ZodObject<{
@@ -126,7 +138,9 @@ export declare const usageSnapshotSchema: z.ZodObject<{
126
138
  antigravity: z.ZodOptional<z.ZodNumber>;
127
139
  copilot: z.ZodOptional<z.ZodNumber>;
128
140
  cursor: z.ZodOptional<z.ZodNumber>;
141
+ gemini: z.ZodOptional<z.ZodNumber>;
129
142
  grok: z.ZodOptional<z.ZodNumber>;
143
+ opencode: z.ZodOptional<z.ZodNumber>;
130
144
  pi: z.ZodOptional<z.ZodNumber>;
131
145
  }, z.core.$strict>;
132
146
  }, z.core.$strict>>;
@@ -137,7 +151,9 @@ export declare const usageSnapshotSchema: z.ZodObject<{
137
151
  codex: "codex";
138
152
  copilot: "copilot";
139
153
  cursor: "cursor";
154
+ gemini: "gemini";
140
155
  grok: "grok";
156
+ opencode: "opencode";
141
157
  pi: "pi";
142
158
  }>;
143
159
  window: z.ZodString;
package/dist/schema.js CHANGED
@@ -21,7 +21,9 @@ export const PROVIDERS = [
21
21
  'pi',
22
22
  'grok',
23
23
  'copilot',
24
- 'antigravity'
24
+ 'antigravity',
25
+ 'gemini',
26
+ 'opencode'
25
27
  ];
26
28
  // Public ranges. 7d, 30d and 90d are bucketed by UTC day, `all` by ISO week. Nothing is finer
27
29
  // than a day: an hourly view would show when each machine is in use.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "big-spender",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Track what your AI coding agents would cost at API prices, across all your machines.",
5
5
  "keywords": [
6
6
  "ai",
@@ -11,5 +11,5 @@ BIG_SPENDER_INGEST_TOKEN=
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
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.
14
+ # data but have not been checked against real usage yet. Available: antigravity, gemini.
15
15
  # BIG_SPENDER_EXPERIMENTAL=antigravity