@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.
@@ -1,6 +1,9 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import path from 'node:path'
3
+ import { isDeepStrictEqual } from 'node:util'
3
4
  import { saveSessionTrace } from './session-trace.js'
5
+ import { saveConversationSeed } from './conversation-store.js'
6
+ import { nativeTranscriptEvents } from './native-transcript.js'
4
7
 
5
8
  export function nativeSessionServices(ctx) {
6
9
  const sessions = ctx.get?.('sessions')
@@ -8,7 +11,7 @@ export function nativeSessionServices(ctx) {
8
11
  const workspaces = ctx.get?.('workspaceRegistry')
9
12
  const projectionCache = ctx.get?.('sessionProjectionCache')
10
13
  if (!sessions?.prepare || !persistence?.create || !workspaces?.create) return undefined
11
- return { sessions, persistence, workspaces, projectionCache }
14
+ return { sessions, persistence, workspaces, projectionCache, attachments: ctx.get?.('attachments') }
12
15
  }
13
16
 
14
17
  export function nativeSessionEvents(messages, title, now = Date.now()) {
@@ -21,9 +24,10 @@ export function nativeSessionEvents(messages, title, now = Date.now()) {
21
24
  let turn = 0
22
25
  let step = 0
23
26
  let replied = false
27
+ let endReason
24
28
  const finish = () => {
25
29
  add('step/end', { turn, step })
26
- add('turn/end', { turn, reason: { kind: replied ? 'completed' : 'interrupted' } })
30
+ add('turn/end', { turn, reason: { kind: endReason ?? (replied ? 'completed' : 'interrupted') } })
27
31
  }
28
32
  for (const entry of messages) {
29
33
  const content = [{ type: 'text', text: entry.text }]
@@ -33,6 +37,7 @@ export function nativeSessionEvents(messages, title, now = Date.now()) {
33
37
  turn++
34
38
  step = 1
35
39
  replied = false
40
+ endReason = entry.endReason
36
41
  add('turn/start', { turn })
37
42
  add('step/start', { turn, step })
38
43
  if (turn === 1) {
@@ -61,9 +66,60 @@ export function nativeSessionEvents(messages, title, now = Date.now()) {
61
66
  return events
62
67
  }
63
68
 
69
+ async function storeSeed(services, record, cwd, markHostWrite) {
70
+ const { sessions, persistence } = services
71
+ let seed = record.seed
72
+ if (!seed) {
73
+ if (record.history?.attachments && (services.attachments?.saveImage || services.attachments?.saveFile)) markHostWrite()
74
+ const { events, nativeTimeline } = record.id && record.config && record.history
75
+ ? await nativeTranscriptEvents(record, services.attachments)
76
+ : { events: nativeSessionEvents(record.messages, record.title) }
77
+ const prepared = sessions.prepare(record.sessionId, { seed: events, meta: { cwd, createdAt: events[0].time } })
78
+ if (prepared.header.version !== 4) {
79
+ throw Object.assign(new Error('当前 DSH 的会话格式暂不支持历史迁入。'), { status: 409 })
80
+ }
81
+ seed = { header: prepared.header, events, ...(nativeTimeline ? { nativeTimeline } : {}) }
82
+ if (record.id && record.config) seed = await saveConversationSeed(record.config, record.id, seed)
83
+ }
84
+ const { header, events } = seed
85
+ // A failed lookup or create can hide a partial log. From here on, retry the same ID.
86
+ markHostWrite()
87
+ const existing = await persistence.stat?.(record.sessionId)
88
+ const handle = existing ? await persistence.open(record.sessionId, 'write') : await persistence.create(header)
89
+ try {
90
+ let offset = 0
91
+ if (existing) {
92
+ const loaded = (await handle.read(0, events.length + 1)).events
93
+ if (handle.header.id !== header.id || handle.header.version !== header.version
94
+ || handle.header.cwd !== header.cwd || loaded.length > events.length
95
+ || !loaded.every((entry, index) => isDeepStrictEqual(JSON.parse(JSON.stringify(entry)), events[index]))) {
96
+ throw Object.assign(new Error('目标会话的已有内容与迁入凭据不一致。'), { status: 409 })
97
+ }
98
+ offset = loaded.length
99
+ }
100
+ if (offset < events.length) await handle.append(events.slice(offset))
101
+ await handle.flush()
102
+ return seed
103
+ } finally {
104
+ await handle.close()
105
+ }
106
+ }
107
+
64
108
  export async function saveNativeSession(services, record, cwd) {
65
- const { sessions, persistence, workspaces, projectionCache } = services
109
+ let unwritten = !record.stored && !record.traceStored
110
+ try {
111
+ return await writeNativeSession(services, record, cwd, () => { unwritten = false })
112
+ } catch (error) {
113
+ if (!unwritten) throw error
114
+ throw Object.assign(new Error(error.message, { cause: error }), { status: error.status, nativeSessionUnwritten: true })
115
+ }
116
+ }
117
+
118
+ async function writeNativeSession(services, record, cwd, markHostWrite) {
119
+ const { workspaces, projectionCache } = services
66
120
  const workspace = await workspaces.create(cwd)
121
+ const attached = workspace.sessionIds.includes(record.sessionId)
122
+ if (attached) markHostWrite()
67
123
  const normalize = value => {
68
124
  const normalized = path.normalize(value)
69
125
  return process.platform === 'win32' ? normalized.toLowerCase() : normalized
@@ -71,26 +127,16 @@ export async function saveNativeSession(services, record, cwd) {
71
127
  if (normalize(workspace.path) !== normalize(cwd)) {
72
128
  throw Object.assign(new Error('原工作目录已变化,请刷新项目。'), { status: 409 })
73
129
  }
74
- if (!record.stored) {
75
- const events = nativeSessionEvents(record.messages, record.title)
76
- const prepared = sessions.prepare(record.sessionId, { seed: events, meta: { cwd, createdAt: events[0].time } })
77
- if (prepared.header.version !== 4) {
78
- throw Object.assign(new Error('当前 DSH 的会话格式暂不支持历史迁入。'), { status: 409 })
79
- }
80
- const handle = await persistence.create(prepared.header)
81
- try {
82
- await handle.append(events)
83
- await handle.flush()
84
- record.stored = { header: prepared.header, events }
85
- } finally {
86
- await handle.close()
87
- }
88
- }
130
+ if (!attached && !record.stored) record.stored = await storeSeed(services, record, cwd, markHostWrite)
131
+ record.nativeTimeline = record.stored?.nativeTimeline ?? record.seed?.nativeTimeline
89
132
  // Save the reviewed source snapshot before attaching the new DSH session.
90
133
  const hasTrace = Array.isArray(record.trace) && record.trace.length > 0
91
134
  if (!record.traceStored && record.config && (hasTrace || record.sourceStats)) {
92
135
  try {
93
- const saved = await saveSessionTrace(record.config, record.sessionId, record.trace, record.sourceStats)
136
+ const sourceStats = record.sourceStats && record.nativeTimeline
137
+ ? { ...record.sourceStats, importedMessages: record.nativeTimeline.nativeMessages }
138
+ : record.sourceStats
139
+ const saved = await saveSessionTrace(record.config, record.sessionId, record.trace, sourceStats)
94
140
  record.traceStored = saved.saved === true
95
141
  } catch {
96
142
  throw Object.assign(
@@ -4,7 +4,7 @@ import path from 'node:path'
4
4
 
5
5
  const sessionIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
6
6
  const kinds = new Set(['summary', 'tool_call', 'tool_result'])
7
- const states = new Set(['ok', 'error', 'missing', 'pending', 'truncated'])
7
+ const states = new Set(['ok', 'error', 'missing', 'pending', 'truncated', 'incomplete'])
8
8
  const maxTraceItems = 200
9
9
  const maxTraceBytes = 96 * 1024
10
10
 
@@ -0,0 +1,287 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { realpath, stat } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { parseArgs } from 'node:util'
5
+ import { authorizeProjectReference, listProjectAssets, readAsset, verifyAssetSource, verifySourceAuthorization } from './assets.js'
6
+ import { loadConfig } from './config.js'
7
+ import { canReadConversation, conversationId, conversationIds, conversationTitle, makePrompt, mergeProjects, pathKey, redact } from './handoff.js'
8
+ import { dateMillis, readConversationHistory, scanProjects } from './projects.js'
9
+
10
+ const usage = `Agent Bridge · DSH
11
+
12
+ projects [--agent <来源>] [--query <关键词>] [--page <页码>] [--include-archived]
13
+ inspect [--project <目录>] [--agent <来源>] [--query <关键词>] [--page <页码>]
14
+ [--no-history] [--include-skills] [--include-global]
15
+ asset --asset <ID> [--include-skills] [--include-global]
16
+ history --session <ID> [--turn <回合>] [--cursor <位置>]
17
+ [--output <Markdown文件> [--format local|share] [--include-trace]]
18
+ attachment --session <ID> --attachment <ID> --output <文件>
19
+ skill-info --asset <Skill ID>
20
+ project-state --operation pin|unpin|archive|restore
21
+ handoff [--session <ID> | --no-history] [--asset <ID> ...]
22
+ [--include-skills] [--include-global] [--format prompt|local|share] [--output <文件>]
23
+
24
+ 项目操作默认使用当前目录。可以用 --project 指定项目和 --agent 限定来源。
25
+ `
26
+
27
+ const string = { type: 'string' }
28
+ const boolean = { type: 'boolean' }
29
+ const assets = { type: 'string', multiple: true, default: [] }
30
+ const inventoryOptions = { 'include-skills': boolean, 'include-global': boolean }
31
+ const commandOptions = {
32
+ projects: { query: string, page: string, 'include-archived': boolean },
33
+ inspect: { query: string, page: string, 'no-history': boolean, ...inventoryOptions },
34
+ asset: { asset: assets, page: string, ...inventoryOptions },
35
+ history: { session: string, turn: string, cursor: string, format: string, 'include-trace': boolean, output: string },
36
+ attachment: { session: string, attachment: string, output: string },
37
+ 'skill-info': { asset: assets, page: string },
38
+ 'project-state': { operation: string },
39
+ handoff: { session: string, asset: assets, 'no-history': boolean, format: string, output: string, ...inventoryOptions },
40
+ }
41
+
42
+ const json = value => JSON.stringify(value) + '\n'
43
+ const isId = value => /^[a-f0-9]{24}$/.test(value ?? '')
44
+ const fold = value => String(value ?? '').trim().normalize('NFKC').toLowerCase()
45
+
46
+ function positiveInteger(value, name) {
47
+ if (value === undefined) return
48
+ if (!/^[1-9]\d{0,7}$/.test(value)) throw new Error(`${name} 必须是正整数。`)
49
+ return Number(value)
50
+ }
51
+
52
+ function pageOf(items, page, size) {
53
+ const end = page * size
54
+ return { items: items.slice(end - size, end), more: items.length > end }
55
+ }
56
+
57
+ async function listProjects(config, matches, page, includeArchived) {
58
+ const { readProjectState } = await import('./project-archive.js')
59
+ const [{ projects, sources }, state] = await Promise.all([scanProjects(config), readProjectState(config)])
60
+ const choices = mergeProjects(projects).filter(project =>
61
+ (includeArchived || !state.archivedIds.has(project.id)) && matches(project.name, project.cwd, ...project.agents))
62
+ .sort((a, b) => Number(Boolean(state.preferences.get(b.id)?.pinned)) - Number(Boolean(state.preferences.get(a.id)?.pinned))
63
+ || String(b.updatedAt ?? '').localeCompare(a.updatedAt ?? '') || a.name.localeCompare(b.name, 'zh-CN'))
64
+ const selected = pageOf(choices, page, 20)
65
+ return json({
66
+ projects: await Promise.all(selected.items.map(async project => ({
67
+ id: project.id, cwd: project.cwd, name: redact(project.name), agents: project.agents, updatedAt: project.updatedAt,
68
+ online: (await stat(project.cwd).catch(() => undefined))?.isDirectory() ?? false,
69
+ archived: state.archivedIds.has(project.id), pinned: state.preferences.get(project.id)?.pinned === true,
70
+ }))),
71
+ page, moreProjects: selected.more, sources,
72
+ })
73
+ }
74
+
75
+ async function run(args) {
76
+ if (args.length === 1 && args[0] === '--help') return usage
77
+ const [action, ...flags] = args
78
+ if (!Object.hasOwn(commandOptions, action)) throw new Error('操作无效。使用 --help 查看用法。')
79
+ const { values } = parseArgs({
80
+ args: flags,
81
+ options: { agent: string, ...(action === 'projects' ? {} : { project: string }), ...commandOptions[action] },
82
+ })
83
+ const { project: requested, agent, query, session, asset: assetIds = [], output, cursor, attachment, operation } = values
84
+ const noHistory = values['no-history'] === true || ['asset', 'skill-info', 'project-state'].includes(action)
85
+ const includeSkills = values['include-skills'] === true || action === 'skill-info'
86
+ const includeGlobalMemory = values['include-global'] === true
87
+ const includeTrace = values['include-trace'] === true
88
+ const format = values.format ?? (output ? 'local' : 'prompt')
89
+ const page = positiveInteger(values.page, '页码') ?? 1
90
+ const turn = positiveInteger(values.turn, '回合号')
91
+ const filter = fold(query)
92
+ const matches = (...fields) => !filter || fields.some(value => fold(value).includes(filter))
93
+ if ((session !== undefined && (!isId(session) || noHistory))
94
+ || assetIds.length > 24 || assetIds.some(id => !isId(id))
95
+ || !['prompt', 'local', 'share'].includes(format)) {
96
+ throw new Error('会话、资料或输出格式无效。使用 inspect 获取可用 ID。')
97
+ }
98
+ if (['history', 'attachment'].includes(action) && !session) throw new Error('请用 --session 指定要查看的会话。')
99
+ if (action === 'attachment' && (!/^[a-f0-9]{64}$/.test(attachment ?? '') || !output?.trim())) {
100
+ throw new Error('请指定在 history 中看到的附件 ID 和输出文件。')
101
+ }
102
+ if (action === 'history' && (output && cursor || output && format === 'prompt' || !output && (values.format || includeTrace))) {
103
+ throw new Error('导出历史时请使用 --output 和可选的 local 或 share 格式,分页位置用于查看历史。')
104
+ }
105
+ if (['asset', 'skill-info'].includes(action) && assetIds.length !== 1) throw new Error('请指定一个资料 ID。')
106
+ if (action === 'project-state' && !['pin', 'unpin', 'archive', 'restore'].includes(operation)) {
107
+ throw new Error('请指定 pin、unpin、archive 或 restore。')
108
+ }
109
+ const config = await loadConfig()
110
+ if (agent !== undefined) {
111
+ const selected = new Set(['agentsview', ...Object.keys(config.agentRoots)])
112
+ if (!selected.has(agent)) throw new Error(`不支持该来源。可用来源:${[...selected].join('、')}。`)
113
+ for (const name of Object.keys(config.agentRoots)) {
114
+ if (name !== agent) config.agentRoots[name] = []
115
+ }
116
+ if (agent !== 'agentsview') config.archiveFiles = []
117
+ }
118
+ if (action === 'projects') return listProjects(config, matches, page, values['include-archived'])
119
+ if (requested !== undefined && !requested.trim()) throw new Error('项目目录不能为空。')
120
+ const directory = path.resolve(requested ?? '.')
121
+ const canonical = await realpath(directory).catch(error => {
122
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error
123
+ })
124
+ const cwd = canonical ?? directory
125
+ if (cwd === path.parse(cwd).root || (canonical && !(await stat(canonical)).isDirectory())) {
126
+ throw new Error('请指定项目目录。')
127
+ }
128
+ config.projectRoots = canonical ? [cwd] : []
129
+ const projectKey = pathKey(cwd)
130
+ const { projects, sources } = await scanProjects(config, { includeTranscripts: !noHistory || !canonical })
131
+ const [project] = mergeProjects(projects.filter(item => pathKey(item.cwd) === projectKey))
132
+ if (!project) throw new Error('该目录不可访问,也没有匹配的本机归档。请用 projects 查找已知项目。')
133
+ if (action === 'project-state') {
134
+ const { writeProjectArchive, writeProjectPin } = await import('./project-archive.js')
135
+ if (operation === 'pin' || operation === 'unpin') await writeProjectPin(config, project.id, operation === 'pin')
136
+ else await writeProjectArchive(config, [project.id], operation === 'archive')
137
+ return json({ project: project.name, cwd, operation })
138
+ }
139
+ const conversations = new Map()
140
+ const archives = project.archives.filter(canReadConversation).sort((a, b) => dateMillis(b.date) - dateMillis(a.date))
141
+ for (const archive of archives) {
142
+ const id = conversationId(archive)
143
+ if (!conversations.has(id)) conversations.set(id, archive)
144
+ }
145
+ let selectedArchive = conversations.get(session)
146
+ if (session && !selectedArchive) {
147
+ const matches = new Set()
148
+ for (const archive of archives) {
149
+ const ids = conversationIds(archive)
150
+ if (ids.includes(session)) matches.add(ids[0])
151
+ }
152
+ if (matches.size !== 1) throw new Error('所选会话不在这个项目或来源中。')
153
+ const [id] = matches
154
+ selectedArchive = conversations.get(id)
155
+ }
156
+ if (action === 'history' || action === 'attachment') {
157
+ const { readSkillHistory } = await import('./skill-history.js')
158
+ return json(await readSkillHistory({
159
+ project, archive: selectedArchive, config, turn, cursor, format, includeTrace, output, attachment,
160
+ }))
161
+ }
162
+
163
+ const inventory = new Map()
164
+ if (action === 'inspect' || assetIds.length) {
165
+ const found = await listProjectAssets(project, config, { projectMemoryOnly: true, includeSkills, includeGlobalMemory })
166
+ for (const [kind, items] of [['memory', found.memories], ['skill', found.skills]]) {
167
+ for (const item of items) {
168
+ const id = createHash('sha256').update(item.file).digest('hex').slice(0, 24)
169
+ if (!inventory.has(id)) inventory.set(id, { ...item, kind })
170
+ }
171
+ }
172
+ }
173
+ if (action === 'inspect') {
174
+ const sessions = pageOf([...conversations].map(([id, archive]) => ({
175
+ id, agent: archive.agent ?? archive.kind, title: conversationTitle(archive.title) || '未命名会话',
176
+ date: dateMillis(archive.date) || undefined,
177
+ })).filter(item => matches(item.title, item.agent)), page, 20)
178
+ const material = kind => pageOf([...inventory].filter(([, item]) => item.kind === kind &&
179
+ matches(redact(item.name), item.agent, redact(item.detail), redact(path.basename(item.file))))
180
+ .map(([id, item]) => ({ id, name: redact(item.name), agent: item.agent, detail: redact(item.detail), scope: item.scope })),
181
+ page, kind === 'skill' ? 20 : 40)
182
+ const notes = material('memory')
183
+ const skills = material('skill')
184
+ return json({
185
+ project: { cwd, name: redact(project.name), online: Boolean(canonical) },
186
+ page, conversations: noHistory ? [] : sessions.items, moreConversations: !noHistory && sessions.more,
187
+ memories: notes.items, moreMemories: notes.more, skills: skills.items, moreSkills: skills.more,
188
+ sources: agent === undefined ? sources : sources.filter(source => source.id === agent),
189
+ })
190
+ }
191
+ if (action === 'asset' || action === 'skill-info') {
192
+ const item = inventory.get(assetIds[0])
193
+ if (!item) throw new Error('所选资料不在这个项目中。请用相同的来源和筛选范围重新查看。')
194
+ if (action === 'asset') {
195
+ const { text, truncated } = await readAsset(item)
196
+ const excerpt = pageOf(Array.from(redact(text)), page, 8_000)
197
+ return json({
198
+ name: redact(item.name), agent: item.agent, scope: item.scope, source: item.file,
199
+ text: excerpt.items.join(''), page, more: excerpt.more, truncated,
200
+ })
201
+ }
202
+ if (item.kind !== 'skill') throw new Error('请选择 Skill 资料。')
203
+ const { readSkillPackage } = await import('./skill-package.js')
204
+ const manifest = await readSkillPackage(item.file, { authorization: await verifyAssetSource(item) })
205
+ const files = pageOf(manifest.files, page, 40)
206
+ return json({
207
+ name: manifest.name, description: redact(manifest.description), scope: item.scope, agent: item.agent,
208
+ source: item.file, files: files.items.map(file => redact(file.rel)), page, more: files.more,
209
+ fileCount: manifest.fileCount, bytes: manifest.bytes, hasScripts: manifest.hasScripts, invocation: manifest.invocation,
210
+ })
211
+ }
212
+
213
+ const sections = await Promise.all([...new Set(assetIds)].map(async id => {
214
+ const item = inventory.get(id)
215
+ if (!item) throw new Error('所选资料不在这个项目中。')
216
+ return {
217
+ label: `${item.kind === 'skill' ? '来源 Skill 说明' : '项目资料'} · ${item.name}(${item.agent})`,
218
+ file: item.file, ...await readAsset(item),
219
+ }
220
+ }))
221
+ if (!noHistory) {
222
+ const selected = session ? [selectedArchive] : conversations.values()
223
+ for (const archive of selected) {
224
+ const history = await readConversationHistory(archive, cwd, config, { includeTrace: false }).catch(error => {
225
+ if (session) throw error
226
+ return undefined
227
+ })
228
+ if (!history?.messages.length) continue
229
+ const recent = history.messages.slice(-8)
230
+ if (recent[0].role === 'assistant' && !recent.some(item => item.role === 'user')) {
231
+ const user = history.messages.findLast(item => item.role === 'user')
232
+ if (user) recent.splice(0, 1, user)
233
+ }
234
+ sections.push({
235
+ label: '会话来源',
236
+ text: [archive.agent ?? archive.kind, conversationTitle(archive.title)].filter(Boolean).join(' · '),
237
+ truncated: history.truncated || history.sourceStats.partial || history.messages.length > recent.length,
238
+ })
239
+ for (const message of recent) {
240
+ const author = message.role === 'user' ? '用户' : '助手'
241
+ sections.push({
242
+ label: `近期会话 · ${author}`, text: message.text, conversation: true,
243
+ markdown: message.role === 'assistant',
244
+ })
245
+ }
246
+ break
247
+ }
248
+ if (!sections.some(item => item.conversation)) throw new Error('此项目或来源没有可读取的近期问答。仅交接项目资料时使用 --no-history。')
249
+ }
250
+ if (!sections.length) throw new Error('没有选择项目资料。请用 inspect 查看资料并传入 --asset。')
251
+
252
+ const { prompt, preview } = makePrompt(project, sections, '')
253
+ if (format === 'prompt' && !output) return prompt + '\n'
254
+ if (format === 'prompt') {
255
+ const { saveOutput } = await import('./skill-output.js')
256
+ return json({ file: await saveOutput(output, [prompt + '\n']) })
257
+ }
258
+ const { makeExport } = await import('./export.js')
259
+ if (canonical && assetIds.length) {
260
+ const { relativeMarkdownLinks } = await import('../web/markdown.js')
261
+ for (const section of preview.sections) {
262
+ if (!section.file) continue
263
+ section.references = await Promise.all(relativeMarkdownLinks(section.text).slice(0, 128).map(async href => {
264
+ const reference = await authorizeProjectReference(cwd, section.file, href)
265
+ const verified = reference.authorization && await verifySourceAuthorization(reference.authorization).catch(() => undefined)
266
+ return { href, path: reference.path, verifiedFile: verified?.file }
267
+ }))
268
+ }
269
+ }
270
+ let { markdown } = makeExport({
271
+ title: redact(project.name), origin: '项目交接', preview, format, savePath: output ? path.resolve(output) : undefined,
272
+ })
273
+ if (format === 'share') {
274
+ const { findShareFindings, redactShareMarkdown } = await import('../web/share-redaction.js')
275
+ markdown = redactShareMarkdown(markdown, findShareFindings(markdown))
276
+ }
277
+ if (!output) return markdown
278
+ const { saveOutput } = await import('./skill-output.js')
279
+ return json({ file: await saveOutput(output, [markdown]) })
280
+ }
281
+
282
+ try {
283
+ process.stdout.write(await run(process.argv.slice(2)))
284
+ } catch (error) {
285
+ process.stderr.write(`Agent Bridge: ${redact(error.message)}\n`)
286
+ process.exitCode = 1
287
+ }
@@ -0,0 +1,129 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { mkdtemp, realpath, rm, stat } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import path from 'node:path'
5
+ import { readHistoryAttachment, readHistoryPage, stageConversation } from './conversation-store.js'
6
+ import { conversationId, conversationTitle, redact } from './handoff.js'
7
+ import { readConversationAttachment } from './history-attachment.js'
8
+ import { readSourceEvents } from './projects.js'
9
+ import { saveOutput } from './skill-output.js'
10
+ import { findShareFindings, privateKeyMarkers, redactShareMarkdown, shareReplacements } from '../web/share-redaction.js'
11
+
12
+ async function sourceVersion(archive) {
13
+ const files = [archive.file, archive.file + '-wal']
14
+ const versions = await Promise.all(files.map(async file => {
15
+ const info = await stat(file, { bigint: true }).catch(error => {
16
+ if (error.code !== 'ENOENT') throw error
17
+ })
18
+ return info && [info.ino, info.size, info.mtimeNs].join(':')
19
+ }))
20
+ return createHash('sha256').update(JSON.stringify(versions)).digest('hex').slice(0, 20)
21
+ }
22
+
23
+ async function lastPrivateKeyEnd(readRecords) {
24
+ let last = 0
25
+ let index = 0
26
+ for await (const text of readRecords()) {
27
+ index++
28
+ for (const marker of text.matchAll(privateKeyMarkers)) {
29
+ if (marker[1] === 'END') {
30
+ last = index
31
+ break
32
+ }
33
+ }
34
+ }
35
+ return last
36
+ }
37
+
38
+ async function* shareHistoryMarkdown(readRecords) {
39
+ // Records already join all stored parts and end at paragraph boundaries.
40
+ // Only a PEM block can match across records. Look ahead in the immutable
41
+ // snapshot once, on demand, so an unmatched BEGIN never swallows later text.
42
+ let insideKey = false
43
+ let lastEnd
44
+ let index = 0
45
+ for await (const text of readRecords()) {
46
+ index++
47
+ if (!text) continue
48
+ const continued = insideKey
49
+ let start = continued ? 0 : undefined
50
+ let end
51
+ for (const marker of text.matchAll(privateKeyMarkers)) {
52
+ if (marker[1] === 'BEGIN') start ??= marker.index
53
+ else {
54
+ if (continued) end ??= marker.index + marker[0].length
55
+ start = undefined
56
+ }
57
+ }
58
+ if (continued && end === undefined) continue
59
+ const fragments = continued ? [{ start: 0, end }] : []
60
+ insideKey = false
61
+ if (start !== undefined) {
62
+ lastEnd ??= await lastPrivateKeyEnd(readRecords)
63
+ if (index < lastEnd) {
64
+ fragments.push({ start, end: text.length })
65
+ insideKey = true
66
+ }
67
+ }
68
+ const safe = redactShareMarkdown(text, findShareFindings(text, fragments))
69
+ // The first fragment's placeholder was emitted with its opening record.
70
+ yield continued ? safe.slice(shareReplacements.credential.length) : safe
71
+ }
72
+ }
73
+
74
+ export async function readSkillHistory({ project, archive, config, turn, cursor, format, includeTrace, output, attachment }) {
75
+ const sourceId = conversationId(archive)
76
+ const version = await sourceVersion(archive)
77
+ const cursorPrefix = `${sourceId}:${version}:${turn ?? 0}:`
78
+ if (cursor && (!cursor.startsWith(cursorPrefix) || !/^\d+:\d+:\d+$/.test(cursor.slice(cursorPrefix.length)))) {
79
+ throw new Error('历史分页位置已变化,请从该会话的第一页重新查看。')
80
+ }
81
+ const parent = await realpath(tmpdir())
82
+ const scratch = await mkdtemp(path.join(parent, 'dsh-bridge-history-'))
83
+ const storage = { configFile: path.join(scratch, 'agent-bridge.json') }
84
+ const id = randomUUID()
85
+ try {
86
+ const record = await stageConversation(storage, {
87
+ id, sessionId: randomUUID(), projectId: project.id, sourceId,
88
+ sourceCwd: project.cwd, title: conversationTitle(archive.title) || '来源会话',
89
+ }, readSourceEvents(archive, { config, sourceCwd: project.cwd }), redact,
90
+ item => readConversationAttachment(project, archive, item))
91
+ if (attachment) {
92
+ const item = await readHistoryAttachment(storage, id, attachment, { preview: true })
93
+ if (!item) throw new Error('这条会话中没有可取回的该附件。')
94
+ return { file: await saveOutput(output, [item.bytes]), name: item.name, bytes: item.bytes.length }
95
+ }
96
+
97
+ async function pageAt(position) {
98
+ const page = await readHistoryPage(storage, id, position, turn, { maxBytes: output ? undefined : 14 * 1024 })
99
+ if (turn !== undefined && page.items.some(item => item.turn !== turn)) {
100
+ return { ...page, items: page.items.filter(item => item.turn === turn), nextCursor: null }
101
+ }
102
+ return page
103
+ }
104
+ if (output) {
105
+ const { sourceHistoryMarkdown } = await import('./export.js')
106
+ async function* pages() {
107
+ let position
108
+ do {
109
+ const page = await pageAt(position)
110
+ yield page
111
+ position = page.nextCursor
112
+ } while (position)
113
+ }
114
+ const readRecords = () => sourceHistoryMarkdown(record, pages(), { format, includeTrace })
115
+ const markdown = format === 'share' ? shareHistoryMarkdown(readRecords) : readRecords()
116
+ return { file: await saveOutput(output, markdown), history: record.history }
117
+ }
118
+ const page = await pageAt(cursor && `${id}:${cursor.slice(cursorPrefix.length)}`)
119
+ return {
120
+ ...page, title: record.title, sourceStats: record.sourceStats, usedSkills: record.usedSkills,
121
+ nextCursor: page.nextCursor ? cursorPrefix + page.nextCursor.slice(id.length + 1) : null,
122
+ }
123
+ } finally {
124
+ const checked = await realpath(scratch)
125
+ if (path.dirname(checked) === parent && path.basename(checked).startsWith('dsh-bridge-history-')) {
126
+ await rm(checked, { recursive: true, force: true })
127
+ }
128
+ }
129
+ }
@@ -0,0 +1,19 @@
1
+ import { createWriteStream } from 'node:fs'
2
+ import { unlink } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { pipeline } from 'node:stream/promises'
5
+
6
+ export async function saveOutput(file, chunks) {
7
+ const target = path.resolve(file)
8
+ const output = createWriteStream(target, { flags: 'wx', mode: 0o600 })
9
+ let created = false
10
+ output.once('open', () => { created = true })
11
+ try {
12
+ await pipeline(chunks, output)
13
+ return target
14
+ } catch (error) {
15
+ if (created) await unlink(target).catch(() => {})
16
+ if (error.code === 'EEXIST') throw new Error('输出文件已存在,请选择另一个文件名。')
17
+ throw error
18
+ }
19
+ }