-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcc_export.py
More file actions
220 lines (180 loc) · 7.62 KB
/
Copy pathcc_export.py
File metadata and controls
220 lines (180 loc) · 7.62 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
#!/usr/bin/env python3
"""
Claude Code Transcript Exporter
用法: python3 cc_export.py <session.jsonl> [output.md]
将 Claude Code 的会话 JSONL 文件导出为带目录、可折叠的 Markdown 文档。
包含: 用户消息、助手回复、Thinking、工具调用(输入+输出)。
路径: ~/.claude/projects/<project-hash>/<session-id>.jsonl
例子:
# 导出当前会话
python3 /tmp/cc_export.py \
~/.claude/projects/<project>/<session>.jsonl \
导出.md
# 默认输出到同名 .md
python3 /tmp/cc_export.py session.jsonl
"""
import json, sys, re, os
# ── 配置 ──────────────────────────────────────────────
TOOL_RESULT_MAX = 5000 # 工具输出截断长度
THINKING_COLLAPSED = True # 默认折叠 Thinking
# ── 辅助函数 ──────────────────────────────────────────
def esc_md(s):
"""转义 Markdown 特殊字符"""
return s.replace('|', '\\|').replace('<', '<').replace('>', '>')
def fmt_json(obj):
"""将 JSON 对象格式化为紧凑的可读字符串"""
try:
if isinstance(obj, str):
obj = json.loads(obj)
s = json.dumps(obj, indent=2, ensure_ascii=False)
if len(s) > TOOL_RESULT_MAX:
s = s[:TOOL_RESULT_MAX] + '\n\n... *(truncated)*'
return s
except:
return str(obj)
def extract_content_blocks(content):
"""从助手消息的 content 数组中提取各类块"""
blocks = []
for item in (content if isinstance(content, list) else []):
if not isinstance(item, dict):
continue
bt = item.get('type', '')
if bt == 'thinking':
blocks.append(('thinking', item.get('thinking', '')))
elif bt == 'text':
blocks.append(('text', item.get('text', '')))
elif bt == 'tool_use':
blocks.append(('tool_use', item))
return blocks
# ── 主程序 ────────────────────────────────────────────
def main(input_file, output_file=None):
if not os.path.exists(input_file):
print(f"Error: {input_file} 不存在")
sys.exit(1)
if output_file is None:
output_file = os.path.splitext(input_file)[0] + '.md'
with open(input_file, 'r') as f:
lines = f.readlines()
out = []
out.append("# Claude Code 会话 Transcript\n\n")
out.append(f"**源文件**: `{input_file}` \n")
out.append(f"**记录数**: {len(lines)}\n\n")
out.append("---\n\n")
msg_idx = 0
tool_idx = 0
# 第一遍: 收集所有 tool_use → tool_result 配对
tool_pool = {} # tool_use_id -> (input_data, output_data)
for line in lines:
try:
obj = json.loads(line)
except:
continue
t = obj.get('type', '')
# 收集工具结果
if t == 'user' and obj.get('toolUseResult'):
msg = obj.get('message', {})
for block in (msg.get('content') if isinstance(msg.get('content'), list) else []):
if isinstance(block, dict) and block.get('type') == 'tool_result':
tid = block.get('tool_use_id', '')
result = block.get('content', '')
if tid not in tool_pool:
tool_pool[tid] = [None, None]
tool_pool[tid][1] = result
# 收集工具调用
elif t == 'assistant':
msg = obj.get('message', {})
for block in (msg.get('content') if isinstance(msg.get('content'), list) else []):
if isinstance(block, dict) and block.get('type') == 'tool_use':
tid = block.get('id', '')
if tid not in tool_pool:
tool_pool[tid] = [None, None]
tool_pool[tid][0] = block
# 第二遍: 生成 Markdown
for line in lines:
try:
obj = json.loads(line)
except:
continue
t = obj.get('type', '')
# ── 用户消息 ──
if t == 'user' and not obj.get('toolUseResult'):
msg = obj.get('message', {})
content = msg.get('content', '')
if isinstance(content, str) and content.strip():
msg_idx += 1
out.append(f"---\n\n## 👤 {msg_idx}\n\n{content}\n\n")
elif t == 'queue-operation' and obj.get('operation') == 'enqueue' and msg_idx == 0:
content = obj.get('content', '')
if isinstance(content, str) and content.strip():
msg_idx += 1
out.append(f"---\n\n## 👤 {msg_idx}\n\n{content}\n\n")
# ── 助手消息 ──
elif t == 'assistant':
msg = obj.get('message', {})
blocks = extract_content_blocks(msg.get('content', []))
if not blocks:
continue
out.append(f"### 🤖 {msg_idx}\n\n")
for btype, bdata in blocks:
if btype == 'thinking':
if THINKING_COLLAPSED:
out.append(f'<details>\n<summary>💭 Thinking ({len(bdata)} chars)</summary>\n\n')
out.append(bdata + '\n')
out.append('</details>\n\n')
else:
out.append(bdata + '\n\n')
elif btype == 'text':
if bdata.strip():
out.append(bdata.strip() + '\n\n')
elif btype == 'tool_use':
tool_idx += 1
name = bdata.get('name', '???')
inp = bdata.get('input', {})
tid = bdata.get('id', '')
# Input
inp_lines = []
for k, v in inp.items():
vs = str(v)
if len(vs) > 200:
vs = vs[:200] + '...'
inp_lines.append(f" - **{k}**: `{esc_md(vs)}`")
inp_text = '\n'.join(inp_lines) if inp_lines else ' *(无参数)*'
# Output
result_text = ''
if tid in tool_pool and tool_pool[tid][1]:
result_text = fmt_json(tool_pool[tid][1])
out.append(f'''<details>
<summary>🔧 <b>{name}</b> #{tool_idx}</summary>
**Input:**
{inp_text}
''')
if result_text:
out.append(f'''**Output:**
```
{result_text}
```
''')
out.append('</details>\n\n')
# ── 整理 ──
text = re.sub(r'\n{4,}', '\n\n\n', ''.join(out))
# Insert TOC after header
toc = ["## 目录\n\n"]
for i in range(1, msg_idx + 1):
toc.append(f"- [👤 {i}](#{i})\n")
toc_text = ''.join(toc)
insert_pos = text.find('---\n\n')
if insert_pos > 0:
text = text[:insert_pos + 5] + '\n' + toc_text + '\n---\n\n' + text[insert_pos + 5:]
with open(output_file, 'w') as f:
f.write(text)
# 统计
tool_count = sum(1 for line in text.split('\n') if line.strip().startswith('<summary>🔧'))
print(f"✅ {output_file}")
print(f" {len(text):,} bytes | {msg_idx} 轮对话 | {tool_count} 个工具调用")
print(f" 工具输入+输出: {'✅' if any('**Output:**' in text for _ in [1]) else '⚠️'}")
if __name__ == '__main__':
if len(sys.argv) < 2:
print(__doc__)
print("用法: python3 cc_export.py <session.jsonl> [output.md]")
sys.exit(1)
main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)