dsh-plugin-external-session-sync 0.0.0-stage → 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 +192 -0
- package/LICENSE +21 -0
- package/README.md +131 -3
- package/client.js +389 -0
- package/cordis.patch.yml +6 -0
- package/discovery.js +43 -0
- package/engine.js +505 -0
- package/icon.svg +1 -0
- package/index.js +465 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/native.js +168 -0
- package/package.json +55 -6
- package/readers-antigravity.js +306 -0
- package/readers.js +1449 -0
- package/reverse.js +451 -0
package/index.js
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
// Host half of the plugin: HTTP routes for the panel plus three agent tools.
|
|
2
|
+
// The Client half (client.js) only talks to these routes; all DSH mutations happen here.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { SyncEngine } from './engine.js';
|
|
8
|
+
import { nativeEvents } from './native.js';
|
|
9
|
+
import { planReverse, appendTurns, readRolloutFacts, turnRecords, readSessionHeader, readSessionAny, readHeaderAny, sessionMessages, pendingTurns, prefixMatches, targetRollout, newRolloutPath, exportRecords } from './reverse.js';
|
|
10
|
+
|
|
11
|
+
export const name = 'dsh-plugin-external-session-sync';
|
|
12
|
+
|
|
13
|
+
/** Every service the Host half touches must be declared, or Cordis refuses the row. */
|
|
14
|
+
export const inject = [
|
|
15
|
+
'webServer',
|
|
16
|
+
'tools',
|
|
17
|
+
'sessionPersistence',
|
|
18
|
+
'sessions',
|
|
19
|
+
'sessionController',
|
|
20
|
+
'workspaceRegistry',
|
|
21
|
+
'clientModules',
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
export const API = '/external-session-sync';
|
|
25
|
+
const VERSION = '1.10.3';
|
|
26
|
+
const PACKAGE_ID = 'dsh-plugin-external-session-sync';
|
|
27
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
28
|
+
const DIAGNOSTIC_EVENTS = 60;
|
|
29
|
+
const ALLOWED_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
30
|
+
|
|
31
|
+
export function apply(ctx) {
|
|
32
|
+
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
|
|
33
|
+
const engine = new SyncEngine(ctx, home);
|
|
34
|
+
const logPath = path.join(home, 'external-session-sync', 'runtime.log');
|
|
35
|
+
fs.mkdirSync(path.dirname(logPath), { recursive: true });
|
|
36
|
+
const log = (text) => fs.appendFileSync(logPath, `${new Date().toISOString()} ${text}\n`);
|
|
37
|
+
|
|
38
|
+
const diagnostics = { version: VERSION, mountedAt: Date.now(), events: [] };
|
|
39
|
+
let lastSync;
|
|
40
|
+
|
|
41
|
+
const send = (res, value, code = 200) => {
|
|
42
|
+
res.statusCode = code;
|
|
43
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
44
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
45
|
+
res.end(JSON.stringify(value));
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
async function readBody(req) {
|
|
49
|
+
const chunks = [];
|
|
50
|
+
let bytes = 0;
|
|
51
|
+
for await (const chunk of req) {
|
|
52
|
+
bytes += chunk.length;
|
|
53
|
+
if (bytes > MAX_BODY_BYTES) throw new Error('请求过大');
|
|
54
|
+
chunks.push(chunk);
|
|
55
|
+
}
|
|
56
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function route(pathname, method, handle) {
|
|
60
|
+
ctx.effect(
|
|
61
|
+
() =>
|
|
62
|
+
ctx.webServer.register({
|
|
63
|
+
kind: 'exact',
|
|
64
|
+
path: API + pathname,
|
|
65
|
+
handler: async (req, res) => {
|
|
66
|
+
if (req.method !== method) return send(res, { error: 'Method not allowed' }, 405);
|
|
67
|
+
// A same-origin mutation must prove it came from this app, not a cross-site form.
|
|
68
|
+
if (method === 'POST' && req.headers['x-dsh-sync'] !== '1') return send(res, { error: '缺少同步请求标记' }, 403);
|
|
69
|
+
if (req.headers.origin) {
|
|
70
|
+
try {
|
|
71
|
+
const origin = new URL(req.headers.origin);
|
|
72
|
+
if (!ALLOWED_HOSTS.has(origin.hostname)) return send(res, { error: '跨站请求被拒绝' }, 403);
|
|
73
|
+
} catch {
|
|
74
|
+
return send(res, { error: 'Invalid origin' }, 403);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
await handle(req, res, new URL(req.url, 'http://127.0.0.1'));
|
|
79
|
+
} catch (error) {
|
|
80
|
+
log(`error ${pathname} ${error.message}`);
|
|
81
|
+
send(res, { error: error.message }, 500);
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
}),
|
|
85
|
+
`external-sync.route${pathname}`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
route('/status', 'GET', async (req, res, url) =>
|
|
90
|
+
send(res, await engine.status({ source: url.searchParams.get('source') || undefined, q: url.searchParams.get('q') || '' })),
|
|
91
|
+
);
|
|
92
|
+
route('/conversation', 'GET', async (req, res, url) =>
|
|
93
|
+
send(res, await engine.conversation(url.searchParams.get('source'), url.searchParams.get('id'), url.searchParams.get('maxMessages'))),
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
route('/sync', 'POST', async (req, res) => {
|
|
97
|
+
lastSync = await engine.sync(await readBody(req));
|
|
98
|
+
send(res, lastSync);
|
|
99
|
+
});
|
|
100
|
+
route('/archive', 'POST', async (req, res) => {
|
|
101
|
+
const request = await readBody(req);
|
|
102
|
+
const requested = [...new Set(Array.isArray(request.sessionIds) ? request.sessionIds.filter(Boolean) : [])];
|
|
103
|
+
// The registry is authoritative for pins; a client list can only add to that set.
|
|
104
|
+
const pinned = new Set([
|
|
105
|
+
...(Array.isArray(request.pinnedSessionIds) ? request.pinnedSessionIds : []),
|
|
106
|
+
...(Array.isArray(ctx.workspaceRegistry.pinnedSessionIds) ? ctx.workspaceRegistry.pinnedSessionIds : []),
|
|
107
|
+
]);
|
|
108
|
+
const archived = [];
|
|
109
|
+
const skippedPinned = [];
|
|
110
|
+
const failed = [];
|
|
111
|
+
for (const sessionId of requested) {
|
|
112
|
+
if (pinned.has(sessionId)) {
|
|
113
|
+
skippedPinned.push(sessionId);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
await ctx.workspaceRegistry.archiveSession(sessionId, { stopActivity: false });
|
|
118
|
+
archived.push(sessionId);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
failed.push({ id: sessionId, error: error.message });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const archivedSet = new Set([...(ctx.workspaceRegistry.archivedSessionIds || []), ...archived]);
|
|
124
|
+
const deletedWorkspaces = [];
|
|
125
|
+
const deleteFailures = [];
|
|
126
|
+
// Cleanup only follows a real archive in this call: an empty or no-op request must
|
|
127
|
+
// never sweep project registrations on its own.
|
|
128
|
+
if (request.deleteEmptyWorkspaces !== false && archived.length) {
|
|
129
|
+
for (const workspace of ctx.workspaceRegistry.list()) {
|
|
130
|
+
if (!workspace.sessionIds.length || !workspace.sessionIds.every((id) => archivedSet.has(id))) continue;
|
|
131
|
+
try {
|
|
132
|
+
if (await ctx.workspaceRegistry.delete(workspace.id)) {
|
|
133
|
+
deletedWorkspaces.push({ id: workspace.id, title: workspace.title, path: workspace.path });
|
|
134
|
+
}
|
|
135
|
+
} catch (error) {
|
|
136
|
+
deleteFailures.push({ id: workspace.id, error: error.message });
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
send(res, { requested: requested.length, archived, skippedPinned, failed: [...failed, ...deleteFailures], deletedWorkspaces });
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
// Re-register a project for an existing directory and restore named session membership.
|
|
144
|
+
route('/workspace', 'POST', async (req, res) => {
|
|
145
|
+
const request = await readBody(req);
|
|
146
|
+
if (typeof request.path !== 'string' || !request.path) throw new Error('缺少项目路径');
|
|
147
|
+
const workspace = await ctx.workspaceRegistry.create(request.path);
|
|
148
|
+
const attached = [];
|
|
149
|
+
const failed = [];
|
|
150
|
+
for (const sessionId of Array.isArray(request.sessionIds) ? request.sessionIds : []) {
|
|
151
|
+
try {
|
|
152
|
+
await workspace.attachSession(sessionId);
|
|
153
|
+
attached.push(sessionId);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
failed.push({ id: sessionId, error: error.message });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
send(res, {
|
|
159
|
+
workspaceId: workspace.id,
|
|
160
|
+
title: workspace.title,
|
|
161
|
+
path: workspace.path,
|
|
162
|
+
sessionIds: workspace.sessionIds.length,
|
|
163
|
+
attached,
|
|
164
|
+
failed,
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
route('/validate', 'GET', async (req, res, url) => send(res, await engine.validateSession(url.searchParams.get('id'))));
|
|
169
|
+
|
|
170
|
+
// Runs the importer's event shape through DSH's own session validator twice: the
|
|
171
|
+
// events as written, and with the system message the runtime appends when the user
|
|
172
|
+
// continues the chat. Nothing is persisted; the id is throwaway.
|
|
173
|
+
route('/self-check', 'POST', async (req, res) => {
|
|
174
|
+
const now = Date.now();
|
|
175
|
+
const conversation = {
|
|
176
|
+
title: 'shape check',
|
|
177
|
+
startedAt: now,
|
|
178
|
+
messages: [
|
|
179
|
+
{ role: 'user', text: 'first question', timestamp: now - 2000 },
|
|
180
|
+
{ role: 'assistant', text: 'first answer', timestamp: now - 1000 },
|
|
181
|
+
],
|
|
182
|
+
};
|
|
183
|
+
const base = nativeEvents(conversation, 'codex');
|
|
184
|
+
const continuation = [...base];
|
|
185
|
+
const turn = Math.max(0, ...base.filter((event) => event.type === 'turn/start').map((event) => event.data.turn)) + 1;
|
|
186
|
+
const push = (type, data, surface = false) => {
|
|
187
|
+
const event = { type, seq: continuation.length, time: now, data };
|
|
188
|
+
if (surface) event.surfaceOp = 'append';
|
|
189
|
+
continuation.push(event);
|
|
190
|
+
};
|
|
191
|
+
push('turn/start', { turn });
|
|
192
|
+
push('step/start', { turn, step: 1 });
|
|
193
|
+
push('system/message', { turn, step: 1, message: { role: 'system', id: crypto.randomUUID(), source: { kind: 'system-prompt' }, content: [{ type: 'text', text: 'runtime prompt' }] } }, true);
|
|
194
|
+
push('step/end', { turn, step: 1 });
|
|
195
|
+
push('turn/end', { turn, reason: { kind: 'completed' } });
|
|
196
|
+
const check = (events) => {
|
|
197
|
+
try {
|
|
198
|
+
ctx.sessions.prepare(`session-${crypto.randomUUID()}`, {
|
|
199
|
+
seed: events,
|
|
200
|
+
meta: { createdAt: now, isSeeded: false, delegationDepth: 0, agentPreset: 'standard', cwd: home },
|
|
201
|
+
});
|
|
202
|
+
return { ok: true };
|
|
203
|
+
} catch (error) {
|
|
204
|
+
return { ok: false, error: error.message };
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
send(res, { events: base.length, importedShape: check(base), afterContinuation: check(continuation) });
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
// Reverse of /archive: brings sessions back to the sidebar without touching their logs.
|
|
211
|
+
route('/unarchive', 'POST', async (req, res) => {
|
|
212
|
+
const request = await readBody(req);
|
|
213
|
+
const requested = [...new Set(Array.isArray(request.sessionIds) ? request.sessionIds.filter(Boolean) : [])];
|
|
214
|
+
const tombstones = engine.state.deleted || {};
|
|
215
|
+
const unarchived = [];
|
|
216
|
+
const failed = [];
|
|
217
|
+
for (const sessionId of requested) {
|
|
218
|
+
// A deleted payload can never come back: refuse instead of showing a broken chat.
|
|
219
|
+
if (tombstones[sessionId]) {
|
|
220
|
+
failed.push({ id: sessionId, error: '该会话的正文已被永久删除,无法取消归档' });
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
await ctx.workspaceRegistry.unarchiveSession(sessionId);
|
|
225
|
+
unarchived.push(sessionId);
|
|
226
|
+
} catch (error) {
|
|
227
|
+
failed.push({ id: sessionId, error: error.message });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
send(res, { requested: requested.length, unarchived, failed });
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
route('/legacy-imports', 'GET', async (req, res) => {
|
|
234
|
+
const rows = await engine.legacyImports();
|
|
235
|
+
send(res, {
|
|
236
|
+
count: rows.length,
|
|
237
|
+
reimportable: rows.filter((row) => row.reimportable && !row.unreadable).length,
|
|
238
|
+
unrecoverable: rows.filter((row) => !row.reimportable).length,
|
|
239
|
+
unreadable: rows.filter((row) => row.unreadable).length,
|
|
240
|
+
sample: rows.slice(0, 5),
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
// Archive legacy logs (no protected head) and re-import the same source conversation
|
|
245
|
+
// under a fresh identity. Old logs stay archived, so unarchiveSession reverses it.
|
|
246
|
+
route('/migrate-heads', 'POST', async (req, res) => send(res, await engine.migrateLegacyHeads(await readBody(req))));
|
|
247
|
+
|
|
248
|
+
// Walk a session's parent chain to the imported ancestor. A DSH "fork" copies the
|
|
249
|
+
// imported session, so the fork's own turns start after its parent's messages.
|
|
250
|
+
const resolveSource=async(sessionId)=>{
|
|
251
|
+
const entries=engine.state.entries;
|
|
252
|
+
const findEntry=(id)=>Object.entries(entries).find(([,value])=>value.sessionId===id) || null;
|
|
253
|
+
let mapped=findEntry(sessionId);
|
|
254
|
+
const chain=[];
|
|
255
|
+
let current=sessionId;
|
|
256
|
+
while(!mapped && chain.length<8){
|
|
257
|
+
const head=await readHeaderAny(ctx,current);
|
|
258
|
+
const parentId=head?.header?.parentSession;
|
|
259
|
+
if(!parentId)return {error:'该会话没有 Codex 来源,也不是导入会话的 fork'};
|
|
260
|
+
chain.push({id:current,parentId});
|
|
261
|
+
current=parentId;
|
|
262
|
+
mapped=findEntry(current);
|
|
263
|
+
}
|
|
264
|
+
if(!mapped)return {error:'父链过深,无法定位导入来源'};
|
|
265
|
+
const [key,entry]=mapped;
|
|
266
|
+
if(!chain.length)return {key,entry,boundary:Number(entry.messages)||0,forked:false};
|
|
267
|
+
let parentMessages;
|
|
268
|
+
try{const parent=await readSessionAny(ctx,chain[0].parentId);if(!parent)throw new Error('父会话日志不可读');parentMessages=sessionMessages(parent.events);}
|
|
269
|
+
catch(error){return {error:`无法读取父会话:${error.message}`};}
|
|
270
|
+
return {key,entry,boundary:parentMessages.length,parentId:chain[0].parentId,parentMessages,forked:true};
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// Sidebar-shaped source for the reverse page: projects with their unarchived sessions.
|
|
274
|
+
route('/reverse-groups','GET',async(req,res)=>{
|
|
275
|
+
const archived=new Set(ctx.workspaceRegistry.archivedSessionIds || []);
|
|
276
|
+
const groups=ctx.workspaceRegistry.list().map(workspace=>({
|
|
277
|
+
id:workspace.id,
|
|
278
|
+
title:workspace.title,
|
|
279
|
+
path:workspace.path,
|
|
280
|
+
sessionIds:(workspace.sessionIds || []).filter(id=>!archived.has(id)),
|
|
281
|
+
})).filter(group=>group.sessionIds.length);
|
|
282
|
+
send(res,{groups,archived:archived.size});
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// Classify one session: append to its Codex main, or export it as a new Codex thread.
|
|
286
|
+
// Message preview for the reverse page: what would be written for this DSH session.
|
|
287
|
+
route('/session-preview','GET',async(req,res,url)=>{
|
|
288
|
+
const sessionId=url.searchParams.get('id');
|
|
289
|
+
const maxMessages=Math.max(1,Math.min(200,Number(url.searchParams.get('maxMessages'))||40));
|
|
290
|
+
if(!sessionId)return send(res,{error:'缺少 id'},400);
|
|
291
|
+
const inspected=await readSessionAny(ctx,sessionId);
|
|
292
|
+
if(!inspected)return send(res,{error:'无法读取会话:日志不可读'},500);
|
|
293
|
+
const messages=sessionMessages(inspected.events);
|
|
294
|
+
const tail=messages.slice(-maxMessages);
|
|
295
|
+
send(res,{sessionId,total:messages.length,shown:tail.length,messages:tail.map(message=>({role:message.role,text:message.text.length>600?message.text.slice(0,600)+'…':message.text,time:message.time}))});
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
route('/reverse-targets','POST',async(req,res)=>{
|
|
299
|
+
const request=await readBody(req);
|
|
300
|
+
const ids=[...new Set(Array.isArray(request.sessionIds)?request.sessionIds.filter(Boolean):[])];
|
|
301
|
+
if(!ids.length)return send(res,{error:'必须显式指定 sessionIds'},400);
|
|
302
|
+
const rows=[];
|
|
303
|
+
for(const sessionId of ids.slice(0,400)){
|
|
304
|
+
let events;
|
|
305
|
+
const read=await readSessionAny(ctx,sessionId);
|
|
306
|
+
if(!read){rows.push({sessionId,mode:'error',error:'无法读取会话:日志不可读'});continue;}
|
|
307
|
+
events=read.events;
|
|
308
|
+
const messages=sessionMessages(events);
|
|
309
|
+
const resolved=await resolveSource(sessionId);
|
|
310
|
+
if(resolved.error){
|
|
311
|
+
const turns=pendingTurns(messages,0);
|
|
312
|
+
rows.push({sessionId,mode:'export',messages:messages.length,turns:turns.length});
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
const {key,boundary,parentMessages,forked}=resolved;
|
|
316
|
+
const prefixOk=!forked || prefixMatches(messages,parentMessages);
|
|
317
|
+
const turns=prefixOk?pendingTurns(messages,boundary):[];
|
|
318
|
+
const threadId=key.slice(key.indexOf(':')+1);
|
|
319
|
+
rows.push({sessionId,mode:'append',threadId,key,forked,prefixOk,messages:messages.length,importedCount:boundary,turns:turns.length,hasRollout:!!targetRollout(threadId)});
|
|
320
|
+
}
|
|
321
|
+
send(res,{requested:ids.length,rows});
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
route('/reverse','POST',async(req,res)=>{
|
|
325
|
+
const request=await readBody(req);
|
|
326
|
+
const dryRun=request.dryRun!==false;
|
|
327
|
+
const wanted=[...new Set(Array.isArray(request.sessionIds)?request.sessionIds.filter(Boolean):[])];
|
|
328
|
+
const results=[];
|
|
329
|
+
if(!wanted.length){
|
|
330
|
+
return send(res,{error:'必须显式指定 sessionIds,反同步不会自动处理全部会话'},400);
|
|
331
|
+
}
|
|
332
|
+
for(const requested of wanted){
|
|
333
|
+
let events;
|
|
334
|
+
const read=await readSessionAny(ctx,requested);
|
|
335
|
+
if(!read){results.push({sessionId:requested,error:'无法读取会话:日志不可读'});continue;}
|
|
336
|
+
events=read.events;
|
|
337
|
+
const messages=sessionMessages(events);
|
|
338
|
+
const resolved=await resolveSource(requested);
|
|
339
|
+
|
|
340
|
+
if(resolved.error){
|
|
341
|
+
// Export: a session that never came from Codex becomes a new Codex thread.
|
|
342
|
+
const turns=pendingTurns(messages,0);
|
|
343
|
+
if(!turns.length){results.push({sessionId:requested,mode:'export',turns:0,note:'没有可导出的完整轮次(缺少助手回复)'});continue;}
|
|
344
|
+
const threadId=crypto.randomUUID();
|
|
345
|
+
const startedAt=Number(turns[0].user.time)||Date.now();
|
|
346
|
+
const target=newRolloutPath(threadId,startedAt);
|
|
347
|
+
const records=exportRecords({threadId,cwd:request.cwd||home,startedAtMs:startedAt,turns});
|
|
348
|
+
if(dryRun){
|
|
349
|
+
results.push({sessionId:requested,mode:'export',threadId,rollout:target,turns:turns.length,records:records.length,sample:records.slice(0,2),dryRun:true});
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
try{
|
|
353
|
+
fs.mkdirSync(path.dirname(target),{recursive:true});
|
|
354
|
+
fs.writeFileSync(target,records.map(record=>JSON.stringify(record)).join('\n')+'\n');
|
|
355
|
+
const written=fs.readFileSync(target,'utf8').split('\n').filter(Boolean).map(line=>JSON.parse(line));
|
|
356
|
+
results.push({sessionId:requested,mode:'export',threadId,rollout:target,turns:turns.length,records:records.length,appended:records.length,verified:written.length===records.length});
|
|
357
|
+
}catch(error){results.push({sessionId:requested,mode:'export',error:'导出失败:'+error.message});}
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const {key,entry,boundary,parentMessages,forked}=resolved;
|
|
362
|
+
if(forked && !prefixMatches(messages,parentMessages)){
|
|
363
|
+
results.push({sessionId:requested,key,error:'fork 的种子前缀与父会话不一致,拒绝回写'});
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
const turns=pendingTurns(messages,boundary);
|
|
367
|
+
if(!turns.length){results.push({sessionId:requested,key,mode:'append',turns:0,note:'没有仅存在于 DSH 的新轮次'});continue;}
|
|
368
|
+
const threadId=key.slice(key.indexOf(':')+1);
|
|
369
|
+
const target=targetRollout(threadId);
|
|
370
|
+
if(!target){results.push({sessionId:requested,key,threadId,mode:'append',turns:turns.length,error:'该 Codex 会话已没有 rollout 文件,无法回写'});continue;}
|
|
371
|
+
const facts=readRolloutFacts(target);
|
|
372
|
+
const records=[];
|
|
373
|
+
for(const turn of turns)records.push(...turnRecords({threadId:facts.threadId,modelContextWindow:facts.modelContextWindow,contextTemplate:facts.contextTemplate,turn,ordinal:facts.lastOrdinal+1+records.length}));
|
|
374
|
+
if(dryRun){
|
|
375
|
+
results.push({sessionId:requested,key,threadId,mode:'append',rollout:target,forked,turns:turns.length,records:records.length,sample:records.slice(0,3),dryRun:true});
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const written=appendTurns(target,records);
|
|
379
|
+
entry.reversed={...(entry.reversed||{}),[requested]:{turns:turns.length,messages:messages.length,at:Date.now(),threadId}};
|
|
380
|
+
entry.reverseThrough=(Number(entry.reverseThrough)||0)+turns.length;
|
|
381
|
+
engine.save();
|
|
382
|
+
results.push({sessionId:requested,key,threadId,mode:'append',rollout:target,forked,turns:turns.length,records:records.length,...written});
|
|
383
|
+
}
|
|
384
|
+
send(res,{dryRun,results,done:results.filter(row=>row.verified).length,failed:results.filter(row=>row.error).length});
|
|
385
|
+
});
|
|
386
|
+
// Permanent deletion of archived session payloads. Dry run unless dryRun is false.
|
|
387
|
+
route('/delete-archived', 'POST', async (req, res) => send(res, await engine.deleteArchived(await readBody(req))));
|
|
388
|
+
|
|
389
|
+
route('/health', 'GET', async (req, res) =>
|
|
390
|
+
send(res, {
|
|
391
|
+
...diagnostics,
|
|
392
|
+
...(lastSync
|
|
393
|
+
? { lastSync: { imported: lastSync.imported.length, skipped: lastSync.skipped.length, repaired: lastSync.repaired.length, failed: lastSync.failed.length } }
|
|
394
|
+
: {}),
|
|
395
|
+
}),
|
|
396
|
+
);
|
|
397
|
+
route('/refresh-client','POST',async(req,res)=>send(res,{revision:ctx.clientModules.rebuilt('dsh-plugin-external-session-sync')}));
|
|
398
|
+
route('/client-graph', 'GET', async (req, res) =>
|
|
399
|
+
send(res, {
|
|
400
|
+
entries: ctx.clientModules.graph().entries.filter((entry) => entry.id === PACKAGE_ID),
|
|
401
|
+
path: ctx.clientModules.clientPath(PACKAGE_ID),
|
|
402
|
+
}),
|
|
403
|
+
);
|
|
404
|
+
route('/client-state', 'POST', async (req, res) => {
|
|
405
|
+
const event = await readBody(req);
|
|
406
|
+
diagnostics.events.push({ ...event, time: Date.now() });
|
|
407
|
+
diagnostics.events = diagnostics.events.slice(-DIAGNOSTIC_EVENTS);
|
|
408
|
+
send(res, { ok: true });
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
// DSH requires lossless JSON from a tool: drop non-finite numbers and exotic values.
|
|
412
|
+
const jsonSafe = (value) => JSON.parse(JSON.stringify(value, (key, item) => (typeof item === 'number' && !Number.isFinite(item) ? null : item)));
|
|
413
|
+
|
|
414
|
+
const tools = [
|
|
415
|
+
{
|
|
416
|
+
name: 'codex_sync_status',
|
|
417
|
+
description: 'List external Codex and Claude conversations and their DSH sync state.',
|
|
418
|
+
parameters: { type: 'object', properties: { source: { type: 'string', enum: ['codex', 'claude', 'antigravity'] }, limit: { type: 'number' } } },
|
|
419
|
+
run: async (args) => {
|
|
420
|
+
const status = await engine.status(args);
|
|
421
|
+
if (args.limit) status.discovered = status.discovered.slice(0, args.limit);
|
|
422
|
+
return status;
|
|
423
|
+
},
|
|
424
|
+
},
|
|
425
|
+
{
|
|
426
|
+
name: 'codex_sync_import',
|
|
427
|
+
description: 'Import external conversations using DSH native persistence. Continued sessions are preserved.',
|
|
428
|
+
parameters: {
|
|
429
|
+
type: 'object',
|
|
430
|
+
properties: {
|
|
431
|
+
source: { type: 'string', enum: ['codex', 'claude', 'antigravity'] },
|
|
432
|
+
ids: { type: 'array', items: { type: 'string' } },
|
|
433
|
+
limit: { type: 'number' },
|
|
434
|
+
},
|
|
435
|
+
},
|
|
436
|
+
run: async (args) => jsonSafe(await engine.sync(args)),
|
|
437
|
+
},
|
|
438
|
+
{
|
|
439
|
+
name: 'codex_read_conversation',
|
|
440
|
+
description: 'Read the newest visible user and assistant messages from an external conversation.',
|
|
441
|
+
parameters: {
|
|
442
|
+
type: 'object',
|
|
443
|
+
properties: { source: { type: 'string', enum: ['codex', 'claude', 'antigravity'] }, id: { type: 'string' }, maxMessages: { type: 'number' } },
|
|
444
|
+
required: ['source', 'id'],
|
|
445
|
+
},
|
|
446
|
+
run: async (args) => jsonSafe(await engine.conversation(args.source, args.id, args.maxMessages)),
|
|
447
|
+
},
|
|
448
|
+
];
|
|
449
|
+
for (const tool of tools) {
|
|
450
|
+
ctx.effect(
|
|
451
|
+
() =>
|
|
452
|
+
ctx.tools.register({
|
|
453
|
+
name: tool.name,
|
|
454
|
+
description: tool.description,
|
|
455
|
+
parameters: tool.parameters,
|
|
456
|
+
output: { schema: { type: 'object' }, render: (args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }] },
|
|
457
|
+
execute: (args) => tool.run(args || {}),
|
|
458
|
+
}),
|
|
459
|
+
`external-sync.tool.${tool.name}`,
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
log(`mounted ${PACKAGE_ID} ${VERSION}; no automatic imports`);
|
|
464
|
+
ctx.effect(() => () => log('disposed routes and tools'), 'external-sync.lifecycle');
|
|
465
|
+
}
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/native.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function canonicalCwd(value) {
|
|
4
|
+
if (!value) return undefined;
|
|
5
|
+
let cwd = String(value);
|
|
6
|
+
if (cwd.startsWith('\\\\?\\UNC\\')) cwd = '\\\\' + cwd.slice(8);
|
|
7
|
+
else if (cwd.startsWith('\\\\?\\')) cwd = cwd.slice(4);
|
|
8
|
+
return cwd;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function nativeId(source, id, revision) {
|
|
12
|
+
const bytes = crypto.createHash('sha256').update(`dsh-sync-native-2:${source}:${id}:${revision}`).digest().subarray(0, 16);
|
|
13
|
+
bytes[6] = (bytes[6] & 15) | 0x50;
|
|
14
|
+
bytes[8] = (bytes[8] & 63) | 0x80;
|
|
15
|
+
const s = bytes.toString('hex');
|
|
16
|
+
return `session-${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The system message every imported session starts with.
|
|
21
|
+
*
|
|
22
|
+
* DSH treats the first surface event of a session as the protected head:
|
|
23
|
+
* `session-format`'s relations keeper records `protectedHead` only when a
|
|
24
|
+
* `system/message` is the first surface node, and it throws
|
|
25
|
+
* "system/message requires a protected first surface head" for any later
|
|
26
|
+
* `system/message` when no head was recorded. Continuing an imported chat makes
|
|
27
|
+
* the runtime append its own system message, so an import that starts with a
|
|
28
|
+
* user message corrupts the log on the first continued turn.
|
|
29
|
+
*
|
|
30
|
+
* The text states provenance instead of pretending to be the live prompt: the
|
|
31
|
+
* runtime appends the real prompt when the conversation continues.
|
|
32
|
+
*/
|
|
33
|
+
export const IMPORT_SYSTEM_HEAD = [
|
|
34
|
+
'This session continues a conversation that was imported from an external agent history by the DSH external session sync plugin.',
|
|
35
|
+
'Earlier turns are a faithful text transcript: tool calls, hidden reasoning and binary attachments were not replayed.',
|
|
36
|
+
'Rely on the files and tools available in this workspace, and verify anything taken from the transcript before acting on it.',
|
|
37
|
+
].join('\n\n');
|
|
38
|
+
|
|
39
|
+
const TITLE_FALLBACK = '外部会话';
|
|
40
|
+
|
|
41
|
+
// Foreign tool execution is never replayed. One assistant reply occupies one model
|
|
42
|
+
// step, and the first step of a turn also carries that turn's user message.
|
|
43
|
+
export function nativeEvents(conversation, source, options = {}) {
|
|
44
|
+
const events = [];
|
|
45
|
+
const messages = (conversation.messages || []).filter(
|
|
46
|
+
(message) => (message.role === 'user' || message.role === 'assistant') && message.text?.trim(),
|
|
47
|
+
);
|
|
48
|
+
if (!messages.length) return events;
|
|
49
|
+
|
|
50
|
+
const headText = options.systemHead ?? conversation.systemHead ?? IMPORT_SYSTEM_HEAD;
|
|
51
|
+
let clock = Number(conversation.startedAt) || Date.now();
|
|
52
|
+
let turn = 0;
|
|
53
|
+
let step = 0;
|
|
54
|
+
let turnOpen = false;
|
|
55
|
+
let stepOpen = false;
|
|
56
|
+
let stepHasAssistant = false;
|
|
57
|
+
let headSeq;
|
|
58
|
+
let firstUserSeq;
|
|
59
|
+
|
|
60
|
+
const append = (type, data, surface = false) => {
|
|
61
|
+
const event = { type, seq: events.length, time: clock, data };
|
|
62
|
+
if (surface) event.surfaceOp = 'append';
|
|
63
|
+
events.push(event);
|
|
64
|
+
return event.seq;
|
|
65
|
+
};
|
|
66
|
+
const openTurn = () => {
|
|
67
|
+
turn += 1;
|
|
68
|
+
step = 0;
|
|
69
|
+
turnOpen = true;
|
|
70
|
+
append('turn/start', { turn });
|
|
71
|
+
};
|
|
72
|
+
const openStep = () => {
|
|
73
|
+
step += 1;
|
|
74
|
+
stepOpen = true;
|
|
75
|
+
stepHasAssistant = false;
|
|
76
|
+
append('step/start', { turn, step });
|
|
77
|
+
};
|
|
78
|
+
const closeStep = () => {
|
|
79
|
+
if (!stepOpen) return;
|
|
80
|
+
append('step/end', { turn, step });
|
|
81
|
+
stepOpen = false;
|
|
82
|
+
stepHasAssistant = false;
|
|
83
|
+
};
|
|
84
|
+
const closeTurn = () => {
|
|
85
|
+
closeStep();
|
|
86
|
+
if (!turnOpen) return;
|
|
87
|
+
append('turn/end', { turn, reason: { kind: 'completed' } });
|
|
88
|
+
turnOpen = false;
|
|
89
|
+
};
|
|
90
|
+
// Emitted only while a step is open: the relations keeper requires it to match
|
|
91
|
+
// the open turn and step, and only the first one becomes the protected head.
|
|
92
|
+
// A seed message also has to be identifiable, so it carries an id and a source.
|
|
93
|
+
const emitHead = () => {
|
|
94
|
+
if (headSeq !== undefined) return headSeq;
|
|
95
|
+
headSeq = append(
|
|
96
|
+
'system/message',
|
|
97
|
+
{
|
|
98
|
+
turn,
|
|
99
|
+
step,
|
|
100
|
+
message: {
|
|
101
|
+
role: 'system',
|
|
102
|
+
id: crypto.randomUUID(),
|
|
103
|
+
source: { kind: 'system-prompt' },
|
|
104
|
+
content: [{ type: 'text', text: headText }],
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
true,
|
|
108
|
+
);
|
|
109
|
+
return headSeq;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
for (const message of messages) {
|
|
113
|
+
const time = typeof message.timestamp === 'number' ? message.timestamp : Date.parse(message.timestamp);
|
|
114
|
+
if (Number.isFinite(time)) clock = Math.max(clock, time);
|
|
115
|
+
|
|
116
|
+
if (message.role === 'user') {
|
|
117
|
+
closeTurn();
|
|
118
|
+
openTurn();
|
|
119
|
+
openStep();
|
|
120
|
+
emitHead();
|
|
121
|
+
const seq = append(
|
|
122
|
+
'user/message',
|
|
123
|
+
{ role: 'user', id: crypto.randomUUID(), source: { kind: 'user' }, content: [{ type: 'text', text: message.text }] },
|
|
124
|
+
true,
|
|
125
|
+
);
|
|
126
|
+
if (firstUserSeq === undefined) firstUserSeq = seq;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Assistant reply: the first one joins the turn's opening step, later ones open
|
|
131
|
+
// their own step so every model turn stays reconstructable.
|
|
132
|
+
if (!turnOpen) openTurn();
|
|
133
|
+
if (!stepOpen) openStep();
|
|
134
|
+
else if (stepHasAssistant) {
|
|
135
|
+
closeStep();
|
|
136
|
+
openStep();
|
|
137
|
+
}
|
|
138
|
+
emitHead();
|
|
139
|
+
append(
|
|
140
|
+
'assistant/message',
|
|
141
|
+
{
|
|
142
|
+
turn,
|
|
143
|
+
step,
|
|
144
|
+
stream: [],
|
|
145
|
+
message: {
|
|
146
|
+
id: crypto.randomUUID(),
|
|
147
|
+
role: 'assistant',
|
|
148
|
+
source: { kind: 'model', provider: source, model: 'external-history' },
|
|
149
|
+
content: [{ type: 'text', text: message.text }],
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
true,
|
|
153
|
+
);
|
|
154
|
+
stepHasAssistant = true;
|
|
155
|
+
}
|
|
156
|
+
closeTurn();
|
|
157
|
+
|
|
158
|
+
// A non-user title must cite at least one message sequence; without an anchor the
|
|
159
|
+
// event is omitted and DSH derives the title from the history instead.
|
|
160
|
+
if (firstUserSeq !== undefined) {
|
|
161
|
+
append('session/title', {
|
|
162
|
+
title: conversation.title || TITLE_FALLBACK,
|
|
163
|
+
messageSeqs: [firstUserSeq],
|
|
164
|
+
source: { kind: 'fallback' },
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return events;
|
|
168
|
+
}
|