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/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
7
|
import { SyncEngine } from './engine.js';
|
|
8
8
|
import { nativeEvents } from './native.js';
|
|
9
|
+
import { planReverse, appendTurns, readRolloutFacts, turnRecords, readSessionHeader, readSessionAny, readHeaderAny, sessionMessages, pendingTurns, prefixMatches, targetRollout, newRolloutPath, exportRecords } from './reverse.js';
|
|
9
10
|
|
|
10
11
|
export const name = 'dsh-plugin-external-session-sync';
|
|
11
12
|
|
|
@@ -21,7 +22,7 @@ export const inject = [
|
|
|
21
22
|
];
|
|
22
23
|
|
|
23
24
|
export const API = '/external-session-sync';
|
|
24
|
-
const VERSION = '1.
|
|
25
|
+
const VERSION = '1.10.3';
|
|
25
26
|
const PACKAGE_ID = 'dsh-plugin-external-session-sync';
|
|
26
27
|
const MAX_BODY_BYTES = 64 * 1024;
|
|
27
28
|
const DIAGNOSTIC_EVENTS = 60;
|
|
@@ -96,7 +97,6 @@ export function apply(ctx) {
|
|
|
96
97
|
lastSync = await engine.sync(await readBody(req));
|
|
97
98
|
send(res, lastSync);
|
|
98
99
|
});
|
|
99
|
-
|
|
100
100
|
route('/archive', 'POST', async (req, res) => {
|
|
101
101
|
const request = await readBody(req);
|
|
102
102
|
const requested = [...new Set(Array.isArray(request.sessionIds) ? request.sessionIds.filter(Boolean) : [])];
|
|
@@ -230,9 +230,6 @@ export function apply(ctx) {
|
|
|
230
230
|
send(res, { requested: requested.length, unarchived, failed });
|
|
231
231
|
});
|
|
232
232
|
|
|
233
|
-
// Permanent deletion of archived session payloads. Dry run unless dryRun is false.
|
|
234
|
-
route('/delete-archived', 'POST', async (req, res) => send(res, await engine.deleteArchived(await readBody(req))));
|
|
235
|
-
|
|
236
233
|
route('/legacy-imports', 'GET', async (req, res) => {
|
|
237
234
|
const rows = await engine.legacyImports();
|
|
238
235
|
send(res, {
|
|
@@ -248,6 +245,147 @@ export function apply(ctx) {
|
|
|
248
245
|
// under a fresh identity. Old logs stay archived, so unarchiveSession reverses it.
|
|
249
246
|
route('/migrate-heads', 'POST', async (req, res) => send(res, await engine.migrateLegacyHeads(await readBody(req))));
|
|
250
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
|
+
|
|
251
389
|
route('/health', 'GET', async (req, res) =>
|
|
252
390
|
send(res, {
|
|
253
391
|
...diagnostics,
|
|
@@ -256,6 +394,7 @@ export function apply(ctx) {
|
|
|
256
394
|
: {}),
|
|
257
395
|
}),
|
|
258
396
|
);
|
|
397
|
+
route('/refresh-client','POST',async(req,res)=>send(res,{revision:ctx.clientModules.rebuilt('dsh-plugin-external-session-sync')}));
|
|
259
398
|
route('/client-graph', 'GET', async (req, res) =>
|
|
260
399
|
send(res, {
|
|
261
400
|
entries: ctx.clientModules.graph().entries.filter((entry) => entry.id === PACKAGE_ID),
|
|
@@ -269,11 +408,14 @@ export function apply(ctx) {
|
|
|
269
408
|
send(res, { ok: true });
|
|
270
409
|
});
|
|
271
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
|
+
|
|
272
414
|
const tools = [
|
|
273
415
|
{
|
|
274
416
|
name: 'codex_sync_status',
|
|
275
417
|
description: 'List external Codex and Claude conversations and their DSH sync state.',
|
|
276
|
-
parameters: { type: 'object', properties: { source: { type: 'string', enum: ['codex', 'claude'] }, limit: { type: 'number' } } },
|
|
418
|
+
parameters: { type: 'object', properties: { source: { type: 'string', enum: ['codex', 'claude', 'antigravity'] }, limit: { type: 'number' } } },
|
|
277
419
|
run: async (args) => {
|
|
278
420
|
const status = await engine.status(args);
|
|
279
421
|
if (args.limit) status.discovered = status.discovered.slice(0, args.limit);
|
|
@@ -286,22 +428,22 @@ export function apply(ctx) {
|
|
|
286
428
|
parameters: {
|
|
287
429
|
type: 'object',
|
|
288
430
|
properties: {
|
|
289
|
-
source: { type: 'string', enum: ['codex', 'claude'] },
|
|
431
|
+
source: { type: 'string', enum: ['codex', 'claude', 'antigravity'] },
|
|
290
432
|
ids: { type: 'array', items: { type: 'string' } },
|
|
291
433
|
limit: { type: 'number' },
|
|
292
434
|
},
|
|
293
435
|
},
|
|
294
|
-
run: (args) => engine.sync(args),
|
|
436
|
+
run: async (args) => jsonSafe(await engine.sync(args)),
|
|
295
437
|
},
|
|
296
438
|
{
|
|
297
439
|
name: 'codex_read_conversation',
|
|
298
440
|
description: 'Read the newest visible user and assistant messages from an external conversation.',
|
|
299
441
|
parameters: {
|
|
300
442
|
type: 'object',
|
|
301
|
-
properties: { source: { type: 'string', enum: ['codex', 'claude'] }, id: { type: 'string' }, maxMessages: { type: 'number' } },
|
|
443
|
+
properties: { source: { type: 'string', enum: ['codex', 'claude', 'antigravity'] }, id: { type: 'string' }, maxMessages: { type: 'number' } },
|
|
302
444
|
required: ['source', 'id'],
|
|
303
445
|
},
|
|
304
|
-
run: (args) => engine.conversation(args.source, args.id, args.maxMessages),
|
|
446
|
+
run: async (args) => jsonSafe(await engine.conversation(args.source, args.id, args.maxMessages)),
|
|
305
447
|
},
|
|
306
448
|
];
|
|
307
449
|
for (const tool of tools) {
|
|
@@ -320,4 +462,4 @@ export function apply(ctx) {
|
|
|
320
462
|
|
|
321
463
|
log(`mounted ${PACKAGE_ID} ${VERSION}; no automatic imports`);
|
|
322
464
|
ctx.effect(() => () => log('disposed routes and tools'), 'external-sync.lifecycle');
|
|
323
|
-
}
|
|
465
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-external-session-sync",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.3",
|
|
4
4
|
"description": "Sync Codex and Claude Code conversation history into native DSH sessions, verify project membership, and archive old sessions in bulk.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
@@ -26,8 +26,9 @@
|
|
|
26
26
|
"engine.js",
|
|
27
27
|
"discovery.js",
|
|
28
28
|
"readers.js",
|
|
29
|
+
"readers-antigravity.js",
|
|
29
30
|
"native.js",
|
|
30
|
-
"
|
|
31
|
+
"reverse.js",
|
|
31
32
|
"client.js",
|
|
32
33
|
"cordis.patch.yml",
|
|
33
34
|
"locale/*.json",
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Antigravity reader/writer — ported from dsh-conversation-sync (same profile),
|
|
3
|
+
* whose Antigravity adapter is verified against this machine.
|
|
4
|
+
*
|
|
5
|
+
* Storage (verified here): `~/.gemini/antigravity{,-ide}/brain/<session>/.system_generated/
|
|
6
|
+
* logs/transcript.jsonl`. 102 of 249 brain directories carry it (12 IDE + 90 agent).
|
|
7
|
+
* Each line is JSON: {source, type, created_at, content, step_index, model, tool_calls}.
|
|
8
|
+
* The user turn is `USER_INPUT` / source containing USER, with the text wrapped in
|
|
9
|
+
* `<USER_REQUEST>…</USER_REQUEST>`; the assistant turn is `PLANNER_RESPONSE` / source
|
|
10
|
+
* containing MODEL and carries the REAL reply — this is why the transcript beats the
|
|
11
|
+
* SQLite `steps` table, which only holds reasoning.
|
|
12
|
+
*
|
|
13
|
+
* Writes append rendered lines to the same file. Every written line carries `dshSyncId`
|
|
14
|
+
* and the reader skips such lines, so our own writes never echo back into an import.
|
|
15
|
+
*/
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
20
|
+
|
|
21
|
+
const home = os.homedir();
|
|
22
|
+
|
|
23
|
+
export function antigravityRoots() {
|
|
24
|
+
const roots = [];
|
|
25
|
+
for (const [dir, profile] of [
|
|
26
|
+
['antigravity-ide', 'antigravity-ide'],
|
|
27
|
+
['antigravity', 'antigravity'],
|
|
28
|
+
['antigravity-cli', 'antigravity-cli'],
|
|
29
|
+
]) {
|
|
30
|
+
const brain = path.join(home, '.gemini', dir, 'brain');
|
|
31
|
+
if (fs.existsSync(brain)) roots.push({ brain, config: path.join(home, '.gemini', dir), profile });
|
|
32
|
+
}
|
|
33
|
+
return roots;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const LOG_REL = path.join('.system_generated', 'logs', 'transcript.jsonl');
|
|
37
|
+
const listCache = new Map();
|
|
38
|
+
const cwdCache = new Map();
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* `transcript.jsonl` carries no working directory, so the project is recovered from the
|
|
42
|
+
* sibling cascade database (`<config>/conversations/<id>.db`), whose
|
|
43
|
+
* `trajectory_metadata_blob` holds the `file://` root the conversation was opened on.
|
|
44
|
+
* Opened read-only; a missing or locked database simply yields null.
|
|
45
|
+
*/
|
|
46
|
+
function decodeFileUri(uri) {
|
|
47
|
+
const match = /^file:\/\/\/(.+)$/i.exec(uri);
|
|
48
|
+
if (!match) return null;
|
|
49
|
+
let rest = decodeURIComponent(match[1]);
|
|
50
|
+
if (/^[a-z]:/i.test(rest)) rest = rest.replace(/\//g, '\\');
|
|
51
|
+
rest = rest.replace(/\\+$/, '');
|
|
52
|
+
return rest || null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function antigravityCwdFromBlob(blob) {
|
|
56
|
+
if (!blob) return null;
|
|
57
|
+
const text = Buffer.from(blob).toString('utf8');
|
|
58
|
+
const uris = text.match(/file:\/\/\/[^\s\u0000-\u001f"']+/g) || [];
|
|
59
|
+
for (const uri of uris) {
|
|
60
|
+
const decoded = decodeFileUri(uri);
|
|
61
|
+
if (decoded) return decoded;
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function antigravityCwd(configDir, id) {
|
|
67
|
+
if (!configDir || !id) return null;
|
|
68
|
+
const dbPath = path.join(configDir, 'conversations', `${id}.db`);
|
|
69
|
+
let stat;
|
|
70
|
+
try {
|
|
71
|
+
stat = fs.statSync(dbPath);
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
const key = `${stat.size}:${Math.trunc(stat.mtimeMs)}`;
|
|
76
|
+
const cached = cwdCache.get(dbPath);
|
|
77
|
+
if (cached && cached.key === key) return cached.cwd;
|
|
78
|
+
let db;
|
|
79
|
+
try {
|
|
80
|
+
db = new DatabaseSync(dbPath, { readOnly: true, timeout: 1200 });
|
|
81
|
+
const row = db.prepare('select data from trajectory_metadata_blob limit 1').get();
|
|
82
|
+
const cwd = antigravityCwdFromBlob(row && row.data);
|
|
83
|
+
cwdCache.set(dbPath, { key, cwd });
|
|
84
|
+
return cwd;
|
|
85
|
+
} catch {
|
|
86
|
+
return null;
|
|
87
|
+
} finally {
|
|
88
|
+
try {
|
|
89
|
+
db && db.close();
|
|
90
|
+
} catch {
|
|
91
|
+
/* already closed */
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Lossless-JSON safe: drop lone surrogates and control characters that DSH rejects. */
|
|
97
|
+
export function safeText(value) {
|
|
98
|
+
if (typeof value !== 'string') return value;
|
|
99
|
+
return value
|
|
100
|
+
.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, '')
|
|
101
|
+
.replace(/(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, '')
|
|
102
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '');
|
|
103
|
+
}
|
|
104
|
+
function textOf(value) {
|
|
105
|
+
if (typeof value === 'string') return value;
|
|
106
|
+
if (Array.isArray(value)) return value.map(textOf).filter(Boolean).join('\n');
|
|
107
|
+
if (value && typeof value === 'object') return value.text ?? value.content ?? '';
|
|
108
|
+
return '';
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function antigravityClean(text) {
|
|
112
|
+
return String(text ?? '')
|
|
113
|
+
.replace(/^[\s\S]*?<USER_REQUEST>/, '')
|
|
114
|
+
.replace(/<\/USER_REQUEST>[\s\S]*$/, '')
|
|
115
|
+
.replace(/<ADDITIONAL_METADATA>[\s\S]*?<\/ADDITIONAL_METADATA>/g, '')
|
|
116
|
+
.trim();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function parseLine(line) {
|
|
120
|
+
let obj;
|
|
121
|
+
try {
|
|
122
|
+
obj = JSON.parse(line);
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
if (obj?.dshSyncId) return null;
|
|
127
|
+
const source = String(obj.source ?? '');
|
|
128
|
+
const type = String(obj.type ?? '');
|
|
129
|
+
if (type === 'CHECKPOINT' || type === 'GENERIC' || source === 'SYSTEM') return null;
|
|
130
|
+
const isUser = /USER/i.test(source) || type === 'USER_INPUT';
|
|
131
|
+
const isModel = /MODEL/i.test(source) || type === 'PLANNER_RESPONSE';
|
|
132
|
+
const raw = isUser ? antigravityClean(obj.content) : textOf(obj.content);
|
|
133
|
+
if (!raw) return null;
|
|
134
|
+
const role = isUser ? 'user' : isModel ? 'assistant' : null;
|
|
135
|
+
if (!role) return null;
|
|
136
|
+
return { role, text: safeText(raw), time: obj.created_at ? Date.parse(obj.created_at) || null : null, model: obj.model ?? null };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function transcriptPath(dir) {
|
|
140
|
+
return path.join(dir, LOG_REL);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** One row per brain directory that actually has a readable transcript. */
|
|
144
|
+
export function listAntigravitySessions() {
|
|
145
|
+
const rows = [];
|
|
146
|
+
for (const root of antigravityRoots()) {
|
|
147
|
+
let entries = [];
|
|
148
|
+
try {
|
|
149
|
+
entries = fs.readdirSync(root.brain, { withFileTypes: true });
|
|
150
|
+
} catch {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
for (const entry of entries) {
|
|
154
|
+
if (!entry.isDirectory()) continue;
|
|
155
|
+
const dir = path.join(root.brain, entry.name);
|
|
156
|
+
const file = transcriptPath(dir);
|
|
157
|
+
let stat;
|
|
158
|
+
try {
|
|
159
|
+
stat = fs.statSync(file);
|
|
160
|
+
} catch {
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (!stat.size) continue;
|
|
164
|
+
const key = `${stat.size}:${Math.trunc(stat.mtimeMs)}`;
|
|
165
|
+
const cached = listCache.get(file);
|
|
166
|
+
if (cached && cached.key === key) {
|
|
167
|
+
rows.push(cached.row);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
let title = null;
|
|
171
|
+
let users = 0;
|
|
172
|
+
let messages = 0;
|
|
173
|
+
let firstUser = null;
|
|
174
|
+
let lastTime = stat.mtimeMs;
|
|
175
|
+
try {
|
|
176
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
177
|
+
for (const line of text.split('\n')) {
|
|
178
|
+
if (!line.trim()) continue;
|
|
179
|
+
const parsed = parseLine(line);
|
|
180
|
+
if (!parsed) continue;
|
|
181
|
+
messages += 1;
|
|
182
|
+
if (parsed.role === 'user') {
|
|
183
|
+
users += 1;
|
|
184
|
+
if (!firstUser) firstUser = parsed.text;
|
|
185
|
+
}
|
|
186
|
+
if (parsed.time) lastTime = Math.max(lastTime, parsed.time);
|
|
187
|
+
}
|
|
188
|
+
} catch {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (!messages) continue;
|
|
192
|
+
title = firstUser ? firstUser.split('\n')[0].slice(0, 120) : '未命名会话';
|
|
193
|
+
const row = {
|
|
194
|
+
id: entry.name,
|
|
195
|
+
source: 'antigravity',
|
|
196
|
+
profile: root.profile,
|
|
197
|
+
file,
|
|
198
|
+
title,
|
|
199
|
+
cwd: antigravityCwd(root.config, entry.name),
|
|
200
|
+
updatedAt: lastTime,
|
|
201
|
+
userMessages: users,
|
|
202
|
+
steps: messages,
|
|
203
|
+
revision: key,
|
|
204
|
+
isSubagent: false,
|
|
205
|
+
firstUserText: firstUser ? safeText(firstUser).slice(0, 400) : null,
|
|
206
|
+
};
|
|
207
|
+
listCache.set(file, { key, row });
|
|
208
|
+
rows.push(row);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return rows.sort((a, b) => Number(b.updatedAt || 0) - Number(a.updatedAt || 0));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export async function listAntigravitySessionsAsync() {
|
|
215
|
+
return listAntigravitySessions();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function resolveDir(idOrFile) {
|
|
219
|
+
const text = String(idOrFile);
|
|
220
|
+
if (text.endsWith('.jsonl')) return path.dirname(path.dirname(path.dirname(text)));
|
|
221
|
+
for (const root of antigravityRoots()) {
|
|
222
|
+
const dir = path.join(root.brain, text);
|
|
223
|
+
if (fs.existsSync(dir)) return dir;
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Full conversation, including the assistant replies the UI showed. */
|
|
229
|
+
export function readAntigravityConversation(idOrFile) {
|
|
230
|
+
const dir = resolveDir(idOrFile);
|
|
231
|
+
if (!dir) return null;
|
|
232
|
+
const file = transcriptPath(dir);
|
|
233
|
+
let text;
|
|
234
|
+
try {
|
|
235
|
+
text = fs.readFileSync(file, 'utf8');
|
|
236
|
+
} catch {
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
const messages = [];
|
|
240
|
+
for (const line of text.split('\n')) {
|
|
241
|
+
if (!line.trim()) continue;
|
|
242
|
+
const parsed = parseLine(line);
|
|
243
|
+
if (parsed) messages.push(parsed);
|
|
244
|
+
}
|
|
245
|
+
if (!messages.length) return null;
|
|
246
|
+
const firstUser = messages.find((message) => message.role === 'user');
|
|
247
|
+
const id = path.basename(dir);
|
|
248
|
+
const config = path.dirname(path.dirname(dir));
|
|
249
|
+
return {
|
|
250
|
+
id,
|
|
251
|
+
source: 'antigravity',
|
|
252
|
+
title: safeText(firstUser ? firstUser.text.split('\n')[0].slice(0, 120) : '未命名会话'),
|
|
253
|
+
cwd: antigravityCwd(config, id),
|
|
254
|
+
messages,
|
|
255
|
+
updatedAt: (() => {
|
|
256
|
+
try {
|
|
257
|
+
return Math.trunc(fs.statSync(file).mtimeMs);
|
|
258
|
+
} catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
})(),
|
|
262
|
+
lastMessageTime: messages[messages.length - 1].time,
|
|
263
|
+
assistantRepliesPersisted: true,
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Append DSH-side turns into the Antigravity transcript.
|
|
269
|
+
* Marks every line with `dshSyncId` so a later import ignores what we wrote.
|
|
270
|
+
*/
|
|
271
|
+
export function appendAntigravityTurns(idOrFile, turns, options = {}) {
|
|
272
|
+
const dir = resolveDir(idOrFile);
|
|
273
|
+
if (!dir) throw new Error('找不到该 Antigravity 会话目录');
|
|
274
|
+
const file = transcriptPath(dir);
|
|
275
|
+
if (!fs.existsSync(file)) throw new Error('该会话没有 transcript.jsonl,无法写回');
|
|
276
|
+
const syncId = options.syncId || `dsh-${Date.now()}`;
|
|
277
|
+
const title = options.title || null;
|
|
278
|
+
const lines = [];
|
|
279
|
+
for (const turn of turns) {
|
|
280
|
+
const isUser = turn.role !== 'assistant';
|
|
281
|
+
lines.push(
|
|
282
|
+
JSON.stringify({
|
|
283
|
+
step_index: 0,
|
|
284
|
+
source: isUser ? 'USER_EXPLICIT' : 'MODEL',
|
|
285
|
+
type: isUser ? 'USER_INPUT' : 'PLANNER_RESPONSE',
|
|
286
|
+
status: null,
|
|
287
|
+
created_at: new Date(turn.time || Date.now()).toISOString(),
|
|
288
|
+
content: isUser ? `<USER_REQUEST>\n${turn.text}\n</USER_REQUEST>` : turn.text,
|
|
289
|
+
dshSyncId: syncId,
|
|
290
|
+
...(title ? { dshTitle: title } : {}),
|
|
291
|
+
}),
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
const payload = `${lines.join('\n')}\n`;
|
|
295
|
+
const before = fs.readFileSync(file);
|
|
296
|
+
const backup = `${file}.dsh-sync-backup-${Date.now()}`;
|
|
297
|
+
fs.writeFileSync(backup, before);
|
|
298
|
+
fs.appendFileSync(file, payload, 'utf8');
|
|
299
|
+
const after = fs.readFileSync(file, 'utf8');
|
|
300
|
+
if (!after.endsWith(payload)) throw new Error('写入校验失败:追加内容未落盘');
|
|
301
|
+
return { file, backup, appended: lines.length, bytes: Buffer.byteLength(payload), syncId };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function clearAntigravityCache() {
|
|
305
|
+
listCache.clear();
|
|
306
|
+
}
|