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

antigravityUsageReader.ts

588 lines21.3 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​
81// Offline fallback for records without names. New names are learned from the scanned metadata.
82// Cross-checked against ccusage's Antigravity parser and mrexodia/agent-cost-dashboard.
83const MODEL_IDS: Record<number, string> = {
84 246: "gemini-2.5-pro",
85 312: "gemini-2.5-flash",
86 313: "gemini-2.5-flash-thinking",
87 329: "gemini-2.5-flash-thinking",
88 330: "gemini-2.5-flash-lite",
89 281: "claude-sonnet-4",
90 282: "claude-sonnet-4",
91 290: "claude-opus-4",
92 291: "claude-opus-4",
93 333: "claude-sonnet-4-5",
94 334: "claude-sonnet-4-5",
95 340: "claude-haiku-4-5",
96 341: "claude-haiku-4-5",
97 342: "gpt-oss-120b-medium",
98 1026: "claude-opus-4-6",
99 1035: "claude-sonnet-4-6",
100 1016: "gemini-3.1-pro",
101 1036: "gemini-3.1-pro",
102 1037: "gemini-3.1-pro",
103 1018: "gemini-3-flash-preview",
104 1084: "gemini-3-flash-preview",
105 1047: "gemini-3-flash-preview",
106 1020: "gemini-3.5-flash-medium",
107 1021: "gemini-3.1-flash-image",
108 1050: "gemini-3.1-flash-lite",
109 1071: "gemini-3.6-flash-high",
110 1072: "gemini-3.6-flash-medium",
111 1073: "gemini-3.6-flash-low",
112 1132: "gemini-3.5-flash-high",
113 1133: "gemini-3.5-flash-high",
114 1187: "gemini-3.5-flash-extra-low",
115 1196: "gemini-3.6-flash",
116 1266: "gemini-3.6-flash",
117 1298: "gemini-3.7-flash-high",
118 1299: "gemini-3.7-flash-medium",
119 1300: "gemini-3.7-flash-low",
120 1301: "gemini-3.7-flash-tiered",
121 1318: "gemini-3.8-flash-high",
122 1319: "gemini-3.8-flash-medium",
123 1320: "gemini-3.8-flash-low",
124 1322: "gemini-3.8-flash-tiered",
125 1402: "claude-opus-5-5",
126 1417: "gemini-4-argon",
127 1418: "gemini-4-argon",
128 1419: "gemini-4-argon",
129};
130​
131// Effort and routing variants share the base model's price.
132export const antigravityRateModel = (model: string) => {
133 const base = model.replace(/-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, "");
134 return /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model)
135 ? "gemini-3.5-flash"
136 : model === "gemini-3.7-flash-safety-le"
137 ? "gemini-3.7-flash"
138 : base === "gemini-3-flash"
139 ? "gemini-3-flash-preview"
140 : base;
141};
142​
143function withRateModel(record: UsageRecord): UsageRecord {
144 const rateModel = antigravityRateModel(record.model);
145 return rateModel === record.model ? record : { ...record, rateModel };
147​
148function modelName(name: string): string {
149 if (name) {
150 const normalized = name
151 .toLowerCase()
152 .replace(/\s*\(([^)]*)\)\s*$/, "-$1")
153 .replace(/\s+/g, "-");
154 if (normalized.startsWith("claude-")) {
155 return normalized
156 .replace(/^claude-(\d+(?:\.\d+)?)-(sonnet|opus|haiku)/, "claude-$2-$1")
157 .replaceAll(".", "-");
158 }
159 return normalized;
160 }
161 return "";
163​
164function isConcreteModel(model: string): boolean {
165 return (
166 /^(?:gemini-\d|claude-(?:sonnet|opus|haiku)-\d|gpt-)/.test(model) &&
167 !/^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model)
168 );
170​
171function rememberModel(models: Map<number, string | null>, id: number, model: string | null) {
172 const previous = models.get(id);
173 models.set(id, previous === undefined || previous === model ? model : null);
175​
176interface Metadata {
177 model: string;
178 modelId: number;
179 timestampMs: number | null;
180 usages: Fields[];
182​
183function metadata(bytes: Uint8Array, step: boolean): Metadata {
184 const root = fields(bytes);
185 if (!step && bytesAt(root, 1) === undefined) {
186 throw new Error("Missing Antigravity generation metadata");
187 }
188 const data = step ? root : nested(root, 1);
189 const model = step ? nested(data, 24) : data;
190 const usage = bytesAt(data, step ? 9 : 4);
191 // Copy the usage bytes: subarrays kept in usages would hold each row's whole blob alive.
192 const primaryUsage = usage === undefined ? undefined : fields(usage.slice());
193 const usages = primaryUsage === undefined ? [] : [primaryUsage];
194 for (const retry of data.get(step ? 28 : 17) ?? []) {
195 if (!(retry instanceof Uint8Array)) throw new Error("Invalid retry metadata");
196 const retryUsage = bytesAt(fields(retry), 2);
197 if (retryUsage !== undefined) usages.push(fields(retryUsage.slice()));
198 }
199 const names = [textAt(model, step ? 12 : 19), textAt(model, step ? 8 : 21)].map(modelName);
200 return {
201 model:
202 names.find(isConcreteModel) ?? names.find((name) => name && !/^model[_-]/.test(name)) ?? "",
203 modelId:
204 numberAt(model, step ? 1 : 3) || (primaryUsage === undefined ? 0 : numberAt(primaryUsage, 1)),
205 timestampMs: step
206 ? (timestamp(nested(data, 8)) ?? timestamp(nested(data, 1)))
207 : timestamp(nested(nested(data, 9), 4)),
208 usages,
209 };
211​
212function blob(value: unknown): Uint8Array {
213 if (!(value instanceof Uint8Array)) throw new Error("Invalid Antigravity metadata blob");
214 return value;
216​
217interface UsageCandidate {
218 record: UsageRecord;
219 modelId: number;
220 modelQuality: number;
221 keys: readonly string[];
222 timestampQuality: number;
224​
225class AntigravityDatabaseDecodeError extends Schema.TaggedError<AntigravityDatabaseDecodeError>()(
226 "AntigravityDatabaseDecodeError",
227 { path: Schema.String, cause: Schema.optional(Schema.Defect()) },
228) {
229 override get message(): string {
230 return `Antigravity usage could not be decoded from ${this.path}.`;
231 }
233​
234/** Generation rows can hold megabytes of context; read one at a time to bound blocking statement.all(). */
235const GENERATION_PAGE_ROWS = 1;
236const STEP_PAGE_ROWS = 64;
237​
238const readDatabase = Effect.fn("readDatabase")(function* (
239 path: string,
240 sessionId: string,
241 fallbackTimestamp: number,
242) {
243 const sql = yield* SqlClient.SqlClient;
244 const decode = <A>(evaluate: () => A) =>
245 Effect.try({
246 try: evaluate,
247 catch: (cause) => new AntigravityDatabaseDecodeError({ path, cause }),
248 });
249 yield* sql.unsafe("PRAGMA busy_timeout = 100");
250 return yield* Effect.gen(function* () {
251 const tables = new Set(
252 (yield* sql.unsafe<{ readonly name: unknown }>(
253 "SELECT name FROM sqlite_master WHERE type = 'table'",
254 )).map((row) => row.name),
255 );
256 if (!tables.has("gen_metadata") && !tables.has("steps")) {
257 return yield* new AntigravityDatabaseDecodeError({ path });
258 }
259 // Seek by rowid regardless of indexes; idx normally aliases rowid, but sort for layouts where it does not.
260 const readMetadata = Effect.fnUntraced(function* (
261 query: string,
262 pageRows: number,
263 step: boolean,
264 ) {
265 const entries: Array<{ idx: number; entry: Metadata }> = [];
266 let after = -Infinity;
267 while (true) {
268 const rows = yield* sql
269 .unsafe<{
270 readonly row_id: number;
271 readonly idx: unknown;
272 readonly data: unknown;
273 }>(query, [after, pageRows])
274 .pipe(Effect.withTracerEnabled(false));
275 for (const row of rows) {
276 // Filter outside SQL to bound scans to one page, including rows without metadata.
277 if (step && row.data === null) continue;
278 const idx = row.idx;
279 if (typeof idx !== "number") {
280 return yield* new AntigravityDatabaseDecodeError({ path });
281 }
282 entries.push({ idx, entry: yield* decode(() => metadata(blob(row.data), step)) });
283 }
284 if (rows.length < pageRows) break;
285 after = rows[rows.length - 1]!.row_id;
286 yield* Effect.yieldNow;
287 }
288 return entries.sort((a, b) => a.idx - b.idx);
289 });
290 const generations = tables.has("gen_metadata")
291 ? yield* readMetadata(
292 "SELECT rowid AS row_id, idx, data FROM gen_metadata WHERE rowid > ? ORDER BY rowid LIMIT ?",
293 GENERATION_PAGE_ROWS,
294 false,
295 )
296 : [];
297 let trajectoryTimestamp: number | null = null;
298 if (tables.has("trajectory_metadata_blob")) {
299 for (const row of yield* sql.unsafe<{ readonly data: unknown }>(
300 "SELECT data FROM trajectory_metadata_blob",
301 )) {
302 trajectoryTimestamp ??= yield* decode(() =>
303 pipe(blob(row.data), fields, (message) => nested(message, 2), timestamp),
304 );
305 }
306 }
307 const steps = tables.has("steps")
308 ? yield* readMetadata(
309 "SELECT rowid AS row_id, idx, metadata AS data FROM steps WHERE rowid > ? ORDER BY rowid LIMIT ?",
310 STEP_PAGE_ROWS,
311 true,
312 )
313 : [];
314 return yield* decode(() => {
315 const models = new Map<number, string | null>();
316 for (const { entry } of [...generations, ...steps]) {
317 if (entry.modelId > 0 && isConcreteModel(entry.model))
318 rememberModel(models, entry.modelId, entry.model);
319 }
320 return {
321 candidates: usageCandidates(
322 sessionId,
323 generations,
324 steps,
325 trajectoryTimestamp,
326 fallbackTimestamp,
327 ),
328 models,
329 };
330 });
331 }).pipe(sql.withTransaction);
332});
333​
334function usageCandidates(
335 sessionId: string,
336 generations: ReadonlyArray<{ idx: number; entry: Metadata }>,
337 steps: ReadonlyArray<{ idx: number; entry: Metadata }>,
338 trajectoryTimestamp: number | null,
339 fallbackTimestamp: number,
340): UsageCandidate[] {
341 const records: UsageCandidate[] = [];
342 const generationModels = new Map(generations.map(({ idx, entry }) => [idx, entry]));
343 for (const [source, entries] of [
344 ["step", steps],
345 ["generation", generations],
346 ] as const) {
347 for (const [index, { idx, entry }] of entries.entries()) {
348 for (const [usageIndex, usage] of entry.usages.entries()) {
349 const modelId = numberAt(usage, 1) || entry.modelId;
350 const generation = source === "step" ? generationModels.get(idx) : undefined;
351 // A retry can use a different model than its enclosing generation or step.
352 const matches = (metadata: Metadata) => modelId === 0 || metadata.modelId === modelId;
353 const model =
354 matches(entry) && entry.model
355 ? entry.model
356 : generation && matches(generation)
357 ? generation.model
358 : "";
359 const outputTokens = Math.max(numberAt(usage, 3), numberAt(usage, 9) + numberAt(usage, 10));
360 const totals = {
361 uncachedInputTokens: numberAt(usage, 2),
362 cachedInputTokens: numberAt(usage, 5),
363 cacheCreationTokens: numberAt(usage, 4),
364 outputTokens,
365 reasoningTokens: Math.min(outputTokens, numberAt(usage, 9)),
366 };
367 if (
368 totals.uncachedInputTokens +
369 totals.cachedInputTokens +
370 totals.cacheCreationTokens +
371 outputTokens ===
372 0
373 )
374 continue;
375 const keys = ([11, 12, 7] as const).flatMap((key) => {
376 const id = textAt(usage, key);
377 return id ? [`antigravity:${key}:${id}`] : [];
378 });
379 const record: UsageRecord = {
380 provider: "antigravity",
381 sessionId,
382 timestampMs: entry.timestampMs ?? trajectoryTimestamp ?? fallbackTimestamp,
383 model,
384 totals,
385 reportedCostUsd: null,
386 speed: "standard",
387 dedupeKey: keys[0] ?? `antigravity:${sessionId}:${source}:${index}:${usageIndex}`,
388 };
389 records.push({
390 record,
391 modelId,
392 modelQuality: isConcreteModel(model) ? 4 : model ? 1 : 0,
393 keys,
394 timestampQuality: entry.timestampMs !== null ? 2 : trajectoryTimestamp !== null ? 1 : 0,
395 });
396 }
397 }
398 }
399 return records;
401​
402interface CachedDatabase {
403 readonly fingerprint: string;
404 readonly data: Effect.Success<ReturnType<typeof readDatabase>>;
406​
407/** Fingerprint canonical DB/WAL paths by size, mtime and ctime; WAL holds new rows, and ctime catches restored mtimes. */
408export const makeAntigravityUsageCache = () => new Map<string, CachedDatabase>();
409​
410export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* (
411 conversationsDirectories: string | readonly string[],
412 sinceMs: number,
413 cache?: Map<string, CachedDatabase>,
414) {
415 const fileSystem = yield* FileSystem.FileSystem;
416 const pathService = yield* Path.Path;
417 const roots =
418 typeof conversationsDirectories === "string"
419 ? [conversationsDirectories]
420 : conversationsDirectories;
421 const files: Array<{ root: string; path: string; records: UsageRecord[] }> = [];
422 const errors: string[] = [];
423 const models = new Map<number, string | null>();
424 const pending: Array<{ data: CachedDatabase["data"]; fileIndex: number }> = [];
425 const identities = new Map<string, number>();
426 const groups: Array<
427 UsageCandidate & { parent: number; size: number; owner: number; fileIndex: number }
428 > = [];
429 const find = (index: number): number => {
430 let root = index;
431 while (groups[root]!.parent !== root) root = groups[root]!.parent;
432 while (index !== root) {
433 const parent = groups[index]!.parent;
434 groups[index]!.parent = root;
435 index = parent;
436 }
437 return root;
438 };
439 const merge = (left: number, right: number): number => {
440 let a = find(left);
441 let b = find(right);
442 if (a === b) return a;
443 if (groups[a]!.size < groups[b]!.size) [a, b] = [b, a];
444 const target = groups[a]!;
445 const source = groups[b]!;
446 const first = target.owner < source.owner ? target : source;
447 const bestModel =
448 source.modelQuality === target.modelQuality
449 ? first
450 : source.modelQuality > target.modelQuality
451 ? source
452 : target;
453 const bestTime =
454 source.timestampQuality > target.timestampQuality ||
455 (source.timestampQuality === target.timestampQuality &&
456 source.record.timestampMs < target.record.timestampMs)
457 ? source
458 : target;
459 const x = target.record.totals;
460 const y = source.record.totals;
461 target.record = {
462 ...first.record,
463 model: bestModel.record.model,
464 timestampMs: bestTime.record.timestampMs,
465 totals: {
466 uncachedInputTokens: Math.max(x.uncachedInputTokens, y.uncachedInputTokens),
467 cachedInputTokens: Math.max(x.cachedInputTokens, y.cachedInputTokens),
468 cacheCreationTokens: Math.max(x.cacheCreationTokens, y.cacheCreationTokens),
469 outputTokens: Math.max(x.outputTokens, y.outputTokens),
470 reasoningTokens: Math.max(x.reasoningTokens, y.reasoningTokens),
471 },
472 };
473 target.timestampQuality = bestTime.timestampQuality;
474 target.modelQuality = bestModel.modelQuality;
475 target.owner = first.owner;
476 target.fileIndex = first.fileIndex;
477 target.size += source.size;
478 source.parent = a;
479 return a;
480 };
481 const append = (candidate: UsageCandidate, fileIndex: number) => {
482 const index = groups.length;
483 groups.push({ ...candidate, parent: index, size: 1, owner: index, fileIndex });
484 for (const key of candidate.keys) {
485 const existing = identities.get(key);
486 if (existing !== undefined) merge(index, existing);
487 identities.set(key, index);
488 }
489 };
490 const visited = new Set<string>();
491 const readFile = Effect.fn("readAntigravityUsage.readFile")(function* (path: string) {
492 const canonical = yield* fileSystem.realPath(path);
493 if (visited.has(canonical)) return null;
494 visited.add(canonical);
495 const fingerprintOf = (file: string) =>
496 Effect.tryPromise({
497 try: () => NodeFSP.stat(file),
498 catch: (cause) => new AntigravityDatabaseDecodeError({ path: file, cause }),
499 }).pipe(
500 Effect.map((stat) => ({ stat, part: `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` })),
501 );
502 const { stat, part } = yield* fingerprintOf(path);
503 const wal = yield* fingerprintOf(`${path}-wal`).pipe(Effect.option);
504 const fingerprint = `${part}/${wal._tag === "Some" ? wal.value.part : "-"}`;
505 const cached = cache?.get(canonical);
506 if (cached?.fingerprint === fingerprint) return cached.data;
507 const data = yield* readDatabase(path, pathService.basename(path, ".db"), stat.mtimeMs).pipe(
508 Effect.provide(NodeSqliteClient.layer({ filename: path, readonly: true })),
509 );
510 cache?.set(canonical, { fingerprint, data });
511 return data;
512 });
513 const walk = Effect.fn("antigravityUsageReader.walk")(function* (
514 directory: string,
515 root: string,
516 ): Effect.fn.Return<void> {
517 const names = yield* fileSystem.readDirectory(directory).pipe(
518 Effect.catchTags({
519 PlatformError: (cause) => {
520 if (cause.reason._tag !== "NotFound") errors.push(directory);
521 return Effect.succeed(null);
522 },
523 }),
524 );
525 if (names === null) return;
526 names.sort((a, b) => a.localeCompare(b));
527 for (const name of names) {
528 const path = pathService.join(directory, name);
529 // Like a directory listing's entry types: symlinks are neither files nor directories.
530 const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));
531 const type = isLink
532 ? "SymbolicLink"
533 : yield* fileSystem.stat(path).pipe(
534 Effect.map((info) => info.type),
535 Effect.orElseSucceed(() => null),
536 );
537 if (type === "Directory") {
538 yield* walk(path, root);
539 } else if ((type === "File" || type === null) && name.endsWith(".db")) {
540 const data = yield* readFile(path).pipe(
541 Effect.catch(() => {
542 errors.push(path);
543 return Effect.succeed(null);
544 }),
545 );
546 if (data === null) continue;
547 for (const [id, model] of data.models) {
548 rememberModel(models, id, model);
549 }
550 const fileIndex = files.length;
551 files.push({ root, path, records: [] });
552 pending.push({ data, fileIndex });
553 }
554 }
555 });
556 for (const root of roots) yield* walk(root, root);
557 if (cache !== undefined) {
558 for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);
559 }
560 for (const { data, fileIndex } of pending) {
561 for (const [index, candidate] of data.candidates.entries()) {
562 const learned = models.get(candidate.modelId);
563 const fallback = learned === null ? undefined : MODEL_IDS[candidate.modelId];
564 const model =
565 (candidate.modelQuality === 4 ? candidate.record.model : "") ||
566 learned ||
567 fallback ||
568 candidate.record.model ||
569 (candidate.modelId > 0 ? `antigravity-model-${candidate.modelId}` : "antigravity-unknown");
570 append(
571 {
572 ...candidate,
573 record: { ...candidate.record, model },
574 modelQuality:
575 candidate.modelQuality === 4 ? 4 : learned ? 3 : fallback ? 2 : candidate.modelQuality,
576 },
577 fileIndex,
578 );
579 if (index % 256 === 255) yield* Effect.yieldNow;
580 }
581 }
582 for (const [index, group] of groups.entries()) {
583 if (group.parent === index && group.record.timestampMs >= sinceMs) {
584 files[group.fileIndex]!.records.push(withRateModel(group.record));
585 }
586 }
587 return { files, errors };
588});