|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""cc-export - export a Claude Code session transcript to Markdown or plain text. |
| 3 | +
|
| 4 | +Reads the session JSONL directly (the high-fidelity source: exact text, no |
| 5 | +re-conversion), so it is independent of the VS Code webview. Default output is |
| 6 | +the readable conversation only (user text + assistant text); thinking and tool |
| 7 | +calls are opt-in. `--open` opens the raw .jsonl in the editor instead. |
| 8 | +
|
| 9 | + python3 cc-export.py # latest session in this cwd -> stdout (markdown) |
| 10 | + python3 cc-export.py --session ID # a specific session id |
| 11 | + python3 cc-export.py --format text # plain text |
| 12 | + python3 cc-export.py --include-thinking --include-tools |
| 13 | + python3 cc-export.py -o out.md # write to a file |
| 14 | + python3 cc-export.py --open # open the raw transcript in VS Code |
| 15 | + python3 cc-export.py --cwd /path/to/proj # resolve as if launched from there |
| 16 | +
|
| 17 | +The JSONL is an internal format that can change, so each row's shape is validated |
| 18 | +and unknown shapes are skipped rather than assuming a fixed schema. |
| 19 | +""" |
| 20 | +import argparse |
| 21 | +import glob |
| 22 | +import json |
| 23 | +import os |
| 24 | +import subprocess |
| 25 | +import sys |
| 26 | +import unicodedata |
| 27 | + |
| 28 | + |
| 29 | +def config_dir(env=None): |
| 30 | + env = env if env is not None else os.environ |
| 31 | + return env.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude") |
| 32 | + |
| 33 | + |
| 34 | +def project_key_for_cwd(cwd): |
| 35 | + """The on-disk project dir name: realpath, NFC-normalized, slashes -> dashes.""" |
| 36 | + real = os.path.realpath(cwd) |
| 37 | + norm = unicodedata.normalize("NFC", real) |
| 38 | + return norm.replace(os.sep, "-").replace("/", "-") |
| 39 | + |
| 40 | + |
| 41 | +def resolve_session(config, cwd, session_id): |
| 42 | + """Return the path to the session JSONL, or None. |
| 43 | +
|
| 44 | + With an explicit id: look in this cwd's project dir, then scan all project |
| 45 | + dirs. With no id: the most recently modified .jsonl in this cwd's project dir. |
| 46 | + """ |
| 47 | + projects = os.path.join(config, "projects") |
| 48 | + key = project_key_for_cwd(cwd) |
| 49 | + proj_dir = os.path.join(projects, key) |
| 50 | + if session_id: |
| 51 | + local = os.path.join(proj_dir, f"{session_id}.jsonl") |
| 52 | + if os.path.isfile(local): |
| 53 | + return local |
| 54 | + for hit in glob.glob(os.path.join(projects, "*", f"{session_id}.jsonl")): |
| 55 | + if os.path.isfile(hit): |
| 56 | + return hit |
| 57 | + return None |
| 58 | + candidates = glob.glob(os.path.join(proj_dir, "*.jsonl")) |
| 59 | + if not candidates: |
| 60 | + return None |
| 61 | + return max(candidates, key=lambda p: os.path.getmtime(p)) |
| 62 | + |
| 63 | + |
| 64 | +def read_rows(path): |
| 65 | + rows = [] |
| 66 | + with open(path, "r", encoding="utf-8") as f: |
| 67 | + for line in f: |
| 68 | + line = line.strip() |
| 69 | + if not line: |
| 70 | + continue |
| 71 | + try: |
| 72 | + rows.append(json.loads(line)) |
| 73 | + except json.JSONDecodeError: |
| 74 | + continue # skip a corrupt line rather than abort |
| 75 | + return rows |
| 76 | + |
| 77 | + |
| 78 | +def _blocks(content): |
| 79 | + """Normalize a message's content to a list of block dicts. |
| 80 | +
|
| 81 | + Content may be a plain string (treated as one text block) or a list. |
| 82 | + """ |
| 83 | + if isinstance(content, str): |
| 84 | + return [{"type": "text", "text": content}] |
| 85 | + if isinstance(content, list): |
| 86 | + return [b for b in content if isinstance(b, dict)] |
| 87 | + return [] |
| 88 | + |
| 89 | + |
| 90 | +def render(rows, fmt="markdown", include_thinking=False, include_tools=False): |
| 91 | + """Render rows to markdown (with role headers) or plain text.""" |
| 92 | + md = fmt != "text" |
| 93 | + parts = [] |
| 94 | + for row in rows: |
| 95 | + if not isinstance(row, dict): |
| 96 | + continue |
| 97 | + rtype = row.get("type") |
| 98 | + if rtype not in ("user", "assistant"): |
| 99 | + continue # skip summary / file-history-snapshot / etc. |
| 100 | + message = row.get("message") |
| 101 | + if not isinstance(message, dict): |
| 102 | + continue |
| 103 | + blocks = _blocks(message.get("content")) |
| 104 | + chunks = [] |
| 105 | + for b in blocks: |
| 106 | + bt = b.get("type") |
| 107 | + if bt == "text": |
| 108 | + t = b.get("text") |
| 109 | + if isinstance(t, str) and t.strip(): |
| 110 | + chunks.append(t.rstrip()) |
| 111 | + elif bt == "thinking" and include_thinking: |
| 112 | + t = b.get("thinking") |
| 113 | + if isinstance(t, str) and t.strip(): |
| 114 | + chunks.append(_fence("thinking", t) if md else t.rstrip()) |
| 115 | + elif bt == "tool_use" and include_tools: |
| 116 | + name = b.get("name", "tool") |
| 117 | + payload = json.dumps(b.get("input", {}), indent=2, ensure_ascii=False) |
| 118 | + chunks.append(_fence(f"tool_use {name}", payload) if md else f"[tool_use {name}] {payload}") |
| 119 | + elif bt == "tool_result" and include_tools: |
| 120 | + payload = b.get("content") |
| 121 | + if isinstance(payload, (dict, list)): |
| 122 | + payload = json.dumps(payload, indent=2, ensure_ascii=False) |
| 123 | + payload = "" if payload is None else str(payload) |
| 124 | + chunks.append(_fence("tool_result", payload) if md else f"[tool_result] {payload}") |
| 125 | + if not chunks: |
| 126 | + continue |
| 127 | + body = "\n\n".join(chunks) |
| 128 | + if md: |
| 129 | + header = "## User" if rtype == "user" else "## Assistant" |
| 130 | + parts.append(f"{header}\n\n{body}") |
| 131 | + else: |
| 132 | + parts.append(body) |
| 133 | + return ("\n\n".join(parts) + "\n") if parts else "" |
| 134 | + |
| 135 | + |
| 136 | +def _fence(label, text): |
| 137 | + # Pick a fence longer than the longest backtick run in the body, so content |
| 138 | + # that itself contains ``` cannot close the fence early. |
| 139 | + text = text.rstrip() |
| 140 | + longest = run = 0 |
| 141 | + for ch in text: |
| 142 | + if ch == "`": |
| 143 | + run += 1 |
| 144 | + longest = max(longest, run) |
| 145 | + else: |
| 146 | + run = 0 |
| 147 | + fence = "`" * max(3, longest + 1) |
| 148 | + return f"{fence}{label}\n{text}\n{fence}" |
| 149 | + |
| 150 | + |
| 151 | +def main(argv=None, config=None, env=None): |
| 152 | + env = env if env is not None else os.environ |
| 153 | + argv = list(sys.argv[1:] if argv is None else argv) |
| 154 | + ap = argparse.ArgumentParser(prog="cc-export", description="Export a Claude Code session.") |
| 155 | + ap.add_argument("--session", default=None, help="session id (default: latest in cwd)") |
| 156 | + ap.add_argument("--cwd", default=None, help="resolve as if launched from this dir") |
| 157 | + ap.add_argument("--format", choices=("markdown", "text"), default="markdown") |
| 158 | + ap.add_argument("--include-thinking", action="store_true") |
| 159 | + ap.add_argument("--include-tools", action="store_true") |
| 160 | + ap.add_argument("--open", action="store_true", help="open the raw .jsonl in VS Code") |
| 161 | + ap.add_argument("-o", "--output", default=None, help="write to FILE (default: stdout)") |
| 162 | + args = ap.parse_args(argv) |
| 163 | + |
| 164 | + conf = config if config is not None else config_dir(env) |
| 165 | + cwd = args.cwd or os.getcwd() |
| 166 | + path = resolve_session(conf, cwd, args.session) |
| 167 | + if not path: |
| 168 | + sys.stderr.write("cc-export: no matching session transcript found\n") |
| 169 | + return 1 |
| 170 | + |
| 171 | + if args.open: |
| 172 | + editor = env.get("CC_EDITOR", "code") |
| 173 | + try: |
| 174 | + subprocess.run([editor, path], check=False, env=env) |
| 175 | + except FileNotFoundError: |
| 176 | + sys.stderr.write(f"cc-export: editor '{editor}' not found on PATH\n") |
| 177 | + return 1 |
| 178 | + return 0 |
| 179 | + |
| 180 | + out = render( |
| 181 | + read_rows(path), |
| 182 | + fmt=args.format, |
| 183 | + include_thinking=args.include_thinking, |
| 184 | + include_tools=args.include_tools, |
| 185 | + ) |
| 186 | + if args.output: |
| 187 | + with open(args.output, "w", encoding="utf-8") as f: |
| 188 | + f.write(out) |
| 189 | + else: |
| 190 | + sys.stdout.write(out) |
| 191 | + return 0 |
| 192 | + |
| 193 | + |
| 194 | +if __name__ == "__main__": |
| 195 | + sys.exit(main()) |
0 commit comments