@wwwfz/dsh-agent-bridge 0.10.0 → 0.11.0

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/src/index.js CHANGED
@@ -112,6 +112,12 @@ export function apply(ctx) {
112
112
  if (!host) throw Object.assign(new Error('当前 DSH 未提供会话迁入服务。'), { status: 409 })
113
113
  return saveNativeSession(host, record, cwd)
114
114
  },
115
+ async canOpenConversation(id) {
116
+ const host = services()
117
+ if (!host || host.workspaces.archivedSessionIds?.includes(id)) return false
118
+ if (!host.persistence.stat) return true
119
+ return (await host.persistence.stat(id))?.header?.id === id
120
+ },
115
121
  skillHandoff,
116
122
  loadSourceRecord,
117
123
  })
@@ -123,6 +129,9 @@ export function apply(ctx) {
123
129
  ['/reader.css', 'reader.css', 'text/css; charset=utf-8'],
124
130
  ['/inline-process.css', 'inline-process.css', 'text/css; charset=utf-8'],
125
131
  ['/panel.js', 'panel.js', 'text/javascript; charset=utf-8'],
132
+ ['/relay-categories.js', 'relay-categories.js', 'text/javascript; charset=utf-8'],
133
+ ['/share-review.js', 'share-review.js', 'text/javascript; charset=utf-8'],
134
+ ['/share-redaction.js', 'share-redaction.js', 'text/javascript; charset=utf-8'],
126
135
  ['/project-context.js', 'project-context.js', 'text/javascript; charset=utf-8'],
127
136
  ['/markdown.js', 'markdown.js', 'text/javascript; charset=utf-8'],
128
137
  ['/vendor/markdown-it.mjs', 'vendor/markdown-it.mjs', 'text/javascript; charset=utf-8'],
@@ -159,6 +168,7 @@ export function apply(ctx) {
159
168
  } catch (error) {
160
169
  if (!res.headersSent) json(res, error.status || 500, {
161
170
  error: error.status ? error.message : '无法读取本地资料。请检查 agent-bridge.json 和文件权限后刷新。',
171
+ ...(isSessionId(error.recoveryTicket) ? { recoveryTicket: error.recoveryTicket } : {}),
162
172
  })
163
173
  }
164
174
  },
@@ -177,7 +187,8 @@ export function apply(ctx) {
177
187
  return
178
188
  }
179
189
  const input = await readBody(req)
180
- const conversationAction = ['list-conversations', 'preview-conversation', 'import-conversation'].includes(input.action)
190
+ const conversationAction = ['list-conversations', 'search-conversations', 'conversation-import-status', 'preview-conversation',
191
+ 'preview-conversation-context', 'retarget-failed-conversation', 'import-conversation'].includes(input.action)
181
192
  const nativeSessionImport = (conversationAction || input.action === 'catalog') && Boolean(services())
182
193
  if (conversationAction && !nativeSessionImport) {
183
194
  json(res, 403, { error: '请在支持会话迁入的本机 DSH 主界面中使用。' })
@@ -251,25 +262,27 @@ export function apply(ctx) {
251
262
  'Content-Disposition': attachmentDisposition(attachment.name, `${attachmentId.slice(0, 12)}.${extension}`, inline) })
252
263
  res.end(attachment.bytes)
253
264
  })
