-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport_session.py
More file actions
92 lines (78 loc) · 2.71 KB
/
Copy pathexport_session.py
File metadata and controls
92 lines (78 loc) · 2.71 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
"""导出指定的 Claude Code session"""
import json
import os
import sys
import glob
from datetime import datetime
session_id = sys.argv[1] if len(sys.argv) > 1 else ''
output_dir = sys.argv[2] if len(sys.argv) > 2 else 'D:/信息总结'
if not session_id:
print('{"error": "Missing session_id"}')
sys.exit(1)
# 查找session文件(使用glob代替find,兼容Windows)
projects_dir = os.path.expanduser('~/.claude/projects')
pattern = os.path.join(projects_dir, '**', f'*{session_id}*.jsonl')
matches = glob.glob(pattern, recursive=True)
if not matches:
print(json.dumps({'error': f'Session not found: {session_id}'}))
sys.exit(1)
session_file = matches[0]
# 解析session
messages = []
project_path = ''
with open(session_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
data = json.loads(line)
if not project_path:
project_path = data.get('cwd', '')
if data.get('type') == 'user':
content = data.get('message', {}).get('content', '')
ts = data.get('timestamp', '')
messages.append({'role': 'user', 'content': content, 'timestamp': ts})
elif data.get('type') == 'assistant':
msg = data.get('message', {})
content_parts = msg.get('content', [])
text = ''
for part in content_parts:
if part.get('type') == 'text':
text += part.get('text', '')
ts = data.get('timestamp', '')
if text.strip():
messages.append({'role': 'assistant', 'content': text, 'timestamp': ts})
except:
continue
# 生成 Markdown
short_id = session_id[:8]
output_file = os.path.join(output_dir, f'session_{short_id}_export.md')
md_content = f'''# Session Export: {session_id}
**Project:** {project_path}
**Exported:** {datetime.now().strftime('%Y-%m-%d %H:%M')}
**Total Messages:** {len(messages)}
---
'''
for msg in messages:
role = '**User**' if msg['role'] == 'user' else '**Claude**'
ts = msg.get('timestamp', '')
if ts:
try:
dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
ts_str = dt.strftime('%H:%M:%S')
except:
ts_str = ''
else:
ts_str = ''
md_content += f'## {role} ({ts_str})\n\n{msg["content"]}\n\n---\n\n'
with open(output_file, 'w', encoding='utf-8') as f:
f.write(md_content)
print(json.dumps({
'success': True,
'session_id': session_id,
'short_id': short_id,
'project': project_path,
'messages': len(messages),
'output_file': output_file
}, ensure_ascii=False))