@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/export.js CHANGED
@@ -1,12 +1,273 @@
1
- export function makeExport({ title, prompt, origin, date = new Date(), truncated = false }) {
2
- const heading = title.replace(/[\r\n\u0000-\u001f]+/g, ' ').trim() || '项目交接'
3
- const name = heading.replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^[.-]+|[.-]+$/g, '')
4
- const stamp = date.toISOString()
5
- const suffix = stamp.slice(0, 19).replace(/[-:]/g, '') + 'Z'
6
- const metadata = [`来源:${origin}`, `导出时间:${stamp}`]
7
- if (truncated) metadata.push('部分内容已截取。')
8
- return {
9
- filename: `handoff-${Array.from(name).slice(0, 48).join('') || 'project'}-${suffix}.md`,
10
- markdown: [`# ${heading}`, '', metadata.join(' \n'), '', prompt.trimEnd(), ''].join('\n'),
11
- }
12
- }
1
+ import path from 'node:path'
2
+ import { pathToFileURL } from 'node:url'
3
+ import { isMarkdownFile, markdownExportSpans, parseMarkdown } from '../web/markdown.js'
4
+
5
+ const control = /[\u0000-\u001f\u007f]+/g
6
+
7
+ function clean(value, limit = 240) {
8
+ return String(value ?? '').replace(control, ' ').trim().slice(0, limit)
9
+ }
10
+
11
+ function shortName(file) {
12
+ return clean(String(file).replace(/[\\/]+$/, '').replace(/^.*[\\/]/, ''), 160)
13
+ }
14
+
15
+ function linkLabel(value) {
16
+ return String(value ?? '').replace(/[\\[\]]/g, character => `\\${character}`)
17
+ }
18
+
19
+ function fileLink(label, target) {
20
+ return `[${linkLabel(label)}](<${target}>)`
21
+ }
22
+
23
+ function directoryUrl(directory) {
24
+ const href = pathToFileURL(directory).href
25
+ return href.endsWith('/') ? href : `${href}/`
26
+ }
27
+
28
+ function relativeUrl(fromFile, target) {
29
+ const relative = path.relative(path.dirname(fromFile), target)
30
+ if (!relative || path.isAbsolute(relative)) return ''
31
+ return relative.split(path.sep).map(segment => encodeURIComponent(segment)).join('/')
32
+ }
33
+
34
+ function projectRelative(root, target) {
35
+ if (!path.isAbsolute(root) || !target || !path.isAbsolute(target)) return ''
36
+ const relative = path.relative(root, target)
37
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return ''
38
+ return relative.split(path.sep).join('/')
39
+ }
40
+
41
+ function codeSpan(value) {
42
+ const delimiter = '`'.repeat(1 + Math.max(0, ...(value.match(/`+/g) ?? []).map(run => run.length)))
43
+ const padding = /^[ `]|[ `]$/.test(value) ? ' ' : ''
44
+ return `${delimiter}${padding}${value}${padding}${delimiter}`
45
+ }
46
+
47
+ function linkDestination(href, title) {
48
+ const target = href.replace(/&/g, '&amp;').replace(/</g, '%3C').replace(/>/g, '%3E')
49
+ // Keep a reference title in the same table cell and on the same source line.
50
+ const tooltip = title ? ` "${title.replace(/[&"\\|\n\r]/g, char => `&#${char.charCodeAt(0)};`)}"` : ''
51
+ return `(<${target}>${tooltip})`
52
+ }
53
+
54
+ function handoffBody(item, cwd, mode, savePath) {
55
+ if (!isMarkdownFile(item.file)) return item.text
56
+ const references = new Map((item.references ?? []).map(reference => [reference.href, reference]))
57
+ const { links, definitions } = markdownExportSpans(item.text)
58
+ // Materialize references before merging sections. A definition left in the
59
+ // combined document could bind an unresolved label in another source.
60
+ const edits = definitions.map(range => ({ ...range, text: '' }))
61
+ let droppedThrough = 0
62
+ for (const { href, start, labelEnd, end, relative, title } of links) {
63
+ if (start < droppedThrough) continue
64
+ let target = href
65
+ if (relative) {
66
+ const reference = references.get(href)
67
+ const verified = reference?.verifiedFile
68
+ target = ''
69
+ if (projectRelative(cwd, verified)) {
70
+ if (mode === 'local') target = pathToFileURL(verified).href.replace(/&/g, '%26')
71
+ else if (savePath) target = relativeUrl(savePath, verified)
72
+ }
73
+ if (!target) {
74
+ const caption = escapeProse(item.text.slice(start + 1, labelEnd - 1)).replace(/(?<!\\)[\[\]]/g, '\\$&')
75
+ const label = projectRelative(cwd, reference?.path)
76
+ edits.push({ start, end, text: label ? `${caption}(${codeSpan(label)})` : caption })
77
+ droppedThrough = end
78
+ continue
79
+ }
80
+ target += href.match(/#[^\s<>]*$/)?.[0] ?? ''
81
+ }
82
+ edits.push({ start: labelEnd, end, text: linkDestination(target, title) })
83
+ }
84
+ let rewritten = ''
85
+ let offset = 0
86
+ for (const { start, end, text } of edits.sort((a, b) => a.start - b.start)) {
87
+ rewritten += item.text.slice(offset, start) + text
88
+ offset = end
89
+ }
90
+ return rewritten + item.text.slice(offset)
91
+ }
92
+
93
+ // Keep plain user text and source excerpts from changing the document structure.
94
+ function escapeProse(text) {
95
+ return String(text ?? '').split('\n').map(line => {
96
+ if (/^ {0,3}(?:#{1,6}(?:[ \t]|$)|(?:-{3,}|={3,}|\*{3,}|_{3,})[ \t]*$|`{3,}|~{3,})/.test(line)) {
97
+ return line.replace(/^( {0,3})/, '$1\\')
98
+ }
99
+ return line
100
+ }).join('\n')
101
+ }
102
+
103
+ function stamp(date) {
104
+ return date.toISOString().slice(0, 19) + 'Z'
105
+ }
106
+
107
+ // Body sections are quoted source material, so their Markdown stays intact.
108
+ // An unbalanced fence would swallow the rest of the document, so it is closed
109
+ // at the end of its own section instead.
110
+ function fenceSafe(text) {
111
+ const fence = parseMarkdown(text).at(-1)
112
+ if (fence?.type !== 'fence') return text
113
+ const lines = text.split(/\r\n|\n|\r/)
114
+ const [start, end] = fence.map
115
+ const closing = new RegExp(`^ {0,3}${fence.markup[0]}{${fence.markup.length},}[ \\t]*$`)
116
+ if (end > start + 1 && closing.test(lines[end - 1])) return text
117
+ const eol = text.match(/\r\n|\n|\r/)?.[0] ?? '\n'
118
+ return `${text}${/\r$|\n$/.test(text) ? '' : eol}${fence.markup}`
119
+ }
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
+
153
+ function fileStamp(date) {
154
+ return date.toISOString().slice(0, 19).replace(/[-:]/g, '') + 'Z'
155
+ }
156
+
157
+ function filenameOf(heading, date) {
158
+ const name = heading.replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^[.-]+|[.-]+$/g, '')
159
+ return `handoff-${Array.from(name).slice(0, 48).join('') || 'project'}-${fileStamp(date)}.md`
160
+ }
161
+
162
+ function sourceValue(file, { format, savePath }) {
163
+ if (format === 'share') {
164
+ const relative = savePath ? relativeUrl(savePath, file) : ''
165
+ return relative ? fileLink(shortName(file), relative) : `\`${shortName(file)}\``
166
+ }
167
+ return fileLink(shortName(file), pathToFileURL(file).href)
168
+ }
169
+
170
+ function conversationHeading(label) {
171
+ return clean(String(label ?? '').replace(/^近期会话\s*·\s*/, '')) || '消息'
172
+ }
173
+
174
+ const traceKinds = { summary: '思考摘要', tool_call: '工具调用', tool_result: '工具结果' }
175
+ const traceStates = {
176
+ ok: '已完成', error: '失败', missing: '未记录结果', pending: '未完成', truncated: '已截取',
177
+ }
178
+
179
+ function traceLines(trace) {
180
+ if (!Array.isArray(trace) || !trace.length) return []
181
+ const lines = ['## 来源记录', '', '> 从旧 Agent 的会话记录中读取,只供查阅,不会重放任何工具调用。', '']
182
+ let turn
183
+ for (const item of trace.slice(0, 200)) {
184
+ if (item.turn && item.turn !== turn) {
185
+ turn = item.turn
186
+ lines.push('', `### 第 ${turn} 轮`, '')
187
+ }
188
+ const kind = traceKinds[item?.kind] ?? '记录'
189
+ const name = clean(item?.name, 120)
190
+ const state = traceStates[item?.status] ?? ''
191
+ const excerpt = item?.kind === 'tool_call' ? '' : clean(item?.text, 400)
192
+ if (item?.kind === 'summary') {
193
+ lines.push(`- ${[kind, excerpt].filter(Boolean).join(' · ')}`)
194
+ continue
195
+ }
196
+ const callId = clean(item.callId, 200).replace(/`/g, '')
197
+ lines.push(`- ${[kind, name && `\`${name.replace(/`/g, '')}\``, callId && `调用 \`${callId}\``, state,
198
+ item.truncated && item.status !== 'truncated' && '已截取'].filter(Boolean).join(' · ')}`)
199
+ if (excerpt) lines.push(` - ${escapeProse(excerpt).replace(/\n/g, '\n ')}`)
200
+ }
201
+ lines.push('')
202
+ return lines
203
+ }
204
+
205
+ export function makeExport({
206
+ title, origin, date = new Date(), preview = {}, prompt, truncated: legacyTruncated = false,
207
+ format = 'local', savePath, includeTrace = false,
208
+ } = {}) {
209
+ const heading = clean(title) || '项目交接'
210
+ const session = origin === 'DSH 会话'
211
+ const mode = format === 'share' ? 'share' : 'local'
212
+ const exportFile = typeof savePath === 'string' && path.isAbsolute(savePath) ? savePath : undefined
213
+ const legacy = typeof prompt === 'string' && prompt.trim() && !Array.isArray(preview.sections)
214
+ const sections = Array.isArray(preview.sections)
215
+ ? preview.sections.filter(item => item && typeof item.text === 'string' && item.text.trim())
216
+ : []
217
+ const conversation = sections.filter(item => item.conversation === true)
218
+ const body = sections.filter(item => item.conversation !== true)
219
+ const files = body.filter(item => typeof item.file === 'string' && item.file)
220
+ const sources = (Array.isArray(preview.sources) ? preview.sources : [])
221
+ .map(value => clean(value, 40)).filter(Boolean)
222
+ const truncated = legacy ? legacyTruncated === true : preview.truncated === true
223
+
224
+ const lines = [`# ${heading} · ${session ? '会话记录' : '开发交接'}`, '']
225
+ const summary = [`来源:${sources.join('、') || clean(origin, 40) || '本地项目'}`, stamp(date)]
226
+ if (files.length) summary.push(`${files.length} 份资料`)
227
+ if (conversation.length) summary.push(`${conversation.length} 段对话`)
228
+ lines.push(`> ${summary.join(' · ')}`, '')
229
+
230
+ const cwd = typeof preview.cwd === 'string' && preview.cwd ? preview.cwd : ''
231
+ if (cwd) {
232
+ const name = clean(path.basename(cwd.replace(/[\\/]+$/, '')) || cwd, 120)
233
+ const value = mode === 'share' ? `\`${name}\`` : fileLink(name, directoryUrl(cwd))
234
+ lines.push(`**${session ? '原工作目录' : '工作目录'}**:${value}`, '')
235
+ }
236
+
237
+ if (legacy) {
238
+ lines.push(fenceSafe(prompt), '')
239
+ if (truncated) lines.push('> 部分内容已截取,完整内容见来源文件。', '')
240
+ if (preview.footer) lines.push(`> ${clean(preview.footer, 200)}`, '')
241
+ return { filename: filenameOf(heading, date), markdown: `${lines.join('\n').trimEnd()}\n` }
242
+ }
243
+
244
+ if (files.length) {
245
+ lines.push('## 资料索引', '')
246
+ for (const item of files) {
247
+ lines.push(`- ${sourceValue(item.file, { format: mode, savePath: exportFile })}${item.label ? ` · ${linkLabel(clean(item.label))}` : ''}`)
248
+ }
249
+ lines.push('')
250
+ }
251
+
252
+ for (const item of body) {
253
+ lines.push(`## ${clean(item.label) || '资料'}`, '')
254
+ if (typeof item.file === 'string' && item.file) {
255
+ lines.push(`来源:${sourceValue(item.file, { format: mode, savePath: exportFile })}`, '')
256
+ }
257
+ lines.push(fenceSafe(session ? item.text : handoffBody(item, cwd, mode, exportFile)), '')
258
+ }
259
+
260
+ if (conversation.length) {
261
+ lines.push('## 最近对话', '')
262
+ for (const item of conversation) {
263
+ lines.push(`### ${conversationHeading(item.label)}`, '',
264
+ item.markdown ? fenceSafe(item.text) : escapeProse(item.text.trimEnd()), '')
265
+ }
266
+ }
267
+
268
+ if (includeTrace === true) lines.push(...traceLines(preview.trace))
269
+ if (truncated) lines.push('> 部分内容已截取,完整内容见来源文件。', '')
270
+ if (preview.footer) lines.push(`> ${clean(preview.footer, 200)}`, '')
271
+
272
+ return { filename: filenameOf(heading, date), markdown: `${lines.join('\n').trimEnd()}\n` }
273
+ }