-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodex-md.py
More file actions
1362 lines (1199 loc) · 59 KB
/
codex-md.py
File metadata and controls
1362 lines (1199 loc) · 59 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 python3
"""
Codex Session Manager & Markdown Converter (v2)
-------------------------------------------------
An interactive tool to browse, filter, and convert OpenAI Codex
session logs (.jsonl) into readable Markdown documents.
Features:
• Browse all Codex sessions with preview
• Interactive per-section filter with line counts
• Toggle sections on/off with arrow keys
• Presets for common export scenarios
• Clean-content mode to strip IDE scaffolding
"""
import os
import sys
import json
import glob
import re
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Optional, Tuple, Set
# Platform-specific terminal handling
_IS_WINDOWS = sys.platform == 'win32'
if not _IS_WINDOWS:
import tty
import termios
# ──────────────────────────────────────────────────────────────
# Terminal Styling
# ──────────────────────────────────────────────────────────────
class Style:
HEADER = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
DIM = '\033[2m'
REVERSE = '\033[7m'
RESET = '\033[0m'
BG_GRAY = '\033[48;5;236m'
@staticmethod
def title(msg): return f"{Style.BOLD}{Style.HEADER}{msg}{Style.RESET}"
@staticmethod
def info(msg): return f"{Style.BLUE}ℹ {msg}{Style.RESET}"
@staticmethod
def success(msg): return f"{Style.GREEN}✔ {msg}{Style.RESET}"
@staticmethod
def error(msg): return f"{Style.RED}✖ {msg}{Style.RESET}"
@staticmethod
def warn(msg): return f"{Style.YELLOW}⚠ {msg}{Style.RESET}"
# ──────────────────────────────────────────────────────────────
# Configuration
# ──────────────────────────────────────────────────────────────
DEFAULT_CODEX_HOME = os.path.expanduser("~/.codex")
ENV_CODEX_HOME = os.environ.get("CODEX_HOME")
CODEX_PATH = Path(ENV_CODEX_HOME) if ENV_CODEX_HOME else Path(DEFAULT_CODEX_HOME)
SESSIONS_DIR = CODEX_PATH / "sessions"
SESSION_INDEX_PATH = CODEX_PATH / "session_index.jsonl"
USER_MESSAGE_BEGIN = "## My request for Codex:"
INTERACTIVE_SESSION_SOURCES = {"cli", "vscode", "atlas", "chatgpt"}
# ──────────────────────────────────────────────────────────────
# Section Definitions (key, display_name, emoji, default_on)
#
# These are ALL the section types discovered across every Codex
# session file. Each maps to one or more JSONL entry patterns.
# ──────────────────────────────────────────────────────────────
# Function name → sub-category mapping
# Built from scanning 223 session files (21 unique function names)
TERMINAL_FUNCS = {'exec_command', 'shell', 'shell_command', 'write_stdin', 'send_input'}
OTHER_TOOL_FUNCS = {'spawn_agent', 'wait_agent', 'close_agent', 'update_plan',
'request_user_input', 'view_image', 'list_mcp_resources',
'read_mcp_resource', 'list_mcp_resource_templates'}
def classify_tool(name: str) -> str:
"""Classify a function_call name into a sub-category key."""
if name in TERMINAL_FUNCS: return 'terminal_cmd'
if name.startswith('mcp__'): return 'mcp_tool'
if name in OTHER_TOOL_FUNCS: return 'other_tool'
return 'terminal_cmd'
SECTION_DEFS = [
('user_message', 'User Messages', '👤', True ),
('agent_message', 'Agent Messages', '🤖', True ),
('agent_reasoning', 'Agent Reasoning', '🧠', False),
('reasoning', 'Internal Reasoning', '🔒', False),
('terminal_cmd', 'Terminal Commands', '💻', True ),
('terminal_output', 'Terminal Outputs', '📤', True ),
('mcp_tool', 'MCP Calls', '🔌', False),
('mcp_tool_output', 'MCP Outputs', '🔗', False),
('custom_tool_call', 'Patches', '🔧', True ),
('custom_tool_output', 'Patch Outputs', '🔨', True ),
('other_tool', 'Other Tools', '🧩', False),
('other_tool_output', 'Other Tool Outputs', '📎', False),
('web_search', 'Web Searches', '🔍', False),
('token_count', 'Token & Rate Limits', '📊', False),
('turn_context', 'Turn Context', '🔄', False),
('task_event', 'Task Events', '📌', False),
('system_message', 'System Messages', '⚙️ ', False),
('git_snapshot', 'Git Snapshots', '📸', False),
('session_event', 'Session Events', '🔔', False),
('session_meta', 'Session Metadata', '📝', True ),
]
ALL_SECTION_KEYS = {s[0] for s in SECTION_DEFS}
TOOL_OUTPUT_MAP = {
'terminal_cmd': 'terminal_output',
'mcp_tool': 'mcp_tool_output',
'other_tool': 'other_tool_output',
}
# ──────────────────────────────────────────────────────────────
# Filter Presets (name, enabled_keys | None=defaults, clean)
# ──────────────────────────────────────────────────────────────
FILTER_PRESETS = [
('Defaults', None, False),
('Chat Only', {'user_message', 'agent_message', 'session_meta'}, False),
('Chat (Clean)', {'user_message', 'agent_message', 'session_meta'}, True),
('Chat + Terminal', {'user_message', 'agent_message', 'terminal_cmd', 'terminal_output',
'custom_tool_call', 'custom_tool_output', 'session_meta'}, False),
('Terminal Only', {'terminal_cmd', 'terminal_output'}, False),
('Outputs Only', {'terminal_output', 'custom_tool_output', 'mcp_tool_output',
'other_tool_output'}, False),
('Full Export', ALL_SECTION_KEYS, False),
]
# ──────────────────────────────────────────────────────────────
# Parsing Utilities (kept from v1)
# ──────────────────────────────────────────────────────────────
def clean_filename(text: str) -> str:
text = re.sub(r'<[^>]+>', '', text)
text = re.sub(r'[*_`]', '', text)
text = re.sub(r'[^\w\s-]', '', text).strip().lower()
text = re.sub(r'[-\s]+', '-', text)
return text[:60] if text else "untitled-session"
def trim_chat_content(content: str) -> str:
content = content.replace('\r\n', '\n').replace('\r', '\n')
content = re.sub(
r'(?is)<([A-Za-z0-9_-]*context[A-Za-z0-9_-]*)>\s*.*?</\1>\s*', '\n', content,
)
content = re.sub(
r'(?is)<subagent_notification>\s*.*?</subagent_notification>\s*', '\n', content,
)
dropped_block_prefixes = (
"## active file:", "## active selection of the file:",
"## open tabs:", "## files mentioned by the user:",
)
dropped_line_prefixes = (
"# context from my ide setup:", "## my request for codex:", "## my request:",
)
cleaned_lines: List[str] = []
lines = content.split('\n')
index = 0
while index < len(lines):
stripped = lines[index].strip()
lowered = stripped.lower()
if any(lowered.startswith(p) for p in dropped_line_prefixes):
index += 1; continue
if any(lowered.startswith(p) for p in dropped_block_prefixes):
active_sel = lowered.startswith("## active selection of the file:")
index += 1
while index < len(lines):
nl = lines[index].strip().lower()
if any(nl.startswith(p) for p in dropped_line_prefixes):
break
if not active_sel and re.match(r'#{1,6}\s', lines[index].strip()):
break
index += 1
continue
cleaned_lines.append(lines[index])
index += 1
cleaned = "\n".join(cleaned_lines)
cleaned = re.sub(r'\n{3,}', '\n\n', cleaned)
return cleaned.strip()
def normalize_title_candidate(text: str) -> str:
text = re.sub(r'\s+', ' ', text.strip())
return text[:80] + ("..." if len(text) > 80 else "")
def strip_user_message_prefix(text: str) -> str:
idx = text.find(USER_MESSAGE_BEGIN)
if idx != -1:
return text[idx + len(USER_MESSAGE_BEGIN):].strip()
return text.strip()
def extract_first_user_line(text: str) -> str:
message = strip_user_message_prefix(text)
if not message:
return ""
for line in message.splitlines():
candidate = line.strip()
if candidate:
return normalize_title_candidate(candidate)
return ""
def is_title_noise(line: str) -> bool:
lowered = line.strip().lower()
if not lowered: return True
if lowered.startswith('<') and lowered.endswith('>'): return True
if "system role:" in lowered: return True
if re.match(r'^\d+\s+\d{4}-\d{2}-\d{2}\s+', lowered): return True
if re.match(r'^[-=]{3,}$', lowered): return True
noise_prefixes = (
"hi chatgpt", "hi claude", "hello chatgpt", "hello claude",
"i've hit my", "i have hit my", "here is the exact context",
"here is the current context", "perfect.", "okay,", "ok,",
"❯", "●", "searched for ", "read ", "listed ", "brought in ",
"update(", "write(", "bash(", "error:", "caused by:",
)
if lowered.startswith(noise_prefixes): return True
noise_headings = (
"system context", "server topology", "the story so far",
"the roadblock", "your mission & execution steps",
"system context & the new strategy", "diagnostics & fixes",
"speedtest results", "live production deployment report",
"codebase cleanup & compatibility report",
)
if lowered.startswith('#'):
heading = lowered.lstrip('#').strip(': ').strip()
return any(heading.startswith(p) for p in noise_headings)
return False
def extract_title_from_content(content: str) -> str:
title = extract_first_user_line(content)
return title or "Empty or Technical Session"
def format_size(num_bytes: int) -> str:
units = ("B", "KB", "MB", "GB", "TB")
size = float(num_bytes)
unit = units[0]
for unit in units:
if size < 1024 or unit == units[-1]:
break
size /= 1024
if unit == "B":
return f"{int(size)}{unit}"
return f"{size:.1f}{unit}"
# ──────────────────────────────────────────────────────────────
# Thread / Session Index
# ──────────────────────────────────────────────────────────────
def load_thread_names() -> Dict[str, str]:
names: Dict[str, str] = {}
if not SESSION_INDEX_PATH.exists():
return names
try:
with open(SESSION_INDEX_PATH, 'r', encoding='utf-8', errors='ignore') as fp:
for line in fp:
line = line.strip()
if not line: continue
try:
entry = json.loads(line)
except json.JSONDecodeError:
continue
tid = entry.get('id')
tname = entry.get('thread_name')
if isinstance(tid, str) and isinstance(tname, str) and tname.strip():
names[tid] = tname.strip()
except Exception:
return {}
return names
THREAD_NAMES = load_thread_names()
# ──────────────────────────────────────────────────────────────
# Session Scanning (fast head-scan for preview list)
# ──────────────────────────────────────────────────────────────
def read_session_summary(filepath: Path, head_limit=10, user_scan_limit=200):
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as fp:
session_meta = None
first_user_message = None
saw_user_event = False
lines_scanned = 0
while lines_scanned < head_limit or (
session_meta is not None and not saw_user_event
and lines_scanned < head_limit + user_scan_limit
):
line = fp.readline()
if not line: break
trimmed = line.strip()
if not trimmed: continue
lines_scanned += 1
try:
entry = json.loads(trimmed)
except json.JSONDecodeError:
continue
if entry.get('type') == 'session_meta' and session_meta is None:
session_meta = entry.get('payload', {})
continue
if (entry.get('type') == 'event_msg'
and entry.get('payload', {}).get('type') == 'user_message'):
saw_user_event = True
if first_user_message is None:
message = strip_user_message_prefix(entry['payload'].get('message', ''))
if message:
first_user_message = message
if session_meta is not None:
break
return session_meta, first_user_message, saw_user_event
except Exception:
return None, None, False
def is_interactive_session_meta(meta: Optional[Dict]) -> bool:
if not meta: return False
source = meta.get('source')
if not isinstance(source, str): return False
return source.lower() in INTERACTIVE_SESSION_SOURCES
def get_session_preview_title(filepath: Path) -> str:
meta, first_user_message, saw_user_event = read_session_summary(filepath)
if not is_interactive_session_meta(meta) or not saw_user_event:
return "Untitled / System Log"
thread_id = meta.get('id') if isinstance(meta.get('id'), str) else None
if thread_id and thread_id in THREAD_NAMES:
return normalize_title_candidate(THREAD_NAMES[thread_id])
if not first_user_message:
return "[Image]"
title = extract_first_user_line(first_user_message)
return title or "Untitled / System Log"
# ──────────────────────────────────────────────────────────────
# Session Parser (full parse of a .jsonl file)
# ──────────────────────────────────────────────────────────────
class SessionParser:
def __init__(self, filepath: Path):
self.filepath = filepath
self.data: List[Dict] = []
self.metadata: Dict = {}
self.title = "Untitled Session"
self.start_time = None
self._load()
# --- loading ---
def _load(self):
if not self.filepath.exists():
return
with open(self.filepath, 'r', encoding='utf-8', errors='replace') as f:
for line_num, line in enumerate(f):
line = line.strip()
if not line: continue
try:
entry = json.loads(line)
self._process_entry(entry, line_num)
except json.JSONDecodeError:
continue
# Derive title
thread_id = self.metadata.get('id')
title_found = False
if isinstance(thread_id, str) and thread_id in THREAD_NAMES:
self.title = normalize_title_candidate(THREAD_NAMES[thread_id])
title_found = True
else:
for item in self.data:
if item['type'] == 'user_message':
t = extract_title_from_content(item['content'])
if t != "Empty or Technical Session":
self.title = t
title_found = True
break
if not title_found and self.metadata.get('id'):
self.title = f"System Session {self.metadata['id'][:8]}"
# --- entry processing (ALL 23 discovered patterns) ---
def _process_entry(self, entry: Dict, line_num: int):
ts = entry.get('timestamp')
if line_num == 0 and not self.start_time:
self.start_time = ts
etype = entry.get('type', '')
payload = entry.get('payload', {})
if not isinstance(payload, dict):
payload = {}
ptype = payload.get('type', '')
role = payload.get('role', '')
# 1 ─ Session metadata
if etype == 'session_meta':
self.metadata = payload
return
# 2 ─ User message (event_msg wrapper)
if etype == 'event_msg' and ptype == 'user_message':
msg = payload.get('message', '')
if msg:
self.data.append({'type': 'user_message', 'timestamp': ts, 'content': msg})
return
# 3 ─ Agent reasoning (event_msg wrapper)
if etype == 'event_msg' and ptype == 'agent_reasoning':
text = payload.get('text', '')
if text:
self.data.append({'type': 'agent_reasoning', 'timestamp': ts, 'content': text})
return
# 4 ─ Agent message (event_msg wrapper)
if etype == 'event_msg' and ptype == 'agent_message':
msg = payload.get('message', '')
if msg:
self.data.append({'type': 'agent_message', 'timestamp': ts, 'content': msg})
return
# 5 ─ Token count & rate limits
if etype == 'event_msg' and ptype == 'token_count':
rl = payload.get('rate_limits', {})
parts = []
if isinstance(rl, dict):
pri = rl.get('primary', {})
sec = rl.get('secondary', {})
if pri:
parts.append(f"primary {pri.get('used_percent', '?')}%")
if sec:
parts.append(f"secondary {sec.get('used_percent', '?')}%")
info = payload.get('info')
if info and isinstance(info, dict):
parts.append(f"in={info.get('input_tokens', '?')}, out={info.get('output_tokens', '?')}")
content = ', '.join(parts) if parts else 'token count event'
self.data.append({
'type': 'token_count', 'timestamp': ts,
'content': content,
})
return
# 6 ─ Task lifecycle
if etype == 'event_msg' and ptype in ('task_started', 'task_complete'):
detail = ''
if ptype == 'task_started':
model = payload.get('collaboration_mode_kind', '')
ctx = payload.get('model_context_window', '')
if model or ctx:
detail = f" ({model}, ctx={ctx:,})" if ctx else f" ({model})"
self.data.append({
'type': 'task_event', 'timestamp': ts,
'event': ptype,
'content': ptype.replace('_', ' ').title() + detail,
})
return
# 7 ─ Context compacted / thread rolled back / turn aborted / item completed
if etype == 'event_msg' and ptype in ('context_compacted', 'thread_rolled_back', 'turn_aborted', 'item_completed'):
detail = ''
if ptype == 'thread_rolled_back':
detail = f" ({payload.get('num_turns', '?')} turns)"
elif ptype == 'turn_aborted':
detail = f" (reason: {payload.get('reason', '?')})"
elif ptype == 'item_completed':
idata = payload.get('item', {})
detail = f" ({idata.get('type', '?')})"
self.data.append({
'type': 'session_event', 'timestamp': ts,
'event': ptype,
'content': ptype.replace('_', ' ').title() + detail,
})
return
# 8 ─ Compacted top-level entry
if etype == 'compacted':
self.data.append({
'type': 'session_event', 'timestamp': ts,
'event': 'context_compacted',
'content': 'Context Compacted',
})
return
# 9 ─ Turn context
if etype == 'turn_context':
model = payload.get('model', '?')
effort = payload.get('effort', '?')
cwd = payload.get('cwd', '?')
self.data.append({
'type': 'turn_context', 'timestamp': ts,
'content': f"model={model}, effort={effort}, cwd={cwd}",
})
return
# 10 ─ response_item entries
if etype == 'response_item':
# 10a ─ Internal reasoning (usually encrypted, summary may be empty)
if ptype == 'reasoning':
parts = payload.get('summary', [])
summary = '\n'.join(p.get('text', '') for p in parts if p.get('text', ''))
encrypted = bool(payload.get('encrypted_content'))
self.data.append({
'type': 'reasoning', 'timestamp': ts,
'content': summary,
'encrypted': encrypted,
})
return
# 10b ─ Function call (classified by function name)
if ptype == 'function_call':
fname = payload.get('name', '')
cat = classify_tool(fname)
call_id = payload.get('call_id')
self.data.append({
'type': cat, 'timestamp': ts,
'name': fname,
'arguments': payload.get('arguments', ''),
'call_id': call_id,
'_tool_cat': cat, # save category for output matching
})
# Remember call_id → category for output pairing
if not hasattr(self, '_call_id_map'):
self._call_id_map = {}
if call_id:
self._call_id_map[call_id] = cat
return
# 10c ─ Function call output (matched to its call's category)
if ptype == 'function_call_output':
call_id = payload.get('call_id')
if not hasattr(self, '_call_id_map'):
self._call_id_map = {}
parent_cat = self._call_id_map.get(call_id, 'terminal_cmd')
out_cat = TOOL_OUTPUT_MAP.get(parent_cat, 'terminal_output')
self.data.append({
'type': out_cat, 'timestamp': ts,
'output': payload.get('output', ''),
'call_id': call_id,
})
return
# 10d ─ Custom tool call (apply_patch, etc.)
if ptype == 'custom_tool_call':
self.data.append({
'type': 'custom_tool_call', 'timestamp': ts,
'name': payload.get('name', 'custom_tool'),
'content': payload.get('input', ''),
'call_id': payload.get('call_id'),
})
return
# 10e ─ Custom tool output
if ptype == 'custom_tool_call_output':
self.data.append({
'type': 'custom_tool_output', 'timestamp': ts,
'content': payload.get('output', ''),
'call_id': payload.get('call_id'),
})
return
# 10f ─ Web search
if ptype == 'web_search_call':
self.data.append({
'type': 'web_search', 'timestamp': ts,
'content': 'Web search executed',
})
return
# 10g ─ Ghost snapshot (git)
if ptype == 'ghost_snapshot':
gc = payload.get('ghost_commit', {})
cid = gc.get('id', '?')[:12]
self.data.append({
'type': 'git_snapshot', 'timestamp': ts,
'content': f"commit {cid}",
'commit': gc,
})
return
# 10h ─ Developer / system messages
if ptype == 'message' and role == 'developer':
parts = payload.get('content', [])
if isinstance(parts, list):
text = '\n'.join(p.get('text', '') for p in parts if p.get('type') == 'input_text')
else:
text = str(parts)
if text:
self.data.append({'type': 'system_message', 'timestamp': ts, 'content': text})
return
# 10i ─ response_item message (assistant / user raw) — skip, covered by event_msg
if ptype == 'message' and role in ('assistant', 'user'):
return
# Everything else is silently ignored.
# --- line counting per section ---
def count_lines_by_section(self) -> Dict[str, int]:
"""Estimate markdown output lines for each section type."""
counts: Dict[str, int] = {}
# Tool-call sub-categories (ones that have 'arguments')
tool_call_types = {'terminal_cmd', 'mcp_tool', 'other_tool'}
tool_output_types = {'terminal_output', 'mcp_tool_output', 'other_tool_output'}
for item in self.data:
itype = item['type']
content = item.get('content', '')
if itype == 'user_message':
lines = content.count('\n') + 4
elif itype == 'agent_message':
lines = content.count('\n') + 4
elif itype == 'agent_reasoning':
lines = 2
elif itype == 'reasoning':
lines = 2 if not content else content.count('\n') + 3
elif itype in tool_call_types:
args = item.get('arguments', '')
try:
args = json.dumps(json.loads(args), indent=2)
except Exception:
pass
lines = args.count('\n') + 5
elif itype in tool_output_types:
out = item.get('output', '')
lines = out.count('\n') + 5 if out.strip() else 0
elif itype == 'custom_tool_call':
lines = content.count('\n') + 5
elif itype == 'custom_tool_output':
lines = content.count('\n') + 5 if content.strip() else 0
elif itype in ('web_search', 'token_count', 'turn_context',
'task_event', 'git_snapshot', 'session_event'):
lines = 2
elif itype == 'system_message':
lines = content.count('\n') + 5
else:
lines = 1
counts[itype] = counts.get(itype, 0) + lines
# Session metadata block
counts['session_meta'] = 5 if self.metadata else 0
return counts
# --- markdown rendering with filter ---
def to_markdown(self, section_filter: Optional[Dict[str, bool]] = None,
clean_content: bool = False, output_cap: int = 0, user_cap: int = 0, agent_cap: int = 0, reasoning_cap: int = 0, internal_cap: int = 0) -> str:
if section_filter is None:
section_filter = {s[0]: True for s in SECTION_DEFS}
def _cap_text(text: str) -> str:
"""Truncate output text to output_cap lines (last N lines)."""
if output_cap <= 0 or not text:
return text
lines = text.split('\n')
if len(lines) <= output_cap:
return text
kept = lines[-output_cap:]
return f'... ({len(lines) - output_cap} lines trimmed) ...\n' + '\n'.join(kept)
keep_indices = set(range(len(self.data)))
counts = {'user_message': 0, 'agent_message': 0, 'agent_reasoning': 0, 'reasoning': 0}
for i in range(len(self.data) - 1, -1, -1):
itype = self.data[i]['type']
if itype == 'user_message' and user_cap > 0:
if counts['user_message'] >= user_cap: keep_indices.remove(i)
counts['user_message'] += 1
elif itype == 'agent_message' and agent_cap > 0:
if counts['agent_message'] >= agent_cap: keep_indices.remove(i)
counts['agent_message'] += 1
elif itype == 'agent_reasoning' and reasoning_cap > 0:
if counts['agent_reasoning'] >= reasoning_cap: keep_indices.remove(i)
counts['agent_reasoning'] += 1
elif itype == 'reasoning' and internal_cap > 0:
if counts['reasoning'] >= internal_cap: keep_indices.remove(i)
counts['reasoning'] += 1
md: List[str] = []
md.append(f"# {self.title}\n")
last_rendered_message = None
# Session metadata
if section_filter.get('session_meta', False) and self.metadata:
md.append("```yaml")
md.append(f"Source: {self.filepath.name}")
if self.start_time:
md.append(f"Date: {self.start_time}")
if self.metadata.get('cwd'):
md.append(f"CWD: {self.metadata['cwd']}")
md.append("```\n")
for i, item in enumerate(self.data):
if i not in keep_indices: continue
itype = item['type']
if not section_filter.get(itype, False):
continue
content = item.get('content', '')
if itype == 'user_message':
if clean_content:
content = trim_chat_content(content)
if not content: continue
mk = ('user', content)
if mk == last_rendered_message: continue
last_rendered_message = mk
md.append(f"## 👤 User\n\n{content}\n")
elif itype == 'agent_message':
if clean_content:
content = trim_chat_content(content)
if not content: continue
mk = ('agent', content)
if mk == last_rendered_message: continue
last_rendered_message = mk
md.append(f"## 🤖 Agent\n\n{content}\n")
elif itype == 'agent_reasoning':
clean = content.replace('**', '').strip()
md.append(f"> 🧠 **Reasoning:** {clean}\n")
elif itype == 'reasoning':
if content:
md.append(f"> 🔒 **Internal Reasoning:**\n> {content}\n")
else:
md.append("> 🔒 *Internal reasoning (encrypted)*\n")
elif itype in ('terminal_cmd', 'mcp_tool', 'other_tool'):
name = item.get('name', 'tool')
args = item.get('arguments', '')
try:
args = json.dumps(json.loads(args), indent=2)
lang = "json"
except Exception:
lang = "text"
emoji_map = {'terminal_cmd': '💻', 'mcp_tool': '🔌', 'other_tool': '🧩'}
em = emoji_map.get(itype, '🛠️')
md.append(f"### {em} Tool: `{name}`\n\n```{lang}\n{args}\n```\n")
elif itype in ('terminal_output', 'mcp_tool_output', 'other_tool_output'):
out = _cap_text(item.get('output', ''))
if out.strip():
md.append(f"**Output:**\n\n```text\n{out}\n```\n")
elif itype == 'custom_tool_call':
name = item.get('name', 'custom_tool')
md.append(f"### 🔧 Custom Tool: `{name}`\n\n```text\n{content}\n```\n")
elif itype == 'custom_tool_output':
out = _cap_text(content)
if out.strip():
md.append(f"**Custom Tool Output:**\n\n```text\n{out}\n```\n")
elif itype == 'web_search':
md.append(f"> 🔍 **Web Search**\n")
elif itype == 'token_count':
md.append(f"> 📊 **Tokens:** {content}\n")
elif itype == 'turn_context':
md.append(f"> 🔄 **Turn:** {content}\n")
elif itype == 'task_event':
md.append(f"> 📌 **{content}**\n")
elif itype == 'system_message':
# Truncate very long system prompts
display = content[:800]
if len(content) > 800:
display += f"\n... ({len(content) - 800} chars truncated)"
md.append(f"### ⚙️ System Message\n\n```text\n{display}\n```\n")
elif itype == 'git_snapshot':
md.append(f"> 📸 **Git Snapshot:** {content}\n")
elif itype == 'session_event':
md.append(f"> 🔔 **{content}**\n")
return "\n".join(md)
# ──────────────────────────────────────────────────────────────
# Keyboard Input (raw terminal, single keypress)
# ──────────────────────────────────────────────────────────────
def _clear_screen():
"""Cross-platform screen clear."""
os.system('cls' if _IS_WINDOWS else 'clear')
def read_key() -> str:
"""Read a single keypress cross-platform."""
if _IS_WINDOWS:
import msvcrt
ch = msvcrt.getwch()
if ch in ('\r', '\n'):
return 'ENTER'
if ch == ' ':
return 'SPACE'
if ch == '\x03':
raise KeyboardInterrupt
if ch == '\xe0' or ch == '\x00': # special key prefix on Windows
ext = msvcrt.getwch()
return {'H': 'UP', 'P': 'DOWN', 'M': 'RIGHT', 'K': 'LEFT'}.get(ext, '')
return ch.upper()
else:
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
if ch == '\x1b':
ch2 = sys.stdin.read(1)
if ch2 == '[':
ch3 = sys.stdin.read(1)
return {'A': 'UP', 'B': 'DOWN', 'C': 'RIGHT', 'D': 'LEFT'}.get(ch3, '')
return 'ESC'
if ch in ('\r', '\n'):
return 'ENTER'
if ch == ' ':
return 'SPACE'
if ch == '\x03':
raise KeyboardInterrupt
return ch.upper()
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
# ──────────────────────────────────────────────────────────────
# Interactive Section Filter
# ──────────────────────────────────────────────────────────────
# Output sections whose blocks can be capped
OUTPUT_SECTIONS = {'terminal_output', 'mcp_tool_output', 'other_tool_output', 'custom_tool_output'}
# Cap steps for ◀ ▶ control (0 = no cap, show all)
CAP_STEPS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 50, 100, 200, 500]
MSG_CAP_STEPS = [0, 5] + list(range(10, 101, 10)) + [150, 200, 300, 500]
def interactive_filter(parsers: List[SessionParser]) -> Tuple[Dict[str, bool], bool, int, int, int, int]:
"""
Full-screen interactive filter.
Returns (section_filter, clean_content, output_cap, user_cap, agent_cap, reasoning_cap, internal_cap).
"""
_line_cache = {}
def get_lines_for_state(cap_out: int, cap_user: int, cap_agent: int, cap_reason: int, cap_internal: int, cc: bool):
cache_key = (cap_out, cap_user, cap_agent, cap_reason, cap_internal, cc)
if cache_key in _line_cache:
return _line_cache[cache_key]
counts = {s[0]: 0 for s in SECTION_DEFS}
msg_counts: Dict[str, int] = {} # actual block/message counts for chat types
tool_call_types = {'terminal_cmd', 'mcp_tool', 'other_tool'}
tool_output_types = {'terminal_output', 'mcp_tool_output', 'other_tool_output'}
for parser in parsers:
keep_indices = set(range(len(parser.data)))
chat_counts = {'u': 0, 'a': 0, 'r': 0, 'i': 0}
for i in range(len(parser.data) - 1, -1, -1):
itype = parser.data[i]['type']
if itype == 'user_message' and cap_user > 0:
if chat_counts['u'] >= cap_user: keep_indices.remove(i)
chat_counts['u'] += 1
elif itype == 'agent_message' and cap_agent > 0:
if chat_counts['a'] >= cap_agent: keep_indices.remove(i)
chat_counts['a'] += 1
elif itype == 'agent_reasoning' and cap_reason > 0:
if chat_counts['r'] >= cap_reason: keep_indices.remove(i)
chat_counts['r'] += 1
elif itype == 'reasoning' and cap_internal > 0:
if chat_counts['i'] >= cap_internal: keep_indices.remove(i)
chat_counts['i'] += 1
for i, item in enumerate(parser.data):
if i not in keep_indices: continue
itype = item['type']
content = item.get('content', '')
# Count actual messages for chat-type sections
if itype in ('user_message', 'agent_message', 'agent_reasoning', 'reasoning'):
msg_counts[itype] = msg_counts.get(itype, 0) + 1
if itype == 'user_message':
if cc: content = trim_chat_content(content)
lines = content.count('\n') + 4 if content else 0
elif itype == 'agent_message':
if cc: content = trim_chat_content(content)
lines = content.count('\n') + 4 if content else 0
elif itype in ('agent_reasoning', 'reasoning'):
lines = 2 if not content else content.count('\n') + 3
elif itype in tool_call_types:
args = item.get('arguments', '')
lines = args.count('\n') + 5
elif itype in tool_output_types:
out = item.get('output', '')
total_out = out.count('\n') + 1 if out.strip() else 0
if cap_out > 0: lines = min(total_out, cap_out) + 4 if total_out > 0 else 0
else: lines = total_out + 4 if total_out > 0 else 0
elif itype == 'custom_tool_call':
lines = content.count('\n') + 5
elif itype == 'custom_tool_output':
total_out = content.count('\n') + 1 if content.strip() else 0
if cap_out > 0: lines = min(total_out, cap_out) + 4 if total_out > 0 else 0
else: lines = total_out + 4 if total_out > 0 else 0
elif itype in ('web_search', 'token_count', 'turn_context', 'task_event', 'git_snapshot', 'session_event'):
lines = 2
elif itype == 'system_message':
lines = content.count('\n') + 5
else:
lines = 1
counts[itype] = counts.get(itype, 0) + lines
if parser.metadata:
counts['session_meta'] = counts.get('session_meta', 0) + 5
_line_cache[cache_key] = (counts, msg_counts)
return counts, msg_counts
fstate: Dict[str, bool] = {s[0]: s[3] for s in SECTION_DEFS}
clean_content = False
output_cap = 8
cap_idx = CAP_STEPS.index(8)
user_cap = 0
u_idx = 0
agent_cap = 0
a_idx = 0
reason_cap = 0
r_idx = 0
internal_cap = 0
i_idx = 0
cursor = 0
ROW_CLEAN = len(SECTION_DEFS)
ROW_CAP = len(SECTION_DEFS) + 1
ROW_USER = len(SECTION_DEFS) + 2
ROW_AGENT = len(SECTION_DEFS) + 3
ROW_REASON= len(SECTION_DEFS) + 4
ROW_INTERNAL = len(SECTION_DEFS) + 5
num_items = len(SECTION_DEFS) + 6
while True:
agg_lines, agg_msgs = get_lines_for_state(output_cap, user_cap, agent_cap, reason_cap, internal_cap, clean_content)
total_lines = sum(agg_lines.get(s[0], 0) for s in SECTION_DEFS)
selected_lines = sum(agg_lines.get(s[0], 0) for s in SECTION_DEFS if fstate.get(s[0], False))
pct = (selected_lines / total_lines * 100) if total_lines > 0 else 0
# ── Render ──
_clear_screen()
sessions_label = f"{len(parsers)} session{'s' if len(parsers) > 1 else ''}"
print(f"\n {Style.BOLD}{Style.HEADER}SECTION FILTER{Style.RESET} {Style.DIM}({sessions_label}){Style.RESET}")
print(f" {Style.DIM}{'━' * 62}{Style.RESET}\n")
for i, (key, name, emoji, _default) in enumerate(SECTION_DEFS):
is_cursor = (i == cursor)
is_on = fstate.get(key, False)
lines = agg_lines.get(key, 0)
arrow = f'{Style.BOLD}{Style.YELLOW}▸{Style.RESET}' if is_cursor else ' '
toggle = f'{Style.GREEN}██{Style.RESET}' if is_on else f'{Style.DIM}░░{Style.RESET}'
if is_cursor and is_on: nstyle = f'{Style.BOLD}{Style.GREEN}'
elif is_cursor and not is_on: nstyle = f'{Style.BOLD}{Style.RED}'
elif is_on: nstyle = ''
else: nstyle = Style.DIM
_MSG_COUNT_TYPES = {'user_message', 'agent_message', 'agent_reasoning', 'reasoning'}
msg_n = agg_msgs.get(key, 0)
if key in _MSG_COUNT_TYPES and msg_n > 0:
msg_label = f' {Style.DIM}({msg_n:,} Msg){Style.RESET}'
else:
msg_label = ''
count_str = f'{Style.CYAN}{lines:>6,}{Style.RESET}' if is_on and lines > 0 else f'{Style.DIM}{lines:>6,}{Style.RESET}'
if lines == 0: count_str = f'{Style.DIM} 0{Style.RESET}'
visible_name = f'{emoji} {name}'
pad_len = max(1, 44 - len(visible_name))
dots = f'{Style.DIM}{"·" * pad_len}{Style.RESET}'
print(f' {arrow} {toggle} {nstyle}{visible_name}{Style.RESET} {dots} {count_str}{msg_label}')
print(f' {Style.DIM}{"─" * 62}{Style.RESET}')
# Clean Chat
cc_on = clean_content
cc_cur = (cursor == ROW_CLEAN)
cc_arrow = f'{Style.BOLD}{Style.YELLOW}▸{Style.RESET}' if cc_cur else ' '
cc_tog = f'{Style.GREEN}██{Style.RESET}' if cc_on else f'{Style.DIM}░░{Style.RESET}'
cc_st = f'{Style.BOLD}' if cc_cur else Style.DIM
cc_val = f'{Style.GREEN}ON {Style.RESET}' if cc_on else f'{Style.DIM}OFF{Style.RESET}'
chat_lines = agg_lines.get('user_message', 0) + agg_lines.get('agent_message', 0)
print(f' {cc_arrow} {cc_tog} {cc_st}✂️ Clean Chat{Style.RESET} {Style.DIM}(strips IDE context from 👤🤖){Style.RESET} {Style.DIM}{chat_lines:,}L{Style.RESET} {cc_val}')
# Output Cap
cap_cur = (cursor == ROW_CAP)
cap_arrow = f'{Style.BOLD}{Style.YELLOW}▸{Style.RESET}' if cap_cur else ' '
cap_st = f'{Style.BOLD}' if cap_cur else Style.DIM
cap_label = f'{Style.DIM}ALL{Style.RESET}' if output_cap == 0 else f'{Style.YELLOW}{output_cap}{Style.RESET}'
hint = f' {Style.DIM}◀▶{Style.RESET}' if cap_cur else ''
print(f' {cap_arrow} {cap_st}💻 Terminal Output Cap{Style.RESET} {Style.DIM}(max lines/block){Style.RESET} {cap_label}{hint}')