-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy path__init__.py
More file actions
2271 lines (1947 loc) · 85.8 KB
/
__init__.py
File metadata and controls
2271 lines (1947 loc) · 85.8 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
"""Convert Claude Code session JSON to a clean mobile-friendly HTML page with pagination."""
import json
import html
import os
import platform
import re
import shutil
import subprocess
import tempfile
import webbrowser
from datetime import datetime
from pathlib import Path
import click
from click_default_group import DefaultGroup
import httpx
from jinja2 import Environment, PackageLoader
import markdown
import questionary
# Set up Jinja2 environment
_jinja_env = Environment(
loader=PackageLoader("claude_code_transcripts", "templates"),
autoescape=True,
)
# Load macros template and expose macros
_macros_template = _jinja_env.get_template("macros.html")
_macros = _macros_template.module
def get_template(name):
"""Get a Jinja2 template by name."""
return _jinja_env.get_template(name)
# Regex to match git commit output: [branch hash] message
COMMIT_PATTERN = re.compile(r"\[[\w\-/]+ ([a-f0-9]{7,})\] (.+?)(?:\n|$)")
# Regex to detect GitHub repo from git push output (e.g., github.com/owner/repo/pull/new/branch)
GITHUB_REPO_PATTERN = re.compile(
r"github\.com/([a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+)/pull/new/"
)
PROMPTS_PER_PAGE = 5
LONG_TEXT_THRESHOLD = (
300 # Characters - text blocks longer than this are shown in index
)
def extract_text_from_content(content):
"""Extract plain text from message content.
Handles both string content (older format) and array content (newer format).
Args:
content: Either a string or a list of content blocks like
[{"type": "text", "text": "..."}, {"type": "image", ...}]
Returns:
The extracted text as a string, or empty string if no text found.
"""
if isinstance(content, str):
return content.strip()
elif isinstance(content, list):
# Extract text from content blocks of type "text"
texts = []
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
text = block.get("text", "")
if text:
texts.append(text)
return " ".join(texts).strip()
return ""
# Module-level variable for GitHub repo (set by generate_html)
_github_repo = None
# API constants
API_BASE_URL = "https://api.anthropic.com/v1"
ANTHROPIC_VERSION = "2023-06-01"
def get_session_summary(filepath, max_length=200):
"""Extract a human-readable summary from a session file.
Supports both JSON and JSONL formats.
Returns a summary string or "(no summary)" if none found.
"""
filepath = Path(filepath)
try:
if filepath.suffix == ".jsonl":
return _get_jsonl_summary(filepath, max_length)
else:
# For JSON files, try to get first user message
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
loglines = data.get("loglines", [])
for entry in loglines:
if entry.get("type") == "user":
msg = entry.get("message", {})
content = msg.get("content", "")
text = extract_text_from_content(content)
if text:
if len(text) > max_length:
return text[: max_length - 3] + "..."
return text
return "(no summary)"
except Exception:
return "(no summary)"
def _get_jsonl_summary(filepath, max_length=200):
"""Extract summary from JSONL file."""
try:
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
# First priority: summary type entries
if obj.get("type") == "summary" and obj.get("summary"):
summary = obj["summary"]
if len(summary) > max_length:
return summary[: max_length - 3] + "..."
return summary
except json.JSONDecodeError:
continue
# Second pass: find first non-meta user message
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
if (
obj.get("type") == "user"
and not obj.get("isMeta")
and obj.get("message", {}).get("content")
):
content = obj["message"]["content"]
text = extract_text_from_content(content)
if text and not text.startswith("<"):
if len(text) > max_length:
return text[: max_length - 3] + "..."
return text
except json.JSONDecodeError:
continue
except Exception:
pass
return "(no summary)"
def find_local_sessions(folder, limit=10):
"""Find recent JSONL session files in the given folder.
Returns a list of (Path, summary) tuples sorted by modification time.
Excludes agent files and warmup/empty sessions.
"""
folder = Path(folder)
if not folder.exists():
return []
results = []
for f in folder.glob("**/*.jsonl"):
if f.name.startswith("agent-"):
continue
summary = get_session_summary(f)
# Skip boring/empty sessions
if summary.lower() == "warmup" or summary == "(no summary)":
continue
results.append((f, summary))
# Sort by modification time, most recent first
results.sort(key=lambda x: x[0].stat().st_mtime, reverse=True)
return results[:limit]
def get_project_display_name(folder_name):
"""Convert encoded folder name to readable project name.
Claude Code stores projects in folders like:
- -home-user-projects-myproject -> myproject
- -mnt-c-Users-name-Projects-app -> app
For nested paths under common roots (home, projects, code, Users, etc.),
extracts the meaningful project portion.
"""
# Common path prefixes to strip
prefixes_to_strip = [
"-home-",
"-mnt-c-Users-",
"-mnt-c-users-",
"-Users-",
]
name = folder_name
for prefix in prefixes_to_strip:
if name.lower().startswith(prefix.lower()):
name = name[len(prefix) :]
break
# Split on dashes and find meaningful parts
parts = name.split("-")
# Common intermediate directories to skip
skip_dirs = {"projects", "code", "repos", "src", "dev", "work", "documents"}
# Find the first meaningful part (after skipping username and common dirs)
meaningful_parts = []
found_project = False
for i, part in enumerate(parts):
if not part:
continue
# Skip the first part if it looks like a username (before common dirs)
if i == 0 and not found_project:
# Check if next parts contain common dirs
remaining = [p.lower() for p in parts[i + 1 :]]
if any(d in remaining for d in skip_dirs):
continue
if part.lower() in skip_dirs:
found_project = True
continue
meaningful_parts.append(part)
found_project = True
if meaningful_parts:
return "-".join(meaningful_parts)
# Fallback: return last non-empty part or original
for part in reversed(parts):
if part:
return part
return folder_name
def find_all_sessions(folder, include_agents=False):
"""Find all sessions in a Claude projects folder, grouped by project.
Returns a list of project dicts, each containing:
- name: display name for the project
- path: Path to the project folder
- sessions: list of session dicts with path, summary, mtime, size
Sessions are sorted by modification time (most recent first) within each project.
Projects are sorted by their most recent session.
"""
folder = Path(folder)
if not folder.exists():
return []
projects = {}
for session_file in folder.glob("**/*.jsonl"):
# Skip agent files unless requested
if not include_agents and session_file.name.startswith("agent-"):
continue
# Get summary and skip boring sessions
summary = get_session_summary(session_file)
if summary.lower() == "warmup" or summary == "(no summary)":
continue
# Get project folder
project_folder = session_file.parent
project_key = project_folder.name
if project_key not in projects:
projects[project_key] = {
"name": get_project_display_name(project_key),
"path": project_folder,
"sessions": [],
}
stat = session_file.stat()
projects[project_key]["sessions"].append(
{
"path": session_file,
"summary": summary,
"mtime": stat.st_mtime,
"size": stat.st_size,
}
)
# Sort sessions within each project by mtime (most recent first)
for project in projects.values():
project["sessions"].sort(key=lambda s: s["mtime"], reverse=True)
# Convert to list and sort projects by most recent session
result = list(projects.values())
result.sort(
key=lambda p: p["sessions"][0]["mtime"] if p["sessions"] else 0, reverse=True
)
return result
def generate_batch_html(
source_folder, output_dir, include_agents=False, progress_callback=None
):
"""Generate HTML archive for all sessions in a Claude projects folder.
Creates:
- Master index.html listing all projects
- Per-project directories with index.html listing sessions
- Per-session directories with transcript pages
Args:
source_folder: Path to the Claude projects folder
output_dir: Path for output archive
include_agents: Whether to include agent-* session files
progress_callback: Optional callback(project_name, session_name, current, total)
called after each session is processed
Returns statistics dict with total_projects, total_sessions, failed_sessions, output_dir.
"""
source_folder = Path(source_folder)
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
# Find all sessions
projects = find_all_sessions(source_folder, include_agents=include_agents)
# Calculate total for progress tracking
total_session_count = sum(len(p["sessions"]) for p in projects)
processed_count = 0
successful_sessions = 0
failed_sessions = []
# Process each project
for project in projects:
project_dir = output_dir / project["name"]
project_dir.mkdir(exist_ok=True)
# Process each session
for session in project["sessions"]:
session_name = session["path"].stem
session_dir = project_dir / session_name
# Generate transcript HTML with error handling
try:
generate_html(session["path"], session_dir)
successful_sessions += 1
except Exception as e:
failed_sessions.append(
{
"project": project["name"],
"session": session_name,
"error": str(e),
}
)
processed_count += 1
# Call progress callback if provided
if progress_callback:
progress_callback(
project["name"], session_name, processed_count, total_session_count
)
# Generate project index
_generate_project_index(project, project_dir)
# Generate master index
_generate_master_index(projects, output_dir)
return {
"total_projects": len(projects),
"total_sessions": successful_sessions,
"failed_sessions": failed_sessions,
"output_dir": output_dir,
}
def _generate_project_index(project, output_dir):
"""Generate index.html for a single project."""
template = get_template("project_index.html")
# Format sessions for template
sessions_data = []
for session in project["sessions"]:
mod_time = datetime.fromtimestamp(session["mtime"])
sessions_data.append(
{
"name": session["path"].stem,
"summary": session["summary"],
"date": mod_time.strftime("%Y-%m-%d %H:%M"),
"size_kb": session["size"] / 1024,
}
)
html_content = template.render(
project_name=project["name"],
sessions=sessions_data,
session_count=len(sessions_data),
css=CSS,
js=JS,
)
output_path = output_dir / "index.html"
output_path.write_text(html_content, encoding="utf-8")
def _generate_master_index(projects, output_dir):
"""Generate master index.html listing all projects."""
template = get_template("master_index.html")
# Format projects for template
projects_data = []
total_sessions = 0
for project in projects:
session_count = len(project["sessions"])
total_sessions += session_count
# Get most recent session date
if project["sessions"]:
most_recent = datetime.fromtimestamp(project["sessions"][0]["mtime"])
recent_date = most_recent.strftime("%Y-%m-%d")
else:
recent_date = "N/A"
projects_data.append(
{
"name": project["name"],
"session_count": session_count,
"recent_date": recent_date,
}
)
html_content = template.render(
projects=projects_data,
total_projects=len(projects),
total_sessions=total_sessions,
css=CSS,
js=JS,
)
output_path = output_dir / "index.html"
output_path.write_text(html_content, encoding="utf-8")
def parse_session_file(filepath):
"""Parse a session file and return normalized data.
Supports both JSON and JSONL formats.
Returns a dict with 'loglines' key containing the normalized entries.
"""
filepath = Path(filepath)
if filepath.suffix == ".jsonl":
return _parse_jsonl_file(filepath)
else:
# Standard JSON format
with open(filepath, "r", encoding="utf-8") as f:
return json.load(f)
def _parse_jsonl_file(filepath):
"""Parse JSONL file and convert to standard format."""
loglines = []
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
entry_type = obj.get("type")
# Skip non-message entries
if entry_type not in ("user", "assistant"):
continue
# Convert to standard format
entry = {
"type": entry_type,
"timestamp": obj.get("timestamp", ""),
"message": obj.get("message", {}),
}
# Preserve isCompactSummary if present
if obj.get("isCompactSummary"):
entry["isCompactSummary"] = True
loglines.append(entry)
except json.JSONDecodeError:
continue
return {"loglines": loglines}
class CredentialsError(Exception):
"""Raised when credentials cannot be obtained."""
pass
def get_access_token_from_keychain():
"""Get access token from system credentials.
On macOS, retrieves from keychain.
On Linux, retrieves from ~/.claude/.credentials.json.
Returns the access token or None if not found/expired.
Raises CredentialsError with helpful message on failure.
"""
system = platform.system()
if system == "Darwin":
# macOS: use keychain
try:
result = subprocess.run(
[
"security",
"find-generic-password",
"-a",
os.environ.get("USER", ""),
"-s",
"Claude Code-credentials",
"-w",
],
capture_output=True,
text=True,
)
if result.returncode != 0:
return None
# Parse the JSON to get the access token
creds = json.loads(result.stdout.strip())
return creds.get("claudeAiOauth", {}).get("accessToken")
except (json.JSONDecodeError, subprocess.SubprocessError):
return None
elif system == "Linux":
# Linux: read from ~/.claude/.credentials.json
creds_path = Path.home() / ".claude" / ".credentials.json"
if not creds_path.exists():
return None
try:
with open(creds_path, "r") as f:
creds = json.load(f)
oauth_data = creds.get("claudeAiOauth", {})
access_token = oauth_data.get("accessToken")
expires_at = oauth_data.get("expiresAt")
# If no access token, return None
if not access_token:
return None
# Check if token is expired (if expiresAt is provided)
if expires_at:
try:
# Parse ISO format datetime (e.g., "2099-12-31T23:59:59Z")
expiry_time = datetime.fromisoformat(
expires_at.replace("Z", "+00:00")
)
current_time = datetime.now(expiry_time.tzinfo)
if current_time >= expiry_time:
# Token is expired
return None
except (ValueError, AttributeError):
# If we can't parse the expiration date, treat as no expiration
pass
return access_token
except (json.JSONDecodeError, IOError):
return None
else:
# Unsupported platform
return None
def get_org_uuid_from_config():
"""Get organization UUID from ~/.claude.json.
Returns the organization UUID or None if not found.
"""
config_path = Path.home() / ".claude.json"
if not config_path.exists():
return None
try:
with open(config_path) as f:
config = json.load(f)
return config.get("oauthAccount", {}).get("organizationUuid")
except (json.JSONDecodeError, IOError):
return None
def get_api_headers(token, org_uuid):
"""Build API request headers."""
return {
"Authorization": f"Bearer {token}",
"anthropic-version": ANTHROPIC_VERSION,
"Content-Type": "application/json",
"x-organization-uuid": org_uuid,
}
def fetch_sessions(token, org_uuid):
"""Fetch list of sessions from the API.
Returns the sessions data as a dict.
Raises httpx.HTTPError on network/API errors.
"""
headers = get_api_headers(token, org_uuid)
response = httpx.get(f"{API_BASE_URL}/sessions", headers=headers, timeout=30.0)
response.raise_for_status()
return response.json()
def fetch_session(token, org_uuid, session_id):
"""Fetch a specific session from the API.
Returns the session data as a dict.
Raises httpx.HTTPError on network/API errors.
"""
headers = get_api_headers(token, org_uuid)
response = httpx.get(
f"{API_BASE_URL}/session_ingress/session/{session_id}",
headers=headers,
timeout=60.0,
)
response.raise_for_status()
return response.json()
def detect_github_repo(loglines):
"""
Detect GitHub repo from git push output in tool results.
Looks for patterns like:
- github.com/owner/repo/pull/new/branch (from git push messages)
Returns the first detected repo (owner/name) or None.
"""
for entry in loglines:
message = entry.get("message", {})
content = message.get("content", [])
if not isinstance(content, list):
continue
for block in content:
if not isinstance(block, dict):
continue
if block.get("type") == "tool_result":
result_content = block.get("content", "")
if isinstance(result_content, str):
match = GITHUB_REPO_PATTERN.search(result_content)
if match:
return match.group(1)
return None
def extract_repo_from_session(session):
"""Extract GitHub repo from session metadata.
Looks in session_context.outcomes for git_info.repo,
or parses from session_context.sources URL.
Returns repo as "owner/name" or None.
"""
context = session.get("session_context", {})
# Try outcomes first (has clean repo format)
outcomes = context.get("outcomes", [])
for outcome in outcomes:
if outcome.get("type") == "git_repository":
git_info = outcome.get("git_info", {})
repo = git_info.get("repo")
if repo:
return repo
# Fall back to sources URL
sources = context.get("sources", [])
for source in sources:
if source.get("type") == "git_repository":
url = source.get("url", "")
# Parse github.com/owner/repo from URL
if "github.com/" in url:
# Extract owner/repo from https://github.com/owner/repo
match = re.search(r"github\.com/([^/]+/[^/]+?)(?:\.git)?$", url)
if match:
return match.group(1)
return None
def enrich_sessions_with_repos(sessions, token=None, org_uuid=None, fetch_fn=None):
"""Enrich sessions with repo information from session metadata.
Args:
sessions: List of session dicts from the API
token: Unused (kept for backward compatibility)
org_uuid: Unused (kept for backward compatibility)
fetch_fn: Unused (kept for backward compatibility)
Returns:
List of session dicts with 'repo' key added
"""
enriched = []
for session in sessions:
session_copy = dict(session)
session_copy["repo"] = extract_repo_from_session(session)
enriched.append(session_copy)
return enriched
def filter_sessions_by_repo(sessions, repo):
"""Filter sessions by repo.
Args:
sessions: List of session dicts with 'repo' key
repo: Repo to filter by (owner/name), or None to return all
Returns:
Filtered list of sessions
"""
if repo is None:
return sessions
return [s for s in sessions if s.get("repo") == repo]
def format_json(obj):
try:
if isinstance(obj, str):
obj = json.loads(obj)
formatted = json.dumps(obj, indent=2, ensure_ascii=False)
return f'<pre class="json">{html.escape(formatted)}</pre>'
except (json.JSONDecodeError, TypeError):
return f"<pre>{html.escape(str(obj))}</pre>"
def render_markdown_text(text):
if not text:
return ""
return markdown.markdown(text, extensions=["fenced_code", "tables"])
def is_json_like(text):
if not text or not isinstance(text, str):
return False
text = text.strip()
return (text.startswith("{") and text.endswith("}")) or (
text.startswith("[") and text.endswith("]")
)
def render_todo_write(tool_input, tool_id):
todos = tool_input.get("todos", [])
if not todos:
return ""
return _macros.todo_list(todos, tool_id)
def render_write_tool(tool_input, tool_id):
"""Render Write tool calls with file path header and content preview."""
file_path = tool_input.get("file_path", "Unknown file")
content = tool_input.get("content", "")
return _macros.write_tool(file_path, content, tool_id)
def render_edit_tool(tool_input, tool_id):
"""Render Edit tool calls with diff-like old/new display."""
file_path = tool_input.get("file_path", "Unknown file")
old_string = tool_input.get("old_string", "")
new_string = tool_input.get("new_string", "")
replace_all = tool_input.get("replace_all", False)
return _macros.edit_tool(file_path, old_string, new_string, replace_all, tool_id)
def render_bash_tool(tool_input, tool_id):
"""Render Bash tool calls with command as plain text."""
command = tool_input.get("command", "")
description = tool_input.get("description", "")
return _macros.bash_tool(command, description, tool_id)
def render_content_block(block):
if not isinstance(block, dict):
return f"<p>{html.escape(str(block))}</p>"
block_type = block.get("type", "")
if block_type == "image":
source = block.get("source", {})
media_type = source.get("media_type", "image/png")
data = source.get("data", "")
return _macros.image_block(media_type, data)
elif block_type == "thinking":
content_html = render_markdown_text(block.get("thinking", ""))
return _macros.thinking(content_html)
elif block_type == "text":
content_html = render_markdown_text(block.get("text", ""))
return _macros.assistant_text(content_html)
elif block_type == "tool_use":
tool_name = block.get("name", "Unknown tool")
tool_input = block.get("input", {})
tool_id = block.get("id", "")
if tool_name == "TodoWrite":
return render_todo_write(tool_input, tool_id)
if tool_name == "Write":
return render_write_tool(tool_input, tool_id)
if tool_name == "Edit":
return render_edit_tool(tool_input, tool_id)
if tool_name == "Bash":
return render_bash_tool(tool_input, tool_id)
description = tool_input.get("description", "")
display_input = {k: v for k, v in tool_input.items() if k != "description"}
input_json = json.dumps(display_input, indent=2, ensure_ascii=False)
return _macros.tool_use(tool_name, description, input_json, tool_id)
elif block_type == "tool_result":
content = block.get("content", "")
is_error = block.get("is_error", False)
has_images = False
# Check for git commits and render with styled cards
if isinstance(content, str):
commits_found = list(COMMIT_PATTERN.finditer(content))
if commits_found:
# Build commit cards + remaining content
parts = []
last_end = 0
for match in commits_found:
# Add any content before this commit
before = content[last_end : match.start()].strip()
if before:
parts.append(f"<pre>{html.escape(before)}</pre>")
commit_hash = match.group(1)
commit_msg = match.group(2)
parts.append(
_macros.commit_card(commit_hash, commit_msg, _github_repo)
)
last_end = match.end()
# Add any remaining content after last commit
after = content[last_end:].strip()
if after:
parts.append(f"<pre>{html.escape(after)}</pre>")
content_html = "".join(parts)
else:
content_html = f"<pre>{html.escape(content)}</pre>"
elif isinstance(content, list):
# Handle tool result content that contains multiple blocks (text, images, etc.)
parts = []
for item in content:
if isinstance(item, dict):
item_type = item.get("type", "")
if item_type == "text":
text = item.get("text", "")
if text:
parts.append(f"<pre>{html.escape(text)}</pre>")
elif item_type == "image":
source = item.get("source", {})
media_type = source.get("media_type", "image/png")
data = source.get("data", "")
if data:
parts.append(_macros.image_block(media_type, data))
has_images = True
else:
# Unknown type, render as JSON
parts.append(format_json(item))
else:
# Non-dict item, escape as text
parts.append(f"<pre>{html.escape(str(item))}</pre>")
content_html = "".join(parts) if parts else format_json(content)
elif is_json_like(content):
content_html = format_json(content)
else:
content_html = format_json(content)
return _macros.tool_result(content_html, is_error, has_images)
else:
return format_json(block)
def render_user_message_content(message_data):
content = message_data.get("content", "")
if isinstance(content, str):
if is_json_like(content):
return _macros.user_content(format_json(content))
return _macros.user_content(render_markdown_text(content))
elif isinstance(content, list):
return "".join(render_content_block(block) for block in content)
return f"<p>{html.escape(str(content))}</p>"
def render_assistant_message(message_data):
content = message_data.get("content", [])
if not isinstance(content, list):
return f"<p>{html.escape(str(content))}</p>"
return "".join(render_content_block(block) for block in content)
def make_msg_id(timestamp):
return f"msg-{timestamp.replace(':', '-').replace('.', '-')}"
def analyze_conversation(messages):
"""Analyze messages in a conversation to extract stats and long texts."""
tool_counts = {} # tool_name -> count
long_texts = []
commits = [] # list of (hash, message, timestamp)
for log_type, message_json, timestamp in messages:
if not message_json:
continue
try:
message_data = json.loads(message_json)
except json.JSONDecodeError:
continue
content = message_data.get("content", [])
if not isinstance(content, list):
continue
for block in content:
if not isinstance(block, dict):
continue
block_type = block.get("type", "")
if block_type == "tool_use":
tool_name = block.get("name", "Unknown")
tool_counts[tool_name] = tool_counts.get(tool_name, 0) + 1
elif block_type == "tool_result":
# Check for git commit output
result_content = block.get("content", "")
if isinstance(result_content, str):
for match in COMMIT_PATTERN.finditer(result_content):
commits.append((match.group(1), match.group(2), timestamp))
elif block_type == "text":
text = block.get("text", "")
if len(text) >= LONG_TEXT_THRESHOLD:
long_texts.append(text)
return {
"tool_counts": tool_counts,
"long_texts": long_texts,
"commits": commits,
}
def format_tool_stats(tool_counts):
"""Format tool counts into a concise summary string."""
if not tool_counts:
return ""
# Abbreviate common tool names
abbrev = {
"Bash": "bash",
"Read": "read",
"Write": "write",
"Edit": "edit",
"Glob": "glob",
"Grep": "grep",
"Task": "task",
"TodoWrite": "todo",
"WebFetch": "fetch",
"WebSearch": "search",
}
parts = []
for name, count in sorted(tool_counts.items(), key=lambda x: -x[1]):
short_name = abbrev.get(name, name.lower())
parts.append(f"{count} {short_name}")
return " · ".join(parts)
def is_tool_result_message(message_data):
"""Check if a message contains only tool_result blocks."""
content = message_data.get("content", [])
if not isinstance(content, list):
return False
if not content:
return False
return all(
isinstance(block, dict) and block.get("type") == "tool_result"
for block in content
)
def render_message(log_type, message_json, timestamp):
if not message_json:
return ""
try:
message_data = json.loads(message_json)