@wwwfz/dsh-agent-bridge 0.8.3 → 0.9.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.
Files changed (40) hide show
  1. package/README.md +198 -194
  2. package/THIRD_PARTY_NOTICES.md +67 -0
  3. package/cordis.patch.yml +4 -4
  4. package/package.json +40 -40
  5. package/src/assets.js +405 -348
  6. package/src/catalog.js +906 -605
  7. package/src/client.js +623 -310
  8. package/src/config.js +88 -88
  9. package/src/export.js +241 -12
  10. package/src/index.js +160 -136
  11. package/src/project-archive.js +145 -145
  12. package/src/projects.js +1189 -980
  13. package/src/session-import.js +107 -93
  14. package/src/session-trace.js +121 -0
  15. package/src/skill-handoff.js +1327 -0
  16. package/src/skill-package.js +417 -0
  17. package/src/skill-provider.js +249 -0
  18. package/src/watch.js +309 -309
  19. package/web/Geist-OFL.txt +93 -93
  20. package/web/agent-icons/NOTICE.md +19 -19
  21. package/web/agent-icons/antigravity.svg +76 -76
  22. package/web/agent-icons/claude.svg +3 -3
  23. package/web/agent-icons/dsh.svg +58 -58
  24. package/web/agent-icons/licenses/copilot.txt +21 -21
  25. package/web/agent-icons/licenses/dsh.txt +21 -21
  26. package/web/agent-icons/licenses/gemini.txt +201 -201
  27. package/web/agent-icons/licenses/opencode.txt +21 -21
  28. package/web/agent-icons/licenses/qoder-notice.txt +18 -18
  29. package/web/agent-icons/licenses/qoder.txt +22 -22
  30. package/web/agent-icons/licenses/qwen.txt +202 -202
  31. package/web/agent-icons/qoder.svg +4 -4
  32. package/web/agent-icons/qwen.svg +5 -5
  33. package/web/agent-icons/workbuddy.svg +29 -29
  34. package/web/markdown.js +225 -0
  35. package/web/panel.css +607 -502
  36. package/web/panel.html +277 -246
  37. package/web/panel.js +2334 -1559
  38. package/web/project-context.js +25 -25
  39. package/web/vendor/markdown-it-LICENSE.txt +156 -0
  40. package/web/vendor/markdown-it.mjs +3064 -0
