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