dsh-plugin-external-session-sync 1.2.1 → 1.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -21
- package/README.md +129 -127
- package/client.js +127 -12
- package/engine.js +23 -94
- package/index.js +153 -11
- package/package.json +3 -2
- package/readers-antigravity.js +306 -0
- package/reverse.js +451 -0
- package/cleanup.js +0 -99
package/reverse.js
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
// Reverse sync: append the turns that only exist in a DSH session back into the Codex
|
|
2
|
+
// conversation that was imported ("fork" -> "main").
|
|
3
|
+
//
|
|
4
|
+
// Safety rules this module keeps:
|
|
5
|
+
// - Codex rollout files are append-only. Nothing is rewritten or reordered.
|
|
6
|
+
// - A turn is only written when the conversation still has a rollout file on disk; a
|
|
7
|
+
// thread that exists only in Codex's index cannot be recovered by writing a new file.
|
|
8
|
+
// - Every append is preceded by a byte copy of the target file and followed by a
|
|
9
|
+
// re-read that must show the new messages.
|
|
10
|
+
// - Dry run is the default: it returns the exact records that would be appended.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import zlib from 'node:zlib';
|
|
16
|
+
import { codexFilesForThread } from './readers.js';
|
|
17
|
+
|
|
18
|
+
const BACKUP_SUFFIX = '.reverse-sync-backup';
|
|
19
|
+
|
|
20
|
+
const textOf = (content) =>
|
|
21
|
+
(Array.isArray(content) ? content : [])
|
|
22
|
+
.filter((part) => part && (part.type === 'text' || part.type === 'output_text' || part.type === 'input_text'))
|
|
23
|
+
.map((part) => part.text || '')
|
|
24
|
+
.join('');
|
|
25
|
+
|
|
26
|
+
// DSH stores runtime context as user/message events: workspace reminders, the runtime
|
|
27
|
+
// snapshot, the skill catalog and the turn timestamp. They are not something the user
|
|
28
|
+
// said, so they must never be written back into another tool's history.
|
|
29
|
+
const INJECTED_HEAD = /^(<system-reminder|Current runtime context\.|Time sampled while preparing|<environment_context|<user_instructions)/;
|
|
30
|
+
|
|
31
|
+
export function cleanUserText(text) {
|
|
32
|
+
let value = String(text || '');
|
|
33
|
+
const cut = value.indexOf('<system-reminder');
|
|
34
|
+
if (cut > 0) value = value.slice(0, cut);
|
|
35
|
+
if (INJECTED_HEAD.test(value.trimStart())) return '';
|
|
36
|
+
return value.trim();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Ordered visible messages of a DSH session, each tagged with the turn it belongs to. */
|
|
40
|
+
export function sessionMessages(events) {
|
|
41
|
+
const messages = [];
|
|
42
|
+
let turn = 0;
|
|
43
|
+
for (const event of events) {
|
|
44
|
+
if (event.type === 'turn/start') {
|
|
45
|
+
turn = event.data?.turn ?? turn + 1;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (event.type === 'user/message') {
|
|
49
|
+
const text = cleanUserText(textOf(event.data?.content));
|
|
50
|
+
if (text) messages.push({ role: 'user', text, time: event.time, turn });
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (event.type === 'assistant/message') {
|
|
54
|
+
const text = textOf(event.data?.message?.content).trim();
|
|
55
|
+
if (text) messages.push({ role: 'assistant', text, time: event.time, turn });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return messages;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Group messages into writable turns: user message plus the assistant replies that follow it. */
|
|
62
|
+
export function pendingTurns(messages, importedCount) {
|
|
63
|
+
const pending = messages.slice(Math.max(0, importedCount));
|
|
64
|
+
const turns = [];
|
|
65
|
+
for (const message of pending) {
|
|
66
|
+
if (message.role === 'user') {
|
|
67
|
+
turns.push({ user: message, assistants: [] });
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (!turns.length) {
|
|
71
|
+
// An assistant message with no preceding user message cannot start a Codex turn.
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
turns.at(-1).assistants.push(message);
|
|
75
|
+
}
|
|
76
|
+
return turns.filter((turn) => turn.assistants.length);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function readRolloutFacts(file) {
|
|
80
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
81
|
+
const lines = text.split('\n').filter((line) => line.trim());
|
|
82
|
+
let threadId = null;
|
|
83
|
+
let modelContextWindow = 258400;
|
|
84
|
+
let lastOrdinal = -1;
|
|
85
|
+
let lastTimestamp = null;
|
|
86
|
+
let contextTemplate = null;
|
|
87
|
+
for (const line of lines) {
|
|
88
|
+
let record;
|
|
89
|
+
try { record = JSON.parse(line); } catch { continue; }
|
|
90
|
+
if (record.type === 'session_meta') {
|
|
91
|
+
threadId = record.payload?.session_id || record.payload?.id || null;
|
|
92
|
+
modelContextWindow = record.payload?.context_window || modelContextWindow;
|
|
93
|
+
}
|
|
94
|
+
if (record.payload?.type === 'task_started' && record.payload.model_context_window) {
|
|
95
|
+
modelContextWindow = record.payload.model_context_window;
|
|
96
|
+
}
|
|
97
|
+
// Codex writes one turn_context per turn; reuse the previous one so an appended turn
|
|
98
|
+
// carries the same model, cwd and sandbox policy instead of looking foreign.
|
|
99
|
+
if (record.type === 'turn_context' && record.payload) contextTemplate = record.payload;
|
|
100
|
+
if (Number.isInteger(record.ordinal)) lastOrdinal = Math.max(lastOrdinal, record.ordinal);
|
|
101
|
+
if (record.timestamp) lastTimestamp = record.timestamp;
|
|
102
|
+
}
|
|
103
|
+
return { threadId, modelContextWindow, lastOrdinal, lastTimestamp, contextTemplate, recordCount: lines.length };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Build the Codex records for one DSH turn, mirroring what Codex itself writes. */
|
|
107
|
+
export function turnRecords({ threadId, turn, ordinal, modelContextWindow, contextTemplate }) {
|
|
108
|
+
const startedMs = Number(turn.user.time) || Date.now();
|
|
109
|
+
const completedMs = Number(turn.assistants.at(-1)?.time) || startedMs;
|
|
110
|
+
const turnId = crypto.randomUUID();
|
|
111
|
+
const userId = 'msg_' + crypto.randomUUID();
|
|
112
|
+
const assistantId = 'msg_' + crypto.randomUUID();
|
|
113
|
+
const assistantText = turn.assistants.map((message) => message.text).join('\n\n');
|
|
114
|
+
const records = [];
|
|
115
|
+
const push = (type, payload, metadata) => {
|
|
116
|
+
const record = { timestamp: new Date(startedMs + records.length).toISOString(), ordinal: ordinal + records.length, type, payload };
|
|
117
|
+
if (metadata !== undefined) record.metadata = metadata;
|
|
118
|
+
records.push(record);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
push('event_msg', {
|
|
122
|
+
type: 'task_started',
|
|
123
|
+
turn_id: turnId,
|
|
124
|
+
root_turn_id: turnId,
|
|
125
|
+
started_at: Math.floor(startedMs / 1000),
|
|
126
|
+
model_context_window: modelContextWindow,
|
|
127
|
+
collaboration_mode_kind: 'default',
|
|
128
|
+
});
|
|
129
|
+
if (contextTemplate) {
|
|
130
|
+
push('turn_context', { ...contextTemplate, turn_id: turnId, root_turn_id: turnId });
|
|
131
|
+
}
|
|
132
|
+
push(
|
|
133
|
+
'response_item',
|
|
134
|
+
{
|
|
135
|
+
type: 'message',
|
|
136
|
+
id: userId,
|
|
137
|
+
role: 'user',
|
|
138
|
+
content: [{ type: 'input_text', text: turn.user.text }],
|
|
139
|
+
internal_chat_message_metadata_passthrough: {
|
|
140
|
+
turn_id: turnId,
|
|
141
|
+
create_time: startedMs / 1000,
|
|
142
|
+
content_item_kinds: ['user.text'],
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
{ client_authored: false, user_input_order: 0, mcp_attribution: { status: 'attribution_error' } },
|
|
146
|
+
);
|
|
147
|
+
push('event_msg', {
|
|
148
|
+
type: 'item_completed',
|
|
149
|
+
thread_id: threadId,
|
|
150
|
+
turn_id: turnId,
|
|
151
|
+
item: {
|
|
152
|
+
type: 'UserMessage',
|
|
153
|
+
id: 'item_' + crypto.randomUUID(),
|
|
154
|
+
client_id: crypto.randomUUID(),
|
|
155
|
+
content: [{ type: 'text', text: turn.user.text, text_elements: [] }],
|
|
156
|
+
},
|
|
157
|
+
started_at_ms: startedMs,
|
|
158
|
+
completed_at_ms: startedMs,
|
|
159
|
+
});
|
|
160
|
+
push(
|
|
161
|
+
'response_item',
|
|
162
|
+
{
|
|
163
|
+
type: 'message',
|
|
164
|
+
id: assistantId,
|
|
165
|
+
role: 'assistant',
|
|
166
|
+
content: [{ type: 'output_text', text: assistantText }],
|
|
167
|
+
},
|
|
168
|
+
{ client_authored: true, user_input_order: 0 },
|
|
169
|
+
);
|
|
170
|
+
push('event_msg', {
|
|
171
|
+
type: 'item_completed',
|
|
172
|
+
thread_id: threadId,
|
|
173
|
+
turn_id: turnId,
|
|
174
|
+
item: { type: 'AgentMessage', id: assistantId, content: [{ type: 'Text', text: assistantText }] },
|
|
175
|
+
started_at_ms: completedMs,
|
|
176
|
+
completed_at_ms: completedMs,
|
|
177
|
+
});
|
|
178
|
+
push('event_msg', { type: 'task_complete', turn_id: turnId, last_agent_message: assistantText });
|
|
179
|
+
return records;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function targetRollout(threadId) {
|
|
183
|
+
let files = [];
|
|
184
|
+
try { files = codexFilesForThread(threadId) || []; } catch { files = []; }
|
|
185
|
+
const existing = files.filter((file) => fs.existsSync(file));
|
|
186
|
+
if (!existing.length) return null;
|
|
187
|
+
const withStats = existing.map((file) => ({ file, stat: fs.statSync(file) }));
|
|
188
|
+
withStats.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
|
|
189
|
+
return withStats[0].file;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Describe what a reverse sync would do for one imported session. */
|
|
193
|
+
export function planReverse({ sessionId, events, entry }) {
|
|
194
|
+
const messages = sessionMessages(events);
|
|
195
|
+
const importedCount = Number(entry?.messages) || 0;
|
|
196
|
+
const alreadyReversed = Number(entry?.reverseThrough) || 0;
|
|
197
|
+
const turns = pendingTurns(messages, importedCount + alreadyReversed);
|
|
198
|
+
// An imported mapping is keyed `source:externalId`; the thread id is the external id.
|
|
199
|
+
const key = String(entry?.key || '');
|
|
200
|
+
const threadId = entry?.externalId || (key ? key.slice(key.indexOf(':') + 1) : null);
|
|
201
|
+
const target = threadId ? targetRollout(threadId) : null;
|
|
202
|
+
return { sessionId, messages: messages.length, importedCount, alreadyReversed, turns, threadId, target };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function appendTurns(target, records) {
|
|
206
|
+
const backup = `${target}${BACKUP_SUFFIX}-${Date.now()}`;
|
|
207
|
+
fs.copyFileSync(target, backup);
|
|
208
|
+
const text = records.map((record) => JSON.stringify(record)).join('\n') + '\n';
|
|
209
|
+
fs.appendFileSync(target, text, 'utf8');
|
|
210
|
+
// Re-read the tail so a malformed write is caught immediately.
|
|
211
|
+
const tail = fs.readFileSync(target, 'utf8').split('\n').filter((line) => line.trim());
|
|
212
|
+
const parsed = tail.slice(-records.length).map((line) => JSON.parse(line));
|
|
213
|
+
const ok = parsed.length === records.length && parsed.every((record, index) => record.ordinal === records[index].ordinal);
|
|
214
|
+
return { backup, appended: records.length, verified: ok };
|
|
215
|
+
}
|
|
216
|
+
/* ------------------------------------------------------------------ *
|
|
217
|
+
* Fork resolution: DSH "fork conversation" copies an imported session *
|
|
218
|
+
* into a new session whose header names `parentSession`. The copy is *
|
|
219
|
+
* the seeded prefix, so the fork's own turns are everything after the *
|
|
220
|
+
* parent's messages. The Codex thread to write back to is the one the *
|
|
221
|
+
* imported ancestor was mapped to. *
|
|
222
|
+
* ------------------------------------------------------------------ */
|
|
223
|
+
const SESSIONS_ROOT = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'sessions');
|
|
224
|
+
|
|
225
|
+
export function sessionLogFile(sessionId) {
|
|
226
|
+
let slugs = [];
|
|
227
|
+
try {
|
|
228
|
+
slugs = fs.readdirSync(SESSIONS_ROOT, { withFileTypes: true }).filter((entry) => entry.isDirectory());
|
|
229
|
+
} catch {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
for (const slug of slugs) {
|
|
233
|
+
const dir = path.join(SESSIONS_ROOT, slug.name, sessionId);
|
|
234
|
+
if (!fs.existsSync(dir)) continue;
|
|
235
|
+
for (const name of ['session.v4.jsonl.zstd', 'session.v4.jsonl', 'session.jsonl.zstd', 'session.jsonl']) {
|
|
236
|
+
const file = path.join(dir, name);
|
|
237
|
+
if (fs.existsSync(file)) return file;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** First record of a session log, decoded from the first zstd frame when needed. */
|
|
244
|
+
export function readSessionHeader(sessionId) {
|
|
245
|
+
const file = sessionLogFile(sessionId);
|
|
246
|
+
if (!file) return null;
|
|
247
|
+
const buf = fs.readFileSync(file);
|
|
248
|
+
let text;
|
|
249
|
+
if (file.endsWith('.zstd')) {
|
|
250
|
+
const magic = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
251
|
+
const frames = [];
|
|
252
|
+
for (let i = 0; i + 3 < buf.length; i++) {
|
|
253
|
+
if (buf[i] === 0x28 && buf[i + 1] === 0xb5 && buf[i + 2] === 0x2f && buf[i + 3] === 0xfd) frames.push(i);
|
|
254
|
+
}
|
|
255
|
+
frames.push(buf.length);
|
|
256
|
+
const chunks = [];
|
|
257
|
+
for (let f = 0; f + 1 < frames.length; f++) {
|
|
258
|
+
const slice = buf.subarray(frames[f], frames[f + 1]);
|
|
259
|
+
if (slice.length < 8) continue;
|
|
260
|
+
try { chunks.push(zlib.zstdDecompressSync(slice).toString('utf8')); } catch { continue; }
|
|
261
|
+
if (chunks.join('').includes('\n')) break;
|
|
262
|
+
}
|
|
263
|
+
text = chunks.join('');
|
|
264
|
+
} else {
|
|
265
|
+
text = buf.toString('utf8');
|
|
266
|
+
}
|
|
267
|
+
for (const line of text.split('\n')) {
|
|
268
|
+
if (!line.trim()) continue;
|
|
269
|
+
try {
|
|
270
|
+
const record = JSON.parse(line);
|
|
271
|
+
if (record.type === 'session') return { file, header: record };
|
|
272
|
+
} catch {
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return { file, header: null };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** `sessionMessages` comparison used to prove a fork prefix really copies its parent. */
|
|
280
|
+
export function prefixMatches(child, parent) {
|
|
281
|
+
if (parent.length > child.length) return false;
|
|
282
|
+
return parent.every((message, index) => child[index] && child[index].role === message.role && child[index].text === message.text);
|
|
283
|
+
}
|
|
284
|
+
/* ------------------------------------------------------------------ *
|
|
285
|
+
* Export mode: a session with no external origin (or a fork whose *
|
|
286
|
+
* ancestor was never imported) has no "main" to append to, so the *
|
|
287
|
+
* whole conversation becomes a new Codex thread. *
|
|
288
|
+
* ------------------------------------------------------------------ */
|
|
289
|
+
export function newRolloutPath(threadId, startedAtMs = Date.now()) {
|
|
290
|
+
const date = new Date(startedAtMs);
|
|
291
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
292
|
+
const dir = path.join(
|
|
293
|
+
process.env.CODEX_HOME || path.join(os.homedir(), '.codex'),
|
|
294
|
+
'sessions',
|
|
295
|
+
String(date.getFullYear()),
|
|
296
|
+
pad(date.getMonth() + 1),
|
|
297
|
+
pad(date.getDate()),
|
|
298
|
+
);
|
|
299
|
+
const stamp = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}-${pad(date.getMinutes())}-${pad(date.getSeconds())}`;
|
|
300
|
+
return path.join(dir, `rollout-${stamp}-${threadId}.jsonl`);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** session_meta plus one record sequence per turn, in Codex's own shape. */
|
|
304
|
+
export function exportRecords({ threadId, cwd, startedAtMs, turns, contextTemplate, modelContextWindow }) {
|
|
305
|
+
const records = [];
|
|
306
|
+
const header = {
|
|
307
|
+
timestamp: new Date(startedAtMs).toISOString(),
|
|
308
|
+
ordinal: 0,
|
|
309
|
+
type: 'session_meta',
|
|
310
|
+
payload: {
|
|
311
|
+
session_id: threadId,
|
|
312
|
+
id: threadId,
|
|
313
|
+
timestamp: new Date(startedAtMs).toISOString(),
|
|
314
|
+
cwd,
|
|
315
|
+
runtime_workspace_roots: [cwd],
|
|
316
|
+
originator: 'Codex Desktop',
|
|
317
|
+
cli_version: '0.166.0',
|
|
318
|
+
source: 'vscode',
|
|
319
|
+
thread_source: 'user',
|
|
320
|
+
model_provider: 'custom',
|
|
321
|
+
history_mode: 'full',
|
|
322
|
+
context_window: modelContextWindow || 475000,
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
records.push(header);
|
|
326
|
+
for (const turn of turns) {
|
|
327
|
+
records.push(
|
|
328
|
+
...turnRecords({
|
|
329
|
+
threadId,
|
|
330
|
+
turn,
|
|
331
|
+
ordinal: records.length,
|
|
332
|
+
modelContextWindow: modelContextWindow || 475000,
|
|
333
|
+
contextTemplate,
|
|
334
|
+
}),
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
return records;
|
|
338
|
+
}
|
|
339
|
+
/* ------------------------------------------------------------------ *
|
|
340
|
+
* Session reader: DSH's controller surface has changed across releases *
|
|
341
|
+
* (`sessionController.inspect` disappeared from this profile), so the *
|
|
342
|
+
* plugin reads the stored log itself. This path is strictly read-only. *
|
|
343
|
+
* ------------------------------------------------------------------ */
|
|
344
|
+
const ZSTD_MAGIC = [0x28, 0xb5, 0x2f, 0xfd];
|
|
345
|
+
const eventCache = new Map();
|
|
346
|
+
|
|
347
|
+
export function decodeSessionLines(file) {
|
|
348
|
+
const buf = fs.readFileSync(file);
|
|
349
|
+
if (!file.endsWith('.zstd')) return buf.toString('utf8').split('\n').filter((line) => line.trim());
|
|
350
|
+
const starts = [];
|
|
351
|
+
for (let i = 0; i + 3 < buf.length; i++) {
|
|
352
|
+
if (buf[i] === ZSTD_MAGIC[0] && buf[i + 1] === ZSTD_MAGIC[1] && buf[i + 2] === ZSTD_MAGIC[2] && buf[i + 3] === ZSTD_MAGIC[3]) starts.push(i);
|
|
353
|
+
}
|
|
354
|
+
starts.push(buf.length);
|
|
355
|
+
const lines = [];
|
|
356
|
+
for (let f = 0; f + 1 < starts.length; f++) {
|
|
357
|
+
const slice = buf.subarray(starts[f], starts[f + 1]);
|
|
358
|
+
if (slice.length < 8) continue;
|
|
359
|
+
let text;
|
|
360
|
+
try { text = zlib.zstdDecompressSync(slice).toString('utf8'); } catch { continue; }
|
|
361
|
+
for (const line of text.split('\n')) if (line.trim()) lines.push(line);
|
|
362
|
+
}
|
|
363
|
+
return lines;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** { meta, events } for one stored session, or null when the log cannot be read. */
|
|
367
|
+
export function readSessionEvents(sessionId, options = {}) {
|
|
368
|
+
if (!sessionId) return null;
|
|
369
|
+
const cached = eventCache.get(sessionId);
|
|
370
|
+
const mtimeKey = `${sessionId}`;
|
|
371
|
+
if (cached && !options.force) {
|
|
372
|
+
try {
|
|
373
|
+
const stat = fs.statSync(cached.file);
|
|
374
|
+
if (stat.mtimeMs === cached.mtime) return cached.value;
|
|
375
|
+
} catch {
|
|
376
|
+
eventCache.delete(mtimeKey);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
const file = sessionLogFile(sessionId);
|
|
380
|
+
if (!file) return null;
|
|
381
|
+
const lines = decodeSessionLines(file);
|
|
382
|
+
let meta = null;
|
|
383
|
+
const events = [];
|
|
384
|
+
for (const line of lines) {
|
|
385
|
+
let record;
|
|
386
|
+
try { record = JSON.parse(line); } catch { continue; }
|
|
387
|
+
if (record.type === 'session') { meta = record; continue; }
|
|
388
|
+
events.push(record);
|
|
389
|
+
}
|
|
390
|
+
if (!meta) return null;
|
|
391
|
+
const value = { meta, events, file };
|
|
392
|
+
try { value.mtime = fs.statSync(file).mtimeMs; } catch { value.mtime = 0; }
|
|
393
|
+
eventCache.set(sessionId, { file, mtime: value.mtime, value });
|
|
394
|
+
return value;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export function clearSessionCache() {
|
|
398
|
+
eventCache.clear();
|
|
399
|
+
}
|
|
400
|
+
/* ------------------------------------------------------------------ *
|
|
401
|
+
* API-first session access. *
|
|
402
|
+
* DSH exposes stored sessions through sessionPersistence.open(id, *
|
|
403
|
+
* 'read'); that handle carries the header and the validated events. *
|
|
404
|
+
* It is the supported path and survives format changes, so it is *
|
|
405
|
+
* always tried first. The raw-log decoder above stays as a fallback *
|
|
406
|
+
* for the case where the service is unavailable or refuses a log *
|
|
407
|
+
* (for example a legacy format the current build cannot restore). *
|
|
408
|
+
* ------------------------------------------------------------------ */
|
|
409
|
+
export async function openSessionViaPersistence(ctx, sessionId) {
|
|
410
|
+
const persistence = ctx && ctx.sessionPersistence;
|
|
411
|
+
if (!persistence || typeof persistence.open !== 'function') return null;
|
|
412
|
+
let handle;
|
|
413
|
+
try {
|
|
414
|
+
handle = await persistence.open(sessionId, 'read');
|
|
415
|
+
const read = await handle.read();
|
|
416
|
+
const events = Array.isArray(read) ? read : read && Array.isArray(read.events) ? read.events : [];
|
|
417
|
+
return { meta: handle.header || null, events, file: null, via: 'persistence' };
|
|
418
|
+
} catch {
|
|
419
|
+
return null;
|
|
420
|
+
} finally {
|
|
421
|
+
try { await handle?.close(); } catch { /* handle may already be released */ }
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Read one stored session: supported API first, decoded log second. */
|
|
426
|
+
export async function readSessionAny(ctx, sessionId, options = {}) {
|
|
427
|
+
if (!sessionId) return null;
|
|
428
|
+
const viaApi = await openSessionViaPersistence(ctx, sessionId);
|
|
429
|
+
if (viaApi) return viaApi;
|
|
430
|
+
const viaDisk = readSessionEvents(sessionId, options);
|
|
431
|
+
if (!viaDisk) return null;
|
|
432
|
+
return { ...viaDisk, via: 'log' };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Header only (parent chain resolution): API first, decoded log second. */
|
|
436
|
+
export async function readHeaderAny(ctx, sessionId) {
|
|
437
|
+
if (!sessionId) return null;
|
|
438
|
+
const persistence = ctx && ctx.sessionPersistence;
|
|
439
|
+
if (persistence && typeof persistence.open === 'function') {
|
|
440
|
+
let handle;
|
|
441
|
+
try {
|
|
442
|
+
handle = await persistence.open(sessionId, 'read');
|
|
443
|
+
if (handle.header) return { header: handle.header, file: null, via: 'persistence' };
|
|
444
|
+
} catch {
|
|
445
|
+
/* fall through to the decoded log */
|
|
446
|
+
} finally {
|
|
447
|
+
try { await handle?.close(); } catch { /* ignore */ }
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return readSessionHeader(sessionId);
|
|
451
|
+
}
|
package/cleanup.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
// Permanent deletion of archived session payloads.
|
|
2
|
-
//
|
|
3
|
-
// DSH exposes no session-delete API: `sessionPersistence` is create/open/flush/stat/list
|
|
4
|
-
// and `ctx.sessions` is the in-memory store with no removal. Deletion therefore removes
|
|
5
|
-
// the on-disk payload and records a tombstone in the sync state, while the id stays in the
|
|
6
|
-
// workspace registry's archived list. Archived ids are never rendered by the sidebar, so a
|
|
7
|
-
// deleted session cannot reappear as an empty chat; `unarchive` refuses tombstoned ids.
|
|
8
|
-
import fs from 'node:fs';
|
|
9
|
-
import path from 'node:path';
|
|
10
|
-
|
|
11
|
-
const SAFE_ID = /^session-[0-9a-f-]{16,}$/i;
|
|
12
|
-
|
|
13
|
-
/** A session id must look like a session id before it is ever joined into a path. */
|
|
14
|
-
export function isSafeSessionId(sessionId) {
|
|
15
|
-
return typeof sessionId === 'string' && SAFE_ID.test(sessionId);
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/** `$DSH_HOME/sessions/<project slug>/<sessionId>` — the slug is opaque, so look it up. */
|
|
19
|
-
export function sessionDirFor(sessionsRoot, sessionId) {
|
|
20
|
-
if (!isSafeSessionId(sessionId)) return null;
|
|
21
|
-
let entries;
|
|
22
|
-
try {
|
|
23
|
-
entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });
|
|
24
|
-
} catch {
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
27
|
-
for (const entry of entries) {
|
|
28
|
-
if (!entry.isDirectory()) continue;
|
|
29
|
-
const candidate = path.join(sessionsRoot, entry.name, sessionId);
|
|
30
|
-
if (fs.existsSync(candidate)) return candidate;
|
|
31
|
-
}
|
|
32
|
-
return null;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Refuse anything that is not exactly `<root>/<one slug>/<sessionId>`. */
|
|
36
|
-
export function assertContained(sessionsRoot, dir, sessionId) {
|
|
37
|
-
const root = path.resolve(sessionsRoot);
|
|
38
|
-
const target = path.resolve(dir);
|
|
39
|
-
const relative = path.relative(root, target);
|
|
40
|
-
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
41
|
-
throw new Error(`拒绝删除工作目录之外的路径: ${target}`);
|
|
42
|
-
}
|
|
43
|
-
const parts = relative.split(path.sep);
|
|
44
|
-
if (parts.length !== 2 || parts[1] !== sessionId) {
|
|
45
|
-
throw new Error(`拒绝删除非会话目录结构的路径: ${target}`);
|
|
46
|
-
}
|
|
47
|
-
return target;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function directoryBytes(dir) {
|
|
51
|
-
let total = 0;
|
|
52
|
-
let entries = [];
|
|
53
|
-
try {
|
|
54
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
55
|
-
} catch {
|
|
56
|
-
return 0;
|
|
57
|
-
}
|
|
58
|
-
for (const entry of entries) {
|
|
59
|
-
const full = path.join(dir, entry.name);
|
|
60
|
-
try {
|
|
61
|
-
if (entry.isDirectory()) total += directoryBytes(full);
|
|
62
|
-
else total += fs.statSync(full).size;
|
|
63
|
-
} catch {
|
|
64
|
-
// a file that disappeared mid-walk contributes nothing
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
return total;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** What deletion would remove for one archived session, without touching anything. */
|
|
71
|
-
export function planSessionDeletion({ sessionsRoot, archivesRoot, sessionId }) {
|
|
72
|
-
const dir = sessionDirFor(sessionsRoot, sessionId);
|
|
73
|
-
const archiveFile = path.join(archivesRoot, `${sessionId}.json`);
|
|
74
|
-
const hasArchiveFile = fs.existsSync(archiveFile);
|
|
75
|
-
return {
|
|
76
|
-
sessionId,
|
|
77
|
-
dir,
|
|
78
|
-
exists: !!dir,
|
|
79
|
-
archiveFile: hasArchiveFile ? archiveFile : null,
|
|
80
|
-
bytes: dir ? directoryBytes(dir) + (hasArchiveFile ? fs.statSync(archiveFile).size : 0) : 0,
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/** Delete one session payload. Returns the bytes reclaimed. Irreversible by design. */
|
|
85
|
-
export function deleteSessionPayload({ sessionsRoot, archivesRoot, sessionId }) {
|
|
86
|
-
const plan = planSessionDeletion({ sessionsRoot, archivesRoot, sessionId });
|
|
87
|
-
if (plan.dir) {
|
|
88
|
-
assertContained(sessionsRoot, plan.dir, sessionId);
|
|
89
|
-
fs.rmSync(plan.dir, { recursive: true, force: true });
|
|
90
|
-
if (fs.existsSync(plan.dir)) throw new Error(`会话目录仍然存在: ${plan.dir}`);
|
|
91
|
-
}
|
|
92
|
-
if (plan.archiveFile) {
|
|
93
|
-
const root = path.resolve(archivesRoot);
|
|
94
|
-
const target = path.resolve(plan.archiveFile);
|
|
95
|
-
if (path.relative(root, target).startsWith('..')) throw new Error('拒绝删除存档目录之外的文件');
|
|
96
|
-
fs.rmSync(plan.archiveFile, { force: true });
|
|
97
|
-
}
|
|
98
|
-
return { sessionId, bytes: plan.bytes, removedDir: !!plan.dir, removedArchive: !!plan.archiveFile };
|
|
99
|
-
}
|