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

antigravityUsageReader.ts

483 lines17.4 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​
104// ACP slugs append the thinking level, which shares the base model's price.
105function withRateModel(record: UsageRecord): UsageRecord {
106 const rateModel = record.model.replace(/-(?:low|medium|high)$/, "");
107 return rateModel === record.model ? record : { ...record, rateModel };
109​
110function modelName(name: string, id: number): string {
111 if (name) {
112 const normalized = name
113 .toLowerCase()
114 .replace(/\s*\([^)]*\)\s*$/, "")
115 .replaceAll(" ", "-");
116 if (normalized.startsWith("claude-")) {
117 return normalized
118 .replace(/^claude-(4(?:\.\d+)?)-(sonnet|opus|haiku)/, "claude-$2-$1")
119 .replaceAll(".", "-");
120 }
121 return normalized;
122 }
123 return MODEL_IDS[id] ?? (id > 0 ? `antigravity-model-${id}` : "");
125​
126interface Metadata {
127 model: string;
128 timestampMs: number | null;
129 usages: Fields[];
131​
132function metadata(bytes: Uint8Array, step: boolean): Metadata {
133 const root = fields(bytes);
134 if (!step && bytesAt(root, 1) === undefined) {
135 throw new Error("Missing Antigravity generation metadata");
136 }
137 const data = step ? root : nested(root, 1);
138 const model = step ? nested(data, 24) : data;
139 const usage = bytesAt(data, step ? 9 : 4);
140 // Copy the usage bytes: subarrays kept in usages would hold each row's whole blob alive.
141 const usages = usage === undefined ? [] : [fields(usage.slice())];
142 for (const retry of data.get(step ? 28 : 17) ?? []) {
143 if (!(retry instanceof Uint8Array)) throw new Error("Invalid retry metadata");
144 const retryUsage = bytesAt(fields(retry), 2);
145 if (retryUsage !== undefined) usages.push(fields(retryUsage.slice()));
146 }
147 return {
148 model: modelName(
149 textAt(model, step ? 12 : 19) || textAt(model, step ? 8 : 21),
150 numberAt(model, step ? 1 : 3),
151 ),
152 timestampMs: step
153 ? (timestamp(nested(data, 8)) ?? timestamp(nested(data, 1)))
154 : timestamp(nested(nested(data, 9), 4)),
155 usages,
156 };
158​
159function blob(value: unknown): Uint8Array {
160 if (!(value instanceof Uint8Array)) throw new Error("Invalid Antigravity metadata blob");
161 return value;
163​
164interface UsageCandidate {
165 record: UsageRecord;
166 keys: readonly string[];
167 timestampQuality: number;
169​
170class AntigravityDatabaseDecodeError extends Schema.TaggedError<AntigravityDatabaseDecodeError>()(
171 "AntigravityDatabaseDecodeError",
172 { path: Schema.String, cause: Schema.optional(Schema.Defect()) },
173) {
174 override get message(): string {
175 return `Antigravity usage could not be decoded from ${this.path}.`;
176 }
178​
179/** Generation rows can hold megabytes of context; read one at a time to bound blocking statement.all(). */
180const GENERATION_PAGE_ROWS = 1;
181const STEP_PAGE_ROWS = 64;
182​
183const readDatabase = Effect.fn("readDatabase")(function* (
184 path: string,
185 sessionId: string,
186 fallbackTimestamp: number,
187) {
188 const sql = yield* SqlClient.SqlClient;
189 const decode = <A>(evaluate: () => A) =>
190 Effect.try({
191 try: evaluate,
192 catch: (cause) => new AntigravityDatabaseDecodeError({ path, cause }),
193 });
194 yield* sql.unsafe("PRAGMA busy_timeout = 100");
195 return yield* Effect.gen(function* () {
196 const tables = new Set(
197 (yield* sql.unsafe<{ readonly name: unknown }>(
198 "SELECT name FROM sqlite_master WHERE type = 'table'",
199 )).map((row) => row.name),
200 );
201 if (!tables.has("gen_metadata") && !tables.has("steps")) {
202 return yield* new AntigravityDatabaseDecodeError({ path });
203 }
204 // Seek by rowid regardless of indexes; idx normally aliases rowid, but sort for layouts where it does not.
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 // Filter outside SQL to bound scans to one page, including rows without metadata.
222 if (step && row.data === null) continue;
223 const idx = row.idx;
224 if (typeof idx !== "number") {
225 return yield* new AntigravityDatabaseDecodeError({ path });
226 }
227 entries.push({ idx, entry: yield* decode(() => metadata(blob(row.data), step)) });
228 }
229 if (rows.length < pageRows) break;
230 after = rows[rows.length - 1]!.row_id;
231 yield* Effect.yieldNow;
232 }
233 return entries.sort((a, b) => a.idx - b.idx);
234 });
235 const generations = tables.has("gen_metadata")
236 ? yield* readMetadata(
237 "SELECT rowid AS row_id, idx, data FROM gen_metadata WHERE rowid > ? ORDER BY rowid LIMIT ?",
238 GENERATION_PAGE_ROWS,
239 false,
240 )
241 : [];
242 let trajectoryTimestamp: number | null = null;
243 if (tables.has("trajectory_metadata_blob")) {
244 for (const row of yield* sql.unsafe<{ readonly data: unknown }>(
245 "SELECT data FROM trajectory_metadata_blob",
246 )) {
247 trajectoryTimestamp ??= yield* decode(() => timestamp(nested(fields(blob(row.data)), 2)));
248 }
249 }
250 const steps = tables.has("steps")
251 ? yield* readMetadata(
252 "SELECT rowid AS row_id, idx, metadata AS data FROM steps WHERE rowid > ? ORDER BY rowid LIMIT ?",
253 STEP_PAGE_ROWS,
254 true,
255 )
256 : [];
257 return yield* decode(() =>
258 usageCandidates(sessionId, generations, steps, trajectoryTimestamp, fallbackTimestamp),
259 );
260 }).pipe(sql.withTransaction);
261});
262​
263function usageCandidates(
264 sessionId: string,
265 generations: ReadonlyArray<{ idx: number; entry: Metadata }>,
266 steps: ReadonlyArray<{ idx: number; entry: Metadata }>,
267 trajectoryTimestamp: number | null,
268 fallbackTimestamp: number,
269): UsageCandidate[] {
270 const records: UsageCandidate[] = [];
271 const generationModels = new Map(generations.map(({ idx, entry }) => [idx, entry.model]));
272 for (const [source, entries] of [
273 ["step", steps],
274 ["generation", generations],
275 ] as const) {
276 for (const [index, { idx, entry }] of entries.entries()) {
277 for (const [usageIndex, usage] of entry.usages.entries()) {
278 const outputTokens = Math.max(numberAt(usage, 3), numberAt(usage, 9) + numberAt(usage, 10));
279 const totals = {
280 uncachedInputTokens: numberAt(usage, 2),
281 cachedInputTokens: numberAt(usage, 5),
282 cacheCreationTokens: numberAt(usage, 4),
283 outputTokens,
284 reasoningTokens: Math.min(outputTokens, numberAt(usage, 9)),
285 };
286 if (
287 totals.uncachedInputTokens +
288 totals.cachedInputTokens +
289 totals.cacheCreationTokens +
290 outputTokens ===
291 0
292 )
293 continue;
294 const keys = ([11, 12, 7] as const).flatMap((key) => {
295 const id = textAt(usage, key);
296 return id ? [`antigravity:${key}:${id}`] : [];
297 });
298 const record: UsageRecord = {
299 provider: "antigravity",
300 sessionId,
301 timestampMs: entry.timestampMs ?? trajectoryTimestamp ?? fallbackTimestamp,
302 model:
303 MODEL_IDS[numberAt(usage, 1)] ||
304 entry.model ||
305 (source === "step" ? generationModels.get(idx) : "") ||
306 modelName("", numberAt(usage, 1)) ||
307 "antigravity-unknown",
308 totals,
309 reportedCostUsd: null,
310 speed: "standard",
311 dedupeKey: keys[0] ?? `antigravity:${sessionId}:${source}:${index}:${usageIndex}`,
312 };
313 records.push({
314 record,
315 keys,
316 timestampQuality: entry.timestampMs !== null ? 2 : trajectoryTimestamp !== null ? 1 : 0,
317 });
318 }
319 }
320 }
321 return records;
323​
324interface CachedDatabase {
325 readonly fingerprint: string;
326 readonly candidates: readonly UsageCandidate[];
328​
329/** Fingerprint canonical DB/WAL paths by size, mtime and ctime; WAL holds new rows, and ctime catches restored mtimes. */
330export const makeAntigravityUsageCache = () => new Map<string, CachedDatabase>();
331​
332export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* (
333 conversationsDirectories: string | readonly string[],
334 sinceMs: number,
335 cache?: Map<string, CachedDatabase>,
336) {
337 const fileSystem = yield* FileSystem.FileSystem;
338 const pathService = yield* Path.Path;
339 const roots =
340 typeof conversationsDirectories === "string"
341 ? [conversationsDirectories]
342 : conversationsDirectories;
343 const files: Array<{ root: string; path: string; records: UsageRecord[] }> = [];
344 const errors: string[] = [];
345 const identities = new Map<string, number>();
346 const groups: Array<
347 UsageCandidate & { parent: number; size: number; owner: number; fileIndex: number }
348 > = [];
349 const find = (index: number): number => {
350 let root = index;
351 while (groups[root]!.parent !== root) root = groups[root]!.parent;
352 while (index !== root) {
353 const parent = groups[index]!.parent;
354 groups[index]!.parent = root;
355 index = parent;
356 }
357 return root;
358 };
359 const merge = (left: number, right: number): number => {
360 let a = find(left);
361 let b = find(right);
362 if (a === b) return a;
363 if (groups[a]!.size < groups[b]!.size) [a, b] = [b, a];
364 const target = groups[a]!;
365 const source = groups[b]!;
366 const first = target.owner < source.owner ? target : source;
367 const bestTime =
368 source.timestampQuality > target.timestampQuality ||
369 (source.timestampQuality === target.timestampQuality &&
370 source.record.timestampMs < target.record.timestampMs)
371 ? source
372 : target;
373 const x = target.record.totals;
374 const y = source.record.totals;
375 target.record = {
376 ...first.record,
377 model:
378 first.record.model === "antigravity-unknown"
379 ? first === target
380 ? source.record.model
381 : target.record.model
382 : first.record.model,
383 timestampMs: bestTime.record.timestampMs,
384 totals: {
385 uncachedInputTokens: Math.max(x.uncachedInputTokens, y.uncachedInputTokens),
386 cachedInputTokens: Math.max(x.cachedInputTokens, y.cachedInputTokens),
387 cacheCreationTokens: Math.max(x.cacheCreationTokens, y.cacheCreationTokens),
388 outputTokens: Math.max(x.outputTokens, y.outputTokens),
389 reasoningTokens: Math.max(x.reasoningTokens, y.reasoningTokens),
390 },
391 };
392 target.timestampQuality = bestTime.timestampQuality;
393 target.owner = first.owner;
394 target.fileIndex = first.fileIndex;
395 target.size += source.size;
396 source.parent = a;
397 return a;
398 };
399 const append = (candidate: UsageCandidate, fileIndex: number) => {
400 const index = groups.length;
401 groups.push({ ...candidate, parent: index, size: 1, owner: index, fileIndex });
402 for (const key of candidate.keys) {
403 const existing = identities.get(key);
404 if (existing !== undefined) merge(index, existing);
405 identities.set(key, index);
406 }
407 };
408 const visited = new Set<string>();
409 const readFile = Effect.fn("readAntigravityUsage.readFile")(function* (path: string) {
410 const canonical = yield* fileSystem.realPath(path);
411 if (visited.has(canonical)) return null;
412 visited.add(canonical);
413 const fingerprintOf = (file: string) =>
414 Effect.tryPromise(() => NodeFSP.stat(file)).pipe(
415 Effect.map((stat) => ({ stat, part: `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` })),
416 );
417 const { stat, part } = yield* fingerprintOf(path);
418 const wal = yield* fingerprintOf(`${path}-wal`).pipe(Effect.option);
419 const fingerprint = `${part}/${wal._tag === "Some" ? wal.value.part : "-"}`;
420 const cached = cache?.get(canonical);
421 if (cached?.fingerprint === fingerprint) return cached.candidates;
422 const candidates = yield* readDatabase(
423 path,
424 pathService.basename(path, ".db"),
425 stat.mtimeMs,
426 ).pipe(Effect.provide(NodeSqliteClient.layer({ filename: path, readonly: true })));
427 cache?.set(canonical, { fingerprint, candidates });
428 return candidates;
429 });
430 const walk = Effect.fn("antigravityUsageReader.walk")(function* (
431 directory: string,
432 root: string,
433 ): Effect.fn.Return<void> {
434 const names = yield* fileSystem.readDirectory(directory).pipe(
435 Effect.catchTags({
436 PlatformError: (cause) => {
437 if (cause.reason._tag !== "NotFound") errors.push(directory);
438 return Effect.succeed(null);
439 },
440 }),
441 );
442 if (names === null) return;
443 names.sort((a, b) => a.localeCompare(b));
444 for (const name of names) {
445 const path = pathService.join(directory, name);
446 // Like a directory listing's entry types: symlinks are neither files nor directories.
447 const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));
448 const type = isLink
449 ? "SymbolicLink"
450 : yield* fileSystem.stat(path).pipe(
451 Effect.map((info) => info.type),
452 Effect.orElseSucceed(() => null),
453 );
454 if (type === "Directory") {
455 yield* walk(path, root);
456 } else if ((type === "File" || type === null) && name.endsWith(".db")) {
457 const candidates = yield* readFile(path).pipe(
458 Effect.catch(() => {
459 errors.push(path);
460 return Effect.succeed(null);
461 }),
462 );
463 if (candidates === null) continue;
464 const fileIndex = files.length;
465 files.push({ root, path, records: [] });
466 for (const [index, candidate] of candidates.entries()) {
467 append(candidate, fileIndex);
468 if (index % 256 === 255) yield* Effect.yieldNow;
469 }
470 }
471 }
472 });
473 for (const root of roots) yield* walk(root, root);
474 if (cache !== undefined) {
475 for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);
476 }
477 for (const [index, group] of groups.entries()) {
478 if (group.parent === index && group.record.timestampMs >= sinceMs) {
479 files[group.fileIndex]!.records.push(withRateModel(group.record));
480 }
481 }
482 return { files, errors };
483});