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/package.json CHANGED
@@ -1,6 +1,55 @@
1
- {
2
- "name": "dsh-plugin-external-session-sync",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dsh-plugin-external-session-sync",
3
+ "version": "1.10.3",
4
+ "description": "Sync Codex and Claude Code conversation history into native DSH sessions, verify project membership, and archive old sessions in bulk.",
5
+ "keywords": [
6
+ "dsh",
7
+ "deepseek-harness",
8
+ "cordis",
9
+ "codex",
10
+ "claude-code",
11
+ "session-sync",
12
+ "migration"
13
+ ],
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "main": "index.js",
17
+ "exports": {
18
+ ".": "./index.js",
19
+ "./client": "./client.js",
20
+ "./package.json": "./package.json",
21
+ "./locale/*.json": "./locale/*.json",
22
+ "./icon": "./icon.svg"
23
+ },
24
+ "files": [
25
+ "index.js",
26
+ "engine.js",
27
+ "discovery.js",
28
+ "readers.js",
29
+ "readers-antigravity.js",
30
+ "native.js",
31
+ "reverse.js",
32
+ "client.js",
33
+ "cordis.patch.yml",
34
+ "locale/*.json",
35
+ "icon.svg",
36
+ "README.md",
37
+ "CHANGELOG.md",
38
+ "LICENSE"
39
+ ],
40
+ "scripts": {
41
+ "test": "node --test test/"
42
+ },
43
+ "engines": {
44
+ "node": ">=22.5"
45
+ },
46
+ "dsh": {
47
+ "bundle": {
48
+ "patch": "./cordis.patch.yml"
49
+ },
50
+ "client": {
51
+ "platform": "web",
52
+ "inject": []
53
+ }
54
+ }
55
+ }
@@ -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
+ }