chompyy 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +14 -1
  2. package/dist/advice.js +98 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/approvals.js +129 -0
  6. package/dist/appstate.js +73 -3
  7. package/dist/away.js +48 -5
  8. package/dist/blueprint.js +3 -7
  9. package/dist/board.js +1 -0
  10. package/dist/cli.js +343 -18
  11. package/dist/codexquota.js +106 -0
  12. package/dist/codexusage.js +10 -0
  13. package/dist/config.js +2 -0
  14. package/dist/context.js +30 -0
  15. package/dist/costs.js +41 -2
  16. package/dist/demon.js +20 -0
  17. package/dist/detect.js +38 -6
  18. package/dist/didwork.js +26 -0
  19. package/dist/label.js +33 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +72 -0
  22. package/dist/nudge.js +70 -24
  23. package/dist/pacing.js +16 -1
  24. package/dist/punchcard.js +39 -0
  25. package/dist/questions.js +71 -0
  26. package/dist/recap.js +74 -0
  27. package/dist/receipt.js +48 -0
  28. package/dist/recipe.js +79 -0
  29. package/dist/savings.js +111 -0
  30. package/dist/stamps.js +14 -0
  31. package/dist/suggest.js +15 -5
  32. package/dist/triggers.js +5 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6955 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/dist/wastechecks.js +233 -0
  162. package/package.json +1 -1
