tokless 0.0.0-stage → 0.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,864 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const { resolveSessionTarget, getConversationMeta, inspectSessionMountedMcp } = require('./paths');
5
+
6
+ const COMPACTION_THRESHOLD_256K = 256000;
7
+ const COMPACTION_THRESHOLD_512K = 512000;
8
+ const CACHE_CLIFF_MIN_PREV_CONTEXT = 8000;
9
+ const CACHE_CLIFF_RETENTION_RATIO = 0.55;
10
+ const CACHE_CLIFF_MIN_DROP_TOKENS = 6000;
11
+ const CACHE_CLIFF_MIN_INPUT_SPIKE = 5000;
12
+ const IDLE_TTL_WARNING_SECONDS = 3000; // ~50m+ (1h cache TTL boundary)
13
+ const HEAVY_MCP_NAME_RE = /chrome|devtools|playwright|puppeteer|browser|selenium|figma|github|notion|jira|linear|supabase|slack|postgres/i;
14
+ const HEAVY_MCP_EST_TOKENS = 3000;
15
+ const STANDARD_MCP_EST_TOKENS = 1200;
16
+
17
+ function estimateTokens(chars) {
18
+ if (!chars || chars <= 0) return 0;
19
+ return Math.ceil(chars / 3.5);
20
+ }
21
+
22
+ function byteLength(str) {
23
+ if (!str) return 0;
24
+ return Buffer.byteLength(str, 'utf8');
25
+ }
26
+
27
+ function isReadFileTool(name) {
28
+ return name === 'read_file' || name === 'view_file';
29
+ }
30
+
31
+ function parseLineNumber(val) {
32
+ if (val === undefined || val === null || val === '') return null;
33
+ const n = Number(val);
34
+ return Number.isFinite(n) ? Math.floor(n) : null;
35
+ }
36
+
37
+ function hasLineRange(args) {
38
+ if (!args || typeof args !== 'object') return false;
39
+ return (
40
+ parseLineNumber(args.StartLine ?? args.startLine ?? args.start_line) !== null ||
41
+ parseLineNumber(args.EndLine ?? args.endLine ?? args.end_line) !== null
42
+ );
43
+ }
44
+
45
+ function computeRequestedSpanLines(args) {
46
+ if (!args || typeof args !== 'object') return null;
47
+ const start = parseLineNumber(args.StartLine ?? args.startLine ?? args.start_line);
48
+ const end = parseLineNumber(args.EndLine ?? args.endLine ?? args.end_line);
49
+ if (start === null && end === null) return null;
50
+ if (start !== null && end !== null) {
51
+ return Math.max(0, end - start);
52
+ }
53
+ if (end !== null && start === null) {
54
+ return Math.max(0, end - 1);
55
+ }
56
+ return null;
57
+ }
58
+
59
+ function parseActualReadSpanFromOutput(contentStr) {
60
+ if (typeof contentStr !== 'string' || !contentStr) return null;
61
+ const m = contentStr.match(/Showing lines\s+(\d+)\s*-\s*(\d+)\s+of\s+(\d+)/i);
62
+ if (!m) return null;
63
+ const s = parseInt(m[1], 10);
64
+ const e = parseInt(m[2], 10);
65
+ if (!Number.isFinite(s) || !Number.isFinite(e) || e < s) return null;
66
+ return e - s;
67
+ }
68
+
69
+ function parseToolExecDurationSec(contentStr) {
70
+ if (typeof contentStr !== 'string' || !contentStr) return null;
71
+ const mCreate = contentStr.match(/Created At:\s*([^\r\n]+)/);
72
+ const mDone = contentStr.match(/Completed At:\s*([^\r\n]+)/);
73
+ if (!mCreate || !mDone) return null;
74
+ const t1 = Date.parse(mCreate[1].trim());
75
+ const t2 = Date.parse(mDone[1].trim());
76
+ if (Number.isNaN(t1) || Number.isNaN(t2) || t2 < t1) return null;
77
+ return Number(((t2 - t1) / 1000).toFixed(2));
78
+ }
79
+
80
+ function computeTimestampDiffSec(startIso, endIso) {
81
+ if (!startIso || !endIso) return null;
82
+ const t1 = Date.parse(startIso);
83
+ const t2 = Date.parse(endIso);
84
+ if (Number.isNaN(t1) || Number.isNaN(t2) || t2 < t1) return null;
85
+ return Number(((t2 - t1) / 1000).toFixed(2));
86
+ }
87
+
88
+ function extractMcpInvocation(name, args) {
89
+ if (!name || typeof name !== 'string') return null;
90
+ const safeArgs = args && typeof args === 'object' ? args : {};
91
+
92
+ if (name === 'call_mcp_tool') {
93
+ const serverName = String(safeArgs.ServerName ?? safeArgs.server_name ?? safeArgs.serverName ?? 'unknown_mcp').trim() || 'unknown_mcp';
94
+ const toolName = String(safeArgs.ToolName ?? safeArgs.tool_name ?? safeArgs.toolName ?? '').trim();
95
+ return {
96
+ serverName,
97
+ prefix: `mcp_${serverName}_`,
98
+ toolName: toolName || name,
99
+ callMode: 'lazy_call_mcp_tool'
100
+ };
101
+ }
102
+
103
+ if ((name === 'list_resources' || name === 'read_resource') && (safeArgs.ServerName || safeArgs.server_name)) {
104
+ const serverName = String(safeArgs.ServerName ?? safeArgs.server_name).trim();
105
+ return {
106
+ serverName,
107
+ prefix: `mcp_${serverName}_`,
108
+ toolName: name,
109
+ callMode: 'mcp_resource'
110
+ };
111
+ }
112
+
113
+ // Eagerly loaded MCP tools in Antigravity: `mcp_<serverName>_<toolName>` or `<serverName>__<toolName>`
114
+ if (name.startsWith('mcp_') && name !== 'mcp_servers') {
115
+ const rest = name.slice(4);
116
+ const sepIdx = rest.indexOf('_');
117
+ if (sepIdx > 0) {
118
+ const serverName = rest.slice(0, sepIdx);
119
+ const toolName = rest.slice(sepIdx + 1);
120
+ return {
121
+ serverName,
122
+ prefix: `mcp_${serverName}_`,
123
+ toolName,
124
+ callMode: 'eager_native_tool'
125
+ };
126
+ }
127
+ }
128
+
129
+ if (name.includes('__')) {
130
+ const parts = name.split('__');
131
+ if (parts[0] && parts[1]) {
132
+ const serverName = parts[0].replace(/^mcp_/, '');
133
+ return {
134
+ serverName,
135
+ prefix: `mcp_${serverName}_`,
136
+ toolName: parts.slice(1).join('__'),
137
+ callMode: 'prefixed_tool'
138
+ };
139
+ }
140
+ }
141
+
142
+ // Also detect reading MCP schema files from `<appDataDir>/mcp/<serverName>/<toolName>.json`
143
+ if (isReadFileTool(name)) {
144
+ const p = String(safeArgs.Path ?? safeArgs.path ?? '').replace(/\\/g, '/');
145
+ const m = p.match(/\/\.gemini\/(?:antigravity(?:-cli)?)\/mcp\/([^/]+)\/([^/]+)\.json$/i);
146
+ if (m) {
147
+ const serverName = m[1];
148
+ return {
149
+ serverName,
150
+ prefix: `mcp_${serverName}_`,
151
+ toolName: `schema:${m[2]}`,
152
+ callMode: 'mcp_schema_read'
153
+ };
154
+ }
155
+ }
156
+
157
+ return null;
158
+ }
159
+
160
+ function formatToolTarget(name, args) {
161
+ if (!args || typeof args !== 'object') return '';
162
+ if (name === 'call_mcp_tool') {
163
+ const srv = args.ServerName ?? args.server_name ?? 'mcp';
164
+ const tl = args.ToolName ?? args.tool_name ?? '';
165
+ const inner = args.Arguments ?? args.arguments ?? {};
166
+ const innerStr = JSON.stringify(inner);
167
+ const snippet = innerStr && innerStr !== '{}' ? ` ${innerStr.slice(0, 60)}${innerStr.length > 60 ? '...' : ''}` : '';
168
+ return `${srv}::${tl}${snippet}`;
169
+ }
170
+ if (args.Path || args.path) {
171
+ const p = args.Path || args.path;
172
+ const start = args.StartLine ?? args.startLine ?? args.start_line;
173
+ const end = args.EndLine ?? args.endLine ?? args.end_line;
174
+ if (start !== undefined || end !== undefined) {
175
+ return `${p} [L${start ?? 1}-L${end ?? 'EOF'}]`;
176
+ }
177
+ return p;
178
+ }
179
+ if (args.CommandLine || args.command) {
180
+ return args.CommandLine || args.command;
181
+ }
182
+ if (args.query) {
183
+ return `query: ${args.query}`;
184
+ }
185
+ if (args.Prompt) {
186
+ return `prompt: ${String(args.Prompt).slice(0, 80)}`;
187
+ }
188
+ if (args.Description) {
189
+ return String(args.Description).slice(0, 80);
190
+ }
191
+ const raw = JSON.stringify(args);
192
+ return raw.length > 100 ? raw.slice(0, 100) + '...' : raw;
193
+ }
194
+
195
+ function extractTokenUsage(step) {
196
+ const usage = step.usage && typeof step.usage === 'object' ? step.usage : step;
197
+ const input =
198
+ typeof usage.input_tokens === 'number'
199
+ ? usage.input_tokens
200
+ : typeof usage.prompt_tokens === 'number'
201
+ ? usage.prompt_tokens
202
+ : 0;
203
+ const output =
204
+ typeof usage.output_tokens === 'number'
205
+ ? usage.output_tokens
206
+ : typeof usage.completion_tokens === 'number'
207
+ ? usage.completion_tokens
208
+ : 0;
209
+ const cacheRead =
210
+ typeof usage.cache_read_tokens === 'number'
211
+ ? usage.cache_read_tokens
212
+ : typeof usage.cached_tokens === 'number'
213
+ ? usage.cached_tokens
214
+ : 0;
215
+ const hasUsage =
216
+ typeof usage.input_tokens === 'number' ||
217
+ typeof usage.output_tokens === 'number' ||
218
+ typeof usage.cache_read_tokens === 'number' ||
219
+ typeof usage.prompt_tokens === 'number';
220
+ return { input, output, cacheRead, hasUsage };
221
+ }
222
+
223
+ function computeIdleSeconds(prevIso, currIso) {
224
+ if (!prevIso || !currIso) return null;
225
+ const t1 = Date.parse(prevIso);
226
+ const t2 = Date.parse(currIso);
227
+ if (Number.isNaN(t1) || Number.isNaN(t2) || t2 < t1) return null;
228
+ return Math.round((t2 - t1) / 1000);
229
+ }
230
+
231
+ function analyzeSession(idOrPrefixOrPath) {
232
+ const { conversationId, transcriptInfo: info } = resolveSessionTarget(idOrPrefixOrPath);
233
+ if (!info) {
234
+ throw new Error(`Transcript file not found for conversation: ${idOrPrefixOrPath}`);
235
+ }
236
+
237
+ const rawContent = fs.readFileSync(info.filePath, 'utf8');
238
+ const rawLines = rawContent.split('\n').filter(l => l.trim().length > 0);
239
+ const steps = [];
240
+ for (const line of rawLines) {
241
+ try {
242
+ steps.push(JSON.parse(line));
243
+ } catch {
244
+ // Skip malformed line
245
+ }
246
+ }
247
+
248
+ let totalTurns = 0;
249
+ let plannerSteps = 0;
250
+ let totalInputTokens = 0;
251
+ let totalOutputTokens = 0;
252
+ let totalCacheReadTokens = 0;
253
+ let postWarmupInputTokens = 0;
254
+ let postWarmupCacheReadTokens = 0;
255
+ let coldStartInputTokens = 0;
256
+ let usageFieldSteps = 0;
257
+ let peakContextTokens = 0;
258
+ let peakContextStepIndex = null;
259
+ let lastStepContextTokens = 0;
260
+ let firstTimestamp = null;
261
+ let lastTimestamp = null;
262
+
263
+ const checkpoints = [];
264
+ let pendingCheckpoint = null;
265
+ const cacheCliffs = [];
266
+ let prevUsageStep = null;
267
+ let sawCheckpointSincePrevUsage = false;
268
+ let sawSettingsChangeSincePrevUsage = false;
269
+
270
+ const toolCalls = [];
271
+ const pendingQueue = [];
272
+ const toolBreakdown = {};
273
+ const turnStatsMap = new Map();
274
+ const invokedMcpMap = new Map();
275
+
276
+ function getOrCreateTurnStat(turnIdx) {
277
+ const key = Math.max(1, turnIdx);
278
+ if (!turnStatsMap.has(key)) {
279
+ turnStatsMap.set(key, {
280
+ turnIndex: key,
281
+ firstStepIndex: null,
282
+ lastStepIndex: null,
283
+ plannerSteps: 0,
284
+ toolCalls: 0,
285
+ startContextTokens: null,
286
+ endContextTokens: null,
287
+ peakContextTokens: 0,
288
+ inputTokens: 0,
289
+ cacheReadTokens: 0,
290
+ outputTokens: 0,
291
+ compactionsInTurn: 0
292
+ });
293
+ }
294
+ return turnStatsMap.get(key);
295
+ }
296
+
297
+ // Precompute prefix sums of USER_INPUT and PLANNER_RESPONSE indices so we know remaining turns/calls after any step
298
+ const turnsSeenAtPos = new Array(steps.length).fill(0);
299
+ const plannersSeenAtPos = new Array(steps.length).fill(0);
300
+ let tAcc = 0;
301
+ let pAcc = 0;
302
+ for (let i = 0; i < steps.length; i++) {
303
+ if (steps[i].type === 'USER_INPUT') tAcc++;
304
+ if (steps[i].type === 'PLANNER_RESPONSE') pAcc++;
305
+ turnsSeenAtPos[i] = tAcc;
306
+ plannersSeenAtPos[i] = pAcc;
307
+ }
308
+ const grandTotalTurns = tAcc;
309
+ const grandTotalPlanners = pAcc;
310
+
311
+ for (let i = 0; i < steps.length; i++) {
312
+ const step = steps[i];
313
+ if (!firstTimestamp && step.created_at) firstTimestamp = step.created_at;
314
+ if (step.created_at) lastTimestamp = step.created_at;
315
+
316
+ const stepIndex = step.step_index ?? i;
317
+ if (step.type === 'USER_INPUT') {
318
+ totalTurns++;
319
+ const ts = getOrCreateTurnStat(totalTurns);
320
+ if (ts.firstStepIndex === null) ts.firstStepIndex = stepIndex;
321
+ ts.lastStepIndex = stepIndex;
322
+ } else if (step.type === 'USER_SETTINGS_CHANGE') {
323
+ sawSettingsChangeSincePrevUsage = true;
324
+ }
325
+
326
+ const currentTurnStat = getOrCreateTurnStat(Math.max(1, totalTurns));
327
+ if (currentTurnStat.firstStepIndex === null) currentTurnStat.firstStepIndex = stepIndex;
328
+ currentTurnStat.lastStepIndex = stepIndex;
329
+
330
+ const usage = extractTokenUsage(step);
331
+ const stepContextTokens = usage.input + usage.cacheRead;
332
+
333
+ if (usage.hasUsage) {
334
+ usageFieldSteps++;
335
+ totalInputTokens += usage.input;
336
+ totalOutputTokens += usage.output;
337
+ totalCacheReadTokens += usage.cacheRead;
338
+
339
+ currentTurnStat.inputTokens += usage.input;
340
+ currentTurnStat.cacheReadTokens += usage.cacheRead;
341
+ currentTurnStat.outputTokens += usage.output;
342
+
343
+ if (stepContextTokens > 0) {
344
+ if (currentTurnStat.startContextTokens === null) {
345
+ currentTurnStat.startContextTokens = stepContextTokens;
346
+ }
347
+ currentTurnStat.endContextTokens = stepContextTokens;
348
+ if (stepContextTokens > currentTurnStat.peakContextTokens) {
349
+ currentTurnStat.peakContextTokens = stepContextTokens;
350
+ }
351
+
352
+ if (!prevUsageStep) {
353
+ coldStartInputTokens = usage.input;
354
+ } else {
355
+ postWarmupInputTokens += usage.input;
356
+ postWarmupCacheReadTokens += usage.cacheRead;
357
+
358
+ // Detect unexpected Prefix Cache cliff (excluding normal CHECKPOINT compactions)
359
+ if (!sawCheckpointSincePrevUsage) {
360
+ const prevContext = prevUsageStep.contextTokens;
361
+ const uncachedGap = prevContext - usage.cacheRead;
362
+ const retentionRatio = prevContext > 0 ? usage.cacheRead / prevContext : 1;
363
+
364
+ if (
365
+ prevContext >= CACHE_CLIFF_MIN_PREV_CONTEXT &&
366
+ retentionRatio < CACHE_CLIFF_RETENTION_RATIO &&
367
+ uncachedGap >= CACHE_CLIFF_MIN_DROP_TOKENS &&
368
+ usage.input >= CACHE_CLIFF_MIN_INPUT_SPIKE &&
369
+ usage.input >= uncachedGap * 0.5
370
+ ) {
371
+ const idleSeconds = computeIdleSeconds(prevUsageStep.createdAt, step.created_at);
372
+ let reasonCode = 'prefix_mutated_or_evicted';
373
+ let reason = `前缀变动或缓存驱逐 (仅复用 ${(retentionRatio * 100).toFixed(1)}% 历史前缀,排查动态规则/工具变更)`;
374
+
375
+ if (idleSeconds !== null && idleSeconds >= IDLE_TTL_WARNING_SECONDS) {
376
+ reasonCode = 'idle_ttl_expired';
377
+ reason = `闲置超时导致缓存过期 (距上一步间隔 ${(idleSeconds / 60).toFixed(1)} 分钟,超出缓存保活窗口)`;
378
+ } else if (sawSettingsChangeSincePrevUsage) {
379
+ reasonCode = 'settings_or_model_switch';
380
+ reason = '会话中途切换模型或设置 (USER_SETTINGS_CHANGE) 导致前缀重算';
381
+ }
382
+
383
+ const estRebilledTokens = Math.min(usage.input, Math.max(0, uncachedGap));
384
+ cacheCliffs.push({
385
+ index: cacheCliffs.length + 1,
386
+ prevStepIndex: prevUsageStep.stepIndex,
387
+ stepIndex,
388
+ turnIndex: Math.max(1, totalTurns),
389
+ createdAt: step.created_at || null,
390
+ idleSeconds,
391
+ prevContextTokens: prevContext,
392
+ prevCacheReadTokens: prevUsageStep.cacheRead,
393
+ currCacheReadTokens: usage.cacheRead,
394
+ currInputTokens: usage.input,
395
+ currContextTokens: stepContextTokens,
396
+ cacheDropTokens: Math.max(0, uncachedGap),
397
+ retentionPct: Number((retentionRatio * 100).toFixed(1)),
398
+ estRebilledTokens,
399
+ reasonCode,
400
+ reason
401
+ });
402
+ }
403
+ }
404
+ }
405
+
406
+ if (stepContextTokens > peakContextTokens) {
407
+ peakContextTokens = stepContextTokens;
408
+ peakContextStepIndex = stepIndex;
409
+ }
410
+ if (pendingCheckpoint && step.type !== 'CHECKPOINT') {
411
+ pendingCheckpoint.postCompactionTokens = stepContextTokens;
412
+ pendingCheckpoint = null;
413
+ }
414
+ lastStepContextTokens = stepContextTokens;
415
+
416
+ prevUsageStep = {
417
+ stepIndex,
418
+ turnIndex: Math.max(1, totalTurns),
419
+ input: usage.input,
420
+ cacheRead: usage.cacheRead,
421
+ contextTokens: stepContextTokens,
422
+ createdAt: step.created_at || null
423
+ };
424
+ sawCheckpointSincePrevUsage = false;
425
+ sawSettingsChangeSincePrevUsage = false;
426
+ }
427
+ }
428
+
429
+ if (step.type === 'CHECKPOINT') {
430
+ sawCheckpointSincePrevUsage = true;
431
+ currentTurnStat.compactionsInTurn++;
432
+ const contentStr = typeof step.content === 'string' ? step.content : '';
433
+ const preTokens = stepContextTokens > 0 ? stepContextTokens : lastStepContextTokens;
434
+ const cpRecord = {
435
+ index: checkpoints.length + 1,
436
+ stepIndex,
437
+ createdAt: step.created_at || null,
438
+ preCompactionTokens: preTokens,
439
+ postCompactionTokens: null,
440
+ summaryChars: contentStr.length,
441
+ summaryEstTokens: estimateTokens(contentStr.length)
442
+ };
443
+ checkpoints.push(cpRecord);
444
+ pendingCheckpoint = cpRecord;
445
+ } else if (step.type === 'PLANNER_RESPONSE') {
446
+ plannerSteps++;
447
+ currentTurnStat.plannerSteps++;
448
+
449
+ if (Array.isArray(step.tool_calls)) {
450
+ const batchLen = step.tool_calls.length;
451
+ for (let tcIdx = 0; tcIdx < batchLen; tcIdx++) {
452
+ const tc = step.tool_calls[tcIdx];
453
+ const name = tc.name || tc.toolName || 'unknown_tool';
454
+ const args = tc.args || tc.parameters || {};
455
+ const argsStr = JSON.stringify(args);
456
+ const inputChars = argsStr.length;
457
+ const inputBytes = byteLength(argsStr);
458
+ const inputEstTokens = estimateTokens(inputChars);
459
+
460
+ const isRead = isReadFileTool(name);
461
+ const ranged = isRead ? hasLineRange(args) : false;
462
+ const reqSpan = isRead ? computeRequestedSpanLines(args) : null;
463
+
464
+ const mcpCall = extractMcpInvocation(name, args);
465
+ if (mcpCall) {
466
+ if (!invokedMcpMap.has(mcpCall.serverName)) {
467
+ invokedMcpMap.set(mcpCall.serverName, {
468
+ name: mcpCall.serverName,
469
+ prefix: mcpCall.prefix,
470
+ callCount: 0,
471
+ invokedTools: new Set(),
472
+ callModes: new Set()
473
+ });
474
+ }
475
+ const entry = invokedMcpMap.get(mcpCall.serverName);
476
+ entry.callCount++;
477
+ if (mcpCall.toolName) entry.invokedTools.add(mcpCall.toolName);
478
+ entry.callModes.add(mcpCall.callMode);
479
+ }
480
+
481
+ currentTurnStat.toolCalls++;
482
+
483
+ const record = {
484
+ callPos: i,
485
+ resultPos: i,
486
+ stepIndex: step.step_index ?? i,
487
+ resultStepIndex: null,
488
+ turnIndex: Math.max(1, totalTurns),
489
+ plannerCreatedAt: step.created_at || null,
490
+ resultCreatedAt: null,
491
+ isFirstInPlannerBatch: tcIdx === 0,
492
+ toolName: name,
493
+ target: formatToolTarget(name, args),
494
+ isReadFile: isRead,
495
+ isBlindRead: isRead && !ranged,
496
+ isRangedRead: isRead && ranged,
497
+ requestedSpanLines: reqSpan,
498
+ actualSpanLines: null,
499
+ effectiveSpanLines: reqSpan,
500
+ execDurationSec: null,
501
+ stepWallSec: null,
502
+ durationSec: 0,
503
+ durationSource: 'unavailable',
504
+ inputChars,
505
+ inputBytes,
506
+ inputEstTokens,
507
+ outputChars: 0,
508
+ outputBytes: 0,
509
+ outputEstTokens: 0
510
+ };
511
+
512
+ toolCalls.push(record);
513
+ pendingQueue.push(record);
514
+
515
+ if (!toolBreakdown[name]) {
516
+ toolBreakdown[name] = {
517
+ count: 0,
518
+ inputChars: 0,
519
+ inputBytes: 0,
520
+ inputEstTokens: 0,
521
+ outputChars: 0,
522
+ outputBytes: 0,
523
+ outputEstTokens: 0
524
+ };
525
+ }
526
+ toolBreakdown[name].count++;
527
+ toolBreakdown[name].inputChars += inputChars;
528
+ toolBreakdown[name].inputBytes += inputBytes;
529
+ toolBreakdown[name].inputEstTokens += inputEstTokens;
530
+ }
531
+ }
532
+ } else if (step.type === 'GENERIC') {
533
+ // Match the oldest pending tool call from the nearest preceding PLANNER_RESPONSE when possible
534
+ const rec = pendingQueue.shift();
535
+ if (rec) {
536
+ const outStr = typeof step.content === 'string' ? step.content : JSON.stringify(step.content || '');
537
+ const outChars = outStr.length;
538
+ const outBytes = byteLength(outStr);
539
+ const outEstTokens = estimateTokens(outChars);
540
+
541
+ rec.resultPos = i;
542
+ rec.resultStepIndex = step.step_index ?? i;
543
+ rec.resultCreatedAt = step.created_at || null;
544
+ rec.outputChars = outChars;
545
+ rec.outputBytes = outBytes;
546
+ rec.outputEstTokens = outEstTokens;
547
+
548
+ // Parse exact tool execution duration (Created At -> Completed At), and end-to-end step wall time
549
+ const execSec = parseToolExecDurationSec(outStr);
550
+ const wallSec = computeTimestampDiffSec(rec.plannerCreatedAt, rec.resultCreatedAt);
551
+ rec.execDurationSec = execSec;
552
+ // Guard against out-of-order queue skew if an earlier step errored out without emitting GENERIC
553
+ const hasInterveningError = steps.slice(rec.callPos + 1, i).some(s => s.type === 'ERROR_MESSAGE');
554
+ rec.stepWallSec = !hasInterveningError ? wallSec : null;
555
+
556
+ if (execSec !== null && rec.stepWallSec !== null) {
557
+ // stepWallSec includes LLM streaming generation of large tool arguments + tool execution
558
+ rec.durationSec = rec.isFirstInPlannerBatch ? Math.max(execSec, rec.stepWallSec) : execSec;
559
+ rec.durationSource = rec.durationSec > execSec ? 'step_wall+exec' : 'tool_exec';
560
+ } else if (execSec !== null) {
561
+ rec.durationSec = execSec;
562
+ rec.durationSource = 'tool_exec';
563
+ } else if (rec.stepWallSec !== null) {
564
+ rec.durationSec = rec.stepWallSec;
565
+ rec.durationSource = 'step_wall';
566
+ }
567
+
568
+ if (rec.isReadFile) {
569
+ const actualSpan = parseActualReadSpanFromOutput(outStr);
570
+ rec.actualSpanLines = actualSpan;
571
+ const effSpan = rec.requestedSpanLines !== null ? rec.requestedSpanLines : actualSpan;
572
+ rec.effectiveSpanLines = effSpan;
573
+ }
574
+
575
+ const bd = toolBreakdown[rec.toolName];
576
+ if (bd) {
577
+ bd.outputChars += outChars;
578
+ bd.outputBytes += outBytes;
579
+ bd.outputEstTokens += outEstTokens;
580
+ }
581
+ }
582
+ } else if (step.type === 'ERROR_MESSAGE') {
583
+ // Clear orphaned pending tool calls from aborted planner step so subsequent GENERIC results align cleanly
584
+ pendingQueue.length = 0;
585
+ }
586
+ }
587
+
588
+ let blindReadCount = 0;
589
+ let rangedReadCount = 0;
590
+ let totalToolInputChars = 0;
591
+ let totalToolInputBytes = 0;
592
+ let totalToolOutputChars = 0;
593
+ let totalToolOutputBytes = 0;
594
+
595
+ for (const tc of toolCalls) {
596
+ if (tc.isBlindRead) blindReadCount++;
597
+ if (tc.isRangedRead) rangedReadCount++;
598
+ totalToolInputChars += tc.inputChars;
599
+ totalToolInputBytes += tc.inputBytes;
600
+ totalToolOutputChars += tc.outputChars;
601
+ totalToolOutputBytes += tc.outputBytes;
602
+
603
+ const refPos = tc.resultPos;
604
+ tc.remainingTurns = Math.max(0, grandTotalTurns - turnsSeenAtPos[refPos]);
605
+ tc.remainingPlannerSteps = Math.max(0, grandTotalPlanners - plannersSeenAtPos[refPos]);
606
+ tc.estSnowballTokens = tc.outputEstTokens * tc.remainingPlannerSteps;
607
+ }
608
+
609
+ const sortedByDuration = [...toolCalls]
610
+ .filter(tc => typeof tc.durationSec === 'number' && tc.durationSec >= 0)
611
+ .sort((a, b) => b.durationSec - a.durationSec || (b.execDurationSec ?? 0) - (a.execDurationSec ?? 0));
612
+
613
+ const slowestSteps = sortedByDuration.slice(0, 3).map((tc, idx) => ({
614
+ rank: idx + 1,
615
+ stepIndex: tc.stepIndex,
616
+ resultStepIndex: tc.resultStepIndex,
617
+ turnIndex: tc.turnIndex,
618
+ toolName: tc.toolName,
619
+ target: tc.target,
620
+ durationSec: tc.durationSec,
621
+ execDurationSec: tc.execDurationSec,
622
+ stepWallSec: tc.stepWallSec,
623
+ durationSource: tc.durationSource,
624
+ outputBytes: tc.outputBytes,
625
+ outputEstTokens: tc.outputEstTokens
626
+ }));
627
+
628
+ // Build per-turn context net growth & cache hit rate breakdown
629
+ const turnDeltas = [];
630
+ let prevTurnEndContext = 0;
631
+ const sortedTurnEntries = Array.from(turnStatsMap.values()).sort((a, b) => a.turnIndex - b.turnIndex);
632
+ for (const t of sortedTurnEntries) {
633
+ const endCtx = t.endContextTokens !== null ? t.endContextTokens : prevTurnEndContext;
634
+ const startCtx = t.startContextTokens !== null ? t.startContextTokens : prevTurnEndContext;
635
+ const netContextDeltaTokens = t.endContextTokens !== null ? endCtx - prevTurnEndContext : 0;
636
+ const billed = t.inputTokens + t.cacheReadTokens;
637
+ const turnCacheHitRatePct = billed > 0 ? Number(((t.cacheReadTokens / billed) * 100).toFixed(1)) : 0;
638
+
639
+ turnDeltas.push({
640
+ turnIndex: t.turnIndex,
641
+ firstStepIndex: t.firstStepIndex,
642
+ lastStepIndex: t.lastStepIndex,
643
+ plannerSteps: t.plannerSteps,
644
+ toolCalls: t.toolCalls,
645
+ prevTurnEndContextTokens: prevTurnEndContext,
646
+ startContextTokens: startCtx,
647
+ endContextTokens: endCtx,
648
+ peakContextTokens: t.peakContextTokens,
649
+ netContextDeltaTokens,
650
+ inputTokens: t.inputTokens,
651
+ cacheReadTokens: t.cacheReadTokens,
652
+ outputTokens: t.outputTokens,
653
+ cacheHitRatePct: turnCacheHitRatePct,
654
+ compactionsInTurn: t.compactionsInTurn
655
+ });
656
+
657
+ if (t.endContextTokens !== null) {
658
+ prevTurnEndContext = t.endContextTokens;
659
+ }
660
+ }
661
+
662
+ // Merge session DB `<mcp_servers>` prompt inspection + transcript actual MCP invocations
663
+ const dbMcpInfo = inspectSessionMountedMcp(conversationId, info.filePath);
664
+ const mergedMcpMap = new Map();
665
+
666
+ for (const srv of dbMcpInfo.servers) {
667
+ const isHeavy = HEAVY_MCP_NAME_RE.test(srv.name);
668
+ mergedMcpMap.set(srv.name, {
669
+ name: srv.name,
670
+ prefix: srv.prefix,
671
+ mountedInPrompt: true,
672
+ invokedInTranscript: false,
673
+ callCount: 0,
674
+ eagerToolCount: srv.eagerTools.length,
675
+ lazyToolCount: srv.lazyTools.length,
676
+ invokedTools: [],
677
+ tier: isHeavy ? 'heavy' : 'standard',
678
+ estTokensPerStep: isHeavy ? HEAVY_MCP_EST_TOKENS : STANDARD_MCP_EST_TOKENS
679
+ });
680
+ }
681
+
682
+ for (const [srvName, inv] of invokedMcpMap.entries()) {
683
+ const isHeavy = HEAVY_MCP_NAME_RE.test(srvName);
684
+ if (!mergedMcpMap.has(srvName)) {
685
+ mergedMcpMap.set(srvName, {
686
+ name: srvName,
687
+ prefix: inv.prefix,
688
+ mountedInPrompt: true,
689
+ invokedInTranscript: true,
690
+ callCount: inv.callCount,
691
+ eagerToolCount: 0,
692
+ lazyToolCount: 0,
693
+ invokedTools: Array.from(inv.invokedTools),
694
+ tier: isHeavy ? 'heavy' : 'standard',
695
+ estTokensPerStep: isHeavy ? HEAVY_MCP_EST_TOKENS : STANDARD_MCP_EST_TOKENS
696
+ });
697
+ } else {
698
+ const existing = mergedMcpMap.get(srvName);
699
+ existing.invokedInTranscript = true;
700
+ existing.callCount = inv.callCount;
701
+ existing.invokedTools = Array.from(inv.invokedTools);
702
+ }
703
+ }
704
+
705
+ const mountedMcpServers = Array.from(mergedMcpMap.values());
706
+ const mountedMcpPrefixes = mountedMcpServers.map(s => s.prefix);
707
+ const unusedMountedMcpServers = mountedMcpServers.filter(s => s.callCount === 0).map(s => s.name);
708
+ const estMountedMcpTokensPerStep = mountedMcpServers.reduce((acc, s) => acc + s.estTokensPerStep, 0);
709
+ const estMountedMcpSessionTaxTokens = estMountedMcpTokensPerStep * Math.max(1, plannerSteps);
710
+
711
+ const mcpAudit = {
712
+ detectionSource: dbMcpInfo.detectedFromSessionDb
713
+ ? (invokedMcpMap.size > 0 ? 'session_db+transcript' : 'session_db')
714
+ : (invokedMcpMap.size > 0 ? 'transcript_calls' : 'transcript_only'),
715
+ detectedFromSessionDb: dbMcpInfo.detectedFromSessionDb,
716
+ mountedCount: mountedMcpServers.length,
717
+ invokedServerCount: invokedMcpMap.size,
718
+ totalMcpToolCalls: Array.from(invokedMcpMap.values()).reduce((s, x) => s + x.callCount, 0),
719
+ prefixes: mountedMcpPrefixes,
720
+ unusedServerNames: unusedMountedMcpServers,
721
+ estTokensPerStep: estMountedMcpTokensPerStep,
722
+ estSessionTaxTokens: estMountedMcpSessionTaxTokens,
723
+ servers: mountedMcpServers
724
+ };
725
+
726
+ const sortedByOutput = [...toolCalls].sort((a, b) => b.outputBytes - a.outputBytes || b.outputChars - a.outputChars);
727
+ const topBloats = sortedByOutput.slice(0, 5).map((tc, idx) => ({
728
+ rank: idx + 1,
729
+ stepIndex: tc.stepIndex,
730
+ resultStepIndex: tc.resultStepIndex,
731
+ turnIndex: tc.turnIndex,
732
+ toolName: tc.toolName,
733
+ target: tc.target,
734
+ isReadFile: tc.isReadFile,
735
+ isBlindRead: tc.isBlindRead,
736
+ isRangedRead: tc.isRangedRead,
737
+ effectiveSpanLines: tc.effectiveSpanLines,
738
+ durationSec: tc.durationSec,
739
+ inputChars: tc.inputChars,
740
+ inputBytes: tc.inputBytes,
741
+ inputEstTokens: tc.inputEstTokens,
742
+ outputChars: tc.outputChars,
743
+ outputBytes: tc.outputBytes,
744
+ outputEstTokens: tc.outputEstTokens,
745
+ remainingTurns: tc.remainingTurns,
746
+ remainingPlannerSteps: tc.remainingPlannerSteps,
747
+ estSnowballTokens: tc.estSnowballTokens
748
+ }));
749
+
750
+ const maxSingleStepOutput = topBloats.length > 0 ? topBloats[0] : null;
751
+ const slowestStep = slowestSteps.length > 0 ? slowestSteps[0] : null;
752
+
753
+ let durationSeconds = 0;
754
+ if (firstTimestamp && lastTimestamp) {
755
+ const startMs = new Date(firstTimestamp).getTime();
756
+ const endMs = new Date(lastTimestamp).getTime();
757
+ if (!isNaN(startMs) && !isNaN(endMs) && endMs >= startMs) {
758
+ durationSeconds = Math.round((endMs - startMs) / 1000);
759
+ }
760
+ }
761
+
762
+ const dbMeta = getConversationMeta(conversationId);
763
+ const meta = {
764
+ conversationId,
765
+ shortId: conversationId.slice(0, 8),
766
+ title: (dbMeta && dbMeta.title) || 'Untitled Session',
767
+ workspace: (dbMeta && dbMeta.workspace) || '',
768
+ logType: info.logType,
769
+ logFile: info.filePath,
770
+ logBytes: info.bytes,
771
+ firstTimestamp,
772
+ lastTimestamp,
773
+ durationSec: durationSeconds,
774
+ durationSeconds
775
+ };
776
+
777
+ const peakContextPct256k = peakContextTokens > 0
778
+ ? Number(((peakContextTokens / COMPACTION_THRESHOLD_256K) * 100).toFixed(1))
779
+ : 0;
780
+ const peakContextPct512k = peakContextTokens > 0
781
+ ? Number(((peakContextTokens / COMPACTION_THRESHOLD_512K) * 100).toFixed(1))
782
+ : 0;
783
+ const totalBilledContextTokens = totalInputTokens + totalCacheReadTokens;
784
+ const totalThroughputTokens = totalBilledContextTokens + totalOutputTokens;
785
+ const cacheHitRatePct = totalBilledContextTokens > 0
786
+ ? Number(((totalCacheReadTokens / totalBilledContextTokens) * 100).toFixed(1))
787
+ : 0;
788
+ const postWarmupTotal = postWarmupInputTokens + postWarmupCacheReadTokens;
789
+ const postWarmupCacheHitRatePct = postWarmupTotal > 0
790
+ ? Number(((postWarmupCacheReadTokens / postWarmupTotal) * 100).toFixed(1))
791
+ : 0;
792
+ const cacheRebilledTokens = cacheCliffs.reduce((s, c) => s + c.estRebilledTokens, 0);
793
+
794
+ const netDeltas = turnDeltas.map(t => t.netContextDeltaTokens);
795
+ const maxTurnNetContextDeltaTokens = netDeltas.length > 0 ? Math.max(...netDeltas) : 0;
796
+ const minTurnNetContextDeltaTokens = netDeltas.length > 0 ? Math.min(...netDeltas) : 0;
797
+ const avgTurnNetContextDeltaTokens = netDeltas.length > 0
798
+ ? Math.round(netDeltas.reduce((a, b) => a + b, 0) / netDeltas.length)
799
+ : 0;
800
+
801
+ return {
802
+ meta,
803
+ stats: {
804
+ durationSec: durationSeconds,
805
+ durationSeconds,
806
+ totalTurns,
807
+ totalSteps: steps.length,
808
+ plannerSteps,
809
+ totalToolCalls: toolCalls.length,
810
+ blindReadCount,
811
+ rangedReadCount,
812
+ readTotalCount: blindReadCount + rangedReadCount,
813
+ mountedMcpCount: mcpAudit.mountedCount,
814
+ mountedMcpServers: mountedMcpServers.map(s => s.name),
815
+ mountedMcpPrefixes,
816
+ invokedMcpToolCalls: mcpAudit.totalMcpToolCalls,
817
+ hasUsageMetrics: usageFieldSteps > 0,
818
+ usageFieldSteps,
819
+ coldStartInputTokens,
820
+ totalInputTokens,
821
+ totalOutputTokens,
822
+ totalCacheReadTokens,
823
+ totalEffectiveTokens: totalInputTokens + totalOutputTokens,
824
+ totalBilledContextTokens,
825
+ totalThroughputTokens,
826
+ cacheHitRatePct,
827
+ postWarmupCacheHitRatePct,
828
+ cacheCliffCount: cacheCliffs.length,
829
+ cacheRebilledTokens,
830
+ peakContextTokens,
831
+ peakContextPct256k,
832
+ peakContextPct512k,
833
+ peakContextStepIndex,
834
+ maxTurnNetContextDeltaTokens,
835
+ minTurnNetContextDeltaTokens,
836
+ avgTurnNetContextDeltaTokens,
837
+ compactionThresholdTokens: COMPACTION_THRESHOLD_256K,
838
+ compactionThresholdGen4EstTokens: COMPACTION_THRESHOLD_512K,
839
+ compactionCount: checkpoints.length,
840
+ totalToolInputChars,
841
+ totalToolInputBytes,
842
+ totalToolInputEstTokens: estimateTokens(totalToolInputChars),
843
+ totalToolOutputChars,
844
+ totalToolOutputBytes,
845
+ totalToolOutputEstTokens: estimateTokens(totalToolOutputChars),
846
+ maxSingleStepOutput,
847
+ slowestStep
848
+ },
849
+ slowestSteps,
850
+ mcpAudit,
851
+ turnDeltas,
852
+ checkpoints,
853
+ cacheCliffs,
854
+ toolBreakdown,
855
+ topBloats
856
+ };
857
+ }
858
+
859
+ module.exports = {
860
+ analyzeSession,
861
+ estimateTokens,
862
+ COMPACTION_THRESHOLD_256K,
863
+ COMPACTION_THRESHOLD_512K
864
+ };