-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-report.js
More file actions
1929 lines (1731 loc) · 70.9 KB
/
generate-report.js
File metadata and controls
1929 lines (1731 loc) · 70.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* generate-report.js
*
* Reads a JSONL log file (captured by tracecc proxy) and generates
* a self-contained HTML report with:
* - Conversations tab: grouped by (model_class, first_user_text), shown as turns
* - Raw Calls tab: every API call with cache hit rate, tokens, latency
*
* Usage: node generate-report.js <input.jsonl> [output.html]
*/
import fs from 'fs';
import path from 'path';
import { detectFormat, convertCCEntries } from './analyze-lib.js';
// ── Constants ───────────────────────────────────────────────────────────────
const TEXT_PREVIEW_LEN = 200; // max chars for user text previews
const TOOL_RESULT_MAX = 1000; // max chars for tool result content display
const TOOL_RESULT_SHORT = 500; // max chars for tool results in step view
const SYSTEM_PROMPT_MAX = 3000; // max chars before truncating system prompt
const DESCRIPTION_MAX = 120; // max chars for tool description preview
const SYSTEM_PROMPT_THRESHOLD = 10000; // system prompt length heuristic for main thread detection
// ── Helpers ──────────────────────────────────────────────────────────────────
function extractSSEData(bodyRaw) {
if (!bodyRaw) return { usage: null, model: null, text: '', thinking: '' };
let usage = null, model = null, text = '', thinking = '';
let finalOutputTokens = 0;
for (const line of bodyRaw.split('\n')) {
if (!line.startsWith('data:')) continue;
try {
const evt = JSON.parse(line.slice(5).trim());
if (evt.type === 'message_start' && evt.message) {
usage = evt.message.usage || null;
model = evt.message.model || null;
}
if (evt.type === 'message_delta' && evt.usage) {
finalOutputTokens = evt.usage.output_tokens || 0;
}
if (evt.type === 'content_block_delta') {
const delta = evt.delta || {};
if (delta.type === 'text_delta') text += delta.text || '';
if (delta.type === 'thinking_delta') thinking += delta.thinking || '';
}
} catch (e) { /* malformed SSE event, skip */ }
}
if (usage) usage.output_tokens = finalOutputTokens || usage.output_tokens || 0;
return { usage, model, text, thinking };
}
function stripSystemReminders(text) {
if (!text) return '';
return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trim();
}
function getFirstUserText(messages) {
if (!messages || !messages.length) return '';
for (const m of messages) {
if (m.role !== 'user') continue;
const content = m.content;
if (typeof content === 'string') return stripSystemReminders(content).slice(0, TEXT_PREVIEW_LEN);
if (Array.isArray(content)) {
const texts = content
.filter(p => p.type === 'text' && typeof p.text === 'string')
.map(p => stripSystemReminders(p.text))
.filter(t => t.length > 0);
return texts.join(' ').slice(0, TEXT_PREVIEW_LEN);
}
}
return '';
}
function getModelClass(model) {
if (!model) return 'unknown';
if (model.includes('opus')) return 'opus';
if (model.includes('sonnet')) return 'sonnet';
if (model.includes('haiku')) return 'haiku';
return model;
}
function getSystemPromptLength(system) {
if (!system) return 0;
if (typeof system === 'string') return system.length;
if (Array.isArray(system)) return system.reduce((s, p) => s + (p.text || '').length, 0);
return 0;
}
// ── Parse JSONL ──────────────────────────────────────────────────────────────
function parseJSONL(filePath) {
const content = fs.readFileSync(filePath, 'utf-8');
const parsed = [];
for (const line of content.split('\n')) {
if (!line.trim()) continue;
try { parsed.push(JSON.parse(line)); } catch {}
}
// Detect format and convert if needed
const format = detectFormat(parsed);
if (format === 'claude-code') {
return convertCCEntries(parsed);
}
return parsed;
}
// ── Build structured data ────────────────────────────────────────────────────
function extractFromCCContent(content, usage, model) {
let text = '', thinking = '';
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'text') text += (block.text || '') + '\n';
if (block.type === 'thinking') thinking += (block.thinking || '') + '\n';
}
}
return { usage: usage || null, model: model || null, text: text.trim(), thinking: thinking.trim() };
}
function buildRawCalls(entries) {
return entries.map((e, index) => {
const reqBody = e.request?.body || {};
const sse = e._ccContent
? extractFromCCContent(e._ccContent, e._ccUsage, e._ccModel)
: extractSSEData(e.response?.body_raw);
const usage = sse.usage || {};
const inputTokens = usage.input_tokens || 0;
const cacheCreation = usage.cache_creation_input_tokens || 0;
const cacheRead = usage.cache_read_input_tokens || 0;
const outputTokens = usage.output_tokens || 0;
const totalInput = inputTokens + cacheCreation + cacheRead;
const cacheHitRate = totalInput > 0 ? ((cacheRead / totalInput) * 100) : 0;
// Extract request-side info
const messages = reqBody.messages || [];
const lastUserText = getFirstUserText(messages.slice().reverse().filter(m => m.role === 'user').length ? [messages.slice().reverse().find(m => m.role === 'user')] : []);
const firstUserText = getFirstUserText(messages);
// Extract tool_use calls from assistant messages in request
const requestToolCalls = [];
for (const msg of messages) {
if (msg.role === 'assistant' && Array.isArray(msg.content)) {
for (const part of msg.content) {
if (part.type === 'tool_use') {
requestToolCalls.push({
name: part.name,
summary: toolCallSummary(part.name, part.input || {}),
category: categorizeToolCall(part.name),
});
}
}
}
}
// Build message structure summary: [user, assistant(3 tools), user(3 results), ...]
const msgStructure = messages.map(m => {
if (!Array.isArray(m.content)) return m.role;
const tools = m.content.filter(p => p.type === 'tool_use').length;
const results = m.content.filter(p => p.type === 'tool_result').length;
if (tools > 0) return `${m.role}(${tools} tools)`;
if (results > 0) return `${m.role}(${results} results)`;
return m.role;
});
return {
index,
timestamp: e.request?.timestamp,
loggedAt: e.logged_at,
method: e.request?.method || '',
url: e.request?.url || '',
statusCode: e.response?.status_code,
model: reqBody.model || sse.model || 'unknown',
modelClass: getModelClass(reqBody.model || sse.model || ''),
messageCount: messages.length,
latency: ((e.response?.timestamp || 0) - (e.request?.timestamp || 0)),
inputTokens,
cacheCreation,
cacheRead,
outputTokens,
totalInput,
cacheHitRate: parseFloat(cacheHitRate.toFixed(1)),
responseText: sse.text,
thinkingText: sse.thinking,
hasTools: Array.isArray(reqBody.tools) && reqBody.tools.length > 0,
stream: !!reqBody.stream,
firstUserText,
lastUserText,
requestToolCalls,
msgStructure,
};
});
}
/**
* Extract tool_use and tool_result from a list of new messages (delta since previous step).
* Returns { newToolCalls, newToolResults }.
*/
function extractStepTools(newMessages) {
const newToolCalls = [];
const newToolResults = [];
for (const msg of newMessages) {
if (!Array.isArray(msg.content)) continue;
if (msg.role === 'assistant') {
for (const part of msg.content) {
if (part.type === 'tool_use') {
newToolCalls.push({
name: part.name,
summary: toolCallSummary(part.name, part.input || {}),
category: categorizeToolCall(part.name),
});
}
}
} else if (msg.role === 'user') {
for (const part of msg.content) {
if (part.type === 'tool_result') {
const rawContent = typeof part.content === 'string'
? part.content
: Array.isArray(part.content)
? part.content.map(c => c.text || '').join('\n')
: '';
newToolResults.push({
toolUseId: part.tool_use_id,
content: rawContent.slice(0, TOOL_RESULT_SHORT),
isError: !!part.is_error,
});
}
}
}
}
return { newToolCalls, newToolResults };
}
/** Build a step object for each API call in a conversation group. */
function buildSteps(members) {
return members.map((member, stepIdx) => {
const stepBody = member.entry.request?.body || {};
const stepMsgs = stepBody.messages || [];
const stepSSE = member.entry._ccContent
? extractFromCCContent(member.entry._ccContent, member.entry._ccUsage, member.entry._ccModel)
: extractSSEData(member.entry.response?.body_raw);
const stepUsage = stepSSE.usage || {};
const prevMsgCount = stepIdx > 0 ? members[stepIdx - 1].messageCount : 0;
const newMessages = stepMsgs.slice(prevMsgCount);
const { newToolCalls, newToolResults } = extractStepTools(newMessages);
const inputTokens = stepUsage.input_tokens || 0;
const cacheCreation = stepUsage.cache_creation_input_tokens || 0;
const cacheRead = stepUsage.cache_read_input_tokens || 0;
const outputTokens = stepUsage.output_tokens || 0;
const totalInput = inputTokens + cacheCreation + cacheRead;
const stepModel = stepSSE.model || stepBody.model || member.model || 'unknown';
return {
stepIndex: stepIdx,
entryIndex: member.entryIndex,
timestamp: member.entry.request?.timestamp,
responseTimestamp: member.entry.response?.timestamp,
latency: (member.entry.response?.timestamp || 0) - (member.entry.request?.timestamp || 0),
model: stepModel,
modelClass: getModelClass(stepModel),
messageCount: stepMsgs.length,
prevMessageCount: prevMsgCount,
responseText: stepSSE.text,
thinkingText: stepSSE.thinking,
newToolCalls,
newToolResults,
totalInput, inputTokens, cacheCreation, cacheRead, outputTokens,
cacheHitRate: totalInput > 0 ? parseFloat(((cacheRead / totalInput) * 100).toFixed(1)) : 0,
_ccUuid: member.entry._ccUuid || null,
_ccParentUuid: member.entry._ccParentUuid || null,
};
});
}
/**
* Split turns into segments at each real user input boundary, and assign
* steps to the correct segment based on message-index ranges.
* Returns { segments, stepsBySegment }.
*/
function splitTurnsIntoSegments(allTurns, messages, steps) {
// Split turns at each new user text input
const segments = [];
let currentSegment = [];
for (const turn of allTurns) {
if (turn.type === 'user' && turn.content.text && currentSegment.length > 0) {
segments.push(currentSegment);
currentSegment = [turn];
} else {
currentSegment.push(turn);
}
}
if (currentSegment.length > 0) segments.push(currentSegment);
// Build user-input boundary indices from messages to map steps → segments
const userInputMsgIndices = [0];
let realUserCount = 0;
for (let mi = 0; mi < messages.length; mi++) {
if (messages[mi].role === 'user') {
const txt = extractContent(messages[mi].content);
if (txt.text) {
realUserCount++;
if (realUserCount > 1) userInputMsgIndices.push(mi);
}
}
}
// Assign each step to the correct segment
const stepsBySegment = segments.map(() => []);
for (const step of steps) {
let segIdx = 0;
for (let s = userInputMsgIndices.length - 1; s >= 0; s--) {
if (step.prevMessageCount >= userInputMsgIndices[s] || step.messageCount > userInputMsgIndices[s]) {
segIdx = s;
break;
}
}
if (segIdx < stepsBySegment.length) stepsBySegment[segIdx].push(step);
}
return { segments, stepsBySegment };
}
/** Link Agent tool_use calls in main threads to matching sub-agent conversations. */
function linkSubAgents(conversations) {
const mainThreads = conversations.filter(c => c.isMainThread);
const subAgents = conversations.filter(c => !c.isMainThread);
for (const main of mainThreads) {
for (const turn of main.turns) {
for (const tool of turn.toolCalls) {
if (tool.name !== 'Agent') continue;
const agentPrompt = tool.input?.prompt || '';
const prompt = stripSystemReminders(agentPrompt).slice(0, TEXT_PREVIEW_LEN);
const match = subAgents.find(sa =>
sa.firstUserText && prompt && sa.firstUserText.startsWith(prompt.slice(0, 60))
);
if (match) {
tool.linkedConversationId = match.id;
match.parentConversationId = main.id;
if (!main.subAgents.find(s => s.id === match.id)) {
main.subAgents.push(match);
}
}
}
}
}
}
/**
* Build structured conversation objects from parsed log entries.
*
* Groups API calls by (modelClass, firstUserText), then splits each group
* into per-user-input segments. Each segment becomes one conversation card
* in the UI. Also links main threads to sub-agent conversations.
*/
function buildConversations(entries) {
// Step 1: Group entries by (modelClass, firstUserText)
const groups = new Map();
for (let i = 0; i < entries.length; i++) {
const e = entries[i];
const reqBody = e.request?.body || {};
const messages = reqBody.messages || [];
const model = reqBody.model || '';
if (!messages.length || !model) continue;
const modelClass = getModelClass(model);
const firstUserText = getFirstUserText(messages);
if (!firstUserText) continue;
const key = `${modelClass}::${firstUserText}`;
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push({ entryIndex: i, entry: e, messageCount: messages.length, model });
}
// Step 2: Build conversations from each group
const conversations = [];
for (const [key, members] of groups) {
members.sort((a, b) => a.messageCount - b.messageCount);
const final = members[members.length - 1];
const first = members[0];
const reqBody = final.entry.request?.body || {};
const messages = reqBody.messages || [];
const sseData = final.entry._ccContent
? extractFromCCContent(final.entry._ccContent, final.entry._ccUsage, final.entry._ccModel)
: extractSSEData(final.entry.response?.body_raw);
const allTurns = extractTurns(messages, sseData);
const steps = buildSteps(members);
// Detect main thread vs sub-agent (prefer CC metadata over heuristic)
const sysLen = getSystemPromptLength(reqBody.system);
const modelClass = getModelClass(final.model);
const hasSidechainMeta = members.some(m => m.entry._ccIsSidechain !== undefined);
const isMainThread = hasSidechainMeta
? !final.entry._ccIsSidechain
: (modelClass === 'opus' || sysLen > SYSTEM_PROMPT_THRESHOLD);
// Extract system prompt
const systemRaw = reqBody.system;
let systemPromptText = '';
if (typeof systemRaw === 'string') systemPromptText = systemRaw;
else if (Array.isArray(systemRaw)) systemPromptText = systemRaw.map(p => p.text || '').join('\n\n');
const toolDefs = (reqBody.tools || []).map(t => ({
name: t.name || '',
description: (t.description || '').slice(0, DESCRIPTION_MAX),
}));
const truncatedSystemPrompt = systemPromptText.length > SYSTEM_PROMPT_MAX
? systemPromptText.slice(0, SYSTEM_PROMPT_MAX) + `\n\n... [truncated, ${systemPromptText.length} chars total]`
: systemPromptText;
// Step 3: Split into per-user-input segments
const { segments, stepsBySegment } = splitTurnsIntoSegments(allTurns, messages, steps);
for (let segIdx = 0; segIdx < segments.length; segIdx++) {
const segTurns = segments[segIdx];
const segUserTurn = segTurns.find(t => t.type === 'user' && t.content.text);
const segUserText = segUserTurn ? segUserTurn.content.text.slice(0, TEXT_PREVIEW_LEN) : getFirstUserText(messages);
const segSteps = stepsBySegment[segIdx] || [];
conversations.push({
id: `${key}::seg${segIdx}`,
modelClass,
model: final.model,
firstUserText: segUserText,
isMainThread,
totalRounds: segSteps.length,
entryIndices: segSteps.map(s => s.entryIndex),
startTime: segSteps.length > 0 ? segSteps[0].timestamp : (segIdx === 0 ? first.entry.request?.timestamp : undefined),
endTime: segSteps.length > 0 ? segSteps[segSteps.length - 1].responseTimestamp : (segIdx === segments.length - 1 ? final.entry.response?.timestamp : undefined),
turns: segTurns,
steps: segSteps,
finalResponseText: segIdx === segments.length - 1 ? sseData.text : '',
finalThinking: segIdx === segments.length - 1 ? sseData.thinking : '',
subAgents: [],
systemPrompt: segIdx === 0 ? truncatedSystemPrompt : '',
toolDefs: segIdx === 0 ? toolDefs : [],
_segmentIndex: segIdx,
_groupKey: key,
});
}
}
// Step 4: Link sub-agents to main threads and sort
linkSubAgents(conversations);
conversations.sort((a, b) => {
if (a.isMainThread && !b.isMainThread) return -1;
if (!a.isMainThread && b.isMainThread) return 1;
return (a.startTime || 0) - (b.startTime || 0);
});
return conversations;
}
function extractTurns(messages, finalSSE) {
const turns = [];
let i = 0;
while (i < messages.length) {
const msg = messages[i];
if (msg.role === 'user') {
// User turn
const userContent = extractContent(msg.content);
turns.push({
type: 'user',
content: userContent,
toolResults: [],
toolCalls: [],
});
i++;
} else if (msg.role === 'assistant') {
// Assistant turn: extract text + tool_use
const assistantContent = extractContent(msg.content);
const toolCalls = extractToolCalls(msg.content);
const toolResults = [];
// Check if next message is user with tool_results
if (i + 1 < messages.length && messages[i + 1].role === 'user') {
const nextContent = messages[i + 1].content;
if (Array.isArray(nextContent)) {
for (const part of nextContent) {
if (part.type === 'tool_result') {
const rawContent = typeof part.content === 'string'
? part.content
: Array.isArray(part.content)
? part.content.map(c => c.text || '').join('\n')
: '';
toolResults.push({
toolUseId: part.tool_use_id,
content: rawContent.length > 1000
? rawContent.slice(0, TOOL_RESULT_MAX) + `\n... [${rawContent.length} chars total]`
: rawContent,
isError: !!part.is_error,
});
}
}
}
if (toolResults.length > 0) i++; // skip the tool_result user message
}
turns.push({
type: 'assistant',
content: assistantContent,
toolCalls,
toolResults,
});
i++;
} else {
i++;
}
}
// If we have SSE text, update or append the final assistant turn
if (finalSSE.text && turns.length > 0) {
const lastAssistant = turns.filter(t => t.type === 'assistant').pop();
if (lastAssistant && !lastAssistant.content.text) {
// Update existing assistant turn that has no text yet
lastAssistant.content.text = finalSSE.text;
lastAssistant.content.thinking = finalSSE.thinking;
} else if (!lastAssistant) {
// No assistant turn exists at all — add one
turns.push({
type: 'assistant',
content: { text: finalSSE.text, thinking: finalSSE.thinking },
toolCalls: [],
toolResults: [],
});
}
}
return turns;
}
function extractContent(content) {
if (typeof content === 'string') {
return { text: stripSystemReminders(content), thinking: '' };
}
if (Array.isArray(content)) {
let text = '', thinking = '';
for (const part of content) {
if (part.type === 'text') text += stripSystemReminders(part.text || '') + '\n';
if (part.type === 'thinking') thinking += (part.thinking || '') + '\n';
}
return { text: text.trim(), thinking: thinking.trim() };
}
return { text: '', thinking: '' };
}
function extractToolCalls(content) {
if (!Array.isArray(content)) return [];
return content
.filter(p => p.type === 'tool_use')
.map(p => ({
id: p.id,
name: p.name,
input: p.input || {},
category: categorizeToolCall(p.name),
}));
}
function toolCallSummary(name, input) {
switch (name) {
case 'Read': return input.file_path ? input.file_path.split('/').slice(-2).join('/') : '';
case 'Grep': return input.pattern ? `"${input.pattern}"` : '';
case 'Glob': return input.pattern || '';
case 'Bash': return (input.command || '').slice(0, 80);
case 'Edit': return input.file_path ? input.file_path.split('/').slice(-2).join('/') : '';
case 'Write': return input.file_path ? input.file_path.split('/').slice(-2).join('/') : '';
case 'Agent': return input.description || (input.prompt || '').slice(0, 60);
default: return '';
}
}
function categorizeToolCall(name) {
if (['Read', 'Grep', 'Glob'].includes(name)) return 'file-read';
if (['Edit', 'Write', 'NotebookEdit'].includes(name)) return 'file-write';
if (name === 'Bash') return 'command';
if (name === 'Agent') return 'agent';
if (['WebFetch', 'WebSearch'].includes(name)) return 'web';
if (['AskUserQuestion'].includes(name)) return 'interaction';
return 'other';
}
// ── Generate HTML ────────────────────────────────────────────────────────────
function truncateDeep(obj, maxStrLen = 500, depth = 0) {
if (depth > 10) return '[nested]';
if (obj === null || obj === undefined) return obj;
if (typeof obj === 'string') {
return obj.length > maxStrLen ? obj.slice(0, maxStrLen) + `... [${obj.length} chars total]` : obj;
}
if (Array.isArray(obj)) {
return obj.map(item => truncateDeep(item, maxStrLen, depth + 1));
}
if (typeof obj === 'object') {
const result = {};
for (const [k, v] of Object.entries(obj)) {
result[k] = truncateDeep(v, maxStrLen, depth + 1);
}
return result;
}
return obj;
}
function buildRawEntries(entries) {
return entries.map((e, index) => {
const req = truncateDeep(e.request, 500);
const resp = { ...e.response };
// Remove body_raw (SSE stream data, very large)
if (resp.body_raw) {
resp._body_raw_length = resp.body_raw.length;
delete resp.body_raw;
}
const respTrunc = truncateDeep(resp, 500);
return { index, request: req, response: respTrunc, logged_at: e.logged_at };
});
}
function generateHTML(rawCalls, conversations, rawEntries, inputFile) {
const data = { rawCalls, conversations, rawEntries, inputFile, generatedAt: new Date().toISOString() };
const dataJSON = JSON.stringify(data);
const encodedData = Buffer.from(dataJSON).toString('base64');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Claude Session Report — ${path.basename(inputFile)}</title>
<style>
${getCSS()}
</style>
</head>
<body>
<div id="app"></div>
<script>
${getJS()}
// Load data (UTF-8 safe base64 decode)
const bytes = Uint8Array.from(atob('${encodedData}'), c => c.charCodeAt(0));
const raw = new TextDecoder().decode(bytes);
const data = JSON.parse(raw);
renderApp(data);
</script>
</body>
</html>`;
}
function getCSS() {
return `
:root {
--bg: #1e1e1e;
--bg-card: #252526;
--bg-hover: #2d2d30;
--bg-active: #37373d;
--border: #3e3e42;
--text: #cccccc;
--text-muted: #808080;
--text-bright: #e0e0e0;
--accent: #569cd6;
--accent2: #4ec9b0;
--green: #6a9955;
--orange: #ce9178;
--red: #f44747;
--yellow: #dcdcaa;
--purple: #c586c0;
--blue: #9cdcfe;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: var(--bg);
color: var(--text);
font-family: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', 'Consolas', monospace;
font-size: 13px;
line-height: 1.6;
}
.container { max-width: 960px; margin: 0 auto; padding: 16px; }
/* Header */
.header {
border-bottom: 1px solid var(--border);
padding-bottom: 12px;
margin-bottom: 16px;
}
.header h1 { color: var(--accent); font-size: 16px; font-weight: 600; }
.header .meta { color: var(--text-muted); font-size: 12px; margin-top: 4px; }
.header .meta span { margin-right: 16px; }
/* Tabs */
.tabs {
display: flex;
gap: 0;
border-bottom: 1px solid var(--border);
margin-bottom: 16px;
}
.tab {
padding: 8px 20px;
cursor: pointer;
color: var(--text-muted);
border-bottom: 2px solid transparent;
transition: all 0.15s;
user-select: none;
}
.tab:hover { color: var(--text); }
.tab.active { color: var(--accent); border-bottom-color: var(--accent); }
.tab-content { display: none; }
.tab-content.active { display: block; }
/* Conversations */
.conversation {
border: 1px solid var(--border);
margin-bottom: 12px;
}
.conv-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 14px;
background: var(--bg-card);
cursor: pointer;
user-select: none;
}
.conv-header:hover { background: var(--bg-hover); }
.conv-header .title { color: var(--accent2); font-weight: 600; }
.conv-header .badge {
display: inline-block;
padding: 1px 6px;
font-size: 11px;
border-radius: 3px;
margin-left: 8px;
}
.badge-opus { background: rgba(86,156,214,0.2); color: var(--accent); }
.badge-haiku { background: rgba(78,201,176,0.2); color: var(--accent2); }
.badge-sonnet { background: rgba(197,134,192,0.2); color: var(--purple); }
.conv-meta { color: var(--text-muted); font-size: 11px; }
.conv-body { display: none; padding: 0; }
.conv-body.open { display: block; }
/* Turns */
.turn {
border-top: 1px solid var(--border);
padding: 12px 14px;
}
.turn-label {
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
margin-bottom: 6px;
}
.turn-label.user { color: var(--green); }
.turn-label.assistant { color: var(--accent); }
.turn-text {
white-space: pre-wrap;
word-break: break-word;
color: var(--text-bright);
}
.turn-text.muted { color: var(--text-muted); }
/* Tool calls */
.tool-call {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 4px 0;
color: var(--text);
}
.tool-icon {
flex-shrink: 0;
width: 18px;
text-align: center;
color: var(--text-muted);
}
.tool-name { color: var(--yellow); font-weight: 600; }
.tool-desc { color: var(--text-muted); margin-left: 4px; }
.tool-category-file-read .tool-name { color: var(--blue); }
.tool-category-file-write .tool-name { color: var(--orange); }
.tool-category-command .tool-name { color: var(--accent2); }
.tool-category-agent .tool-name { color: var(--purple); }
/* Collapsible */
.collapsible-toggle {
cursor: pointer;
color: var(--text-muted);
font-size: 12px;
user-select: none;
padding: 4px 0;
}
.collapsible-toggle:hover { color: var(--text); }
.collapsible-content { display: none; }
.collapsible-content.open { display: block; }
/* Tool result */
.tool-result {
margin: 4px 0 4px 26px;
padding: 6px 10px;
background: var(--bg);
border-left: 2px solid var(--border);
font-size: 12px;
max-height: 200px;
overflow-y: auto;
white-space: pre-wrap;
word-break: break-all;
color: var(--text-muted);
}
.tool-result.error { border-left-color: var(--red); color: var(--red); }
/* Thinking */
.thinking-block {
margin: 4px 0;
padding: 6px 10px;
background: rgba(86,156,214,0.05);
border-left: 2px solid var(--accent);
font-size: 12px;
max-height: 150px;
overflow-y: auto;
white-space: pre-wrap;
color: var(--text-muted);
font-style: italic;
}
/* Sub-agent link */
.agent-link {
color: var(--purple);
cursor: pointer;
text-decoration: underline;
}
.agent-link:hover { color: var(--text-bright); }
/* Raw calls table */
.raw-table { width: 100%; border-collapse: collapse; }
.raw-table th {
text-align: left;
padding: 6px 10px;
border-bottom: 2px solid var(--border);
color: var(--text-muted);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
position: sticky;
top: 0;
background: var(--bg);
}
.raw-table td {
padding: 6px 10px;
border-bottom: 1px solid var(--border);
font-size: 12px;
vertical-align: top;
}
.raw-table tr { cursor: pointer; }
.raw-table tr:hover td { background: var(--bg-hover); }
.raw-table .num { text-align: right; font-variant-numeric: tabular-nums; }
.cache-high { color: var(--green); font-weight: 600; }
.cache-mid { color: var(--yellow); }
.cache-low { color: var(--red); }
.raw-detail {
display: none;
padding: 10px 14px;
background: var(--bg-card);
border-bottom: 1px solid var(--border);
}
.raw-detail.open { display: table-row; }
.raw-detail td { padding: 10px 14px; }
/* Markdown-like rendering */
.md-content h1, .md-content h2, .md-content h3 { color: var(--accent); margin: 12px 0 6px; }
.md-content h1 { font-size: 16px; }
.md-content h2 { font-size: 14px; }
.md-content h3 { font-size: 13px; }
.md-content code {
background: var(--bg);
padding: 1px 4px;
border-radius: 3px;
font-size: 12px;
}
.md-content pre {
background: var(--bg);
padding: 10px;
border-radius: 4px;
overflow-x: auto;
margin: 8px 0;
}
.md-content pre code { padding: 0; background: none; }
.md-content ul, .md-content ol { padding-left: 20px; margin: 4px 0; }
.md-content li { margin: 2px 0; }
.md-content table { border-collapse: collapse; margin: 8px 0; }
.md-content th, .md-content td {
border: 1px solid var(--border);
padding: 4px 8px;
font-size: 12px;
}
.md-content th { background: var(--bg-hover); color: var(--accent); }
.md-content strong { color: var(--text-bright); }
.md-content hr { border: none; border-top: 1px solid var(--border); margin: 12px 0; }
.md-content blockquote {
border-left: 3px solid var(--accent);
padding-left: 12px;
color: var(--text-muted);
margin: 8px 0;
}
/* Simulator */
.sim-controls {
display: flex; align-items: center; gap: 10px; padding: 10px 0;
border-bottom: 1px solid var(--border); margin-bottom: 12px; flex-wrap: wrap;
}
.sim-btn {
padding: 5px 14px; background: var(--bg-card); border: 1px solid var(--border);
color: var(--text); cursor: pointer; font-family: inherit; font-size: 12px;
}
.sim-btn:hover { background: var(--bg-hover); border-color: var(--accent); }
.sim-btn:disabled { opacity: 0.3; cursor: default; }
.sim-btn.primary { background: rgba(86,156,214,0.2); border-color: var(--accent); color: var(--accent); }
.sim-btn.playing { background: rgba(244,71,71,0.2); border-color: var(--red); color: var(--red); }
.sim-select {
padding: 5px 8px; background: var(--bg-card); border: 1px solid var(--border);
color: var(--text); font-family: inherit; font-size: 12px; max-width: 400px;
}
.sim-step-label { color: var(--text-muted); font-size: 12px; font-variant-numeric: tabular-nums; }
/* Flowchart */
.flow-canvas {
position: relative; padding: 16px 0;
}
.flow-svg {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
pointer-events: none; z-index: 0;
}
.flow-svg line { stroke: var(--border); stroke-width: 1.5; }
.flow-svg polygon { fill: var(--text-muted); }
.flow-svg path { stroke: var(--border); stroke-width: 1.5; fill: none; }
.flow-nodes {
position: relative; z-index: 1;
display: flex; flex-wrap: wrap; gap: 8px 0; align-items: flex-start;
}
.flow-row {
display: flex; align-items: center; width: 100%; gap: 0;
padding: 4px 0;
}
.flow-row.reverse { flex-direction: row-reverse; }
.flow-group {
display: flex; flex-direction: column; align-items: center; gap: 4px;
flex-shrink: 0;
}
.flow-arrow {
flex-shrink: 0; width: 32px; display: flex; align-items: center; justify-content: center;
color: var(--text-muted); font-size: 16px; opacity: 0.15; transition: opacity 0.3s;
}
.flow-arrow.visible { opacity: 0.6; }
.flow-node {
border: 1px solid var(--border); padding: 6px 10px; font-size: 11px;
max-width: 200px; min-width: 80px; cursor: pointer;
opacity: 0.15; transition: all 0.3s; position: relative;
background: var(--bg-card);
}
.flow-node.visible { opacity: 1; }
.flow-node.current { opacity: 1; box-shadow: 0 0 0 2px var(--accent), 0 0 12px rgba(86,156,214,0.3); }
.flow-node .flow-icon { font-size: 13px; margin-right: 4px; }
.flow-node .flow-label {
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block;
}
.flow-node .flow-detail {
display: none; white-space: pre-wrap; font-size: 10px; color: var(--text-muted);
margin-top: 4px; max-height: 120px; overflow-y: auto; word-break: break-all;
}
.flow-node.expanded .flow-label { white-space: pre-wrap; }
.flow-node.expanded .flow-detail { display: block; }
.flow-node.expanded { max-width: 400px; }
.flow-node .flow-meta {
font-size: 10px; color: var(--text-muted); margin-top: 2px;
}
/* Node type styles */
.flow-node.node-request { border-left: 3px solid var(--green); border-radius: 8px; }
.flow-node.node-response { border-left: 3px solid var(--accent); border-radius: 8px; }
.flow-node.node-thinking { border-left: 3px solid var(--purple); border-radius: 12px; font-style: italic; background: rgba(197,134,192,0.05); }
.flow-node.node-tool-call { border-left: 3px solid var(--yellow); }
.flow-node.node-agent-call { border-left: 3px solid var(--purple); border-width: 2px; }
.flow-node.node-tool-result { border-left: 3px solid var(--yellow); border-style: dashed; }
.flow-node.node-agent-result { border-left: 3px solid var(--purple); border-style: dashed; }
/* Context meter */