@wwwfz/dsh-agent-bridge 0.8.3 → 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.
Files changed (45) hide show
  1. package/README.md +132 -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 +999 -605
  7. package/src/client.js +883 -4
  8. package/src/config.js +88 -88
  9. package/src/conversation-readers.js +198 -0
  10. package/src/conversation-store.js +583 -0
  11. package/src/export.js +273 -12
  12. package/src/index.js +282 -136
  13. package/src/native-transcript.js +217 -0
  14. package/src/project-archive.js +145 -145
  15. package/src/projects.js +1837 -980
  16. package/src/session-import.js +138 -93
  17. package/src/session-trace.js +121 -0
  18. package/src/skill-handoff.js +1327 -0
  19. package/src/skill-package.js +417 -0
  20. package/src/skill-provider.js +249 -0
  21. package/src/watch.js +319 -309
  22. package/web/Geist-OFL.txt +93 -93
  23. package/web/agent-icons/NOTICE.md +19 -19
  24. package/web/agent-icons/antigravity.svg +76 -76
  25. package/web/agent-icons/claude.svg +3 -3
  26. package/web/agent-icons/dsh.svg +58 -58
  27. package/web/agent-icons/licenses/copilot.txt +21 -21
  28. package/web/agent-icons/licenses/dsh.txt +21 -21
  29. package/web/agent-icons/licenses/gemini.txt +201 -201
  30. package/web/agent-icons/licenses/opencode.txt +21 -21
  31. package/web/agent-icons/licenses/qoder-notice.txt +18 -18
  32. package/web/agent-icons/licenses/qoder.txt +22 -22
  33. package/web/agent-icons/licenses/qwen.txt +202 -202
  34. package/web/agent-icons/qoder.svg +4 -4
  35. package/web/agent-icons/qwen.svg +5 -5
  36. package/web/agent-icons/workbuddy.svg +29 -29
  37. package/web/inline-process.css +22 -0
  38. package/web/markdown.js +225 -0
  39. package/web/panel.css +168 -151
  40. package/web/panel.html +82 -43
  41. package/web/panel.js +1316 -93
  42. package/web/project-context.js +25 -25
  43. package/web/reader.css +259 -0
  44. package/web/vendor/markdown-it-LICENSE.txt +156 -0
  45. package/web/vendor/markdown-it.mjs +3064 -0
