Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1917 lines (1697 loc) · 67.2 KB
/
Copy pathapp.js
File metadata and controls
1917 lines (1697 loc) · 67.2 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
/**
* Session Renderer – app.js
*
* Plays back a Copilot CLI .jsonl session file inside an xterm.js terminal,
* with per-event-type styling and playback controls.
*/
/* ================================================================
ANSI helpers
================================================================ */
const ESC = '\x1b[';
const RESET = `${ESC}0m`;
const ansi = {
bold: s => `${ESC}1m${s}${RESET}`,
dim: s => `${ESC}2m${s}${RESET}`,
italic: s => `${ESC}3m${s}${RESET}`,
underline: s => `${ESC}4m${s}${RESET}`,
fg: {
black: s => `${ESC}30m${s}${RESET}`,
red: s => `${ESC}31m${s}${RESET}`,
green: s => `${ESC}32m${s}${RESET}`,
yellow: s => `${ESC}33m${s}${RESET}`,
blue: s => `${ESC}34m${s}${RESET}`,
magenta: s => `${ESC}35m${s}${RESET}`,
cyan: s => `${ESC}36m${s}${RESET}`,
white: s => `${ESC}37m${s}${RESET}`,
brightRed: s => `${ESC}91m${s}${RESET}`,
brightGreen: s => `${ESC}92m${s}${RESET}`,
brightYellow: s => `${ESC}93m${s}${RESET}`,
brightBlue: s => `${ESC}94m${s}${RESET}`,
brightMagenta: s => `${ESC}95m${s}${RESET}`,
brightCyan: s => `${ESC}96m${s}${RESET}`,
brightWhite: s => `${ESC}97m${s}${RESET}`,
gray: s => `${ESC}90m${s}${RESET}`,
},
bg: {
black: s => `${ESC}40m${s}${RESET}`,
red: s => `${ESC}41m${s}${RESET}`,
green: s => `${ESC}42m${s}${RESET}`,
yellow: s => `${ESC}43m${s}${RESET}`,
blue: s => `${ESC}44m${s}${RESET}`,
magenta: s => `${ESC}45m${s}${RESET}`,
},
};
/* ================================================================
Event categories — used for filtering
================================================================ */
const EVENT_CATEGORIES = {
'tool.execution_start': 'tools',
'tool.execution_complete': 'tools',
'tool.user_requested': 'tools',
'session.info': 'system',
'session.compaction_start': 'system',
'session.compaction_complete': 'system',
'session.model_change': 'system',
'session.resume': 'system',
};
/* ================================================================
Playback timing — base delays per event type (ms)
================================================================ */
const BASE_DELAYS = {
'user.message': 1200,
'assistant.message': 800,
'assistant.turn_start': 400,
'assistant.turn_end': 300,
'tool.execution_start': 200,
'tool.execution_complete': 200,
'session.start': 1500,
'session.info': 300,
'session.error': 800,
'session.model_change': 600,
'session.resume': 800,
'session.compaction_start': 300,
'session.compaction_complete': 500,
'subagent.started': 600,
'subagent.completed': 400,
'tool.user_requested': 400,
};
/* ================================================================
Tool-specific renderers for tool.execution_start
Each returns styled string lines or null to skip.
================================================================ */
const TOOL_START_RENDERERS = {
/* ── Shell commands ─────────────────────────────────────────── */
'powershell': (args) => {
const cmd = args.command || '';
const desc = args.description || '';
const lines = [];
lines.push(ansi.bold(ansi.fg.brightYellow(' $ ')) + ansi.fg.brightWhite(truncate(cmd, 120)));
if (desc) lines.push(ansi.dim(ansi.fg.gray(` # ${desc}`)));
return lines.join('\r\n');
},
'read_powershell': (args) => {
return ansi.dim(ansi.fg.yellow(` ◂ reading shell output…`));
},
'write_powershell': (args) => {
const input = args.input || '';
return ansi.fg.yellow(` ▸ shell input: `) + ansi.fg.brightWhite(truncate(input, 80));
},
'stop_powershell': (args) => {
return ansi.dim(ansi.fg.yellow(` ■ stopping shell`));
},
'list_powershell': (_args) => {
return ansi.dim(ansi.fg.yellow(` ◆ listing shell sessions`));
},
/* ── File operations ────────────────────────────────────────── */
'view': (args) => {
const path = args.path || '';
const range = args.view_range ? ` [${args.view_range.join('-')}]` : '';
return ansi.fg.cyan(` 👁 view `) + ansi.fg.brightCyan(shortenPath(path)) + ansi.dim(ansi.fg.cyan(range));
},
'edit': (args) => {
const path = args.path || '';
const hasNew = !!args.new_str;
const hasOld = !!args.old_str;
const label = hasNew && hasOld ? 'replace in' : hasNew ? 'insert into' : 'edit';
return ansi.fg.brightGreen(` ✏ ${label} `) + ansi.fg.brightGreen(shortenPath(path));
},
'create': (args) => {
const path = args.path || '';
return ansi.fg.brightGreen(` + create `) + ansi.fg.brightGreen(shortenPath(path));
},
/* ── Search tools ───────────────────────────────────────────── */
'grep': (args) => {
const pattern = args.pattern || '';
const path = args.path ? shortenPath(args.path) : '.';
const glob = args.glob ? ` (${args.glob})` : '';
return ansi.fg.yellow(` 🔍 grep `) + ansi.fg.brightWhite(`/${pattern}/`) +
ansi.dim(ansi.fg.yellow(` in ${path}${glob}`));
},
'rg': (args) => {
const pattern = args.pattern || args.query || '';
const path = args.path ? shortenPath(args.path) : '.';
return ansi.fg.yellow(` 🔍 rg `) + ansi.fg.brightWhite(`/${pattern}/`) +
ansi.dim(ansi.fg.yellow(` in ${path}`));
},
'glob': (args) => {
const pattern = args.pattern || '';
const path = args.path ? shortenPath(args.path) : '.';
return ansi.fg.yellow(` 📂 glob `) + ansi.fg.brightWhite(pattern) +
ansi.dim(ansi.fg.yellow(` in ${path}`));
},
/* ── Sub-agent invocation ───────────────────────────────────── */
'task': (args) => {
const agentType = args.agent_type || 'unknown';
const desc = args.description || '';
const model = args.model || '';
const mode = args.mode === 'background' ? ' (background)' : '';
const lines = [];
lines.push(
ansi.bold(ansi.fg.brightMagenta(` 🤖 agent:${agentType}`)) +
(model ? ansi.dim(ansi.fg.magenta(` [${model}]`)) : '') +
ansi.dim(ansi.fg.magenta(mode))
);
if (desc) lines.push(ansi.fg.magenta(` ${desc}`));
return lines.join('\r\n');
},
'read_agent': (args) => {
const wait = args.wait ? ' (waiting)' : '';
return ansi.dim(ansi.fg.magenta(` ◂ reading agent result${wait}`));
},
/* ── Web tools ──────────────────────────────────────────────── */
'web_fetch': (args) => {
const url = args.url || '';
return ansi.fg.blue(` 🌐 fetch `) + ansi.underline(ansi.fg.brightBlue(truncate(url, 100)));
},
'web_search': (args) => {
const query = args.query || '';
return ansi.fg.blue(` 🔎 search `) + ansi.fg.brightWhite(`"${truncate(query, 90)}"`);
},
/* ── SQL ────────────────────────────────────────────────────── */
'sql': (args) => {
const desc = args.description || '';
const query = args.query || '';
const preview = truncate(query, 80);
const lines = [];
lines.push(ansi.fg.cyan(` 🗄 sql`) + (desc ? ansi.dim(ansi.fg.cyan(` — ${desc}`)) : ''));
if (preview) lines.push(ansi.dim(ansi.fg.gray(` ${preview}`)));
return lines.join('\r\n');
},
/* ── User interaction ───────────────────────────────────────── */
'ask_user': (args) => {
const question = truncate(args.question || '', 120);
return ansi.fg.brightCyan(` 💬 ask_user: `) + ansi.fg.white(question);
},
/* ── Completion ─────────────────────────────────────────────── */
'task_complete': (args) => {
const summary = truncate(args.summary || '', 120);
return ansi.bold(ansi.fg.brightGreen(` 🏁 task_complete`)) +
(summary ? '\r\n' + ansi.fg.green(` ${summary}`) : '');
},
/* ── Intent (already handled but listed for completeness) ──── */
'report_intent': (args) => {
const intent = args.intent;
if (intent) return ansi.fg.brightMagenta(` 🎯 Intent: ${intent}`);
return null;
},
'update_todo': (args) => {
return ansi.dim(ansi.fg.gray(` ☑ update_todo`));
},
};
/* ── Tool-specific renderers for tool.execution_complete ──────── */
const TOOL_COMPLETE_RENDERERS = {
// View: suppress completion entirely (start already shows the path)
'view': (_d) => null,
// Shell: show output preview (potentially interesting)
'powershell': (d) => {
if (d.success) {
const preview = truncate(d.result?.content || '', 200);
if (!preview) return ansi.dim(ansi.fg.green(' ✔ (exit 0)'));
return ansi.fg.green(` ✔ `) + ansi.dim(ansi.fg.white(preview));
}
const err = truncate(d.result?.content || 'failed', 200);
return ansi.fg.brightRed(` ✖ ${err}`);
},
// Edit: just show confirmation
'edit': (d) => {
if (d.success) {
const msg = truncate(d.result?.content || 'updated', 120);
return ansi.fg.green(` ✔ ${msg}`);
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'failed', 120)}`);
},
// Create: show confirmation
'create': (d) => {
if (d.success) {
const msg = truncate(d.result?.content || 'created', 120);
return ansi.fg.green(` ✔ ${msg}`);
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'failed', 120)}`);
},
// Task (agent): show brief result
'task': (d) => {
if (d.success) {
const preview = truncate(d.result?.content || '', 150);
if (!preview) return ansi.fg.magenta(' ✔ agent completed');
return ansi.fg.magenta(' ✔ agent completed: ') + ansi.dim(ansi.fg.white(preview));
}
return ansi.fg.brightRed(` ✖ agent failed: ${truncate(d.result?.content || 'error', 120)}`);
},
// Read agent: show brief result
'read_agent': (d) => {
if (d.success) {
const preview = truncate(d.result?.content || '', 150);
if (!preview) return ansi.dim(ansi.fg.magenta(' ✔ agent result received'));
return ansi.fg.magenta(' ✔ ') + ansi.dim(ansi.fg.white(preview));
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'failed', 120)}`);
},
// Grep/glob: show file list or count
'grep': (d) => {
if (d.success) {
const content = d.result?.content || '';
const lineCount = content.split('\n').filter(l => l.trim()).length;
if (lineCount > 3) {
const first3 = content.split('\n').filter(l => l.trim()).slice(0, 3).map(l => shortenPath(l.trim()));
return ansi.fg.green(` ✔ ${lineCount} results: `) + ansi.dim(ansi.fg.white(first3.join(', ') + '…'));
}
return ansi.fg.green(` ✔ ${truncate(content, 150)}`);
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'no matches', 120)}`);
},
'rg': (d) => TOOL_COMPLETE_RENDERERS['grep'](d),
'glob': (d) => {
if (d.success) {
const content = d.result?.content || '';
const files = content.split('\n').filter(l => l.trim());
if (files.length > 3) {
return ansi.fg.green(` ✔ ${files.length} files found`);
}
return ansi.fg.green(` ✔ ${files.map(f => shortenPath(f.trim())).join(', ') || '(none)'}`);
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'failed', 120)}`);
},
// Web: show brief preview
'web_fetch': (d) => {
if (d.success) {
const preview = truncate(d.result?.content || '', 120);
return ansi.fg.blue(` ✔ `) + ansi.dim(ansi.fg.white(preview || '(fetched)'));
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'fetch failed', 120)}`);
},
'web_search': (d) => {
if (d.success) {
const preview = truncate(d.result?.content || '', 120);
return ansi.fg.blue(` ✔ `) + ansi.dim(ansi.fg.white(preview || '(results)'));
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'search failed', 120)}`);
},
// SQL: brief confirmation
'sql': (d) => {
if (d.success) {
const preview = truncate(d.result?.content || 'ok', 120);
return ansi.fg.cyan(` ✔ ${preview}`);
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'query failed', 120)}`);
},
// Ask user: show selected answer
'ask_user': (d) => {
if (d.success) {
const answer = truncate(d.result?.content || '', 120);
return ansi.fg.brightCyan(` ↩ ${answer}`);
}
return ansi.fg.brightRed(` ✖ (no response)`);
},
// Quiet tools
'report_intent': (_d) => null,
'update_todo': (d) => d.success ? ansi.dim(ansi.fg.gray(' ✔ todos updated')) : null,
'read_powershell': (d) => {
if (d.success) {
const preview = truncate(d.result?.content || '', 150);
if (!preview) return ansi.dim(ansi.fg.yellow(' ✔ (no output)'));
return ansi.fg.green(` ✔ `) + ansi.dim(ansi.fg.white(preview));
}
return ansi.fg.brightRed(` ✖ ${truncate(d.result?.content || 'failed', 120)}`);
},
'stop_powershell': (d) => d.success ? ansi.dim(ansi.fg.yellow(' ✔ shell stopped')) : null,
'list_powershell': (d) => {
const preview = truncate(d.result?.content || '', 120);
return ansi.dim(ansi.fg.yellow(` ✔ ${preview || '(no sessions)'}`));
},
'task_complete': (d) => {
if (d.success) return ansi.bold(ansi.fg.brightGreen(' ✔ Task marked complete'));
return null;
},
};
/* ── Path shortening helper ───────────────────────────────────── */
function shortenPath(p) {
if (!p) return '';
// Show last 2-3 path segments for readability
const sep = p.includes('/') ? '/' : '\\';
const parts = p.split(sep).filter(Boolean);
if (parts.length <= 3) return p;
return '…' + sep + parts.slice(-3).join(sep);
}
/* ================================================================
Style map – one entry per event type.
Each value is a function: (event, filters) => string | null.
Customise colours/formatting here.
================================================================ */
const STYLE_MAP = {
/* ── Session lifecycle ──────────────────────────────────────── */
'session.start': (ev) => {
const d = ev.data;
const ctx = d.context || {};
const lines = [
'',
ansi.bold(ansi.fg.brightBlue('╔══════════════════════════════════════════════════════════╗')),
ansi.bold(ansi.fg.brightBlue('║')) + ansi.bold(ansi.fg.brightWhite(' SESSION START')) + ansi.bold(ansi.fg.brightBlue(' ║')),
ansi.bold(ansi.fg.brightBlue('╚══════════════════════════════════════════════════════════╝')),
ansi.fg.blue(` Session : ${d.sessionId || '?'}`),
ansi.fg.blue(` Agent : ${d.producer || '?'} v${d.copilotVersion || '?'}`),
ansi.fg.blue(` Time : ${d.startTime || ev.timestamp}`),
];
if (ctx.cwd) lines.push(ansi.fg.blue(` CWD : ${ctx.cwd}`));
if (ctx.branch) lines.push(ansi.fg.blue(` Branch : ${ctx.branch}`));
lines.push('');
return lines.join('\r\n');
},
'session.resume': (ev) => {
const d = ev.data;
const ctx = d.context || {};
return [
'',
ansi.fg.blue(`⟳ Session resumed at ${d.resumeTime || ev.timestamp} (${d.eventCount || '?'} events)`),
ctx.branch ? ansi.fg.blue(` Branch: ${ctx.branch}`) : '',
'',
].filter(Boolean).join('\r\n');
},
'session.info': (ev) => {
const d = ev.data;
return ansi.dim(ansi.fg.blue(`ℹ [${d.infoType || 'info'}] ${d.message}`));
},
'session.model_change': (ev) => {
return ansi.fg.magenta(`🔄 Model changed → ${ansi.bold(ev.data.newModel)}`);
},
'session.error': (ev) => {
return ansi.fg.brightRed(`✖ ERROR [${ev.data.errorType || 'unknown'}]: ${ev.data.message}`);
},
'session.compaction_start': (_ev) => {
return ansi.dim(ansi.fg.yellow('⏳ Context compaction started…'));
},
'session.compaction_complete': (ev) => {
const d = ev.data;
if (d.success) {
return ansi.dim(ansi.fg.yellow(
`✓ Compaction complete — ${d.preCompactionTokens?.toLocaleString() || '?'} tokens, ` +
`${d.preCompactionMessagesLength || '?'} messages → checkpoint #${d.checkpointNumber ?? '?'}`
));
}
return ansi.fg.brightRed('✖ Compaction failed');
},
/* ── User messages ──────────────────────────────────────────── */
'user.message': (ev) => {
const text = ev.data.content || '';
const wrapped = wordWrap(text, 100);
const lines = [
'',
ansi.bold(ansi.fg.brightCyan('❯ USER')),
...wrapped.map(l => ansi.fg.brightCyan(` ${l}`)),
'',
];
return lines.join('\r\n');
},
/* ── Assistant messages ─────────────────────────────────────── */
'assistant.turn_start': (ev) => {
return [
'',
ansi.dim(ansi.fg.gray(`── turn ${ev.data.turnId} ${'─'.repeat(50)}`)),
].join('\r\n');
},
'assistant.turn_end': (_ev) => {
return ansi.dim(ansi.fg.gray('─'.repeat(64)));
},
'assistant.message': (ev, filters) => {
const d = ev.data;
const parts = [];
// Reasoning (thinking) — respect filter
if (d.reasoningText && filters.reasoning) {
parts.push('');
parts.push(ansi.italic(ansi.fg.blue('💭 Thinking…')));
const rLines = wordWrap(d.reasoningText, 100);
for (const l of rLines) {
parts.push(ansi.italic(ansi.fg.blue(` ${l}`)));
}
}
// Main content
const content = (d.content || '').trim();
if (content) {
parts.push('');
parts.push(ansi.bold(ansi.fg.brightWhite('🤖 ASSISTANT')));
const cLines = formatContent(content, 100);
for (const l of cLines) {
// Table lines from formatContent already contain ANSI escapes
if (l.includes('\x1b[')) {
parts.push(` ${l}`);
} else {
parts.push(ansi.fg.white(` ${l}`));
}
}
}
// Tool requests — use specialized renderers
if (d.toolRequests && d.toolRequests.length > 0) {
const meaningful = d.toolRequests.filter(t => t.name !== 'report_intent');
if (meaningful.length > 0) {
parts.push('');
parts.push(ansi.fg.yellow(` 📎 Tool calls (${meaningful.length}):`));
for (const tr of meaningful) {
const renderer = TOOL_START_RENDERERS[tr.name];
if (renderer) {
const rendered = renderer(tr.arguments || {});
if (rendered) parts.push(rendered);
} else {
const argStr = summariseArgs(tr.arguments);
parts.push(ansi.fg.yellow(` ▸ ${tr.name}`) + ansi.dim(ansi.fg.yellow(argStr ? ` — ${argStr}` : '')));
}
}
}
}
if (parts.length === 0) return null;
parts.push('');
return parts.join('\r\n');
},
/* ── Tool events ────────────────────────────────────────────── */
'tool.execution_start': (ev) => {
const d = ev.data;
const renderer = TOOL_START_RENDERERS[d.toolName];
if (renderer) {
return renderer(d.arguments || {});
}
// Fallback for unknown tools
const argStr = summariseArgs(d.arguments);
return ansi.fg.yellow(` ⚙ ${d.toolName}`) + (argStr ? ansi.dim(ansi.fg.yellow(` — ${argStr}`)) : '');
},
'tool.execution_complete': (ev) => {
const d = ev.data;
// Look up tool name from correlation map
const toolName = _toolCallIdMap[d.toolCallId];
if (toolName) {
const renderer = TOOL_COMPLETE_RENDERERS[toolName];
if (renderer) {
const result = renderer(d);
if (result !== null && result !== undefined) return result;
return null; // explicitly suppressed
}
}
// Fallback
if (d.success) {
const preview = truncate(d.result?.content || '', 200);
if (!preview) return ansi.fg.green(' ✔ (done)');
return ansi.fg.green(` ✔ ${preview}`);
}
const errMsg = truncate(d.result?.content || d.error || 'failed', 200);
return ansi.fg.brightRed(` ✖ ${errMsg}`);
},
'tool.user_requested': (ev) => {
const d = ev.data;
// Skip local_shell — user typing in their own terminal
if (d.toolName === 'local_shell') return null;
const renderer = TOOL_START_RENDERERS[d.toolName];
if (renderer) {
return ansi.italic(ansi.fg.yellow(' 👤 User-requested: ')) + '\r\n' + renderer(d.arguments || {});
}
const argStr = summariseArgs(d.arguments);
return ansi.italic(ansi.fg.yellow(` 👤 User-requested tool: ${d.toolName}${argStr ? ' — ' + argStr : ''}`));
},
/* ── Sub-agents ─────────────────────────────────────────────── */
'subagent.started': (ev) => {
const d = ev.data;
return [
'',
ansi.bold(ansi.fg.brightMagenta(` 🤖 Sub-agent started: ${d.agentDisplayName || d.agentName}`)),
d.agentDescription ? ansi.dim(ansi.fg.magenta(` ${truncate(d.agentDescription.trim(), 120)}`)) : '',
].filter(Boolean).join('\r\n');
},
'subagent.completed': (ev) => {
const d = ev.data;
return ansi.fg.magenta(` ✔ Sub-agent completed: ${d.agentDisplayName || d.agentName}`);
},
};
/* ================================================================
Utility helpers
================================================================ */
function truncate(s, max) {
if (!s) return '';
const oneLine = s.replace(/[\r\n]+/g, ' ').trim();
if (oneLine.length <= max) return oneLine;
return oneLine.slice(0, max - 1) + '…';
}
function summariseArgs(args) {
if (!args) return '';
const keys = ['path', 'command', 'description', 'pattern', 'query', 'intent', 'url', 'prompt'];
for (const k of keys) {
if (args[k]) return truncate(String(args[k]), 80);
}
for (const [, v] of Object.entries(args)) {
if (typeof v === 'string' && v.length > 0) return truncate(v, 80);
}
return '';
}
function wordWrap(text, maxWidth) {
if (maxWidth <= 0) return [text];
const lines = [];
for (const raw of text.split(/\r?\n/)) {
if (raw.length <= maxWidth) {
lines.push(raw);
continue;
}
let remaining = raw;
while (remaining.length > maxWidth) {
let idx = remaining.lastIndexOf(' ', maxWidth);
if (idx <= 0) idx = maxWidth;
lines.push(remaining.slice(0, idx));
remaining = remaining.slice(idx).trimStart();
}
if (remaining) lines.push(remaining);
}
return lines;
}
/* ================================================================
Markdown table → box-drawing table formatter
================================================================ */
/**
* Detect whether a line is a markdown table separator (e.g. |---|---|)
*/
function isTableSeparator(line) {
return /^\|[\s:]*-+[\s:]*(\|[\s:]*-+[\s:]*)*\|?\s*$/.test(line.trim());
}
/**
* Parse cells from a markdown table row. Strips leading/trailing pipes and
* trims each cell.
*/
function parseTableRow(line) {
let s = line.trim();
if (s.startsWith('|')) s = s.slice(1);
if (s.endsWith('|')) s = s.slice(0, -1);
return s.split('|').map(c => c.trim());
}
/**
* Render a parsed markdown table as box-drawing lines with ANSI styling.
* Returns an array of styled strings (one per output line).
*
* ┌────────┬────────────┐
* │ Header │ Header 2 │ ← bold cyan
* ├────────┼────────────┤
* │ cell │ cell 2 │ ← white
* └────────┴────────────┘
*/
function renderBoxTable(headerCells, bodyRows, colWidths) {
const result = [];
const pad = 1; // spaces around cell content
// Build horizontal rules
const topLine = '┌' + colWidths.map(w => '─'.repeat(w + pad * 2)).join('┬') + '┐';
const midLine = '├' + colWidths.map(w => '─'.repeat(w + pad * 2)).join('┼') + '┤';
const bottomLine = '└' + colWidths.map(w => '─'.repeat(w + pad * 2)).join('┴') + '┘';
const renderRow = (cells, styleFn) => {
const parts = cells.map((cell, i) => {
const padded = (cell || '').padEnd(colWidths[i]);
return ' ' + styleFn(padded) + ' ';
});
return ansi.dim('│') + parts.join(ansi.dim('│')) + ansi.dim('│');
};
result.push(ansi.dim(topLine));
result.push(renderRow(headerCells, s => ansi.bold(ansi.fg.brightCyan(s))));
result.push(ansi.dim(midLine));
for (const row of bodyRows) {
result.push(renderRow(row, s => ansi.fg.white(s)));
}
result.push(ansi.dim(bottomLine));
return result;
}
/**
* Process text that may contain markdown tables mixed with regular prose.
* Detects table regions (consecutive lines starting with |), formats them
* as box-drawing tables, and word-wraps everything else.
* Returns an array of styled/plain lines.
*/
function formatContent(text, maxWidth) {
const rawLines = text.split(/\r?\n/);
const output = [];
let i = 0;
while (i < rawLines.length) {
const line = rawLines[i];
// Detect start of a table: line starts with |
if (line.trim().startsWith('|')) {
// Collect all consecutive table lines
const tableLines = [];
while (i < rawLines.length && rawLines[i].trim().startsWith('|')) {
tableLines.push(rawLines[i]);
i++;
}
// Need at least a header + separator + 1 body row to be a real table
// Find the separator row
let sepIdx = -1;
for (let t = 0; t < tableLines.length; t++) {
if (isTableSeparator(tableLines[t])) { sepIdx = t; break; }
}
if (sepIdx >= 1 && tableLines.length > sepIdx + 1) {
// Parse header (rows before separator, typically just one)
const headerCells = parseTableRow(tableLines[sepIdx - 1]);
const bodyRows = [];
for (let t = sepIdx + 1; t < tableLines.length; t++) {
if (isTableSeparator(tableLines[t])) continue; // skip extra separators
bodyRows.push(parseTableRow(tableLines[t]));
}
// Compute column widths
const colCount = Math.max(headerCells.length, ...bodyRows.map(r => r.length));
const colWidths = [];
for (let c = 0; c < colCount; c++) {
let maxW = (headerCells[c] || '').length;
for (const row of bodyRows) {
maxW = Math.max(maxW, (row[c] || '').length);
}
colWidths.push(maxW);
}
// Any lines before the header in the table block (e.g. a preceding | line)
for (let t = 0; t < sepIdx - 1; t++) {
output.push(...wordWrap(tableLines[t], maxWidth));
}
// Render the box table
output.push(...renderBoxTable(headerCells, bodyRows, colWidths));
} else {
// Not a real table, just lines starting with |, pass through
for (const tl of tableLines) {
output.push(...wordWrap(tl, maxWidth));
}
}
} else {
// Regular line — word wrap
output.push(...wordWrap(line, maxWidth));
i++;
}
}
return output;
}
/* ================================================================
JSONL parser — returns array of events, sorted by timestamp
================================================================ */
function parseJSONL(text) {
const events = [];
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
events.push(JSON.parse(trimmed));
} catch (e) {
console.warn('Skipping invalid JSONL line:', e.message);
}
}
events.sort((a, b) => {
if (a.timestamp && b.timestamp) return new Date(a.timestamp) - new Date(b.timestamp);
return 0;
});
return events;
}
/* ================================================================
Tool call ID → tool name correlation map.
Populated during event load so that tool.execution_complete
events can look up which tool they belong to.
================================================================ */
let _toolCallIdMap = {}; // toolCallId → toolName
/* ================================================================
Renderable event filter
================================================================ */
const RENDERABLE_TYPES = new Set([
'session.start', 'session.resume', 'session.info', 'session.error',
'session.model_change', 'user.message', 'assistant.message',
'subagent.started', 'subagent.completed',
'session.compaction_start', 'session.compaction_complete',
'tool.user_requested', 'tool.execution_start', 'tool.execution_complete',
]);
function isRenderable(ev) {
return RENDERABLE_TYPES.has(ev.type);
}
/**
* Check if an event is a sub-agent child event (tool call or assistant
* message running inside a background agent).
*/
function isSubagentChild(ev) {
return !!(ev.data && ev.data.parentToolCallId);
}
/**
* Produce a compact status line for a sub-agent child event, showing
* what the agent is currently doing. Returns null for events that
* should not update the status (e.g. tool completions — we wait for
* the next start or assistant message).
*/
function subagentStatusLine(ev, agentName) {
const d = ev.data;
const prefix = ansi.bold(ansi.fg.magenta(` 🤖 ${agentName}`));
const spinner = ansi.dim(ansi.fg.magenta(' ⟳ '));
if (ev.type === 'tool.execution_start') {
const toolName = d.toolName || 'tool';
const argStr = summariseArgs(d.arguments);
const detail = argStr ? ` — ${truncate(argStr, 60)}` : '';
return prefix + spinner + ansi.fg.yellow(toolName) + ansi.dim(ansi.fg.yellow(detail));
}
if (ev.type === 'assistant.message') {
const msg = truncate(d.content || '', 70);
if (msg) return prefix + spinner + ansi.dim(ansi.fg.white(msg));
return null; // empty assistant message, don't update status
}
// tool.execution_complete — don't update the status line
return null;
}
/* ================================================================
Playback Engine — with snapshots, filtering, batched rendering
================================================================ */
const SNAPSHOT_INTERVAL = 200; // take a snapshot every N renderable events
class PlaybackEngine {
constructor(terminal) {
this.terminal = terminal;
this.events = [];
this.renderableEvents = [];
this.currentIndex = -1;
this.playing = false;
this.speed = 1;
this.timer = null;
this.onUpdate = null;
// Filters: which categories are visible
this.filters = { tools: true, reasoning: true, system: true };
// Snapshot cache for fast seeking: index -> rendered output buffer
this._snapshots = new Map();
// Pre-rendered output cache per event index
this._renderCache = [];
// Index of user.message events for turn navigation
this._userMessageIndices = [];
// Sub-agent collapsing: parentToolCallId → { agentName, indices[] }
this._subagentGroups = {};
// Set of renderable-event indices that are sub-agent children
this._subagentChildIndices = new Set();
// Tracks the last rendered status line per agent group during live playback
this._subagentLastStatus = {};
// Flag for newline management during live playback
this._lastWasSubagentChild = false;
}
load(events) {
this.stop();
this.events = events;
this.renderableEvents = events.filter(isRenderable);
this.currentIndex = -1;
// Build toolCallId → toolName correlation map
_toolCallIdMap = {};
for (const ev of events) {
if (ev.type === 'tool.execution_start' && ev.data.toolCallId) {
_toolCallIdMap[ev.data.toolCallId] = ev.data.toolName;
}
}
this._buildSubagentGroups();
this._buildCaches();
this.terminal.clear();
this.terminal.reset();
this._notify();
}
get total() { return this.renderableEvents.length; }
get position() { return this.currentIndex + 1; }
/* ── Filter management ──────────────────────────────────── */
setFilter(category, enabled) {
if (this.filters[category] === enabled) return;
this.filters[category] = enabled;
this._invalidateRenderCache();
if (this.currentIndex >= 0) {
this._replayUpTo(this.currentIndex);
}
this._notify();
}
toggleFilter(category) {
this.setFilter(category, !this.filters[category]);
}
/* ── Playback controls ──────────────────────────────────── */
play() {
if (this.renderableEvents.length === 0) return;
this.playing = true;
this._notify();
this._scheduleNext();
}
pause() {
this.playing = false;
clearTimeout(this.timer);
this.timer = null;
this._notify();
}
togglePlay() {
if (this.playing) this.pause();
else this.play();
}
stop() {
this.pause();
this.currentIndex = -1;
this._subagentLastStatus = {};
this._lastWasSubagentChild = false;
this.terminal.clear();
this.terminal.reset();
this._notify();
}
next() {
if (this.currentIndex >= this.renderableEvents.length - 1) {
this.pause();
return;
}
this.currentIndex++;
this._renderSingleEvent(this.currentIndex);
this._notify();
if (this.playing) this._scheduleNext();
}
prev() {
if (this.currentIndex <= 0) return;
this.currentIndex--;
this._replayUpTo(this.currentIndex);
this._notify();
}
jumpTo(index) {
if (index < 0 || index >= this.renderableEvents.length) return;
const wasPlaying = this.playing;
if (wasPlaying) this.pause();
this.currentIndex = index;
this._replayUpTo(index);
this._notify();
if (wasPlaying) this.play();
}
nextUserMessage() {
const next = this._userMessageIndices.find(i => i > this.currentIndex);
if (next !== undefined) this.jumpTo(next);
}
prevUserMessage() {
// Find the last user message index before currentIndex
let target = undefined;
for (const i of this._userMessageIndices) {
if (i >= this.currentIndex) break;
target = i;
}
if (target !== undefined) this.jumpTo(target);
}
setSpeed(s) {
this.speed = s;
// Reschedule pending timer with new speed
if (this.playing && this.timer !== null) {
clearTimeout(this.timer);
this._scheduleNext();
}