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

antigravityUsageReader.ts

477 lines17.1 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/** Generation rows can hold megabytes of context; read one at a time to bound blocking statement.all(). */
174const GENERATION_PAGE_ROWS = 1;
175const STEP_PAGE_ROWS = 64;
176​
177const readDatabase = Effect.fn("readDatabase")(function* (
178 path: string,
179 sessionId: string,
180 fallbackTimestamp: number,
181) {
182 const sql = yield* SqlClient.SqlClient;
183 const decode = <A>(evaluate: () => A) =>
184 Effect.try({
185 try: evaluate,
186 catch: (cause) => new AntigravityDatabaseDecodeError({ path, cause }),
187 });
188 yield* sql.unsafe("PRAGMA busy_timeout = 100");
189 return yield* Effect.gen(function* () {
190 const tables = new Set(
191 (yield* sql.unsafe<{ readonly name: unknown }>(
192 "SELECT name FROM sqlite_master WHERE type = 'table'",
193 )).map((row) => row.name),
194 );
195 if (!tables.has("gen_metadata") && !tables.has("steps")) {
196 return yield* new AntigravityDatabaseDecodeError({ path });
197 }
198 // Seek by rowid regardless of indexes; idx normally aliases rowid, but sort for layouts where it does not.
199 const readMetadata = Effect.fnUntraced(function* (
200 query: string,
201 pageRows: number,
202 step: boolean,
203 ) {
204 const entries: Array<{ idx: number; entry: Metadata }> = [];
205 let after = -Infinity;
206 while (true) {
207 const rows = yield* sql
208 .unsafe<{
209 readonly row_id: number;
210 readonly idx: unknown;
211 readonly data: unknown;
212 }>(query, [after, pageRows])
213 .pipe(Effect.withTracerEnabled(false));
214 for (const row of rows) {
215 // Filter outside SQL to bound scans to one page, including rows without metadata.
216 if (step && row.data === null) continue;
217 const idx = row.idx;
218 if (typeof idx !== "number") {
219 return yield* new AntigravityDatabaseDecodeError({ path });
220 }
221 entries.push({ idx, entry: yield* decode(() => metadata(blob(row.data), step)) });
222 }
223 if (rows.length < pageRows) break;
224 after = rows[rows.length - 1]!.row_id;
225 yield* Effect.yieldNow;
226 }
227 return entries.sort((a, b) => a.idx - b.idx);
228 });
229 const generations = tables.has("gen_metadata")
230 ? yield* readMetadata(
231 "SELECT rowid AS row_id, idx, data FROM gen_metadata WHERE rowid > ? ORDER BY rowid LIMIT ?",
232 GENERATION_PAGE_ROWS,
233 false,
234 )
235 : [];
236 let trajectoryTimestamp: number | null = null;
237 if (tables.has("trajectory_metadata_blob")) {
238 for (const row of yield* sql.unsafe<{ readonly data: unknown }>(
239 "SELECT data FROM trajectory_metadata_blob",
240 )) {
241 trajectoryTimestamp ??= yield* decode(() => timestamp(nested(fields(blob(row.data)), 2)));
242 }
243 }
244 const steps = tables.has("steps")
245 ? yield* readMetadata(
246 "SELECT rowid AS row_id, idx, metadata AS data FROM steps WHERE rowid > ? ORDER BY rowid LIMIT ?",
247 STEP_PAGE_ROWS,
248 true,
249 )
250 : [];
251 return yield* decode(() =>
252 usageCandidates(sessionId, generations, steps, trajectoryTimestamp, fallbackTimestamp),
253 );
254 }).pipe(sql.withTransaction);
255});
256​
257function usageCandidates(
258 sessionId: string,
259 generations: ReadonlyArray<{ idx: number; entry: Metadata }>,
260 steps: ReadonlyArray<{ idx: number; entry: Metadata }>,
261 trajectoryTimestamp: number | null,
262 fallbackTimestamp: number,
263): UsageCandidate[] {
264 const records: UsageCandidate[] = [];
265 const generationModels = new Map(generations.map(({ idx, entry }) => [idx, entry.model]));
266 for (const [source, entries] of [
267 ["step", steps],
268 ["generation", generations],
269 ] as const) {
270 for (const [index, { idx, entry }] of entries.entries()) {
271 for (const [usageIndex, usage] of entry.usages.entries()) {
272 const outputTokens = Math.max(numberAt(usage, 3), numberAt(usage, 9) + numberAt(usage, 10));
273 const totals = {
274 uncachedInputTokens: numberAt(usage, 2),
275 cachedInputTokens: numberAt(usage, 5),
276 cacheCreationTokens: numberAt(usage, 4),
277 outputTokens,
278 reasoningTokens: Math.min(outputTokens, numberAt(usage, 9)),
279 };
280 if (
281 totals.uncachedInputTokens +
282 totals.cachedInputTokens +
283 totals.cacheCreationTokens +
284 outputTokens ===
285 0
286 )
287 continue;
288 const keys = ([11, 12, 7] as const).flatMap((key) => {
289 const id = textAt(usage, key);
290 return id ? [`antigravity:${key}:${id}`] : [];
291 });
292 const record: UsageRecord = {
293 provider: "antigravity",
294 sessionId,
295 timestampMs: entry.timestampMs ?? trajectoryTimestamp ?? fallbackTimestamp,
296 model:
297 MODEL_IDS[numberAt(usage, 1)] ||
298 entry.model ||
299 (source === "step" ? generationModels.get(idx) : "") ||
300 modelName("", numberAt(usage, 1)) ||
301 "antigravity-unknown",
302 totals,
303 reportedCostUsd: null,
304 speed: "standard",
305 dedupeKey: keys[0] ?? `antigravity:${sessionId}:${source}:${index}:${usageIndex}`,
306 };
307 records.push({
308 record,
309 keys,
310 timestampQuality: entry.timestampMs !== null ? 2 : trajectoryTimestamp !== null ? 1 : 0,
311 });
312 }
313 }
314 }
315 return records;
317​
318interface CachedDatabase {
319 readonly fingerprint: string;
320 readonly candidates: readonly UsageCandidate[];
322​
323/** Fingerprint canonical DB/WAL paths by size, mtime and ctime; WAL holds new rows, and ctime catches restored mtimes. */
324export const makeAntigravityUsageCache = () => new Map<string, CachedDatabase>();
325​
326export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* (
327 conversationsDirectories: string | readonly string[],
328 sinceMs: number,
329 cache?: Map<string, CachedDatabase>,
330) {
331 const fileSystem = yield* FileSystem.FileSystem;
332 const pathService = yield* Path.Path;
333 const roots =
334 typeof conversationsDirectories === "string"
335 ? [conversationsDirectories]
336 : conversationsDirectories;
337 const files: Array<{ root: string; path: string; records: UsageRecord[] }> = [];
338 const errors: string[] = [];
339 const identities = new Map<string, number>();
340 const groups: Array<
341 UsageCandidate & { parent: number; size: number; owner: number; fileIndex: number }
342 > = [];
343 const find = (index: number): number => {
344 let root = index;
345 while (groups[root]!.parent !== root) root = groups[root]!.parent;
346 while (index !== root) {
347 const parent = groups[index]!.parent;
348 groups[index]!.parent = root;
349 index = parent;
350 }
351 return root;
352 };
353 const merge = (left: number, right: number): number => {
354 let a = find(left);
355 let b = find(right);
356 if (a === b) return a;
357 if (groups[a]!.size < groups[b]!.size) [a, b] = [b, a];
358 const target = groups[a]!;
359 const source = groups[b]!;
360 const first = target.owner < source.owner ? target : source;
361 const bestTime =
362 source.timestampQuality > target.timestampQuality ||
363 (source.timestampQuality === target.timestampQuality &&
364 source.record.timestampMs < target.record.timestampMs)
365 ? source
366 : target;
367 const x = target.record.totals;
368 const y = source.record.totals;
369 target.record = {
370 ...first.record,
371 model:
372 first.record.model === "antigravity-unknown"
373 ? first === target
374 ? source.record.model
375 : target.record.model
376 : first.record.model,
377 timestampMs: bestTime.record.timestampMs,
378 totals: {
379 uncachedInputTokens: Math.max(x.uncachedInputTokens, y.uncachedInputTokens),
380 cachedInputTokens: Math.max(x.cachedInputTokens, y.cachedInputTokens),
381 cacheCreationTokens: Math.max(x.cacheCreationTokens, y.cacheCreationTokens),
382 outputTokens: Math.max(x.outputTokens, y.outputTokens),
383 reasoningTokens: Math.max(x.reasoningTokens, y.reasoningTokens),
384 },
385 };
386 target.timestampQuality = bestTime.timestampQuality;
387 target.owner = first.owner;
388 target.fileIndex = first.fileIndex;
389 target.size += source.size;
390 source.parent = a;
391 return a;
392 };
393 const append = (candidate: UsageCandidate, fileIndex: number) => {
394 const index = groups.length;
395 groups.push({ ...candidate, parent: index, size: 1, owner: index, fileIndex });
396 for (const key of candidate.keys) {
397 const existing = identities.get(key);
398 if (existing !== undefined) merge(index, existing);
399 identities.set(key, index);
400 }
401 };
402 const visited = new Set<string>();
403 const readFile = Effect.fn("readAntigravityUsage.readFile")(function* (path: string) {
404 const canonical = yield* fileSystem.realPath(path);
405 if (visited.has(canonical)) return null;
406 visited.add(canonical);
407 const fingerprintOf = (file: string) =>
408 Effect.tryPromise(() => NodeFSP.stat(file)).pipe(
409 Effect.map((stat) => ({ stat, part: `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` })),
410 );
411 const { stat, part } = yield* fingerprintOf(path);
412 const wal = yield* fingerprintOf(`${path}-wal`).pipe(Effect.option);
413 const fingerprint = `${part}/${wal._tag === "Some" ? wal.value.part : "-"}`;
414 const cached = cache?.get(canonical);
415 if (cached?.fingerprint === fingerprint) return cached.candidates;
416 const candidates = yield* readDatabase(
417 path,
418 pathService.basename(path, ".db"),
419 stat.mtimeMs,
420 ).pipe(Effect.provide(NodeSqliteClient.layer({ filename: path, readonly: true })));
421 cache?.set(canonical, { fingerprint, candidates });
422 return candidates;
423 });
424 const walk = Effect.fn("antigravityUsageReader.walk")(function* (
425 directory: string,
426 root: string,
427 ): Effect.fn.Return<void> {
428 const names = yield* fileSystem.readDirectory(directory).pipe(
429 Effect.catchTags({
430 PlatformError: (cause) => {
431 if (cause.reason._tag !== "NotFound") errors.push(directory);
432 return Effect.succeed(null);
433 },
434 }),
435 );
436 if (names === null) return;
437 names.sort((a, b) => a.localeCompare(b));
438 for (const name of names) {
439 const path = pathService.join(directory, name);
440 // Like a directory listing's entry types: symlinks are neither files nor directories.
441 const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));
442 const type = isLink
443 ? "SymbolicLink"
444 : yield* fileSystem.stat(path).pipe(
445 Effect.map((info) => info.type),
446 Effect.orElseSucceed(() => null),
447 );
448 if (type === "Directory") {
449 yield* walk(path, root);
450 } else if ((type === "File" || type === null) && name.endsWith(".db")) {
451 const candidates = yield* readFile(path).pipe(
452 Effect.catch(() => {
453 errors.push(path);
454 return Effect.succeed(null);
455 }),
456 );
457 if (candidates === null) continue;
458 const fileIndex = files.length;
459 files.push({ root, path, records: [] });
460 for (const [index, candidate] of candidates.entries()) {
461 append(candidate, fileIndex);
462 if (index % 256 === 255) yield* Effect.yieldNow;
463 }
464 }
465 }
466 });
467 for (const root of roots) yield* walk(root, root);
468 if (cache !== undefined) {
469 for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);
470 }
471 for (const [index, group] of groups.entries()) {
472 if (group.parent === index && group.record.timestampMs >= sinceMs) {
473 files[group.fileIndex]!.records.push(group.record);
474 }
475 }
476 return { files, errors };
477});