package/src/index.js CHANGED
@@ -1,136 +1,282 @@
1
- import { randomBytes } from 'node:crypto'
2
- import { existsSync, readdirSync } from 'node:fs'
3
- import { readFile } from 'node:fs/promises'
4
- import { createCatalog } from './catalog.js'
5
- import { loadConfig } from './config.js'
6
- import { nativeSessionServices, saveNativeSession } from './session-import.js'
7
-
8
- export const name = 'dsh-agent-bridge'
9
- export const inject = {
10
- connection: true, webServer: true,
11
- sessions: false, sessionPersistence: false, workspaceRegistry: false, sessionProjectionCache: false,
12
- }
13
-
14
- const prefix = '/agent-bridge'
15
- const pageHeaders = {
16
- 'Cache-Control': 'no-store',
17
- 'Referrer-Policy': 'no-referrer',
18
- 'X-Content-Type-Options': 'nosniff',
19
- 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'",
20
- }
21
-
22
- function respond(res, status, type, value) {
23
- res.writeHead(status, { ...pageHeaders, 'Content-Type': type })
24
- res.end(value)
25
- }
26
-
27
- function json(res, status, data) {
28
- respond(res, status, 'application/json; charset=utf-8', JSON.stringify(data))
29
- }
30
-
31
- function isLoopback(address) {
32
- return typeof address === 'string' && (address === '::1' || /^(?:::ffff:)?127(?:\.\d{1,3}){3}$/.test(address))
33
- }
34
-
35
- async function readBody(req) {
36
- const chunks = []
37
- let bytes = 0
38
- for await (const chunk of req.iterator({ destroyOnReturn: false })) {
39
- bytes += chunk.length
40
- if (bytes > 192 * 1024) {
41
- const error = new Error('请求过大。')
42
- error.status = 413
43
- // Drain without buffering, so the client can receive a normal error response.
44
- req.resume()
45
- throw error
46
- }
47
- chunks.push(chunk)
48
- }
49
- try {
50
- const data = JSON.parse(Buffer.concat(chunks).toString('utf8'))
51
- if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error()
52
- return data
53
- } catch {
54
- const error = new Error('请求格式无效。')
55
- error.status = 400
56
- throw error
57
- }
58
- }
59
-
60
- export function apply(ctx) {
61
- const services = () => nativeSessionServices(ctx)
62
- const catalog = createCatalog(loadConfig, {
63
- importConversation(record, cwd) {
64
- const host = services()
65
- if (!host) throw Object.assign(new Error('当前 DSH 未提供会话迁入服务。'), { status: 409 })
66
- return saveNativeSession(host, record, cwd)
67
- },
68
- })
69
- ctx.effect(() => () => catalog.dispose())
70
- const nonce = randomBytes(32).toString('hex')
71
- const staticRoutes = [
72
- ['/panel', 'panel.html', 'text/html; charset=utf-8'],
73
- ['/panel.css', 'panel.css', 'text/css; charset=utf-8'],
74
- ['/panel.js', 'panel.js', 'text/javascript; charset=utf-8'],
75
- ['/project-context.js', 'project-context.js', 'text/javascript; charset=utf-8'],
76
- ['/geist-latin-wght-normal.woff2', 'geist-latin-wght-normal.woff2', 'font/woff2'],
77
- ]
78
- const agentIcons = Object.create(null)
79
- const iconsDirectory = new URL('../web/agent-icons/', import.meta.url)
80
- if (existsSync(iconsDirectory)) {
81
- for (const entry of readdirSync(iconsDirectory, { withFileTypes: true })) {
82
- const match = /^([a-z][a-z0-9-]*)\.(svg|png)$/.exec(entry.name)
83
- if (!entry.isFile() || !match) continue
84
- const [, agent, extension] = match
85
- const file = `agent-icons/${entry.name}`
86
- agentIcons[agent] = file
87
- staticRoutes.push([`/${file}`, file, extension === 'svg' ? 'image/svg+xml' : 'image/png'])
88
- }
89
- }
90
- function register(path, method, action) {
91
- ctx.effect(() => ctx.webServer.register({
92
- kind: 'exact', path: prefix + path,
93
- async handler(req, res) {
94
- if (!isLoopback(req.socket.remoteAddress)
95
- || ctx.connection.admit?.(req)?.peer?.principal?.kind !== 'owner') {
96
- json(res, 403, { error: '请使用本机 DSH 所有者身份打开 Agent 接续。' })
97
- return
98
- }
99
- if (req.method !== method) {
100
- res.setHeader('Allow', method)
101
- json(res, 405, { error: '请求方法不受支持。' })
102
- return
103
- }
104
- try {
105
- await action(req, res)
106
- } catch (error) {
107
- if (!res.headersSent) json(res, error.status || 500, {
108
- error: error.status ? error.message : '无法读取本地资料。请检查 agent-bridge.json 和文件权限后刷新。',
109
- })
110
- }
111
- },
112
- }))
113
- }
114
- for (const [path, file, type] of staticRoutes) {
115
- register(path, 'GET', async (_req, res) => {
116
- const body = await readFile(new URL(`../web/${file}`, import.meta.url))
117
- respond(res, 200, type, file === 'panel.html' ? body.toString('utf8').replace('__DSH_BRIDGE_NONCE__', nonce) : body)
118
- })
119
- }
120
- register('/api', 'POST', async (req, res) => {
121
- if (req.headers['x-dsh-agent-bridge'] !== nonce
122
- || !/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] ?? '')) {
123
- json(res, 403, { error: '面板已过期。重新打开 Agent 接续后重试。' })
124
- return
125
- }
126
- const input = await readBody(req)
127
- const conversationAction = ['list-conversations', 'preview-conversation', 'import-conversation'].includes(input.action)
128
- const nativeSessionImport = (conversationAction || input.action === 'catalog') && Boolean(services())
129
- if (conversationAction && !nativeSessionImport) {
130
- json(res, 403, { error: '请在支持会话迁入的本机 DSH 主界面中使用。' })
131
- return
132
- }
133
- const result = await catalog.execute(input.action, input)
134
- json(res, 200, input.action === 'catalog' ? { ...result, agentIcons, nativeSessionImport } : result)
135
- })
136
- }
1
+ import { randomBytes } from 'node:crypto'
2
+ import { once } from 'node:events'
3
+ import { existsSync, readdirSync } from 'node:fs'
4
+ import { readFile } from 'node:fs/promises'
5
+ import { createCatalog } from './catalog.js'
6
+ import { loadConfig } from './config.js'
7
+ import { nativeSessionEvents, nativeSessionServices, saveNativeSession } from './session-import.js'
8
+ import { countTrace, isSessionId, readSessionTrace } from './session-trace.js'
9
+ import { createSkillBridge } from './skill-provider.js'
10
+ import { readHistoryAttachment, readHistoryPage, readProcessPlacements, readStoredConversation } from './conversation-store.js'
11
+ import { sourceHistoryMarkdown } from './export.js'
12
+
13
+ export const name = 'dsh-agent-bridge'
14
+ export const inject = {
15
+ connection: true, webServer: true,
16
+ sessions: false, sessionPersistence: false, workspaceRegistry: false, sessionProjectionCache: false,
17
+ attachments: false,
18
+ skills: false,
19
+ }
20
+
21
+ const prefix = '/agent-bridge'
22
+ const pageHeaders = {
23
+ 'Cache-Control': 'no-store',
24
+ 'Referrer-Policy': 'no-referrer',
25
+ 'X-Content-Type-Options': 'nosniff',
26
+ 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'",
27
+ }
28
+
29
+ function respond(res, status, type, value) {
30
+ res.writeHead(status, { ...pageHeaders, 'Content-Type': type })
31
+ res.end(value)
32
+ }
33
+
34
+ function json(res, status, data) {
35
+ respond(res, status, 'application/json; charset=utf-8', JSON.stringify(data))
36
+ }
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
+
48
+ function isLoopback(address) {
49
+ return typeof address === 'string' && (address === '::1' || /^(?:::ffff:)?127(?:\.\d{1,3}){3}$/.test(address))
50
+ }
51
+
52
+ async function readBody(req) {
53
+ const chunks = []
54
+ let bytes = 0
55
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
56
+ bytes += chunk.length
57
+ if (bytes > 192 * 1024) {
58
+ const error = new Error('请求过大。')
59
+ error.status = 413
60
+ // Drain without buffering, so the client can receive a normal error response.
61
+ req.resume()
62
+ throw error
63
+ }
64
+ chunks.push(chunk)
65
+ }
66
+ try {
67
+ const data = JSON.parse(Buffer.concat(chunks).toString('utf8'))
68
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error()
69
+ return data
70
+ } catch {
71
+ const error = new Error('请求格式无效。')
72
+ error.status = 400
73
+ throw error
74
+ }
75
+ }
76
+
77
+ export function apply(ctx) {
78
+ const services = () => nativeSessionServices(ctx)
79
+ const skillHandoff = ctx.get?.('skills') ? createSkillBridge(ctx) : undefined
80
+ async function verifyStoredSession(sessionId) {
81
+ if (!isSessionId(sessionId)) throw Object.assign(new Error('会话标识无效。'), { status: 400 })
82
+ const session = await ctx.get?.('sessionPersistence')?.stat?.(sessionId)
83
+ if (session?.header?.id !== sessionId) {
84
+ throw Object.assign(new Error('找不到这条 DSH 会话。'), { status: 404 })
85
+ }
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) {
100
+ throw Object.assign(new Error('没有为这条会话保存来源记录。'), { status: 404 })
101
+ }
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)
108
+ }
109
+ const catalog = createCatalog(loadConfig, {
110
+ importConversation(record, cwd) {
111
+ const host = services()
112
+ if (!host) throw Object.assign(new Error('当前 DSH 未提供会话迁入服务。'), { status: 409 })
113
+ return saveNativeSession(host, record, cwd)
114
+ },
115
+ skillHandoff,
116
+ loadSourceRecord,
117
+ })
118
+ ctx.effect(() => () => catalog.dispose())
119
+ const nonce = randomBytes(32).toString('hex')
120
+ const staticRoutes = [
121
+ ['/panel', 'panel.html', 'text/html; charset=utf-8'],
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'],
125
+ ['/panel.js', 'panel.js', 'text/javascript; charset=utf-8'],
126
+ ['/project-context.js', 'project-context.js', 'text/javascript; charset=utf-8'],
127
+ ['/markdown.js', 'markdown.js', 'text/javascript; charset=utf-8'],
128
+ ['/vendor/markdown-it.mjs', 'vendor/markdown-it.mjs', 'text/javascript; charset=utf-8'],
129
+ ['/geist-latin-wght-normal.woff2', 'geist-latin-wght-normal.woff2', 'font/woff2'],
130
+ ]
131
+ const agentIcons = Object.create(null)
132
+ const iconsDirectory = new URL('../web/agent-icons/', import.meta.url)
133
+ if (existsSync(iconsDirectory)) {
134
+ for (const entry of readdirSync(iconsDirectory, { withFileTypes: true })) {
135
+ const match = /^([a-z][a-z0-9-]*)\.(svg|png)$/.exec(entry.name)
136
+ if (!entry.isFile() || !match) continue
137
+ const [, agent, extension] = match
138
+ const file = `agent-icons/${entry.name}`
139
+ agentIcons[agent] = file
140
+ staticRoutes.push([`/${file}`, file, extension === 'svg' ? 'image/svg+xml' : 'image/png'])
141
+ }
142
+ }
143
+ function register(path, method, action) {
144
+ ctx.effect(() => ctx.webServer.register({
145
+ kind: 'exact', path: prefix + path,
146
+ async handler(req, res) {
147
+ if (!isLoopback(req.socket.remoteAddress)
148
+ || ctx.connection.admit?.(req)?.peer?.principal?.kind !== 'owner') {
149
+ json(res, 403, { error: '请使用本机 DSH 所有者身份打开 Agent 接续。' })
150
+ return
151
+ }
152
+ if (req.method !== method) {
153
+ res.setHeader('Allow', method)
154
+ json(res, 405, { error: '请求方法不受支持。' })
155
+ return
156
+ }
157
+ try {
158
+ await action(req, res)
159
+ } catch (error) {
160
+ if (!res.headersSent) json(res, error.status || 500, {
161
+ error: error.status ? error.message : '无法读取本地资料。请检查 agent-bridge.json 和文件权限后刷新。',
162
+ })
163
+ }
164
+ },
165
+ }))
166
+ }
167
+ for (const [path, file, type] of staticRoutes) {
168
+ register(path, 'GET', async (_req, res) => {
169
+ const body = await readFile(new URL(`../web/${file}`, import.meta.url))
170
+ respond(res, 200, type, file === 'panel.html' ? body.toString('utf8').replace('__DSH_BRIDGE_NONCE__', nonce) : body)
171
+ })
172
+ }
173
+ register('/api', 'POST', async (req, res) => {
174
+ if (req.headers['x-dsh-agent-bridge'] !== nonce
175
+ || !/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] ?? '')) {
176
+ json(res, 403, { error: '面板已过期。重新打开 Agent 接续后重试。' })
177
+ return
178
+ }
179
+ const input = await readBody(req)
180
+ const conversationAction = ['list-conversations', 'preview-conversation', 'import-conversation'].includes(input.action)
181
+ const nativeSessionImport = (conversationAction || input.action === 'catalog') && Boolean(services())
182
+ if (conversationAction && !nativeSessionImport) {
183
+ json(res, 403, { error: '请在支持会话迁入的本机 DSH 主界面中使用。' })
184
+ return
185
+ }
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
+ }
197
+ json(res, 200, input.action === 'catalog' ? { ...result, agentIcons, nativeSessionImport } : result)
198
+ })
199
+ register('/session-trace', 'GET', async (req, res) => {
200
+ const sessionId = new URL(req.url ?? '/', 'http://localhost').searchParams.get('sessionId') ?? ''
201
+ json(res, 200, await loadSourceRecord(sessionId))
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
+ })
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
+ }