@devries-cameron20 / t3code-1 / commits / e2aa223229
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(antigravity): resolve model names from usage metadata (#33661)

Yash Singh committed Nov 9, 2026 at 20:18 UTC e2aa223229e42dd742b6dd05a9fad61775231d88
2 files changed +279 -48
apps/server/src/provider/Drivers/antigravityUsageReader.test.ts
+153 -3
@@ -72,6 +72,145 @@ const records = (result: Effect.Success<ReturnType<typeof readAntigravityUsage>>
72 result.files.flatMap((file) => file.records);
73
74 describe("readAntigravityUsage", () => {
75 + it.effect("learns numeric models from offline metadata and refreshes cached resolutions", () =>
76 + Effect.gen(function* () {
77 + const path = yield* Path.Path;
78 + const fs = yield* FileSystem.FileSystem;
79 + const dir = yield* tempDir;
80 + const cache = makeAntigravityUsageCache();
81 + yield* seedDatabase(path.join(dir, "a-usage.db"), (db) =>
82 + Effect.gen(function* () {
83 + yield* createTables(db);
84 + for (const [idx, id] of [9001, 9002, 1319].entries()) {
85 + yield* db.run("INSERT INTO steps VALUES (?, ?)", [
86 + idx,
87 + new Uint8Array(protoBytes(9, [...protoNumber(1, id), ...protoNumber(2, 10)])),
88 + ]);
89 + }
90 + }),
91 + );
92 + const first = yield* readAntigravityUsage(dir, 0, cache);
93 + assert.strictEqual(records(first)[0]?.model, "antigravity-model-9001");
94 + const evidence = path.join(dir, "z-names.db");
95 + yield* seedDatabase(evidence, (db) =>
96 + Effect.gen(function* () {
97 + yield* createTables(db);
98 + for (const [idx, [id, name]] of (
99 + [
100 + [9001, "Gemini 9.1 Flash (High)"],
101 + [9002, "Gemini default"],
102 + [1319, "Gemini 9.2 Flash"],
103 + ] as const
104 + ).entries()) {
105 + yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
106 + idx,
107 + new Uint8Array(
108 + protoBytes(1, [
109 + ...protoNumber(3, id),
110 + ...protoText(19, "gemini-default"),
111 + ...protoText(21, name),
112 + ]),
113 + ),
114 + ]);
115 + }
116 + }),
117 + );
118 + const next = yield* readAntigravityUsage(dir, 0, cache);
119 + assert.deepStrictEqual(
120 + records(next).map(({ model, rateModel }) => [model, rateModel]),
121 + [
122 + ["gemini-9.1-flash-high", "gemini-9.1-flash"],
123 + ["antigravity-model-9002", undefined],
124 + ["gemini-9.2-flash", undefined],
125 + ],
126 + );
127 + assert.deepStrictEqual(records(yield* readAntigravityUsage(dir, 0, cache)), records(next));
128 + yield* fs.remove(evidence);
129 + assert.deepStrictEqual(records(yield* readAntigravityUsage(dir, 0, cache)), records(first));
130 + }).pipe(Effect.provide(NodeServices.layer)),
131 + );
132 +
133 + it.effect("keeps explicit model evidence separate from retries and conflicting names", () =>
134 + Effect.gen(function* () {
135 + const path = yield* Path.Path;
136 + const dir = yield* tempDir;
137 + yield* seedDatabase(path.join(dir, "conflicts.db"), (db) =>
138 + Effect.gen(function* () {
139 + yield* createTables(db);
140 + for (const [idx, name] of ["Gemini 9.1 Flash", "Gemini 9.2 Flash"].entries()) {
141 + yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
142 + idx,
143 + new Uint8Array(
144 + protoBytes(1, [
145 + ...protoNumber(3, 1319),
146 + ...protoText(19, name),
147 + ...protoBytes(4, [
148 + ...protoNumber(1, 1319),
149 + ...protoNumber(2, 10),
150 + ...protoText(11, `r-${idx}`),
151 + ]),
152 + ...protoBytes(
153 + 17,
154 + protoBytes(2, [...protoNumber(1, 1026), ...protoNumber(2, 12)]),
155 + ),
156 + ]),
157 + ),
158 + ]);
159 + }
160 + for (const [idx, id] of [1319, 9003].entries()) {
161 + yield* db.run("INSERT INTO steps VALUES (?, ?)", [
162 + 10 + idx,
163 + new Uint8Array(
164 + protoBytes(9, [
165 + ...protoNumber(1, id),
166 + ...protoNumber(2, 10),
167 + ...(idx === 0 ? protoText(11, "r-0") : []),
168 + ]),
169 + ),
170 + ]);
171 + }
172 + yield* db.run("INSERT INTO steps VALUES (?, ?)", [
173 + 2,
174 + new Uint8Array(protoBytes(9, [...protoNumber(1, 1319), ...protoNumber(2, 10)])),
175 + ]);
176 + yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
177 + 3,
178 + new Uint8Array(
179 + protoBytes(1, [
180 + ...protoText(19, "Gemini 9.3 Flash"),
181 + ...protoBytes(17, protoBytes(2, [...protoNumber(1, 9004), ...protoNumber(2, 10)])),
182 + ]),
183 + ),
184 + ]);
185 + yield* db.run("INSERT INTO steps VALUES (?, ?)", [
186 + 4,
187 + new Uint8Array([
188 + ...protoBytes(24, protoText(12, "Claude 5.5 Opus (Thinking)")),
189 + ...protoBytes(9, [...protoNumber(1, 9005), ...protoNumber(2, 10)]),
190 + ]),
191 + ]);
192 + }),
193 + );
194 + const result = yield* readAntigravityUsage(dir, 0);
195 + assert.deepStrictEqual(result.errors, []);
196 + assert.deepStrictEqual(
197 + records(result)
198 + .map(({ model }) => model)
199 + .sort(),
200 + [
201 + "gemini-9.1-flash",
202 + "antigravity-model-9003",
203 + "antigravity-model-1319",
204 + "claude-opus-4-6",
205 + "gemini-9.2-flash",
206 + "claude-opus-4-6",
207 + "antigravity-model-9004",
208 + "claude-opus-5-5-thinking",
209 + ].sort(),
210 + );
211 + }).pipe(Effect.provide(NodeServices.layer)),
212 + );
213 +
214 it.effect(
215 "deduplicates Antigravity generation and step usage while preserving retry model and token buckets",
216 () =>
@@ -210,14 +349,14 @@ describe("readAntigravityUsage", () => {
349 [
350 ["gemini-3.7-flash-control", "gemini-3.7-flash"],
351 ["gemini-3.8-flash-medium", "gemini-3.8-flash"],
213 - ["gemini-3-flash-agent", "gemini-3-flash-preview"],
352 + ["gemini-3.5-flash-high", "gemini-3.5-flash"],
353 ["gemini-3.8-flash-high", "gemini-3.8-flash"],
354 ],
355 );
356 const table = parseRateTable({
357 "gemini-3.7-flash": { input_cost_per_token: 0.75e-6, output_cost_per_token: 3.75e-6 },
358 "gemini-3.8-flash": { input_cost_per_token: 0.75e-6, output_cost_per_token: 3.75e-6 },
220 - "gemini-3-flash-preview": { input_cost_per_token: 0.5e-6, output_cost_per_token: 3e-6 },
359 + "gemini-3.5-flash": { input_cost_per_token: 0.5e-6, output_cost_per_token: 3e-6 },
360 });
361 const priced = records(result).map((record) => priceUsage(table, record));
362 assert.deepStrictEqual(
@@ -237,7 +376,14 @@ describe("readAntigravityUsage", () => {
376 yield* seedDatabase(path.join(dir, "effort.db"), (db) =>
377 Effect.gen(function* () {
378 yield* createTables(db);
240 - for (const [idx, name] of ["gemini-4-argon-high", "gemini-4-argon"].entries()) {
379 + for (const [idx, name] of [
380 + "gemini-4-argon-high",
381 + "gemini-4-argon",
382 + "gemini-3.7-flash-safety-le",
383 + "gemini-3-flash-agent",
384 + "gemini-3-flash",
385 + "gemini-default",
386 + ].entries()) {
387 yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [
388 idx,
389 new Uint8Array(protoBytes(1, protoText(19, name))),
@@ -255,6 +401,10 @@ describe("readAntigravityUsage", () => {
401 [
402 ["gemini-4-argon-high", "gemini-4-argon"],
403 ["gemini-4-argon", undefined],
404 + ["gemini-3.7-flash-safety-le", "gemini-3.7-flash"],
405 + ["gemini-3-flash-agent", "gemini-3.5-flash"],
406 + ["gemini-3-flash", "gemini-3-flash-preview"],
407 + ["gemini-default", undefined],
408 ],
409 );
410 }).pipe(Effect.provide(NodeServices.layer)),
apps/server/src/provider/Drivers/antigravityUsageReader.ts
+126 -45
@@ -78,6 +78,8 @@ const timestamp = (value: Fields) => {
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.
83 const MODEL_IDS: Record<number, string> = {
84 246: "gemini-2.5-pro",
85 312: "gemini-2.5-flash",
@@ -92,6 +94,7 @@ const MODEL_IDS: Record<number, string> = {
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",
@@ -100,19 +103,29 @@ const MODEL_IDS: Record<number, string> = {
103 1018: "gemini-3-flash-preview",
104 1084: "gemini-3-flash-preview",
105 1047: "gemini-3-flash-preview",
103 - 1020: "gemini-3.5-flash-low",
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",
106 - 1132: "gemini-3-flash-agent",
107 - 1133: "gemini-3-flash-agent",
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.
@@ -121,28 +134,47 @@ function withRateModel(record: UsageRecord): UsageRecord {
134 /-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/,
135 "",
136 );
124 - const rateModel = base === "gemini-3-flash" ? "gemini-3-flash-preview" : base;
137 + const rateModel = /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(record.model)
138 + ? "gemini-3.5-flash"
139 + : record.model === "gemini-3.7-flash-safety-le"
140 + ? "gemini-3.7-flash"
141 + : base === "gemini-3-flash"
142 + ? "gemini-3-flash-preview"
143 + : base;
144 return rateModel === record.model ? record : { ...record, rateModel };
145 }
146
128 -function modelName(name: string, id: number): string {
147 +function modelName(name: string): string {
148 if (name) {
149 const normalized = name
150 .toLowerCase()
132 - .replace(/\s*\([^)]*\)\s*$/, "")
133 - .replaceAll(" ", "-");
151 + .replace(/\s*\(([^)]*)\)\s*$/, "-$1")
152 + .replace(/\s+/g, "-");
153 if (normalized.startsWith("claude-")) {
154 return normalized
136 - .replace(/^claude-(4(?:\.\d+)?)-(sonnet|opus|haiku)/, "claude-$2-$1")
155 + .replace(/^claude-(\d+(?:\.\d+)?)-(sonnet|opus|haiku)/, "claude-$2-$1")
156 .replaceAll(".", "-");
157 }
158 return normalized;
159 }
141 - return MODEL_IDS[id] ?? (id > 0 ? `antigravity-model-${id}` : "");
160 + return "";
161 +}
162 +
163 +function isConcreteModel(model: string): boolean {
164 + return (
165 + /^(?:gemini-\d|claude-(?:sonnet|opus|haiku)-\d|gpt-)/.test(model) &&
166 + !/^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model)
167 + );
168 +}
169 +
170 +function rememberModel(models: Map<number, string | null>, id: number, model: string | null) {
171 + const previous = models.get(id);
172 + models.set(id, previous === undefined || previous === model ? model : null);
173 }
174
175 interface Metadata {
176 model: string;
177 + modelId: number;
178 timestampMs: number | null;
179 usages: Fields[];
180 }
@@ -156,17 +188,19 @@ function metadata(bytes: Uint8Array, step: boolean): Metadata {
188 const model = step ? nested(data, 24) : data;
189 const usage = bytesAt(data, step ? 9 : 4);
190 // Copy the usage bytes: subarrays kept in usages would hold each row's whole blob alive.
159 - const usages = usage === undefined ? [] : [fields(usage.slice())];
191 + const primaryUsage = usage === undefined ? undefined : fields(usage.slice());
192 + const usages = primaryUsage === undefined ? [] : [primaryUsage];
193 for (const retry of data.get(step ? 28 : 17) ?? []) {
194 if (!(retry instanceof Uint8Array)) throw new Error("Invalid retry metadata");
195 const retryUsage = bytesAt(fields(retry), 2);
196 if (retryUsage !== undefined) usages.push(fields(retryUsage.slice()));
197 }
198 + const names = [textAt(model, step ? 12 : 19), textAt(model, step ? 8 : 21)].map(modelName);
199 return {
166 - model: modelName(
167 - textAt(model, step ? 12 : 19) || textAt(model, step ? 8 : 21),
168 - numberAt(model, step ? 1 : 3),
169 - ),
200 + model:
201 + names.find(isConcreteModel) ?? names.find((name) => name && !/^model[_-]/.test(name)) ?? "",
202 + modelId:
203 + numberAt(model, step ? 1 : 3) || (primaryUsage === undefined ? 0 : numberAt(primaryUsage, 1)),
204 timestampMs: step
205 ? (timestamp(nested(data, 8)) ?? timestamp(nested(data, 1)))
206 : timestamp(nested(nested(data, 9), 4)),
@@ -181,6 +215,8 @@ function blob(value: unknown): Uint8Array {
215
216 interface UsageCandidate {
217 record: UsageRecord;
218 + modelId: number;
219 + modelQuality: number;
220 keys: readonly string[];
221 timestampQuality: number;
222 }
@@ -274,9 +310,23 @@ const readDatabase = Effect.fn("readDatabase")(function* (
310 true,
311 )
312 : [];
277 - return yield* decode(() =>
278 - usageCandidates(sessionId, generations, steps, trajectoryTimestamp, fallbackTimestamp),
279 - );
313 + return yield* decode(() => {
314 + const models = new Map<number, string | null>();
315 + for (const { entry } of [...generations, ...steps]) {
316 + if (entry.modelId > 0 && isConcreteModel(entry.model))
317 + rememberModel(models, entry.modelId, entry.model);
318 + }
319 + return {
320 + candidates: usageCandidates(
321 + sessionId,
322 + generations,
323 + steps,
324 + trajectoryTimestamp,
325 + fallbackTimestamp,
326 + ),
327 + models,
328 + };
329 + });
330 }).pipe(sql.withTransaction);
331 });
332
@@ -288,13 +338,23 @@ function usageCandidates(
338 fallbackTimestamp: number,
339 ): UsageCandidate[] {
340 const records: UsageCandidate[] = [];
291 - const generationModels = new Map(generations.map(({ idx, entry }) => [idx, entry.model]));
341 + const generationModels = new Map(generations.map(({ idx, entry }) => [idx, entry]));
342 for (const [source, entries] of [
343 ["step", steps],
344 ["generation", generations],
345 ] as const) {
346 for (const [index, { idx, entry }] of entries.entries()) {
347 for (const [usageIndex, usage] of entry.usages.entries()) {
348 + const modelId = numberAt(usage, 1) || entry.modelId;
349 + const generation = source === "step" ? generationModels.get(idx) : undefined;
350 + // A retry can use a different model than its enclosing generation or step.
351 + const matches = (metadata: Metadata) => modelId === 0 || metadata.modelId === modelId;
352 + const model =
353 + matches(entry) && entry.model
354 + ? entry.model
355 + : generation && matches(generation)
356 + ? generation.model
357 + : "";
358 const outputTokens = Math.max(numberAt(usage, 3), numberAt(usage, 9) + numberAt(usage, 10));
359 const totals = {
360 uncachedInputTokens: numberAt(usage, 2),
@@ -319,12 +379,7 @@ function usageCandidates(
379 provider: "antigravity",
380 sessionId,
381 timestampMs: entry.timestampMs ?? trajectoryTimestamp ?? fallbackTimestamp,
322 - model:
323 - MODEL_IDS[numberAt(usage, 1)] ||
324 - entry.model ||
325 - (source === "step" ? generationModels.get(idx) : "") ||
326 - modelName("", numberAt(usage, 1)) ||
327 - "antigravity-unknown",
382 + model,
383 totals,
384 reportedCostUsd: null,
385 speed: "standard",
@@ -332,6 +387,8 @@ function usageCandidates(
387 };
388 records.push({
389 record,
390 + modelId,
391 + modelQuality: isConcreteModel(model) ? 4 : model ? 1 : 0,
392 keys,
393 timestampQuality: entry.timestampMs !== null ? 2 : trajectoryTimestamp !== null ? 1 : 0,
394 });
@@ -343,7 +400,7 @@ function usageCandidates(
400
401 interface CachedDatabase {
402 readonly fingerprint: string;
346 - readonly candidates: readonly UsageCandidate[];
403 + readonly data: Effect.Success<ReturnType<typeof readDatabase>>;
404 }
405
406 /** Fingerprint canonical DB/WAL paths by size, mtime and ctime; WAL holds new rows, and ctime catches restored mtimes. */
@@ -362,6 +419,8 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
419 : conversationsDirectories;
420 const files: Array<{ root: string; path: string; records: UsageRecord[] }> = [];
421 const errors: string[] = [];
422 + const models = new Map<number, string | null>();
423 + const pending: Array<{ data: CachedDatabase["data"]; fileIndex: number }> = [];
424 const identities = new Map<string, number>();
425 const groups: Array<
426 UsageCandidate & { parent: number; size: number; owner: number; fileIndex: number }
@@ -384,6 +443,12 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
443 const target = groups[a]!;
444 const source = groups[b]!;
445 const first = target.owner < source.owner ? target : source;
446 + const bestModel =
447 + source.modelQuality === target.modelQuality
448 + ? first
449 + : source.modelQuality > target.modelQuality
450 + ? source
451 + : target;
452 const bestTime =
453 source.timestampQuality > target.timestampQuality ||
454 (source.timestampQuality === target.timestampQuality &&
@@ -394,12 +459,7 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
459 const y = source.record.totals;
460 target.record = {
461 ...first.record,
397 - model:
398 - first.record.model === "antigravity-unknown"
399 - ? first === target
400 - ? source.record.model
401 - : target.record.model
402 - : first.record.model,
462 + model: bestModel.record.model,
463 timestampMs: bestTime.record.timestampMs,
464 totals: {
465 uncachedInputTokens: Math.max(x.uncachedInputTokens, y.uncachedInputTokens),
@@ -410,6 +470,7 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
470 },
471 };
472 target.timestampQuality = bestTime.timestampQuality;
473 + target.modelQuality = bestModel.modelQuality;
474 target.owner = first.owner;
475 target.fileIndex = first.fileIndex;
476 target.size += source.size;
@@ -441,14 +502,12 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
502 const wal = yield* fingerprintOf(`${path}-wal`).pipe(Effect.option);
503 const fingerprint = `${part}/${wal._tag === "Some" ? wal.value.part : "-"}`;
504 const cached = cache?.get(canonical);
444 - if (cached?.fingerprint === fingerprint) return cached.candidates;
445 - const candidates = yield* readDatabase(
446 - path,
447 - pathService.basename(path, ".db"),
448 - stat.mtimeMs,
449 - ).pipe(Effect.provide(NodeSqliteClient.layer({ filename: path, readonly: true })));
450 - cache?.set(canonical, { fingerprint, candidates });
451 - return candidates;
505 + if (cached?.fingerprint === fingerprint) return cached.data;
506 + const data = yield* readDatabase(path, pathService.basename(path, ".db"), stat.mtimeMs).pipe(
507 + Effect.provide(NodeSqliteClient.layer({ filename: path, readonly: true })),
508 + );
509 + cache?.set(canonical, { fingerprint, data });
510 + return data;
511 });
512 const walk = Effect.fn("antigravityUsageReader.walk")(function* (
513 directory: string,
@@ -477,19 +536,19 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
536 if (type === "Directory") {
537 yield* walk(path, root);
538 } else if ((type === "File" || type === null) && name.endsWith(".db")) {
480 - const candidates = yield* readFile(path).pipe(
539 + const data = yield* readFile(path).pipe(
540 Effect.catch(() => {
541 errors.push(path);
542 return Effect.succeed(null);
543 }),
544 );
486 - if (candidates === null) continue;
545 + if (data === null) continue;
546 + for (const [id, model] of data.models) {
547 + rememberModel(models, id, model);
548 + }
549 const fileIndex = files.length;
550 files.push({ root, path, records: [] });
489 - for (const [index, candidate] of candidates.entries()) {
490 - append(candidate, fileIndex);
491 - if (index % 256 === 255) yield* Effect.yieldNow;
492 - }
551 + pending.push({ data, fileIndex });
552 }
553 }
554 });
@@ -497,6 +556,28 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
556 if (cache !== undefined) {
557 for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);
558 }
559 + for (const { data, fileIndex } of pending) {
560 + for (const [index, candidate] of data.candidates.entries()) {
561 + const learned = models.get(candidate.modelId);
562 + const fallback = learned === null ? undefined : MODEL_IDS[candidate.modelId];
563 + const model =
564 + (candidate.modelQuality === 4 ? candidate.record.model : "") ||
565 + learned ||
566 + fallback ||
567 + candidate.record.model ||
568 + (candidate.modelId > 0 ? `antigravity-model-${candidate.modelId}` : "antigravity-unknown");
569 + append(
570 + {
571 + ...candidate,
572 + record: { ...candidate.record, model },
573 + modelQuality:
574 + candidate.modelQuality === 4 ? 4 : learned ? 3 : fallback ? 2 : candidate.modelQuality,
575 + },
576 + fileIndex,
577 + );
578 + if (index % 256 === 255) yield* Effect.yieldNow;
579 + }
580 + }
581 for (const [index, group] of groups.entries()) {
582 if (group.parent === index && group.record.timestampMs >= sinceMs) {
583 files[group.fileIndex]!.records.push(withRateModel(group.record));