-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExport-CodexThread.py
More file actions
2237 lines (1873 loc) · 81.7 KB
/
Export-CodexThread.py
File metadata and controls
2237 lines (1873 loc) · 81.7 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
from __future__ import annotations
import argparse
import base64
import ctypes
import hashlib
import json
import os
import re
import sqlite3
import subprocess
import sys
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any
try:
from zoneinfo import ZoneInfo
except Exception: # pragma: no cover
ZoneInfo = None
__version__ = "0.1.0"
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_OUT_DIR = Path(os.environ.get("CODEX_THREAD_EXPORT_DIR") or (SCRIPT_DIR / "codex-thread-exports"))
LOCAL_TZ_ENV = "CODEX_EXPORT_TZ"
SECRET_PATTERNS = [
(re.compile(r"sk-[A-Za-z0-9_\-]{20,}"), "[REDACTED_OPENAI_KEY]"),
(re.compile(r"github_pat_[A-Za-z0-9_]{20,}"), "[REDACTED_GITHUB_PAT]"),
(re.compile(r"gh[pousr]_[A-Za-z0-9_]{20,}"), "[REDACTED_GITHUB_TOKEN]"),
(re.compile(r"(?i)(bearer\s+)[A-Za-z0-9._\-]{20,}"), r"\1[REDACTED_TOKEN]"),
(re.compile(r"(?i)(password|passwd|token|secret|api[_-]?key)(\s*[:=]\s*)([^\s'\";]+)"), r"\1\2[REDACTED]"),
(re.compile(r"(?i)(cloudflare[_-]?tunnel[_-]?token)(\s*[:=]\s*)([^\s'\";]+)"), r"\1\2[REDACTED]"),
]
DATA_URI_PATTERN = re.compile(
r"data:(?P<mime>image|audio|video|application|font)/[A-Za-z0-9.+_-]+;base64,(?P<data>[A-Za-z0-9+/=\r\n_-]{512,})",
re.IGNORECASE,
)
MARKDOWN_DATA_IMAGE_PATTERN = re.compile(
r"!\[(?P<alt>[^\]]*)\]\(\s*data:image/[A-Za-z0-9.+_-]+;base64,[A-Za-z0-9+/=\r\n_-]{512,}\s*\)",
re.IGNORECASE,
)
HTML_DATA_SRC_PATTERN = re.compile(
r"""(?P<prefix>\bsrc\s*=\s*["'])data:(?P<mime>image|audio|video|application|font)/[A-Za-z0-9.+_-]+;base64,[A-Za-z0-9+/=\r\n_-]{512,}(?P<suffix>["'])""",
re.IGNORECASE,
)
BASE64_BLOB_PATTERN = re.compile(
r"(?<![A-Za-z0-9+/=_-])(?:[A-Za-z0-9+/]{2048,}={0,2}|[A-Za-z0-9_-]{2048,}={0,2})(?![A-Za-z0-9+/=_-])"
)
HEX_BLOB_PATTERN = re.compile(r"(?<![A-Fa-f0-9])(?:[A-Fa-f0-9]{4096,})(?![A-Fa-f0-9])")
OSC_PATTERN = re.compile(r"\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)")
ANSI_PATTERN = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
CONTROL_PATTERN = re.compile(r"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]")
IMAGEISH_TYPES = {
"image",
"input_image",
"output_image",
"screenshot",
"computer_screenshot",
"image_url",
"file_image",
}
MESSAGE_TYPES = {"message", "user_message", "assistant_message", "agent_message", "system_message"}
ACTION_HINTS = (
"tool",
"function",
"shell",
"command",
"exec",
"apply_patch",
"patch",
"edit",
"write_stdin",
"call",
"local_shell",
"browser",
)
NOISY_TYPE_HINTS = (
"token_count",
"turn_context",
"session_meta",
"reasoning",
"delta",
"rate_limits",
)
@dataclass
class Record:
kind: str # message | action | note
role: str # user | assistant | tool | system
text: str
timestamp: str = ""
source_type: str = ""
seq: int = 0
command_key: str = ""
output_key: str = ""
def cp437_cp1252_mojibake_repair(text: str) -> str:
"""Repair already-corrupted clip.exe-style mojibake such as IÆll -> I’ll."""
if not any(ch in text for ch in "ÆæôöâäÖÜ"):
return text
out: list[str] = []
for ch in text:
code = ord(ch)
if 0x80 <= code <= 0xFF:
try:
out.append(bytes([code]).decode("cp1252"))
continue
except UnicodeDecodeError:
pass
out.append(ch)
return "".join(out)
def redact(text: str, enabled: bool) -> str:
if not enabled:
return text
for pattern, replacement in SECRET_PATTERNS:
text = pattern.sub(replacement, text)
return text
def bytes_from_base64_len(chars: int) -> int:
return int(chars * 3 / 4)
def summarize_blob(label: str, raw: str, extra: str = "") -> str:
chars = len(raw)
approx = bytes_from_base64_len(chars) if "base64" in label.lower() else chars
digest = hashlib.sha256(raw[:2_000_000].encode("utf-8", errors="ignore")).hexdigest()[:16]
suffix = f"; {extra}" if extra else ""
return f"[{label} omitted: {chars:,} characters, ~{approx:,} bytes, sha256-prefix={digest}{suffix}]"
def strip_hogs(
text: str,
*,
enabled: bool = True,
max_line_chars: int = 20_000,
max_repeated_lines: int = 25,
) -> str:
if not enabled or not text:
return text or ""
# Remove OSC/title-control sequences before stripping ESC/BEL. Otherwise
# Windows/Next terminal title updates can leave visible residues such as
# ``0;npm0;npm run dev`` in exported output.
text = OSC_PATTERN.sub("", text)
text = ANSI_PATTERN.sub("", text)
text = CONTROL_PATTERN.sub("", text)
text = re.sub(r"(?m)^0;[^\n]*(?:\n|$)", "", text)
def repl_markdown_img(match: re.Match[str]) -> str:
alt = match.group("alt") or "image"
return f""
def repl_html_src(match: re.Match[str]) -> str:
return f"{match.group('prefix')}[base64 {match.group('mime')} omitted]{match.group('suffix')}"
def repl_data_uri(match: re.Match[str]) -> str:
return summarize_blob(f"data:{match.group('mime')} base64 payload", match.group("data"))
def repl_base64(match: re.Match[str]) -> str:
blob = re.sub(r"\s+", "", match.group(0))
try:
padded = blob + ("=" * ((4 - len(blob) % 4) % 4))
base64.b64decode(padded, validate=False)
except Exception:
return match.group(0)
return summarize_blob("base64 blob", blob)
text = MARKDOWN_DATA_IMAGE_PATTERN.sub(repl_markdown_img, text)
text = HTML_DATA_SRC_PATTERN.sub(repl_html_src, text)
text = DATA_URI_PATTERN.sub(repl_data_uri, text)
text = BASE64_BLOB_PATTERN.sub(repl_base64, text)
text = HEX_BLOB_PATTERN.sub(lambda m: summarize_blob("hex blob", m.group(0)), text)
lines = text.splitlines()
compacted: list[str] = []
prev: str | None = None
repeat_count = 0
for line in lines:
if len(line) > max_line_chars:
digest = hashlib.sha256(line.encode("utf-8", errors="ignore")).hexdigest()[:16]
head = line[:1200].rstrip()
tail = line[-1200:].lstrip()
line = f"{head}\n[single overlong line truncated: {len(line):,} characters, sha256-prefix={digest}]\n{tail}"
if line == prev:
repeat_count += 1
if repeat_count == max_repeated_lines + 1:
compacted.append(f"[repeated identical line omitted after {max_repeated_lines:,} repeats]")
elif repeat_count > max_repeated_lines:
continue
else:
compacted.append(line)
else:
prev = line
repeat_count = 1
compacted.append(line)
return "\n".join(compacted).strip()
def safe_slug(text: str, max_len: int = 80) -> str:
text = text.strip().lower()
text = re.sub(r"[^\w\s.-]+", "", text, flags=re.UNICODE)
text = re.sub(r"\s+", "_", text)
text = re.sub(r"_+", "_", text).strip("._- ")
return (text or "codex_thread")[:max_len].strip("._- ")
def _abbrev_tz(name: str) -> str:
"""Compress full Windows tz names like ``Pacific Daylight Time`` to ``PDT``.
Already-short forms like ``PDT`` and ``UTC+02:00`` pass through. Used to
keep filenames safe across platforms (Windows ``%Z`` returns the full
locale name; Linux/macOS return the abbreviation).
"""
s = (name or "").strip()
if not s:
return ""
if " " in s:
words = [w for w in re.split(r"\s+", s) if w]
# Map "Pacific Daylight Time" -> "PDT"; otherwise keep the joined words.
if len(words) >= 2 and all(w[0].isalpha() for w in words):
return "".join(w[0] for w in words).upper()
return "".join(words)
return s
def export_stamp() -> str:
"""Render the timestamp suffix used in output filenames.
Resolution order:
1. ``CODEX_EXPORT_TZ`` env var (any IANA tz, e.g. ``America/Los_Angeles``)
2. The system local timezone
3. Naive local time (last resort)
Format is preserved across versions: ``WED_04292026_060940_PM-PDT``.
"""
tz_name = os.environ.get(LOCAL_TZ_ENV, "").strip()
now: datetime
if ZoneInfo and tz_name:
try:
now = datetime.now(ZoneInfo(tz_name))
except Exception:
now = datetime.now().astimezone()
else:
try:
now = datetime.now().astimezone()
except Exception:
now = datetime.now()
head = now.strftime("%a_%m%d%Y_%I%M%S_%p").upper()
tz = _abbrev_tz(now.strftime("%Z"))
return f"{head}-{tz}" if tz else head
# Back-compat alias for callers that still import the old name.
pacific_stamp = export_stamp
def codex_home() -> Path:
return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
def session_roots() -> list[Path]:
home = codex_home()
return [p for p in (home / "sessions", home / "archived_sessions") if p.exists()]
SESSION_ID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.IGNORECASE)
def all_session_files() -> list[Path]:
out: list[Path] = []
for root in session_roots():
out.extend(root.rglob("*.jsonl"))
return out
def parse_session_id_from_name(path: Path) -> str:
m = SESSION_ID_RE.search(path.name)
return m.group(0) if m else ""
def latest_session_file() -> Path:
candidates = all_session_files()
if not candidates:
raise FileNotFoundError(f"No Codex session JSONL files found under {codex_home()}")
return max(candidates, key=lambda p: p.stat().st_mtime)
def find_session_file(session_id: str) -> Path:
roots = session_roots()
if not roots:
raise FileNotFoundError(f"No Codex session roots found under {codex_home()}")
candidates: list[Path] = []
for root in roots:
candidates.extend(root.rglob(f"*{session_id}*.jsonl"))
if not candidates:
needle = session_id.encode("utf-8")
for root in roots:
for path in root.rglob("*.jsonl"):
try:
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
if needle in chunk:
candidates.append(path)
break
except OSError:
continue
if not candidates:
raise FileNotFoundError(f"No local Codex JSONL transcript found for session: {session_id}")
return max(candidates, key=lambda p: p.stat().st_mtime)
def maybe_json(value: Any) -> Any:
if not isinstance(value, str):
return None
s = value.strip()
if not ((s.startswith("{") and s.endswith("}")) or (s.startswith("[") and s.endswith("]"))):
return None
try:
return json.loads(s)
except Exception:
return None
def as_string(value: Any) -> str:
if value is None:
return ""
if isinstance(value, str):
return value
if isinstance(value, list):
return "\n".join(as_string(v) for v in value if as_string(v)).strip()
if isinstance(value, dict):
return json.dumps(value, ensure_ascii=False, indent=2)
return str(value)
def image_placeholder(value: dict[str, Any]) -> str:
mime = value.get("mime_type") or value.get("mime") or value.get("media_type") or "image"
detail = value.get("detail") or value.get("quality") or ""
url = value.get("url") or value.get("image_url") or ""
if isinstance(url, dict):
url = url.get("url") or ""
if isinstance(url, str) and url.startswith("data:"):
return f"[{mime} content part omitted: embedded base64 image/data URI]"
suffix = f", detail={detail}" if detail else ""
if url:
return f"[{mime} content part omitted: url/reference present{suffix}]"
return f"[{mime} content part omitted{suffix}]"
def extract_text_parts(
value: Any,
*,
strip: bool,
max_line_chars: int,
max_repeated_lines: int,
depth: int = 0,
json_aware: bool = False,
) -> list[str]:
if value is None or depth > 14:
return []
if isinstance(value, str):
if json_aware:
parsed = maybe_json(value)
if parsed is not None:
return extract_text_parts(
parsed,
strip=strip,
max_line_chars=max_line_chars,
max_repeated_lines=max_repeated_lines,
depth=depth + 1,
json_aware=True,
)
text = strip_hogs(value, enabled=strip, max_line_chars=max_line_chars, max_repeated_lines=max_repeated_lines)
return [text] if text else []
if isinstance(value, (int, float, bool)):
return [str(value)]
if isinstance(value, list):
parts: list[str] = []
for item in value:
parts.extend(
extract_text_parts(
item,
strip=strip,
max_line_chars=max_line_chars,
max_repeated_lines=max_repeated_lines,
depth=depth + 1,
json_aware=json_aware,
)
)
return [p for p in parts if p]
if isinstance(value, dict):
value_type = str(value.get("type") or "").lower()
if value_type in IMAGEISH_TYPES or any(k in value for k in ("image_url", "b64_json", "base64_image")):
return [image_placeholder(value)]
ordered_keys = (
"text",
"output_text",
"input_text",
"markdown",
"message",
"content",
"summary",
"transcript",
"stdout",
"stderr",
"output",
"result",
"diff",
"patch",
)
parts: list[str] = []
for key in ordered_keys:
if key in value:
parts.extend(
extract_text_parts(
value.get(key),
strip=strip,
max_line_chars=max_line_chars,
max_repeated_lines=max_repeated_lines,
depth=depth + 1,
json_aware=json_aware,
)
)
if not parts:
for key in ("item", "payload", "data", "event", "response"):
if key in value:
parts.extend(
extract_text_parts(
value.get(key),
strip=strip,
max_line_chars=max_line_chars,
max_repeated_lines=max_repeated_lines,
depth=depth + 1,
json_aware=json_aware,
)
)
if parts:
break
return [p for p in parts if p]
text = strip_hogs(str(value), enabled=strip, max_line_chars=max_line_chars, max_repeated_lines=max_repeated_lines)
return [text] if text else []
def extract_text(value: Any, *, strip: bool, max_line_chars: int, max_repeated_lines: int, json_aware: bool = False) -> str:
parts = extract_text_parts(value, strip=strip, max_line_chars=max_line_chars, max_repeated_lines=max_repeated_lines, json_aware=json_aware)
# Preserve order while de-duplicating exact repeated payloads.
return "\n\n".join(dict.fromkeys(p.strip() for p in parts if p.strip())).strip()
def parse_command_envelope(value: Any) -> tuple[str, dict[str, Any]]:
"""Return (command, metadata) from Codex/container-style arguments.
Important: local Codex JSONL often stores command arguments as a JSON string:
{"cmd":"...","workdir":"...","yield_time_ms":1000,"max_output_tokens":4000}
The GUI displays only cmd; exporting the raw JSON was the main v3 mismatch.
"""
meta: dict[str, Any] = {}
if isinstance(value, str):
parsed = maybe_json(value)
if parsed is not None:
return parse_command_envelope(parsed)
return value, meta
if isinstance(value, list):
return " ".join(as_string(x) for x in value), meta
if isinstance(value, dict):
meta = {k: v for k, v in value.items() if k not in {"cmd", "command", "script", "code", "shell_command"}}
for key in ("cmd", "command", "script", "code", "shell_command"):
if key in value:
return as_string(value.get(key)), meta
if "argv" in value:
return as_string(value.get("argv")), meta
if "args" in value:
return parse_command_envelope(value.get("args"))
if "arguments" in value:
return parse_command_envelope(value.get("arguments"))
return "", meta
return as_string(value), meta
def strip_powershell_wrapper(command: str) -> str:
command = command.strip()
if not command:
return ""
# C:\Program Files\PowerShell\7\pwsh.exe -Command <script>
wrapper = re.compile(
r"""^(?P<exe>(?:"[^"]*pwsh(?:\.exe)?"|[A-Za-z]:\\[^\r\n]*?pwsh(?:\.exe)?|pwsh(?:\.exe)?))\s+-Command\s+(?P<script>[\s\S]+)$""",
re.IGNORECASE,
)
m = wrapper.match(command)
if m:
script = m.group("script").strip()
if (script.startswith('"') and script.endswith('"')) or (script.startswith("'") and script.endswith("'")):
script = script[1:-1]
return script.strip()
return command
def normalize_command(command: str) -> str:
command = command.replace("\r\n", "\n").replace("\r", "\n").strip()
command = strip_powershell_wrapper(command)
return command.strip()
def command_key(command: str) -> str:
cmd = normalize_command(command)
cmd = re.sub(r"\s+", " ", cmd).strip().lower()
return cmd
def extract_command(obj: dict[str, Any]) -> str:
# Prefer arguments/call fields that are closest to user-visible tool invocations.
for key in ("arguments", "args"):
if key in obj:
cmd, _meta = parse_command_envelope(obj.get(key))
if cmd:
return normalize_command(cmd)
for key in ("command", "cmd", "shell_command", "script", "code"):
if key in obj:
cmd, _meta = parse_command_envelope(obj.get(key))
if cmd:
return normalize_command(cmd)
for key in ("call", "action", "input"):
if key in obj:
cmd, _meta = parse_command_envelope(obj.get(key))
if cmd:
return normalize_command(cmd)
return ""
def strip_codex_tool_metadata(text: str) -> tuple[str, dict[str, Any]]:
"""Remove Codex/container transport headers while preserving substantive output.
The Codex GUI direct-copy view shows command stdout/stderr and a concise
Success/Failure state, not container transport details such as Chunk ID,
Wall time, Process exited, Original token count, and Output:. Keep those
details out of normal Markdown while extracting exit_code for status.
"""
meta: dict[str, Any] = {}
if not text:
return "", meta
lines = text.splitlines()
if not lines:
return text, meta
# Common container-tool shape:
# Chunk ID: ...
# Wall time: ...
# Process exited with code 0
# Original token count: ...
# Output:
# <substantive output>
saw_transport_header = False
output_idx: int | None = None
kept: list[str] = []
for i, line in enumerate(lines[:8]):
stripped = line.strip()
if stripped.startswith("Chunk ID:") or stripped.startswith("Wall time:") or stripped.startswith("Original token count:"):
saw_transport_header = True
continue
m = re.match(r"Process exited with code\s+(-?\d+)", stripped)
if m:
saw_transport_header = True
try:
meta["exit_code"] = int(m.group(1))
except ValueError:
meta["exit_code"] = m.group(1)
continue
if stripped == "Output:":
saw_transport_header = True
output_idx = i + 1
break
kept.append(line)
if output_idx is not None:
return "\n".join(lines[output_idx:]).strip(), meta
if saw_transport_header:
# Fall back to dropping only recognized transport lines from the top.
rest: list[str] = []
for line in lines:
stripped = line.strip()
if stripped.startswith(("Chunk ID:", "Wall time:", "Original token count:")):
continue
m = re.match(r"Process exited with code\s+(-?\d+)", stripped)
if m:
try:
meta["exit_code"] = int(m.group(1))
except ValueError:
meta["exit_code"] = m.group(1)
continue
if stripped == "Output:":
continue
rest.append(line)
return "\n".join(rest).strip(), meta
return text, meta
def extract_output_and_meta(
obj: dict[str, Any],
*,
strip: bool,
max_line_chars: int,
max_repeated_lines: int,
) -> tuple[str, dict[str, Any]]:
meta: dict[str, Any] = {}
# Tool output records often have {"output":"...","metadata":{...}} as a JSON string.
for key in ("output", "result", "stdout", "stderr", "text", "content", "message", "diff", "patch"):
if key not in obj:
continue
value = obj.get(key)
parsed = maybe_json(value) if isinstance(value, str) else None
if isinstance(parsed, dict):
if isinstance(parsed.get("metadata"), dict):
meta.update(parsed["metadata"])
text = extract_text(
parsed.get("output") if "output" in parsed else parsed,
strip=strip,
max_line_chars=max_line_chars,
max_repeated_lines=max_repeated_lines,
json_aware=True,
)
else:
text = extract_text(
value,
strip=strip,
max_line_chars=max_line_chars,
max_repeated_lines=max_repeated_lines,
json_aware=True,
)
if text:
clean_text, transport_meta = strip_codex_tool_metadata(text)
meta.update({k: v for k, v in transport_meta.items() if k not in meta})
return clean_text, meta
if isinstance(obj.get("metadata"), dict):
meta.update(obj["metadata"])
return "", meta
def summarize_tool_output(text: str, mode: str, max_chars: int) -> str:
clean = text.strip()
if not clean or mode == "none":
return ""
if mode == "full":
return clean
if mode == "summary":
first = clean.splitlines()[0][:300]
return f"[tool output omitted: {len(clean):,} characters; first line: {first!r}]"
if mode == "tail":
if len(clean) <= max_chars:
return clean
return f"[tool output truncated to final {max_chars:,} characters from {len(clean):,} total]\n\n{clean[-max_chars:]}"
raise ValueError(f"Unknown tool output mode: {mode}")
def guess_lang(text: str, fallback: str = "text") -> str:
sample = text.lstrip()
if not sample:
return fallback
if sample.startswith("{") or sample.startswith("["):
return "json"
if sample.startswith("diff --git") or sample.startswith("@@ "):
return "diff"
if sample.startswith("import ") or "export function " in sample or "const " in sample:
return "ts"
if "$ErrorActionPreference" in sample or "Get-Content " in sample or "npm run " in sample or sample.startswith("$ "):
return "ps1"
return fallback
def max_backtick_run(text: str) -> int:
runs = [len(m.group(0)) for m in re.finditer(r"`+", text)]
return max(runs) if runs else 0
def fenced_block(text: str, lang: str = "", ticks: int = 3) -> str:
body = text.rstrip()
fence_len = max(ticks, max_backtick_run(body) + 1)
fence = "`" * fence_len
return f"{fence}{lang}\n{body}\n{fence}"
def first_line(text: str, limit: int = 220) -> str:
line = re.sub(r"\s+", " ", text.strip().splitlines()[0] if text.strip() else "")
return line if len(line) <= limit else line[: limit - 1] + "…"
def first_command_line(command: str, limit: int = 220) -> str:
lines = [ln.strip() for ln in command.strip().splitlines() if ln.strip()]
if len(lines) > 1 and re.fullmatch(r"\$?ErrorActionPreference\s*=\s*['\"]Stop['\"]", lines[0], flags=re.IGNORECASE):
line = lines[1]
else:
line = lines[0] if lines else ""
line = re.sub(r"\s+", " ", line)
return line if len(line) <= limit else line[: limit - 1] + "…"
def parse_apply_patch(command: str) -> list[dict[str, Any]]:
"""Parse an apply_patch payload into per-file edited/created/deleted blocks."""
if "*** Begin Patch" not in command or "*** End Patch" not in command:
return []
files: list[dict[str, Any]] = []
current: dict[str, Any] | None = None
current_path: str | None = None
def flush() -> None:
nonlocal current
if current is not None:
files.append(current)
current = None
for raw in command.splitlines():
line = raw.rstrip("\n")
if line.strip() in {"*** Begin Patch", "*** End Patch"}:
continue
m = re.match(r"\*\*\* (Add|Update|Delete) File:\s+(.+?)\s*$", line)
if m:
flush()
op = m.group(1).lower()
current_path = m.group(2).strip()
current = {"op": op, "path": current_path, "lines": [], "added": 0, "removed": 0}
continue
if current is None:
continue
current["lines"].append(line)
if line.startswith("+") and not line.startswith("+++"):
current["added"] += 1
elif line.startswith("-") and not line.startswith("---"):
current["removed"] += 1
flush()
return files
def patch_lang_for_path(path: str, fallback: str = "diff") -> str:
suffix = Path(path).suffix.lower()
return {
".ts": "ts",
".tsx": "tsx",
".js": "js",
".jsx": "jsx",
".mjs": "js",
".cjs": "js",
".json": "json",
".md": "md",
".css": "css",
".html": "html",
".yml": "yaml",
".yaml": "yaml",
".ps1": "ps1",
".py": "python",
".sh": "bash",
}.get(suffix, fallback)
def render_patch_file_block(file_info: dict[str, Any]) -> str:
op = str(file_info.get("op") or "update")
path = str(file_info.get("path") or "unknown")
added = int(file_info.get("added") or 0)
removed = int(file_info.get("removed") or 0)
lines = [str(x) for x in file_info.get("lines") or []]
if op == "add":
label = "Created file"
# Reconstruct added file contents without patch '+' markers when possible.
content_lines = [ln[1:] for ln in lines if ln.startswith("+") and not ln.startswith("+++")]
body = "\n".join(content_lines).rstrip()
lang = patch_lang_for_path(path, "text")
elif op == "delete":
label = "Deleted file"
content_lines = [ln[1:] for ln in lines if ln.startswith("-") and not ln.startswith("---")]
body = "\n".join(content_lines).rstrip()
lang = patch_lang_for_path(path, "text")
else:
label = "Edited file"
body = "\n".join(lines).rstrip()
lang = "diff"
parts = [label, path, f"+{added}", f"-{removed}"]
if body:
parts.append(fenced_block(body, lang, 3))
return "\n".join(parts)
def render_apply_patch_record(command: str, output: str, meta: dict[str, Any]) -> str:
files = parse_apply_patch(command)
if not files:
return ""
created = sum(1 for f in files if f.get("op") == "add")
edited = sum(1 for f in files if f.get("op") == "update")
deleted = sum(1 for f in files if f.get("op") == "delete")
summary_bits: list[str] = []
if created:
summary_bits.append(f"Created {created} file" + ("" if created == 1 else "s"))
if edited:
summary_bits.append(f"Edited {edited} file" + ("" if edited == 1 else "s"))
if deleted:
summary_bits.append(f"Deleted {deleted} file" + ("" if deleted == 1 else "s"))
parts: list[str] = [", ".join(summary_bits) if summary_bits else "Applied patch"]
parts.extend(render_patch_file_block(f) for f in files)
# Preserve meaningful apply_patch tool output, but avoid duplicating the raw
# patch or noisy success JSON. The GUI usually shows the edited-file cards
# plus Success.
cleaned_output = (output or "").strip()
if cleaned_output and not cleaned_output.lower().startswith("success. updated the following files"):
parts.append(fenced_block(cleaned_output, guess_lang(cleaned_output, "text"), 3))
exit_code = meta.get("exit_code", meta.get("exitCode", meta.get("code")))
if exit_code == 0 or str(exit_code) == "0" or cleaned_output.lower().startswith("success"):
parts.append("Success")
return "\n\n".join(p for p in parts if p).strip()
def render_action_record(
*,
title: str,
command: str,
output: str,
meta: dict[str, Any],
source_type: str,
timestamp: str,
seq: int,
) -> Record | None:
title_l = (title or "").lower()
cmd_key = command_key(command) if command else ""
if command and ("*** Begin Patch" in command and "*** End Patch" in command):
patch_text = render_apply_patch_record(command, output, meta)
if patch_text:
out_key = hashlib.sha256(patch_text.encode("utf-8", errors="ignore")).hexdigest()
return Record("action", "tool", patch_text, timestamp, source_type or title, seq, cmd_key, out_key)
# Drop tool lifecycle placeholders that carry neither a command nor output.
# The GUI direct-copy transcript does not include empty transport markers.
if not command and not output:
return None
chunks: list[str] = []
if command:
chunks.append(f"Ran {first_command_line(command)}")
chunks.append(fenced_block(f"$ {command}", "ps1", 3))
if output:
# GUI direct-copy output records usually do not show labels such as
# ``Action mcp_tool_call_end`` or ``Action write_stdin``; the output
# itself is the substantive content.
chunks.append(fenced_block(output, guess_lang(output, "text"), 3))
exit_code = meta.get("exit_code")
if exit_code is None:
exit_code = meta.get("exitCode")
if exit_code is None:
exit_code = meta.get("code")
if exit_code == 0 or str(exit_code) == "0":
# GUI-style direct copies show "Success"; keep it concise and searchable.
if output or command:
chunks.append("Success")
elif exit_code not in (None, ""):
chunks.append(f"Exit code {exit_code}")
text = "\n\n".join(chunks).strip()
if not text:
return None
out_key = hashlib.sha256(output.encode("utf-8", errors="ignore")).hexdigest() if output else ""
return Record("action", "tool", text, timestamp, source_type, seq, cmd_key, out_key)
def extract_action_record(
obj: dict[str, Any],
*,
timestamp: str,
source_type: str,
seq: int,
strip: bool,
max_line_chars: int,
max_repeated_lines: int,
tool_outputs: str,
max_tool_chars: int,
) -> Record | None:
title = as_string(obj.get("title") or obj.get("name") or obj.get("type") or source_type or "action")
command = extract_command(obj)
output, meta = extract_output_and_meta(obj, strip=strip, max_line_chars=max_line_chars, max_repeated_lines=max_repeated_lines)
output = summarize_tool_output(output, tool_outputs, max_tool_chars)
return render_action_record(title=title, command=command, output=output, meta=meta, source_type=source_type, timestamp=timestamp, seq=seq)
def get_timestamp(obj: dict[str, Any]) -> str:
for key in ("timestamp", "time", "created_at", "createdAt"):
value = obj.get(key)
if value:
return str(value)
return ""
def event_type_blob(obj: dict[str, Any]) -> tuple[str, dict[str, Any], str, dict[str, Any], str]:
top_type = str(obj.get("type") or "")
payload = obj.get("payload") if isinstance(obj.get("payload"), dict) else {}
payload_type = str(payload.get("type") or "")
item = payload.get("item") if isinstance(payload.get("item"), dict) else {}
item_type = str(item.get("type") or "")
return top_type, payload, payload_type, item, item_type
def classify_record(
obj: dict[str, Any],
*,
seq: int,
include_actions: bool,
tool_outputs: str,
max_tool_chars: int,
strip: bool,
max_line_chars: int,
max_repeated_lines: int,
) -> Record | None:
timestamp = get_timestamp(obj)
top_type, payload, payload_type, item, item_type = event_type_blob(obj)
type_blob = " ".join([top_type, payload_type, item_type]).lower()
if any(h in type_blob for h in NOISY_TYPE_HINTS):
return None
# Response item messages.
if item:
item_role = str(item.get("role") or "")
if (item_type == "message" or item_type in MESSAGE_TYPES) and item_role in {"user", "assistant", "system"}:
text = extract_text(
item.get("content") or item.get("message") or item.get("text"),
strip=strip,
max_line_chars=max_line_chars,
max_repeated_lines=max_repeated_lines,
)
if text:
return Record("message", item_role, text, timestamp, item_type, seq)
if include_actions and any(h in item_type.lower() for h in ACTION_HINTS):
return extract_action_record(
item,
timestamp=timestamp,
source_type=item_type,
seq=seq,
strip=strip,
max_line_chars=max_line_chars,
max_repeated_lines=max_repeated_lines,