@@ -0,0 +1,1731 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { createReadStream } from 'fs';
3
+ import { readdir, readFile, mkdir, stat, open, rename, unlink } from 'fs/promises';
4
+ import { createInterface } from 'readline';
5
+ import { execFile } from 'child_process';
6
+ import { randomBytes } from 'crypto';
7
+ import { basename, dirname, join, resolve } from 'path';
8
+ import { homedir } from 'os';
9
+ import { fileURLToPath } from 'url';
10
+ import https from 'https';
11
+ import { extractBashCommands } from '../bash-utils.js';
12
+ import { getCodeburnCacheDir, readExistingTextFile } from '../cache-dir.js';
13
+ import { calculateCost, ownValue } from '../models.js';
14
+ import { daemonHub } from '../quota/antigravity.js';
15
+ import { isSqliteAvailable, isSqliteBusyError, openDatabase } from '../sqlite.js';
16
+ // Computed on each call rather than frozen at module load so discovery honors
17
+ // the current home directory (env overrides in tests, and any runtime change).
18
+ function conversationRoots() {
19
+ const home = homedir();
20
+ return [
21
+ {
22
+ dir: join(home, '.gemini', 'antigravity', 'conversations'),
23
+ project: 'antigravity',
24
+ extensions: ['.pb', '.db'],
25
+ },
26
+ {
27
+ dir: join(home, '.gemini', 'antigravity-cli', 'conversations'),
28
+ project: 'antigravity-cli',
29
+ extensions: ['.pb', '.db'],
30
+ },
31
+ {
32
+ dir: join(home, '.gemini', 'antigravity-cli', 'implicit'),
33
+ project: 'antigravity-cli',
34
+ extensions: ['.pb'],
35
+ },
36
+ {
37
+ dir: join(home, '.gemini', 'antigravity-ide', 'conversations'),
38
+ project: 'antigravity-ide',
39
+ extensions: ['.pb', '.db'],
40
+ },
41
+ {
42
+ dir: join(home, '.gemini', 'antigravity-ide', 'implicit'),
43
+ project: 'antigravity-ide',
44
+ extensions: ['.pb'],
45
+ },
46
+ ];
47
+ }
48
+ const CACHE_VERSION = 11;
49
+ export const STATUSLINE_KEY_PREFIX = 'antigravity-statusline:';
50
+ export const ANTIGRAVITY_CACHE_VERSION = CACHE_VERSION;
51
+ export const ANTIGRAVITY_LEGACY_CACHE_FILE = 'antigravity-results.json';
52
+ export function antigravityCacheFileName(version = CACHE_VERSION) {
53
+ return `antigravity-results.v${version}.json`;
54
+ }
55
+ const RPC_TIMEOUT_MS = 5000;
56
+ const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
57
+ // Server discovery and model maps are memoized for the process lifetime, which
58
+ // in the resident `serve` daemon means a single transient miss (or an
59
+ // Antigravity restart onto a new port/CSRF) would otherwise disable RPC
60
+ // enrichment forever. Re-probe on a TTL: a good result is trusted for a while,
61
+ // a null/empty (failed) one is retried soon.
62
+ const DETECT_SUCCESS_TTL_MS = 60_000;
63
+ const DETECT_FAILURE_TTL_MS = 5_000;
64
+ const cachedServers = new Map();
65
+ const cachedModelMaps = new Map();
66
+ const cacheStates = new Map();
67
+ const previousVersionCascades = new Map();
68
+ // Dropped by the resident RSS guard. A dirty state holds cascades not yet on
69
+ // disk, so it stays resident until its own flush publishes it. The server and
70
+ // model-map memos carry no unflushed data, so drop them wholesale — the next
71
+ // call re-probes.
72
+ export function clearAntigravityCacheStates() {
73
+ cachedServers.clear();
74
+ cachedModelMaps.clear();
75
+ previousVersionCascades.clear();
76
+ for (const [dir, state] of cacheStates) {
77
+ if (!state.dirty)
78
+ cacheStates.delete(dir);
79
+ }
80
+ }
81
+ let httpsAgent;
82
+ const protoTextDecoder = new TextDecoder('utf-8', { fatal: false });
83
+ const SERVER_PORT_FLAGS = ['https_server_port', 'extension_server_port', 'https-server-port', 'extension-server-port'];
84
+ const CSRF_TOKEN_FLAGS = ['csrf_token', 'extension_server_csrf_token', 'csrf-token', 'extension-server-csrf-token'];
85
+ const APP_DATA_DIR_FLAGS = ['app_data_dir', 'app-data-dir'];
86
+ function getAgent() {
87
+ if (!httpsAgent)
88
+ httpsAgent = new https.Agent({ rejectUnauthorized: false });
89
+ return httpsAgent;
90
+ }
91
+ function currentCacheDir() {
92
+ return resolve(getCodeburnCacheDir());
93
+ }
94
+ function getCachePath(cacheDir) {
95
+ return join(cacheDir, antigravityCacheFileName());
96
+ }
97
+ function getLegacyCachePath(cacheDir) {
98
+ return join(cacheDir, ANTIGRAVITY_LEGACY_CACHE_FILE);
99
+ }
100
+ function isCurrentCache(cache) {
101
+ return cache.version === CACHE_VERSION && !!cache.cascades && typeof cache.cascades === 'object';
102
+ }
103
+ export function getAntigravityStatusLineEventsPath() {
104
+ return join(getCodeburnCacheDir(), 'antigravity-statusline.jsonl');
105
+ }
106
+ function execFileText(command, args, timeout = 3000) {
107
+ return new Promise((resolve, reject) => {
108
+ execFile(command, args, { encoding: 'utf-8', timeout, maxBuffer: 1024 * 1024 }, (err, stdout) => {
109
+ if (err)
110
+ reject(err);
111
+ else
112
+ resolve(stdout);
113
+ });
114
+ });
115
+ }
116
+ function getFlagValue(line, names) {
117
+ for (const name of names) {
118
+ const match = line.match(new RegExp(`--${name}(?:=|\\s+)(?:"([^"]+)"|'([^']+)'|([^\\s]+))`, 'i'));
119
+ const value = match?.[1] ?? match?.[2] ?? match?.[3];
120
+ if (value && !value.startsWith('--'))
121
+ return value;
122
+ }
123
+ return null;
124
+ }
125
+ function isLikelyCsrfToken(value) {
126
+ return value.length >= 16 && /^[A-Za-z0-9._~:/+=-]+$/.test(value);
127
+ }
128
+ function normalizeAppDataDir(value) {
129
+ if (!value)
130
+ return undefined;
131
+ const normalized = value.replace(/\\/g, '/').toLowerCase();
132
+ if (normalized.includes('antigravity-ide'))
133
+ return 'antigravity-ide';
134
+ if (normalized.includes('antigravity-cli'))
135
+ return 'antigravity-cli';
136
+ if (normalized.includes('antigravity'))
137
+ return 'antigravity';
138
+ return undefined;
139
+ }
140
+ export function extractAntigravityAppDataDirFromLine(line) {
141
+ return normalizeAppDataDir(getFlagValue(line, APP_DATA_DIR_FLAGS));
142
+ }
143
+ function parseAntigravityServerCandidateFromLine(line, daemonDir) {
144
+ const lower = line.toLowerCase();
145
+ if (!lower.includes('language_server') || !lower.includes('antigravity'))
146
+ return null;
147
+ const appDataDir = extractAntigravityAppDataDirFromLine(line);
148
+ const flagToken = getFlagValue(line, CSRF_TOKEN_FLAGS);
149
+ const pid = line.match(/^\s*(\d+)\s/)?.[1];
150
+ const hub = !flagToken && pid && appDataDir === 'antigravity' ? daemonHub(pid, daemonDir) : undefined;
151
+ const rawPort = hub ? String(hub.httpsPort) : getFlagValue(line, SERVER_PORT_FLAGS);
152
+ const csrfToken = flagToken ?? hub?.csrfToken;
153
+ if (!rawPort || !csrfToken)
154
+ return null;
155
+ if (!isLikelyCsrfToken(csrfToken))
156
+ return null;
157
+ const port = Number(rawPort);
158
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
159
+ return null;
160
+ return {
161
+ port,
162
+ csrfToken,
163
+ appDataDir,
164
+ };
165
+ }
166
+ export function parseAntigravityServerInfoFromLine(line, daemonDir) {
167
+ const candidate = parseAntigravityServerCandidateFromLine(line, daemonDir);
168
+ return candidate ? { port: candidate.port, csrfToken: candidate.csrfToken } : null;
169
+ }
170
+ export function parseAntigravityServerInfo(lines) {
171
+ for (const line of lines) {
172
+ const server = parseAntigravityServerInfoFromLine(line);
173
+ if (server)
174
+ return server;
175
+ }
176
+ return null;
177
+ }
178
+ function parseAntigravityServerCandidates(lines) {
179
+ return lines
180
+ .map(line => parseAntigravityServerCandidateFromLine(line))
181
+ .filter((server) => server !== null);
182
+ }
183
+ // Antigravity's own model-map config sometimes hasn't caught up with a new
184
+ // model yet, so both the config key and displayName can still be the raw
185
+ // placeholder id (e.g. "MODEL_PLACEHOLDER_M26"). Falling through to that
186
+ // value as the "canonical" model would leak an internal placeholder as a
187
+ // model name; 'unknown' is what this file already uses when no model can be
188
+ // resolved at all (see antigravitySqliteModel).
189
+ const MODEL_PLACEHOLDER_PATTERN = /^MODEL_PLACEHOLDER_/;
190
+ export function dropPlaceholderModelId(model) {
191
+ if (!model)
192
+ return 'unknown';
193
+ return MODEL_PLACEHOLDER_PATTERN.test(model) ? 'unknown' : model;
194
+ }
195
+ function getCanonicalModelId(key, displayName) {
196
+ if (displayName) {
197
+ const lower = displayName.toLowerCase();
198
+ if (lower.includes('3.5 flash')) {
199
+ if (lower.includes('high'))
200
+ return 'gemini-3.5-flash-high';
201
+ if (lower.includes('medium'))
202
+ return 'gemini-3.5-flash-medium';
203
+ if (lower.includes('low'))
204
+ return 'gemini-3.5-flash-low';
205
+ return 'gemini-3.5-flash';
206
+ }
207
+ if (lower.includes('3.1 pro')) {
208
+ if (lower.includes('high'))
209
+ return 'gemini-3.1-pro-high';
210
+ if (lower.includes('low'))
211
+ return 'gemini-3.1-pro-low';
212
+ return 'gemini-3.1-pro';
213
+ }
214
+ if (lower.includes('3.1 flash')) {
215
+ if (lower.includes('image'))
216
+ return 'gemini-3.1-flash-image';
217
+ if (lower.includes('lite'))
218
+ return 'gemini-3.1-flash-lite';
219
+ return 'gemini-3.1-flash';
220
+ }
221
+ if (lower.includes('3 flash')) {
222
+ return 'gemini-3-flash';
223
+ }
224
+ if (lower.includes('3 pro')) {
225
+ return 'gemini-3-pro';
226
+ }
227
+ }
228
+ return dropPlaceholderModelId(key);
229
+ }
230
+ export function extractAntigravityModelMap(resp) {
231
+ if (!resp || typeof resp !== 'object')
232
+ return {};
233
+ const data = resp;
234
+ const models = data.response?.models ?? data.models;
235
+ const map = new Map();
236
+ if (!models)
237
+ return {};
238
+ for (const [key, info] of Object.entries(models)) {
239
+ if (info && typeof info === 'object' && typeof info.model === 'string') {
240
+ const canonicalKey = getCanonicalModelId(key, info.displayName);
241
+ map.set(info.model, canonicalKey);
242
+ }
243
+ }
244
+ return Object.fromEntries(map);
245
+ }
246
+ export function extractAntigravityGeneratorMetadata(resp) {
247
+ if (!resp || typeof resp !== 'object')
248
+ return [];
249
+ const data = resp;
250
+ const metadata = data.response?.generatorMetadata ?? data.generatorMetadata;
251
+ return Array.isArray(metadata) ? metadata : [];
252
+ }
253
+ async function loadCache(cacheDir) {
254
+ const inMemory = cacheStates.get(cacheDir);
255
+ if (inMemory)
256
+ return inMemory;
257
+ const versioned = await readExistingTextFile(getCachePath(cacheDir));
258
+ if (versioned.status === 'ok') {
259
+ try {
260
+ const cache = JSON.parse(versioned.text);
261
+ if (isCurrentCache(cache)) {
262
+ const state = { cache, dirty: false };
263
+ cacheStates.set(cacheDir, state);
264
+ return state;
265
+ }
266
+ }
267
+ catch { /* present but invalid */ }
268
+ const invalid = {
269
+ cache: { version: CACHE_VERSION, cascades: {} },
270
+ dirty: false,
271
+ };
272
+ cacheStates.set(cacheDir, invalid);
273
+ return invalid;
274
+ }
275
+ if (versioned.status === 'unreadable') {
276
+ const invalid = {
277
+ cache: { version: CACHE_VERSION, cascades: {} },
278
+ dirty: false,
279
+ };
280
+ cacheStates.set(cacheDir, invalid);
281
+ return invalid;
282
+ }
283
+ // Versioned file is absent (ENOENT). Adopt the unsuffixed file only when its
284
+ // version matches — old binaries still own that path; we never write or delete it.
285
+ try {
286
+ const raw = await readFile(getLegacyCachePath(cacheDir), 'utf-8');
287
+ const cache = JSON.parse(raw);
288
+ if (isCurrentCache(cache)) {
289
+ const state = { cache, dirty: false };
290
+ cacheStates.set(cacheDir, state);
291
+ return state;
292
+ }
293
+ }
294
+ catch { /* no legacy cache or invalid */ }
295
+ const state = {
296
+ cache: { version: CACHE_VERSION, cascades: {} },
297
+ dirty: false,
298
+ };
299
+ cacheStates.set(cacheDir, state);
300
+ return state;
301
+ }
302
+ // A cache-version bump drops every .pb cascade, and .pb files are readable
303
+ // only through the RPC, so with Antigravity closed they would vanish until it
304
+ // is next opened. Serve the previous version's entry meanwhile; mtimeMs -1
305
+ // makes the next run with the server up re-fetch it.
306
+ async function adoptPreviousVersionCascade(cacheDir, state, cascadeId) {
307
+ let cascades = previousVersionCascades.get(cacheDir);
308
+ if (!cascades) {
309
+ cascades = {};
310
+ try {
311
+ const cache = JSON.parse(await readFile(join(cacheDir, antigravityCacheFileName(CACHE_VERSION - 1)), 'utf-8'));
312
+ if (cache.version === CACHE_VERSION - 1 && cache.cascades && typeof cache.cascades === 'object')
313
+ cascades = cache.cascades;
314
+ }
315
+ catch { /* no previous cache */ }
316
+ previousVersionCascades.set(cacheDir, cascades);
317
+ }
318
+ const previous = cascades[cascadeId];
319
+ if (!previous?.calls?.length)
320
+ return undefined;
321
+ const adopted = { mtimeMs: -1, sizeBytes: previous.sizeBytes, calls: previous.calls };
322
+ state.cache.cascades[cascadeId] = adopted;
323
+ state.dirty = true;
324
+ return adopted;
325
+ }
326
+ async function flushCache(liveCascadeIds, cacheDir = currentCacheDir()) {
327
+ const state = cacheStates.get(cacheDir);
328
+ if (!state)
329
+ return;
330
+ const memCache = state.cache;
331
+ // If the caller supplied liveCascadeIds, we must run the eviction step
332
+ // even when no cascade was added or updated this run; otherwise deleted
333
+ // .pb files would persist in the cache forever once it stops getting
334
+ // dirty writes. Mark the cache dirty when an eviction happens so the
335
+ // file write below proceeds.
336
+ if (liveCascadeIds) {
337
+ for (const id of Object.keys(memCache.cascades)) {
338
+ if (!liveCascadeIds.has(id)) {
339
+ delete memCache.cascades[id];
340
+ state.dirty = true;
341
+ }
342
+ }
343
+ }
344
+ if (!state.dirty)
345
+ return;
346
+ try {
347
+ await mkdir(cacheDir, { recursive: true });
348
+ const finalPath = getCachePath(cacheDir);
349
+ const tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp`;
350
+ const handle = await open(tempPath, 'w', 0o600);
351
+ try {
352
+ await handle.writeFile(JSON.stringify(memCache), { encoding: 'utf-8' });
353
+ await handle.sync();
354
+ }
355
+ finally {
356
+ await handle.close();
357
+ }
358
+ try {
359
+ await rename(tempPath, finalPath);
360
+ }
361
+ catch {
362
+ try {
363
+ await unlink(tempPath);
364
+ }
365
+ catch { /* cleanup */ }
366
+ }
367
+ state.dirty = false;
368
+ }
369
+ catch { /* best-effort */ }
370
+ }
371
+ async function readProcessCommandLines() {
372
+ if (process.platform === 'win32') {
373
+ const script = [
374
+ "$ErrorActionPreference = 'SilentlyContinue'",
375
+ '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
376
+ "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -like '*language_server*' -and $_.CommandLine -like '*antigravity*' } | ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }",
377
+ ].join('; ');
378
+ const output = await execFileText('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script], 5000);
379
+ return output.split(/\r?\n/);
380
+ }
381
+ const output = await execFileText('ps', ['-ww', '-eo', 'pid=,args=']);
382
+ return output.split('\n');
383
+ }
384
+ async function resolveEphemeralPort(csrfToken, appDataDir) {
385
+ if (process.platform === 'win32') {
386
+ try {
387
+ const script = [
388
+ "$ErrorActionPreference = 'SilentlyContinue'",
389
+ '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
390
+ "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -like '*language_server*' -and $_.CommandLine -like '*antigravity*' } | ForEach-Object { @{ PID = $_.ProcessId; Cmd = $_.CommandLine } | ConvertTo-Json -Compress }"
391
+ ].join('; ');
392
+ const output = await execFileText('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script], 5000);
393
+ let targetPid = 0;
394
+ for (const line of output.split(/\r?\n/)) {
395
+ if (!line.trim())
396
+ continue;
397
+ try {
398
+ const proc = JSON.parse(line);
399
+ const candidate = parseAntigravityServerCandidateFromLine(proc.Cmd);
400
+ if (candidate && candidate.csrfToken === csrfToken) {
401
+ if (!appDataDir || !candidate.appDataDir || candidate.appDataDir === appDataDir) {
402
+ targetPid = proc.PID;
403
+ break;
404
+ }
405
+ }
406
+ }
407
+ catch { /* skip invalid parse */ }
408
+ }
409
+ if (targetPid === 0)
410
+ return null;
411
+ const portScript = `Get-NetTCPConnection -State Listen -OwningProcess ${targetPid} | Select-Object -ExpandProperty LocalPort`;
412
+ const portOutput = await execFileText('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', portScript], 5000);
413
+ const ports = portOutput.split(/\r?\n/)
414
+ .map(p => Number(p.trim()))
415
+ .filter(p => Number.isInteger(p) && p > 0);
416
+ for (const port of ports) {
417
+ try {
418
+ await new Promise((resolve, reject) => {
419
+ const req = https.request({
420
+ hostname: '127.0.0.1',
421
+ port: port,
422
+ path: '/exa.language_server_pb.LanguageServerService/GetAvailableModels',
423
+ method: 'POST',
424
+ headers: {
425
+ 'Content-Type': 'application/json',
426
+ 'Connect-Protocol-Version': '1',
427
+ 'X-Codeium-Csrf-Token': csrfToken,
428
+ 'Content-Length': 2,
429
+ },
430
+ agent: getAgent(),
431
+ timeout: 1000,
432
+ }, (res) => {
433
+ if (res.statusCode === 200)
434
+ resolve(true);
435
+ else
436
+ reject(new Error());
437
+ });
438
+ req.on('error', reject);
439
+ req.write('{}');
440
+ req.end();
441
+ });
442
+ return { port, csrfToken };
443
+ }
444
+ catch { /* try next port */ }
445
+ }
446
+ }
447
+ catch { /* best-effort */ }
448
+ return null;
449
+ }
450
+ try {
451
+ const processOutput = await execFileText('ps', ['-ww', '-eo', 'pid=,args=']);
452
+ let pid = '';
453
+ for (const line of processOutput.split('\n')) {
454
+ const match = line.trim().match(/^(\d+)\s+(.+)$/);
455
+ if (!match)
456
+ continue;
457
+ const candidate = parseAntigravityServerCandidateFromLine(match[2]);
458
+ if (!candidate)
459
+ continue;
460
+ if (candidate.csrfToken !== csrfToken)
461
+ continue;
462
+ if (appDataDir && candidate.appDataDir && candidate.appDataDir !== appDataDir)
463
+ continue;
464
+ pid = match[1];
465
+ break;
466
+ }
467
+ if (!pid)
468
+ return null;
469
+ const lsofOutput = await execFileText('lsof', ['-a', '-i', '-P', '-n', '-p', pid]);
470
+ for (const line of lsofOutput.split('\n')) {
471
+ if (!line.includes('LISTEN'))
472
+ continue;
473
+ const match = line.match(/:(\d+)\s+\(LISTEN\)/);
474
+ if (match) {
475
+ const port = Number(match[1]);
476
+ if (port > 0)
477
+ return { port, csrfToken };
478
+ }
479
+ }
480
+ }
481
+ catch { /* best-effort */ }
482
+ return null;
483
+ }
484
+ export function antigravityAppDataDirFromSourcePath(path) {
485
+ const lower = path.replace(/\\/g, '/').toLowerCase();
486
+ if (lower.includes('/.gemini/antigravity-ide/'))
487
+ return 'antigravity-ide';
488
+ if (lower.includes('/.gemini/antigravity-cli/'))
489
+ return 'antigravity-cli';
490
+ return 'antigravity';
491
+ }
492
+ function cachedValueIsFresh(cached, failed) {
493
+ if (!cached)
494
+ return false;
495
+ const ttl = failed(cached.value) ? DETECT_FAILURE_TTL_MS : DETECT_SUCCESS_TTL_MS;
496
+ return Date.now() - cached.at < ttl;
497
+ }
498
+ async function detectServer(appDataDir = 'antigravity') {
499
+ const cached = cachedServers.get(appDataDir);
500
+ if (cachedValueIsFresh(cached, value => value === null))
501
+ return cached.value;
502
+ let resolved = null;
503
+ try {
504
+ const candidates = parseAntigravityServerCandidates(await readProcessCommandLines());
505
+ const info = candidates.find(candidate => candidate.appDataDir === appDataDir)
506
+ ?? (appDataDir === 'antigravity' ? candidates.find(candidate => candidate.appDataDir === undefined) : undefined)
507
+ ?? null;
508
+ if (info && info.port > 0 && appDataDir !== 'antigravity-ide') {
509
+ resolved = { port: info.port, csrfToken: info.csrfToken };
510
+ }
511
+ else if (info) {
512
+ resolved = await resolveEphemeralPort(info.csrfToken, appDataDir);
513
+ }
514
+ }
515
+ catch { /* process discovery failed or timed out */ }
516
+ cachedServers.set(appDataDir, { value: resolved, at: Date.now() });
517
+ return resolved;
518
+ }
519
+ async function rpc(server, method, body = {}) {
520
+ return new Promise((resolve, reject) => {
521
+ const data = JSON.stringify(body);
522
+ const req = https.request({
523
+ hostname: '127.0.0.1',
524
+ port: server.port,
525
+ path: `/exa.language_server_pb.LanguageServerService/${method}`,
526
+ method: 'POST',
527
+ headers: {
528
+ 'Content-Type': 'application/json',
529
+ 'Connect-Protocol-Version': '1',
530
+ 'X-Codeium-Csrf-Token': server.csrfToken,
531
+ 'Content-Length': Buffer.byteLength(data),
532
+ },
533
+ agent: getAgent(),
534
+ timeout: RPC_TIMEOUT_MS,
535
+ }, (res) => {
536
+ const chunks = [];
537
+ let totalBytes = 0;
538
+ res.on('data', (chunk) => {
539
+ totalBytes += chunk.length;
540
+ if (totalBytes > MAX_RESPONSE_BYTES) {
541
+ res.destroy();
542
+ reject(new Error(`RPC ${method}: response too large`));
543
+ return;
544
+ }
545
+ chunks.push(chunk);
546
+ });
547
+ res.on('end', () => {
548
+ if (res.statusCode !== 200) {
549
+ reject(new Error(`RPC ${method}: HTTP ${res.statusCode}`));
550
+ return;
551
+ }
552
+ try {
553
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf-8')));
554
+ }
555
+ catch {
556
+ reject(new Error(`RPC ${method}: invalid JSON`));
557
+ }
558
+ });
559
+ res.on('error', reject);
560
+ });
561
+ req.on('error', reject);
562
+ req.on('timeout', () => { req.destroy(); reject(new Error(`RPC ${method}: timeout`)); });
563
+ req.write(data);
564
+ req.end();
565
+ });
566
+ }
567
+ async function getModelMap(server) {
568
+ const cacheKey = `${server.port}:${server.csrfToken}`;
569
+ const cached = cachedModelMaps.get(cacheKey);
570
+ if (cachedValueIsFresh(cached, value => Object.keys(value).length === 0))
571
+ return cached.value;
572
+ try {
573
+ const modelMap = extractAntigravityModelMap(await rpc(server, 'GetAvailableModels'));
574
+ cachedModelMaps.set(cacheKey, { value: modelMap, at: Date.now() });
575
+ return modelMap;
576
+ }
577
+ catch { /* best-effort */ }
578
+ cachedModelMaps.set(cacheKey, { value: {}, at: Date.now() });
579
+ return {};
580
+ }
581
+ // Strip Antigravity-specific suffixes so the pricing DB can match
582
+ const PRICING_ALIASES = {
583
+ 'gemini-pro': 'gemini-3.1-pro',
584
+ 'gemini-3-flash-a': 'gemini-3-flash-preview',
585
+ 'gemini-3-flash-d': 'gemini-3-flash-preview',
586
+ };
587
+ export function normalizePricingModel(model) {
588
+ if (!model)
589
+ return 'unknown';
590
+ const stripped = model.replace(/-(high|medium|low|agent)$/, '');
591
+ return ownValue(PRICING_ALIASES, stripped) ?? stripped;
592
+ }
593
+ function readProtoVarint(data, startOffset) {
594
+ let value = 0n;
595
+ let shift = 0n;
596
+ let offset = startOffset;
597
+ while (offset < data.length) {
598
+ const byte = BigInt(data[offset]);
599
+ offset += 1;
600
+ value |= (byte & 0x7fn) << shift;
601
+ if ((byte & 0x80n) === 0n)
602
+ return { value, offset };
603
+ shift += 7n;
604
+ if (shift > 70n)
605
+ return null;
606
+ }
607
+ return null;
608
+ }
609
+ function parseProtoFields(data) {
610
+ const fields = [];
611
+ let offset = 0;
612
+ while (offset < data.length) {
613
+ const key = readProtoVarint(data, offset);
614
+ if (!key)
615
+ break;
616
+ offset = key.offset;
617
+ const fieldNumber = Number(key.value >> 3n);
618
+ const wireType = Number(key.value & 0x7n);
619
+ if (!Number.isSafeInteger(fieldNumber) || fieldNumber <= 0)
620
+ break;
621
+ if (wireType === 0) {
622
+ const value = readProtoVarint(data, offset);
623
+ if (!value)
624
+ break;
625
+ fields.push({ number: fieldNumber, wireType, value: value.value });
626
+ offset = value.offset;
627
+ continue;
628
+ }
629
+ if (wireType === 1) {
630
+ if (offset + 8 > data.length)
631
+ break;
632
+ fields.push({ number: fieldNumber, wireType, bytes: data.subarray(offset, offset + 8) });
633
+ offset += 8;
634
+ continue;
635
+ }
636
+ if (wireType === 2) {
637
+ const length = readProtoVarint(data, offset);
638
+ if (!length)
639
+ break;
640
+ offset = length.offset;
641
+ const byteLength = Number(length.value);
642
+ if (!Number.isSafeInteger(byteLength) || byteLength < 0 || offset + byteLength > data.length)
643
+ break;
644
+ fields.push({ number: fieldNumber, wireType, bytes: data.subarray(offset, offset + byteLength) });
645
+ offset += byteLength;
646
+ continue;
647
+ }
648
+ if (wireType === 5) {
649
+ if (offset + 4 > data.length)
650
+ break;
651
+ fields.push({ number: fieldNumber, wireType, bytes: data.subarray(offset, offset + 4) });
652
+ offset += 4;
653
+ continue;
654
+ }
655
+ break;
656
+ }
657
+ return fields;
658
+ }
659
+ function firstProtoField(fields, fieldNumber) {
660
+ return fields.find(field => field.number === fieldNumber);
661
+ }
662
+ function protoFieldText(field) {
663
+ if (!field?.bytes || field.bytes.length === 0)
664
+ return undefined;
665
+ const text = protoTextDecoder.decode(field.bytes);
666
+ if (!text || /[\u0000-\u0008\u000E-\u001F\u007F\uFFFD]/.test(text))
667
+ return undefined;
668
+ return text;
669
+ }
670
+ function protoFieldPositiveInteger(field) {
671
+ if (field?.value === undefined)
672
+ return 0;
673
+ const value = Number(field.value);
674
+ return Number.isSafeInteger(value) && value > 0 ? value : 0;
675
+ }
676
+ function protoFieldBytes(field) {
677
+ return field?.bytes;
678
+ }
679
+ function isAntigravityResponseId(value) {
680
+ return /^[^\s]+$/.test(value);
681
+ }
682
+ function antigravitySqliteResponseId(usageFields, fallback) {
683
+ const responseId = protoFieldText(firstProtoField(usageFields, 11));
684
+ return responseId && isAntigravityResponseId(responseId) ? responseId : fallback;
685
+ }
686
+ function genMetadataDataBytes(value) {
687
+ return typeof value === 'string'
688
+ ? new TextEncoder().encode(value)
689
+ : value;
690
+ }
691
+ function antigravitySqliteMetadataAttributes(chatFields) {
692
+ const attributes = new Map();
693
+ for (const field of chatFields) {
694
+ if (field.number !== 20)
695
+ continue;
696
+ const pairFields = parseProtoFields(protoFieldBytes(field) ?? new Uint8Array());
697
+ const key = protoFieldText(firstProtoField(pairFields, 1));
698
+ const value = protoFieldText(firstProtoField(pairFields, 2));
699
+ if (key && value)
700
+ attributes.set(key, value);
701
+ }
702
+ return attributes;
703
+ }
704
+ // The standalone app (2.19) writes only the placeholder enum and a generic
705
+ // "gemini-pro-default" into gen_metadata, no display name. These are the ids
706
+ // its own GetAvailableModels catalog resolved those placeholders to on 6 Oct
707
+ // 2026 (the same ids the RPC path derives). A later app build can repoint a
708
+ // placeholder, so calls resolved here are flagged as estimated.
709
+ const PLACEHOLDER_MODELS = {
710
+ MODEL_PLACEHOLDER_M16: 'gemini-3.1-pro-high',
711
+ MODEL_PLACEHOLDER_M37: 'gemini-3.1-pro-high',
712
+ MODEL_PLACEHOLDER_M36: 'gemini-3.1-pro-low',
713
+ MODEL_PLACEHOLDER_M84: 'gemini-3.5-flash-high',
714
+ MODEL_PLACEHOLDER_M18: 'gemini-3-flash',
715
+ MODEL_PLACEHOLDER_M318: 'gemini-3.8-flash-high',
716
+ MODEL_PLACEHOLDER_M319: 'gemini-3.8-flash-medium',
717
+ MODEL_PLACEHOLDER_M320: 'gemini-3.8-flash-low',
718
+ MODEL_PLACEHOLDER_M35: 'claude-sonnet-4-6',
719
+ MODEL_PLACEHOLDER_M26: 'claude-opus-4-6-thinking',
720
+ };
721
+ function antigravitySqliteModel(chatFields) {
722
+ const attributes = antigravitySqliteMetadataAttributes(chatFields);
723
+ const displayName = protoFieldText(firstProtoField(chatFields, 21));
724
+ const placeholderModel = ownValue(PLACEHOLDER_MODELS, attributes.get('model_enum') ?? '');
725
+ if (!displayName && placeholderModel)
726
+ return { model: placeholderModel, estimated: true };
727
+ const rawModel = protoFieldText(firstProtoField(chatFields, 19))
728
+ ?? attributes.get('model_enum')
729
+ ?? displayName
730
+ ?? 'unknown';
731
+ return { model: getCanonicalModelId(rawModel, displayName), estimated: false };
732
+ }
733
+ // Decode a proto field that carries a time into an ISO-8601 string. Antigravity
734
+ // may encode ChatStartMetadata.created_at as an ISO string, a Timestamp
735
+ // submessage (seconds in field 1), or a bare unix varint. Returns '' when the
736
+ // field is absent or unparseable so the caller can fall back.
737
+ function protoTimestampToIso(field) {
738
+ if (!field)
739
+ return '';
740
+ const text = protoFieldText(field);
741
+ if (text && !Number.isNaN(Date.parse(text)))
742
+ return new Date(text).toISOString();
743
+ if (field.bytes) {
744
+ // google.protobuf.Timestamp submessage: seconds (#1), nanos (#2).
745
+ const tsFields = parseProtoFields(field.bytes);
746
+ const seconds = firstProtoField(tsFields, 1)?.value;
747
+ if (seconds !== undefined) {
748
+ const nanos = firstProtoField(tsFields, 2)?.value ?? 0n;
749
+ const ms = Number(seconds) * 1000 + Math.floor(Number(nanos) / 1e6);
750
+ if (Number.isSafeInteger(ms) && ms > 0)
751
+ return new Date(ms).toISOString();
752
+ }
753
+ }
754
+ if (field.value !== undefined) {
755
+ const raw = Number(field.value);
756
+ const ms = raw < 1e12 ? raw * 1000 : raw;
757
+ if (Number.isSafeInteger(ms) && ms > 0)
758
+ return new Date(ms).toISOString();
759
+ }
760
+ return '';
761
+ }
762
+ // ChatStartMetadata lives at chatModel(#1).#9; its created_at is #4. Not every
763
+ // gen_metadata row carries it, so this returns '' when missing.
764
+ function antigravitySqliteCreatedAt(chatFields) {
765
+ const metadataBytes = protoFieldBytes(firstProtoField(chatFields, 9));
766
+ if (!metadataBytes)
767
+ return '';
768
+ return protoTimestampToIso(firstProtoField(parseProtoFields(metadataBytes), 4));
769
+ }
770
+ const SKILL_MD_PATTERN = /(?:^|[\\/])([^\\/]+)[\\/]SKILL\.md$/i;
771
+ const toolNameMap = {
772
+ invoke_subagent: 'Agent',
773
+ manage_task: 'TodoWrite',
774
+ search_web: 'WebSearch',
775
+ read_url_content: 'WebFetch',
776
+ };
777
+ /**
778
+ * Normalizes Antigravity tool calls to the canonical Codeburn format (`mcp__<server>__<tool>`).
779
+ *
780
+ * Antigravity emits MCP tool calls in two distinct shapes:
781
+ * 1. Eager: `mcp_<server>_<tool>` (single underscore delimiter between prefix, server, and tool).
782
+ * 2. Lazy: `call_mcp_tool` with JSON arguments `{ ServerName: "...", ToolName: "..." }`.
783
+ *
784
+ * Both are normalized to `mcp__<server>__<tool>` so they match `extractMcpTools`,
785
+ * attribute properly to MCP inventory, and deduplicate cleanly in dashboards.
786
+ */
787
+ export function normalizeAntigravityToolCall(toolName, args) {
788
+ if (!toolName)
789
+ return '';
790
+ if (toolName === 'call_mcp_tool') {
791
+ const rawServer = args?.['ServerName'] ?? args?.['server_name'] ?? args?.['serverName'] ?? args?.['server'] ?? args?.['Server'];
792
+ const server = typeof rawServer === 'string' ? rawServer.trim() : '';
793
+ const rawTool = args?.['ToolName'] ?? args?.['tool_name'] ?? args?.['toolName'] ?? args?.['tool'] ?? args?.['Tool'];
794
+ const tool = typeof rawTool === 'string' ? rawTool.trim() : '';
795
+ if (server && tool) {
796
+ return `mcp__${server}__${tool}`;
797
+ }
798
+ return 'call_mcp_tool';
799
+ }
800
+ if (toolName.startsWith('mcp__')) {
801
+ return toolName;
802
+ }
803
+ if (toolName.startsWith('mcp_')) {
804
+ const rest = toolName.slice(4);
805
+ // ponytail: first-underscore split misattributes servers whose names contain '_'; upgrade: longest-prefix match against mcp_config.json server keys
806
+ const sep = rest.indexOf('_');
807
+ if (sep > 0 && sep < rest.length - 1) {
808
+ const server = rest.slice(0, sep);
809
+ const tool = rest.slice(sep + 1);
810
+ return `mcp__${server}__${tool}`;
811
+ }
812
+ return toolName;
813
+ }
814
+ return toolName;
815
+ }
816
+ function extractAntigravityToolFromStep(metadataBytes, turn) {
817
+ const fields = parseProtoFields(metadataBytes);
818
+ for (const field of fields) {
819
+ if (field.number !== 4 || !field.bytes)
820
+ continue;
821
+ const toolFields = parseProtoFields(field.bytes);
822
+ const toolName = protoFieldText(firstProtoField(toolFields, 2));
823
+ if (!toolName || toolName === 'send_message')
824
+ continue;
825
+ const rawArgs = protoFieldText(firstProtoField(toolFields, 3));
826
+ let args = null;
827
+ if (rawArgs) {
828
+ try {
829
+ const parsed = JSON.parse(rawArgs);
830
+ if (parsed && typeof parsed === 'object')
831
+ args = parsed;
832
+ }
833
+ catch { /* ignore malformed json */ }
834
+ }
835
+ if (toolName === 'call_mcp_tool') {
836
+ turn.tools.push(normalizeAntigravityToolCall(toolName, args));
837
+ continue;
838
+ }
839
+ if (toolName === 'run_command') {
840
+ turn.tools.push(toolName);
841
+ const cmd = typeof args?.['CommandLine'] === 'string' ? args['CommandLine'].trim() : '';
842
+ if (cmd)
843
+ turn.bashCommands.push(...extractBashCommands(cmd));
844
+ continue;
845
+ }
846
+ if (toolName === 'view_file') {
847
+ turn.tools.push(toolName);
848
+ const path = typeof args?.['AbsolutePath'] === 'string'
849
+ ? args['AbsolutePath']
850
+ : typeof args?.['file_path'] === 'string' ? args['file_path'] : '';
851
+ if (path) {
852
+ const match = path.match(SKILL_MD_PATTERN);
853
+ if (match?.[1]) {
854
+ if (!turn.skills)
855
+ turn.skills = [];
856
+ turn.skills.push(match[1]);
857
+ }
858
+ }
859
+ continue;
860
+ }
861
+ if (toolName === 'invoke_subagent') {
862
+ turn.tools.push(toolNameMap[toolName]);
863
+ if (Array.isArray(args?.['Subagents'])) {
864
+ for (const sa of args['Subagents']) {
865
+ if (sa && typeof sa === 'object') {
866
+ const typeOrRole = typeof sa['TypeName'] === 'string' && sa['TypeName']
867
+ ? sa['TypeName']
868
+ : typeof sa['Role'] === 'string' ? sa['Role'] : '';
869
+ if (typeOrRole) {
870
+ if (!turn.subagentTypes)
871
+ turn.subagentTypes = [];
872
+ turn.subagentTypes.push(typeOrRole);
873
+ }
874
+ }
875
+ }
876
+ }
877
+ continue;
878
+ }
879
+ turn.tools.push(ownValue(toolNameMap, toolName) ?? normalizeAntigravityToolCall(toolName, args));
880
+ }
881
+ }
882
+ function decodePackedVarints(data) {
883
+ const values = [];
884
+ let offset = 0;
885
+ while (offset < data.length) {
886
+ const res = readProtoVarint(data, offset);
887
+ if (!res)
888
+ break;
889
+ values.push(Number(res.value));
890
+ offset = res.offset;
891
+ }
892
+ return values;
893
+ }
894
+ // ModelUsageStats' output total (field 3, thinking + response) wins over its
895
+ // split when it is present: an absent split (proto3 omits unset fields) takes
896
+ // the total as response, and a split that disagrees, even one whose thinking
897
+ // alone exceeds the total or one beside an explicit 0, is cut back to it. An
898
+ // absent or unreadable total (undefined) keeps the split. Returns
899
+ // [response, thinking].
900
+ function reconcileOutputSplit(total, thinking, response) {
901
+ if (total === undefined || response + thinking === total)
902
+ return [response, thinking];
903
+ const kept = Math.min(thinking, total);
904
+ return [total - kept, kept];
905
+ }
906
+ function buildCallFromSqliteGenMetadataRow(cascadeId, row, rootFields, turnTools, firstStepTimestamp = '', userMessage = '') {
907
+ const chatFields = parseProtoFields(protoFieldBytes(firstProtoField(rootFields, 1)) ?? new Uint8Array());
908
+ const usageFields = parseProtoFields(protoFieldBytes(firstProtoField(chatFields, 4)) ?? new Uint8Array());
909
+ if (usageFields.length === 0)
910
+ return null;
911
+ // exa.codeium_common_pb.ModelUsageStats: 1 model enum, 2 input (uncached),
912
+ // 3 output (thinking + response), 4 cache write, 5 cache read,
913
+ // 9 thinking output, 10 response output, 11 response id.
914
+ const inputTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 2));
915
+ const totalOutputTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 3));
916
+ const cacheWriteTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 4));
917
+ const cacheReadTokens = protoFieldPositiveInteger(firstProtoField(usageFields, 5));
918
+ const [responseTokens, thinkingTokens] = reconcileOutputSplit(firstProtoField(usageFields, 3)?.value !== undefined ? totalOutputTokens : undefined, protoFieldPositiveInteger(firstProtoField(usageFields, 9)), protoFieldPositiveInteger(firstProtoField(usageFields, 10)));
919
+ if (inputTokens === 0 && totalOutputTokens === 0)
920
+ return null;
921
+ const responseId = antigravitySqliteResponseId(usageFields, String(row.idx));
922
+ const { model, estimated } = antigravitySqliteModel(chatFields);
923
+ const pricingModel = normalizePricingModel(model);
924
+ const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, cacheWriteTokens, cacheReadTokens, 0, 'standard', 0, 'antigravity');
925
+ return {
926
+ provider: 'antigravity',
927
+ model,
928
+ inputTokens,
929
+ outputTokens: responseTokens,
930
+ cacheCreationInputTokens: cacheWriteTokens,
931
+ cacheReadInputTokens: cacheReadTokens,
932
+ cachedInputTokens: 0,
933
+ reasoningTokens: thinkingTokens,
934
+ webSearchRequests: 0,
935
+ costUSD,
936
+ ...(estimated ? { costIsEstimated: true } : {}),
937
+ tools: turnTools?.tools ?? [],
938
+ bashCommands: turnTools?.bashCommands ?? [],
939
+ ...(turnTools?.skills && turnTools.skills.length > 0 ? { skills: turnTools.skills } : {}),
940
+ ...(turnTools?.subagentTypes && turnTools.subagentTypes.length > 0 ? { subagentTypes: turnTools.subagentTypes } : {}),
941
+ timestamp: antigravitySqliteCreatedAt(chatFields) || firstStepTimestamp,
942
+ speed: 'standard',
943
+ deduplicationKey: `antigravity:${cascadeId}:${responseId}`,
944
+ userMessage,
945
+ sessionId: cascadeId,
946
+ };
947
+ }
948
+ function buildCallsFromSqliteGenMetadata(cascadeId, rows, stepMap, userMessage = '') {
949
+ const calls = [];
950
+ const seenResponseIds = new Set();
951
+ for (const row of rows) {
952
+ const rootFields = parseProtoFields(genMetadataDataBytes(row.data));
953
+ const stepIndices = [];
954
+ for (const field of rootFields) {
955
+ if (field.number === 2 && field.bytes) {
956
+ stepIndices.push(...decodePackedVarints(field.bytes));
957
+ }
958
+ }
959
+ // Resolve steps through gen_metadata.stepIndices. Steps not referenced
960
+ // by gen_metadata represent in-flight actions (status=2) or aborted sessions
961
+ // (status=9) without finalized token accounting, which are omitted until committed.
962
+ const turnTools = { tools: [], bashCommands: [] };
963
+ for (const stepIdx of stepIndices) {
964
+ const step = stepMap.get(stepIdx);
965
+ if (step?.metadata) {
966
+ extractAntigravityToolFromStep(genMetadataDataBytes(step.metadata), turnTools);
967
+ }
968
+ }
969
+ // The standalone app leaves out ChatStartMetadata.created_at; the
970
+ // generation's first step carries the same time (steps.metadata #1, a
971
+ // Timestamp), which matches created_at to the second where both exist.
972
+ const firstStep = stepIndices.length > 0 ? stepMap.get(stepIndices[0]) : undefined;
973
+ const firstStepTimestamp = firstStep?.metadata
974
+ ? protoTimestampToIso(firstProtoField(parseProtoFields(genMetadataDataBytes(firstStep.metadata)), 1))
975
+ : '';
976
+ const call = buildCallFromSqliteGenMetadataRow(cascadeId, row, rootFields, turnTools, firstStepTimestamp, userMessage);
977
+ if (!call)
978
+ continue;
979
+ if (seenResponseIds.has(call.deduplicationKey))
980
+ continue;
981
+ seenResponseIds.add(call.deduplicationKey);
982
+ calls.push(call);
983
+ }
984
+ return calls;
985
+ }
986
+ export const MAX_USER_TEXT_LENGTH = 500;
987
+ export function cleanAntigravityUserPrompt(raw) {
988
+ if (!raw)
989
+ return '';
990
+ const match = /<USER_REQUEST>([\s\S]*?)(?:<\/USER_REQUEST>|$)/i.exec(raw);
991
+ const text = (match ? match[1] : raw)?.trim() ?? '';
992
+ return text.slice(0, MAX_USER_TEXT_LENGTH);
993
+ }
994
+ async function readPromptFromTranscriptFile(filePath) {
995
+ let stream;
996
+ let rl;
997
+ try {
998
+ const s = await stat(filePath).catch(() => null);
999
+ if (!s || !s.isFile())
1000
+ return '';
1001
+ stream = createReadStream(filePath, { encoding: 'utf-8' });
1002
+ stream.on('error', () => { });
1003
+ rl = createInterface({ input: stream, crlfDelay: Infinity });
1004
+ let linesChecked = 0;
1005
+ for await (const line of rl) {
1006
+ linesChecked++;
1007
+ if (linesChecked > 50)
1008
+ break;
1009
+ if (!line.includes('"USER_INPUT"'))
1010
+ continue;
1011
+ try {
1012
+ const data = JSON.parse(line);
1013
+ if (data.type === 'USER_INPUT') {
1014
+ if (typeof data.content === 'string') {
1015
+ const clean = cleanAntigravityUserPrompt(data.content);
1016
+ if (clean)
1017
+ return clean;
1018
+ }
1019
+ else if (Array.isArray(data.content)) {
1020
+ for (const item of data.content) {
1021
+ if (typeof item === 'string') {
1022
+ const clean = cleanAntigravityUserPrompt(item);
1023
+ if (clean)
1024
+ return clean;
1025
+ }
1026
+ else if (item && typeof item === 'object' && 'text' in item && typeof item.text === 'string') {
1027
+ const clean = cleanAntigravityUserPrompt(item.text);
1028
+ if (clean)
1029
+ return clean;
1030
+ }
1031
+ }
1032
+ }
1033
+ }
1034
+ }
1035
+ catch { }
1036
+ }
1037
+ }
1038
+ catch {
1039
+ return '';
1040
+ }
1041
+ finally {
1042
+ rl?.close();
1043
+ stream?.destroy();
1044
+ }
1045
+ return '';
1046
+ }
1047
+ export async function extractAntigravityTranscriptPrompt(cascadeId, sourcePath) {
1048
+ const home = homedir();
1049
+ const candidates = [];
1050
+ if (sourcePath) {
1051
+ candidates.push(join(dirname(sourcePath), '..', 'brain', cascadeId, '.system_generated', 'logs', 'transcript.jsonl'));
1052
+ candidates.push(join(home, '.gemini', antigravityAppDataDirFromSourcePath(sourcePath), 'brain', cascadeId, '.system_generated', 'logs', 'transcript.jsonl'));
1053
+ }
1054
+ candidates.push(join(home, '.gemini', 'antigravity', 'brain', cascadeId, '.system_generated', 'logs', 'transcript.jsonl'));
1055
+ candidates.push(join(home, '.gemini', 'antigravity-ide', 'brain', cascadeId, '.system_generated', 'logs', 'transcript.jsonl'));
1056
+ candidates.push(join(home, '.gemini', 'antigravity-cli', 'brain', cascadeId, '.system_generated', 'logs', 'transcript.jsonl'));
1057
+ for (const filePath of new Set(candidates)) {
1058
+ const prompt = await readPromptFromTranscriptFile(filePath);
1059
+ if (prompt)
1060
+ return prompt;
1061
+ }
1062
+ return '';
1063
+ }
1064
+ export function extractAntigravitySqlitePrompt(db) {
1065
+ try {
1066
+ const rows = db.query('SELECT step_payload FROM steps WHERE idx = 0 OR step_type = 14 ORDER BY idx LIMIT 1');
1067
+ if (rows.length === 0 || !rows[0]?.step_payload)
1068
+ return '';
1069
+ const rootFields = parseProtoFields(rows[0].step_payload);
1070
+ const tag19 = firstProtoField(rootFields, 19);
1071
+ if (!tag19)
1072
+ return '';
1073
+ const subFields = parseProtoFields(protoFieldBytes(tag19) ?? new Uint8Array());
1074
+ const tag2 = firstProtoField(subFields, 2);
1075
+ if (!tag2)
1076
+ return '';
1077
+ const rawPrompt = protoFieldText(tag2) ?? '';
1078
+ return cleanAntigravityUserPrompt(rawPrompt);
1079
+ }
1080
+ catch {
1081
+ return '';
1082
+ }
1083
+ }
1084
+ export async function extractAntigravityUserPrompt(cascadeId, sourcePath, db) {
1085
+ const transcriptPrompt = await extractAntigravityTranscriptPrompt(cascadeId, sourcePath);
1086
+ if (transcriptPrompt)
1087
+ return transcriptPrompt;
1088
+ if (db) {
1089
+ return extractAntigravitySqlitePrompt(db);
1090
+ }
1091
+ if (sourcePath && sourcePath.toLowerCase().endsWith('.db') && isSqliteAvailable()) {
1092
+ try {
1093
+ const autoDb = openDatabase(sourcePath);
1094
+ try {
1095
+ return extractAntigravitySqlitePrompt(autoDb);
1096
+ }
1097
+ finally {
1098
+ autoDb.close();
1099
+ }
1100
+ }
1101
+ catch { }
1102
+ }
1103
+ return '';
1104
+ }
1105
+ async function parseSqliteGenMetadataCalls(filePath, cascadeId) {
1106
+ if (!filePath.toLowerCase().endsWith('.db'))
1107
+ return [];
1108
+ if (!isSqliteAvailable())
1109
+ return [];
1110
+ let db = null;
1111
+ try {
1112
+ db = openDatabase(filePath);
1113
+ const rows = db.query('SELECT idx, data FROM gen_metadata ORDER BY idx');
1114
+ if (rows.length === 0)
1115
+ return [];
1116
+ const userMessage = await extractAntigravityUserPrompt(cascadeId, filePath, db);
1117
+ const stepMap = new Map();
1118
+ try {
1119
+ const stepRows = db.query('SELECT idx, metadata FROM steps ORDER BY idx');
1120
+ for (const step of stepRows) {
1121
+ stepMap.set(step.idx, step);
1122
+ }
1123
+ }
1124
+ catch (err) {
1125
+ if (isSqliteBusyError(err))
1126
+ throw err;
1127
+ }
1128
+ return buildCallsFromSqliteGenMetadata(cascadeId, rows, stepMap, userMessage);
1129
+ }
1130
+ catch (err) {
1131
+ // Let a transient lock propagate so the run retries this file on the next
1132
+ // refresh instead of treating it as empty (see parser.ts busy handling).
1133
+ if (isSqliteBusyError(err))
1134
+ throw err;
1135
+ return [];
1136
+ }
1137
+ finally {
1138
+ db?.close();
1139
+ }
1140
+ }
1141
+ function parseFiniteToken(value) {
1142
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
1143
+ ? Math.floor(value)
1144
+ : 0;
1145
+ }
1146
+ function usageSignature(event) {
1147
+ const u = event.usage;
1148
+ return [
1149
+ event.model,
1150
+ u.inputTokens,
1151
+ u.outputTokens,
1152
+ u.cacheCreationInputTokens,
1153
+ u.cacheReadInputTokens,
1154
+ ].join(':');
1155
+ }
1156
+ function usageHasTokens(usage) {
1157
+ return (usage.inputTokens > 0 ||
1158
+ usage.outputTokens > 0 ||
1159
+ usage.cacheCreationInputTokens > 0 ||
1160
+ usage.cacheReadInputTokens > 0);
1161
+ }
1162
+ function usageIsMonotonic(current, previous) {
1163
+ return (current.inputTokens >= previous.inputTokens &&
1164
+ current.outputTokens >= previous.outputTokens &&
1165
+ current.cacheCreationInputTokens >= previous.cacheCreationInputTokens &&
1166
+ current.cacheReadInputTokens >= previous.cacheReadInputTokens);
1167
+ }
1168
+ function usageDelta(current, previous) {
1169
+ return {
1170
+ inputTokens: current.inputTokens - previous.inputTokens,
1171
+ outputTokens: current.outputTokens - previous.outputTokens,
1172
+ cacheCreationInputTokens: current.cacheCreationInputTokens - previous.cacheCreationInputTokens,
1173
+ cacheReadInputTokens: current.cacheReadInputTokens - previous.cacheReadInputTokens,
1174
+ };
1175
+ }
1176
+ export function antigravityCascadeIdFromPath(path) {
1177
+ return basename(path).replace(/\.(pb|db)$/i, '');
1178
+ }
1179
+ export function buildCallsFromGeneratorMetadata(cascadeId, metadata, modelMap, userMessage = '') {
1180
+ const results = [];
1181
+ for (let i = 0; i < metadata.length; i++) {
1182
+ const entry = metadata[i];
1183
+ const usage = entry.chatModel?.usage;
1184
+ if (!usage)
1185
+ continue;
1186
+ const inputTokens = parseInt(usage.inputTokens ?? '0', 10);
1187
+ const outputTokens = parseInt(usage.outputTokens ?? '0', 10);
1188
+ const [responseTokens, thinkingTokens] = reconcileOutputSplit(usage.outputTokens !== undefined && Number.isFinite(outputTokens) ? outputTokens : undefined, parseInt(usage.thinkingOutputTokens ?? '0', 10), parseInt(usage.responseOutputTokens ?? '0', 10));
1189
+ const cacheReadTokens = parseInt(usage.cacheReadTokens ?? '0', 10);
1190
+ const cacheWriteTokens = parseInt(usage.cacheWriteTokens ?? '0', 10);
1191
+ if (inputTokens === 0 && outputTokens === 0)
1192
+ continue;
1193
+ const responseId = usage.responseId || String(i);
1194
+ const dedupKey = `antigravity:${cascadeId}:${responseId}`;
1195
+ const rawModel = usage.model || entry.chatModel?.model || '';
1196
+ const model = dropPlaceholderModelId(ownValue(modelMap, rawModel) ?? rawModel);
1197
+ const pricingModel = normalizePricingModel(model);
1198
+ const timestamp = entry.chatModel?.chatStartMetadata?.createdAt ?? '';
1199
+ const costUSD = calculateCost(pricingModel, inputTokens, responseTokens + thinkingTokens, cacheWriteTokens, cacheReadTokens, 0, 'standard', 0, 'antigravity');
1200
+ results.push({
1201
+ provider: 'antigravity',
1202
+ model,
1203
+ inputTokens,
1204
+ outputTokens: responseTokens,
1205
+ cacheCreationInputTokens: cacheWriteTokens,
1206
+ cacheReadInputTokens: cacheReadTokens,
1207
+ cachedInputTokens: 0,
1208
+ reasoningTokens: thinkingTokens,
1209
+ webSearchRequests: 0,
1210
+ costUSD,
1211
+ tools: [],
1212
+ bashCommands: [],
1213
+ timestamp,
1214
+ speed: 'standard',
1215
+ deduplicationKey: dedupKey,
1216
+ userMessage,
1217
+ sessionId: cascadeId,
1218
+ });
1219
+ }
1220
+ return results;
1221
+ }
1222
+ function isConversationFile(file, extensions) {
1223
+ const lowerFile = file.toLowerCase();
1224
+ return extensions.some(ext => lowerFile.endsWith(ext));
1225
+ }
1226
+ export function isAntigravityStatusLineEventsPath(path) {
1227
+ return path === getAntigravityStatusLineEventsPath();
1228
+ }
1229
+ export async function discoverAntigravitySessionSources(roots) {
1230
+ // The statusline JSONL is a synthetic source only appended for the real
1231
+ // default roots, not when a caller passes an explicit (test) root set.
1232
+ const includeStatusLineEvents = roots === undefined;
1233
+ const effectiveRoots = roots ?? conversationRoots();
1234
+ const sources = [];
1235
+ for (const root of effectiveRoots) {
1236
+ let files;
1237
+ try {
1238
+ files = await readdir(root.dir);
1239
+ }
1240
+ catch {
1241
+ continue;
1242
+ }
1243
+ for (const file of files.sort()) {
1244
+ if (!isConversationFile(file, root.extensions))
1245
+ continue;
1246
+ const path = join(root.dir, file);
1247
+ const s = await stat(path).catch(() => null);
1248
+ if (!s?.isFile())
1249
+ continue;
1250
+ sources.push({
1251
+ path,
1252
+ project: root.project,
1253
+ provider: 'antigravity',
1254
+ });
1255
+ }
1256
+ }
1257
+ if (includeStatusLineEvents) {
1258
+ const statusLinePath = getAntigravityStatusLineEventsPath();
1259
+ const statusLineStat = await stat(statusLinePath).catch(() => null);
1260
+ if (statusLineStat?.isFile()) {
1261
+ sources.push({
1262
+ path: statusLinePath,
1263
+ project: 'antigravity-cli',
1264
+ provider: 'antigravity',
1265
+ });
1266
+ }
1267
+ }
1268
+ return sources;
1269
+ }
1270
+ function parseStatusLinePayload(input) {
1271
+ if (!input || typeof input !== 'object')
1272
+ return null;
1273
+ const payload = input;
1274
+ if (typeof payload.conversation_id !== 'string' || payload.conversation_id.length === 0)
1275
+ return null;
1276
+ const usage = payload.context_window?.current_usage;
1277
+ if (!usage)
1278
+ return null;
1279
+ const event = {
1280
+ at: new Date().toISOString(),
1281
+ conversationId: payload.conversation_id,
1282
+ sessionId: typeof payload.session_id === 'string' ? payload.session_id : undefined,
1283
+ model: typeof payload.model === 'string'
1284
+ ? payload.model
1285
+ : payload.model?.id ?? payload.model?.display_name ?? 'unknown',
1286
+ usage: {
1287
+ inputTokens: parseFiniteToken(usage.input_tokens),
1288
+ outputTokens: parseFiniteToken(usage.output_tokens),
1289
+ cacheCreationInputTokens: parseFiniteToken(usage.cache_creation_input_tokens),
1290
+ cacheReadInputTokens: parseFiniteToken(usage.cache_read_input_tokens),
1291
+ },
1292
+ };
1293
+ const u = event.usage;
1294
+ if (u.inputTokens === 0 && u.outputTokens === 0 && u.cacheCreationInputTokens === 0 && u.cacheReadInputTokens === 0) {
1295
+ return null;
1296
+ }
1297
+ if (event.model === 'unknown')
1298
+ return null;
1299
+ return event;
1300
+ }
1301
+ export async function recordAntigravityStatusLinePayload(input) {
1302
+ const event = parseStatusLinePayload(input);
1303
+ if (!event)
1304
+ return false;
1305
+ const path = getAntigravityStatusLineEventsPath();
1306
+ await mkdir(getCodeburnCacheDir(), { recursive: true, mode: 0o700 });
1307
+ const fd = await open(path, 'a', 0o600);
1308
+ try {
1309
+ await fd.appendFile(`${JSON.stringify(event)}\n`, { encoding: 'utf-8' });
1310
+ }
1311
+ finally {
1312
+ await fd.close();
1313
+ }
1314
+ return true;
1315
+ }
1316
+ function parseStatusLineEvent(input) {
1317
+ if (!input || typeof input !== 'object')
1318
+ return null;
1319
+ const event = input;
1320
+ if (typeof event.at !== 'string' || Number.isNaN(new Date(event.at).getTime()))
1321
+ return null;
1322
+ if (typeof event.conversationId !== 'string' || event.conversationId.length === 0)
1323
+ return null;
1324
+ if (typeof event.model !== 'string' || event.model.length === 0)
1325
+ return null;
1326
+ if (!event.usage || typeof event.usage !== 'object')
1327
+ return null;
1328
+ const usage = {
1329
+ inputTokens: parseFiniteToken(event.usage.inputTokens),
1330
+ outputTokens: parseFiniteToken(event.usage.outputTokens),
1331
+ cacheCreationInputTokens: parseFiniteToken(event.usage.cacheCreationInputTokens),
1332
+ cacheReadInputTokens: parseFiniteToken(event.usage.cacheReadInputTokens),
1333
+ };
1334
+ if (usage.inputTokens === 0 &&
1335
+ usage.outputTokens === 0 &&
1336
+ usage.cacheCreationInputTokens === 0 &&
1337
+ usage.cacheReadInputTokens === 0)
1338
+ return null;
1339
+ return {
1340
+ at: event.at,
1341
+ conversationId: event.conversationId,
1342
+ sessionId: typeof event.sessionId === 'string' ? event.sessionId : undefined,
1343
+ model: event.model,
1344
+ usage,
1345
+ };
1346
+ }
1347
+ // Conversation ids that the RPC cache already covers. Built once per parse:
1348
+ // a scan of seenKeys for each statusLine event is O(events x keys), and the
1349
+ // statusLine log grows by one line per status line refresh.
1350
+ function rpcCachedConversationIds(seenKeys) {
1351
+ const prefix = 'antigravity:';
1352
+ const ids = new Set();
1353
+ for (const key of seenKeys) {
1354
+ if (!key.startsWith(prefix))
1355
+ continue;
1356
+ // Add every colon-delimited prefix so that the lookup matches
1357
+ // key.startsWith(`antigravity:${conversationId}:`) for any id.
1358
+ for (let end = key.indexOf(':', prefix.length); end !== -1; end = key.indexOf(':', end + 1)) {
1359
+ ids.add(key.slice(prefix.length, end));
1360
+ }
1361
+ }
1362
+ return ids;
1363
+ }
1364
+ async function parseStatusLineCalls(source, seenKeys) {
1365
+ const raw = await readFile(source.path, 'utf-8').catch(() => '');
1366
+ const runsByConversation = new Map();
1367
+ const rpcConversationIds = rpcCachedConversationIds(seenKeys);
1368
+ for (const line of raw.split(/\r?\n/)) {
1369
+ if (!line.trim())
1370
+ continue;
1371
+ let parsed;
1372
+ try {
1373
+ parsed = JSON.parse(line);
1374
+ }
1375
+ catch {
1376
+ continue;
1377
+ }
1378
+ const event = parseStatusLineEvent(parsed);
1379
+ if (!event)
1380
+ continue;
1381
+ if (rpcConversationIds.has(event.conversationId))
1382
+ continue;
1383
+ const signature = usageSignature(event);
1384
+ const runs = runsByConversation.get(event.conversationId) ?? [];
1385
+ const lastRun = runs.at(-1);
1386
+ if (lastRun?.signature === signature) {
1387
+ lastRun.count += 1;
1388
+ lastRun.event = event;
1389
+ }
1390
+ else {
1391
+ runs.push({ event, signature, count: 1 });
1392
+ runsByConversation.set(event.conversationId, runs);
1393
+ }
1394
+ }
1395
+ const results = [];
1396
+ for (const runs of runsByConversation.values()) {
1397
+ let turnIndex = 0;
1398
+ let previousSnapshotUsage = null;
1399
+ for (let i = 0; i < runs.length; i++) {
1400
+ const run = runs[i];
1401
+ const isLastRun = i === runs.length - 1;
1402
+ if (run.count === 1 && !isLastRun)
1403
+ continue;
1404
+ const event = run.event;
1405
+ const signature = run.signature;
1406
+ const billableUsage = previousSnapshotUsage && usageIsMonotonic(event.usage, previousSnapshotUsage)
1407
+ ? usageDelta(event.usage, previousSnapshotUsage)
1408
+ : event.usage;
1409
+ previousSnapshotUsage = event.usage;
1410
+ if (!usageHasTokens(billableUsage))
1411
+ continue;
1412
+ const dedupKey = `${STATUSLINE_KEY_PREFIX}${event.conversationId}:${turnIndex}:${signature}`;
1413
+ turnIndex += 1;
1414
+ if (seenKeys.has(dedupKey))
1415
+ continue;
1416
+ const u = billableUsage;
1417
+ const costUSD = calculateCost(normalizePricingModel(event.model), u.inputTokens, u.outputTokens, u.cacheCreationInputTokens, u.cacheReadInputTokens, 0);
1418
+ results.push({
1419
+ provider: 'antigravity',
1420
+ model: event.model,
1421
+ inputTokens: u.inputTokens,
1422
+ outputTokens: u.outputTokens,
1423
+ cacheCreationInputTokens: u.cacheCreationInputTokens,
1424
+ cacheReadInputTokens: u.cacheReadInputTokens,
1425
+ cachedInputTokens: 0,
1426
+ // StatusLine current_usage exposes aggregate output tokens, not a
1427
+ // separate thinking/response split. Preserve the exact total instead
1428
+ // of inventing a breakdown.
1429
+ reasoningTokens: 0,
1430
+ webSearchRequests: 0,
1431
+ costUSD,
1432
+ tools: [],
1433
+ bashCommands: [],
1434
+ timestamp: event.at,
1435
+ speed: 'standard',
1436
+ deduplicationKey: dedupKey,
1437
+ userMessage: '',
1438
+ sessionId: event.conversationId,
1439
+ project: source.project,
1440
+ });
1441
+ }
1442
+ }
1443
+ return results;
1444
+ }
1445
+ export function shouldReparseAntigravitySource(path, cachedTurnCount) {
1446
+ if (cachedTurnCount === 0)
1447
+ return true;
1448
+ if (cacheStates.get(currentCacheDir())?.cache.cascades[antigravityCascadeIdFromPath(path)]?.mtimeMs === -1)
1449
+ return true;
1450
+ return isAntigravityStatusLineEventsPath(path);
1451
+ }
1452
+ // Loads the results cache before the session cache decides which sources to
1453
+ // reparse, so a cascade served from the previous cache version is retried.
1454
+ export async function preloadAntigravityCache(cacheDir) {
1455
+ await loadCache(resolve(cacheDir));
1456
+ }
1457
+ async function findCascadeSource(cascadeId) {
1458
+ const sources = await discoverAntigravitySessionSources();
1459
+ return sources.find(source => {
1460
+ const lower = source.path.replace(/\\/g, '/').toLowerCase();
1461
+ return (lower.includes('/.gemini/antigravity-cli/') || lower.includes('/.gemini/antigravity-ide/')) &&
1462
+ antigravityCascadeIdFromPath(source.path) === cascadeId;
1463
+ }) ?? null;
1464
+ }
1465
+ export async function snapshotAntigravityStatusLinePayload(input) {
1466
+ const event = parseStatusLinePayload(input);
1467
+ if (!event)
1468
+ return false;
1469
+ const cascadeId = event.conversationId;
1470
+ const source = await findCascadeSource(cascadeId);
1471
+ if (!source)
1472
+ return false;
1473
+ const s = await stat(source.path).catch(() => null);
1474
+ if (!s)
1475
+ return false;
1476
+ const cacheDir = currentCacheDir();
1477
+ const state = await loadCache(cacheDir);
1478
+ const cache = state.cache;
1479
+ const cached = cache.cascades[cascadeId];
1480
+ if (cached && cached.mtimeMs === s.mtimeMs && cached.sizeBytes === s.size && cached.calls.length > 0) {
1481
+ return true;
1482
+ }
1483
+ const server = await detectServer(antigravityAppDataDirFromSourcePath(source.path));
1484
+ if (!server)
1485
+ return false;
1486
+ let metadata;
1487
+ try {
1488
+ const modelMap = await getModelMap(server);
1489
+ metadata = extractAntigravityGeneratorMetadata(await rpc(server, 'GetCascadeTrajectoryGeneratorMetadata', { cascadeId }));
1490
+ const userMessage = await extractAntigravityUserPrompt(cascadeId, source.path);
1491
+ const snapshotCalls = buildCallsFromGeneratorMetadata(cascadeId, metadata, modelMap, userMessage);
1492
+ assignStableTimestamps(snapshotCalls, cached?.calls, new Date(s.mtimeMs).toISOString());
1493
+ cache.cascades[cascadeId] = {
1494
+ mtimeMs: s.mtimeMs,
1495
+ sizeBytes: s.size,
1496
+ calls: snapshotCalls,
1497
+ };
1498
+ state.dirty = true;
1499
+ await flushCache(undefined, cacheDir);
1500
+ return cache.cascades[cascadeId].calls.length > 0;
1501
+ }
1502
+ catch {
1503
+ return false;
1504
+ }
1505
+ }
1506
+ async function extractWorkspacePath(filePath) {
1507
+ let text = '';
1508
+ if (filePath.endsWith('.db') && isSqliteAvailable()) {
1509
+ try {
1510
+ const db = openDatabase(filePath);
1511
+ const rows = db.query('SELECT data FROM trajectory_metadata_blob');
1512
+ db.close();
1513
+ const textDecoder = new TextDecoder('utf-8', { fatal: false });
1514
+ text = rows.map(r => textDecoder.decode(r.data)).join(' ');
1515
+ }
1516
+ catch { /* ignore and fallback */ }
1517
+ }
1518
+ if (!text) {
1519
+ try {
1520
+ text = await readFile(filePath, 'utf-8');
1521
+ }
1522
+ catch {
1523
+ return undefined;
1524
+ }
1525
+ }
1526
+ const match = text.match(/file:\/\/\/[^\x00-\x1F\x7F"'\s]+/i);
1527
+ if (!match)
1528
+ return undefined;
1529
+ try {
1530
+ return fileURLToPath(match[0]);
1531
+ }
1532
+ catch {
1533
+ return undefined;
1534
+ }
1535
+ }
1536
+ function sanitizeProject(path) {
1537
+ return basename(path.replace(/\\/g, '/'));
1538
+ }
1539
+ function applyAntigravityProject(call, source, projectPath) {
1540
+ if (projectPath) {
1541
+ call.projectPath = projectPath;
1542
+ call.project = sanitizeProject(projectPath);
1543
+ return;
1544
+ }
1545
+ call.project = source.project;
1546
+ }
1547
+ // gen_metadata rows and RPC entries without a real ChatStartMetadata.created_at
1548
+ // carry no per-call timestamp. Left empty, those calls are dropped by the
1549
+ // date-range filters in parser.ts (`if (!callTs) continue`), so each needs a
1550
+ // fallback. The fallback must be *stable* across file rewrites: the generic
1551
+ // session-cache persists whatever timestamp is emitted, and a non-durable
1552
+ // source is cleared and reparsed whenever its mtime changes, so stamping the
1553
+ // current mtime on every reparse would retro-date the whole session forward.
1554
+ //
1555
+ // assignStableTimestamps carries forward the timestamp already recorded for a
1556
+ // dedup key (its first-seen time, held in the durable Antigravity cache) and
1557
+ // only falls back to the current file mtime for genuinely new calls. Real
1558
+ // timestamps (created_at) are preserved untouched. This runs on the fresh-parse
1559
+ // paths whose result is written back to the cache.
1560
+ function assignStableTimestamps(calls, priorCalls, firstSeenTimestamp) {
1561
+ const priorByKey = new Map();
1562
+ for (const prior of priorCalls ?? []) {
1563
+ if (prior.timestamp)
1564
+ priorByKey.set(prior.deduplicationKey, prior.timestamp);
1565
+ }
1566
+ for (const call of calls) {
1567
+ if (call.timestamp)
1568
+ continue;
1569
+ call.timestamp = priorByKey.get(call.deduplicationKey) ?? firstSeenTimestamp;
1570
+ }
1571
+ }
1572
+ // Emit-time safety net for cache-hit / cached-fallback paths, where the calls
1573
+ // already carry stable timestamps from a prior parse. Applied to a copy so the
1574
+ // cache is never mutated; only fills a still-empty timestamp defensively.
1575
+ function withFallbackTimestamp(call, fallbackTimestamp) {
1576
+ return call.timestamp ? call : { ...call, timestamp: fallbackTimestamp };
1577
+ }
1578
+ function createParser(source, seenKeys) {
1579
+ return {
1580
+ async *parse() {
1581
+ if (isAntigravityStatusLineEventsPath(source.path)) {
1582
+ for (const call of await parseStatusLineCalls(source, seenKeys)) {
1583
+ seenKeys.add(call.deduplicationKey);
1584
+ yield call;
1585
+ }
1586
+ return;
1587
+ }
1588
+ const cascadeId = antigravityCascadeIdFromPath(source.path);
1589
+ const state = await loadCache(currentCacheDir());
1590
+ const cache = state.cache;
1591
+ const s = await stat(source.path).catch(() => null);
1592
+ if (!s)
1593
+ return;
1594
+ const projectPath = await extractWorkspacePath(source.path);
1595
+ const fallbackTimestamp = new Date(s.mtimeMs).toISOString();
1596
+ const cached = cache.cascades[cascadeId];
1597
+ if (cached && cached.mtimeMs === s.mtimeMs && cached.sizeBytes === s.size && cached.calls.length > 0) {
1598
+ for (const call of cached.calls) {
1599
+ applyAntigravityProject(call, source, projectPath);
1600
+ if (seenKeys.has(call.deduplicationKey))
1601
+ continue;
1602
+ seenKeys.add(call.deduplicationKey);
1603
+ yield withFallbackTimestamp(call, fallbackTimestamp);
1604
+ }
1605
+ return;
1606
+ }
1607
+ const sqliteResults = await parseSqliteGenMetadataCalls(source.path, cascadeId);
1608
+ if (sqliteResults.length > 0) {
1609
+ assignStableTimestamps(sqliteResults, cached?.calls, fallbackTimestamp);
1610
+ for (const call of sqliteResults) {
1611
+ applyAntigravityProject(call, source, projectPath);
1612
+ }
1613
+ cache.cascades[cascadeId] = {
1614
+ mtimeMs: s.mtimeMs,
1615
+ sizeBytes: s.size,
1616
+ calls: sqliteResults,
1617
+ };
1618
+ state.dirty = true;
1619
+ for (const call of sqliteResults) {
1620
+ if (seenKeys.has(call.deduplicationKey))
1621
+ continue;
1622
+ seenKeys.add(call.deduplicationKey);
1623
+ yield call;
1624
+ }
1625
+ return;
1626
+ }
1627
+ const server = await detectServer(antigravityAppDataDirFromSourcePath(source.path));
1628
+ if (!server) {
1629
+ const fallback = cached ?? (source.path.toLowerCase().endsWith('.pb')
1630
+ ? await adoptPreviousVersionCascade(currentCacheDir(), state, cascadeId)
1631
+ : undefined);
1632
+ if (fallback) {
1633
+ for (const call of fallback.calls) {
1634
+ applyAntigravityProject(call, source, projectPath);
1635
+ if (seenKeys.has(call.deduplicationKey))
1636
+ continue;
1637
+ seenKeys.add(call.deduplicationKey);
1638
+ yield withFallbackTimestamp(call, fallbackTimestamp);
1639
+ }
1640
+ }
1641
+ return;
1642
+ }
1643
+ const modelMap = await getModelMap(server);
1644
+ let metadata;
1645
+ try {
1646
+ metadata = extractAntigravityGeneratorMetadata(await rpc(server, 'GetCascadeTrajectoryGeneratorMetadata', { cascadeId }));
1647
+ }
1648
+ catch {
1649
+ if (cached) {
1650
+ for (const call of cached.calls) {
1651
+ applyAntigravityProject(call, source, projectPath);
1652
+ if (seenKeys.has(call.deduplicationKey))
1653
+ continue;
1654
+ seenKeys.add(call.deduplicationKey);
1655
+ yield withFallbackTimestamp(call, fallbackTimestamp);
1656
+ }
1657
+ }
1658
+ return;
1659
+ }
1660
+ const userMessage = await extractAntigravityUserPrompt(cascadeId, source.path);
1661
+ const results = buildCallsFromGeneratorMetadata(cascadeId, metadata, modelMap, userMessage);
1662
+ assignStableTimestamps(results, cached?.calls, fallbackTimestamp);
1663
+ for (const call of results) {
1664
+ applyAntigravityProject(call, source, projectPath);
1665
+ }
1666
+ cache.cascades[cascadeId] = {
1667
+ mtimeMs: s.mtimeMs,
1668
+ sizeBytes: s.size,
1669
+ calls: results,
1670
+ };
1671
+ state.dirty = true;
1672
+ for (const call of results) {
1673
+ if (seenKeys.has(call.deduplicationKey))
1674
+ continue;
1675
+ seenKeys.add(call.deduplicationKey);
1676
+ yield call;
1677
+ }
1678
+ },
1679
+ };
1680
+ }
1681
+ const modelDisplayNames = {
1682
+ 'gemini-pro-agent': 'Gemini Pro',
1683
+ 'gemini-3-pro': 'Gemini 3 Pro',
1684
+ 'gemini-3.1-pro-high': 'Gemini 3.1 Pro',
1685
+ 'gemini-3.1-pro-low': 'Gemini 3.1 Pro (Low)',
1686
+ 'gemini-3-flash': 'Gemini 3 Flash',
1687
+ 'gemini-3-flash-agent': 'Gemini 3 Flash',
1688
+ 'gemini-3.5-flash': 'Gemini 3.5 Flash',
1689
+ 'gemini-3.5-flash-high': 'Gemini 3.5 Flash',
1690
+ 'gemini-3.5-flash-medium': 'Gemini 3.5 Flash',
1691
+ 'gemini-3.5-flash-low': 'Gemini 3.5 Flash',
1692
+ 'Gemini 3.5 Flash (High)': 'Gemini 3.5 Flash',
1693
+ 'Gemini 3.5 Flash (Medium)': 'Gemini 3.5 Flash',
1694
+ 'Gemini 3.5 Flash (Low)': 'Gemini 3.5 Flash',
1695
+ 'gemini-3.8-flash': 'Gemini 3.8 Flash',
1696
+ 'gemini-3.8-flash-high': 'Gemini 3.8 Flash',
1697
+ 'gemini-3.8-flash-medium': 'Gemini 3.8 Flash',
1698
+ 'gemini-3.8-flash-low': 'Gemini 3.8 Flash',
1699
+ 'gemini-3.1-flash-image': 'Gemini 3.1 Flash',
1700
+ 'gemini-3.1-flash-lite': 'Gemini 3.1 Flash Lite',
1701
+ 'claude-opus-4-6-thinking': 'Opus 4.6',
1702
+ 'claude-sonnet-4-6': 'Sonnet 4.6',
1703
+ };
1704
+ export function createAntigravityProvider() {
1705
+ return {
1706
+ name: 'antigravity',
1707
+ displayName: 'Antigravity',
1708
+ modelDisplayName(model) {
1709
+ return ownValue(modelDisplayNames, model) ?? model;
1710
+ },
1711
+ toolDisplayName(rawTool) {
1712
+ return normalizeAntigravityToolCall(rawTool);
1713
+ },
1714
+ async probeRoots() {
1715
+ return [
1716
+ ...conversationRoots().map(root => ({ path: root.dir, label: 'conversations' })),
1717
+ { path: getAntigravityStatusLineEventsPath(), label: 'statusline' },
1718
+ ];
1719
+ },
1720
+ async discoverSessions() {
1721
+ return discoverAntigravitySessionSources();
1722
+ },
1723
+ createSessionParser(source, seenKeys) {
1724
+ return createParser(source, seenKeys);
1725
+ },
1726
+ };
1727
+ }
1728
+ export async function flushAntigravityCache(liveCascadeIds, cacheDir) {
1729
+ await flushCache(liveCascadeIds, cacheDir ? resolve(cacheDir) : currentCacheDir());
1730
+ }
1731
+ export const antigravity = createAntigravityProvider();