254
- register('/conversation-export', 'GET', async (req, res) => {
255
- const query = new URL(req.url ?? '/', 'http://localhost').searchParams
265
+ async function streamConversationMarkdown(query, res, format) {
256
266
  const { config, stored } = await loadArchive(query.get('sessionId'))
257
267
  async function* pages() {
258
268
  let cursor
259
269
  do {
260
270
  const page = await readHistoryPage(config, stored.id, cursor)
261
- if (!page || res.destroyed) return
271
+ if (res.destroyed) return
272
+ if (!page) throw new Error('The source archive is no longer available')
262
273
  yield page
263
274
  cursor = page.nextCursor
264
275
  } while (cursor)
265
276
  }
266
- res.writeHead(200, { ...pageHeaders, 'Content-Type': 'text/markdown; charset=utf-8',
267
- 'Content-Disposition': 'attachment; filename="agent-conversation.md"' })
277
+ res.writeHead(200, format === 'share'
278
+ ? { ...pageHeaders, 'Content-Type': 'text/plain; charset=utf-8' }
279
+ : { ...pageHeaders, 'Content-Type': 'text/markdown; charset=utf-8',
280
+ 'Content-Disposition': 'attachment; filename="agent-conversation.md"' })
268
281
  try {
269
282
  const signal = new AbortController()
270
283
  res.once('close', () => signal.abort())
271
284
  for await (const chunk of sourceHistoryMarkdown(stored, pages(), {
272
- format: query.get('format'), includeTrace: query.get('includeTrace') === 'true',
285
+ format, includeTrace: query.get('includeTrace') === 'true',
273
286
  })) {
274
287
  if (res.destroyed) return
275
288
  if (chunk && !res.write(chunk)) await once(res, 'drain', { signal: signal.signal })
@@ -278,5 +291,16 @@ export function apply(ctx) {
278
291
  } catch (error) {
279
292
  if (!res.destroyed) res.destroy(error)
280
293
  }
294
+ }
295
+ register('/conversation-export', 'GET', async (req, res) => {
296
+ const query = new URL(req.url ?? '/', 'http://localhost').searchParams
297
+ if (query.get('format') === 'share') {
298
+ json(res, 409, { error: '请在来源记录中审阅并确认分享版后下载。' })
299
+ return
300
+ }
301
+ await streamConversationMarkdown(query, res, 'local')
302
+ })
303
+ register('/conversation-share-preview', 'GET', async (req, res) => {
304
+ await streamConversationMarkdown(new URL(req.url ?? '/', 'http://localhost').searchParams, res, 'share')
281
305
  })
282
306
  }
@@ -143,3 +143,53 @@ export async function writeProjectContinuation(config, projectId) {
143
143
  RETURNING continued_at`).get(projectId, Date.now()).continued_at
144
144
  })
145
145
  }
146
+
147
+ export async function readCodexAliases(config) {
148
+ const projects = new Map()
149
+ await readArchive(config, db => {
150
+ if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='codex_source_aliases'").get()) return
151
+ for (const { project_id, source_id, alias } of db.prepare('SELECT project_id,source_id,alias FROM codex_source_aliases WHERE source_id IS NOT NULL').iterate()) {
152
+ if (!projects.has(project_id)) projects.set(project_id, new Map())
153
+ const sources = projects.get(project_id)
154
+ if (!sources.has(source_id)) sources.set(source_id, [])
155
+ sources.get(source_id).push(alias)
156
+ }
157
+ })
158
+ return projects
159
+ }
160
+
161
+ export async function saveCodexAliases(config, projectId, links) {
162
+ await writeArchive(config, true, db => {
163
+ db.exec(`CREATE TABLE IF NOT EXISTS codex_source_aliases (
164
+ project_id TEXT NOT NULL, alias TEXT NOT NULL, source_id TEXT, PRIMARY KEY (project_id,alias)
165
+ ) STRICT`)
166
+ const insert = db.prepare(`INSERT INTO codex_source_aliases VALUES (?,?,?) ON CONFLICT(project_id,alias)
167
+ DO UPDATE SET source_id=NULL WHERE source_id<>excluded.source_id`)
168
+ for (const [source, alias] of links) insert.run(projectId, alias, source.id)
169
+ })
170
+ }
171
+
172
+ export async function readProjectRelay(config, projectId) {
173
+ return await readArchive(config, db => {
174
+ if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE name='project_relay' AND type='table'").get()) return []
175
+ return db.prepare('SELECT item FROM project_relay WHERE project_id=? ORDER BY rowid')
176
+ .all(projectId).map(row => JSON.parse(row.item))
177
+ }) ?? []
178
+ }
179
+
180
+ export async function changeProjectRelay(config, projectId, id, change, previousIds = []) {
181
+ return writeArchive(config, true, db => {
182
+ db.exec(`CREATE TABLE IF NOT EXISTS project_relay (
183
+ project_id TEXT NOT NULL, id TEXT NOT NULL, item TEXT NOT NULL, PRIMARY KEY (project_id,id)
184
+ ) STRICT`)
185
+ const row = db.prepare(`SELECT id,item FROM project_relay WHERE project_id=? AND id IN (SELECT value FROM json_each(?))
186
+ ORDER BY (id=?) DESC,rowid LIMIT 1`).get(projectId, JSON.stringify([id, ...previousIds]), id)
187
+ const storedId = row?.id ?? id
188
+ const item = change(row && JSON.parse(row.item))
189
+ if (item) {
190
+ db.prepare(`INSERT INTO project_relay VALUES (?,?,?) ON CONFLICT(project_id,id)
191
+ DO UPDATE SET item=excluded.item`).run(projectId, storedId, JSON.stringify(item))
192
+ } else db.prepare('DELETE FROM project_relay WHERE project_id=? AND id=?').run(projectId, storedId)
193
+ return item ?? null
194
+ })
195
+ }
package/src/projects.js CHANGED
@@ -5,6 +5,8 @@ import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import zlib from 'node:zlib';
7
7
  import { sourceJson, sourceJsonl, sourceValueLimit } from './conversation-readers.js';
8
+ import { conversationId, keyFor, pathKey as projectPathKey } from './handoff.js';
9
+ import { readCodexAliases } from './project-archive.js';
8
10
 
9
11
  const maxMessages = 36;
10
12
  const maxMessageLength = 4_000;
@@ -16,6 +18,7 @@ const codexLocations = ['sessions', 'archived_sessions'];
16
18
  const jsonlFile = /\.jsonl$/i;
17
19
  const compressedCodexFile = /\.jsonl\.zst$/i;
18
20
  const hasZstd = typeof zlib.createZstdDecompress === 'function';
21
+ const indexedCodexHeaders = new Map();
19
22
  const conversationLimits = { messages: 600, characters: 160_000, messageLength: 24_000 };
20
23
  const traceItemLimit = 600;
21
24
  const traceTextLimit = 8_000;
@@ -192,7 +195,35 @@ async function archivedProjects(file) {
192
195
  });
193
196
  }
194
197
 
195
- async function codexProjects(root) {
198
+ async function indexedCodexMetadata(file, info) {
199
+ const stamp = [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(':');
200
+ const cached = indexedCodexHeaders.get(file);
201
+ if (cached?.stamp === stamp) return cached.meta;
202
+ const input = compressedCodexFile.test(file) ? zstdChunks(file) : createReadStream(file, { highWaterMark: 8 * 1024 });
203
+ const chunks = [];
204
+ let bytes = 0;
205
+ for await (const chunk of input) {
206
+ const newline = chunk.indexOf(10);
207
+ const line = newline < 0 ? chunk : chunk.subarray(0, newline);
208
+ bytes += line.length;
209
+ if (bytes > transcriptHeaderBytes) break;
210
+ chunks.push(line);
211
+ if (newline >= 0) break;
212
+ }
213
+ const row = bytes <= transcriptHeaderBytes && json(Buffer.concat(chunks).toString('utf8').replace(/^\uFEFF/, ''));
214
+ const payload = row?.type === 'session_meta' && row.payload;
215
+ const meta = payload ? {
216
+ id: typeof payload.id === 'string' ? payload.id : undefined,
217
+ cwd: typeof payload.cwd === 'string' ? payload.cwd : undefined,
218
+ } : undefined;
219
+ // Keep only identity fields, never conversation text. Unchanged indexed rolls
220
+ // already require a stat for containment/type checking and need no second read.
221
+ if (!cached && indexedCodexHeaders.size >= 16_384) indexedCodexHeaders.delete(indexedCodexHeaders.keys().next().value);
222
+ indexedCodexHeaders.set(file, { stamp, meta });
223
+ return meta;
224
+ }
225
+
226
+ async function codexProjects(root, configured) {
196
227
  const entries = await directories(root);
197
228
  const states = entries.filter(entry => entry.isFile() && /^state_\d+\.sqlite$/.test(entry.name));
198
229
  states.sort((a, b) => Number(b.name.match(/\d+/)[0]) - Number(a.name.match(/\d+/)[0]));
@@ -216,11 +247,35 @@ async function codexProjects(root) {
216
247
  }
217
248
  const bases = await transcriptDirectories(root, codexLocations);
218
249
  if (!bases.length) throw indexError ?? missingStore();
250
+ const profile = codexLocations.includes(path.basename(root).toLowerCase()) ? path.dirname(root) : root;
251
+ const rolloutRoots = configured.some(dir => pathKey(dir) === pathKey(profile))
252
+ ? codexLocations.map(name => path.join(profile, name))
253
+ : configured.filter(dir => pathKey(path.dirname(dir)) === pathKey(profile) && codexLocations.includes(path.basename(dir).toLowerCase()));
254
+ const threadKey = (cwd, id) => typeof cwd === 'string' && typeof id === 'string' && id.trim()
255
+ ? JSON.stringify([pathKey(cwd), id]) : undefined;
256
+ const observed = new Map();
257
+ function remember(key, file) {
258
+ if (!key || typeof file !== 'string' || !path.isAbsolute(file)) return;
259
+ // Windows index rows sometimes store a namespaced path; realpath(), which
260
+ // supplied the old bridge IDs, returned the ordinary absolute path.
261
+ const clean = path.normalize(process.platform === 'win32'
262
+ ? file.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '') : file);
263
+ if (!(jsonlFile.test(clean) || compressedCodexFile.test(clean)) || !rolloutRoots.some(base => inside(base, clean))) return;
264
+ if (!observed.has(key)) observed.set(key, new Set());
265
+ observed.get(key).add(clean);
266
+ }
219
267
  const byFile = new Map();
220
268
  for (let offset = 0; offset < (indexed?.length ?? 0); offset += 32) {
221
269
  const batch = await Promise.all(indexed.slice(offset, offset + 32).map(async ({ id, cwd, rollout_path, date, title }) => {
222
- const file = await resolveCodexTranscript(rollout_path, bases);
223
- return file ? { cwd, agent: 'codex', archive: { kind: 'codex', file, root, id, date, title } } : undefined;
270
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return;
271
+ remember(threadKey(cwd, id), rollout_path);
272
+ const found = await resolveCodexTranscript(rollout_path, bases);
273
+ if (!found) return;
274
+ const { file, info } = found;
275
+ const meta = await indexedCodexMetadata(file, info).catch(() => undefined);
276
+ if ((meta?.id && id && meta.id !== id)
277
+ || (meta && (!meta.cwd || !path.isAbsolute(meta.cwd) || (pathKey(meta.cwd) !== pathKey(cwd) && !await sameDirectory(meta.cwd, cwd))))) return;
278
+ return { cwd, agent: 'codex', archive: { kind: 'codex', file, root, id: meta?.id || id, date, title } };
224
279
  }));
225
280
  for (const project of batch.filter(Boolean)) {
226
281
  const key = pathKey(project.archive.file);
@@ -229,16 +284,26 @@ async function codexProjects(root) {
229
284
  }
230
285
  // SQLite can lag an active or archived transcript. Keep its titles for
231
286
  // resolved files and discover any additional plain or compressed transcripts.
232
- const byId = new Set([...byFile.values()].map(project => project.archive.id).filter(Boolean));
287
+ const byId = new Set([...byFile.values()].map(project => threadKey(project.cwd, project.archive.id)).filter(Boolean));
233
288
  const include = file => !byFile.has(pathKey(file))
234
289
  && (jsonlFile.test(file) || (hasZstd && compressedCodexFile.test(file)));
235
290
  const fallback = await scanJsonlProjects(root, 'codex', bases, 4, include);
236
291
  for (const project of fallback) {
237
292
  const { file, id } = project.archive;
238
- if (id && byId.has(id)) continue;
239
- if (id) byId.add(id);
293
+ const key = threadKey(project.cwd, id);
294
+ remember(key, file);
295
+ if (key && byId.has(key)) continue;
296
+ if (key) byId.add(key);
240
297
  byFile.set(pathKey(file), project);
241
298
  }
299
+ for (const { cwd, archive } of byFile.values()) {
300
+ const key = threadKey(cwd, archive.id);
301
+ if (!key) continue;
302
+ archive.profile = profile;
303
+ archive.rolloutRoots = rolloutRoots;
304
+ const previousFiles = [...observed.get(key) ?? []].filter(file => file !== archive.file);
305
+ if (previousFiles.length) archive.previousFiles = previousFiles;
306
+ }
242
307
  return [...byFile.values()];
243
308
  }
244
309
 
@@ -250,7 +315,8 @@ async function resolveCodexTranscript(file, bases) {
250
315
  const actual = await physicalPath(candidate);
251
316
  if (!actual || !bases.some(base => inside(base, actual))
252
317
  || !(jsonlFile.test(actual) || hasZstd && compressedCodexFile.test(actual))) continue;
253
- if ((await stat(actual).catch(() => undefined))?.isFile()) return actual;
318
+ const info = await stat(actual, { bigint: true }).catch(() => undefined);
319
+ if (info?.isFile()) return { file: actual, info };
254
320
  }
255
321
  }
256
322
 
@@ -485,7 +551,7 @@ async function antigravityProjects(root) {
485
551
  return projects;
486
552
  }
487
553
 
488
- export async function scanProjects(config) {
554
+ export async function scanProjects(config, { includeTranscripts = true } = {}) {
489
555
  const projects = [];
490
556
  const sources = [];
491
557
  const discovered = new Map();
@@ -502,7 +568,7 @@ export async function scanProjects(config) {
502
568
  let found = 0;
503
569
  for (const file of candidates) {
504
570
  try {
505
- const rows = await load(file);
571
+ const rows = await load(file, candidates);
506
572
  for (const row of rows) projects.push(row);
507
573
  found += rows.length;
508
574
  succeeded++;
@@ -518,19 +584,21 @@ export async function scanProjects(config) {
518
584
 
519
585
  await Promise.all([
520
586
  scan('workspacehub', 'Agent Workspace Manager', config.workspaceHubRoots ?? [], workspaceProjects),
521
- scan('agentsview', 'AgentsView 会话归档', config.archiveFiles ?? [], archivedProjects),
522
- ...Object.entries({
523
- codex: codexProjects, claude: root => jsonlProjects(root, 'claude'),
524
- opencode: opencodeProjects, workbuddy: root => jsonlProjects(root, 'workbuddy'),
525
- qoder: root => jsonlProjects(root, 'qoder'), qwen: root => jsonlProjects(root, 'qwen', ['projects'], 2),
526
- trae: root => editorProjects(root, 'trae'), copilot: root => editorProjects(root, 'copilot'),
527
- gemini: geminiProjects,
528
- antigravity: antigravityProjects,
529
- }).map(([agent, load]) => scan(agent, agentLabels[agent], configuredRoots(config, agent), load, {
530
- trae: '支持工作区元数据;会话可从 AgentsView 读取已归档部分',
531
- copilot: '支持 VS Code 工作区会话及本机会话库;其他版本可从 AgentsView 读取已归档部分',
532
- antigravity: '支持工作区元数据和 CLI 提示记录;完整会话可从 AgentsView 读取已归档部分',
533
- }[agent])),
587
+ ...(includeTranscripts ? [
588
+ scan('agentsview', 'AgentsView 会话归档', config.archiveFiles ?? [], archivedProjects),
589
+ ...Object.entries({
590
+ codex: codexProjects, claude: root => jsonlProjects(root, 'claude'),
591
+ opencode: opencodeProjects, workbuddy: root => jsonlProjects(root, 'workbuddy'),
592
+ qoder: root => jsonlProjects(root, 'qoder'), qwen: root => jsonlProjects(root, 'qwen', ['projects'], 2),
593
+ trae: root => editorProjects(root, 'trae'), copilot: root => editorProjects(root, 'copilot'),
594
+ gemini: geminiProjects,
595
+ antigravity: antigravityProjects,
596
+ }).map(([agent, load]) => scan(agent, agentLabels[agent], configuredRoots(config, agent), load, {
597
+ trae: '支持工作区元数据;会话可从 AgentsView 读取已归档部分',
598
+ copilot: '支持 VS Code 工作区会话及本机会话库;其他版本可从 AgentsView 读取已归档部分',
599
+ antigravity: '支持工作区元数据和 CLI 提示记录;完整会话可从 AgentsView 读取已归档部分',
600
+ }[agent])),
601
+ ] : []),
534
602
  ]);
535
603
 
536
604
  for (const cwd of config.projectRoots ?? []) projects.push({ cwd, agent: 'manual' });
@@ -540,12 +608,21 @@ export async function scanProjects(config) {
540
608
  const key = pathKey(project.cwd);
541
609
  if (!canonical.has(key)) canonical.set(key, await physicalPath(project.cwd) ?? path.normalize(project.cwd));
542
610
  project.cwd = canonical.get(key);
611
+ if (project.archive?.profile) project.archive.sourceCwd = project.cwd;
543
612
  const timestamp = dateMillis(project.archive?.date);
544
613
  if (timestamp > 0 && timestamp < 8_640_000_000_000_000) project.updatedAt = new Date(timestamp).toISOString();
545
614
  const identity = JSON.stringify([pathKey(project.cwd), project.agent, project.projectId, project.archive?.kind, project.archive?.file, project.archive?.id]);
546
615
  const previous = discovered.get(identity);
547
616
  if (!previous || compareDate(project.archive?.date, previous.archive?.date) > 0) discovered.set(identity, project);
548
617
  }
618
+ const sourcesWithThreads = [...discovered.values()].filter(item => item.archive?.profile);
619
+ if (sourcesWithThreads.length && config.configFile) {
620
+ const aliases = await readCodexAliases(config).catch(() => new Map());
621
+ for (const { cwd, archive } of sourcesWithThreads) {
622
+ const known = aliases.get(keyFor(projectPathKey(cwd)))?.get(conversationId(archive));
623
+ if (known) archive.savedIds = known;
624
+ }
625
+ }
549
626
  return { projects: [...discovered.values()], sources: sources.sort((a, b) => a.id.localeCompare(b.id)) };
550
627
  }
551
628
 
@@ -708,13 +785,14 @@ function traceCallId(value) {
708
785
  }
709
786
 
710
787
  function addSummary(result, text, time, id) {
788
+ if (!result.events && !result.trace) return;
711
789
  const value = result.events ? traceValue(text) : cleanTraceText(text);
712
790
  if (!value.trim()) return;
713
791
  addTrace(result, { kind: 'summary', text: value, status: 'ok', time: dateMillis(time), id });
714
792
  }
715
793
 
716
794
  function addToolCall(result, name, callId, input, time) {
717
- if (typeof name !== 'string' || !name.trim()) return;
795
+ if ((!result.events && !result.trace) || typeof name !== 'string' || !name.trim()) return;
718
796
  addTrace(result, {
719
797
  kind: 'tool_call', name: name.trim().slice(0, 120),
720
798
  callId: traceCallId(callId),
@@ -1128,6 +1206,7 @@ function readCodexRow(result, row) {
1128
1206
  return;
1129
1207
  }
1130
1208
  if (payload?.type === 'reasoning') {
1209
+ if (!result.events && !result.trace) return;
1131
1210
  // Only the visible summary is retained; encrypted reasoning has no text.
1132
1211
  const summary = Array.isArray(payload.summary) ? payload.summary : [];
1133
1212
  const text = summary.filter(item => item?.type === 'summary_text' && typeof item.text === 'string')
@@ -1141,6 +1220,7 @@ function readCodexRow(result, row) {
1141
1220
  return;
1142
1221
  }
1143
1222
  if (payload?.type === 'function_call_output' || payload?.type === 'custom_tool_call_output') {
1223
+ if (!result.events && !result.trace) return;
1144
1224
  const output = payload.output ?? payload.content;
1145
1225
  const text = result.events ? traceValue(sourceToolOutput(result, output, payload.call_id))
1146
1226
  : (Array.isArray(output)
@@ -1209,7 +1289,7 @@ async function allowedJsonl(descriptor, config) {
1209
1289
  const bases = (await Promise.all(configuredRoots(config, descriptor.kind)
1210
1290
  .map(root => transcriptDirectories(root, locations)))).flat();
1211
1291
  let file;
1212
- if (codex) file = await resolveCodexTranscript(descriptor.file, bases);
1292
+ if (codex) file = (await resolveCodexTranscript(descriptor.file, bases))?.file;
1213
1293
  else {
1214
1294
  for (const base of bases) {
1215
1295
  file = await scopedFile(descriptor.file, base);
@@ -1755,20 +1835,20 @@ export async function probeConversation(archive, options) {
1755
1835
  return reason ? { state: 'unknown', reason } : { state: 'empty' };
1756
1836
  }
1757
1837
 
1758
- export async function readConversationHistory(archive, cwd, config) {
1838
+ export async function readConversationHistory(archive, cwd, config, { includeTrace = true } = {}) {
1759
1839
  const result = {
1760
1840
  messages: [], usedSkills: new Set(), limits: conversationLimits, characters: 0, truncated: false,
1761
- trace: [], traceKeys: new Set(), traceOrder: 0, messageSeq: 0, turn: 0, turnRef: undefined,
1841
+ ...(includeTrace ? { trace: [], traceKeys: new Set(), traceOrder: 0, messageSeq: 0, turn: 0, turnRef: undefined } : {}),
1762
1842
  readStats: { userMessages: 0, assistantMessages: 0, timedMessages: 0 },
1763
1843
  };
1764
1844
  await readHistory(archive, cwd, config, result);
1765
1845
  const calls = new Map();
1766
- for (const item of result.trace) {
1846
+ for (const item of result.trace ?? []) {
1767
1847
  if (item.kind !== 'tool_call') continue;
1768
1848
  item.status = 'missing';
1769
1849
  if (item.callId) calls.set(item.callId, item);
1770
1850
  }
1771
- for (const item of result.trace) {
1851
+ for (const item of result.trace ?? []) {
1772
1852
  if (item.kind !== 'tool_result') continue;
1773
1853
  const call = calls.get(item.callId);
1774
1854
  item.turnRef = call?.turnRef;
@@ -1794,7 +1874,7 @@ export async function readConversationHistory(archive, cwd, config) {
1794
1874
  // The last displayed reply in each source turn is its disclosure anchor.
1795
1875
  // A turn without a reply is anchored to its own user message.
1796
1876
  const indexOf = new Map(retained.map((message, index) => [message.turnRef, index]));
1797
- const trace = result.trace
1877
+ const trace = (result.trace ?? [])
1798
1878
  .filter(item => item.turnRef !== undefined && indexOf.has(item.turnRef))
1799
1879
  .map(({ turnRef, ...item }) => ({ ...item, messageIndex: indexOf.get(turnRef) }))
1800
1880
  .sort((a, b) => a.turn - b.turn || a.order - b.order);
@@ -66,10 +66,11 @@ export function nativeSessionEvents(messages, title, now = Date.now()) {
66
66
  return events
67
67
  }
68
68
 
69
- async function storeSeed(services, record, cwd) {
69
+ async function storeSeed(services, record, cwd, markHostWrite) {
70
70
  const { sessions, persistence } = services
71
71
  let seed = record.seed
72
72
  if (!seed) {
73
+ if (record.history?.attachments && (services.attachments?.saveImage || services.attachments?.saveFile)) markHostWrite()
73
74
  const { events, nativeTimeline } = record.id && record.config && record.history
74
75
  ? await nativeTranscriptEvents(record, services.attachments)
75
76
  : { events: nativeSessionEvents(record.messages, record.title) }
@@ -81,6 +82,8 @@ async function storeSeed(services, record, cwd) {
81
82
  if (record.id && record.config) seed = await saveConversationSeed(record.config, record.id, seed)
82
83
  }
83
84
  const { header, events } = seed
85
+ // A failed lookup or create can hide a partial log. From here on, retry the same ID.
86
+ markHostWrite()
84
87
  const existing = await persistence.stat?.(record.sessionId)
85
88
  const handle = existing ? await persistence.open(record.sessionId, 'write') : await persistence.create(header)
86
89
  try {
@@ -103,8 +106,20 @@ async function storeSeed(services, record, cwd) {
103
106
  }
104
107
 
105
108
  export async function saveNativeSession(services, record, cwd) {
109
+ let unwritten = !record.stored && !record.traceStored
110
+ try {
111
+ return await writeNativeSession(services, record, cwd, () => { unwritten = false })
112
+ } catch (error) {
113
+ if (!unwritten) throw error
114
+ throw Object.assign(new Error(error.message, { cause: error }), { status: error.status, nativeSessionUnwritten: true })
115
+ }
116
+ }
117
+
118
+ async function writeNativeSession(services, record, cwd, markHostWrite) {
106
119
  const { workspaces, projectionCache } = services
107
120
  const workspace = await workspaces.create(cwd)
121
+ const attached = workspace.sessionIds.includes(record.sessionId)
122
+ if (attached) markHostWrite()
108
123
  const normalize = value => {
109
124
  const normalized = path.normalize(value)
110
125
  return process.platform === 'win32' ? normalized.toLowerCase() : normalized
@@ -112,7 +127,7 @@ export async function saveNativeSession(services, record, cwd) {
112
127
  if (normalize(workspace.path) !== normalize(cwd)) {
113
128
  throw Object.assign(new Error('原工作目录已变化,请刷新项目。'), { status: 409 })
114
129
  }
115
- if (!record.stored && !workspace.sessionIds.includes(record.sessionId)) record.stored = await storeSeed(services, record, cwd)
130
+ if (!attached && !record.stored) record.stored = await storeSeed(services, record, cwd, markHostWrite)
116
131
  record.nativeTimeline = record.stored?.nativeTimeline ?? record.seed?.nativeTimeline
117
132
  // Save the reviewed source snapshot before attaching the new DSH session.
118
133
  const hasTrace = Array.isArray(record.trace) && record.trace.length > 0