@wwwfz/dsh-agent-bridge 0.9.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/README.md +61 -99
- package/THIRD_PARTY_NOTICES.md +5 -63
- package/package.json +2 -1
- package/src/assets.js +32 -19
- package/src/catalog.js +1139 -906
- package/src/client.js +1218 -623
- package/src/conversation-readers.js +198 -0
- package/src/conversation-search.js +55 -0
- package/src/conversation-store.js +747 -0
- package/src/export.js +35 -2
- package/src/handoff.js +149 -0
- package/src/history-attachment.js +41 -0
- package/src/index.js +153 -7
- package/src/native-transcript.js +217 -0
- package/src/project-archive.js +50 -0
- package/src/projects.js +877 -149
- package/src/session-import.js +65 -19
- package/src/session-trace.js +1 -1
- package/src/skill-cli.js +287 -0
- package/src/skill-history.js +129 -0
- package/src/skill-output.js +19 -0
- package/src/skill-package.js +303 -321
- package/src/skill-provider.js +155 -193
- package/src/watch.js +11 -1
- package/web/inline-process.css +22 -0
- package/web/panel.css +547 -607
- package/web/panel.html +298 -277
- package/web/panel.js +3339 -2334
- package/web/reader.css +311 -0
- package/web/relay-categories.js +3 -0
- package/web/share-redaction.js +136 -0
- package/web/share-review.js +204 -0
package/src/export.js
CHANGED
|
@@ -118,6 +118,38 @@ function fenceSafe(text) {
|
|
|
118
118
|
return `${text}${/\r$|\n$/.test(text) ? '' : eol}${fence.markup}`
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
+
export async function* sourceHistoryMarkdown(record, pages, { format, includeTrace }) {
|
|
122
|
+
yield `# 外部会话来源历史\n\n${escapeProse(record.title || '迁入的 Agent 会话')}\n\n`
|
|
123
|
+
if (format === 'local' && record.sourceCwd) {
|
|
124
|
+
yield `来源目录 ${fileLink(shortName(record.sourceCwd), directoryUrl(record.sourceCwd))}\n\n`
|
|
125
|
+
}
|
|
126
|
+
if (!record.history.complete) yield '部分来源内容不可恢复,原因见下方记录。\n\n'
|
|
127
|
+
let current
|
|
128
|
+
function render(item) {
|
|
129
|
+
if (!item) return ''
|
|
130
|
+
const turn = item.turn ? ` · 第 ${item.turn} 轮` : ''
|
|
131
|
+
if (item.kind === 'message') {
|
|
132
|
+
return `## ${item.role === 'user' ? '用户' : '助手'}${turn}\n\n${fenceSafe(item.text)}\n\n`
|
|
133
|
+
}
|
|
134
|
+
if (item.kind === 'attachment') return `附件 ${escapeProse(item.name)}(${item.status === 'saved' ? '本机档案已保存' : item.status})${turn}\n\n`
|
|
135
|
+
if (item.kind === 'gap') return `来源缺失(${escapeProse(item.reason)})\n\n`
|
|
136
|
+
if (item.kind === 'turn_end') return `回合状态 ${item.status}${turn}\n\n`
|
|
137
|
+
if (!includeTrace) return ''
|
|
138
|
+
const label = { summary: '公开摘要', tool_call: '工具调用', tool_result: '工具结果' }[item.kind]
|
|
139
|
+
return label ? `### ${label}${turn}\n\n${escapeProse([item.name, item.callId, item.status].filter(Boolean).join(' · '))}\n\n${fenceSafe(item.text ?? '')}\n\n` : ''
|
|
140
|
+
}
|
|
141
|
+
for await (const page of pages) {
|
|
142
|
+
for (const item of page.items) {
|
|
143
|
+
if (current?.seq === item.seq) current.text += item.text
|
|
144
|
+
else {
|
|
145
|
+
yield render(current)
|
|
146
|
+
current = item
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
yield render(current)
|
|
151
|
+
}
|
|
152
|
+
|
|
121
153
|
function fileStamp(date) {
|
|
122
154
|
return date.toISOString().slice(0, 19).replace(/[-:]/g, '') + 'Z'
|
|
123
155
|
}
|
|
@@ -177,6 +209,7 @@ export function makeExport({
|
|
|
177
209
|
const heading = clean(title) || '项目交接'
|
|
178
210
|
const session = origin === 'DSH 会话'
|
|
179
211
|
const mode = format === 'share' ? 'share' : 'local'
|
|
212
|
+
const filename = filenameOf(mode === 'share' ? 'share' : heading, date)
|
|
180
213
|
const exportFile = typeof savePath === 'string' && path.isAbsolute(savePath) ? savePath : undefined
|
|
181
214
|
const legacy = typeof prompt === 'string' && prompt.trim() && !Array.isArray(preview.sections)
|
|
182
215
|
const sections = Array.isArray(preview.sections)
|
|
@@ -206,7 +239,7 @@ export function makeExport({
|
|
|
206
239
|
lines.push(fenceSafe(prompt), '')
|
|
207
240
|
if (truncated) lines.push('> 部分内容已截取,完整内容见来源文件。', '')
|
|
208
241
|
if (preview.footer) lines.push(`> ${clean(preview.footer, 200)}`, '')
|
|
209
|
-
return { filename
|
|
242
|
+
return { filename, markdown: `${lines.join('\n').trimEnd()}\n` }
|
|
210
243
|
}
|
|
211
244
|
|
|
212
245
|
if (files.length) {
|
|
@@ -237,5 +270,5 @@ export function makeExport({
|
|
|
237
270
|
if (truncated) lines.push('> 部分内容已截取,完整内容见来源文件。', '')
|
|
238
271
|
if (preview.footer) lines.push(`> ${clean(preview.footer, 200)}`, '')
|
|
239
272
|
|
|
240
|
-
return { filename
|
|
273
|
+
return { filename, markdown: `${lines.join('\n').trimEnd()}\n` }
|
|
241
274
|
}
|
package/src/handoff.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import path, { win32 } from 'node:path'
|
|
3
|
+
|
|
4
|
+
const limit = 32_000
|
|
5
|
+
|
|
6
|
+
export function keyFor(...values) {
|
|
7
|
+
return createHash('sha256').update(JSON.stringify(values)).digest('hex').slice(0, 24)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function pathKey(value, platform = process.platform) {
|
|
11
|
+
const normalized = (platform === 'win32' ? win32 : path).normalize(value)
|
|
12
|
+
return platform === 'win32' ? normalized.toLowerCase() : normalized
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function mergeProjects(entries, platform = process.platform) {
|
|
16
|
+
const byPath = new Map()
|
|
17
|
+
for (const item of entries) {
|
|
18
|
+
if (typeof item.cwd !== 'string' || !(platform === 'win32' ? win32 : path).isAbsolute(item.cwd)) continue
|
|
19
|
+
const key = pathKey(item.cwd, platform)
|
|
20
|
+
if (!byPath.has(key)) byPath.set(key, {
|
|
21
|
+
id: keyFor(key), cwd: item.cwd, name: (platform === 'win32' ? win32 : path).basename(item.cwd) || item.cwd,
|
|
22
|
+
agents: [], projectIds: [], archives: [],
|
|
23
|
+
})
|
|
24
|
+
const project = byPath.get(key)
|
|
25
|
+
if (item.projectId && !project.projectIds.includes(item.projectId)) {
|
|
26
|
+
project.projectIds.push(item.projectId)
|
|
27
|
+
project.name = item.name || project.name
|
|
28
|
+
}
|
|
29
|
+
if (item.agent && !project.agents.includes(item.agent)) project.agents.push(item.agent)
|
|
30
|
+
if (Array.isArray(item.archive)) project.archives.push(...item.archive)
|
|
31
|
+
else if (item.archive) project.archives.push(item.archive)
|
|
32
|
+
if (item.updatedAt > (project.updatedAt ?? '')) project.updatedAt = item.updatedAt
|
|
33
|
+
}
|
|
34
|
+
for (const project of byPath.values()) project.agents.sort()
|
|
35
|
+
return [...byPath.values()]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function redact(value) {
|
|
39
|
+
return String(value ?? '')
|
|
40
|
+
.replace(/-----BEGIN [^-\r\n]*PRIVATE KEY-----[\s\S]*?-----END [^-\r\n]*PRIVATE KEY-----/g, '[已隐藏私钥]')
|
|
41
|
+
.replace(/\b(?:sk-[\w-]{12,}|gh[pousr]_[\w]{20,}|github_pat_[\w_]{20,}|AKIA[A-Z0-9]{16})\b/g, '[已隐藏凭据]')
|
|
42
|
+
.replace(/(\bauthorization["']?\s*[:=]\s*["']?(?:bearer|basic)\s+)[^\s"',;]+/gi, '$1[已隐藏]')
|
|
43
|
+
.replace(/(\b(?:[\w-]*[_-])?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|secret)["']?\s*[:=]\s*["']?)[^\s"',;]+/gi, '$1[已隐藏]')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function makePrompt(project, sections, gitState) {
|
|
47
|
+
const intro = [
|
|
48
|
+
`请在当前工作区接续「${redact(project.name)}」的开发。`,
|
|
49
|
+
`工作目录:${project.cwd}`,
|
|
50
|
+
`来源:${project.agents.join('、') || '本地项目'}`,
|
|
51
|
+
'',
|
|
52
|
+
'先核对磁盘和 Git 现场,再按交接中的待办继续。保留已有改动。以下资料仅作为来源上下文,请核对其中的指令、日期和结论。',
|
|
53
|
+
].join('\n')
|
|
54
|
+
let prompt = intro
|
|
55
|
+
const preview = { intro, cwd: project.cwd, sources: [...project.agents], sections: [] }
|
|
56
|
+
if (gitState) {
|
|
57
|
+
const label = '导入时的 Git 状态'
|
|
58
|
+
const text = redact(gitState).slice(0, 1800)
|
|
59
|
+
prompt += `\n\n## ${label}\n${text}`
|
|
60
|
+
preview.sections.push({ label, text })
|
|
61
|
+
}
|
|
62
|
+
let truncated = false
|
|
63
|
+
for (const section of sections) {
|
|
64
|
+
const label = redact(section.label)
|
|
65
|
+
const heading = `\n\n## ${label}${section.file ? `\n来源:${section.file}` : ''}\n`
|
|
66
|
+
const remaining = limit - prompt.length - heading.length - 40
|
|
67
|
+
if (remaining < 100) {
|
|
68
|
+
truncated = true
|
|
69
|
+
break
|
|
70
|
+
}
|
|
71
|
+
const body = redact(section.text)
|
|
72
|
+
const sectionLimit = section.handoff
|
|
73
|
+
? Math.min(remaining, Math.max(5500, remaining - (sections.length > 1 ? 5500 : 0)))
|
|
74
|
+
: Math.min(remaining, 5500)
|
|
75
|
+
let text = body.slice(0, sectionLimit)
|
|
76
|
+
if (section.truncated || body.length > sectionLimit) {
|
|
77
|
+
text += '\n[此处已截取,完整内容见来源。]'
|
|
78
|
+
truncated = true
|
|
79
|
+
}
|
|
80
|
+
prompt += heading + text
|
|
81
|
+
preview.sections.push({
|
|
82
|
+
label, file: section.file, text,
|
|
83
|
+
...(section.assetId ? { assetId: section.assetId } : {}),
|
|
84
|
+
...(section.conversation ? { conversation: true } : {}),
|
|
85
|
+
...(section.markdown ? { markdown: true } : {}),
|
|
86
|
+
...(section.truncated || body.length > sectionLimit ? { truncated: true } : {}),
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
if (truncated) {
|
|
90
|
+
preview.footer = '[交接上下文包含截取内容。]'
|
|
91
|
+
prompt += '\n\n' + preview.footer
|
|
92
|
+
}
|
|
93
|
+
return { prompt, truncated, preview: { ...preview, truncated } }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function canReadConversation(archive) {
|
|
97
|
+
// Antigravity's native CLI index stores prompts, not the assistant replies.
|
|
98
|
+
return archive.kind !== 'antigravity' && typeof archive.file === 'string'
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function conversationId(archive) {
|
|
102
|
+
if (archive.kind === 'codex' && archive.profile && archive.sourceCwd && typeof archive.id === 'string' && archive.id.trim()) {
|
|
103
|
+
return keyFor('codex-thread', pathKey(archive.profile), pathKey(archive.sourceCwd), archive.id)
|
|
104
|
+
}
|
|
105
|
+
return keyFor(archive.kind, archive.file, archive.table, archive.id)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function conversationIds(archive) {
|
|
109
|
+
const ids = new Set([conversationId(archive)])
|
|
110
|
+
if (!archive.profile || !archive.sourceCwd || archive.kind !== 'codex' || typeof archive.id !== 'string' || !archive.id.trim()) return [...ids]
|
|
111
|
+
const paths = new Set()
|
|
112
|
+
for (const file of [archive.file, ...(archive.previousFiles ?? [])]) {
|
|
113
|
+
const plain = file.replace(/\.zst$/i, '')
|
|
114
|
+
paths.add(file)
|
|
115
|
+
paths.add(plain)
|
|
116
|
+
paths.add(plain + '.zst')
|
|
117
|
+
const name = path.basename(plain)
|
|
118
|
+
// Codex moves dated rollouts to a flat archive and may compress them in place.
|
|
119
|
+
const date = /^rollout-(\d{4})-(\d\d)-(\d\d)T/i.exec(name)
|
|
120
|
+
const relatives = [name]
|
|
121
|
+
if (date) relatives.push(path.join(date[1], date[2], date[3], name))
|
|
122
|
+
for (const base of archive.rolloutRoots) {
|
|
123
|
+
const relative = path.relative(base, plain)
|
|
124
|
+
if (relative && !relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative)) relatives.push(relative)
|
|
125
|
+
}
|
|
126
|
+
for (const base of archive.rolloutRoots) {
|
|
127
|
+
for (const relative of relatives) {
|
|
128
|
+
const candidate = path.join(base, relative)
|
|
129
|
+
paths.add(candidate)
|
|
130
|
+
paths.add(candidate + '.zst')
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
for (const file of paths) ids.add(keyFor('codex', file, archive.table, archive.id))
|
|
135
|
+
for (const alias of archive.savedIds ?? []) ids.add(alias)
|
|
136
|
+
return [...ids]
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function conversationTitle(value, bytes = 200) {
|
|
140
|
+
const normalized = redact(value).replace(/[\s\p{Cc}]+/gu, ' ').trim()
|
|
141
|
+
let title = ''
|
|
142
|
+
let length = 0
|
|
143
|
+
for (const char of normalized) {
|
|
144
|
+
length += Buffer.byteLength(char)
|
|
145
|
+
if (length > bytes) break
|
|
146
|
+
title += char
|
|
147
|
+
}
|
|
148
|
+
return title
|
|
149
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { authorizeProjectReference, verifySourceAuthorization } from './assets.js'
|
|
4
|
+
import { redact } from './handoff.js'
|
|
5
|
+
|
|
6
|
+
export async function readConversationAttachment(project, archive, item) {
|
|
7
|
+
if (!item.path) return
|
|
8
|
+
const candidate = path.isAbsolute(item.path) ? path.normalize(item.path) : path.resolve(project.cwd, item.path)
|
|
9
|
+
let withinScope = false
|
|
10
|
+
for (const root of [project.cwd, path.join(path.dirname(archive.file), 'attachments')]) {
|
|
11
|
+
if (!root || !path.isAbsolute(root)) continue
|
|
12
|
+
const relative = path.relative(root, candidate)
|
|
13
|
+
if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) continue
|
|
14
|
+
withinScope = true
|
|
15
|
+
const href = relative.split(path.sep).map(encodeURIComponent).join('/')
|
|
16
|
+
const proof = await authorizeProjectReference(root, path.join(root, '.conversation'), href)
|
|
17
|
+
if (!proof.authorization) continue
|
|
18
|
+
const handle = await open(candidate, 'r').catch(() => undefined)
|
|
19
|
+
if (!handle) continue
|
|
20
|
+
try {
|
|
21
|
+
const initial = await handle.stat({ bigint: true })
|
|
22
|
+
const current = await verifySourceAuthorization(proof.authorization)
|
|
23
|
+
if (initial.dev !== current.fileInfo.dev || initial.ino !== current.fileInfo.ino) continue
|
|
24
|
+
if (initial.size > 32n * 1024n * 1024n) return { details: { status: 'attachment-too-large' } }
|
|
25
|
+
const bytes = Buffer.alloc(Number(initial.size))
|
|
26
|
+
let offset = 0
|
|
27
|
+
while (offset < bytes.length) {
|
|
28
|
+
const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset)
|
|
29
|
+
if (!bytesRead) break
|
|
30
|
+
offset += bytesRead
|
|
31
|
+
}
|
|
32
|
+
const end = await handle.stat({ bigint: true })
|
|
33
|
+
await verifySourceAuthorization(proof.authorization)
|
|
34
|
+
if (offset === bytes.length && end.size === initial.size && end.mtimeNs === initial.mtimeNs && end.ctimeNs === initial.ctimeNs) {
|
|
35
|
+
return { bytes, details: { name: redact(path.basename(candidate)) } }
|
|
36
|
+
}
|
|
37
|
+
} catch { /* Source identity changed during the read. */ }
|
|
38
|
+
finally { await handle.close() }
|
|
39
|
+
}
|
|
40
|
+
return { details: { status: withinScope ? 'attachment-unavailable' : 'outside-project' } }
|
|
41
|
+
}
|
package/src/index.js
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { once } from 'node:events'
|
|
2
3
|
import { existsSync, readdirSync } from 'node:fs'
|
|
3
4
|
import { readFile } from 'node:fs/promises'
|
|
4
5
|
import { createCatalog } from './catalog.js'
|
|
5
6
|
import { loadConfig } from './config.js'
|
|
6
|
-
import { nativeSessionServices, saveNativeSession } from './session-import.js'
|
|
7
|
+
import { nativeSessionEvents, nativeSessionServices, saveNativeSession } from './session-import.js'
|
|
7
8
|
import { countTrace, isSessionId, readSessionTrace } from './session-trace.js'
|
|
8
9
|
import { createSkillBridge } from './skill-provider.js'
|
|
10
|
+
import { readHistoryAttachment, readHistoryPage, readProcessPlacements, readStoredConversation } from './conversation-store.js'
|
|
11
|
+
import { sourceHistoryMarkdown } from './export.js'
|
|
9
12
|
|
|
10
13
|
export const name = 'dsh-agent-bridge'
|
|
11
14
|
export const inject = {
|
|
12
15
|
connection: true, webServer: true,
|
|
13
16
|
sessions: false, sessionPersistence: false, workspaceRegistry: false, sessionProjectionCache: false,
|
|
17
|
+
attachments: false,
|
|
14
18
|
skills: false,
|
|
15
19
|
}
|
|
16
20
|
|
|
@@ -31,6 +35,16 @@ function json(res, status, data) {
|
|
|
31
35
|
respond(res, status, 'application/json; charset=utf-8', JSON.stringify(data))
|
|
32
36
|
}
|
|
33
37
|
|
|
38
|
+
function attachmentDisposition(name, fallback, inline) {
|
|
39
|
+
const recorded = typeof name === 'string'
|
|
40
|
+
? name.split(/[\\/]/).at(-1).replace(/[\u0000-\u001f\u007f-\u009f]/gu, '').trim()
|
|
41
|
+
: ''
|
|
42
|
+
const filename = recorded && !/^\.{1,2}$/.test(recorded) ? recorded.toWellFormed() : fallback
|
|
43
|
+
const encoded = encodeURIComponent(filename)
|
|
44
|
+
.replace(/['()*]/g, character => '%' + character.charCodeAt(0).toString(16).toUpperCase())
|
|
45
|
+
return `${inline ? 'inline' : 'attachment'}; filename="${fallback}"; filename*=UTF-8''${encoded}`
|
|
46
|
+
}
|
|
47
|
+
|
|
34
48
|
function isLoopback(address) {
|
|
35
49
|
return typeof address === 'string' && (address === '::1' || /^(?:::ffff:)?127(?:\.\d{1,3}){3}$/.test(address))
|
|
36
50
|
}
|
|
@@ -63,17 +77,34 @@ async function readBody(req) {
|
|
|
63
77
|
export function apply(ctx) {
|
|
64
78
|
const services = () => nativeSessionServices(ctx)
|
|
65
79
|
const skillHandoff = ctx.get?.('skills') ? createSkillBridge(ctx) : undefined
|
|
66
|
-
async function
|
|
80
|
+
async function verifyStoredSession(sessionId) {
|
|
67
81
|
if (!isSessionId(sessionId)) throw Object.assign(new Error('会话标识无效。'), { status: 400 })
|
|
68
82
|
const session = await ctx.get?.('sessionPersistence')?.stat?.(sessionId)
|
|
69
83
|
if (session?.header?.id !== sessionId) {
|
|
70
84
|
throw Object.assign(new Error('找不到这条 DSH 会话。'), { status: 404 })
|
|
71
85
|
}
|
|
72
|
-
|
|
73
|
-
|
|
86
|
+
}
|
|
87
|
+
async function loadArchive(sessionId) {
|
|
88
|
+
await verifyStoredSession(sessionId)
|
|
89
|
+
const config = await loadConfig()
|
|
90
|
+
const stored = await readStoredConversation(config, sessionId)
|
|
91
|
+
if (!stored) throw Object.assign(new Error('这条会话没有完整来源档案。'), { status: 404 })
|
|
92
|
+
return { config, stored }
|
|
93
|
+
}
|
|
94
|
+
async function loadSourceRecord(sessionId) {
|
|
95
|
+
await verifyStoredSession(sessionId)
|
|
96
|
+
const config = await loadConfig()
|
|
97
|
+
const saved = await readSessionTrace(config, sessionId)
|
|
98
|
+
const stored = await readStoredConversation(config, sessionId)
|
|
99
|
+
if (!saved?.trace?.length && !saved?.sourceStats && !stored) {
|
|
74
100
|
throw Object.assign(new Error('没有为这条会话保存来源记录。'), { status: 404 })
|
|
75
101
|
}
|
|
76
|
-
return { ...saved, traceCounts: countTrace(saved
|
|
102
|
+
return { ...saved, trace: saved?.trace ?? [], traceCounts: countTrace(saved?.trace ?? []),
|
|
103
|
+
...(stored ? { history: stored.history } : {}) }
|
|
104
|
+
}
|
|
105
|
+
async function archivePage(sessionId, cursor, turn) {
|
|
106
|
+
const { config, stored } = await loadArchive(sessionId)
|
|
107
|
+
return readHistoryPage(config, stored.id, cursor, turn)
|
|
77
108
|
}
|
|
78
109
|
const catalog = createCatalog(loadConfig, {
|
|
79
110
|
importConversation(record, cwd) {
|
|
@@ -81,6 +112,12 @@ export function apply(ctx) {
|
|
|
81
112
|
if (!host) throw Object.assign(new Error('当前 DSH 未提供会话迁入服务。'), { status: 409 })
|
|
82
113
|
return saveNativeSession(host, record, cwd)
|
|
83
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
|
+
},
|
|
84
121
|
skillHandoff,
|
|
85
122
|
loadSourceRecord,
|
|
86
123
|
})
|
|
@@ -89,7 +126,12 @@ export function apply(ctx) {
|
|
|
89
126
|
const staticRoutes = [
|
|
90
127
|
['/panel', 'panel.html', 'text/html; charset=utf-8'],
|
|
91
128
|
['/panel.css', 'panel.css', 'text/css; charset=utf-8'],
|
|
129
|
+
['/reader.css', 'reader.css', 'text/css; charset=utf-8'],
|
|
130
|
+
['/inline-process.css', 'inline-process.css', 'text/css; charset=utf-8'],
|
|
92
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'],
|
|
93
135
|
['/project-context.js', 'project-context.js', 'text/javascript; charset=utf-8'],
|
|
94
136
|
['/markdown.js', 'markdown.js', 'text/javascript; charset=utf-8'],
|
|
95
137
|
['/vendor/markdown-it.mjs', 'vendor/markdown-it.mjs', 'text/javascript; charset=utf-8'],
|
|
@@ -126,6 +168,7 @@ export function apply(ctx) {
|
|
|
126
168
|
} catch (error) {
|
|
127
169
|
if (!res.headersSent) json(res, error.status || 500, {
|
|
128
170
|
error: error.status ? error.message : '无法读取本地资料。请检查 agent-bridge.json 和文件权限后刷新。',
|
|
171
|
+
...(isSessionId(error.recoveryTicket) ? { recoveryTicket: error.recoveryTicket } : {}),
|
|
129
172
|
})
|
|
130
173
|
}
|
|
131
174
|
},
|
|
@@ -144,17 +187,120 @@ export function apply(ctx) {
|
|
|
144
187
|
return
|
|
145
188
|
}
|
|
146
189
|
const input = await readBody(req)
|
|
147
|
-
const conversationAction = ['list-conversations', '
|
|
190
|
+
const conversationAction = ['list-conversations', 'search-conversations', 'conversation-import-status', 'preview-conversation',
|
|
191
|
+
'preview-conversation-context', 'retarget-failed-conversation', 'import-conversation'].includes(input.action)
|
|
148
192
|
const nativeSessionImport = (conversationAction || input.action === 'catalog') && Boolean(services())
|
|
149
193
|
if (conversationAction && !nativeSessionImport) {
|
|
150
194
|
json(res, 403, { error: '请在支持会话迁入的本机 DSH 主界面中使用。' })
|
|
151
195
|
return
|
|
152
196
|
}
|
|
153
|
-
const
|
|
197
|
+
const abort = new AbortController()
|
|
198
|
+
const cancel = () => abort.abort()
|
|
199
|
+
res.once('close', cancel)
|
|
200
|
+
let result
|
|
201
|
+
try {
|
|
202
|
+
result = input.action === 'conversation-history' && input.sessionId
|
|
203
|
+
? await archivePage(input.sessionId, input.cursor, input.turn)
|
|
204
|
+
: await catalog.execute(input.action, { ...input, signal: abort.signal })
|
|
205
|
+
} finally {
|
|
206
|
+
res.off('close', cancel)
|
|
207
|
+
}
|
|
154
208
|
json(res, 200, input.action === 'catalog' ? { ...result, agentIcons, nativeSessionImport } : result)
|
|
155
209
|
})
|
|
156
210
|
register('/session-trace', 'GET', async (req, res) => {
|
|
157
211
|
const sessionId = new URL(req.url ?? '/', 'http://localhost').searchParams.get('sessionId') ?? ''
|
|
158
212
|
json(res, 200, await loadSourceRecord(sessionId))
|
|
159
213
|
})
|
|
214
|
+
register('/conversation-history', 'GET', async (req, res) => {
|
|
215
|
+
const query = new URL(req.url ?? '/', 'http://localhost').searchParams
|
|
216
|
+
json(res, 200, await archivePage(query.get('sessionId'), query.get('cursor'), Number(query.get('turn'))))
|
|
217
|
+
})
|
|
218
|
+
register('/conversation-process', 'GET', async (req, res) => {
|
|
219
|
+
const query = new URL(req.url ?? '/', 'http://localhost').searchParams
|
|
220
|
+
const { config, stored } = await loadArchive(query.get('sessionId'))
|
|
221
|
+
if (stored.history.nativeTimeline) {
|
|
222
|
+
json(res, 200, query.has('turn') ? { items: [], nextCursor: null } : { placements: [] })
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
if (query.has('turn')) {
|
|
226
|
+
const turn = Number(query.get('turn'))
|
|
227
|
+
const after = query.has('after') ? Number(query.get('after')) : 0
|
|
228
|
+
const before = query.has('before') ? Number(query.get('before')) : Number.MAX_SAFE_INTEGER
|
|
229
|
+
if (!Number.isSafeInteger(turn) || turn < 1
|
|
230
|
+
|| !Number.isSafeInteger(after) || !Number.isSafeInteger(before) || after < 0 || before <= after) {
|
|
231
|
+
throw Object.assign(new Error('回合号无效。'), { status: 400 })
|
|
232
|
+
}
|
|
233
|
+
const { items, nextCursor } = await readHistoryPage(config, stored.id, query.get('cursor'), turn,
|
|
234
|
+
{ processOnly: true, after, before })
|
|
235
|
+
json(res, 200, { items, nextCursor })
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
const placements = await readProcessPlacements(config, stored, nativeSessionEvents(stored.messages, stored.title))
|
|
239
|
+
json(res, 200, { placements })
|
|
240
|
+
})
|
|
241
|
+
register('/conversation-attachment', 'GET', async (req, res) => {
|
|
242
|
+
const query = new URL(req.url ?? '/', 'http://localhost').searchParams
|
|
243
|
+
const sessionId = query.get('sessionId')
|
|
244
|
+
const snapshotId = query.get('snapshotId')
|
|
245
|
+
if ((sessionId === null) === (snapshotId === null) || (snapshotId !== null && !isSessionId(snapshotId))) {
|
|
246
|
+
throw Object.assign(new Error('附件会话标识无效。'), { status: 400 })
|
|
247
|
+
}
|
|
248
|
+
const position = query.get('seq')
|
|
249
|
+
const seq = position === null ? undefined : Number(position)
|
|
250
|
+
if (position !== null && (!/^\d+$/.test(position) || !Number.isSafeInteger(seq) || seq < 1)) {
|
|
251
|
+
throw Object.assign(new Error('附件记录位置无效。'), { status: 400 })
|
|
252
|
+
}
|
|
253
|
+
const archive = sessionId !== null ? await loadArchive(sessionId) : undefined
|
|
254
|
+
const config = archive?.config ?? await loadConfig()
|
|
255
|
+
const attachmentId = query.get('attachmentId')
|
|
256
|
+
const attachment = await readHistoryAttachment(config, archive?.stored.id ?? snapshotId, attachmentId,
|
|
257
|
+
{ seq, preview: snapshotId !== null })
|
|
258
|
+
if (!attachment) throw Object.assign(new Error('没有找到可读取的附件快照。'), { status: 404 })
|
|
259
|
+
const inline = query.get('inline') === 'true' && attachment.mediaType.startsWith('image/')
|
|
260
|
+
const extension = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif' }[attachment.mediaType] ?? 'bin'
|
|
261
|
+
res.writeHead(200, { ...pageHeaders, 'Content-Type': attachment.mediaType,
|
|
262
|
+
'Content-Disposition': attachmentDisposition(attachment.name, `${attachmentId.slice(0, 12)}.${extension}`, inline) })
|
|
263
|
+
res.end(attachment.bytes)
|
|
264
|
+
})
|
|
265
|
+
async function streamConversationMarkdown(query, res, format) {
|
|
266
|
+
const { config, stored } = await loadArchive(query.get('sessionId'))
|
|
267
|
+
async function* pages() {
|
|
268
|
+
let cursor
|
|
269
|
+
do {
|
|
270
|
+
const page = await readHistoryPage(config, stored.id, cursor)
|
|
271
|
+
if (res.destroyed) return
|
|
272
|
+
if (!page) throw new Error('The source archive is no longer available')
|
|
273
|
+
yield page
|
|
274
|
+
cursor = page.nextCursor
|
|
275
|
+
} while (cursor)
|
|
276
|
+
}
|
|
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"' })
|
|
281
|
+
try {
|
|
282
|
+
const signal = new AbortController()
|
|
283
|
+
res.once('close', () => signal.abort())
|
|
284
|
+
for await (const chunk of sourceHistoryMarkdown(stored, pages(), {
|
|
285
|
+
format, includeTrace: query.get('includeTrace') === 'true',
|
|
286
|
+
})) {
|
|
287
|
+
if (res.destroyed) return
|
|
288
|
+
if (chunk && !res.write(chunk)) await once(res, 'drain', { signal: signal.signal })
|
|
289
|
+
}
|
|
290
|
+
res.end()
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (!res.destroyed) res.destroy(error)
|
|
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')
|
|
305
|
+
})
|
|
160
306
|
}
|