fix(antigravity): count cache reads and price the standalone app's model (#1655)

* fix(antigravity): count cache reads and price the standalone app's model

The standalone Antigravity app (2.19) stores usage as ModelUsageStats in
gen_metadata. Field 5 (cache_read_tokens) was never read, on the SQLite
path or the RPC path, so every cached prompt token was dropped. Fields 9
and 10 are thinking and response output, the reverse of what the SQLite
path assumed. The rows carry only MODEL_PLACEHOLDER_M16 and
"gemini-pro-default", so the model priced at $0.

Read cache read (and cache write) in both paths, read 9/10 in the right
order, drop the input fallback to field 1 (the model enum), and map the
placeholders seen in the app's own model catalog, flagged as estimated.
Bump the antigravity results cache, its parse version and the daily cache.

* fix(antigravity): keep .pb history across the cache bump, step times, 200k tier

With the results cache at v8 and Antigravity closed, .pb cascades had no
entry and no server, so they vanished until the app was next opened.
Serve the v7 entry meanwhile, stored with mtimeMs -1, and preload the
results cache so the session cache reparses such sources and the next run
with the server up re-fetches them with cache reads.

Standalone .db rows without created_at take their first step's time
(steps.metadata #1), which equals created_at wherever both exist, instead
of the file mtime.

Price antigravity at the Gemini long-context tier: add it to
TIERED_PRICING_PROVIDERS and pass the provider at both calculateCost sites.
This commit is contained in:
Resham Joshi 2026-10-06 20:58:31 +02:00 • committed by GitHub
parent 2444afb610
commit 253c9fe85a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 321 additions and 32 deletions

View file

@ -288,7 +288,14 @@ import type { DateRange, ProjectSummary } from './types.js'
// tag instead of the session's last write. Settled days re-derive; a session
// that crossed midnight moves calls to an earlier day, so cursor-agent joins
// PENDING_REDERIVE_PROVIDER_VERSIONS at 58.
export const DAILY_CACHE_VERSION = 58
// v59: Antigravity reads cache-read tokens from gen_metadata and the RPC usage,
// and the standalone app's placeholder-only model (MODEL_PLACEHOLDER_M16, stored
// as "gemini-pro-default") prices as gemini-3.1-pro-high instead of $0, with
// the above-200k tier. Cache read and cost only rise. Standalone rows without
// created_at move from the file-mtime day to their first step's day, so a
// session that crossed midnight moves calls to an earlier day, and antigravity
// joins PENDING_REDERIVE_PROVIDER_VERSIONS at 59.
export const DAILY_CACHE_VERSION = 59
const MIN_SUPPORTED_VERSION = 28
/// Providers whose per-day CALL COUNT means something different at
@ -331,6 +338,9 @@ const PENDING_REDERIVE_PROVIDER_VERSIONS: Readonly<Record<string, number>> = {
devin: 46,
// 58: transcript turns moved from the session's last write to prompt time.
'cursor-agent': 58,
// 59: standalone rows without created_at moved from the file mtime to the
// first step's time.
antigravity: 59,
}
function providersPendingRederiveFrom(fromVersion: number): string[] {

View file

@ -179,7 +179,9 @@ const GROK_4_6_HIGH_PROMPT_COSTS = buildCosts(4e-6, 12e-6, null, 1e-6, null)
// codex sites and the parser.ts central recompute pass it; the Claude journal
// paths and the copilot residual path do not, so a newly added provider whose
// calls flow through those sites would silently stay tierless).
export const TIERED_PRICING_PROVIDERS: ReadonlySet<string> = new Set(['codex'])
// antigravity has no per-token bill of its own; its cost is the Gemini API
// equivalent, and the Gemini API bills the above-200k tier per request.
export const TIERED_PRICING_PROVIDERS: ReadonlySet<string> = new Set(['codex', 'antigravity'])
// Swap in the vendor's high tier when a request's prompt crosses the published
// threshold. A user-set priceOverride wins over any tier: the override row

View file

@ -10,7 +10,7 @@ import { resolveSubagentAttribution, sessionIdentity } from './sessions-report.j
import { normalizeContentBlocks, flatSlice, flatString } from './content-utils.js'
import { discoverAllSessions, discoverAllSessionsWithFailures, getProvider } from './providers/index.js'
import { evictCachedCodexResults, flushCodexCache, readCachedCodexResults, withCodexCacheDirectory, writeCachedCodexResults } from './codex-cache.js'
import { antigravityCascadeIdFromPath, flushAntigravityCache, shouldReparseAntigravitySource } from './providers/antigravity.js'
import { antigravityCascadeIdFromPath, flushAntigravityCache, preloadAntigravityCache, shouldReparseAntigravitySource } from './providers/antigravity.js'
import { getClaudeConfigDirs, getDesktopSessionsDirs } from './providers/claude.js'
import { kimicodeLineageForSource } from './providers/kimicode.js'
import { isSqliteBusyError } from './sqlite.js'
@ -3483,6 +3483,7 @@ export async function parseProviderSources(
// for this whole parse transaction so a host changing CODEBURN_CACHE_DIR
// before the final flush cannot redirect A's dirty state into (or past) B.
const antigravityCacheDir = providerName === 'antigravity' ? getCodeburnCacheDir() : undefined
if (antigravityCacheDir && !readOnly) await preloadAntigravityCache(antigravityCacheDir)
const section = getOrCreateProviderSection(diskCache, providerName)
if (providerName === 'hermes' && !readOnly) {

View file

@ -50,7 +50,7 @@ function conversationRoots(): readonly AntigravityConversationRoot[] {
},
]
}
const CACHE_VERSION = 7
const CACHE_VERSION = 8
export const ANTIGRAVITY_CACHE_VERSION = CACHE_VERSION
export const ANTIGRAVITY_LEGACY_CACHE_FILE = 'antigravity-results.json'
export function antigravityCacheFileName(version = CACHE_VERSION): string {
@ -77,6 +77,8 @@ type UsageEntry = {
outputTokens: string
thinkingOutputTokens?: string
responseOutputTokens?: string
cacheReadTokens?: string
cacheWriteTokens?: string
apiProvider: string
responseId?: string
}
@ -190,6 +192,7 @@ const cachedServers = new Map<string, Cached<ServerInfo | null>>()
const cachedModelMaps = new Map<string, Cached<ModelMap>>()
type AntigravityCacheState = { cache: AntigravityCache; dirty: boolean }
const cacheStates = new Map<string, AntigravityCacheState>()
const previousVersionCascades = new Map<string, Record<string, CachedCascade>>()
// Dropped by the resident RSS guard. A dirty state holds cascades not yet on
// disk, so it stays resident until its own flush publishes it. The server and
@ -198,6 +201,7 @@ const cacheStates = new Map<string, AntigravityCacheState>()
export function clearAntigravityCacheStates(): void {
cachedServers.clear()
cachedModelMaps.clear()
previousVersionCascades.clear()
for (const [dir, state] of cacheStates) {
if (!state.dirty) cacheStates.delete(dir)
}
@ -418,6 +422,28 @@ async function loadCache(cacheDir: string): Promise<AntigravityCacheState> {
return state
}
// A cache-version bump drops every .pb cascade, and .pb files are readable
// only through the RPC, so with Antigravity closed they would vanish until it
// is next opened. Serve the previous version's entry meanwhile; mtimeMs -1
// makes the next run with the server up re-fetch it.
async function adoptPreviousVersionCascade(cacheDir: string, state: AntigravityCacheState, cascadeId: string): Promise<CachedCascade | undefined> {
let cascades = previousVersionCascades.get(cacheDir)
if (!cascades) {
cascades = {}
try {
const cache = JSON.parse(await readFile(join(cacheDir, antigravityCacheFileName(CACHE_VERSION - 1)), 'utf-8')) as AntigravityCache
if (cache.version === CACHE_VERSION - 1 && cache.cascades && typeof cache.cascades === 'object') cascades = cache.cascades
} catch { /* no previous cache */ }
previousVersionCascades.set(cacheDir, cascades)
}
const previous = cascades[cascadeId]
if (!previous?.calls?.length) return undefined
const adopted = { mtimeMs: -1, sizeBytes: previous.sizeBytes, calls: previous.calls }
state.cache.cascades[cascadeId] = adopted
state.dirty = true
return adopted
}
async function flushCache(liveCascadeIds?: Set<string>, cacheDir = currentCacheDir()): Promise<void> {
const state = cacheStates.get(cacheDir)
if (!state) return
@ -782,15 +808,32 @@ function antigravitySqliteMetadataAttributes(chatFields: readonly ProtoField[]):
return attributes
}
function antigravitySqliteModel(chatFields: readonly ProtoField[]): string {
// The standalone app (2.19) writes only the placeholder enum and a generic
// "gemini-pro-default" into gen_metadata, no display name. These are the ids
// its own GetAvailableModels catalog resolved those placeholders to on 6 Oct
// 2026 (the same ids the RPC path derives). A later app build can repoint a
// placeholder, so calls resolved here are flagged as estimated.
const PLACEHOLDER_MODELS: Record<string, string> = {
MODEL_PLACEHOLDER_M16: 'gemini-3.1-pro-high',
MODEL_PLACEHOLDER_M37: 'gemini-3.1-pro-high',
MODEL_PLACEHOLDER_M36: 'gemini-3.1-pro-low',
MODEL_PLACEHOLDER_M84: 'gemini-3.5-flash-high',
MODEL_PLACEHOLDER_M18: 'gemini-3-flash',
MODEL_PLACEHOLDER_M35: 'claude-sonnet-4-6',
MODEL_PLACEHOLDER_M26: 'claude-opus-4-6-thinking',
}
function antigravitySqliteModel(chatFields: readonly ProtoField[]): { model: string; estimated: boolean } {
const attributes = antigravitySqliteMetadataAttributes(chatFields)
const displayName = protoFieldText(firstProtoField(chatFields, 21))
const placeholderModel = PLACEHOLDER_MODELS[attributes.get('model_enum') ?? '']
if (!displayName && placeholderModel) return { model: placeholderModel, estimated: true }
const rawModel = protoFieldText(firstProtoField(chatFields, 19))
?? attributes.get('model_enum')
?? displayName
?? 'unknown'
return getCanonicalModelId(rawModel, displayName)
return { model: getCanonicalModelId(rawModel, displayName), estimated: false }
}
// Decode a proto field that carries a time into an ISO-8601 string. Antigravity
@ -963,16 +1006,21 @@ function buildCallFromSqliteGenMetadataRow(
row: AntigravityGenMetadataRow,
rootFields: readonly ProtoField[],
turnTools?: TurnTools,
firstStepTimestamp = '',
): ParsedProviderCall | null {
const chatFields = parseProtoFields(protoFieldBytes(firstProtoField(rootFields, 1)) ?? new Uint8Array())
const usageFields = parseProtoFields(protoFieldBytes(firstProtoField(chatFields, 4)) ?? new Uint8Array())
if (usageFields.length === 0) return null
// exa.codeium_common_pb.ModelUsageStats: 1 model enum, 2 input (uncached),
// 3 output (thinking + response), 4 cache write, 5 cache read,
// 9 thinking output, 10 response output, 11 response id.
const inputTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 2))
|| protoFieldPositiveInteger(firstProtoField(usageFields, 1))
const totalOutputTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 3))
let responseTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 9))
let thinkingTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 10))
const cacheWriteTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 4))
const cacheReadTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 5))
let thinkingTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 9))
let responseTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 10))
if (responseTokens === 0 && thinkingTokens === 0) {
responseTokens = totalOutputTokens
@ -984,26 +1032,27 @@ function buildCallFromSqliteGenMetadataRow(
if (inputTokens === 0 && totalOutputTokens === 0) return null
const responseId = antigravitySqliteResponseId(usageFields, String(row.idx))
const model = antigravitySqliteModel(chatFields)
const { model, estimated } = antigravitySqliteModel(chatFields)
const pricingModel = normalizePricingModel(model)
const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, 0, 0, 0)
const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, cacheWriteTokens, cacheReadTokens, 0, 'standard', 0, 'antigravity')
return {
provider: 'antigravity',
model,
inputTokens,
outputTokens: responseTokens,
cacheCreationInputTokens: 0,
cacheReadInputTokens: 0,
cacheCreationInputTokens: cacheWriteTokens,
cacheReadInputTokens: cacheReadTokens,
cachedInputTokens: 0,
reasoningTokens: thinkingTokens,
webSearchRequests: 0,
costUSD,
...(estimated ? { costIsEstimated: true } : {}),
tools: turnTools?.tools ?? [],
bashCommands: turnTools?.bashCommands ?? [],
...(turnTools?.skills && turnTools.skills.length > 0 ? { skills: turnTools.skills } : {}),
...(turnTools?.subagentTypes && turnTools.subagentTypes.length > 0 ? { subagentTypes: turnTools.subagentTypes } : {}),
timestamp: antigravitySqliteCreatedAt(chatFields),
timestamp: antigravitySqliteCreatedAt(chatFields) || firstStepTimestamp,
speed: 'standard',
deduplicationKey: `antigravity:${cascadeId}:${responseId}`,
userMessage: '',
@ -1039,7 +1088,15 @@ function buildCallsFromSqliteGenMetadata(
}
}
const call = buildCallFromSqliteGenMetadataRow(cascadeId, row, rootFields, turnTools)
// The standalone app leaves out ChatStartMetadata.created_at; the
// generation's first step carries the same time (steps.metadata #1, a
// Timestamp), which matches created_at to the second where both exist.
const firstStep = stepIndices.length > 0 ? stepMap.get(stepIndices[0]!) : undefined
const firstStepTimestamp = firstStep?.metadata
? protoTimestampToIso(firstProtoField(parseProtoFields(genMetadataDataBytes(firstStep.metadata)), 1))
: ''
const call = buildCallFromSqliteGenMetadataRow(cascadeId, row, rootFields, turnTools, firstStepTimestamp)
if (!call) continue
if (seenResponseIds.has(call.deduplicationKey)) continue
seenResponseIds.add(call.deduplicationKey)
@ -1144,6 +1201,8 @@ function buildCallsFromGeneratorMetadata(
const outputTokens = parseInt(usage.outputTokens ?? '0', 10)
const thinkingTokens = parseInt(usage.thinkingOutputTokens ?? '0', 10)
const responseTokens = parseInt(usage.responseOutputTokens ?? '0', 10)
const cacheReadTokens = parseInt(usage.cacheReadTokens ?? '0', 10)
const cacheWriteTokens = parseInt(usage.cacheWriteTokens ?? '0', 10)
if (inputTokens === 0 && outputTokens === 0) continue
@ -1153,15 +1212,15 @@ function buildCallsFromGeneratorMetadata(
const model = dropPlaceholderModelId(modelMap[usage.model] ?? usage.model)
const pricingModel = normalizePricingModel(model)
const timestamp = entry.chatModel?.chatStartMetadata?.createdAt ?? ''
const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, 0, 0, 0)
const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, cacheWriteTokens, cacheReadTokens, 0, 'standard', 0, 'antigravity')
results.push({
provider: 'antigravity',
model,
inputTokens,
outputTokens: responseTokens,
cacheCreationInputTokens: 0,
cacheReadInputTokens: 0,
cacheCreationInputTokens: cacheWriteTokens,
cacheReadInputTokens: cacheReadTokens,
cachedInputTokens: 0,
reasoningTokens: thinkingTokens,
webSearchRequests: 0,
@ -1408,9 +1467,16 @@ async function parseStatusLineCalls(source: SessionSource, seenKeys: Set<string>
export function shouldReparseAntigravitySource(path: string, cachedTurnCount: number): boolean {
if (cachedTurnCount === 0) return true
if (cacheStates.get(currentCacheDir())?.cache.cascades[antigravityCascadeIdFromPath(path)]?.mtimeMs === -1) return true
return isAntigravityStatusLineEventsPath(path)
}
// Loads the results cache before the session cache decides which sources to
// reparse, so a cascade served from the previous cache version is retried.
export async function preloadAntigravityCache(cacheDir: string): Promise<void> {
await loadCache(resolve(cacheDir))
}
async function findCascadeSource(cascadeId: string): Promise<SessionSource | null> {
const sources = await discoverAntigravitySessionSources()
return sources.find(source => {
@ -1604,8 +1670,11 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
const server = await detectServer(antigravityAppDataDirFromSourcePath(source.path))
if (!server) {
if (cached) {
for (const call of cached.calls) {
const fallback = cached ?? (source.path.toLowerCase().endsWith('.pb')
? await adoptPreviousVersionCascade(currentCacheDir(), state, cascadeId)
: undefined)
if (fallback) {
for (const call of fallback.calls) {
applyAntigravityProject(call, source, projectPath)
if (seenKeys.has(call.deduplicationKey)) continue
seenKeys.add(call.deduplicationKey)

View file

@ -587,7 +587,10 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
// token floor on every read, so they must re-parse once for the real dollars
// to land.
warp: 'worktree-project-grouping-v1-est-cost-billing-cost-v1',
antigravity: 'worktree-project-grouping-v7',
// cache-read-v1-est-cost: gen_metadata and RPC usage now carry cache-read
// tokens, fields 9/10 read as thinking/response (they were swapped), and
// placeholder-only models are priced and flagged costIsEstimated.
antigravity: 'worktree-project-grouping-v7-cache-read-v1-est-cost',
// pr-attribution-v1: the parser now reads the `message`/`part` tables for
// per-turn user prompt text and the GitHub PR URLs it references. Cached
// ZCode sessions hold empty userMessage turns and no session prLinks, so