burnoff 1.3.0 → 1.4.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.
@@ -0,0 +1,703 @@
1
+ /**
2
+ * @file src/storage/telemetry-metrics.mjs
3
+ * Read-only TTFT, tokens/sec (`tok/s`), Antigravity SQLite step-metadata protobuf,
4
+ * and `gen_ai.usage.*` OpenTelemetry span extraction for `burnoff audit` and statusline.
5
+ * Strictly read-only: zero network calls, zero binary patching, zero fabricated timings.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { getHomeDir } from '../config/paths.mjs';
11
+ import { getDatabaseSyncClass } from './sqlite-client.mjs';
12
+
13
+ function readVarintBigInt(buf, startOffset, endOffset) {
14
+ let result = 0n;
15
+ let shift = 0n;
16
+ let offset = startOffset;
17
+ while (offset < endOffset) {
18
+ const byte = buf[offset++];
19
+ result |= BigInt(byte & 0x7f) << shift;
20
+ if ((byte & 0x80) === 0) {
21
+ return { value: result, nextOffset: offset, ok: true };
22
+ }
23
+ shift += 7n;
24
+ if (shift > 63n) {
25
+ return { value: 0n, nextOffset: endOffset, ok: false };
26
+ }
27
+ }
28
+ return { value: 0n, nextOffset: endOffset, ok: false };
29
+ }
30
+
31
+ function iterateProtobufFields(buf, startOffset = 0, endOffset = buf?.length ?? 0, onField) {
32
+ if (!buf || typeof buf.length !== 'number') return;
33
+ let offset = Math.max(0, startOffset);
34
+ const limit = Math.min(buf.length, endOffset);
35
+
36
+ while (offset < limit) {
37
+ const tagRes = readVarintBigInt(buf, offset, limit);
38
+ if (!tagRes.ok || tagRes.value <= 0n) break;
39
+ offset = tagRes.nextOffset;
40
+ const fieldNumber = Number(tagRes.value >> 3n);
41
+ const wireType = Number(tagRes.value & 7n);
42
+
43
+ if (wireType === 0) {
44
+ const valRes = readVarintBigInt(buf, offset, limit);
45
+ if (!valRes.ok) break;
46
+ offset = valRes.nextOffset;
47
+ onField(fieldNumber, wireType, valRes.value, null);
48
+ } else if (wireType === 1) {
49
+ if (offset + 8 > limit) break;
50
+ offset += 8;
51
+ } else if (wireType === 2) {
52
+ const lenRes = readVarintBigInt(buf, offset, limit);
53
+ if (!lenRes.ok) break;
54
+ const len = Number(lenRes.value);
55
+ offset = lenRes.nextOffset;
56
+ if (!Number.isFinite(len) || len < 0 || offset + len > limit) break;
57
+ const sliceEnd = offset + len;
58
+ onField(fieldNumber, wireType, null, { buf, start: offset, end: sliceEnd });
59
+ offset = sliceEnd;
60
+ } else if (wireType === 5) {
61
+ if (offset + 4 > limit) break;
62
+ offset += 4;
63
+ } else {
64
+ break;
65
+ }
66
+ }
67
+ }
68
+
69
+ function decodeProtoTimestampMs(buf, start, end) {
70
+ let seconds = null;
71
+ let nanos = 0;
72
+ iterateProtobufFields(buf, start, end, (fieldNumber, wireType, varintVal) => {
73
+ if (wireType !== 0) return;
74
+ if (fieldNumber === 1) seconds = Number(varintVal);
75
+ else if (fieldNumber === 2) nanos = Number(varintVal);
76
+ });
77
+ if (seconds === null || !Number.isFinite(seconds) || seconds <= 0) return null;
78
+ const safeNanos = Number.isFinite(nanos) && nanos >= 0 ? nanos : 0;
79
+ return Number((seconds * 1000 + safeNanos / 1_000_000).toFixed(3));
80
+ }
81
+
82
+ function toUint8View(blob) {
83
+ if (!blob) return null;
84
+ if (Buffer.isBuffer(blob)) return blob;
85
+ if (blob instanceof Uint8Array) return blob;
86
+ if (ArrayBuffer.isView(blob)) return new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength);
87
+ if (blob instanceof ArrayBuffer) return new Uint8Array(blob);
88
+ return null;
89
+ }
90
+
91
+ /**
92
+ * Decodes Antigravity `steps.metadata` protobuf BLOB:
93
+ * - field `1`: created timestamp (`1.1` sec, `1.2` ns)
94
+ * - field `5`: optional first-token timestamp (`5.1` sec, `5.2` ns)
95
+ * - field `6`: finished timestamp (`6.1` sec, `6.2` ns)
96
+ * - field `20.3`: `gen_metadata.idx`
97
+ * Never fabricates timings; returns `null` when timestamps are absent.
98
+ */
99
+ export function decodeAntigravityStepMetadata(blob) {
100
+ const bytes = toUint8View(blob);
101
+ if (!bytes || bytes.length === 0) {
102
+ return {
103
+ createdMs: null,
104
+ firstTokenMs: null,
105
+ finishedMs: null,
106
+ durationMs: null,
107
+ ttftMs: null,
108
+ genMetadataIdx: null
109
+ };
110
+ }
111
+
112
+ let createdMs = null;
113
+ let firstTokenMs = null;
114
+ let finishedMs = null;
115
+ let genMetadataIdx = null;
116
+
117
+ iterateProtobufFields(bytes, 0, bytes.length, (fieldNumber, wireType, _varint, span) => {
118
+ if (wireType !== 2 || !span) return;
119
+ if (fieldNumber === 1) {
120
+ createdMs = decodeProtoTimestampMs(span.buf, span.start, span.end);
121
+ } else if (fieldNumber === 5) {
122
+ firstTokenMs = decodeProtoTimestampMs(span.buf, span.start, span.end);
123
+ } else if (fieldNumber === 6) {
124
+ finishedMs = decodeProtoTimestampMs(span.buf, span.start, span.end);
125
+ } else if (fieldNumber === 20) {
126
+ iterateProtobufFields(span.buf, span.start, span.end, (subField, subWire, subVarint) => {
127
+ if (subField === 3 && subWire === 0) {
128
+ genMetadataIdx = Number(subVarint);
129
+ }
130
+ });
131
+ }
132
+ });
133
+
134
+ const durationMs =
135
+ createdMs !== null && finishedMs !== null && finishedMs > createdMs
136
+ ? Number((finishedMs - createdMs).toFixed(2))
137
+ : null;
138
+
139
+ const ttftMs =
140
+ createdMs !== null &&
141
+ firstTokenMs !== null &&
142
+ firstTokenMs >= createdMs &&
143
+ (finishedMs === null || firstTokenMs <= finishedMs)
144
+ ? Number((firstTokenMs - createdMs).toFixed(2))
145
+ : null;
146
+
147
+ return {
148
+ createdMs,
149
+ firstTokenMs,
150
+ finishedMs,
151
+ durationMs,
152
+ ttftMs,
153
+ genMetadataIdx
154
+ };
155
+ }
156
+
157
+ /**
158
+ * Decodes Antigravity `gen_metadata.data` protobuf BLOB:
159
+ * - `1.4.2`: uncached input tokens
160
+ * - `1.4.3`: output tokens
161
+ * - `1.4.5`: cache-read input tokens
162
+ */
163
+ export function decodeAntigravityGenMetadata(blob) {
164
+ const bytes = toUint8View(blob);
165
+ const out = {
166
+ inputTokens: 0,
167
+ outputTokens: 0,
168
+ cacheReadTokens: 0
169
+ };
170
+ if (!bytes || bytes.length === 0) return out;
171
+
172
+ iterateProtobufFields(bytes, 0, bytes.length, (f1, w1, _v1, span1) => {
173
+ if (f1 !== 1 || w1 !== 2 || !span1) return;
174
+ iterateProtobufFields(span1.buf, span1.start, span1.end, (f2, w2, _v2, span2) => {
175
+ if (f2 !== 4 || w2 !== 2 || !span2) return;
176
+ iterateProtobufFields(span2.buf, span2.start, span2.end, (f3, w3, v3) => {
177
+ if (w3 !== 0) return;
178
+ const n = Number(v3);
179
+ if (!Number.isFinite(n) || n < 0) return;
180
+ if (f3 === 2) out.inputTokens = n;
181
+ else if (f3 === 3) out.outputTokens = n;
182
+ else if (f3 === 5) out.cacheReadTokens = n;
183
+ });
184
+ });
185
+ });
186
+
187
+ return out;
188
+ }
189
+
190
+ /**
191
+ * Discovers local Antigravity conversation `.db` files strictly read-only.
192
+ */
193
+ export function discoverAntigravityConversationDbs({
194
+ homeDir = getHomeDir(),
195
+ conversationDirs = null,
196
+ maxDbs = 50
197
+ } = {}) {
198
+ const dirs = Array.isArray(conversationDirs)
199
+ ? conversationDirs
200
+ : [
201
+ path.join(homeDir, '.gemini', 'antigravity', 'conversations'),
202
+ path.join(homeDir, '.gemini', 'antigravity-cli', 'conversations'),
203
+ path.join(homeDir, '.gemini', 'antigravity-ide', 'conversations')
204
+ ];
205
+
206
+ const found = [];
207
+ const seen = new Set();
208
+
209
+ for (const dir of dirs) {
210
+ if (!dir || !fs.existsSync(dir)) continue;
211
+ let entries = [];
212
+ try {
213
+ entries = fs.readdirSync(dir, { withFileTypes: true });
214
+ } catch {
215
+ continue; // ignore: unreadable Antigravity conversations directory
216
+ }
217
+ for (const ent of entries) {
218
+ if (!ent.isFile() || !/\.db$/i.test(ent.name)) continue;
219
+ const fullPath = path.resolve(dir, ent.name);
220
+ if (seen.has(fullPath)) continue;
221
+ seen.add(fullPath);
222
+ try {
223
+ const st = fs.statSync(fullPath);
224
+ if (!st.isFile() || st.size === 0) continue;
225
+ found.push({ dbPath: fullPath, mtimeMs: st.mtimeMs });
226
+ } catch {
227
+ // ignore: unreadable DB stat entry
228
+ }
229
+ }
230
+ }
231
+
232
+ found.sort((a, b) => (b.mtimeMs || 0) - (a.mtimeMs || 0));
233
+ const cap = Math.max(1, Number(maxDbs) || 50);
234
+ return found.slice(0, cap).map((x) => x.dbPath);
235
+ }
236
+
237
+ /**
238
+ * Reads an Antigravity conversation SQLite `.db` strictly read-only to extract
239
+ * step `durationMs`, `ttftMs`, token counts, and `tokensPerSec`.
240
+ */
241
+ export function readAntigravityConversationDbMetrics(dbPath) {
242
+ if (!dbPath || !fs.existsSync(dbPath)) {
243
+ return { ok: false, reason: 'missing_db', dbPath: dbPath || '', stepCount: 0, steps: [] };
244
+ }
245
+ const resolved = path.resolve(dbPath);
246
+ const DbCtor = getDatabaseSyncClass();
247
+ if (!DbCtor) {
248
+ return { ok: false, reason: 'sqlite_unavailable', dbPath: resolved, stepCount: 0, steps: [] };
249
+ }
250
+
251
+ let db = null;
252
+ try {
253
+ db = new DbCtor(resolved, { readOnly: true });
254
+ const genMap = new Map();
255
+ try {
256
+ const genRows = db.prepare('SELECT idx, data FROM gen_metadata WHERE data IS NOT NULL').all();
257
+ for (const row of genRows) {
258
+ genMap.set(Number(row.idx), decodeAntigravityGenMetadata(row.data));
259
+ }
260
+ } catch {
261
+ // ignore: gen_metadata table optional in partial or minimal Antigravity DBs
262
+ }
263
+
264
+ const stepRows = db.prepare('SELECT idx, metadata FROM steps WHERE metadata IS NOT NULL').all();
265
+ const steps = [];
266
+ for (const row of stepRows) {
267
+ const meta = decodeAntigravityStepMetadata(row.metadata);
268
+ const joinIdx = meta.genMetadataIdx !== null ? meta.genMetadataIdx : Number(row.idx);
269
+ const gen = genMap.get(joinIdx) || { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
270
+ const tokensPerSec =
271
+ meta.durationMs !== null && meta.durationMs > 0 && gen.outputTokens > 0
272
+ ? Number((gen.outputTokens / (meta.durationMs / 1000)).toFixed(2))
273
+ : null;
274
+ steps.push({
275
+ idx: Number(row.idx),
276
+ createdMs: meta.createdMs,
277
+ finishedMs: meta.finishedMs,
278
+ durationMs: meta.durationMs,
279
+ ttftMs: meta.ttftMs,
280
+ inputTokens: gen.inputTokens,
281
+ outputTokens: gen.outputTokens,
282
+ cacheReadTokens: gen.cacheReadTokens,
283
+ tokensPerSec
284
+ });
285
+ }
286
+
287
+ return {
288
+ ok: true,
289
+ dbPath: resolved,
290
+ stepCount: steps.length,
291
+ steps
292
+ };
293
+ } catch (err) {
294
+ return {
295
+ ok: false,
296
+ reason: err?.message || 'sqlite_read_error',
297
+ dbPath: resolved,
298
+ stepCount: 0,
299
+ steps: []
300
+ };
301
+ } finally {
302
+ if (db && typeof db.close === 'function') {
303
+ try {
304
+ db.close();
305
+ } catch {
306
+ // ignore: read-only SQLite handle cleanup
307
+ }
308
+ }
309
+ }
310
+ }
311
+
312
+ function readAttrValue(val) {
313
+ if (val === null || val === undefined) return undefined;
314
+ if (typeof val !== 'object') return val;
315
+ if (val.intValue !== undefined) return Number(val.intValue);
316
+ if (val.doubleValue !== undefined) return Number(val.doubleValue);
317
+ if (val.stringValue !== undefined) return val.stringValue;
318
+ if (val.boolValue !== undefined) return Boolean(val.boolValue);
319
+ return undefined;
320
+ }
321
+
322
+ function extractSpanAttributes(span = {}) {
323
+ const map = {};
324
+ if (Array.isArray(span.attributes)) {
325
+ for (const entry of span.attributes) {
326
+ if (entry && typeof entry.key === 'string') {
327
+ const parsed = readAttrValue(entry.value);
328
+ if (parsed !== undefined) map[entry.key] = parsed;
329
+ }
330
+ }
331
+ } else if (span.attributes && typeof span.attributes === 'object') {
332
+ for (const [k, v] of Object.entries(span.attributes)) {
333
+ map[k] = readAttrValue(v) ?? v;
334
+ }
335
+ }
336
+ for (const [k, v] of Object.entries(span)) {
337
+ if (k.startsWith('gen_ai.')) {
338
+ map[k] = v;
339
+ }
340
+ }
341
+ return map;
342
+ }
343
+
344
+ function collectRawOtelSpans(parsed) {
345
+ const out = [];
346
+ if (!parsed || typeof parsed !== 'object') return out;
347
+ if (Array.isArray(parsed)) {
348
+ for (const item of parsed) out.push(...collectRawOtelSpans(item));
349
+ return out;
350
+ }
351
+ if (Array.isArray(parsed.resourceSpans)) {
352
+ for (const rs of parsed.resourceSpans) {
353
+ const scopeLists = rs?.scopeSpans || rs?.instrumentationLibrarySpans || [];
354
+ for (const ss of scopeLists) {
355
+ if (Array.isArray(ss?.spans)) {
356
+ out.push(...ss.spans);
357
+ }
358
+ }
359
+ }
360
+ }
361
+ if (Array.isArray(parsed.spans)) {
362
+ out.push(...parsed.spans);
363
+ }
364
+ if (parsed.attributes || Object.keys(parsed).some((k) => k.startsWith('gen_ai.'))) {
365
+ out.push(parsed);
366
+ }
367
+ return out;
368
+ }
369
+
370
+ function parseFiniteNonNeg(val) {
371
+ if (val === null || val === undefined || val === '') return null;
372
+ const n = Number(val);
373
+ return Number.isFinite(n) && n >= 0 ? n : null;
374
+ }
375
+
376
+ function parseFinitePos(val) {
377
+ if (val === null || val === undefined || val === '') return null;
378
+ const n = Number(val);
379
+ return Number.isFinite(n) && n > 0 ? n : null;
380
+ }
381
+
382
+ function normalizeOtelGenAiSpan(rawSpan) {
383
+ const attrs = extractSpanAttributes(rawSpan);
384
+ const hasGenAiAttr = Object.keys(attrs).some(
385
+ (k) =>
386
+ k.startsWith('gen_ai.usage.') ||
387
+ k === 'gen_ai.server.time_to_first_token' ||
388
+ k === 'gen_ai.client.time_to_first_token' ||
389
+ k === 'gen_ai.server.time_to_first_token_ms' ||
390
+ k === 'gen_ai.client.operation.duration'
391
+ );
392
+ if (!hasGenAiAttr) return null;
393
+
394
+ const inputTokens = parseFiniteNonNeg(attrs['gen_ai.usage.input_tokens']) ?? 0;
395
+ const outputTokens = parseFiniteNonNeg(attrs['gen_ai.usage.output_tokens']) ?? 0;
396
+ const cacheReadTokens =
397
+ parseFiniteNonNeg(attrs['gen_ai.usage.cache_read.input_tokens'] ?? attrs['gen_ai.usage.cache_read_input_tokens']) ??
398
+ 0;
399
+ const cacheCreationTokens =
400
+ parseFiniteNonNeg(
401
+ attrs['gen_ai.usage.cache_creation.input_tokens'] ?? attrs['gen_ai.usage.cache_creation_input_tokens']
402
+ ) ?? 0;
403
+ const model = attrs['gen_ai.response.model'] || attrs['gen_ai.request.model'] || null;
404
+
405
+ let durationMs = null;
406
+ if (rawSpan.startTimeUnixNano !== undefined && rawSpan.endTimeUnixNano !== undefined) {
407
+ try {
408
+ const startNs = BigInt(String(rawSpan.startTimeUnixNano));
409
+ const endNs = BigInt(String(rawSpan.endTimeUnixNano));
410
+ if (endNs > startNs) {
411
+ durationMs = Number((Number(endNs - startNs) / 1_000_000).toFixed(2));
412
+ }
413
+ } catch {
414
+ // ignore: invalid nanosecond BigInt falls back to duration attributes
415
+ }
416
+ }
417
+ if (durationMs === null) {
418
+ const opSec = parseFinitePos(attrs['gen_ai.client.operation.duration']);
419
+ if (opSec !== null) {
420
+ durationMs = Number((opSec * 1000).toFixed(2));
421
+ } else {
422
+ durationMs = parseFinitePos(rawSpan.durationMs ?? rawSpan.duration_ms);
423
+ }
424
+ }
425
+
426
+ let ttftMs = null;
427
+ const ttftSec = parseFinitePos(attrs['gen_ai.server.time_to_first_token'] ?? attrs['gen_ai.client.time_to_first_token']);
428
+ if (ttftSec !== null) {
429
+ ttftMs = Number((ttftSec * 1000).toFixed(2));
430
+ } else {
431
+ ttftMs = parseFinitePos(
432
+ attrs['gen_ai.server.time_to_first_token_ms'] ?? rawSpan.ttftMs ?? rawSpan.ttft_ms
433
+ );
434
+ }
435
+
436
+ const tokensPerSec =
437
+ durationMs !== null && durationMs > 0 && outputTokens > 0
438
+ ? Number((outputTokens / (durationMs / 1000)).toFixed(2))
439
+ : null;
440
+
441
+ return {
442
+ name: rawSpan.name ? String(rawSpan.name) : null,
443
+ model: model ? String(model) : null,
444
+ inputTokens,
445
+ outputTokens,
446
+ cacheReadTokens,
447
+ cacheCreationTokens,
448
+ durationMs,
449
+ ttftMs,
450
+ tokensPerSec
451
+ };
452
+ }
453
+
454
+ /**
455
+ * Parses local OTLP JSON or JSONL OpenTelemetry span exports for `gen_ai.usage.*` metrics.
456
+ */
457
+ export function parseOtelGenAiSpans(filePathOrContent = '') {
458
+ let raw = '';
459
+ if (typeof filePathOrContent === 'string' && !filePathOrContent.includes('\n') && fs.existsSync(filePathOrContent)) {
460
+ try {
461
+ raw = fs.readFileSync(path.resolve(filePathOrContent), 'utf8');
462
+ } catch {
463
+ raw = ''; // ignore: unreadable OTel export file
464
+ }
465
+ } else {
466
+ raw = String(filePathOrContent || '');
467
+ }
468
+
469
+ const trimmed = raw.trim();
470
+ const rawSpans = [];
471
+ if (trimmed) {
472
+ let parsedWhole = false;
473
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
474
+ try {
475
+ const obj = JSON.parse(trimmed);
476
+ rawSpans.push(...collectRawOtelSpans(obj));
477
+ parsedWhole = true;
478
+ } catch {
479
+ // ignore: fallback to JSONL line-by-line parsing
480
+ }
481
+ }
482
+ if (!parsedWhole) {
483
+ for (const line of trimmed.split(/\r?\n/)) {
484
+ const clean = line.trim();
485
+ if (!clean) continue;
486
+ try {
487
+ rawSpans.push(...collectRawOtelSpans(JSON.parse(clean)));
488
+ } catch {
489
+ // ignore: skip malformed JSONL OTel line
490
+ }
491
+ }
492
+ }
493
+ }
494
+
495
+ const spans = [];
496
+ let inputTokens = 0;
497
+ let outputTokens = 0;
498
+ let cacheReadTokens = 0;
499
+ let cacheCreationTokens = 0;
500
+ const models = new Set();
501
+
502
+ for (const rs of rawSpans) {
503
+ const norm = normalizeOtelGenAiSpan(rs);
504
+ if (!norm) continue;
505
+ spans.push(norm);
506
+ inputTokens += norm.inputTokens;
507
+ outputTokens += norm.outputTokens;
508
+ cacheReadTokens += norm.cacheReadTokens;
509
+ cacheCreationTokens += norm.cacheCreationTokens;
510
+ if (norm.model) models.add(norm.model);
511
+ }
512
+
513
+ return {
514
+ spans,
515
+ summary: {
516
+ spanCount: spans.length,
517
+ inputTokens,
518
+ outputTokens,
519
+ cacheReadTokens,
520
+ cacheCreationTokens,
521
+ models: Array.from(models)
522
+ }
523
+ };
524
+ }
525
+
526
+ /**
527
+ * Discovers local OTel span export files from `--otel <path>` or standard local telemetry folders.
528
+ */
529
+ export function discoverLocalOtelFiles({ homeDir = getHomeDir(), otelPath = null, maxFiles = 20 } = {}) {
530
+ const cap = Math.max(1, Number(maxFiles) || 20);
531
+ if (otelPath && typeof otelPath === 'string') {
532
+ const resolved = path.resolve(otelPath);
533
+ if (!fs.existsSync(resolved)) return [];
534
+ try {
535
+ const st = fs.statSync(resolved);
536
+ if (st.isFile()) return [resolved];
537
+ if (!st.isDirectory()) return [];
538
+ return fs
539
+ .readdirSync(resolved, { withFileTypes: true })
540
+ .filter((e) => e.isFile() && /\.(?:json|jsonl)$/i.test(e.name))
541
+ .map((e) => {
542
+ const fp = path.join(resolved, e.name);
543
+ return { fp, mtimeMs: fs.statSync(fp).mtimeMs };
544
+ })
545
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
546
+ .slice(0, cap)
547
+ .map((x) => x.fp);
548
+ } catch {
549
+ return []; // ignore: unreadable --otel path
550
+ }
551
+ }
552
+
553
+ const dirs = [path.join(homeDir, '.claude', 'otel'), path.join(homeDir, '.burnoff', 'otel')];
554
+ const entries = [];
555
+ for (const dir of dirs) {
556
+ if (!fs.existsSync(dir)) continue;
557
+ try {
558
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
559
+ if (!e.isFile() || !/\.(?:json|jsonl)$/i.test(e.name)) continue;
560
+ const fp = path.join(dir, e.name);
561
+ entries.push({ fp, mtimeMs: fs.statSync(fp).mtimeMs });
562
+ }
563
+ } catch {
564
+ // ignore: unreadable local OTel directory
565
+ }
566
+ }
567
+ entries.sort((a, b) => b.mtimeMs - a.mtimeMs);
568
+ return entries.slice(0, cap).map((x) => x.fp);
569
+ }
570
+
571
+ /**
572
+ * Computes observed timing metrics (`durationMs`, `ttftMs`, `tokensPerSec`) for a single step
573
+ * without ever fabricating values when timestamps or durations are absent.
574
+ */
575
+ export function extractStepTimingMetrics(step = {}) {
576
+ if (!step || typeof step !== 'object') {
577
+ return { durationMs: null, ttftMs: null, tokensPerSec: null };
578
+ }
579
+
580
+ let durationMs = parseFinitePos(step.durationMs ?? step.duration_ms ?? step.streamDurationMs);
581
+ if (durationMs === null && step.createdAt && step.finishedAt) {
582
+ const startMs = Date.parse(step.createdAt);
583
+ const endMs = Date.parse(step.finishedAt);
584
+ if (Number.isFinite(startMs) && Number.isFinite(endMs) && endMs > startMs) {
585
+ durationMs = Number((endMs - startMs).toFixed(2));
586
+ }
587
+ }
588
+
589
+ let ttftMs = parseFinitePos(step.ttftMs ?? step.ttft_ms);
590
+ if (ttftMs === null && step.createdAt && step.firstTokenAt) {
591
+ const startMs = Date.parse(step.createdAt);
592
+ const firstMs = Date.parse(step.firstTokenAt);
593
+ if (Number.isFinite(startMs) && Number.isFinite(firstMs) && firstMs >= startMs) {
594
+ ttftMs = Number((firstMs - startMs).toFixed(2));
595
+ }
596
+ }
597
+
598
+ const outTokens = parseFinitePos(step.outputTokens ?? step.tokenUsage?.outputTokens);
599
+ const tokensPerSec =
600
+ durationMs !== null && durationMs > 0 && outTokens !== null && outTokens > 0
601
+ ? Number((outTokens / (durationMs / 1000)).toFixed(2))
602
+ : null;
603
+
604
+ return { durationMs, ttftMs, tokensPerSec };
605
+ }
606
+
607
+ function computeMedian(values) {
608
+ if (!Array.isArray(values) || values.length === 0) return null;
609
+ const sorted = [...values].sort((a, b) => a - b);
610
+ const mid = Math.floor(sorted.length / 2);
611
+ const med = sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
612
+ return Number(med.toFixed(2));
613
+ }
614
+
615
+ function computePercentile(values, pct) {
616
+ if (!Array.isArray(values) || values.length === 0) return null;
617
+ const sorted = [...values].sort((a, b) => a - b);
618
+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil((pct / 100) * sorted.length) - 1));
619
+ return Number(sorted[idx].toFixed(2));
620
+ }
621
+
622
+ function computeMean(values) {
623
+ if (!Array.isArray(values) || values.length === 0) return null;
624
+ const sum = values.reduce((acc, v) => acc + v, 0);
625
+ return Number((sum / values.length).toFixed(2));
626
+ }
627
+
628
+ /**
629
+ * Aggregates TTFT (`ms`), generation throughput (`tok/s`), Antigravity DB timings,
630
+ * and OTel `gen_ai.usage.*` spans. Returns `null` for any unmeasured timing series.
631
+ */
632
+ export function aggregateTelemetryMetrics({
633
+ stepTimings = [],
634
+ otelSpans = [],
635
+ antigravityDbSteps = [],
636
+ otelFilesScanned = 0,
637
+ antigravityDbsScanned = 0
638
+ } = {}) {
639
+ const ttftSamples = [];
640
+ const tpsSamples = [];
641
+ let dbDurationSamples = 0;
642
+
643
+ const pushSample = (item, fromDb = false) => {
644
+ if (!item || typeof item !== 'object') return;
645
+ const ttft = parseFinitePos(item.ttftMs);
646
+ const tps = parseFinitePos(item.tokensPerSec);
647
+ if (ttft !== null) ttftSamples.push(ttft);
648
+ if (tps !== null) tpsSamples.push(tps);
649
+ if (fromDb && parseFinitePos(item.durationMs) !== null) dbDurationSamples += 1;
650
+ };
651
+
652
+ for (const s of stepTimings) pushSample(s, false);
653
+ for (const span of otelSpans) pushSample(span, false);
654
+ for (const dbStep of antigravityDbSteps) pushSample(dbStep, true);
655
+
656
+ let otelInputTokens = 0;
657
+ let otelOutputTokens = 0;
658
+ let otelCacheReadTokens = 0;
659
+ let otelCacheCreationTokens = 0;
660
+ const otelModels = new Set();
661
+
662
+ for (const span of otelSpans) {
663
+ otelInputTokens += Number(span.inputTokens || 0);
664
+ otelOutputTokens += Number(span.outputTokens || 0);
665
+ otelCacheReadTokens += Number(span.cacheReadTokens || 0);
666
+ otelCacheCreationTokens += Number(span.cacheCreationTokens || 0);
667
+ if (span.model) otelModels.add(span.model);
668
+ }
669
+
670
+ return {
671
+ ttftSampleCount: ttftSamples.length,
672
+ tpsSampleCount: tpsSamples.length,
673
+ medianTtftMs: computeMedian(ttftSamples),
674
+ p95TtftMs: computePercentile(ttftSamples, 95),
675
+ medianTokensPerSec: computeMedian(tpsSamples),
676
+ meanTokensPerSec: computeMean(tpsSamples),
677
+ otel: {
678
+ filesScanned: Number(otelFilesScanned || 0),
679
+ spanCount: otelSpans.length,
680
+ inputTokens: otelInputTokens,
681
+ outputTokens: otelOutputTokens,
682
+ cacheReadTokens: otelCacheReadTokens,
683
+ cacheCreationTokens: otelCacheCreationTokens,
684
+ models: Array.from(otelModels)
685
+ },
686
+ antigravityDb: {
687
+ dbsScanned: Number(antigravityDbsScanned || 0),
688
+ stepCount: antigravityDbSteps.length,
689
+ durationSamples: dbDurationSamples
690
+ }
691
+ };
692
+ }
693
+
694
+ export default {
695
+ decodeAntigravityStepMetadata,
696
+ decodeAntigravityGenMetadata,
697
+ discoverAntigravityConversationDbs,
698
+ readAntigravityConversationDbMetrics,
699
+ parseOtelGenAiSpans,
700
+ discoverLocalOtelFiles,
701
+ extractStepTimingMetrics,
702
+ aggregateTelemetryMetrics
703
+ };