@wwwfz/dsh-agent-bridge 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -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 loadSourceRecord(sessionId) {
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
- const saved = await readSessionTrace(await loadConfig(), sessionId)
73
- if (!saved?.trace?.length && !saved?.sourceStats) {
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.trace) }
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) {
@@ -89,6 +120,8 @@ export function apply(ctx) {
89
120
  const staticRoutes = [
90
121
  ['/panel', 'panel.html', 'text/html; charset=utf-8'],
91
122
  ['/panel.css', 'panel.css', 'text/css; charset=utf-8'],
123
+ ['/reader.css', 'reader.css', 'text/css; charset=utf-8'],
124
+ ['/inline-process.css', 'inline-process.css', 'text/css; charset=utf-8'],
92
125
  ['/panel.js', 'panel.js', 'text/javascript; charset=utf-8'],
93
126
  ['/project-context.js', 'project-context.js', 'text/javascript; charset=utf-8'],
94
127
  ['/markdown.js', 'markdown.js', 'text/javascript; charset=utf-8'],
@@ -150,11 +183,100 @@ export function apply(ctx) {
150
183
  json(res, 403, { error: '请在支持会话迁入的本机 DSH 主界面中使用。' })
151
184
  return
152
185
  }
153
- const result = await catalog.execute(input.action, input)
186
+ const abort = new AbortController()
187
+ const cancel = () => abort.abort()
188
+ res.once('close', cancel)
189
+ let result
190
+ try {
191
+ result = input.action === 'conversation-history' && input.sessionId
192
+ ? await archivePage(input.sessionId, input.cursor, input.turn)
193
+ : await catalog.execute(input.action, { ...input, signal: abort.signal })
194
+ } finally {
195
+ res.off('close', cancel)
196
+ }
154
197
  json(res, 200, input.action === 'catalog' ? { ...result, agentIcons, nativeSessionImport } : result)
155
198
  })
156
199
  register('/session-trace', 'GET', async (req, res) => {
157
200
  const sessionId = new URL(req.url ?? '/', 'http://localhost').searchParams.get('sessionId') ?? ''
158
201
  json(res, 200, await loadSourceRecord(sessionId))
159
202
  })
203
+ register('/conversation-history', 'GET', async (req, res) => {
204
+ const query = new URL(req.url ?? '/', 'http://localhost').searchParams
205
+ json(res, 200, await archivePage(query.get('sessionId'), query.get('cursor'), Number(query.get('turn'))))
206
+ })
207
+ register('/conversation-process', 'GET', async (req, res) => {
208
+ const query = new URL(req.url ?? '/', 'http://localhost').searchParams
209
+ const { config, stored } = await loadArchive(query.get('sessionId'))
210
+ if (stored.history.nativeTimeline) {
211
+ json(res, 200, query.has('turn') ? { items: [], nextCursor: null } : { placements: [] })
212
+ return
213
+ }
214
+ if (query.has('turn')) {
215
+ const turn = Number(query.get('turn'))
216
+ const after = query.has('after') ? Number(query.get('after')) : 0
217
+ const before = query.has('before') ? Number(query.get('before')) : Number.MAX_SAFE_INTEGER
218
+ if (!Number.isSafeInteger(turn) || turn < 1
219
+ || !Number.isSafeInteger(after) || !Number.isSafeInteger(before) || after < 0 || before <= after) {
220
+ throw Object.assign(new Error('回合号无效。'), { status: 400 })
221
+ }
222
+ const { items, nextCursor } = await readHistoryPage(config, stored.id, query.get('cursor'), turn,
223
+ { processOnly: true, after, before })
224
+ json(res, 200, { items, nextCursor })
225
+ return
226
+ }
227
+ const placements = await readProcessPlacements(config, stored, nativeSessionEvents(stored.messages, stored.title))
228
+ json(res, 200, { placements })
229
+ })
230
+ register('/conversation-attachment', 'GET', async (req, res) => {
231
+ const query = new URL(req.url ?? '/', 'http://localhost').searchParams
232
+ const sessionId = query.get('sessionId')
233
+ const snapshotId = query.get('snapshotId')
234
+ if ((sessionId === null) === (snapshotId === null) || (snapshotId !== null && !isSessionId(snapshotId))) {
235
+ throw Object.assign(new Error('附件会话标识无效。'), { status: 400 })
236
+ }
237
+ const position = query.get('seq')
238
+ const seq = position === null ? undefined : Number(position)
239
+ if (position !== null && (!/^\d+$/.test(position) || !Number.isSafeInteger(seq) || seq < 1)) {
240
+ throw Object.assign(new Error('附件记录位置无效。'), { status: 400 })
241
+ }
242
+ const archive = sessionId !== null ? await loadArchive(sessionId) : undefined
243
+ const config = archive?.config ?? await loadConfig()
244
+ const attachmentId = query.get('attachmentId')
245
+ const attachment = await readHistoryAttachment(config, archive?.stored.id ?? snapshotId, attachmentId,
246
+ { seq, preview: snapshotId !== null })
247
+ if (!attachment) throw Object.assign(new Error('没有找到可读取的附件快照。'), { status: 404 })
248
+ const inline = query.get('inline') === 'true' && attachment.mediaType.startsWith('image/')
249
+ const extension = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif' }[attachment.mediaType] ?? 'bin'
250
+ res.writeHead(200, { ...pageHeaders, 'Content-Type': attachment.mediaType,
251
+ 'Content-Disposition': attachmentDisposition(attachment.name, `${attachmentId.slice(0, 12)}.${extension}`, inline) })
252
+ res.end(attachment.bytes)
253
+ })
254
+ register('/conversation-export', 'GET', async (req, res) => {
255
+ const query = new URL(req.url ?? '/', 'http://localhost').searchParams
256
+ const { config, stored } = await loadArchive(query.get('sessionId'))
257
+ async function* pages() {
258
+ let cursor
259
+ do {
260
+ const page = await readHistoryPage(config, stored.id, cursor)
261
+ if (!page || res.destroyed) return
262
+ yield page
263
+ cursor = page.nextCursor
264
+ } while (cursor)
265
+ }
266
+ res.writeHead(200, { ...pageHeaders, 'Content-Type': 'text/markdown; charset=utf-8',
267
+ 'Content-Disposition': 'attachment; filename="agent-conversation.md"' })
268
+ try {
269
+ const signal = new AbortController()
270
+ res.once('close', () => signal.abort())
271
+ for await (const chunk of sourceHistoryMarkdown(stored, pages(), {
272
+ format: query.get('format'), includeTrace: query.get('includeTrace') === 'true',
273
+ })) {
274
+ if (res.destroyed) return
275
+ if (chunk && !res.write(chunk)) await once(res, 'drain', { signal: signal.signal })
276
+ }
277
+ res.end()
278
+ } catch (error) {
279
+ if (!res.destroyed) res.destroy(error)
280
+ }
281
+ })
160
282
  }
