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

antigravityUsageReader.ts

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