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

antigravityUsageReader.ts

487 lines17.6 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's File.Info has no ctime, which the cache fingerprint needs.
2import * as NodeFSP from "node:fs/promises";
3​
4import type { UsageRecord } from "@t3tools/provider-core/server/usage";
5import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as SqlClient from "effect/sql/SqlClient";
12​
13type FieldValue = number | bigint | Uint8Array;
14type Fields = Map<number, FieldValue[]>;
15​
16function fields(bytes: Uint8Array): Fields {
17 let offset = 0;
18 const result: Fields = new Map();
19 const varint = () => {
20 let value = 0n;
21 for (let shift = 0n; shift < 70n; shift += 7n) {
22 const byte = bytes[offset++];
23 if (byte === undefined || (shift === 63n && byte > 1)) {
24 throw new Error("Invalid Antigravity protobuf varint");
25 }
26 value |= BigInt(byte & 127) << shift;
27 if (byte < 128) {
28 return value > BigInt(Number.MAX_SAFE_INTEGER) ? value : Number(value);
29 }
30 }
31 throw new Error("Invalid Antigravity protobuf varint");
32 };
33 while (offset < bytes.length) {
34 const tag = varint();
35 if (typeof tag !== "number") throw new Error("Invalid protobuf field");
36 const number = Math.floor(tag / 8);
37 const wire = tag % 8;
38 if (number === 0) throw new Error("Invalid protobuf field");
39 let value: FieldValue;
40 if (wire === 0) {
41 value = varint();
42 } else if (wire === 1 || wire === 5 || wire === 2) {
43 const length = wire === 2 ? varint() : wire === 1 ? 8 : 4;
44 if (typeof length !== "number") throw new Error("Invalid protobuf field length");
45 if (length > bytes.length - offset) throw new Error("Truncated protobuf field");
46 value = bytes.subarray(offset, offset + length);
47 offset += length;
48 if (wire !== 2) continue;
49 } else {
50 throw new Error("Unsupported protobuf wire type");
51 }
52 const entries = result.get(number) ?? [];
53 entries.push(value);
54 result.set(number, entries);
55 }
56 return result;
58​
59const numberAt = (value: Fields, key: number) => {
60 const entry = value.get(key)?.[0];
61 return typeof entry === "number" ? entry : 0;
62};
63const bytesAt = (value: Fields, key: number) => {
64 const entry = value.get(key)?.[0];
65 return entry instanceof Uint8Array ? entry : undefined;
66};
67const nested = (value: Fields, key: number) => {
68 const bytes = bytesAt(value, key);
69 return bytes === undefined ? new Map<number, FieldValue[]>() : fields(bytes);
70};
71const textAt = (value: Fields, key: number) => {
72 const bytes = bytesAt(value, key);
73 return bytes === undefined ? "" : new TextDecoder("utf-8", { fatal: true }).decode(bytes).trim();
74};
75const timestamp = (value: Fields) => {
76 const seconds = numberAt(value, 1);
77 return seconds > 0 ? seconds * 1000 + Math.floor(numberAt(value, 2) / 1_000_000) : null;
78};
79​
80const MODEL_IDS: Record<number, string> = {
81 246: "gemini-2.5-pro",
82 312: "gemini-2.5-flash",
83 313: "gemini-2.5-flash-thinking",
84 329: "gemini-2.5-flash-thinking",
85 330: "gemini-2.5-flash-lite",
86 281: "claude-sonnet-4",
87 282: "claude-sonnet-4",
88 290: "claude-opus-4",
89 291: "claude-opus-4",
90 333: "claude-sonnet-4-5",
91 334: "claude-sonnet-4-5",
92 340: "claude-haiku-4-5",
93 341: "claude-haiku-4-5",
94 1026: "claude-opus-4-6",
95 1035: "claude-sonnet-4-6",
96 1016: "gemini-3.1-pro",
97 1036: "gemini-3.1-pro",
98 1037: "gemini-3.1-pro",
99 1018: "gemini-3-flash-preview",
100 1084: "gemini-3-flash-preview",
101 1047: "gemini-3-flash-preview",
102};
103​
104function modelName(name: string, id: number): string {
105 if (name) {
106 const normalized = name
107 .toLowerCase()
108 .replace(/\s*\([^)]*\)\s*$/, "")
109 .replaceAll(" ", "-");
110 if (normalized.startsWith("claude-")) {
111 return normalized
112 .replace(/^claude-(4(?:\.\d+)?)-(sonnet|opus|haiku)/, "claude-$2-$1")
113 .replaceAll(".", "-");
114 }
115 return normalized;
116 }
117 return MODEL_IDS[id] ?? (id > 0 ? `antigravity-model-${id}` : "");
119​
120interface Metadata {
121 model: string;
122 timestampMs: number | null;
123 usages: Fields[];
125​
126function metadata(bytes: Uint8Array, step: boolean): Metadata {
127 const root = fields(bytes);
128 if (!step && bytesAt(root, 1) === undefined) {
129 throw new Error("Missing Antigravity generation metadata");
130 }
131 const data = step ? root : nested(root, 1);
132 const model = step ? nested(data, 24) : data;
133 const usage = bytesAt(data, step ? 9 : 4);
134 // Copy the usage bytes: subarrays kept in usages would hold each row's whole blob alive.
135 const usages = usage === undefined ? [] : [fields(usage.slice())];
136 for (const retry of data.get(step ? 28 : 17) ?? []) {
137 if (!(retry instanceof Uint8Array)) throw new Error("Invalid retry metadata");
138 const retryUsage = bytesAt(fields(retry), 2);
139 if (retryUsage !== undefined) usages.push(fields(retryUsage.slice()));
140 }
141 return {
142 model: modelName(
143 textAt(model, step ? 12 : 19) || textAt(model, step ? 8 : 21),
144 numberAt(model, step ? 1 : 3),
145 ),
146 timestampMs: step
147 ? (timestamp(nested(data, 8)) ?? timestamp(nested(data, 1)))
148 : timestamp(nested(nested(data, 9), 4)),
149 usages,
150 };
152​
153function blob(value: unknown): Uint8Array {
154 if (!(value instanceof Uint8Array)) throw new Error("Invalid Antigravity metadata blob");
155 return value;
157​
158interface UsageCandidate {
159 record: UsageRecord;
160 keys: readonly string[];
161 timestampQuality: number;
163​
164class AntigravityDatabaseDecodeError extends Schema.TaggedError<AntigravityDatabaseDecodeError>()(
165 "AntigravityDatabaseDecodeError",
166 { path: Schema.String, cause: Schema.optional(Schema.Defect()) },
167) {
168 override get message(): string {
169 return `Antigravity usage could not be decoded from ${this.path}.`;
170 }
172​
173/**
174 * One statement.all() holds the event loop until every row it returns is in memory, and a
175 * generation row carries the conversation's whole context so far, often megabytes, so generations
176 * are read one at a time.
177 */
178const GENERATION_PAGE_ROWS = 1;
179const STEP_PAGE_ROWS = 64;
180​
181const readDatabase = Effect.fn("readDatabase")(function* (
182 path: string,
183 sessionId: string,
184 fallbackTimestamp: number,
185) {
186 const sql = yield* SqlClient.SqlClient;
187 const decode = <A>(evaluate: () => A) =>
188 Effect.try({
189 try: evaluate,
190 catch: (cause) => new AntigravityDatabaseDecodeError({ path, cause }),
191 });
192 yield* sql.unsafe("PRAGMA busy_timeout = 100");
193 return yield* Effect.gen(function* () {
194 const tables = new Set(
195 (yield* sql.unsafe<{ readonly name: unknown }>(
196 "SELECT name FROM sqlite_master WHERE type = 'table'",
197 )).map((row) => row.name),
198 );
199 if (!tables.has("gen_metadata") && !tables.has("steps")) {
200 return yield* new AntigravityDatabaseDecodeError({ path });
201 }
202 // A rowid seek works whatever the table's indexes. Antigravity declares idx as the INTEGER
203 // PRIMARY KEY, so rowid order is idx order; the sort keeps idx order where rows are stored
204 // otherwise.
205 const readMetadata = Effect.fnUntraced(function* (
206 query: string,
207 pageRows: number,
208 step: boolean,
209 ) {
210 const entries: Array<{ idx: number; entry: Metadata }> = [];
211 let after = -Infinity;
212 while (true) {
213 const rows = yield* sql
214 .unsafe<{
215 readonly row_id: number;
216 readonly idx: unknown;
217 readonly data: unknown;
218 }>(query, [after, pageRows])
219 .pipe(Effect.withTracerEnabled(false));
220 for (const row of rows) {
221 // Skipped here rather than in SQL, so a statement never scans past
222 // more than one page of steps that have no metadata.
223 if (step && row.data === null) continue;
224 const idx = row.idx;
225 if (typeof idx !== "number") {
226 return yield* new AntigravityDatabaseDecodeError({ path });
227 }
228 entries.push({ idx, entry: yield* decode(() => metadata(blob(row.data), step)) });
229 }
230 if (rows.length < pageRows) break;
231 after = rows[rows.length - 1]!.row_id;
232 yield* Effect.yieldNow;
233 }
234 return entries.sort((a, b) => a.idx - b.idx);
235 });
236 const generations = tables.has("gen_metadata")
237 ? yield* readMetadata(
238 "SELECT rowid AS row_id, idx, data FROM gen_metadata WHERE rowid > ? ORDER BY rowid LIMIT ?",
239 GENERATION_PAGE_ROWS,
240 false,
241 )
242 : [];
243 let trajectoryTimestamp: number | null = null;
244 if (tables.has("trajectory_metadata_blob")) {
245 for (const row of yield* sql.unsafe<{ readonly data: unknown }>(
246 "SELECT data FROM trajectory_metadata_blob",
247 )) {
248 trajectoryTimestamp ??= yield* decode(() => timestamp(nested(fields(blob(row.data)), 2)));
249 }
250 }
251 const steps = tables.has("steps")
252 ? yield* readMetadata(
253 "SELECT rowid AS row_id, idx, metadata AS data FROM steps WHERE rowid > ? ORDER BY rowid LIMIT ?",
254 STEP_PAGE_ROWS,
255 true,
256 )
257 : [];
258 return yield* decode(() =>
259 usageCandidates(sessionId, generations, steps, trajectoryTimestamp, fallbackTimestamp),
260 );
261 }).pipe(sql.withTransaction);
262});
263​
264function usageCandidates(
265 sessionId: string,
266 generations: ReadonlyArray<{ idx: number; entry: Metadata }>,
267 steps: ReadonlyArray<{ idx: number; entry: Metadata }>,
268 trajectoryTimestamp: number | null,
269 fallbackTimestamp: number,
270): UsageCandidate[] {
271 const records: UsageCandidate[] = [];
272 const generationModels = new Map(generations.map(({ idx, entry }) => [idx, entry.model]));
273 for (const [source, entries] of [
274 ["step", steps],
275 ["generation", generations],
276 ] as const) {
277 for (const [index, { idx, entry }] of entries.entries()) {
278 for (const [usageIndex, usage] of entry.usages.entries()) {
279 const outputTokens = Math.max(numberAt(usage, 3), numberAt(usage, 9) + numberAt(usage, 10));
280 const totals = {
281 uncachedInputTokens: numberAt(usage, 2),
282 cachedInputTokens: numberAt(usage, 5),
283 cacheCreationTokens: numberAt(usage, 4),
284 outputTokens,
285 reasoningTokens: Math.min(outputTokens, numberAt(usage, 9)),
286 };
287 if (
288 totals.uncachedInputTokens +
289 totals.cachedInputTokens +
290 totals.cacheCreationTokens +
291 outputTokens ===
292 0
293 )
294 continue;
295 const keys = ([11, 12, 7] as const).flatMap((key) => {
296 const id = textAt(usage, key);
297 return id ? [`antigravity:${key}:${id}`] : [];
298 });
299 const record: UsageRecord = {
300 provider: "antigravity",
301 sessionId,
302 timestampMs: entry.timestampMs ?? trajectoryTimestamp ?? fallbackTimestamp,
303 model:
304 MODEL_IDS[numberAt(usage, 1)] ||
305 entry.model ||
306 (source === "step" ? generationModels.get(idx) : "") ||
307 modelName("", numberAt(usage, 1)) ||
308 "antigravity-unknown",
309 totals,
310 reportedCostUsd: null,
311 speed: "standard",
312 dedupeKey: keys[0] ?? `antigravity:${sessionId}:${source}:${index}:${usageIndex}`,
313 };
314 records.push({
315 record,
316 keys,
317 timestampQuality: entry.timestampMs !== null ? 2 : trajectoryTimestamp !== null ? 1 : 0,
318 });
319 }
320 }
321 }
322 return records;
324​
325interface CachedDatabase {
326 readonly fingerprint: string;
327 readonly candidates: readonly UsageCandidate[];
329​
330/**
331 * Parsed databases keyed by canonical path. An entry is reused only while both
332 * the database and its `-wal` sidecar keep the same size, mtime and ctime: new
333 * rows land in the WAL without touching the main file until a checkpoint, and
334 * ctime moves on any content write even when mtime is restored.
335 */
336export const makeAntigravityUsageCache = () => new Map<string, CachedDatabase>();
337​
338export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* (
339 conversationsDirectories: string | readonly string[],
340 sinceMs: number,
341 cache?: Map<string, CachedDatabase>,
342) {
343 const fileSystem = yield* FileSystem.FileSystem;
344 const pathService = yield* Path.Path;
345 const roots =
346 typeof conversationsDirectories === "string"
347 ? [conversationsDirectories]
348 : conversationsDirectories;
349 const files: Array<{ root: string; path: string; records: UsageRecord[] }> = [];
350 const errors: string[] = [];
351 const identities = new Map<string, number>();
352 const groups: Array<
353 UsageCandidate & { parent: number; size: number; owner: number; fileIndex: number }
354 > = [];
355 const find = (index: number): number => {
356 let root = index;
357 while (groups[root]!.parent !== root) root = groups[root]!.parent;
358 while (index !== root) {
359 const parent = groups[index]!.parent;
360 groups[index]!.parent = root;
361 index = parent;
362 }
363 return root;
364 };
365 const merge = (left: number, right: number): number => {
366 let a = find(left);
367 let b = find(right);
368 if (a === b) return a;
369 if (groups[a]!.size < groups[b]!.size) [a, b] = [b, a];
370 const target = groups[a]!;
371 const source = groups[b]!;
372 const first = target.owner < source.owner ? target : source;
373 const bestTime =
374 source.timestampQuality > target.timestampQuality ||
375 (source.timestampQuality === target.timestampQuality &&
376 source.record.timestampMs < target.record.timestampMs)
377 ? source
378 : target;
379 const x = target.record.totals;
380 const y = source.record.totals;
381 target.record = {
382 ...first.record,
383 model:
384 first.record.model === "antigravity-unknown"
385 ? first === target
386 ? source.record.model
387 : target.record.model
388 : first.record.model,
389 timestampMs: bestTime.record.timestampMs,
390 totals: {
391 uncachedInputTokens: Math.max(x.uncachedInputTokens, y.uncachedInputTokens),
392 cachedInputTokens: Math.max(x.cachedInputTokens, y.cachedInputTokens),
393 cacheCreationTokens: Math.max(x.cacheCreationTokens, y.cacheCreationTokens),
394 outputTokens: Math.max(x.outputTokens, y.outputTokens),
395 reasoningTokens: Math.max(x.reasoningTokens, y.reasoningTokens),
396 },
397 };
398 target.timestampQuality = bestTime.timestampQuality;
399 target.owner = first.owner;
400 target.fileIndex = first.fileIndex;
401 target.size += source.size;
402 source.parent = a;
403 return a;
404 };
405 const append = (candidate: UsageCandidate, fileIndex: number) => {
406 const index = groups.length;
407 groups.push({ ...candidate, parent: index, size: 1, owner: index, fileIndex });
408 for (const key of candidate.keys) {
409 const existing = identities.get(key);
410 if (existing !== undefined) merge(index, existing);
411 identities.set(key, index);
412 }
413 };
414 const visited = new Set<string>();
415 const readFile = Effect.fn("readAntigravityUsage.readFile")(function* (path: string) {
416 const canonical = yield* fileSystem.realPath(path);
417 if (visited.has(canonical)) return null;
418 visited.add(canonical);
419 const fingerprintOf = (file: string) =>
420 Effect.tryPromise(() => NodeFSP.stat(file)).pipe(
421 Effect.map((stat) => ({ stat, part: `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` })),
422 );
423 const { stat, part } = yield* fingerprintOf(path);
424 const wal = yield* fingerprintOf(`${path}-wal`).pipe(Effect.option);
425 const fingerprint = `${part}/${wal._tag === "Some" ? wal.value.part : "-"}`;
426 const cached = cache?.get(canonical);
427 if (cached?.fingerprint === fingerprint) return cached.candidates;
428 const candidates = yield* readDatabase(
429 path,
430 pathService.basename(path, ".db"),
431 stat.mtimeMs,
432 ).pipe(Effect.provide(NodeSqliteClient.layer({ filename: path, readonly: true })));
433 cache?.set(canonical, { fingerprint, candidates });
434 return candidates;
435 });
436 const walk = (directory: string, root: string): Effect.Effect<void> =>
437 Effect.gen(function* () {
438 const names = yield* fileSystem.readDirectory(directory).pipe(
439 Effect.catchTags({
440 PlatformError: (cause) => {
441 if (cause.reason._tag !== "NotFound") errors.push(directory);
442 return Effect.succeed(null);
443 },
444 }),
445 );
446 if (names === null) return;
447 names.sort((a, b) => a.localeCompare(b));
448 for (const name of names) {
449 const path = pathService.join(directory, name);
450 // Like a directory listing's entry types: symlinks are neither files nor directories.
451 const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));
452 const type = isLink
453 ? "SymbolicLink"
454 : yield* fileSystem.stat(path).pipe(
455 Effect.map((info) => info.type),
456 Effect.orElseSucceed(() => null),
457 );
458 if (type === "Directory") {
459 yield* walk(path, root);
460 } else if ((type === "File" || type === null) && name.endsWith(".db")) {
461 const candidates = yield* readFile(path).pipe(
462 Effect.catch(() => {
463 errors.push(path);
464 return Effect.succeed(null);
465 }),
466 );
467 if (candidates === null) continue;
468 const fileIndex = files.length;
469 files.push({ root, path, records: [] });
470 for (const [index, candidate] of candidates.entries()) {
471 append(candidate, fileIndex);
472 if (index % 256 === 255) yield* Effect.yieldNow;
473 }
474 }
475 }
476 });
477 for (const root of roots) yield* walk(root, root);
478 if (cache !== undefined) {
479 for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);
480 }
481 for (const [index, group] of groups.entries()) {
482 if (group.parent === index && group.record.timestampMs >= sinceMs) {
483 files[group.fileIndex]!.records.push(group.record);
484 }
485 }
486 return { files, errors };
487});