@@ -0,0 +1,217 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { readHistoryAttachment, readNativeTurns } from './conversation-store.js'
3
+
4
+ const modelSource = { kind: 'model', provider: 'agent-bridge-import', model: 'imported' }
5
+ const systemSource = { kind: 'system-prompt' }
6
+ const textBlock = text => ({ type: 'text', text })
7
+ const message = (role, content, source) => ({ id: randomUUID(), role, content, source })
8
+
9
+ async function attachmentBlock(record, item, attachments, { file = false } = {}) {
10
+ if (item.attachmentId && attachments) {
11
+ const saved = await readHistoryAttachment(record.config, record.id, item.attachmentId, { seq: item.seq, preview: true })
12
+ if (saved) {
13
+ const { bytes: data, mediaType, name } = saved
14
+ try {
15
+ if (mediaType.startsWith('image/') && attachments.saveImage) {
16
+ return { type: 'image', attachment: await attachments.saveImage({ data, mediaType, name }) }
17
+ }
18
+ if (file && attachments.saveFile) return { type: 'file', attachment: await attachments.saveFile({ data, name }) }
19
+ } catch { /* The exact bytes remain available in the source archive. */ }
20
+ }
21
+ }
22
+ const name = item.name.replace(/[\\`*_[\]<>]/g, '\\$&')
23
+ const status = item.status === 'saved' ? '原件见来源记录' : item.status === 'name-only' ? '仅保留文件名' : '原件不可用'
24
+ return textBlock(`附件:${name}(${status})`)
25
+ }
26
+
27
+ export async function nativeTranscriptEvents(record, attachments, now = Date.now()) {
28
+ const events = []
29
+ const usedCallIds = new Set()
30
+ let time
31
+ let turn = 0
32
+ let step = 0
33
+ let nativeMessages = 0
34
+ let contextMessages = 0
35
+ let nativeFirstTurn
36
+ let nativeLastTurn
37
+ let excluded = []
38
+ const at = value => { time = Math.max(time ?? value ?? now, value ?? 0) }
39
+ const add = (type, data, surface) => {
40
+ const seq = events.length
41
+ events.push({ seq, time, type, data, ...surface })
42
+ return seq
43
+ }
44
+ const system = () => ({ turn, step, message: message('system', [], systemSource) })
45
+ const leaveInHistory = () => {
46
+ if (!excluded.length) return
47
+ // Native surface replacement keeps the original events available to Chat
48
+ // and Trajectory while an empty system node contributes no request message.
49
+ add('system/message', system(), {
50
+ surfaceOp: { op: 'replace', startSeq: excluded[0], endSeq: excluded.at(-1) },
51
+ sourceEventSeqs: excluded,
52
+ })
53
+ excluded = []
54
+ }
55
+ const append = (type, data, retain, sourceEventSeqs) => {
56
+ if (retain) leaveInHistory()
57
+ const seq = add(type, data, { surfaceOp: 'append', ...(sourceEventSeqs && { sourceEventSeqs }) })
58
+ if (!retain) excluded.push(seq)
59
+ return seq
60
+ }
61
+ const openStep = () => add('step/start', { turn, step: ++step })
62
+ const closeStep = () => add('step/end', { turn, step })
63
+
64
+ for await (const { entries, initialTime } of readNativeTurns(record.config, record)) {
65
+ const questions = new Map()
66
+ let currentQuestion
67
+ for (const item of entries) {
68
+ if (item.role !== 'user') continue
69
+ if (item.kind === 'message' || (item.kind === 'attachment' && (item.standalone || !currentQuestion))) {
70
+ currentQuestion = item
71
+ questions.set(item.seq, [])
72
+ }
73
+ if (item.kind === 'attachment') questions.get(currentQuestion.seq).push(item)
74
+ }
75
+ const question = entries.find(item => questions.has(item.seq))
76
+ if (!question) continue
77
+ nativeFirstTurn ??= question.turn
78
+ nativeLastTurn = question.turn
79
+ const results = new Map()
80
+ const resultAttachments = new Map()
81
+ for (const item of entries) {
82
+ if (!item.callKey) continue
83
+ const target = item.kind === 'tool_result' ? results : item.kind === 'attachment' ? resultAttachments : undefined
84
+ if (!target) continue
85
+ if (!target.has(item.callKey)) target.set(item.callKey, [])
86
+ target.get(item.callKey).push(item)
87
+ }
88
+
89
+ time ??= initialTime
90
+ at(question.time)
91
+ add('turn/start', { turn: ++turn })
92
+ step = 0
93
+ openStep()
94
+ if (turn === 1) add('system/message', system(), { surfaceOp: 'append' })
95
+ let needsStep = false
96
+ let replied = false
97
+ let reasoning = []
98
+ let calls = []
99
+ const writeQuestion = async item => {
100
+ if (needsStep) {
101
+ openStep()
102
+ needsStep = false
103
+ }
104
+ at(item.time)
105
+ replied = false
106
+ const files = questions.get(item.seq)
107
+ const content = item.kind === 'message' ? [textBlock(item.text)] : []
108
+ if (item.kind === 'message') nativeMessages++
109
+ for (const file of files) {
110
+ const block = await attachmentBlock(record, file, attachments, { file: true })
111
+ if (block.type === 'text' && content.length) block.text = '\n\n' + block.text
112
+ content.push(block)
113
+ }
114
+ const hasContext = item.contextText !== undefined
115
+ if (hasContext) contextMessages++
116
+ const userSeq = append('user/message', message('user', content, { kind: 'user' }), hasContext)
117
+ if (hasContext && (item.text !== item.contextText || files.length)) {
118
+ add('user/message', message('user', [textBlock(item.contextText)], { kind: 'agent-bridge-context' }), {
119
+ surfaceOp: { op: 'replace', startSeq: userSeq, endSeq: userSeq },
120
+ sourceEventSeqs: [userSeq],
121
+ })
122
+ }
123
+ leaveInHistory()
124
+ }
125
+ const flush = async (reply, followingSeq) => {
126
+ if (!reply && !reasoning.length && !calls.length) return
127
+ if (needsStep) openStep()
128
+ const content = reasoning.map(item => ({ type: 'reasoning', text: item.text }))
129
+ if (reply) content.push(reply.kind === 'attachment' ? await attachmentBlock(record, reply, attachments) : textBlock(reply.text))
130
+ for (const item of calls) content.push(item.block)
131
+ at(reply?.time ?? reasoning.at(-1)?.time ?? calls[0]?.time)
132
+ const keepReply = reply?.kind === 'message' && !reasoning.length && !calls.length && reply.contextText !== undefined
133
+ const needsPrefix = keepReply && reply.text !== reply.contextText
134
+ if (reply?.kind === 'message') nativeMessages++
135
+ if (keepReply) contextMessages++
136
+ if (needsPrefix) {
137
+ // The host settles Chat and Trajectory from the last assistant message
138
+ // of the step. Keep the reviewed prefix on the model surface and the
139
+ // final, full settlement in the timeline.
140
+ append('assistant/message', {
141
+ turn, step, stream: [], message: message('assistant', [textBlock(reply.contextText)], modelSource),
142
+ }, true)
143
+ }
144
+ append('assistant/message', {
145
+ turn, step, stream: [], message: message('assistant', content, modelSource),
146
+ }, keepReply && !needsPrefix)
147
+
148
+ const settled = []
149
+ for (const { entry, block } of calls) {
150
+ at(entry.time)
151
+ const callSeq = add('tool/call', {
152
+ turn, step, callId: block.id, name: block.name, arguments: block.arguments,
153
+ })
154
+ const output = results.get(entry.callKey)
155
+ if (output?.length) settled.push({ block, output, files: resultAttachments.get(entry.callKey) ?? [], callSeq })
156
+ }
157
+ settled.sort((a, b) => a.output[0].seq - b.output[0].seq)
158
+ for (const { block, output, files, callSeq } of settled) {
159
+ const last = output.at(-1)
160
+ // A late result annotates the original call. Its source timestamp
161
+ // remains in the archive and must not move subsequent replies forward.
162
+ if (last.seq < followingSeq) at(last.time)
163
+ const isError = ['error', 'incomplete'].includes(last.status)
164
+ const outputBlocks = output.flatMap((item, index) => index
165
+ ? [textBlock('\n\n---\n\n'), textBlock(item.text ?? '')]
166
+ : [textBlock(item.text ?? '')])
167
+ for (const item of files) outputBlocks.push(await attachmentBlock(record, item, attachments))
168
+ append('tool/result', {
169
+ turn, step,
170
+ message: {
171
+ ...message('tool', outputBlocks, { kind: 'tool', callId: block.id }),
172
+ toolCallId: block.id, isError,
173
+ },
174
+ }, false, [callSeq])
175
+ }
176
+ leaveInHistory()
177
+ closeStep()
178
+ needsStep = true
179
+ reasoning = []
180
+ calls = []
181
+ }
182
+
183
+ for (const item of entries) {
184
+ if (item.seq < question.seq) continue
185
+ if (questions.has(item.seq)) {
186
+ await flush(undefined, item.seq)
187
+ await writeQuestion(item)
188
+ } else if (item.kind === 'summary' && item.text?.trim()) {
189
+ if (calls.length) await flush(undefined, item.seq)
190
+ reasoning.push(item)
191
+ } else if (item.kind === 'tool_call' && item.name) {
192
+ let id = item.callId || `bridge-${item.seq}`
193
+ if (usedCallIds.has(id)) id = randomUUID()
194
+ usedCallIds.add(id)
195
+ calls.push({ entry: item, block: { type: 'tool-call', id, name: item.name, arguments: item.text || '{}' } })
196
+ } else if (item.kind === 'message' && item.role === 'assistant') {
197
+ await flush(undefined, item.seq)
198
+ await flush(item)
199
+ replied = true
200
+ } else if (item.kind === 'attachment' && item.role === 'assistant' && !item.callKey) {
201
+ await flush(undefined, item.seq)
202
+ await flush(item)
203
+ replied = true
204
+ }
205
+ }
206
+ await flush(undefined, 0)
207
+ if (!needsStep) closeStep()
208
+ const ending = entries.findLast(item => item.kind === 'turn_end')
209
+ // DSH uses "interrupted" specifically for recovery after its own crash.
210
+ const completed = ending ? ending.status === 'completed' : replied
211
+ add('turn/end', { turn, reason: completed ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'legacy' } } })
212
+ }
213
+
214
+ if (!turn) throw new Error('The approved source archive has no importable turns')
215
+ add('session/title', { title: record.title, messageSeqs: [], source: { kind: 'user' } })
216
+ return { events, nativeTimeline: { nativeMessages, nativeFirstTurn, nativeLastTurn, contextMessages } }
217
+ }