-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-persistence.js
More file actions
404 lines (340 loc) · 12.7 KB
/
Copy pathsession-persistence.js
File metadata and controls
404 lines (340 loc) · 12.7 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
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const { createSessionQueryEnhancer } = require('./session-query-enhancer');
const { createSessionListAdapter } = require('./cache/adapters/session-list');
const { createSessionDetailAdapter } = require('./cache/adapters/session-detail');
const DB_PATH = path.join(process.env.HOME, '.local/share/opencode/opencode.db');
let sqliteQueue = Promise.resolve();
function sqliteJson(query) {
const task = () => new Promise((resolve, reject) => {
const proc = spawn('sqlite3', [DB_PATH, '-json', query]);
let stdout = '';
let stderr = '';
proc.stdout.on('data', d => stdout += d);
proc.stderr.on('data', d => stderr += d);
proc.on('close', code => {
if (code !== 0) return reject(new Error(stderr || `sqlite3 exited ${code}`));
try {
resolve(JSON.parse(stdout || '[]'));
} catch (e) {
reject(e);
}
});
});
const result = sqliteQueue.then(task, task);
sqliteQueue = result.catch(() => {});
return result;
}
const queryEnhancer = createSessionQueryEnhancer({ sqliteJson });
const getSessions = queryEnhancer.getEnrichedSessions;
async function getSession(sessionId) {
const sid = sessionId.replace(/'/g, "''");
const rows = await sqliteJson(
`SELECT id, title, directory, time_created, time_updated, COALESCE(model, '') as model, COALESCE(agent, '') as agent FROM session WHERE id = '${sid}'`
);
return rows[0] || null;
}
async function getMessages(sessionId) {
const sid = sessionId.replace(/'/g, "''");
const rows = await sqliteJson(`
SELECT m.id, m.time_created, m.data,
(SELECT json_group_array(json_object('id', p.id, 'time_created', p.time_created, 'data', p.data))
FROM part p WHERE p.message_id = m.id ORDER BY p.time_created) as parts
FROM message m
WHERE m.session_id = '${sid}'
ORDER BY m.time_created
`);
return rows.map(row => {
const msgData = JSON.parse(row.data || '{}');
const parts = JSON.parse(row.parts || '[]').map(part => {
try {
return JSON.parse(part.data);
} catch (e) {
return { type: 'unknown', data: part.data };
}
});
return {
id: row.id,
timeCreated: row.time_created,
role: msgData.role || 'unknown',
parts
};
});
}
const defaultDb = { getSessions, getSession, getMessages };
function sanitizeFileName(str) {
return str.replace(/[\\/:*?"<>|]/g, '_').substring(0, 80);
}
function formatDate(ts) {
return new Date(ts).toISOString();
}
function escapeYaml(str) {
if (!str) return '';
if (/[":\n]/.test(str)) return JSON.stringify(str);
return str;
}
function createSessionPathPolicy({ sessionsDir } = {}) {
const dir = sessionsDir || path.join(__dirname, '..', 'opencode-sessions');
function resolveSessionPath(name) {
const fullPath = path.join(dir, path.basename(name));
const resolved = path.resolve(fullPath);
const resolvedDir = path.resolve(dir);
if (!resolved.startsWith(resolvedDir + path.sep)) return null;
return resolved;
}
function getSessionFilePath(sessionId, title) {
const safeTitle = sanitizeFileName(title || 'Untitled');
const fileName = `${sessionId}--${safeTitle}.md`;
return path.join(dir, fileName);
}
return { resolveSessionPath, getSessionFilePath, sessionsDir: dir };
}
function createSessionMarkdownRenderer() {
function renderSessionMarkdown(session, messages) {
let md = `---\n`;
md += `session_id: ${session.id}\n`;
md += `title: ${escapeYaml(session.title || 'Untitled')}\n`;
md += `created: ${formatDate(session.time_created)}\n`;
md += `updated: ${formatDate(session.time_updated)}\n`;
md += `model: ${session.model || ''}\n`;
md += `agent: ${session.agent || ''}\n`;
md += `messages: ${messages.length}\n`;
md += `---\n\n`;
md += `# ${session.title || 'Untitled'}\n\n`;
for (const msg of messages) {
if (!msg.parts || msg.parts.length === 0) continue;
const role = msg.role || 'unknown';
const roleLabel = role.charAt(0).toUpperCase() + role.slice(1);
md += `## ${roleLabel}\n\n`;
for (const part of msg.parts) {
switch (part.type) {
case 'text': {
if (part.text) md += `${part.text}\n\n`;
break;
}
case 'reasoning': {
if (part.text) {
const quoted = part.text.split('\n').map(l => `> ${l}`).join('\n');
md += `> **Thinking**\n${quoted}\n\n`;
}
break;
}
case 'tool': {
md += `**Tool: ${part.tool}** (\`${part.callID || 'unknown'}\`)\n\n`;
if (part.state && part.state.input) {
let inputStr = typeof part.state.input === 'string'
? part.state.input
: JSON.stringify(part.state.input, null, 2);
if (inputStr.length > 5000) inputStr = inputStr.slice(0, 5000) + '\n... [truncated]';
md += `\`\`\`json\n${inputStr}\n\`\`\`\n\n`;
}
if (part.state && part.state.output !== undefined) {
let outputStr = typeof part.state.output === 'string'
? part.state.output
: JSON.stringify(part.state.output, null, 2);
if (outputStr.length > 8000) outputStr = outputStr.slice(0, 8000) + '\n... [truncated]';
md += `\`\`\`\n${outputStr}\n\`\`\`\n\n`;
}
break;
}
// skip: step-start, step-finish, patch, file, subtask, compaction, retry
}
}
}
return md;
}
return { renderSessionMarkdown };
}
function createSessionPersistence({ db, cacheDb, files, markdown, paths, sessionsDir } = {}) {
let adapter = db;
if (!adapter && cacheDb) {
const listAdapter = createSessionListAdapter({ cacheDb });
const detailAdapter = createSessionDetailAdapter({ cacheDb });
adapter = {
getSessions: async () => listAdapter.getEnrichedSessions(),
getSession: async (id) => {
const session = detailAdapter.getSessionWithMessages(id);
if (!session) return null;
return {
id: session.id,
title: session.title,
directory: session.directory,
time_created: session.created,
time_updated: session.updated,
model: session.model,
agent: session.agent
};
},
getMessages: async (id) => {
const session = detailAdapter.getSessionWithMessages(id);
return session ? session.messages : [];
}
};
}
if (!adapter) {
adapter = defaultDb;
}
const cache = cacheDb || null;
const fileSystem = files || fs;
const renderer = markdown || createSessionMarkdownRenderer();
const pathPolicy = paths || createSessionPathPolicy({ sessionsDir });
async function listSessions() {
return adapter.getSessions();
}
async function getSessionWithMessages(id) {
const session = await adapter.getSession(id);
if (!session) return null;
const messages = await adapter.getMessages(id);
return {
id: session.id,
title: session.title || 'Untitled',
directory: session.directory || null,
created: session.time_created,
updated: session.time_updated,
model: session.model || null,
agent: session.agent || null,
messages
};
}
async function ensureMarkdownFile(id) {
const session = await adapter.getSession(id);
if (!session) {
throw new Error(`Session not found: ${id}`);
}
const filePath = pathPolicy.getSessionFilePath(session.id, session.title);
const resolvedPath = pathPolicy.resolveSessionPath(filePath);
if (!resolvedPath) {
throw new Error('Access denied: path traversal detected');
}
if (!fileSystem.existsSync(pathPolicy.sessionsDir)) {
fileSystem.mkdirSync(pathPolicy.sessionsDir, { recursive: true });
}
if (fileSystem.existsSync(resolvedPath)) {
return { session, markdownPath: resolvedPath, created: false };
}
const messages = await adapter.getMessages(id);
const md = renderer.renderSessionMarkdown(session, messages);
fileSystem.writeFileSync(resolvedPath, md, 'utf-8');
return { session, markdownPath: resolvedPath, created: true };
}
async function exportSession(id, toPath) {
const session = await adapter.getSession(id);
if (!session) {
throw new Error(`Session not found: ${id}`);
}
const messages = await adapter.getMessages(id);
const md = renderer.renderSessionMarkdown(session, messages);
const filePath = toPath || pathPolicy.getSessionFilePath(session.id, session.title);
const resolvedPath = pathPolicy.resolveSessionPath(filePath);
if (!resolvedPath) {
throw new Error('Access denied: path traversal detected');
}
if (!fileSystem.existsSync(pathPolicy.sessionsDir)) {
fileSystem.mkdirSync(pathPolicy.sessionsDir, { recursive: true });
}
fileSystem.writeFileSync(resolvedPath, md, 'utf-8');
// Write-through cache: update session time_updated to reflect activity
if (cache) {
const now = Date.now();
cache.prepare('UPDATE session SET time_updated = ? WHERE id = ?').run(now, id);
}
return { markdownPath: resolvedPath };
}
async function appendUserMessage(id, text) {
const session = await adapter.getSession(id);
if (!session) {
throw new Error(`Session not found: ${id}`);
}
const filePath = pathPolicy.getSessionFilePath(session.id, session.title);
const resolvedPath = pathPolicy.resolveSessionPath(filePath);
if (!resolvedPath) {
throw new Error('Access denied: path traversal detected');
}
if (!fileSystem.existsSync(pathPolicy.sessionsDir)) {
fileSystem.mkdirSync(pathPolicy.sessionsDir, { recursive: true });
}
if (!fileSystem.existsSync(resolvedPath)) {
const messages = await adapter.getMessages(id);
const md = renderer.renderSessionMarkdown(session, messages);
fileSystem.writeFileSync(resolvedPath, md, 'utf-8');
}
const appendage = `## User\n\n${text.trim()}\n\n`;
fileSystem.appendFileSync(resolvedPath, appendage, 'utf-8');
// Write-through cache: update session time_updated to reflect activity
if (cache) {
const now = Date.now();
cache.prepare('UPDATE session SET time_updated = ? WHERE id = ?').run(now, id);
}
return { session, markdownPath: resolvedPath };
}
async function exportAll(options = {}) {
const overwrite = options.overwrite !== false;
const onProgress = options.onProgress || (() => {});
const targetDir = options.outDir || pathPolicy.sessionsDir;
const targetPolicy = options.outDir
? createSessionPathPolicy({ sessionsDir: options.outDir })
: pathPolicy;
const sessions = await adapter.getSessions();
const files = [];
let exported = 0;
const usedPaths = new Set();
for (let i = 0; i < sessions.length; i++) {
const session = sessions[i];
const fullSession = await adapter.getSession(session.id);
if (!fullSession) continue;
const messages = await adapter.getMessages(session.id);
const md = renderer.renderSessionMarkdown(fullSession, messages);
let filePath = targetPolicy.getSessionFilePath(fullSession.id, fullSession.title);
let resolvedPath = targetPolicy.resolveSessionPath(filePath);
if (!resolvedPath) {
throw new Error('Access denied: path traversal detected');
}
let uniquePath = resolvedPath;
let counter = 1;
while (usedPaths.has(uniquePath)) {
const base = filePath.replace(/\.md$/, '');
const newFilePath = `${base}-${counter}.md`;
uniquePath = targetPolicy.resolveSessionPath(newFilePath);
counter++;
}
usedPaths.add(uniquePath);
if (!overwrite && fileSystem.existsSync(uniquePath)) {
continue;
}
if (!fileSystem.existsSync(targetPolicy.sessionsDir)) {
fileSystem.mkdirSync(targetPolicy.sessionsDir, { recursive: true });
}
fileSystem.writeFileSync(uniquePath, md, 'utf-8');
files.push({ sessionId: fullSession.id, filePath: uniquePath });
exported++;
onProgress({
session,
index: i,
total: sessions.length,
filePath: uniquePath
});
}
return { exported, files };
}
function getMessageCount(sessionId) {
if (!cache) return 0;
const result = cache.prepare('SELECT COUNT(*) as count FROM message WHERE session_id = ?').get(sessionId);
return result ? result.count : 0;
}
return {
listSessions,
getSessionWithMessages,
ensureMarkdownFile,
exportSession,
appendUserMessage,
exportAll,
getMessageCount
};
}
module.exports = {
createSessionPersistence,
createSessionPathPolicy,
createSessionMarkdownRenderer,
sqliteJson
};