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";
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
16/** Antigravity stores usage metadata as protobuf, independently of conversation text. */
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
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
105function modelName(name: string, id: number): string {
106 if (name) {
107 const normalized = name
108 .toLowerCase()
109 .replace(/\s*\([^)]*\)\s*$/, "")
110 .replaceAll(" ", "-");
111 if (normalized.startsWith("claude-")) {
112 return normalized
113 .replace(/^claude-(4(?:\.\d+)?)-(sonnet|opus|haiku)/, "claude-$2-$1")
114 .replaceAll(".", "-");
115 }
116 return normalized;
117 }
118 return MODEL_IDS[id] ?? (id > 0 ? `antigravity-model-${id}` : "");
119}
120
121interface Metadata {
122 model: string;
123 timestampMs: number | null;
124 usages: Fields[];
125}
126
127function metadata(bytes: Uint8Array, step: boolean): Metadata {
128 const root = fields(bytes);
129 if (!step && bytesAt(root, 1) === undefined) {
130 throw new Error("Missing Antigravity generation metadata");
131 }
132 const data = step ? root : nested(root, 1);
133 const model = step ? nested(data, 24) : data;
134 const usage = bytesAt(data, step ? 9 : 4);
135 const usages = usage === undefined ? [] : [fields(usage)];
136 for (const retry of data.get(step ? 28 : 17) ?? []) {
137 if (!(retry instanceof Uint8Array)) throw new Error("Invalid retry metadata");
138 const retryUsage = bytesAt(fields(retry), 2);
139 if (retryUsage !== undefined) usages.push(fields(retryUsage));
140 }
141 return {
142 model: modelName(
143 textAt(model, step ? 12 : 19) || textAt(model, step ? 8 : 21),
144 numberAt(model, step ? 1 : 3),
145 ),
146 timestampMs: step
147 ? (timestamp(nested(data, 8)) ?? timestamp(nested(data, 1)))
148 : timestamp(nested(nested(data, 9), 4)),
149 usages,
150 };
151}
152
153function blob(value: unknown): Uint8Array {
154 if (!(value instanceof Uint8Array)) throw new Error("Invalid Antigravity metadata blob");
155 return value;
156}
157
158interface UsageCandidate {
159 record: UsageRecord;
160 keys: readonly string[];
161 timestampQuality: number;
162}
163
164/** A conversation database whose usage tables are missing or undecodable. */
165class AntigravityDatabaseDecodeError extends Schema.TaggedError<AntigravityDatabaseDecodeError>()(
166 "AntigravityDatabaseDecodeError",
167 { path: Schema.String, cause: Schema.optional(Schema.Defect()) },
168) {
169 override get message(): string {
170 return `Antigravity usage could not be decoded from ${this.path}.`;
171 }
172}
173
174const readDatabase = Effect.fn("readDatabase")(function* (
175 path: string,
176 sessionId: string,
177 fallbackTimestamp: number,
178) {
179 const sql = yield* SqlClient.SqlClient;
180 const decode = <A>(evaluate: () => A) =>
181 Effect.try({
182 try: evaluate,
183 catch: (cause) => new AntigravityDatabaseDecodeError({ path, cause }),
184 });
185 yield* sql.unsafe("PRAGMA busy_timeout = 100");
186 return yield* Effect.gen(function* () {
187 const tables = new Set(
188 (yield* sql.unsafe<{ readonly name: unknown }>(
189 "SELECT name FROM sqlite_master WHERE type = 'table'",
190 )).map((row) => row.name),
191 );
192 if (!tables.has("gen_metadata") && !tables.has("steps")) {
193 return yield* new AntigravityDatabaseDecodeError({ path });
194 }
195 const readMetadata = Effect.fnUntraced(function* (
196 query: string,
197 column: string,
198 step: boolean,
199 ) {
200 const entries: Array<{ idx: number; entry: Metadata }> = [];
201 for (const row of yield* sql.unsafe<Record<string, unknown>>(query)) {
202 const idx = row.idx;
203 if (typeof idx !== "number") {
204 return yield* new AntigravityDatabaseDecodeError({ path });
205 }
206 entries.push({ idx, entry: yield* decode(() => metadata(blob(row[column]), step)) });
207 if (entries.length % 256 === 0) yield* Effect.yieldNow;
208 }
209 return entries;
210 });
211 const generations = tables.has("gen_metadata")
212 ? yield* readMetadata("SELECT idx, data FROM gen_metadata ORDER BY idx", "data", false)
213 : [];
214 let trajectoryTimestamp: number | null = null;
215 if (tables.has("trajectory_metadata_blob")) {
216 for (const row of yield* sql.unsafe<{ readonly data: unknown }>(
217 "SELECT data FROM trajectory_metadata_blob",
218 )) {
219 trajectoryTimestamp ??= yield* decode(() => timestamp(nested(fields(blob(row.data)), 2)));
220 }
221 }
222 const steps = tables.has("steps")
223 ? yield* readMetadata(
224 "SELECT idx, metadata FROM steps WHERE metadata IS NOT NULL ORDER BY idx",
225 "metadata",
226 true,
227 )
228 : [];
229 return yield* decode(() =>
230 usageCandidates(sessionId, generations, steps, trajectoryTimestamp, fallbackTimestamp),
231 );
232 }).pipe(sql.withTransaction);
233});
234
235function usageCandidates(
236 sessionId: string,
237 generations: ReadonlyArray<{ idx: number; entry: Metadata }>,
238 steps: ReadonlyArray<{ idx: number; entry: Metadata }>,
239 trajectoryTimestamp: number | null,
240 fallbackTimestamp: number,
241): UsageCandidate[] {
242 const records: UsageCandidate[] = [];
243 const generationModels = new Map(generations.map(({ idx, entry }) => [idx, entry.model]));
244 for (const [source, entries] of [
245 ["step", steps],
246 ["generation", generations],
247 ] as const) {
248 for (const [index, { idx, entry }] of entries.entries()) {
249 for (const [usageIndex, usage] of entry.usages.entries()) {
250 const outputTokens = Math.max(numberAt(usage, 3), numberAt(usage, 9) + numberAt(usage, 10));
251 const totals = {
252 uncachedInputTokens: numberAt(usage, 2),
253 cachedInputTokens: numberAt(usage, 5),
254 cacheCreationTokens: numberAt(usage, 4),
255 outputTokens,
256 reasoningTokens: Math.min(outputTokens, numberAt(usage, 9)),
257 };
258 if (
259 totals.uncachedInputTokens +
260 totals.cachedInputTokens +
261 totals.cacheCreationTokens +
262 outputTokens ===
263 0
264 )
265 continue;
266 const keys = ([11, 12, 7] as const).flatMap((key) => {
267 const id = textAt(usage, key);
268 return id ? [`antigravity:${key}:${id}`] : [];
269 });
270 const record: UsageRecord = {
271 provider: "antigravity",
272 sessionId,
273 timestampMs: entry.timestampMs ?? trajectoryTimestamp ?? fallbackTimestamp,
274 model:
275 MODEL_IDS[numberAt(usage, 1)] ||
276 entry.model ||
277 (source === "step" ? generationModels.get(idx) : "") ||
278 modelName("", numberAt(usage, 1)) ||
279 "antigravity-unknown",
280 totals,
281 reportedCostUsd: null,
282 speed: "standard",
283 dedupeKey: keys[0] ?? `antigravity:${sessionId}:${source}:${index}:${usageIndex}`,
284 };
285 records.push({
286 record,
287 keys,
288 timestampQuality: entry.timestampMs !== null ? 2 : trajectoryTimestamp !== null ? 1 : 0,
289 });
290 }
291 }
292 }
293 return records;
294}
295
296interface CachedDatabase {
297 readonly fingerprint: string;
298 readonly candidates: readonly UsageCandidate[];
299}
300
301/**
302 * Parsed databases keyed by canonical path. An entry is reused only while both
303 * the database and its `-wal` sidecar keep the same size, mtime and ctime: new
304 * rows land in the WAL without touching the main file until a checkpoint, and
305 * ctime moves on any content write even when mtime is restored.
306 */
307export const makeAntigravityUsageCache = () => new Map<string, CachedDatabase>();
308
309/**
310 * Reads and merges aliases across every configured Antigravity store before date
311 * filtering. With a cache, databases unchanged since the previous read are not
312 * decoded again.
313 */
314export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* (
315 conversationsDirectories: string | readonly string[],
316 sinceMs: number,
317 cache?: Map<string, CachedDatabase>,
318) {
319 const fileSystem = yield* FileSystem.FileSystem;
320 const pathService = yield* Path.Path;
321 const roots =
322 typeof conversationsDirectories === "string"
323 ? [conversationsDirectories]
324 : conversationsDirectories;
325 const files: Array<{ root: string; path: string; records: UsageRecord[] }> = [];
326 const errors: string[] = [];
327 const identities = new Map<string, number>();
328 const groups: Array<
329 UsageCandidate & { parent: number; size: number; owner: number; fileIndex: number }
330 > = [];
331 const find = (index: number): number => {
332 let root = index;
333 while (groups[root]!.parent !== root) root = groups[root]!.parent;
334 while (index !== root) {
335 const parent = groups[index]!.parent;
336 groups[index]!.parent = root;
337 index = parent;
338 }
339 return root;
340 };
341 const merge = (left: number, right: number): number => {
342 let a = find(left);
343 let b = find(right);
344 if (a === b) return a;
345 if (groups[a]!.size < groups[b]!.size) [a, b] = [b, a];
346 const target = groups[a]!;
347 const source = groups[b]!;
348 const first = target.owner < source.owner ? target : source;
349 const bestTime =
350 source.timestampQuality > target.timestampQuality ||
351 (source.timestampQuality === target.timestampQuality &&
352 source.record.timestampMs < target.record.timestampMs)
353 ? source
354 : target;
355 const x = target.record.totals;
356 const y = source.record.totals;
357 target.record = {
358 ...first.record,
359 model:
360 first.record.model === "antigravity-unknown"
361 ? first === target
362 ? source.record.model
363 : target.record.model
364 : first.record.model,
365 timestampMs: bestTime.record.timestampMs,
366 totals: {
367 uncachedInputTokens: Math.max(x.uncachedInputTokens, y.uncachedInputTokens),
368 cachedInputTokens: Math.max(x.cachedInputTokens, y.cachedInputTokens),
369 cacheCreationTokens: Math.max(x.cacheCreationTokens, y.cacheCreationTokens),
370 outputTokens: Math.max(x.outputTokens, y.outputTokens),
371 reasoningTokens: Math.max(x.reasoningTokens, y.reasoningTokens),
372 },
373 };
374 target.timestampQuality = bestTime.timestampQuality;
375 target.owner = first.owner;
376 target.fileIndex = first.fileIndex;
377 target.size += source.size;
378 source.parent = a;
379 return a;
380 };
381 const append = (candidate: UsageCandidate, fileIndex: number) => {
382 const index = groups.length;
383 groups.push({ ...candidate, parent: index, size: 1, owner: index, fileIndex });
384 for (const key of candidate.keys) {
385 const existing = identities.get(key);
386 if (existing !== undefined) merge(index, existing);
387 identities.set(key, index);
388 }
389 };
390 const visited = new Set<string>();
391 const readFile = Effect.fn("readAntigravityUsage.readFile")(function* (path: string) {
392 const canonical = yield* fileSystem.realPath(path);
393 if (visited.has(canonical)) return null;
394 visited.add(canonical);
395 const fingerprintOf = (file: string) =>
396 Effect.tryPromise(() => NodeFSP.stat(file)).pipe(
397 Effect.map((stat) => ({ stat, part: `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` })),
398 );
399 const { stat, part } = yield* fingerprintOf(path);
400 const wal = yield* fingerprintOf(`${path}-wal`).pipe(Effect.option);
401 const fingerprint = `${part}/${wal._tag === "Some" ? wal.value.part : "-"}`;
402 const cached = cache?.get(canonical);
403 if (cached?.fingerprint === fingerprint) return cached.candidates;
404 const candidates = yield* readDatabase(
405 path,
406 pathService.basename(path, ".db"),
407 stat.mtimeMs,
408 ).pipe(Effect.provide(NodeSqliteClient.layer({ filename: path, readonly: true })));
409 cache?.set(canonical, { fingerprint, candidates });
410 return candidates;
411 });
412 const walk = (directory: string, root: string): Effect.Effect<void> =>
413 Effect.gen(function* () {
414 const names = yield* fileSystem.readDirectory(directory).pipe(
415 Effect.catchTags({
416 PlatformError: (cause) => {
417 if (cause.reason._tag !== "NotFound") errors.push(directory);
418 return Effect.succeed(null);
419 },
420 }),
421 );
422 if (names === null) return;
423 names.sort((a, b) => a.localeCompare(b));
424 for (const name of names) {
425 const path = pathService.join(directory, name);
426 // Like a directory listing's entry types: symlinks are neither files nor directories.
427 const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));
428 const type = isLink
429 ? "SymbolicLink"
430 : yield* fileSystem.stat(path).pipe(
431 Effect.map((info) => info.type),
432 Effect.orElseSucceed(() => null),
433 );
434 if (type === "Directory") {
435 yield* walk(path, root);
436 } else if ((type === "File" || type === null) && name.endsWith(".db")) {
437 const candidates = yield* readFile(path).pipe(
438 Effect.catch(() => {
439 errors.push(path);
440 return Effect.succeed(null);
441 }),
442 );
443 if (candidates === null) continue;
444 const fileIndex = files.length;
445 files.push({ root, path, records: [] });
446 for (const [index, candidate] of candidates.entries()) {
447 append(candidate, fileIndex);
448 if (index % 256 === 255) yield* Effect.yieldNow;
449 }
450 }
451 }
452 });
453 for (const root of roots) yield* walk(root, root);
454 if (cache !== undefined) {
455 for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);
456 }
457 for (const [index, group] of groups.entries()) {
458 if (group.parent === index && group.record.timestampMs >= sinceMs) {
459 files[group.fileIndex]!.records.push(group.record);
460 }
461 }
462 return { files, errors };
463});