-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport-session.mjs
More file actions
428 lines (366 loc) · 15 KB
/
Copy pathexport-session.mjs
File metadata and controls
428 lines (366 loc) · 15 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
#!/usr/bin/env node
/**
* export-session.mjs
*
* Converts an OpenCode session from the global SQLite database into a
* proper .jsonl event-stream file compatible with the Replay Studio.
*
* Usage:
* node scripts/export-session.mjs --list
* node scripts/export-session.mjs --latest [output.jsonl]
* node scripts/export-session.mjs <session-id|date-fragment> [output.jsonl]
*
* Examples:
* node scripts/export-session.mjs --list
* node scripts/export-session.mjs --latest
* node scripts/export-session.mjs ses_1a9062eb8ffepj1DzblV4ruWwA
* node scripts/export-session.mjs "2026-05-23T235138" my-replay.jsonl
*/
import { execSync } from "node:child_process";
import { basename, resolve } from "node:path";
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
// ── Resolve DB path ────────────────────────────────────────────────────────
const homeDir = process.env.HOME || process.env.USERPROFILE || "";
function uniq(items) {
return [...new Set(items.filter(Boolean))];
}
const opencodeDataDirs = uniq([
process.env.OPENCODE_DATA_DIR,
process.env.XDG_DATA_HOME ? resolve(process.env.XDG_DATA_HOME, "opencode") : null,
homeDir ? resolve(homeDir, ".local", "share", "opencode") : null,
process.env.APPDATA ? resolve(process.env.APPDATA, "opencode") : null,
process.env.LOCALAPPDATA ? resolve(process.env.LOCALAPPDATA, "opencode") : null,
homeDir ? resolve(homeDir, "Library", "Application Support", "opencode") : null,
]);
const dbCandidates = uniq(opencodeDataDirs.map(dir => resolve(dir, "opencode.db")));
const resolvedDb = dbCandidates.find(p => existsSync(p));
if (!resolvedDb) {
console.error("❌ Could not find OpenCode database. Tried:");
dbCandidates.forEach(p => console.error(" " + p));
process.exit(1);
}
// ── sqlite3 helper ─────────────────────────────────────────────────────────
function queryRaw(sql) {
return execSync(`sqlite3 -separator "|" "${resolvedDb}" "${sql.replace(/"/g, '\\"').replace(/\n/g, " ")}"`, {
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
maxBuffer: 100 * 1024 * 1024, // 100 MB
}).trim();
}
function escapeSqlText(value) {
return String(value).replace(/'/g, "''");
}
function parseSessionRow(row) {
const firstPipe = row.indexOf("|");
const lastPipe = row.lastIndexOf("|");
if (firstPipe < 0 || lastPipe <= firstPipe) return null;
return {
id: row.slice(0, firstPipe),
title: row.slice(firstPipe + 1, lastPipe),
timeCreated: parseInt(row.slice(lastPipe + 1), 10),
};
}
function fmtSessionTime(tsMs) {
return new Date(parseInt(tsMs, 10)).toISOString().replace("T", " ").slice(0, 19);
}
function compactTimestampInfo(value) {
const m = String(value).match(/^(\d{4}-\d{2}-\d{2})T?(\d{2})(\d{2})(?:(\d{2}))?$/);
if (!m) return null;
const [, day, hour, minute, rawSecond] = m;
const second = rawSecond || "00";
const iso = `${day}T${hour}:${minute}:${second}.000Z`;
const targetMs = Date.parse(iso);
if (Number.isNaN(targetMs)) return null;
return {
targetMs,
sqlite: `${day} ${hour}:${minute}:${second}`,
title: `${day}T${hour}:${minute}:${second}`,
minuteSqlite: `${day} ${hour}:${minute}`,
minuteTitle: `${day}T${hour}:${minute}`,
};
}
function sessionSearchTerms(input, compact) {
const terms = [String(input)];
if (compact) {
terms.push(compact.sqlite, compact.title, compact.minuteSqlite, compact.minuteTitle);
}
return [...new Set(terms.filter(Boolean))];
}
function printSessionChoices(input, matches) {
console.log(`\n⚠️ Multiple sessions match "${input}". Pick one:\n`);
for (const match of matches) {
console.log(` ${fmtSessionTime(match.timeCreated)} ${match.id} ${(match.title || "").slice(0, 55)}`);
}
console.log("\nRun again with the exact session ID.\n");
}
function logDirCandidates() {
return uniq(opencodeDataDirs.flatMap(dir => [
resolve(dir, "log"),
resolve(dir, "logs"),
]));
}
function latestLogFile() {
const files = [];
for (const dir of logDirCandidates()) {
if (!existsSync(dir)) continue;
for (const name of readdirSync(dir)) {
if (!name.toLowerCase().endsWith(".log")) continue;
const path = resolve(dir, name);
try {
const st = statSync(path);
if (st.isFile()) files.push({ path, mtimeMs: st.mtimeMs, size: st.size });
} catch {}
}
}
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
return files[0]?.path || null;
}
function sessionIdFromLog(path) {
const text = readFileSync(path, "utf8");
const matches = [...text.matchAll(/\b(?:id|session\.id)=(ses_[A-Za-z0-9]+)/g)];
return matches.length ? matches[matches.length - 1][1] : null;
}
function logKeyFromPath(path) {
return basename(path).replace(/\.log$/i, "");
}
// ── CLI args ───────────────────────────────────────────────────────────────
const args = process.argv.slice(2);
if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
console.log(`
OpenCode Session → JSONL Exporter
───────────────────────────────────
Exports a session from the OpenCode SQLite database to the event-stream
.jsonl format compatible with the Replay Studio.
Usage:
node scripts/export-session.mjs --list
List all sessions.
node scripts/export-session.mjs --latest
Export the most recently changed OpenCode log session.
node scripts/export-session.mjs <session-id|date> [output.jsonl]
Export session. <date> can be "2026-05-23T22" or "2026-05-23T235138".
Examples:
node scripts/export-session.mjs --list
node scripts/export-session.mjs --latest
node scripts/export-session.mjs ses_1a9062eb8ffepj1DzblV4ruWwA
node scripts/export-session.mjs "2026-05-23T22" my-session.jsonl
`);
process.exit(0);
}
// ── List mode ──────────────────────────────────────────────────────────────
if (args[0] === "--list" || args[0] === "-l") {
const rows = queryRaw(
"SELECT id, title, time_created FROM session ORDER BY time_created DESC LIMIT 50;"
);
if (!rows) { console.log("No sessions found."); process.exit(0); }
console.log("\n📋 OpenCode Sessions (newest first):\n");
console.log(" " + "─".repeat(100));
for (const row of rows.split("\n")) {
if (!row.trim()) continue;
const parsed = parseSessionRow(row);
if (!parsed) continue;
const date = fmtSessionTime(parsed.timeCreated);
const t = (parsed.title || "(untitled)").slice(0, 55).padEnd(57);
console.log(` ${date} ${parsed.id} ${t}`);
}
console.log(" " + "─".repeat(100));
console.log(`\nTo export: node scripts/export-session.mjs <session-id>\n`);
process.exit(0);
}
// ── Resolve session ID ─────────────────────────────────────────────────────
let sessionId = args[0];
let outputStem = sessionId;
if (sessionId === "--latest" || sessionId === "--last" || sessionId === "latest" || sessionId === "last") {
const logPath = latestLogFile();
if (!logPath) {
console.error("❌ Could not find an OpenCode log file. Tried:");
logDirCandidates().forEach(p => console.error(" " + p));
process.exit(1);
}
outputStem = logKeyFromPath(logPath);
const fromLog = sessionIdFromLog(logPath);
sessionId = fromLog || outputStem;
console.log(`🔍 Latest log: ${logPath}`);
if (fromLog) console.log(`🔍 Session from log: ${fromLog}`);
}
const outputFile = args[1] || `${outputStem.replace(/[^a-zA-Z0-9_-]/g, "_")}.jsonl`;
if (!sessionId.startsWith("ses_")) {
let logPathToCheck = null;
for (const dir of logDirCandidates()) {
const p = resolve(dir, sessionId + (sessionId.endsWith(".log") ? "" : ".log"));
if (existsSync(p)) {
logPathToCheck = p;
break;
}
}
if (logPathToCheck) {
const fromLog = sessionIdFromLog(logPathToCheck);
if (fromLog) {
console.log(`🔍 Found log file: ${logPathToCheck}`);
console.log(`🔍 Extracted session ID: ${fromLog}`);
sessionId = fromLog;
}
}
}
if (!sessionId.startsWith("ses_")) {
// Fuzzy date/title search
const compact = compactTimestampInfo(sessionId);
const terms = sessionSearchTerms(sessionId, compact);
const where = terms.map(term => {
const escaped = escapeSqlText(term);
return `datetime(time_created/1000,'unixepoch') LIKE '%${escaped}%' OR title LIKE '%${escaped}%'`;
}).join(" OR ");
const matchRows = queryRaw(
`SELECT id, title, time_created FROM session WHERE ${where} ORDER BY time_created DESC LIMIT 8;`
);
let matches = matchRows
? matchRows.split("\n").filter(r => r.trim()).map(parseSessionRow).filter(Boolean)
: [];
if (!matches.length && compact) {
const windowMs = 2 * 60 * 1000;
const nearRows = queryRaw(
`SELECT id, title, time_created FROM session WHERE time_created BETWEEN ${compact.targetMs - windowMs} AND ${compact.targetMs + windowMs} ORDER BY ABS(time_created - ${compact.targetMs}) ASC LIMIT 8;`
);
matches = nearRows
? nearRows.split("\n").filter(r => r.trim()).map(parseSessionRow).filter(Boolean)
: [];
}
if (!matches.length) {
console.error(`❌ No sessions matching: "${sessionId}"\n Tip: run --list to see all sessions.`);
process.exit(1);
}
if (matches.length > 1) {
if (compact) {
matches.sort((a, b) =>
Math.abs(a.timeCreated - compact.targetMs) - Math.abs(b.timeCreated - compact.targetMs)
);
const bestDelta = Math.abs(matches[0].timeCreated - compact.targetMs);
if (bestDelta <= 2 * 60 * 1000) {
sessionId = matches[0].id;
const sign = matches[0].timeCreated >= compact.targetMs ? "+" : "-";
console.log(`🔍 Closest session: ${sessionId} (${fmtSessionTime(matches[0].timeCreated)}, ${sign}${(bestDelta / 1000).toFixed(1)}s)`);
} else {
printSessionChoices(sessionId, matches);
process.exit(0);
}
} else {
printSessionChoices(sessionId, matches);
process.exit(0);
}
}
if (!sessionId.startsWith("ses_")) {
sessionId = matches[0].id;
console.log(`🔍 Matched session: ${sessionId} (${fmtSessionTime(matches[0].timeCreated)})`);
}
}
// ── Fetch messages for session context ─────────────────────────────────────
console.log(`\n📦 Loading session: ${sessionId}`);
const msgRaw = queryRaw(
`SELECT id, time_created, data FROM message WHERE session_id='${sessionId}' ORDER BY time_created ASC;`
);
// Build a map: messageId → { time_created, data }
const messageMap = new Map();
if (msgRaw) {
for (const row of msgRaw.split("\n")) {
if (!row.trim()) continue;
// id|time_created|data — data may contain pipes, so split only on first 2
const firstPipe = row.indexOf("|");
const secondPipe = row.indexOf("|", firstPipe + 1);
if (firstPipe < 0 || secondPipe < 0) continue;
const msgId = row.slice(0, firstPipe);
const timeCreated = parseInt(row.slice(firstPipe + 1, secondPipe));
const dataStr = row.slice(secondPipe + 1);
try {
messageMap.set(msgId, { time_created: timeCreated, data: JSON.parse(dataStr) });
} catch {
messageMap.set(msgId, { time_created: timeCreated, data: {} });
}
}
}
// ── Fetch all parts for the session ────────────────────────────────────────
const partRaw = queryRaw(
`SELECT id, message_id, time_created, data FROM part WHERE session_id='${sessionId}' ORDER BY time_created ASC, rowid ASC;`
);
if (!partRaw) {
console.error(`❌ No events found for session: ${sessionId}`);
console.error(` The session may exist but have no content parts.`);
process.exit(1);
}
// ── Convert parts → JSONL event-stream ────────────────────────────────────
const lines = [];
// Map SQLite part type → JSONL envelope type
const typeMap = {
"step-start": "step_start",
"step-finish": "step_finish",
"tool": "tool_use",
"text": "text",
"reasoning": "reasoning",
"snapshot": "snapshot",
"error": "error",
};
for (const row of partRaw.split("\n")) {
if (!row.trim()) continue;
// id|message_id|time_created|data — data may contain pipes, split on first 3
const p1 = row.indexOf("|");
const p2 = row.indexOf("|", p1 + 1);
const p3 = row.indexOf("|", p2 + 1);
if (p1 < 0 || p2 < 0 || p3 < 0) continue;
const partId = row.slice(0, p1);
const messageId = row.slice(p1 + 1, p2);
const timeCreated = parseInt(row.slice(p2 + 1, p3));
const dataStr = row.slice(p3 + 1);
let partData;
try {
partData = JSON.parse(dataStr);
} catch {
continue; // skip invalid JSON
}
const partType = partData.type || "unknown";
const envelopeType = typeMap[partType] || partType;
// Get message context
const msgCtx = messageMap.get(messageId) || {};
const msgData = msgCtx.data || {};
// Build the full part object (enrich with IDs)
const fullPart = {
id: partId,
sessionID: sessionId,
messageID: messageId,
...partData,
};
// For step-finish, attach cost/token data from the message if available
if (partType === "step-finish" && msgData.tokens) {
fullPart.cost = msgData.cost ?? fullPart.cost ?? 0;
if (!fullPart.tokens) {
const t = msgData.tokens;
fullPart.tokens = {
input: t.input || 0,
output: t.output || 0,
cached: (t.cache?.read || 0),
};
}
}
const envelope = {
type: envelopeType,
timestamp: timeCreated || (msgCtx.time_created || Date.now()),
sessionID: sessionId,
part: fullPart,
};
// Attach message role context for user messages
if (msgData.role === "user" && partType === "text") {
envelope.role = "user";
}
lines.push(JSON.stringify(envelope));
}
if (lines.length === 0) {
console.error(`❌ Session exists but no convertible parts were found.`);
process.exit(1);
}
writeFileSync(outputFile, lines.join("\n") + "\n");
console.log(`✅ Exported ${lines.length} events → ${outputFile}\n`);
// Write temporary session data for studio.html
const dataJsPath = resolve(process.cwd(), "session-data.js");
const dataJsContent = `window.__OPENCODE_SESSION__ = { filename: ${JSON.stringify(outputFile)}, text: ${JSON.stringify(lines.join("\n") + "\n")} };`;
writeFileSync(dataJsPath, dataJsContent);
console.log(`🚀 Opening Replay Studio...`);
const studioUrl = `file:///${resolve(process.cwd(), "studio.html").replace(/\\/g, "/")}`;
const startCmd = process.platform === "darwin" ? `open "${studioUrl}"` : process.platform === "win32" ? `start "" "${studioUrl}"` : `xdg-open "${studioUrl}"`;
execSync(startCmd);