package/src/catalog.js CHANGED
@@ -1,605 +1,906 @@
1
- import { execFile } from 'node:child_process'
2
- import { createHash, randomUUID } from 'node:crypto'
3
- import { realpath, stat } from 'node:fs/promises'
4
- import path, { win32 } from 'node:path'
5
- import { promisify } from 'node:util'
6
- import { listProjectAssets, readAsset } from './assets.js'
7
- import { dateMillis, readConversationHistory, readProjectHistory, scanProjects } from './projects.js'
8
- import { createSourceMonitor } from './watch.js'
9
- import { makeExport } from './export.js'
10
- import {
11
- ProjectArchiveError, readProjectSelection, readProjectState, writeProjectArchive,
12
- writeProjectContinuation, writeProjectPin, writeProjectSelection,
13
- } from './project-archive.js'
14
-
15
- const run = promisify(execFile)
16
- const limit = 32_000
17
- const fallbackScanInterval = 15_000
18
- const ticketLifetime = 10 * 60_000
19
- const catalogId = /^[0-9a-f]{24}$/
20
- const conversationTicketLimit = 12
21
-
22
- class RequestError extends Error {
23
- constructor(message, status = 400) {
24
- super(message)
25
- this.status = status
26
- }
27
- }
28
-
29
- function keyFor(...values) {
30
- return createHash('sha256').update(JSON.stringify(values)).digest('hex').slice(0, 24)
31
- }
32
-
33
- function pathKey(value, platform = process.platform) {
34
- const normalized = (platform === 'win32' ? win32 : path).normalize(value)
35
- return platform === 'win32' ? normalized.toLowerCase() : normalized
36
- }
37
-
38
- export function mergeProjects(entries, platform = process.platform) {
39
- const byPath = new Map()
40
- for (const item of entries) {
41
- if (typeof item.cwd !== 'string' || !(platform === 'win32' ? win32 : path).isAbsolute(item.cwd)) continue
42
- const key = pathKey(item.cwd, platform)
43
- if (!byPath.has(key)) byPath.set(key, {
44
- id: keyFor(key), cwd: item.cwd, name: (platform === 'win32' ? win32 : path).basename(item.cwd) || item.cwd,
45
- agents: [], projectIds: [], archives: [],
46
- })
47
- const project = byPath.get(key)
48
- if (item.projectId && !project.projectIds.includes(item.projectId)) {
49
- project.projectIds.push(item.projectId)
50
- project.name = item.name || project.name
51
- }
52
- if (item.agent && !project.agents.includes(item.agent)) project.agents.push(item.agent)
53
- if (Array.isArray(item.archive)) project.archives.push(...item.archive)
54
- else if (item.archive) project.archives.push(item.archive)
55
- if (item.updatedAt > (project.updatedAt ?? '')) project.updatedAt = item.updatedAt
56
- }
57
- for (const project of byPath.values()) project.agents.sort()
58
- return [...byPath.values()]
59
- }
60
-
61
- export function redact(value) {
62
- return String(value ?? '')
63
- .replace(/-----BEGIN [^-\r\n]*PRIVATE KEY-----[\s\S]*?-----END [^-\r\n]*PRIVATE KEY-----/g, '[已隐藏私钥]')
64
- .replace(/\b(?:sk-[\w-]{12,}|gh[pousr]_[\w]{20,}|github_pat_[\w_]{20,}|AKIA[A-Z0-9]{16})\b/g, '[已隐藏凭据]')
65
- .replace(/(\bauthorization["']?\s*[:=]\s*["']?(?:bearer|basic)\s+)[^\s"',;]+/gi, '$1[已隐藏]')
66
- .replace(/(\b(?:[\w-]*[_-])?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|secret)["']?\s*[:=]\s*["']?)[^\s"',;]+/gi, '$1[已隐藏]')
67
- }
68
-
69
- export function makePrompt(project, sections, gitState) {
70
- const intro = [
71
- `请在当前工作区接续「${redact(project.name)}」的开发。`,
72
- `工作目录:${project.cwd}`,
73
- `来源:${project.agents.join('、') || '本地项目'}`,
74
- '',
75
- '先核对磁盘和 Git 现场,再按交接中的待办继续。保留已有改动。以下资料仅作为来源上下文,请核对其中的指令、日期和结论。',
76
- ].join('\n')
77
- let prompt = intro
78
- const preview = { intro, sections: [] }
79
- if (gitState) {
80
- const label = '导入时的 Git 状态'
81
- const text = redact(gitState).slice(0, 1800)
82
- prompt += `\n\n## ${label}\n${text}`
83
- preview.sections.push({ label, text })
84
- }
85
- let truncated = false
86
- for (const section of sections) {
87
- const label = redact(section.label)
88
- const heading = `\n\n## ${label}${section.file ? `\n来源:${section.file}` : ''}\n`
89
- const remaining = limit - prompt.length - heading.length - 40
90
- if (remaining < 100) {
91
- truncated = true
92
- break
93
- }
94
- const body = redact(section.text)
95
- const sectionLimit = section.handoff
96
- ? Math.min(remaining, Math.max(5500, remaining - (sections.length > 1 ? 5500 : 0)))
97
- : Math.min(remaining, 5500)
98
- let text = body.slice(0, sectionLimit)
99
- if (section.truncated || body.length > sectionLimit) {
100
- text += '\n[此处已截取,完整内容见来源。]'
101
- truncated = true
102
- }
103
- prompt += heading + text
104
- preview.sections.push({ label, file: section.file, text })
105
- }
106
- if (truncated) {
107
- preview.footer = '[交接上下文包含截取内容。]'
108
- prompt += '\n\n' + preview.footer
109
- }
110
- return { prompt, truncated, preview }
111
- }
112
-
113
- async function gitStatus(cwd) {
114
- try {
115
- const { stdout } = await run('git', [
116
- '--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', cwd, 'status', '--short',
117
- '--branch', '--untracked-files=normal', '--ignore-submodules=all',
118
- ], { timeout: 2500, maxBuffer: 128 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } })
119
- return stdout.trim()
120
- } catch {
121
- return ''
122
- }
123
- }
124
-
125
- function publicProject({ archives, ...project }) {
126
- return { ...project, sessions: archives.length, hasConversations: archives.some(canReadConversation) }
127
- }
128
-
129
- function canReadConversation(archive) {
130
- // Antigravity's native CLI index stores prompts, not the assistant replies.
131
- return archive.kind !== 'antigravity' && typeof archive.file === 'string'
132
- }
133
-
134
- function conversationId(archive) {
135
- return keyFor(archive.kind, archive.file, archive.table, archive.id)
136
- }
137
-
138
- function conversationTitle(value, bytes = 200) {
139
- const normalized = redact(value).replace(/[\s\p{Cc}]+/gu, ' ').trim()
140
- let title = ''
141
- let length = 0
142
- for (const char of normalized) {
143
- length += Buffer.byteLength(char)
144
- if (length > bytes) break
145
- title += char
146
- }
147
- return title
148
- }
149
-
150
- async function currentDirectory(cwd) {
151
- try {
152
- const canonical = await realpath(cwd)
153
- if ((await stat(canonical)).isDirectory()) return canonical
154
- } catch {
155
- // Historical sources may point to an offline drive or a removed worktree.
156
- }
157
- return null
158
- }
159
-
160
- function sortProjects(a, b) {
161
- return Number(b.online) - Number(a.online)
162
- || (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')
163
- || a.name.localeCompare(b.name, 'zh-CN')
164
- }
165
-
166
- function applyProjectState(projects, { archivedIds, preferences }) {
167
- const visibleState = []
168
- for (const project of projects) {
169
- const preference = preferences.get(project.id)
170
- project.archived = archivedIds.has(project.id)
171
- project.pinned = preference?.pinned ?? false
172
- project.continuedAt = preference?.continuedAt ?? null
173
- if (project.archived || project.pinned || project.continuedAt !== null) {
174
- visibleState.push([project.id, project.archived, project.pinned, project.continuedAt])
175
- }
176
- }
177
- return keyFor(visibleState.sort((a, b) => a[0].localeCompare(b[0])))
178
- }
179
-
180
- function storageFailure(operation, error, subject = '项目归档记录') {
181
- const sqliteCode = error.errcode & 0xff
182
- let detail = '请检查 agent-bridge-archive.sqlite 及其所在目录。'
183
- if (error instanceof ProjectArchiveError) detail = error.message
184
- else if ([5, 6].includes(sqliteCode)) detail = '归档数据库正忙,请重试。'
185
- else if ([11, 26].includes(sqliteCode)) detail = '归档文件已损坏或格式无效。'
186
- else if ([3, 8, 14].includes(sqliteCode) || ['EACCES', 'EPERM', 'EROFS'].includes(error.code)) {
187
- detail = '请检查归档文件和目录的访问权限。'
188
- }
189
- return new RequestError(`无法${operation}${subject}。${detail}`, 503)
190
- }
191
-
192
- async function loadProjectState(config) {
193
- try { return await readProjectState(config) }
194
- catch (error) { throw storageFailure('读取', error, '项目归档和偏好记录') }
195
- }
196
-
197
- function isCatalogId(id) {
198
- return typeof id === 'string' && catalogId.test(id)
199
- }
200
-
201
- function requireProject(current, projectId) {
202
- const project = current.projects.find(item => item.id === projectId)
203
- if (!project) throw new RequestError('项目目录已刷新,请重新选择项目。', 404)
204
- return project
205
- }
206
-
207
- export function createCatalog(loadConfig, { importConversation } = {}) {
208
- let snapshot
209
- let scanning
210
- let revision = 0
211
- let epoch = 0
212
- let disposed = false
213
- const details = new Map()
214
- const signatures = new Map()
215
- const tickets = new Map()
216
- const conversationTickets = new Map()
217
- const watched = new Map()
218
- const listeners = new Set()
219
- const monitor = createSourceMonitor({ onChange() {
220
- epoch++
221
- wake()
222
- } })
223
-
224
- function wake() {
225
- for (const listener of listeners) listener()
226
- }
227
-
228
- function waitForChange(knownRevision) {
229
- if (knownRevision !== revision || snapshot?.epoch !== epoch || listeners.size >= 32 || disposed) return
230
- return new Promise(resolve => {
231
- function done() {
232
- clearTimeout(timer)
233
- listeners.delete(done)
234
- resolve()
235
- }
236
- const timer = setTimeout(done, 5_000)
237
- listeners.add(done)
238
- })
239
- }
240
-
241
- async function synchronizeProjectState() {
242
- if (scanning) await scanning
243
- const current = snapshot
244
- const state = await loadProjectState(current.config)
245
- if (scanning || snapshot !== current) return synchronizeProjectState()
246
- const stateFingerprint = applyProjectState(current.projects, state)
247
- if (current.stateFingerprint !== stateFingerprint) {
248
- current.stateFingerprint = stateFingerprint
249
- revision++
250
- wake()
251
- }
252
- return current
253
- }
254
-
255
- async function scan(refresh = false) {
256
- if (scanning) return scanning
257
- if (!refresh && snapshot?.epoch === epoch && Date.now() - snapshot.scannedAt < fallbackScanInterval) {
258
- return synchronizeProjectState()
259
- }
260
- scanning = (async () => {
261
- const scanEpoch = epoch
262
- const config = await loadConfig()
263
- const result = await scanProjects(config)
264
- const resolved = new Map()
265
- const aliases = [...new Set(result.projects.map(item => item.cwd))]
266
- for (let i = 0; i < aliases.length; i += 64) {
267
- await Promise.all(aliases.slice(i, i + 64).map(async cwd => resolved.set(cwd, await currentDirectory(cwd))))
268
- }
269
- const projects = mergeProjects(result.projects.map(item => ({ ...item, cwd: resolved.get(item.cwd) || item.cwd })))
270
- const online = new Set([...resolved.values()].filter(Boolean).map(value => pathKey(value)))
271
- for (const project of projects) {
272
- project.online = online.has(pathKey(project.cwd))
273
- if (watched.has(project.cwd)) watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds })
274
- }
275
- projects.sort(sortProjects)
276
- const fingerprint = keyFor(projects, result.sources)
277
- const stateFingerprint = applyProjectState(projects, await loadProjectState(config))
278
- const changed = refresh || snapshot?.epoch !== scanEpoch || snapshot?.fingerprint !== fingerprint
279
- || snapshot?.stateFingerprint !== stateFingerprint
280
- details.clear()
281
- snapshot = { config, projects, sources: result.sources, scannedAt: Date.now(), fingerprint, stateFingerprint, epoch: scanEpoch }
282
- await monitor.update(config, [...watched.values()])
283
- if (changed) {
284
- revision++
285
- wake()
286
- }
287
- return snapshot
288
- })().finally(() => { scanning = undefined })
289
- return scanning
290
- }
291
-
292
- async function setProjectArchive(input) {
293
- if (typeof input.archived !== 'boolean' || !Array.isArray(input.projectIds) || !input.projectIds.length
294
- || !input.projectIds.every(isCatalogId)) {
295
- throw new RequestError('归档请求格式无效,请重新选择项目。')
296
- }
297
- const projectIds = [...new Set(input.projectIds)]
298
- const current = await scan()
299
- const known = new Set(current.projects.map(project => project.id))
300
- if (projectIds.some(id => !known.has(id))) throw new RequestError('有项目已不在当前目录中,请刷新后重试。', 404)
301
- let changedProjectIds
302
- try { changedProjectIds = await writeProjectArchive(current.config, projectIds, input.archived) }
303
- catch (error) { throw storageFailure('保存', error) }
304
- await synchronizeProjectState()
305
- return { projectIds, changedProjectIds, archived: input.archived, revision }
306
- }
307
-
308
- async function setProjectPin({ projectId, pinned }) {
309
- if (!isCatalogId(projectId) || typeof pinned !== 'boolean') throw new RequestError('置顶请求格式无效。')
310
- const current = await scan()
311
- requireProject(current, projectId)
312
- try { await writeProjectPin(current.config, projectId, pinned) }
313
- catch (error) { throw storageFailure('保存', error, '项目置顶') }
314
- await synchronizeProjectState()
315
- return { projectId, pinned, revision }
316
- }
317
-
318
- async function setProjectSelection({ projectId, assetIds, history }) {
319
- if (!isCatalogId(projectId) || typeof history !== 'boolean'
320
- || !Array.isArray(assetIds) || assetIds.length > 24 || !assetIds.every(isCatalogId)) {
321
- throw new RequestError('资料选择格式无效,每个项目最多记住 24 项。')
322
- }
323
- const current = snapshot ?? await scan()
324
- requireProject(current, projectId)
325
- const selection = { assetIds: [...new Set(assetIds)], history }
326
- try { await writeProjectSelection(current.config, projectId, selection) }
327
- catch (error) { throw storageFailure('保存', error, '项目资料选择') }
328
- return { projectId, selection }
329
- }
330
-
331
- async function recordProjectContinuation(id) {
332
- const ticket = getTicket(id)
333
- if (!ticket.opened) throw new RequestError('请先打开交接草稿,再记录接续。', 409)
334
- ticket.continuation ??= writeProjectContinuation(ticket.config, ticket.projectId).catch(error => {
335
- delete ticket.continuation
336
- throw storageFailure('保存', error, '项目接续记录')
337
- })
338
- const continuedAt = await ticket.continuation
339
- await synchronizeProjectState()
340
- return { projectId: ticket.projectId, continuedAt, revision }
341
- }
342
-
343
- async function detail(id) {
344
- const current = await scan()
345
- const { config } = current
346
- const project = requireProject(current, id)
347
- if (details.has(id)) return details.get(id)
348
- const pending = (async () => {
349
- if (!watched.has(project.cwd)) {
350
- if (watched.size >= 4) watched.delete(watched.keys().next().value)
351
- watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds })
352
- await monitor.update(config, [...watched.values()])
353
- }
354
- const [{ memories, skills }, history] = await Promise.all([
355
- listProjectAssets(project, config),
356
- readProjectHistory(project, config),
357
- ])
358
- const used = new Set(history.usedSkills.map(name => name.toLowerCase()))
359
- const normalize = (item, kind) => ({
360
- ...item, kind, id: keyFor(kind, item.file, item.agent, item.scope),
361
- used: kind === 'skill' && used.has(item.name.toLowerCase()),
362
- })
363
- const result = {
364
- project, history, config,
365
- memories: memories.map(item => normalize(item, 'memory')),
366
- skills: skills.map(item => normalize(item, 'skill')),
367
- }
368
- if (current === snapshot) {
369
- const assets = [...result.memories, ...result.skills].map(item => [publicAsset(item), item.revision])
370
- const signature = keyFor(assets, history)
371
- if (signatures.has(id) && signatures.get(id) !== signature) {
372
- revision++
373
- wake()
374
- }
375
- if (!signatures.has(id) && signatures.size >= 24) signatures.delete(signatures.keys().next().value)
376
- signatures.set(id, signature)
377
- }
378
- return result
379
- })().catch(error => {
380
- if (details.get(id) === pending) details.delete(id)
381
- throw error
382
- })
383
- if (details.size >= 24) details.delete(details.keys().next().value)
384
- details.set(id, pending)
385
- return pending
386
- }
387
-
388
- function publicAsset({ id, name, agent, scope, detail, file, used }) {
389
- return { id, name, agent, scope, detail, file, used }
390
- }
391
-
392
- async function prepare(input) {
393
- const entry = await detail(input.projectId)
394
- const current = await currentDirectory(entry.project.cwd)
395
- const canImport = Boolean(current && pathKey(current) === pathKey(entry.project.cwd))
396
- if (!Array.isArray(input.assetIds) || input.assetIds.length > 24 || input.assetIds.some(id => typeof id !== 'string')) {
397
- throw new RequestError('每次交接最多选择 24 项记忆和 Skills。')
398
- }
399
- const selected = new Set(input.assetIds)
400
- const assets = [...entry.memories, ...entry.skills].filter(item => selected.has(item.id))
401
- if (assets.length !== selected.size) throw new RequestError('所选资料已变化,请刷新项目。', 409)
402
- const sections = await Promise.all(assets.map(async item => {
403
- const result = await readAsset(item).catch(() => {
404
- throw new RequestError(`无法读取「${item.name}」。请刷新后重试。`, 409)
405
- })
406
- return {
407
- label: `${item.kind === 'memory' ? '记忆' : 'Skill'} · ${item.name}(${item.agent})`,
408
- file: item.file, ...result,
409
- handoff: assets.length === 1 && (item.agent === 'export' || item.detail === '项目交接'),
410
- }
411
- }))
412
- if (input.history === true) {
413
- for (const message of entry.history.messages.slice(-8)) {
414
- if (message.role !== 'user' && message.role !== 'assistant') continue
415
- const author = message.role === 'user' ? '用户' : '助手'
416
- sections.push({ label: [`近期会话 · ${author}`, message.agent].filter(Boolean).join(' · '), text: message.text })
417
- }
418
- }
419
- const { prompt, truncated, preview } = makePrompt(entry.project, sections, canImport ? await gitStatus(current) : '')
420
- for (const [key, value] of tickets) {
421
- if (Date.now() - value.created > ticketLifetime) tickets.delete(key)
422
- }
423
- if (tickets.size >= 40) tickets.delete(tickets.keys().next().value)
424
- const ticket = randomUUID()
425
- tickets.set(ticket, {
426
- created: Date.now(), path: canImport ? current : null, prompt, truncated, title: entry.project.name,
427
- projectId: entry.project.id, config: entry.config,
428
- })
429
- return { ticket, prompt, truncated, canImport, preview }
430
- }
431
-
432
- function getTicket(id) {
433
- const ticket = tickets.get(id)
434
- if (!ticket || Date.now() - ticket.created > ticketLifetime) throw new RequestError('预览已过期,请重新生成。', 409)
435
- return ticket
436
- }
437
-
438
- async function listConversations(projectId, recent) {
439
- const current = await scan()
440
- const project = requireProject(current, projectId)
441
- const archives = project.archives
442
- .filter(canReadConversation)
443
- .sort((a, b) => dateMillis(b.date) - dateMillis(a.date))
444
- const seen = new Set()
445
- const sessions = []
446
- for (const archive of archives) {
447
- const id = conversationId(archive)
448
- if (seen.has(id)) continue
449
- seen.add(id)
450
- if (recent && sessions.length === 3) continue
451
- sessions.push({
452
- id, agent: archive.agent ?? archive.kind, date: dateMillis(archive.date),
453
- title: conversationTitle(archive.title), archivedSource: archive.kind === 'agentsview',
454
- })
455
- }
456
- return recent ? { sessions, total: seen.size } : { sessions }
457
- }
458
-
459
- async function previewConversation({ projectId, sessionId }) {
460
- if (!isCatalogId(sessionId)) throw new RequestError('会话标识无效。')
461
- const current = await scan()
462
- const project = requireProject(current, projectId)
463
- const { config } = current
464
- const archive = project.archives.find(item => canReadConversation(item) && conversationId(item) === sessionId)
465
- if (!archive) throw new RequestError('找不到这条会话,请刷新项目。', 404)
466
- const history = await readConversationHistory(archive, project.cwd, config).catch(() => {
467
- throw new RequestError('会话已移动或无法读取,请刷新后重试。', 409)
468
- })
469
- if (!history.messages.length) throw new RequestError('这条会话没有可迁入的文字问答。', 409)
470
- const messages = history.messages.map(({ role, text, time }) => ({ role, text: redact(text), time }))
471
- const title = conversationTitle(archive.title || messages[0].text, 80) || '迁入的 Agent 会话'
472
- const path = await currentDirectory(project.cwd)
473
- const canImport = Boolean(path && pathKey(path) === pathKey(project.cwd))
474
- const ticket = randomUUID()
475
- for (const [key, record] of conversationTickets) {
476
- if (!record.pending && Date.now() - record.created > ticketLifetime) conversationTickets.delete(key)
477
- }
478
- if (canImport && conversationTickets.size >= conversationTicketLimit) {
479
- const oldest = [...conversationTickets].find(([, record]) => !record.pending)
480
- if (!oldest) throw new RequestError('其他会话正在迁入,请稍后重试。', 409)
481
- conversationTickets.delete(oldest[0])
482
- }
483
- if (canImport) conversationTickets.set(ticket, {
484
- created: Date.now(), projectId, sessionId: randomUUID(), path, config, messages, title,
485
- })
486
- return { title, messages, ticket: canImport ? ticket : null, canImport, cwd: project.cwd, truncated: history.truncated }
487
- }
488
-
489
- async function commitConversation(ticket) {
490
- const record = conversationTickets.get(ticket)
491
- if (!record || Date.now() - record.created > ticketLifetime) {
492
- throw new RequestError('会话预览已过期,请重新打开。', 409)
493
- }
494
- if (record.result) return record.result
495
- if (record.pending) return record.pending
496
- record.pending = (async () => {
497
- const cwd = await currentDirectory(record.path)
498
- if (!cwd || pathKey(cwd) !== pathKey(record.path)) {
499
- throw new RequestError('原工作目录已变化,请刷新项目。', 409)
500
- }
501
- try {
502
- record.result = await importConversation(record, cwd)
503
- } catch (error) {
504
- if (error.status) throw error
505
- const message = record.stored ? '会话历史已写入,暂时无法加入工作区。可重试打开。' : '无法将会话写入 DSH。请检查工作区和会话存储后重试。'
506
- throw new RequestError(message, 503)
507
- }
508
- delete record.messages
509
- delete record.stored
510
- try {
511
- await writeProjectContinuation(record.config, record.projectId)
512
- await synchronizeProjectState()
513
- } catch { /* A saved session remains usable even if the recents index cannot be updated. */ }
514
- return record.result
515
- })().finally(() => { delete record.pending })
516
- return record.pending
517
- }
518
-
519
- function exportSession(conversation) {
520
- if (!conversation || typeof conversation.title !== 'string' || conversation.title.length > 500
521
- || typeof conversation.path !== 'string' || conversation.path.length > 4096
522
- || !path.isAbsolute(conversation.path) || /[\u0000-\u001f]/u.test(conversation.path)
523
- || !Array.isArray(conversation.messages) || conversation.messages.length > 24) {
524
- throw new RequestError('DSH 会话资料格式无效。')
525
- }
526
- const sections = conversation.messages
527
- .filter(message => (message?.role === 'user' || message?.role === 'assistant')
528
- && typeof message.text === 'string' && message.text.trim())
529
- .map(message => ({ label: message.role === 'user' ? '用户' : 'DSH 助手', text: message.text }))
530
- if (!sections.length) throw new RequestError('这段会话暂无可导出的消息。', 409)
531
- const title = redact(conversation.title.trim()) || 'DSH 会话'
532
- const { prompt, truncated } = makePrompt({ name: title, cwd: conversation.path, agents: ['DSH'] }, sections, '')
533
- return makeExport({ title, prompt, origin: 'DSH 会话', truncated: truncated || conversation.truncated === true })
534
- }
535
-
536
- return {
537
- dispose() {
538
- disposed = true
539
- wake()
540
- monitor.dispose()
541
- tickets.clear()
542
- conversationTickets.clear()
543
- },
544
- async execute(action, input) {
545
- if (action === 'catalog') {
546
- const { projects, sources, scannedAt } = await scan(input.refresh === true)
547
- return { projects: projects.map(publicProject), sources, scannedAt, revision }
548
- }
549
- if (action === 'set-project-archive') return setProjectArchive(input)
550
- if (action === 'set-project-pin') return setProjectPin(input)
551
- if (action === 'set-project-selection') return setProjectSelection(input)
552
- if (action === 'record-project-continuation') return recordProjectContinuation(input.ticket)
553
- if (action === 'list-conversations' || action === 'preview-conversation' || action === 'import-conversation') {
554
- if (!importConversation) throw new RequestError('当前 DSH 未提供会话迁入服务。', 409)
555
- if (action === 'list-conversations') return listConversations(input.projectId, input.recent === true)
556
- if (action === 'preview-conversation') return previewConversation(input)
557
- return commitConversation(input.ticket)
558
- }
559
- if (action === 'changes') {
560
- const inspect = async () => {
561
- const current = await scan()
562
- if (current.projects.some(item => item.id === input.projectId)) await detail(input.projectId)
563
- }
564
- await inspect()
565
- if (input.wait === true && input.revision === revision) {
566
- await waitForChange(input.revision)
567
- if (!disposed) await inspect()
568
- }
569
- return { revision, changed: input.revision !== revision, scannedAt: snapshot.scannedAt }
570
- }
571
- if (action === 'detail') {
572
- const { project, history, memories, skills, config } = await detail(input.projectId)
573
- let selection
574
- try { selection = await readProjectSelection(config, project.id) }
575
- catch (error) { throw storageFailure('读取', error, '项目资料选择') }
576
- return {
577
- project: publicProject(project), memories: memories.map(publicAsset), skills: skills.map(publicAsset),
578
- usedSkills: history.usedSkills, historyCount: history.messages.length, selection,
579
- }
580
- }
581
- if (action === 'asset') {
582
- const { memories, skills } = await detail(input.projectId)
583
- const item = [...memories, ...skills].find(asset => asset.id === input.assetId)
584
- if (!item) throw new RequestError('找不到所选资料。', 404)
585
- const result = await readAsset(item).catch(() => { throw new RequestError('资料已移动或不可读。', 409) })
586
- return { ...result, text: redact(result.text) }
587
- }
588
- if (action === 'preview') return prepare(input)
589
- if (action === 'export') {
590
- const ticket = getTicket(input.ticket)
591
- return makeExport({ ...ticket, title: redact(ticket.title), origin: '项目交接' })
592
- }
593
- if (action === 'export-session') return exportSession(input.conversation)
594
- if (action === 'open') {
595
- const ticket = getTicket(input.ticket)
596
- if (!ticket.path) throw new RequestError('原工作目录不可访问。可导出交接。', 409)
597
- const current = await currentDirectory(ticket.path)
598
- if (!current || pathKey(current) !== pathKey(ticket.path)) throw new RequestError('原工作目录已变化。', 409)
599
- ticket.opened = true
600
- return { path: current, prompt: ticket.prompt }
601
- }
602
- throw new RequestError('找不到该操作。', 404)
603
- },
604
- }
605
- }
1
+ import { execFile } from 'node:child_process'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import { realpath, stat } from 'node:fs/promises'
4
+ import path, { win32 } from 'node:path'
5
+ import { promisify } from 'node:util'
6
+ import { authorizeProjectReference, listProjectAssets, readAsset, verifyAssetSource, verifySourceAuthorization } from './assets.js'
7
+ import { dateMillis, readConversationHistory, readProjectHistory, scanProjects } from './projects.js'
8
+ import { createSourceMonitor } from './watch.js'
9
+ import { makeExport } from './export.js'
10
+ import { countTrace, normalizeTrace } from './session-trace.js'
11
+ import { isMarkdownFile, relativeMarkdownLinks } from '../web/markdown.js'
12
+ import {
13
+ ProjectArchiveError, readProjectSelection, readProjectState, writeProjectArchive,
14
+ writeProjectContinuation, writeProjectPin, writeProjectSelection,
15
+ } from './project-archive.js'
16
+
17
+ const run = promisify(execFile)
18
+ const limit = 32_000
19
+ const fallbackScanInterval = 15_000
20
+ const ticketLifetime = 10 * 60_000
21
+ const catalogId = /^[0-9a-f]{24}$/
22
+ const conversationTicketLimit = 12
23
+ const traceBudget = { items: 200, bytes: 48 * 1024, resultBytes: 4 * 1024 }
24
+
25
+ class RequestError extends Error {
26
+ constructor(message, status = 400) {
27
+ super(message)
28
+ this.status = status
29
+ }
30
+ }
31
+
32
+ function keyFor(...values) {
33
+ return createHash('sha256').update(JSON.stringify(values)).digest('hex').slice(0, 24)
34
+ }
35
+
36
+ function pathKey(value, platform = process.platform) {
37
+ const normalized = (platform === 'win32' ? win32 : path).normalize(value)
38
+ return platform === 'win32' ? normalized.toLowerCase() : normalized
39
+ }
40
+
41
+ export function mergeProjects(entries, platform = process.platform) {
42
+ const byPath = new Map()
43
+ for (const item of entries) {
44
+ if (typeof item.cwd !== 'string' || !(platform === 'win32' ? win32 : path).isAbsolute(item.cwd)) continue
45
+ const key = pathKey(item.cwd, platform)
46
+ if (!byPath.has(key)) byPath.set(key, {
47
+ id: keyFor(key), cwd: item.cwd, name: (platform === 'win32' ? win32 : path).basename(item.cwd) || item.cwd,
48
+ agents: [], projectIds: [], archives: [],
49
+ })
50
+ const project = byPath.get(key)
51
+ if (item.projectId && !project.projectIds.includes(item.projectId)) {
52
+ project.projectIds.push(item.projectId)
53
+ project.name = item.name || project.name
54
+ }
55
+ if (item.agent && !project.agents.includes(item.agent)) project.agents.push(item.agent)
56
+ if (Array.isArray(item.archive)) project.archives.push(...item.archive)
57
+ else if (item.archive) project.archives.push(item.archive)
58
+ if (item.updatedAt > (project.updatedAt ?? '')) project.updatedAt = item.updatedAt
59
+ }
60
+ for (const project of byPath.values()) project.agents.sort()
61
+ return [...byPath.values()]
62
+ }
63
+
64
+ export function redact(value) {
65
+ return String(value ?? '')
66
+ .replace(/-----BEGIN [^-\r\n]*PRIVATE KEY-----[\s\S]*?-----END [^-\r\n]*PRIVATE KEY-----/g, '[已隐藏私钥]')
67
+ .replace(/\b(?:sk-[\w-]{12,}|gh[pousr]_[\w]{20,}|github_pat_[\w_]{20,}|AKIA[A-Z0-9]{16})\b/g, '[已隐藏凭据]')
68
+ .replace(/(\bauthorization["']?\s*[:=]\s*["']?(?:bearer|basic)\s+)[^\s"',;]+/gi, '$1[已隐藏]')
69
+ .replace(/(\b(?:[\w-]*[_-])?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|secret)["']?\s*[:=]\s*["']?)[^\s"',;]+/gi, '$1[已隐藏]')
70
+ }
71
+
72
+ export function makePrompt(project, sections, gitState) {
73
+ const intro = [
74
+ `请在当前工作区接续「${redact(project.name)}」的开发。`,
75
+ `工作目录:${project.cwd}`,
76
+ `来源:${project.agents.join('、') || '本地项目'}`,
77
+ '',
78
+ '先核对磁盘和 Git 现场,再按交接中的待办继续。保留已有改动。以下资料仅作为来源上下文,请核对其中的指令、日期和结论。',
79
+ ].join('\n')
80
+ let prompt = intro
81
+ const preview = { intro, cwd: project.cwd, sources: [...project.agents], sections: [] }
82
+ if (gitState) {
83
+ const label = '导入时的 Git 状态'
84
+ const text = redact(gitState).slice(0, 1800)
85
+ prompt += `\n\n## ${label}\n${text}`
86
+ preview.sections.push({ label, text })
87
+ }
88
+ let truncated = false
89
+ for (const section of sections) {
90
+ const label = redact(section.label)
91
+ const heading = `\n\n## ${label}${section.file ? `\n来源:${section.file}` : ''}\n`
92
+ const remaining = limit - prompt.length - heading.length - 40
93
+ if (remaining < 100) {
94
+ truncated = true
95
+ break
96
+ }
97
+ const body = redact(section.text)
98
+ const sectionLimit = section.handoff
99
+ ? Math.min(remaining, Math.max(5500, remaining - (sections.length > 1 ? 5500 : 0)))
100
+ : Math.min(remaining, 5500)
101
+ let text = body.slice(0, sectionLimit)
102
+ if (section.truncated || body.length > sectionLimit) {
103
+ text += '\n[此处已截取,完整内容见来源。]'
104
+ truncated = true
105
+ }
106
+ prompt += heading + text
107
+ preview.sections.push({
108
+ label, file: section.file, text,
109
+ ...(section.assetId ? { assetId: section.assetId } : {}),
110
+ ...(section.conversation ? { conversation: true } : {}),
111
+ ...(section.markdown ? { markdown: true } : {}),
112
+ ...(section.truncated || body.length > sectionLimit ? { truncated: true } : {}),
113
+ })
114
+ }
115
+ if (truncated) {
116
+ preview.footer = '[交接上下文包含截取内容。]'
117
+ prompt += '\n\n' + preview.footer
118
+ }
119
+ return { prompt, truncated, preview: { ...preview, truncated } }
120
+ }
121
+
122
+ async function gitStatus(cwd) {
123
+ try {
124
+ const { stdout } = await run('git', [
125
+ '--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', cwd, 'status', '--short',
126
+ '--branch', '--untracked-files=normal', '--ignore-submodules=all',
127
+ ], { timeout: 2500, maxBuffer: 128 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } })
128
+ return stdout.trim()
129
+ } catch {
130
+ return ''
131
+ }
132
+ }
133
+
134
+ function publicProject({ archives, ...project }) {
135
+ return { ...project, sessions: archives.length, hasConversations: archives.some(canReadConversation) }
136
+ }
137
+
138
+ function canReadConversation(archive) {
139
+ // Antigravity's native CLI index stores prompts, not the assistant replies.
140
+ return archive.kind !== 'antigravity' && typeof archive.file === 'string'
141
+ }
142
+
143
+ function conversationId(archive) {
144
+ return keyFor(archive.kind, archive.file, archive.table, archive.id)
145
+ }
146
+
147
+ function conversationTitle(value, bytes = 200) {
148
+ const normalized = redact(value).replace(/[\s\p{Cc}]+/gu, ' ').trim()
149
+ let title = ''
150
+ let length = 0
151
+ for (const char of normalized) {
152
+ length += Buffer.byteLength(char)
153
+ if (length > bytes) break
154
+ title += char
155
+ }
156
+ return title
157
+ }
158
+
159
+ // Source trace is shown to the user and stored with the imported session, so
160
+ // it is bounded and redacted exactly once here. Results are shortened before
161
+ // items are dropped so a long build log cannot hide the surrounding calls.
162
+ function limitUtf8(text, bytes) {
163
+ const data = Buffer.from(text, 'utf8')
164
+ if (data.length <= bytes) return text
165
+ while ((data[bytes] & 0xc0) === 0x80) bytes--
166
+ return data.toString('utf8', 0, bytes)
167
+ }
168
+
169
+ export function conversationTrace(trace, messageCount, offset = 0) {
170
+ const items = []
171
+ const seen = new Set()
172
+ let bytes = 2 // JSON array brackets
173
+ let truncated = false
174
+ const indexOf = new Map()
175
+ for (const item of [...trace].reverse()) {
176
+ const index = Number.isInteger(item?.messageIndex) ? item.messageIndex - offset : undefined
177
+ // Records are shown under the question they belong to. One without a
178
+ // retained message, or whose message fell out of the window, cannot be
179
+ // placed anywhere the user can see, so it is dropped.
180
+ if (index === undefined || index < 0 || index >= messageCount) {
181
+ truncated = true
182
+ continue
183
+ }
184
+ const text = redact(item?.text ?? '')
185
+ const bounded = limitUtf8(text, item?.kind === 'tool_result' ? traceBudget.resultBytes : 2000)
186
+ const [entry] = normalizeTrace([{
187
+ ...item,
188
+ name: item.name ? redact(item.name) : undefined,
189
+ text: bounded,
190
+ truncated: text !== bounded || item.truncated === true,
191
+ messageIndex: index,
192
+ }])
193
+ if (!entry || seen.has(entry.id)) continue
194
+ const cost = Buffer.byteLength(JSON.stringify(entry)) + (items.length ? 1 : 0)
195
+ if (items.length >= traceBudget.items || bytes + cost > traceBudget.bytes) {
196
+ truncated = true
197
+ continue
198
+ }
199
+ seen.add(entry.id)
200
+ bytes += cost
201
+ truncated ||= entry.truncated === true
202
+ items.unshift(entry)
203
+ indexOf.set(index, [entry.id, ...(indexOf.get(index) ?? [])])
204
+ }
205
+ return { trace: items, indexOf, truncated }
206
+ }
207
+
208
+ async function currentDirectory(cwd) {
209
+ try {
210
+ const canonical = await realpath(cwd)
211
+ if ((await stat(canonical)).isDirectory()) return canonical
212
+ } catch {
213
+ // Historical sources may point to an offline drive or a removed worktree.
214
+ }
215
+ return null
216
+ }
217
+
218
+ function sortProjects(a, b) {
219
+ return Number(b.online) - Number(a.online)
220
+ || (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')
221
+ || a.name.localeCompare(b.name, 'zh-CN')
222
+ }
223
+
224
+ function applyProjectState(projects, { archivedIds, preferences }) {
225
+ const visibleState = []
226
+ for (const project of projects) {
227
+ const preference = preferences.get(project.id)
228
+ project.archived = archivedIds.has(project.id)
229
+ project.pinned = preference?.pinned ?? false
230
+ project.continuedAt = preference?.continuedAt ?? null
231
+ if (project.archived || project.pinned || project.continuedAt !== null) {
232
+ visibleState.push([project.id, project.archived, project.pinned, project.continuedAt])
233
+ }
234
+ }
235
+ return keyFor(visibleState.sort((a, b) => a[0].localeCompare(b[0])))
236
+ }
237
+
238
+ function storageFailure(operation, error, subject = '项目归档记录') {
239
+ const sqliteCode = error.errcode & 0xff
240
+ let detail = '请检查 agent-bridge-archive.sqlite 及其所在目录。'
241
+ if (error instanceof ProjectArchiveError) detail = error.message
242
+ else if ([5, 6].includes(sqliteCode)) detail = '归档数据库正忙,请重试。'
243
+ else if ([11, 26].includes(sqliteCode)) detail = '归档文件已损坏或格式无效。'
244
+ else if ([3, 8, 14].includes(sqliteCode) || ['EACCES', 'EPERM', 'EROFS'].includes(error.code)) {
245
+ detail = '请检查归档文件和目录的访问权限。'
246
+ }
247
+ return new RequestError(`无法${operation}${subject}。${detail}`, 503)
248
+ }
249
+
250
+ async function loadProjectState(config) {
251
+ try { return await readProjectState(config) }
252
+ catch (error) { throw storageFailure('读取', error, '项目归档和偏好记录') }
253
+ }
254
+
255
+ function isCatalogId(id) {
256
+ return typeof id === 'string' && catalogId.test(id)
257
+ }
258
+
259
+ function requireProject(current, projectId) {
260
+ const project = current.projects.find(item => item.id === projectId)
261
+ if (!project) throw new RequestError('项目目录已刷新,请重新选择项目。', 404)
262
+ return project
263
+ }
264
+
265
+ export function createCatalog(loadConfig, { importConversation, skillHandoff, loadSourceRecord } = {}) {
266
+ let snapshot
267
+ let scanning
268
+ let revision = 0
269
+ let epoch = 0
270
+ let disposed = false
271
+ const details = new Map()
272
+ const signatures = new Map()
273
+ const skillDetailRevisions = new Map()
274
+ const tickets = new Map()
275
+ const openReferences = new Map()
276
+ const conversationTickets = new Map()
277
+ const watched = new Map()
278
+ const listeners = new Set()
279
+ const monitor = createSourceMonitor({ onChange() {
280
+ epoch++
281
+ wake()
282
+ } })
283
+
284
+ function wake() {
285
+ for (const listener of listeners) listener()
286
+ }
287
+
288
+ function waitForChange(knownRevision) {
289
+ if (knownRevision !== revision || snapshot?.epoch !== epoch || listeners.size >= 32 || disposed) return
290
+ return new Promise(resolve => {
291
+ function done() {
292
+ clearTimeout(timer)
293
+ listeners.delete(done)
294
+ resolve()
295
+ }
296
+ const timer = setTimeout(done, 5_000)
297
+ listeners.add(done)
298
+ })
299
+ }
300
+
301
+ async function synchronizeProjectState() {
302
+ if (scanning) await scanning
303
+ const current = snapshot
304
+ const state = await loadProjectState(current.config)
305
+ if (scanning || snapshot !== current) return synchronizeProjectState()
306
+ const stateFingerprint = applyProjectState(current.projects, state)
307
+ if (current.stateFingerprint !== stateFingerprint) {
308
+ current.stateFingerprint = stateFingerprint
309
+ revision++
310
+ wake()
311
+ }
312
+ return current
313
+ }
314
+
315
+ async function scan(refresh = false) {
316
+ if (scanning) return scanning
317
+ if (!refresh && snapshot?.epoch === epoch && Date.now() - snapshot.scannedAt < fallbackScanInterval) {
318
+ return synchronizeProjectState()
319
+ }
320
+ scanning = (async () => {
321
+ const scanEpoch = epoch
322
+ const config = await loadConfig()
323
+ const result = await scanProjects(config)
324
+ const resolved = new Map()
325
+ const aliases = [...new Set(result.projects.map(item => item.cwd))]
326
+ for (let i = 0; i < aliases.length; i += 64) {
327
+ await Promise.all(aliases.slice(i, i + 64).map(async cwd => resolved.set(cwd, await currentDirectory(cwd))))
328
+ }
329
+ const projects = mergeProjects(result.projects.map(item => ({ ...item, cwd: resolved.get(item.cwd) || item.cwd })))
330
+ const online = new Set([...resolved.values()].filter(Boolean).map(value => pathKey(value)))
331
+ for (const project of projects) {
332
+ project.online = online.has(pathKey(project.cwd))
333
+ if (watched.has(project.cwd)) watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds })
334
+ }
335
+ projects.sort(sortProjects)
336
+ const fingerprint = keyFor(projects, result.sources)
337
+ const stateFingerprint = applyProjectState(projects, await loadProjectState(config))
338
+ const changed = refresh || snapshot?.epoch !== scanEpoch || snapshot?.fingerprint !== fingerprint
339
+ || snapshot?.stateFingerprint !== stateFingerprint
340
+ details.clear()
341
+ snapshot = { config, projects, sources: result.sources, scannedAt: Date.now(), fingerprint, stateFingerprint, epoch: scanEpoch }
342
+ await monitor.update(config, [...watched.values()])
343
+ if (changed) {
344
+ revision++
345
+ wake()
346
+ }
347
+ return snapshot
348
+ })().finally(() => { scanning = undefined })
349
+ return scanning
350
+ }
351
+
352
+ async function setProjectArchive(input) {
353
+ if (typeof input.archived !== 'boolean' || !Array.isArray(input.projectIds) || !input.projectIds.length
354
+ || !input.projectIds.every(isCatalogId)) {
355
+ throw new RequestError('归档请求格式无效,请重新选择项目。')
356
+ }
357
+ const projectIds = [...new Set(input.projectIds)]
358
+ const current = await scan()
359
+ const known = new Set(current.projects.map(project => project.id))
360
+ if (projectIds.some(id => !known.has(id))) throw new RequestError('有项目已不在当前目录中,请刷新后重试。', 404)
361
+ let changedProjectIds
362
+ try { changedProjectIds = await writeProjectArchive(current.config, projectIds, input.archived) }
363
+ catch (error) { throw storageFailure('保存', error) }
364
+ await synchronizeProjectState()
365
+ return { projectIds, changedProjectIds, archived: input.archived, revision }
366
+ }
367
+
368
+ async function setProjectPin({ projectId, pinned }) {
369
+ if (!isCatalogId(projectId) || typeof pinned !== 'boolean') throw new RequestError('置顶请求格式无效。')
370
+ const current = await scan()
371
+ requireProject(current, projectId)
372
+ try { await writeProjectPin(current.config, projectId, pinned) }
373
+ catch (error) { throw storageFailure('保存', error, '项目置顶') }
374
+ await synchronizeProjectState()
375
+ return { projectId, pinned, revision }
376
+ }
377
+
378
+ async function setProjectSelection({ projectId, assetIds, history }) {
379
+ if (!isCatalogId(projectId) || typeof history !== 'boolean'
380
+ || !Array.isArray(assetIds) || assetIds.length > 24 || !assetIds.every(isCatalogId)) {
381
+ throw new RequestError('资料选择格式无效,每个项目最多记住 24 项。')
382
+ }
383
+ const current = snapshot ?? await scan()
384
+ requireProject(current, projectId)
385
+ const selection = { assetIds: [...new Set(assetIds)], history }
386
+ try { await writeProjectSelection(current.config, projectId, selection) }
387
+ catch (error) { throw storageFailure('保存', error, '项目资料选择') }
388
+ return { projectId, selection }
389
+ }
390
+
391
+ async function recordProjectContinuation(id) {
392
+ const ticket = getTicket(id)
393
+ if (!ticket.opened) throw new RequestError('请先打开交接草稿,再记录接续。', 409)
394
+ ticket.continuation ??= writeProjectContinuation(ticket.config, ticket.projectId).catch(error => {
395
+ delete ticket.continuation
396
+ throw storageFailure('保存', error, '项目接续记录')
397
+ })
398
+ const continuedAt = await ticket.continuation
399
+ await synchronizeProjectState()
400
+ return { projectId: ticket.projectId, continuedAt, revision }
401
+ }
402
+
403
+ async function detail(id) {
404
+ const current = await scan()
405
+ const { config } = current
406
+ const project = requireProject(current, id)
407
+ if (skillHandoff?.revision) {
408
+ try {
409
+ const skillRevision = await skillHandoff.revision()
410
+ if (skillDetailRevisions.get(id) !== skillRevision) {
411
+ skillDetailRevisions.set(id, skillRevision)
412
+ if (details.has(id)) {
413
+ details.delete(id)
414
+ signatures.delete(id)
415
+ revision++
416
+ wake()
417
+ }
418
+ }
419
+ } catch { /* The text-only path remains available without a skill service. */ }
420
+ }
421
+ if (details.has(id)) return details.get(id)
422
+ const pending = (async () => {
423
+ if (!watched.has(project.cwd)) {
424
+ if (watched.size >= 4) watched.delete(watched.keys().next().value)
425
+ watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds })
426
+ await monitor.update(config, [...watched.values()])
427
+ }
428
+ const [{ memories, skills }, history] = await Promise.all([
429
+ listProjectAssets(project, config),
430
+ readProjectHistory(project, config),
431
+ ])
432
+ const used = new Set(history.usedSkills.map(name => name.toLowerCase()))
433
+ const normalize = (item, kind) => ({
434
+ ...item, kind, id: keyFor(kind, item.file, item.agent, item.scope),
435
+ used: kind === 'skill' && used.has(item.name.toLowerCase()),
436
+ })
437
+ const normalizedSkills = skills.map(item => normalize(item, 'skill'))
438
+ const inspected = skillHandoff
439
+ ? await skillHandoff.inspect(project, normalizedSkills)
440
+ : {
441
+ available: false,
442
+ projectRoot: undefined,
443
+ skills: Object.fromEntries(normalizedSkills.map(item => [item.id, {
444
+ label: '仅可带入说明',
445
+ state: 'handoff',
446
+ action: 'view',
447
+ allowed: false,
448
+ current: false,
449
+ sourceChanged: false,
450
+ reason: '当前 DSH 未提供原生技能服务。',
451
+ }])),
452
+ }
453
+ for (const item of normalizedSkills) {
454
+ if (inspected.skills[item.id]) item.handoff = inspected.skills[item.id]
455
+ }
456
+ const result = {
457
+ project, history, config,
458
+ memories: memories.map(item => normalize(item, 'memory')),
459
+ skills: normalizedSkills,
460
+ skillNativeAvailable: inspected.available,
461
+ skillProjectRoot: inspected.projectRoot,
462
+ managedSkills: inspected.managedSkills ?? [],
463
+ }
464
+ if (current === snapshot) {
465
+ const assets = [...result.memories, ...result.skills].map(item => [publicAsset(item), item.revision])
466
+ const signature = keyFor(assets, result.managedSkills, history)
467
+ if (signatures.has(id) && signatures.get(id) !== signature) {
468
+ revision++
469
+ wake()
470
+ }
471
+ if (!signatures.has(id) && signatures.size >= 24) signatures.delete(signatures.keys().next().value)
472
+ signatures.set(id, signature)
473
+ }
474
+ return result
475
+ })().catch(error => {
476
+ if (details.get(id) === pending) details.delete(id)
477
+ throw error
478
+ })
479
+ if (details.size >= 24) details.delete(details.keys().next().value)
480
+ details.set(id, pending)
481
+ return pending
482
+ }
483
+
484
+ function publicAsset({ id, name, agent, scope, detail, file, used, handoff }) {
485
+ return { id, name, agent, scope, detail, file, used, ...(handoff ? { handoff } : {}) }
486
+ }
487
+
488
+ async function prepare(input) {
489
+ const entry = await detail(input.projectId)
490
+ const current = await currentDirectory(entry.project.cwd)
491
+ const canImport = Boolean(current && pathKey(current) === pathKey(entry.project.cwd))
492
+ if (!Array.isArray(input.assetIds) || input.assetIds.length > 24 || input.assetIds.some(id => typeof id !== 'string')) {
493
+ throw new RequestError('每次交接最多选择 24 项记忆和 Skills。')
494
+ }
495
+ const selected = new Set(input.assetIds)
496
+ const assets = [...entry.memories, ...entry.skills].filter(item => selected.has(item.id))
497
+ if (assets.length !== selected.size) throw new RequestError('所选资料已变化,请刷新项目。', 409)
498
+ if (input.nativeSkillIds !== undefined && (!Array.isArray(input.nativeSkillIds)
499
+ || input.nativeSkillIds.length > 8
500
+ || input.nativeSkillIds.some(id => typeof id !== 'string' || !selected.has(id)))) {
501
+ throw new RequestError('已启用技能选择格式无效。')
502
+ }
503
+ const nativeSkillIds = new Set(input.nativeSkillIds ?? [])
504
+ const nativeAssets = assets.filter(item => item.kind === 'skill' && nativeSkillIds.has(item.id))
505
+ if (nativeAssets.length !== nativeSkillIds.size) {
506
+ throw new RequestError('已启用技能必须同时属于本次资料选择。')
507
+ }
508
+ let nativeApprovals = []
509
+ if (nativeAssets.length) {
510
+ if (!skillHandoff?.authorizeTextOmission) {
511
+ throw new RequestError('当前 DSH 无法确认技能的原生登记状态。', 409)
512
+ }
513
+ nativeApprovals = await skillHandoff.authorizeTextOmission(entry.project, nativeAssets)
514
+ }
515
+ const sectionAssets = assets.filter(item => !(item.kind === 'skill' && nativeSkillIds.has(item.id)))
516
+ const sections = await Promise.all(sectionAssets.map(async item => {
517
+ const result = await readAsset(item).catch(() => {
518
+ throw new RequestError(`无法读取「${item.name}」。请刷新后重试。`, 409)
519
+ })
520
+ return {
521
+ label: `${item.kind === 'memory' ? '记忆' : 'Skill'} · ${item.name}(${item.agent})`,
522
+ file: item.file, assetId: item.id, ...result,
523
+ handoff: assets.length === 1 && (item.agent === 'export' || item.detail === '项目交接'),
524
+ }
525
+ }))
526
+ if (nativeAssets.length) {
527
+ const approved = new Map(nativeApprovals.map(item => [item.assetId, item]))
528
+ sections.unshift({
529
+ label: '已启用 Skill',
530
+ text: `${nativeAssets.map(item => {
531
+ const name = item.handoff?.dshName || item.name
532
+ return approved.get(item.id)?.invocation?.modelInvocable === false ? `${name}(仅手动)` : name
533
+ }).join('、')} 已由 DSH 原生技能目录提供;按需调用,不在此重复正文。`,
534
+ })
535
+ }
536
+ let historyTrace
537
+ if (input.history === true) {
538
+ const retained = entry.history.messages.slice(-8)
539
+ const offset = entry.history.messages.length - retained.length
540
+ for (const message of retained) {
541
+ if (message.role !== 'user' && message.role !== 'assistant') continue
542
+ const author = message.role === 'user' ? '用户' : '助手'
543
+ sections.push({
544
+ label: [`近期会话 · ${author}`, message.agent].filter(Boolean).join(' · '),
545
+ text: message.text, conversation: true, markdown: message.role === 'assistant',
546
+ })
547
+ }
548
+ // The draft only carries the last few turns, so the trace is trimmed to
549
+ // the same window and re-indexed before it reaches the export preview.
550
+ historyTrace = conversationTrace(entry.history.trace ?? [], retained.length, offset).trace
551
+ }
552
+ const { prompt, truncated, preview } = makePrompt(entry.project, sections, canImport ? await gitStatus(current) : '')
553
+ for (const section of preview.sections) {
554
+ if (!isMarkdownFile(section.file)) continue
555
+ const asset = sectionAssets.find(item => item.id === section.assetId)
556
+ if (asset) section.references = await markdownReferences(entry, asset, section.text)
557
+ }
558
+ if (historyTrace?.length) preview.trace = historyTrace
559
+ for (const [key, value] of tickets) {
560
+ if (Date.now() - value.created > ticketLifetime) tickets.delete(key)
561
+ }
562
+ if (tickets.size >= 40) tickets.delete(tickets.keys().next().value)
563
+ const ticket = randomUUID()
564
+ tickets.set(ticket, {
565
+ created: Date.now(), path: canImport ? current : null, prompt, truncated, title: entry.project.name,
566
+ projectId: entry.project.id, config: entry.config, preview,
567
+ })
568
+ const skillCandidates = entry.skills.filter(item => selected.has(item.id)).map(item => ({
569
+ assetId: item.id,
570
+ ...item.handoff,
571
+ }))
572
+ return { ticket, prompt, truncated, canImport, preview, skillCandidates }
573
+ }
574
+
575
+ function getTicket(id) {
576
+ const ticket = tickets.get(id)
577
+ if (!ticket || Date.now() - ticket.created > ticketLifetime) throw new RequestError('预览已过期,请重新生成。', 409)
578
+ return ticket
579
+ }
580
+
581
+ async function markdownReferences(entry, asset, text) {
582
+ const hrefs = relativeMarkdownLinks(text).slice(0, 128)
583
+ if (!hrefs.length) return []
584
+ const root = await currentDirectory(entry.project.cwd)
585
+ if (!root || pathKey(root) !== pathKey(entry.project.cwd)) return []
586
+ const references = await Promise.all(hrefs.map(async href => {
587
+ const { path: target, authorization, error, revealOnly } = await authorizeProjectReference(root, asset.file, href)
588
+ if (!authorization) return { href, path: target, error }
589
+ const id = randomUUID()
590
+ if (openReferences.size >= 2048) openReferences.delete(openReferences.keys().next().value)
591
+ openReferences.set(id, { projectId: entry.project.id, asset, authorization, revealOnly, created: Date.now() })
592
+ return { href, path: target, id }
593
+ }))
594
+ return references
595
+ }
596
+
597
+ function getOpenReference(id, projectId) {
598
+ const reference = openReferences.get(id)
599
+ if (!reference || reference.projectId !== projectId || Date.now() - reference.created > ticketLifetime) {
600
+ throw new RequestError('文件链接已失效,请重新打开预览。', 409)
601
+ }
602
+ return reference
603
+ }
604
+
605
+ async function verifyOpenReference(reference, current) {
606
+ if (!current || pathKey(current) !== pathKey(reference.authorization.root)) {
607
+ throw new RequestError('项目目录已移动或不可访问。', 409)
608
+ }
609
+ try {
610
+ await verifyAssetSource(reference.asset)
611
+ const target = await verifySourceAuthorization(reference.authorization)
612
+ return { path: target.file, kind: 'file', name: path.basename(target.file), revealOnly: reference.revealOnly }
613
+ } catch {
614
+ throw new RequestError('链接文件已移动、被替换或不在项目范围内。', 409)
615
+ }
616
+ }
617
+
618
+ async function exportPreview(ticket) {
619
+ const current = ticket.path && await currentDirectory(ticket.path)
620
+ if (!current) return ticket.preview
621
+ const sections = await Promise.all(ticket.preview.sections.map(async section => {
622
+ if (!section.references?.length) return section
623
+ const references = await Promise.all(section.references.map(async reference => {
624
+ if (!reference.id) return reference
625
+ try {
626
+ const grant = getOpenReference(reference.id, ticket.projectId)
627
+ const target = await verifyOpenReference(grant, current)
628
+ if (!target.revealOnly) return { ...reference, verifiedFile: target.path }
629
+ } catch { /* A stale reference is exported as text. */ }
630
+ return reference
631
+ }))
632
+ return { ...section, references }
633
+ }))
634
+ return { ...ticket.preview, sections }
635
+ }
636
+
637
+ // The panel never supplies a free-form path for opening. It names an asset
638
+ // that is currently listed for the project (or the project directory
639
+ // itself), and the host re-reads the recorded authorization so a replaced
640
+ // file, a junction, or a moved source is refused instead of opened.
641
+ async function resolveOpenPath(input) {
642
+ const entry = await detail(input.projectId)
643
+ if (input.referenceId !== undefined) {
644
+ const reference = getOpenReference(input.referenceId, entry.project.id)
645
+ const current = await currentDirectory(entry.project.cwd)
646
+ return verifyOpenReference(reference, current)
647
+ }
648
+ if (input.directory === true) {
649
+ const current = await currentDirectory(entry.project.cwd)
650
+ if (!current || pathKey(current) !== pathKey(entry.project.cwd)) {
651
+ throw new RequestError('项目目录已移动或不可访问。', 409)
652
+ }
653
+ return { path: current, kind: 'directory', name: entry.project.name }
654
+ }
655
+ if (typeof input.assetId !== 'string' || !isCatalogId(input.assetId)) {
656
+ throw new RequestError('资料标识无效。')
657
+ }
658
+ const item = [...entry.memories, ...entry.skills].find(asset => asset.id === input.assetId)
659
+ if (!item) throw new RequestError('找不到所选资料,请刷新项目。', 404)
660
+ let source
661
+ try {
662
+ source = await verifyAssetSource(item)
663
+ } catch {
664
+ throw new RequestError('资料已移动或内容已变化,请刷新项目后重试。', 409)
665
+ }
666
+ return { path: source.file, kind: 'file', name: item.name }
667
+ }
668
+
669
+ async function listConversations(projectId, recent) {
670
+ const current = await scan()
671
+ const project = requireProject(current, projectId)
672
+ const archives = project.archives
673
+ .filter(canReadConversation)
674
+ .sort((a, b) => dateMillis(b.date) - dateMillis(a.date))
675
+ const seen = new Set()
676
+ const sessions = []
677
+ for (const archive of archives) {
678
+ const id = conversationId(archive)
679
+ if (seen.has(id)) continue
680
+ seen.add(id)
681
+ if (recent && sessions.length === 3) continue
682
+ sessions.push({
683
+ id, agent: archive.agent ?? archive.kind, date: dateMillis(archive.date),
684
+ title: conversationTitle(archive.title), archivedSource: archive.kind === 'agentsview',
685
+ })
686
+ }
687
+ return recent ? { sessions, total: seen.size } : { sessions }
688
+ }
689
+
690
+ async function previewConversation({ projectId, sessionId }) {
691
+ if (!isCatalogId(sessionId)) throw new RequestError('会话标识无效。')
692
+ const current = await scan()
693
+ const project = requireProject(current, projectId)
694
+ const { config } = current
695
+ const archive = project.archives.find(item => canReadConversation(item) && conversationId(item) === sessionId)
696
+ if (!archive) throw new RequestError('找不到这条会话,请刷新项目。', 404)
697
+ const history = await readConversationHistory(archive, project.cwd, config).catch(() => {
698
+ throw new RequestError('会话已移动或无法读取,请刷新后重试。', 409)
699
+ })
700
+ if (!history.messages.length) throw new RequestError('这条会话没有可迁入的文字问答。', 409)
701
+ const messages = history.messages.map(({ role, text, time }) => ({ role, text: redact(text), time }))
702
+ const { trace, indexOf, truncated: traceTruncated } = conversationTrace(history.trace ?? [], messages.length)
703
+ for (let index = 0; index < messages.length; index++) {
704
+ if (indexOf.has(index)) messages[index].traceIds = indexOf.get(index)
705
+ }
706
+ const traceCounts = countTrace(trace)
707
+ const { sourceStats } = history
708
+ const title = conversationTitle(archive.title || messages[0].text, 80) || '迁入的 Agent 会话'
709
+ const path = await currentDirectory(project.cwd)
710
+ const canImport = Boolean(path && pathKey(path) === pathKey(project.cwd))
711
+ const ticket = randomUUID()
712
+ for (const [key, record] of conversationTickets) {
713
+ if (!record.pending && Date.now() - record.created > ticketLifetime) conversationTickets.delete(key)
714
+ }
715
+ if (canImport && conversationTickets.size >= conversationTicketLimit) {
716
+ const oldest = [...conversationTickets].find(([, record]) => !record.pending)
717
+ if (!oldest) throw new RequestError('其他会话正在迁入,请稍后重试。', 409)
718
+ conversationTickets.delete(oldest[0])
719
+ }
720
+ if (canImport) conversationTickets.set(ticket, {
721
+ created: Date.now(), projectId, sessionId: randomUUID(), path, config, messages, title, trace, sourceStats,
722
+ })
723
+ const entry = await detail(projectId)
724
+ const skillCandidates = skillHandoff
725
+ ? await skillHandoff.conversationCandidates(project, history.usedSkills, entry.skills)
726
+ : []
727
+ return {
728
+ title, messages, ticket: canImport ? ticket : null, canImport, cwd: project.cwd,
729
+ truncated: history.truncated || traceTruncated, skillCandidates, trace, traceCounts, sourceStats,
730
+ }
731
+ }
732
+
733
+ async function commitConversation(ticket) {
734
+ const record = conversationTickets.get(ticket)
735
+ if (!record || Date.now() - record.created > ticketLifetime) {
736
+ throw new RequestError('会话预览已过期,请重新打开。', 409)
737
+ }
738
+ if (record.result) return record.result
739
+ if (record.pending) return record.pending
740
+ record.pending = (async () => {
741
+ const cwd = await currentDirectory(record.path)
742
+ if (!cwd || pathKey(cwd) !== pathKey(record.path)) {
743
+ throw new RequestError('原工作目录已变化,请刷新项目。', 409)
744
+ }
745
+ try {
746
+ record.result = await importConversation(record, cwd)
747
+ } catch (error) {
748
+ if (error.status) throw error
749
+ const message = record.stored ? '会话历史已写入,暂时无法加入工作区。可重试打开。' : '无法将会话写入 DSH。请检查工作区和会话存储后重试。'
750
+ throw new RequestError(message, 503)
751
+ }
752
+ delete record.messages
753
+ delete record.stored
754
+ try {
755
+ await writeProjectContinuation(record.config, record.projectId)
756
+ await synchronizeProjectState()
757
+ } catch { /* A saved session remains usable even if the recents index cannot be updated. */ }
758
+ return record.result
759
+ })().finally(() => { delete record.pending })
760
+ return record.pending
761
+ }
762
+
763
+ async function exportSession({ conversation, format, includeTrace, sessionId }) {
764
+ if (!conversation || typeof conversation.title !== 'string' || conversation.title.length > 500
765
+ || typeof conversation.path !== 'string' || conversation.path.length > 4096
766
+ || !path.isAbsolute(conversation.path) || /[\u0000-\u001f]/u.test(conversation.path)
767
+ || !Array.isArray(conversation.messages) || conversation.messages.length > 24) {
768
+ throw new RequestError('DSH 会话资料格式无效。')
769
+ }
770
+ const sections = conversation.messages
771
+ .filter(message => (message?.role === 'user' || message?.role === 'assistant')
772
+ && typeof message.text === 'string' && message.text.trim())
773
+ .map(message => ({ label: message.role === 'user' ? '用户' : 'DSH 助手', text: message.text,
774
+ conversation: true, markdown: message.role === 'assistant' }))
775
+ if (!sections.length) throw new RequestError('这段会话暂无可导出的消息。', 409)
776
+ const title = redact(conversation.title.trim()) || 'DSH 会话'
777
+ const { truncated, preview } = makePrompt({ name: title, cwd: conversation.path, agents: ['DSH'] }, sections, '')
778
+ const saved = includeTrace === true ? await loadSourceRecord?.(sessionId) : undefined
779
+ return makeExport({
780
+ title, origin: 'DSH 会话', format,
781
+ preview: { ...preview, truncated: truncated || conversation.truncated === true, trace: saved?.trace },
782
+ includeTrace: includeTrace === true,
783
+ })
784
+ }
785
+
786
+ return {
787
+ dispose() {
788
+ disposed = true
789
+ wake()
790
+ monitor.dispose()
791
+ tickets.clear()
792
+ openReferences.clear()
793
+ conversationTickets.clear()
794
+ },
795
+ async execute(action, input) {
796
+ if (action === 'catalog') {
797
+ const { projects, sources, scannedAt } = await scan(input.refresh === true)
798
+ return { projects: projects.map(publicProject), sources, scannedAt, revision }
799
+ }
800
+ if (action === 'set-project-archive') return setProjectArchive(input)
801
+ if (action === 'set-project-pin') return setProjectPin(input)
802
+ if (action === 'set-project-selection') return setProjectSelection(input)
803
+ if (action === 'record-project-continuation') return recordProjectContinuation(input.ticket)
804
+ if (action === 'preview-skill-activation') {
805
+ if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
806
+ if (!isCatalogId(input.projectId) || !Array.isArray(input.assetIds)
807
+ || !input.assetIds.length || input.assetIds.length > 8 || !input.assetIds.every(isCatalogId)) {
808
+ throw new RequestError('技能启用请求格式无效。')
809
+ }
810
+ const current = snapshot ?? await scan()
811
+ const project = requireProject(current, input.projectId)
812
+ const entry = await detail(project.id)
813
+ const wanted = new Set(input.assetIds)
814
+ const assets = entry.skills.filter(item => wanted.has(item.id))
815
+ if (assets.length !== wanted.size) throw new RequestError('所选技能已变化,请刷新项目。', 409)
816
+ return await skillHandoff.preview(project, assets)
817
+ }
818
+ if (action === 'apply-skill-activation') {
819
+ if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
820
+ if (typeof input.ticket !== 'string' || input.ticket.length > 128) {
821
+ throw new RequestError('技能预览凭证无效。')
822
+ }
823
+ const result = await skillHandoff.apply(input.ticket)
824
+ details.clear()
825
+ revision++
826
+ wake()
827
+ return { ...result, revision }
828
+ }
829
+ if (action === 'deactivate-skill-activation' || action === 'undo-skill-activation') {
830
+ if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
831
+ if (!isCatalogId(input.projectId) || !isCatalogId(input.activationId)) {
832
+ throw new RequestError('技能启用记录格式无效。')
833
+ }
834
+ const current = snapshot ?? await scan()
835
+ const project = requireProject(current, input.projectId)
836
+ const result = action === 'undo-skill-activation'
837
+ ? await skillHandoff.undo(project, input.activationId)
838
+ : await skillHandoff.deactivate(project, input.activationId)
839
+ details.clear()
840
+ revision++
841
+ wake()
842
+ return { ...result, revision }
843
+ }
844
+ if (action === 'list-conversations' || action === 'preview-conversation' || action === 'import-conversation') {
845
+ if (!importConversation) throw new RequestError('当前 DSH 未提供会话迁入服务。', 409)
846
+ if (action === 'list-conversations') return listConversations(input.projectId, input.recent === true)
847
+ if (action === 'preview-conversation') return previewConversation(input)
848
+ return commitConversation(input.ticket)
849
+ }
850
+ if (action === 'changes') {
851
+ const inspect = async () => {
852
+ const current = await scan()
853
+ if (current.projects.some(item => item.id === input.projectId)) await detail(input.projectId)
854
+ }
855
+ await inspect()
856
+ if (input.wait === true && input.revision === revision) {
857
+ await waitForChange(input.revision)
858
+ if (!disposed) await inspect()
859
+ }
860
+ return { revision, changed: input.revision !== revision, scannedAt: snapshot.scannedAt }
861
+ }
862
+ if (action === 'detail') {
863
+ const {
864
+ project, history, memories, skills, config, skillNativeAvailable, skillProjectRoot, managedSkills,
865
+ } = await detail(input.projectId)
866
+ let selection
867
+ try { selection = await readProjectSelection(config, project.id) }
868
+ catch (error) { throw storageFailure('读取', error, '项目资料选择') }
869
+ return {
870
+ project: publicProject(project), memories: memories.map(publicAsset), skills: skills.map(publicAsset),
871
+ usedSkills: history.usedSkills, historyCount: history.messages.length, selection,
872
+ skillNativeAvailable, skillProjectRoot, managedSkills,
873
+ }
874
+ }
875
+ if (action === 'asset') {
876
+ const entry = await detail(input.projectId)
877
+ const item = [...entry.memories, ...entry.skills].find(asset => asset.id === input.assetId)
878
+ if (!item) throw new RequestError('找不到所选资料。', 404)
879
+ const result = await readAsset(item).catch(() => { throw new RequestError('资料已移动或不可读。', 409) })
880
+ const text = redact(result.text)
881
+ const references = isMarkdownFile(item.file) ? await markdownReferences(entry, item, text) : []
882
+ return { ...result, text, references }
883
+ }
884
+ if (action === 'preview') return prepare(input)
885
+ if (action === 'resolve-open-path') return resolveOpenPath(input)
886
+ if (action === 'export') {
887
+ const ticket = getTicket(input.ticket)
888
+ return makeExport({
889
+ title: redact(ticket.title), origin: '项目交接', format: input.format,
890
+ preview: await exportPreview(ticket), date: new Date(ticket.created),
891
+ includeTrace: input.includeTrace === true,
892
+ })
893
+ }
894
+ if (action === 'export-session') return exportSession(input)
895
+ if (action === 'open') {
896
+ const ticket = getTicket(input.ticket)
897
+ if (!ticket.path) throw new RequestError('原工作目录不可访问。可导出交接。', 409)
898
+ const current = await currentDirectory(ticket.path)
899
+ if (!current || pathKey(current) !== pathKey(ticket.path)) throw new RequestError('原工作目录已变化。', 409)
900
+ ticket.opened = true
901
+ return { path: current, prompt: ticket.prompt }
902
+ }
903
+ throw new RequestError('找不到该操作。', 404)
904
+ },
905
+ }
906
+ }