Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

antigravityUsageReader.ts

406 lines14.5 KB

1// node:sqlite reads live conversation databases while Node fs discovers them.
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeFSP from "node:fs/promises";
4import * as NodePath from "node:path";
5import * as NodeSqlite from "node:sqlite";
6import * as NodeTimersPromises from "node:timers/promises";
7​
8import type { UsageRecord } from "./usageTranscripts.ts";
9​
10type FieldValue = number | bigint | Uint8Array;
11type Fields = Map<number, FieldValue[]>;
12​
13/** Antigravity stores usage metadata as protobuf, independently of conversation text. */
14function fields(bytes: Uint8Array): Fields {
15 let offset = 0;
16 const result: Fields = new Map();
17 const varint = () => {
18 let value = 0n;
19 for (let shift = 0n; shift < 70n; shift += 7n) {
20 const byte = bytes[offset++];
21 if (byte === undefined || (shift === 63n && byte > 1)) {
22 throw new Error("Invalid Antigravity protobuf varint");
23 }
24 value |= BigInt(byte & 127) << shift;
25 if (byte < 128) {
26 return value > BigInt(Number.MAX_SAFE_INTEGER) ? value : Number(value);
27 }
28 }
29 throw new Error("Invalid Antigravity protobuf varint");
30 };
31 while (offset < bytes.length) {
32 const tag = varint();
33 if (typeof tag !== "number") throw new Error("Invalid protobuf field");
34 const number = Math.floor(tag / 8);
35 const wire = tag % 8;
36 if (number === 0) throw new Error("Invalid protobuf field");
37 let value: FieldValue;
38 if (wire === 0) {
39 value = varint();
40 } else if (wire === 1 || wire === 5 || wire === 2) {
41 const length = wire === 2 ? varint() : wire === 1 ? 8 : 4;
42 if (typeof length !== "number") throw new Error("Invalid protobuf field length");
43 if (length > bytes.length - offset) throw new Error("Truncated protobuf field");
44 value = bytes.subarray(offset, offset + length);
45 offset += length;
46 if (wire !== 2) continue;
47 } else {
48 throw new Error("Unsupported protobuf wire type");
49 }
50 const entries = result.get(number) ?? [];
51 entries.push(value);
52 result.set(number, entries);
53 }
54 return result;
56​
57const numberAt = (value: Fields, key: number) => {
58 const entry = value.get(key)?.[0];
59 return typeof entry === "number" ? entry : 0;
60};
61const bytesAt = (value: Fields, key: number) => {
62 const entry = value.get(key)?.[0];
63 return entry instanceof Uint8Array ? entry : undefined;
64};
65const nested = (value: Fields, key: number) => {
66 const bytes = bytesAt(value, key);
67 return bytes === undefined ? new Map<number, FieldValue[]>() : fields(bytes);
68};
69const textAt = (value: Fields, key: number) => {
70 const bytes = bytesAt(value, key);
71 return bytes === undefined ? "" : new TextDecoder("utf-8", { fatal: true }).decode(bytes).trim();
72};
73const timestamp = (value: Fields) => {
74 const seconds = numberAt(value, 1);
75 return seconds > 0 ? seconds * 1000 + Math.floor(numberAt(value, 2) / 1_000_000) : null;
76};
77​
78const MODEL_IDS: Record<number, string> = {
79 246: "gemini-2.5-pro",
80 312: "gemini-2.5-flash",
81 313: "gemini-2.5-flash-thinking",
82 329: "gemini-2.5-flash-thinking",
83 330: "gemini-2.5-flash-lite",
84 281: "claude-sonnet-4",
85 282: "claude-sonnet-4",
86 290: "claude-opus-4",
87 291: "claude-opus-4",
88 333: "claude-sonnet-4-5",
89 334: "claude-sonnet-4-5",
90 340: "claude-haiku-4-5",
91 341: "claude-haiku-4-5",
92 1026: "claude-opus-4-6",
93 1035: "claude-sonnet-4-6",
94 1016: "gemini-3.1-pro",
95 1036: "gemini-3.1-pro",
96 1037: "gemini-3.1-pro",
97 1018: "gemini-3-flash-preview",
98 1084: "gemini-3-flash-preview",
99 1047: "gemini-3-flash-preview",
100};
101​
102function modelName(name: string, id: number): string {
103 if (name) {
104 const normalized = name
105 .toLowerCase()
106 .replace(/\s*\([^)]*\)\s*$/, "")
107 .replaceAll(" ", "-");
108 if (normalized.startsWith("claude-")) {
109 return normalized
110 .replace(/^claude-(4(?:\.\d+)?)-(sonnet|opus|haiku)/, "claude-$2-$1")
111 .replaceAll(".", "-");
112 }
113 return normalized;
114 }
115 return MODEL_IDS[id] ?? (id > 0 ? `antigravity-model-${id}` : "");
117​
118interface Metadata {
119 model: string;
120 timestampMs: number | null;
121 usages: Fields[];
123​
124function metadata(bytes: Uint8Array, step: boolean): Metadata {
125 const root = fields(bytes);
126 if (!step && bytesAt(root, 1) === undefined) {
127 throw new Error("Missing Antigravity generation metadata");
128 }
129 const data = step ? root : nested(root, 1);
130 const model = step ? nested(data, 24) : data;
131 const usage = bytesAt(data, step ? 9 : 4);
132 const usages = usage === undefined ? [] : [fields(usage)];
133 for (const retry of data.get(step ? 28 : 17) ?? []) {
134 if (!(retry instanceof Uint8Array)) throw new Error("Invalid retry metadata");
135 const retryUsage = bytesAt(fields(retry), 2);
136 if (retryUsage !== undefined) usages.push(fields(retryUsage));
137 }
138 return {
139 model: modelName(
140 textAt(model, step ? 12 : 19) || textAt(model, step ? 8 : 21),
141 numberAt(model, step ? 1 : 3),
142 ),
143 timestampMs: step
144 ? (timestamp(nested(data, 8)) ?? timestamp(nested(data, 1)))
145 : timestamp(nested(nested(data, 9), 4)),
146 usages,
147 };
149​
150function blob(value: unknown): Uint8Array {
151 if (!(value instanceof Uint8Array)) throw new Error("Invalid Antigravity metadata blob");
152 return value;
154​
155interface UsageCandidate {
156 record: UsageRecord;
157 keys: readonly string[];
158 timestampQuality: number;
160​
161async function readDatabase(path: string, fallbackTimestamp: number): Promise<UsageCandidate[]> {
162 const db = new NodeSqlite.DatabaseSync(path, { readOnly: true });
163 try {
164 db.exec("PRAGMA busy_timeout = 100; BEGIN");
165 const tables = new Set(
166 db
167 .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
168 .all()
169 .map((row) => row.name),
170 );
171 if (!tables.has("gen_metadata") && !tables.has("steps")) {
172 throw new Error("Missing Antigravity usage tables");
173 }
174 const readMetadata = async (query: string, column: string, step: boolean) => {
175 const entries: Array<{ idx: number; entry: Metadata }> = [];
176 for (const row of db.prepare(query).iterate()) {
177 if (typeof row.idx !== "number") throw new Error("Invalid Antigravity metadata index");
178 entries.push({ idx: row.idx, entry: metadata(blob(row[column]), step) });
179 if (entries.length % 256 === 0) await NodeTimersPromises.setImmediate();
180 }
181 return entries;
182 };
183 const generations = tables.has("gen_metadata")
184 ? await readMetadata("SELECT idx, data FROM gen_metadata ORDER BY idx", "data", false)
185 : [];
186 let trajectoryTimestamp: number | null = null;
187 if (tables.has("trajectory_metadata_blob")) {
188 for (const row of db.prepare("SELECT data FROM trajectory_metadata_blob").iterate()) {
189 trajectoryTimestamp ??= timestamp(nested(fields(blob(row.data)), 2));
190 }
191 }
192 const steps = tables.has("steps")
193 ? await readMetadata(
194 "SELECT idx, metadata FROM steps WHERE metadata IS NOT NULL ORDER BY idx",
195 "metadata",
196 true,
197 )
198 : [];
199 const sessionId = NodePath.basename(path, ".db");
200 const records: UsageCandidate[] = [];
201 const generationModels = new Map(generations.map(({ idx, entry }) => [idx, entry.model]));
202 for (const [source, entries] of [
203 ["step", steps],
204 ["generation", generations],
205 ] as const) {
206 for (const [index, { idx, entry }] of entries.entries()) {
207 for (const [usageIndex, usage] of entry.usages.entries()) {
208 const outputTokens = Math.max(
209 numberAt(usage, 3),
210 numberAt(usage, 9) + numberAt(usage, 10),
211 );
212 const totals = {
213 uncachedInputTokens: numberAt(usage, 2),
214 cachedInputTokens: numberAt(usage, 5),
215 cacheCreationTokens: numberAt(usage, 4),
216 outputTokens,
217 reasoningTokens: Math.min(outputTokens, numberAt(usage, 9)),
218 };
219 if (
220 totals.uncachedInputTokens +
221 totals.cachedInputTokens +
222 totals.cacheCreationTokens +
223 outputTokens ===
224 0
225 )
226 continue;
227 const keys = ([11, 12, 7] as const).flatMap((key) => {
228 const id = textAt(usage, key);
229 return id ? [`antigravity:${key}:${id}`] : [];
230 });
231 const record: UsageRecord = {
232 provider: "antigravity",
233 sessionId,
234 timestampMs: entry.timestampMs ?? trajectoryTimestamp ?? fallbackTimestamp,
235 model:
236 MODEL_IDS[numberAt(usage, 1)] ||
237 entry.model ||
238 (source === "step" ? generationModels.get(idx) : "") ||
239 modelName("", numberAt(usage, 1)) ||
240 "antigravity-unknown",
241 totals,
242 reportedCostUsd: null,
243 speed: "standard",
244 dedupeKey: keys[0] ?? `antigravity:${sessionId}:${source}:${index}:${usageIndex}`,
245 };
246 records.push({
247 record,
248 keys,
249 timestampQuality: entry.timestampMs !== null ? 2 : trajectoryTimestamp !== null ? 1 : 0,
250 });
251 }
252 }
253 }
254 return records;
255 } finally {
256 db.close();
257 }
259​
260interface CachedDatabase {
261 readonly fingerprint: string;
262 readonly candidates: readonly UsageCandidate[];
264​
265/**
266 * Parsed databases keyed by canonical path. An entry is reused only while both
267 * the database and its `-wal` sidecar keep the same size, mtime and ctime: new
268 * rows land in the WAL without touching the main file until a checkpoint, and
269 * ctime moves on any content write even when mtime is restored.
270 */
271export const makeAntigravityUsageCache = () => new Map<string, CachedDatabase>();
272​
273/**
274 * Reads and merges aliases across every configured Antigravity store before date
275 * filtering. With a cache, databases unchanged since the previous read are not
276 * decoded again.
277 */
278export async function readAntigravityUsage(
279 conversationsDirectories: string | readonly string[],
280 sinceMs: number,
281 cache?: Map<string, CachedDatabase>,
282) {
283 const roots =
284 typeof conversationsDirectories === "string"
285 ? [conversationsDirectories]
286 : conversationsDirectories;
287 const files: Array<{ root: string; path: string; records: UsageRecord[] }> = [];
288 const errors: string[] = [];
289 const identities = new Map<string, number>();
290 const groups: Array<
291 UsageCandidate & { parent: number; size: number; owner: number; fileIndex: number }
292 > = [];
293 const find = (index: number): number => {
294 let root = index;
295 while (groups[root]!.parent !== root) root = groups[root]!.parent;
296 while (index !== root) {
297 const parent = groups[index]!.parent;
298 groups[index]!.parent = root;
299 index = parent;
300 }
301 return root;
302 };
303 const merge = (left: number, right: number): number => {
304 let a = find(left);
305 let b = find(right);
306 if (a === b) return a;
307 if (groups[a]!.size < groups[b]!.size) [a, b] = [b, a];
308 const target = groups[a]!;
309 const source = groups[b]!;
310 const first = target.owner < source.owner ? target : source;
311 const bestTime =
312 source.timestampQuality > target.timestampQuality ||
313 (source.timestampQuality === target.timestampQuality &&
314 source.record.timestampMs < target.record.timestampMs)
315 ? source
316 : target;
317 const x = target.record.totals;
318 const y = source.record.totals;
319 target.record = {
320 ...first.record,
321 model:
322 first.record.model === "antigravity-unknown"
323 ? first === target
324 ? source.record.model
325 : target.record.model
326 : first.record.model,
327 timestampMs: bestTime.record.timestampMs,
328 totals: {
329 uncachedInputTokens: Math.max(x.uncachedInputTokens, y.uncachedInputTokens),
330 cachedInputTokens: Math.max(x.cachedInputTokens, y.cachedInputTokens),
331 cacheCreationTokens: Math.max(x.cacheCreationTokens, y.cacheCreationTokens),
332 outputTokens: Math.max(x.outputTokens, y.outputTokens),
333 reasoningTokens: Math.max(x.reasoningTokens, y.reasoningTokens),
334 },
335 };
336 target.timestampQuality = bestTime.timestampQuality;
337 target.owner = first.owner;
338 target.fileIndex = first.fileIndex;
339 target.size += source.size;
340 source.parent = a;
341 return a;
342 };
343 const append = (candidate: UsageCandidate, fileIndex: number) => {
344 const index = groups.length;
345 groups.push({ ...candidate, parent: index, size: 1, owner: index, fileIndex });
346 for (const key of candidate.keys) {
347 const existing = identities.get(key);
348 if (existing !== undefined) merge(index, existing);
349 identities.set(key, index);
350 }
351 };
352 const visited = new Set<string>();
353 const walk = async (directory: string, root: string): Promise<void> => {
354 let entries;
355 try {
356 entries = await NodeFSP.readdir(directory, { withFileTypes: true });
357 } catch (error) {
358 if ((error as NodeJS.ErrnoException).code !== "ENOENT") errors.push(directory);
359 return;
360 }
361 entries.sort((a, b) => a.name.localeCompare(b.name));
362 for (const entry of entries) {
363 const path = NodePath.join(directory, entry.name);
364 if (entry.isDirectory()) {
365 await walk(path, root);
366 } else if (entry.isFile() && entry.name.endsWith(".db")) {
367 try {
368 const canonical = await NodeFSP.realpath(path);
369 if (visited.has(canonical)) continue;
370 visited.add(canonical);
371 const stat = await NodeFSP.stat(path);
372 const wal = await NodeFSP.stat(`${path}-wal`).catch(() => null);
373 const fingerprint = [stat, wal]
374 .map((file) => (file ? `${file.size}:${file.mtimeMs}:${file.ctimeMs}` : "-"))
375 .join("/");
376 const cached = cache?.get(canonical);
377 let candidates: readonly UsageCandidate[];
378 if (cached?.fingerprint === fingerprint) {
379 candidates = cached.candidates;
380 } else {
381 candidates = await readDatabase(path, stat.mtimeMs);
382 cache?.set(canonical, { fingerprint, candidates });
383 }
384 const fileIndex = files.length;
385 files.push({ root, path, records: [] });
386 for (const [index, candidate] of candidates.entries()) {
387 append(candidate, fileIndex);
388 if (index % 256 === 255) await NodeTimersPromises.setImmediate();
389 }
390 } catch {
391 errors.push(path);
392 }
393 }
394 }
395 };
396 for (const root of roots) await walk(root, root);
397 if (cache !== undefined) {
398 for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);
399 }
400 for (const [index, group] of groups.entries()) {
401 if (group.parent === index && group.record.timestampMs >= sinceMs) {
402 files[group.fileIndex]!.records.push(group.record);
403 }
404 }
405 return { files, errors };