-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·243 lines (218 loc) · 8.63 KB
/
cli.js
File metadata and controls
executable file
·243 lines (218 loc) · 8.63 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
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { program } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
const CLAUDE_DIR = path.join(process.env.HOME, '.claude/projects');
function getProjects() {
return fs.readdirSync(CLAUDE_DIR).filter(f => !f.startsWith('.'));
}
function getSessions(project) {
const projectPath = path.join(CLAUDE_DIR, project);
return fs.readdirSync(projectPath)
.filter(f => f.endsWith('.jsonl'))
.map(f => {
const filePath = path.join(projectPath, f);
const stats = fs.statSync(filePath);
return { file: f, path: filePath, size: stats.size, modified: stats.mtime };
})
.sort((a, b) => b.modified - a.modified);
}
function parseSession(filePath) {
const lines = fs.readFileSync(filePath, 'utf8').split('\n').filter(line => line.trim());
return lines.map(line => {
try {
return JSON.parse(line);
} catch (e) {
console.warn(`Skipping invalid JSON line: ${line.substring(0, 50)}...`);
return null;
}
}).filter(Boolean);
}
function analyzeSession(entries) {
const stats = {
userMessages: 0,
assistantMessages: 0,
toolCalls: 0,
toolResults: 0,
subagents: 0,
types: new Set()
};
entries.forEach(e => {
stats.types.add(e.type);
if (e.type === 'user') stats.userMessages++;
if (e.type === 'assistant') stats.assistantMessages++;
if (e.message?.content) {
const content = Array.isArray(e.message.content) ? e.message.content : [e.message.content];
content.forEach(c => {
if (c.type === 'tool_use') stats.toolCalls++;
if (c.type === 'tool_result') stats.toolResults++;
});
}
});
return stats;
}
function getCurrentProject() {
const cwd = process.cwd();
// Claude encodes paths: /Users/foo/My Project -> -Users-foo-My-Project
// Replace both / and spaces with -, strip leading -
const projectKey = cwd.replace(/[/ ]/g, '-').replace(/^-/, '');
const projects = getProjects();
// Try exact match first, then partial match on the last segments
return projects.find(p => p === projectKey)
|| projects.find(p => p.endsWith(projectKey.split('-').slice(-3).join('-')))
|| projects.find(p => p.endsWith(projectKey.split('-').slice(-2).join('-')))
|| null;
}
async function selectSession() {
const projects = getProjects();
const currentProject = getCurrentProject();
let project;
if (currentProject) {
console.log(chalk.cyan(`📁 Detected project: ${currentProject}`));
const { useDetected } = await inquirer.prompt([{
type: 'confirm',
name: 'useDetected',
message: `Use detected project?`,
default: true
}]);
if (useDetected) {
project = currentProject;
}
}
if (!project) {
const answer = await inquirer.prompt([{
type: 'list',
name: 'project',
message: 'Select project:',
choices: projects
}]);
project = answer.project;
}
const sessions = getSessions(project);
const { session } = await inquirer.prompt([{
type: 'list',
name: 'session',
message: 'Select session:',
choices: sessions.map(s => ({
name: `${s.file} (${(s.size/1024/1024).toFixed(2)}MB, ${s.modified.toLocaleDateString()})`,
value: s
}))
}]);
return session;
}
async function interactiveExport() {
const session = await selectSession();
const entries = parseSession(session.path);
const stats = analyzeSession(entries);
console.log(chalk.cyan(`\n📊 Session Stats:`));
console.log(` User messages: ${stats.userMessages}`);
console.log(` Assistant messages: ${stats.assistantMessages}`);
console.log(` Tool calls: ${stats.toolCalls}`);
console.log(` Tool results: ${stats.toolResults}\n`);
const { filters } = await inquirer.prompt([{
type: 'checkbox',
name: 'filters',
message: 'What to include:',
choices: [
{ name: 'User messages', value: 'user', checked: true },
{ name: 'Assistant messages', value: 'assistant', checked: true },
{ name: 'Tool calls (inputs)', value: 'tool_use', checked: true },
{ name: 'Tool results (outputs)', value: 'tool_result', checked: true },
{ name: 'System messages', value: 'system', checked: false },
{ name: 'Progress events', value: 'progress', checked: false },
{ name: 'File snapshots', value: 'file-history-snapshot', checked: false }
]
}]);
const { format } = await inquirer.prompt([{
type: 'list',
name: 'format',
message: 'Export format:',
choices: ['markdown', 'json', 'jsonl', 'xml']
}]);
const filtered = entries.filter(e => {
if (filters.includes(e.type)) return true;
if (e.type === 'assistant' || e.type === 'user') {
if (!e.message?.content) return filters.includes(e.type);
const content = Array.isArray(e.message.content) ? e.message.content : [e.message.content];
const hasMatchingContent = content.some(c =>
(c?.type && filters.includes(c.type)) || filters.includes(e.type)
);
return hasMatchingContent;
}
return false;
});
const output = format === 'markdown' ? toMarkdown(filtered) :
format === 'json' ? JSON.stringify(filtered, null, 2) :
format === 'jsonl' ? filtered.map(e => JSON.stringify(e)).join('\n') :
toXML(filtered);
const outFile = `export-${Date.now()}.${format === 'markdown' ? 'md' : format === 'xml' ? 'xml' : 'json'}`;
fs.writeFileSync(outFile, output);
console.log(chalk.green(`\n✅ Exported ${filtered.length} entries to ${outFile}`));
}
function toMarkdown(entries) {
let md = '# Claude Code Session Export\n\n';
entries.forEach((e, idx) => {
const timestamp = e.timestamp ? new Date(e.timestamp).toLocaleString() : '';
if (e.type === 'user') {
md += `## 👤 User ${timestamp ? `(${timestamp})` : ''}\n`;
if (!e.message) return;
if (typeof e.message.content === 'string') {
md += `${e.message.content}\n\n`;
} else if (Array.isArray(e.message.content)) {
e.message.content.forEach(c => {
if (typeof c === 'string') md += `${c}\n\n`;
else if (c?.type === 'text') md += `${c.text}\n\n`;
else if (c?.type === 'tool_result') {
md += `**📥 Tool Result** \`${c.tool_use_id}\`\n\`\`\`\n${typeof c.content === 'string' ? c.content : JSON.stringify(c.content, null, 2)}\n\`\`\`\n\n`;
} else if (c?.type === 'image') {
md += `**🖼️ Image**: ${c.source?.type || 'unknown'}\n\n`;
}
});
}
} else if (e.type === 'assistant') {
md += `## 🤖 Assistant ${timestamp ? `(${timestamp})` : ''}\n`;
if (!e.message?.content) return;
const content = Array.isArray(e.message.content) ? e.message.content : [e.message.content];
content.forEach(c => {
if (typeof c === 'string') md += `${c}\n\n`;
else if (c?.type === 'text') md += `${c.text}\n\n`;
else if (c?.type === 'tool_use') {
md += `**🔧 Tool: \`${c.name}\`** (ID: \`${c.id}\`)\n\`\`\`json\n${JSON.stringify(c.input, null, 2)}\n\`\`\`\n\n`;
} else if (c?.type === 'thinking') {
md += `**💭 Thinking**\n\`\`\`\n${c.thinking}\n\`\`\`\n\n`;
}
});
} else if (e.type === 'progress') {
md += `_⏳ Progress: ${e.data?.type || 'unknown'}_\n\n`;
} else if (e.type === 'system') {
md += `**⚙️ System**\n\`\`\`\n${typeof e.message === 'string' ? e.message : JSON.stringify(e.message, null, 2)}\n\`\`\`\n\n`;
}
});
return md;
}
function toXML(entries) {
const escape = s => String(s).replace(/[<>&'"]/g, c => ({'<':'<','>':'>','&':'&',"'":''','"':'"'}[c]));
let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<session>\n';
entries.forEach(e => {
xml += ` <entry type="${e.type}" timestamp="${e.timestamp || ''}" uuid="${e.uuid || ''}">\n`;
if (e.message?.content) {
const content = Array.isArray(e.message.content) ? e.message.content : [e.message.content];
content.forEach(c => {
if (typeof c === 'string') xml += ` <text>${escape(c)}</text>\n`;
else if (c?.type === 'text') xml += ` <text>${escape(c.text)}</text>\n`;
else if (c?.type === 'tool_use') xml += ` <tool_use name="${c.name}" id="${c.id}">${escape(JSON.stringify(c.input))}</tool_use>\n`;
else if (c?.type === 'tool_result') xml += ` <tool_result id="${c.tool_use_id}">${escape(typeof c.content === 'string' ? c.content : JSON.stringify(c.content))}</tool_result>\n`;
});
}
xml += ` </entry>\n`;
});
xml += '</session>';
return xml;
}
program
.name('claude-export')
.description('Export Claude Code sessions with full control')
.action(interactiveExport);
program.parse();