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

antigravityUsageReader.ts

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