@wbohui123/blueprint-studio 0.0.0-stage → 2.0.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 (65) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +72 -2
  3. package/package.json +33 -4
  4. package/src/DeepSeek/344/275/231/351/242/235.js +33 -0
  5. package/src/index.js +5307 -0
  6. package/src//344/272/247/347/211/251.js +386 -0
  7. package/src//344/273/273/345/212/241/345/273/212/351/242/204/350/247/210.js +119 -0
  8. package/src//344/274/232/350/257/235/345/277/253/347/205/247/350/257/273/345/217/226.js +14 -0
  9. package/src//345/200/237/346/235/245/347/232/204//344/272/247/347/211/251.js +87 -0
  10. package/src//345/200/237/346/235/245/347/232/204//345/252/222/344/275/223/346/234/215/345/212/241.js +485 -0
  11. package/src//345/200/237/346/235/245/347/232/204//345/274/200/347/273/210/347/253/257.js +44 -0
  12. package/src//345/200/237/346/235/245/347/232/204//346/235/202/351/241/271.js +67 -0
  13. package/src//345/200/237/346/235/245/347/232/204//346/256/213/347/225/231/350/277/233/347/250/213.js +181 -0
  14. package/src//345/200/237/346/235/245/347/232/204//346/266/210/346/201/257/345/215/217/350/256/256.js +48 -0
  15. package/src//345/200/237/346/235/245/347/232/204//347/225/231/344/270/213/347/232/204/350/277/233/347/250/213.js +35 -0
  16. package/src//345/200/237/346/235/245/347/232/204//347/273/210/347/253/257.js +20 -0
  17. package/src//345/200/237/346/235/245/347/232/204//350/243/205/346/217/220/344/276/233/346/226/271.js +26 -0
  18. package/src//345/200/237/346/235/245/347/232/204//350/267/257/345/276/204.js +21 -0
  19. package/src//345/200/237/346/235/245/347/232/204//351/227/256/347/255/224.js +48 -0
  20. package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/210/240/351/231/244/347/212/266/346/200/201.js +5 -0
  21. package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/220/215/347/247/260.js +116 -0
  22. package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/255/230/345/202/250.js +92 -0
  23. package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/351/231/204/344/273/266.js +55 -0
  24. package/src//345/201/234/346/255/242/345/220/216/345/217/260.js +18 -0
  25. package/src//345/212/251/347/220/206.js +157 -0
  26. package/src//345/220/215/345/206/214/350/247/206/345/233/276.js +251 -0
  27. package/src//345/220/215/345/206/214/350/257/273/347/274/223/345/255/230.js +70 -0
  28. package/src//345/233/236/350/257/235/346/217/220/351/206/222.js +38 -0
  29. package/src//345/233/276/347/272/270/345/256/236/346/227/266.js +91 -0
  30. package/src//345/244/226/351/203/250run/344/272/247/347/211/251.js +75 -0
  31. package/src//345/244/226/351/203/250run/350/247/206/345/233/276.js +86 -0
  32. package/src//345/244/226/351/203/250/345/215/217/345/212/251.js +101 -0
  33. package/src//345/252/222/344/275/223/350/256/276/347/275/256.js +12 -0
  34. package/src//345/255/220/344/273/243/347/220/206.js +337 -0
  35. package/src//345/256/236/346/227/266/350/276/223/345/207/272.js +90 -0
  36. package/src//345/267/245/344/275/234/346/227/266/351/227/264.js +170 -0
  37. package/src//345/271/263/345/217/260/345/205/245/345/217/243.js +703 -0
  38. package/src//346/211/247/350/241/214/350/203/275/345/212/233.js +2 -0
  39. package/src//346/214/201/347/273/255/347/233/256/346/240/207.js +3 -0
  40. package/src//346/217/220/347/244/272/347/273/237/350/256/241.js +24 -0
  41. package/src//346/226/207/344/273/266/345/244/271.js +26 -0
  42. package/src//346/226/260/345/220/215/345/206/214.js +145 -0
  43. package/src//346/226/260/351/241/271/347/233/256.js +203 -0
  44. package/src//346/227/247/345/212/237/350/203/275/346/241/251.js +34 -0
  45. package/src//346/235/220/346/226/231.js +97 -0
  46. package/src//346/240/221/346/221/230/350/246/201/347/233/230.js +37 -0
  47. package/src//346/240/221/350/264/246/346/234/254.js +11 -0
  48. package/src//347/225/214/351/235/242/350/257/255/350/250/200.js +25 -0
  49. package/src//347/273/210/347/253/257.js +128 -0
  50. package/src//350/212/202/347/202/271/344/277/241/346/201/257.js +56 -0
  51. package/src//350/256/260/345/277/206/345/205/245/345/217/243.js +51 -0
  52. package/src//350/275/257/344/273/266.js +227 -0
  53. package/src//350/277/220/350/241/214/347/212/266/346/200/201.js +38 -0
  54. package/src//350/277/236/346/216/245.js +385 -0
  55. package/src//351/227/256/347/255/224/351/223/276.js +160 -0
  56. package/src//351/241/271/347/233/256/345/210/206/347/273/204.js +67 -0
  57. package/src//351/241/271/347/233/256/345/220/215/347/247/260/345/205/245/345/217/243.js +23 -0
  58. package/src//351/241/271/347/233/256/345/255/230/345/202/250/345/205/245/345/217/243.js +30 -0
  59. package/src//351/241/271/347/233/256/346/223/215/344/275/234.js +34 -0
  60. package/src//351/241/271/347/233/256/350/207/252/345/212/250/345/201/234/346/255/242.js +107 -0
  61. package/src//351/241/271/347/233/256/350/256/241/351/207/217.js +114 -0
  62. package/src//351/242/204/350/247/210.js +157 -0
  63. package/viewer//347/225/214/351/235/242/350/257/255/350/250/200.js +97 -0
  64. package/viewer//350/213/261/346/226/207.json +1535 -0
  65. package//345/215/225/344/273/267.json +126 -0
@@ -0,0 +1,386 @@
1
+ /** 产物是现有会话事实的只读投影。记录来源,不把文件修改次数冒充内容快照。 */
2
+ import { open, realpath, stat } from 'node:fs/promises'
3
+ import { existsSync } from 'node:fs'
4
+ import { resolve, relative, extname, basename, sep, isAbsolute } from 'node:path'
5
+ import { 检查产物, 网页入口, 允许产物路径, 允许预览路径, 文本产物扩展名 } from './借来的/产物.js'
6
+ import { nativeFileManager, openNativeAssociatedPath, revealNativePath } from '@deepseek-ai/dsh-native-command'
7
+ import { 展开工具调用 } from './借来的/杂项.js'
8
+ import { 是上下文消息, 工具调用Of, 工具结果Of, 工具结果失败 } from './借来的/消息协议.js'
9
+ /** 跑命令的工具:Mac、Linux 上叫 bash,Windows 上叫 pwsh(11-30)。 */
10
+ const 命令工具 = name => name === 'bash' || name === 'pwsh'
11
+
12
+ const 类型 = new Map(Object.entries({
13
+ image: 'png jpg jpeg gif webp svg avif bmp',
14
+ document: 'md markdown txt', web: 'html htm', pdf: 'pdf',
15
+ slides: 'ppt pptx odp', office: 'doc docx xls xlsx csv',
16
+ video: 'mp4 webm mov', audio: 'mp3 wav ogg m4a', playable: 'app command exe bat cmd',
17
+ }).flatMap(([kind, extensions]) => extensions.split(' ').map(e => [e, kind])))
18
+ export const 产物类型 = path => 类型.get(extname(path).slice(1).toLowerCase()) || (文本产物扩展名.includes(extname(path).slice(1).toLowerCase()) ? 'document' : 'file')
19
+ const argsOf = x => { try { return typeof x === 'string' ? JSON.parse(x) : x || {} } catch { return {} } }
20
+ const textOf = blocks => (blocks || []).filter(b => b.type === 'text').map(b => b.text || '').join('\n')
21
+ const timeOf = x => typeof x === 'number' ? x : Date.parse(x) || 0
22
+
23
+ export function 产物路径(root, input, { cwd = root, any = false, includeTemporary = false, includeEvidence = false } = {}) {
24
+ if (typeof input !== 'string' || !input.trim() || /[\0\r\n]/.test(input)) return null
25
+ let value = input.trim().replace(/^<|>$/g, '')
26
+ if (/^[a-z][a-z\d+.-]*:/i.test(value)) return null
27
+ try { value = decodeURIComponent(value) } catch { return null }
28
+ // Markdown 的行号与锚点不属于文件路径。
29
+ value = value.replace(/#.*$/, '').replace(/:\d+(?::\d+)?$/, '')
30
+ const path = relative(resolve(root), resolve(root, cwd, value)).split(sep).join('/')
31
+ if (!path || path.startsWith('../') || path === '..' || path.startsWith('/')) return null
32
+ if (!允许产物路径(path, {includeTemporary, includeEvidence})) return null
33
+ const kind = 类型.get(extname(path).slice(1).toLowerCase())
34
+ return kind || any ? { path, kind: kind || 产物类型(path) } : null
35
+ }
36
+
37
+ /** 只收成功写入、显式预览和 assistant 正文中明确的文件引用;read 与 reasoning 不算产物。 */
38
+ export function 产物引用(events, session, root, inherited = 0, options = {}) {
39
+ return 续产物引用(null, events, session, root, inherited, options).refs
40
+ }
41
+
42
+ /** 账本只追加:记住折到第几条,再读时只折新来的;前缀对不上就从头折。 */
43
+ export function 续产物引用(state, events, session, root, inherited = 0, { materials = false } = {}) {
44
+ if (!state || state.next > events.length || (state.next && events[state.next - 1]?.seq !== state.lastSeq))
45
+ state = { calls: new Map(), refs: [], seen: new Set(), cwd: root, next: 0, lastSeq: undefined, start: 0 }
46
+ const { calls, refs, seen } = state
47
+ let cwd = state.cwd
48
+ const add =(path, ev, callId, source, title, any = false, directory = cwd, input = path) => {
49
+ const file = 产物路径(root, path, {cwd:directory, any:any || materials, includeTemporary:materials, includeEvidence:materials})
50
+ if (!file || /^\.blueprint-tmp\/后台工具-/.test(file.path)) return
51
+ const key = `${ev.seq}:${file.path}`
52
+ if (seen.has(key)) return
53
+ seen.add(key)
54
+ // bash 输出里提到的带上节点开工时刻,汇集时好认出哪些是开工以后才有的。
55
+ refs.push({ ...file, input, session, seq: ev.seq, callId: callId || null,
56
+ time: timeOf(ev.time), source, title: title || basename(file.path), ...(source === '输出引用' && state.start ? { since: state.start } : {}) })
57
+ }
58
+ const quoted = (text, ev, callId, source, directory = cwd) => {
59
+ if (typeof text !== 'string') return
60
+ for (const m of text.matchAll(/!?\[([^\]\n]*)\]\((<[^>\n]+>|[^()\n]*(?:\([^()\n]*\)[^()\n]*)*)\)/g))
61
+ add(m[2].replace(/\s+["'][^]*$/, ''), ev, callId, source === '引用' ? '展示' : source, m[1], true, directory)
62
+ for (const m of text.matchAll(/`([^`\n]+)`|「([^」\n]+)」|“([^”\n]+)”/g))
63
+ add(m[1] || m[2] || m[3], ev, callId, source, undefined, false, directory)
64
+ }
65
+ const register = (id, name, args, ev, emitReferences = true) => {
66
+ const effective = 展开工具调用(name, args)
67
+ name = effective.name; args = effective.arguments
68
+ const parsed = argsOf(args)
69
+ const directory = 命令工具(name) && typeof parsed.workdir === 'string' ? resolve(cwd, parsed.workdir) : cwd
70
+ calls.set(id, { name, args: parsed, cwd: directory })
71
+ // 提问还在等用户回答时,也展示其中明确引用的文件,不等待 tool/result。
72
+ if (emitReferences && name === 'ask_user_question') {
73
+ const visit = value => {
74
+ if (typeof value === 'string') quoted(value, ev, id, '提问引用')
75
+ else if (value && typeof value === 'object') Object.values(value).forEach(visit)
76
+ }
77
+ visit(parsed)
78
+ }
79
+ }
80
+ for (let index = state.next; index < events.length; index++) {
81
+ const ev = events[index], d = ev.data || {}, blocks = d.message?.content || []
82
+ if (ev.type === 'working-directory/change' && typeof d.cwd === 'string' && isAbsolute(d.cwd)) cwd = d.cwd
83
+ const invoked = 工具调用Of(ev)
84
+ if (invoked) register(invoked.callId, invoked.name, invoked.arguments, ev, index >= inherited)
85
+ if (ev.type === 'assistant/message') {
86
+ for (const b of blocks) if (b.type === 'tool-call') register(b.id, b.name, b.arguments, ev, index >= inherited)
87
+ }
88
+ if (index < inherited) continue
89
+ state.start ||= timeOf(ev.time)
90
+ // 用户上传、项目 context 和持久材料入口仍以项目根为基准。
91
+ if (materials && ev.type === 'user/message') quoted(textOf(d.content), ev, null, 是上下文消息(d) ? '上下文引用' : '输入材料', root)
92
+ if (ev.type === 'assistant/message') {
93
+ quoted(textOf(blocks), ev, null, '引用')
94
+ }
95
+ const b = 工具结果Of(ev)
96
+ if (!b || 工具结果失败(ev)) continue
97
+ const call = calls.get(b.toolCallId)
98
+ if (!call) continue
99
+ if (call.name === 'present_artifact') {
100
+ try {
101
+ const receipt = JSON.parse(textOf(b.content)), a = receipt.artifact
102
+ if (receipt.artifactVersion === 1 && a?.declared && typeof a.path === 'string') {
103
+ const options = {any:true, includeTemporary:materials, includeEvidence:materials}
104
+ const url = 网页入口(a.path), file = url ? null : 产物路径(root, a.path, options)
105
+ if (!url && !file) continue
106
+ const declaration = {...a, path:url || file.path,
107
+ ...(a.coverPath ? {coverPath:产物路径(root, a.coverPath, options)?.path} : {})}
108
+ refs.push({path:declaration.path, input:call.args.entry, kind:url ? 'web' : 类型.get(extname(declaration.path).slice(1).toLowerCase()) || 'file',
109
+ session, seq:ev.seq, callId:b.toolCallId, time:timeOf(ev.time), source:'交付入口', title:a.title, declaration})
110
+ }
111
+ } catch { /* 只读成功工具回执,不猜损坏的协议 */ }
112
+ continue
113
+ }
114
+ // finish 的相关文件(10-22):和交回前那段说明一起,作交付入口列在对话里。先按当时的目录认,那里没有再按项目根(同 finish 的核对)。
115
+ if (call.name === 'finish' && Array.isArray(call.args.files)) {
116
+ for (const path of call.args.files) if (typeof path === 'string')
117
+ add(path, ev, b.toolCallId, '交付入口', undefined, true, existsSync(resolve(call.cwd, path)) ? call.cwd : root)
118
+ }
119
+ if (materials && (call.name === 'next' || call.name === 'finish') && Array.isArray(call.args.items_done)
120
+ && !call.args.wrong_stage && !/这一问记作 Q\d+|用户刚说了话/.test(textOf(b.content))) {
121
+ for (const item of call.args.items_done) {
122
+ quoted(item?.result, ev, b.toolCallId, '引用', call.cwd)
123
+ quoted(item?.look, ev, b.toolCallId, '引用', call.cwd)
124
+ }
125
+ }
126
+ const a = call.args
127
+ const directory = ['bash','pwsh','job_output'].includes(call.name) && typeof d.meta?.cwd === 'string' && isAbsolute(d.meta.cwd) ? d.meta.cwd : call.cwd
128
+ if (materials) {
129
+ const body = textOf(b.content)
130
+ if (['read','read_image','read_audio','read_video'].includes(call.name)) {
131
+ const resolved = body.match(/<path>([^<]+)<\/path>/)?.[1]
132
+ const inputs = [resolved || a.file_path || a.path || a.位置, ...(Array.isArray(a.files) ? a.files : [])].flat().filter(Boolean)
133
+ for (const [index, path] of inputs.entries()) add(path, ev, b.toolCallId, '读取', undefined, false, call.cwd,
134
+ index === 0 && resolved ? a.file_path || a.path || a.位置 || path : path)
135
+ }
136
+ if (['web_fetch','web_search'].includes(call.name)) {
137
+ const urls = [a.url, ...Array.from(body.matchAll(/https?:\/\/[^\s<>"\)\]]+/g), m => m[0])].filter(Boolean)
138
+ for (const input of new Set(urls)) {
139
+ const url = 网页入口(input)
140
+ if (url) refs.push({path:url, kind:'web', session, seq:ev.seq, callId:b.toolCallId,
141
+ time:timeOf(ev.time), source:call.name === 'web_fetch' ? '读取网页' : '检索候选', title:new URL(url).hostname})
142
+ }
143
+ }
144
+ if (['bash','pwsh','job_output'].includes(call.name)) {
145
+ quoted(body, ev, b.toolCallId, '输出引用', directory)
146
+ for (const line of body.split('\n')) if (/^(?:素材\/|\.blueprint-(?:tmp|evidence)\/)/.test(line.trim()) || line.trim().startsWith(root + '/') || line.trim().startsWith(root + sep))
147
+ add(line.trim(), ev, b.toolCallId, '输出引用', undefined, false, directory)
148
+ }
149
+ }
150
+ // media_call 出的图、视频、音频(落在 素材/AI生成):回执里 files 的每一个当写出的文件,出一个就在那一步下面摆卡、文件廊跟着多一项
151
+ // (11-26 用户:「能不能他生一张就能看一张,文件廊就同步?」——原来要等模型在话里点名才认)。异步任务查回来的回执一样认。
152
+ if (call.name === 'media_call') {
153
+ try { for (const file of JSON.parse(textOf(b.content))?.files || []) if (typeof file?.path === 'string') add(file.path, ev, b.toolCallId, '写入', undefined, true, root) }
154
+ catch { /* 回执不是 JSON(出错说明)就不认 */ }
155
+ }
156
+ if (call.name === 'render_page') {
157
+ try { add(JSON.parse(textOf(b.content)).path, ev, b.toolCallId, '写入', undefined, false, root) } catch { /* 只收成功截图回执 */ }
158
+ }
159
+ if (['write', 'edit', 'folder_write', 'folder_edit', 'preview', 'read_image'].includes(call.name)) {
160
+ // 工具返回的绝对路径优先于参数,参数可能是相对工作目录的路径。
161
+ const resolved = textOf(b.content).match(/<path>([^<]+)<\/path>/)?.[1]
162
+ add(resolved || a.file_path || a.path || a.位置, ev, b.toolCallId,
163
+ call.name === 'read_image' ? '查看' : call.name === 'preview' ? '展示' : '写入', undefined, false, call.cwd, a.file_path || a.path || a.位置 || resolved)
164
+ }
165
+ if (命令工具(call.name) || call.name === 'job_output') {
166
+ // 只收回执里明确出现且实际存在的路径,不解析 shell 程序来猜它写了什么。
167
+ for (const line of textOf(b.content).split('\n')) {
168
+ for (const m of line.matchAll(/(?:^|[\s`'"·])([^\s`'"<>()]+\.(?:png|jpe?g|gif|webp|svg|avif|md|markdown|html?|pdf|pptx?|docx?|xlsx?|mp4|webm|mp3|wav|command))(?=$|[\s`'"():,])/gi))
169
+ add(m[1], ev, b.toolCallId, '输出引用', undefined, false, directory)
170
+ }
171
+ }
172
+ }
173
+ state.cwd = cwd; state.next = events.length; state.lastSeq = events.at(-1)?.seq
174
+ return state
175
+ }
176
+
177
+ /** 正文与工具参数点击只认该事件恢复出的入口,不使用会话最新目录。 */
178
+ export function 定位产物引用(root, refs, input, { seq, callId } = {}, events = []) {
179
+ const normalize = value => {
180
+ if (typeof value !== 'string') return null
181
+ try { return decodeURIComponent(value.trim().replace(/^<|>$/g, '')).replace(/#.*$/, '').replace(/:\d+(?::\d+)?$/, '') }
182
+ catch { return null }
183
+ }
184
+ const wanted = normalize(input)
185
+ if (!wanted) throw new Error('缺少文件入口')
186
+ const source = refs.filter(ref => callId ? ref.callId === callId : String(ref.seq) === String(seq))
187
+ const direct = 产物路径(root, input, { any: true, includeTemporary: true, includeEvidence: true })?.path
188
+ const paths = [...new Set(source.filter(ref => normalize(ref.input) === wanted || ref.path === direct).map(ref => ref.path))]
189
+ if (paths.length === 1) return paths[0]
190
+ if (paths.length > 1) throw new Error('这条记录的文件入口不唯一')
191
+ // 头部输入不必成为产物:只核对真实调用中的文件参数和当时目录。
192
+ let cwd = root, candidate
193
+ const call = (id, name, args) => {
194
+ if (!callId || id !== callId) return
195
+ const effective = 展开工具调用(name, args), a = argsOf(effective.arguments)
196
+ const inputs = ['path','位置','file_path','entry'].flatMap(key => {
197
+ const value = a[key]
198
+ if (Array.isArray(value)) return value
199
+ try { const parsed = JSON.parse(value); if (Array.isArray(parsed)) return parsed } catch { /* 普通路径 */ }
200
+ return typeof value === 'string' ? [value] : []
201
+ })
202
+ if (inputs.some(value => normalize(value) === wanted)) candidate = 产物路径(root, input, {
203
+ cwd: 命令工具(effective.name) && typeof a.workdir === 'string' ? resolve(cwd, a.workdir) : cwd,
204
+ any: true, includeTemporary: true, includeEvidence: true,
205
+ })?.path
206
+ }
207
+ for (const event of events) {
208
+ const d = event.data || {}
209
+ if (event.type === 'working-directory/change' && typeof d.cwd === 'string' && isAbsolute(d.cwd)) cwd = d.cwd
210
+ const invoked = 工具调用Of(event)
211
+ if (invoked) call(invoked.callId, invoked.name, invoked.arguments)
212
+ if (event.type === 'assistant/message') for (const block of d.message?.content || [])
213
+ if (block.type === 'tool-call') call(block.id, block.name, block.arguments)
214
+ if (!callId && String(event.seq) === String(seq) && ['assistant/message','user/message'].includes(event.type)) {
215
+ const body = textOf(event.type === 'user/message' ? d.content : d.message?.content)
216
+ if (body.includes(String(input).trim()) || body.includes(wanted)) candidate = 产物路径(root, input, {
217
+ cwd: event.type === 'user/message' ? root : cwd, any: true, includeTemporary: true, includeEvidence: true,
218
+ })?.path
219
+ }
220
+ }
221
+ if (!candidate) throw new Error('这条记录没有对应的文件入口')
222
+ return candidate
223
+ }
224
+
225
+ export function 产物范围(sessions, chosen, roster, scope = 'branch') {
226
+ // 名册父子关系是主干,会话血统补上 do 与支线。
227
+ const byNode = new Map(roster.map(r => [String(r.id), r]))
228
+ const parent = new Map(sessions.map(s => [String(s.id), String(s.parentSession || '')]))
229
+ for (const r of roster) {
230
+ const p = byNode.get(String(r.交给))
231
+ if (r.会话 && p?.会话) parent.set(String(r.会话), String(p.会话))
232
+ }
233
+ if (scope === 'project') return sessions
234
+ return sessions.filter(s => {
235
+ let id = String(s.id)
236
+ const seen = new Set()
237
+ while (id && !seen.has(id)) {
238
+ if (id === String(chosen)) return true
239
+ if (scope === 'self') return false
240
+ seen.add(id); id = parent.get(id)
241
+ }
242
+ return false
243
+ })
244
+ }
245
+
246
+ /** realpath 再验边界,符号链接不能把项目外的文件送进预览。 */
247
+ export async function 安全产物文件(root, path, { preview = false } = {}) {
248
+ const base = await realpath(root), file = await realpath(resolve(root, path))
249
+ if (!file.startsWith(base + sep)) throw new Error('文件位于项目外')
250
+ const paths = [relative(base, resolve(base, path)), relative(base, file)].map(value => value.split(sep).join('/'))
251
+ if (paths.some(value => value.split('/').some(part => /^\.git$/i.test(part)))) throw new Error('Git 管理文件不提供预览')
252
+ if (preview || paths.some(value => value.split('/').includes('.agents'))) {
253
+ if (paths.some(value => !允许预览路径(value, { includeTemporary: true, includeEvidence: true }))) throw new Error('隐藏配置不提供预览')
254
+ }
255
+ return file
256
+ }
257
+
258
+ /** 打开、定位只接本机 Blueprint 页面的点击,不让预览网页、外面的网站触发宿主应用。
259
+ * 先照 dsh 自己「用其他应用打开」的做法问连接服务(requestRejection:Host/Origin 关口+dsh 登录 cookie):
260
+ * dsh 桌面版转发请求时删掉 Origin、换上自己的登录 cookie,只看 Origin 会把桌面版的点击全拦下(11-21 点 Finder 报「只允许本机 Blueprint 页面打开文件」)。
261
+ * 没有连接服务、或它不认的(Blueprint 自己的 App 用 blueprint_session),再看是不是本机同源。 */
262
+ export function 允许打开(req, connection) {
263
+ if (typeof connection?.requestRejection === 'function') {
264
+ try { if (connection.requestRejection(req) === undefined) return true } catch { /* 照同源检查 */ }
265
+ }
266
+ return 允许本机打开(req.headers || {})
267
+ }
268
+ export function 允许本机打开(headers) {
269
+ try {
270
+ const origin = new URL(headers.origin)
271
+ return origin.host === headers.host && ['localhost','127.0.0.1','[::1]'].includes(origin.hostname)
272
+ && headers['sec-fetch-site'] !== 'cross-site'
273
+ } catch { return false }
274
+ }
275
+
276
+ /** 相当于用户双击入口;路径单独传参,不经 shell,不接受附加命令。
277
+ * 打开、定位都交给 dsh 自带的原生命令(dsh-native-command):macOS 是 Finder,Windows 是资源管理器,Linux 开所在文件夹(11-21)。 */
278
+ const 原生打开 = args => {
279
+ const signal = AbortSignal.timeout(5000)
280
+ return args[0] === '-R' ? revealNativePath(args[1], signal) : openNativeAssociatedPath(args[0], signal)
281
+ }
282
+ export async function 打开本地产物(root, path, action, {
283
+ platform = process.platform,
284
+ launch = 原生打开,
285
+ } = {}) {
286
+ if (!['system','reveal'].includes(action)) throw new Error('不支持的打开方式')
287
+ if (nativeFileManager({platform}) === null) throw new Error('这台机器没有可用的文件管理器,不能交给系统打开或定位')
288
+ const artifact = await 检查产物(root, {entry:path, opening:action}, {includeTemporary:true, includeEvidence:true})
289
+ if (网页入口(artifact.path)) throw new Error('请选择项目内文件或目录')
290
+ const full = await 安全产物文件(root, artifact.path)
291
+ if (action === 'reveal') { await launch(['-R', full]); return { revealed: true } }
292
+ // 电脑上没有能开它的应用时不报「打不开」,退一步在 Finder/资源管理器里选中它(11-22 用户:「不应该出现打不开的情况」)。
293
+ try { await launch([full]); return { revealed: false } }
294
+ catch { await launch(['-R', full]); return { revealed: true } }
295
+ }
296
+
297
+ /** 列表只收节点做了、看了、拿给人看的:搜索结果里的候选网址、系统叫醒话里的路径不算;
298
+ * bash 输出里提到的路径只认节点开工以后新建或改过的文件(ctime,解压、拷贝也算),列目录、grep 带出来的旧素材、参考和目录本身不算。
299
+ * 点开路径时的定位仍用全部引用。 */
300
+ async function 列入的引用(root, path, refs) {
301
+ const kept = refs.filter(r => r.source !== '检索候选' && r.source !== '上下文引用')
302
+ if (!kept.some(r => r.source === '输出引用' && r.since)) return kept
303
+ let info = null
304
+ try { info = await stat(await 安全产物文件(root, path)) } catch { /* 不在了就不算 */ }
305
+ return kept.filter(r => r.source !== '输出引用' || !r.since || (info?.isFile() && info.ctimeMs >= r.since))
306
+ }
307
+
308
+ export async function 汇集产物(root, refs, roster, sessions, { materials = false } = {}) {
309
+ const rows = new Map(roster.map(r => [String(r.会话), r]))
310
+ const parents = new Map(sessions.map(s => [String(s.id), String(s.parentSession || '')]))
311
+ const owner = session => {
312
+ const seen = new Set()
313
+ while (session && !seen.has(session)) {
314
+ if (rows.has(session)) return rows.get(session)
315
+ seen.add(session); session = parents.get(session)
316
+ }
317
+ return null
318
+ }
319
+ const grouped = new Map()
320
+ for (const ref of refs) {
321
+ const node = owner(ref.session)
322
+ const list = grouped.get(ref.path) || []
323
+ list.push({ ...ref, nodeId: node?.id || '', nodeName: node?.name || '', nodeStatus: node?.交付结论 || '' })
324
+ grouped.set(ref.path, list)
325
+ }
326
+ const artifacts = []
327
+ for (const [path, all] of grouped) {
328
+ const history = await 列入的引用(root, path, all)
329
+ if (!history.length) continue
330
+ history.sort((a, b) => b.time - a.time || b.seq - a.seq || a.session.localeCompare(b.session))
331
+ const latest = history[0], node = owner(latest.session)
332
+ const item = { ...latest, id: path, history, nodeId: node?.id || '', nodeName: node?.name || '',
333
+ nodeStatus: node?.交付结论 || '', available: false, excerpt: '', modified: 0, size: 0 }
334
+ const declaration = history.find(r => r.declaration)?.declaration
335
+ try {
336
+ {
337
+ const checked = await 检查产物(root, {entry:path, title:declaration?.title || item.title,
338
+ description:declaration?.description, opening:declaration?.opening}, {includeTemporary:materials, includeEvidence:materials})
339
+ Object.assign(item, checked)
340
+ item.declared = !!declaration
341
+ if (checked.directory && item.kind !== 'playable') item.kind = 'file'
342
+ if (declaration?.coverPath) {
343
+ try {
344
+ const coverFile = await 安全产物文件(root, declaration.coverPath), coverStat = await stat(coverFile)
345
+ if (coverStat.isFile() && /\.(png|jpe?g|webp|gif|avif)$/i.test(declaration.coverPath))
346
+ item.cover = {path:declaration.coverPath, modified:coverStat.mtimeMs}
347
+ } catch { /* 封面丢失不隐藏有效入口 */ }
348
+ }
349
+ if (网页入口(path)) {
350
+ item.url = path; item.available = true
351
+ artifacts.push(item); continue
352
+ }
353
+ }
354
+ const full = await 安全产物文件(root, path), st = await stat(full)
355
+ if (!st.isFile() && !item.directory) continue
356
+ item.available = true; item.modified = st.mtimeMs; item.size = st.size
357
+ if (item.cover) item.cover.stale = item.cover.modified < st.mtimeMs
358
+ if (!item.cover && (item.kind === 'web' || item.kind === 'playable')) {
359
+ // 明确约定:同目录、同主文件名的图片作为网页封面;不启动浏览器截图。
360
+ const stem = path.slice(0, -extname(path).length)
361
+ for (const extension of ['png', 'webp', 'jpg', 'jpeg']) {
362
+ const coverPath = `${stem}.${extension}`
363
+ try {
364
+ const coverFile = await 安全产物文件(root, coverPath), coverStat = await stat(coverFile)
365
+ if (!coverStat.isFile()) continue
366
+ item.cover = { path: coverPath, modified: coverStat.mtimeMs, stale: coverStat.mtimeMs < st.mtimeMs }
367
+ break
368
+ } catch { /* 没有同名封面就保留文字入口;越界图片不加载 */ }
369
+ }
370
+ }
371
+ if (item.kind === 'document' || item.kind === 'web') {
372
+ const handle = await open(full, 'r')
373
+ try {
374
+ const buffer = Buffer.alloc(8192), { bytesRead } = await handle.read(buffer, 0, buffer.length, 0)
375
+ const text = buffer.subarray(0, bytesRead).toString('utf8')
376
+ if (item.kind === 'document') item.excerpt = text.slice(0, 800)
377
+ else item.excerpt = (text.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1] || '')
378
+ } finally { await handle.close() }
379
+ }
380
+ } catch (e) { item.unavailableReason = e.code === 'ENOENT' ? '文件已移动或删除' : '文件不可读取或位于项目外' }
381
+ // 单纯的正文引用必须确实落地,写入回执则保留“已删除”的事实。
382
+ if (!item.available && history.every(r => !['写入','交付入口','实时文件'].includes(r.source))) continue
383
+ artifacts.push(item)
384
+ }
385
+ return artifacts.sort((a, b) => b.time - a.time || a.path.localeCompare(b.path))
386
+ }
@@ -0,0 +1,119 @@
1
+ /** 按可见卡片读取内容:文档摘录、目录条目、视频画面、音乐频谱和网页截图。 */
2
+ import {execFile} from 'node:child_process'
3
+ import {createHash, randomUUID} from 'node:crypto'
4
+ import {mkdir, open, opendir, readFile, rename, rm, stat, writeFile} from 'node:fs/promises'
5
+ import {tmpdir} from 'node:os'
6
+ import {dirname, extname, join} from 'node:path'
7
+ import {promisify} from 'node:util'
8
+ import {产物路径, 产物类型, 安全产物文件} from './产物.js'
9
+ import {网页入口} from './借来的/产物.js'
10
+
11
+ const execute = promisify(execFile)
12
+ const pngHeader = Buffer.from('89504e470d0a1a0a', 'hex')
13
+ const validPNG = body => Buffer.isBuffer(body) && body.length >= 45 && body.subarray(0,8).equals(pngHeader)
14
+ && body.toString('ascii',12,16) === 'IHDR' && body.toString('ascii',body.length-8,body.length-4) === 'IEND'
15
+ const cacheVersion = 1
16
+ const stamp = info => [info.size,info.mtimeMs,info.ctimeMs]
17
+ async function excerpt(file) {
18
+ const handle = await open(file, 'r')
19
+ try {
20
+ const buffer = Buffer.alloc(8192), {bytesRead} = await handle.read(buffer, 0, buffer.length, 0)
21
+ const text = buffer.subarray(0, bytesRead).toString('utf8')
22
+ return text.includes('\0') ? '' : text.slice(0, 3000)
23
+ } finally { await handle.close() }
24
+ }
25
+
26
+ async function readCache(path, image) {
27
+ try {
28
+ const info = await stat(path)
29
+ if(!info.isFile() || info.size > (image ? 16*1024*1024 : 65536)) return null
30
+ const body = await readFile(path)
31
+ if(image) return validPNG(body) ? {type:'image',body} : null
32
+ const value = JSON.parse(body.toString('utf8'))
33
+ return value?.type === 'info' ? value : null
34
+ } catch { return null }
35
+ }
36
+
37
+ async function saveCache(path, value) {
38
+ await mkdir(dirname(path), {recursive:true})
39
+ const temporary = path + '-写入-' + process.pid + '-' + randomUUID() + '.tmp'
40
+ try {
41
+ await writeFile(temporary, value.type === 'image' ? value.body : JSON.stringify(value), {flag:'wx',mode:0o600})
42
+ await rename(temporary, path)
43
+ } finally { await rm(temporary, {force:true}) }
44
+ }
45
+
46
+ export function 创建任务廊预览({renderer, ffmpeg = process.env.BLUEPRINT_PREVIEW_FFMPEG || 'ffmpeg', run = execute, cacheDir = join(tmpdir(), 'blueprint-task-gallery-previews'), maxEntries = 64} = {}) {
47
+ const cache = new Map(), pending = new Map(), waiting = []
48
+ let active = 0
49
+ const enter = () => new Promise(resolve => { if(active < 2) {active++; resolve()} else waiting.push(resolve) })
50
+ const leave = () => { const next = waiting.shift(); if(next) next(); else active-- }
51
+ return async function preview(root, {session, path}) {
52
+ if(typeof path !== 'string' || !path || path.length > 8192) throw new Error('材料路径无效')
53
+ const url = 网页入口(path)
54
+ let file, info, kind = 'web'
55
+ if(!url) {
56
+ const entry = 产物路径(root, path, {any:true,includeTemporary:true,includeEvidence:true})
57
+ if(!entry) throw new Error('材料路径无效')
58
+ path = entry.path
59
+ file = await 安全产物文件(root, path, {preview:true})
60
+ info = await stat(file)
61
+ if(!info.isFile() && !info.isDirectory()) throw new Error('材料不是普通文件或目录')
62
+ kind = info.isDirectory() ? 'directory' : 产物类型(path)
63
+ }
64
+ // 会话只用于首次渲染授权;同一项目的同一文件跨节点、重启复用预览。
65
+ // 远程网页没有本地修改时间,保留第一次成功的截图,不定时重新访问。
66
+ const key = JSON.stringify([cacheVersion,root,url || path,kind,info && stamp(info)])
67
+ const saved = cache.get(key)
68
+ if(saved) return saved
69
+ if(pending.has(key)) return pending.get(key)
70
+ const image = ['web','video','audio'].includes(kind)
71
+ const name = kind === 'web' ? '网页缩略图' : kind === 'video' ? '视频缩略图' : kind === 'audio' ? '音乐频谱' : kind === 'directory' ? '目录信息' : '文档信息'
72
+ const hash = createHash('sha256').update(key).digest('hex')
73
+ const cachedFile = join(cacheDir, '预览分片-' + hash.slice(0,2), name + '-' + hash + (image ? '.png' : '.json'))
74
+ const remember = value => {
75
+ cache.delete(key); cache.set(key, value)
76
+ while(cache.size > maxEntries) cache.delete(cache.keys().next().value)
77
+ return value
78
+ }
79
+ const job = (async () => {
80
+ const disk = await readCache(cachedFile, image)
81
+ if(disk) return remember(disk)
82
+ await enter()
83
+ try {
84
+ let value
85
+ if(kind === 'web') {
86
+ if(!renderer) throw new Error('网页预览浏览器暂不可用')
87
+ const body = await renderer.render({session, ...(url ? {url} : {path}), width:960, height:540, waitMs:700}, AbortSignal.timeout(20000))
88
+ value = {type:'image',body}
89
+ } else if(kind === 'video' || kind === 'audio') {
90
+ const filter = kind === 'audio'
91
+ ? 'atrim=duration=30,showspectrumpic=s=640x360:legend=disabled:color=viridis:scale=log:fscale=log'
92
+ : 'thumbnail=30,scale=640:360:force_original_aspect_ratio=increase,crop=640:360,setsar=1'
93
+ const {stdout} = await run(ffmpeg, ['-hide_banner','-loglevel','error','-nostdin','-threads','1','-filter_threads','1','-filter_complex_threads','1',
94
+ '-protocol_whitelist','file,pipe','-t',kind === 'audio' ? '30' : '3','-i',file,kind === 'audio' ? '-lavfi' : '-vf',filter,
95
+ '-frames:v','1','-threads','1','-f','image2pipe','-vcodec','png','pipe:1'], {encoding:'buffer',timeout:15000,maxBuffer:4*1024*1024})
96
+ value = {type:'image',body:stdout}
97
+ } else {
98
+ value = {type:'info',kind,path,format:extname(path).slice(1).toUpperCase(),bytes:info.size,modified:info.mtimeMs}
99
+ if(kind === 'document' || /\.(csv|tsv|rst)$/i.test(path)) value.excerpt = await excerpt(file)
100
+ if(kind === 'directory') {
101
+ value.entries = []
102
+ const directory = await opendir(file)
103
+ for await(const entry of directory) {
104
+ if(entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())
105
+ || !产物路径(root, path + '/' + entry.name, {any:true,includeTemporary:true,includeEvidence:true})) continue
106
+ value.entries.push({name:entry.name,directory:entry.isDirectory()})
107
+ if(value.entries.length === 8) break
108
+ }
109
+ }
110
+ }
111
+ if(value.type === 'image' && !validPNG(value.body)) throw new Error('没有取得有效缩略图')
112
+ await saveCache(cachedFile, value)
113
+ return remember(value)
114
+ } finally { leave() }
115
+ })().finally(() => pending.delete(key))
116
+ pending.set(key, job)
117
+ return job
118
+ }
119
+ }
@@ -0,0 +1,14 @@
1
+ /** 目录沿用原来的有效期;图纸要求新鲜快照,并发调用只扫一次原生目录。 */
2
+ export function 创建会话快照读取(read, { ttl = 1500, now = Date.now } = {}) {
3
+ let cached, started = 0, pending
4
+ return function snapshots(fresh = false) {
5
+ if (pending) return pending
6
+ if (!fresh && cached && now() - started < ttl) return Promise.resolve(cached)
7
+ started = now()
8
+ const request = Promise.resolve().then(read)
9
+ pending = request
10
+ request.then(value => { cached = value }, () => { cached = undefined })
11
+ .finally(() => { if (pending === request) pending = undefined })
12
+ return request
13
+ }
14
+ }
@@ -0,0 +1,87 @@
1
+ // 从旧系统 node/src/产物.js 拷来(2026-11-09 搬回 Blueprint 前端时,旧包不复活,只拷这些纯小工具)。
2
+ /** 展示协议:只检查入口,事实保存在工具回执,不另建登记账。 */
3
+ import { realpath, stat } from 'node:fs/promises'
4
+ import { resolve, relative, sep, extname, basename } from 'node:path'
5
+ const 工具临时目录名 = '.blueprint-tmp'
6
+
7
+ export const 文本产物扩展名 = 'md markdown txt js mjs cjs ts tsx jsx css scss json jsonl yaml yml toml xml ini cfg gd gdshader glsl vert frag py sh bash c h cpp hpp rs go lua sql tscn tres godot log'.split(' ')
8
+
9
+ export const 产物参数 = {
10
+ type:'object', additionalProperties:false, required:['entry'], properties:{
11
+ entry:{type:'string', description:'项目内的文件或目录路径,或 HTTP(S) 网页地址'},
12
+ title:{type:'string', maxLength:160, description:'便于用户辨认的成果名称,省略则使用文件名'},
13
+ cover:{type:'string', description:'可选:项目内现成的截图封面路径'},
14
+ description:{type:'string', maxLength:600, description:'可选:简短使用说明或需要用户查看的内容'},
15
+ opening:{type:'string', enum:['auto','preview','browser','system','reveal'], description:'默认 auto;preview 内置预览,browser 网页,system 由用户点击后用系统默认应用打开,reveal 在 Finder 定位。不接受命令或启动参数'},
16
+ },
17
+ }
18
+
19
+ export function 网页入口(value) {
20
+ try {
21
+ const u = new URL(value)
22
+ if (!['http:','https:'].includes(u.protocol) || u.username || u.password) return null
23
+ return u.href
24
+ } catch { return null }
25
+ }
26
+
27
+ /** 隐藏段只开放原生 worktree 子树;目录浏览可经过它的两层父目录。 */
28
+ export function 允许预览路径(path, { includeTemporary = false, includeEvidence = false, includeWorktreeParents = false } = {}) {
29
+ const parts = String(path || '').split('/')
30
+ return !!path && !path.startsWith('/') && parts.every((part, index) =>
31
+ part && (!part.startsWith('.')
32
+ || (part === '.agents' && ((parts[index + 1] === 'worktrees' && parts[index + 2] && !parts[index + 2].startsWith('.'))
33
+ || (includeWorktreeParents && (index === parts.length - 1 || (index === parts.length - 2 && parts[index + 1] === 'worktrees')))))
34
+ || (index === 0 && ((includeTemporary && part === 工具临时目录名) || (includeEvidence && part === '.blueprint-evidence')))))
35
+ }
36
+
37
+ /** 画廊过滤临时文件;显式点击可打开工具临时目录,仍排除隐藏配置和系统目录。 */
38
+ /**
39
+ * 节点自己拿出来给人看、交回时附上的(present_artifact、finish 的 files、网页截图):临时目录和证据目录也认。
40
+ * 过程里的截图、录屏、参照板本来就该放在那里;只认成品目录,节点就得把它们搬进作品才展示得出来(11-03 塔防游戏 spark 的参照板)。
41
+ */
42
+ export const 节点展示范围 = Object.freeze({ includeTemporary: true, includeEvidence: true })
43
+
44
+ export function 允许产物路径(path, options = {}) {
45
+ return 允许预览路径(path, { ...options, includeWorktreeParents: false })
46
+ && !path.split('/').some(part => ['node_modules','系统文档','旧','坟场'].includes(part))
47
+ }
48
+
49
+ async function 本地入口(root, value, options) {
50
+ if (typeof value !== 'string' || !value.trim() || /[\0\r\n]/.test(value) || /^[a-z][a-z\d+.-]*:/i.test(value)) throw new Error('请提供项目内文件或目录')
51
+ const base = await realpath(root), cwd = await realpath(resolve(base, options.cwd || '.'))
52
+ if (cwd !== base && !cwd.startsWith(base + sep)) throw new Error('当前目录须位于本项目内')
53
+ const file = await realpath(resolve(cwd, value.trim()))
54
+ const path = relative(base, file).split(sep).join('/')
55
+ if (!允许产物路径(path, options)) throw new Error('入口须位于项目产物目录内')
56
+ const st = await stat(file)
57
+ if (!st.isFile() && !st.isDirectory()) throw new Error('入口不是普通文件或目录')
58
+ return {path, directory:st.isDirectory()}
59
+ }
60
+
61
+ export async function 检查产物(root, input, options = {}) {
62
+ if (!input || typeof input.entry !== 'string') throw new Error('缺少 entry')
63
+ const url = 网页入口(input.entry), local = url ? null : await 本地入口(root, input.entry, options)
64
+ let opening = input.opening || 'auto'
65
+ if (!['auto','preview','browser','system','reveal'].includes(opening)) throw new Error('不支持的打开方式')
66
+ const extension = extname(local?.path || '').slice(1).toLowerCase()
67
+ const previewable = 文本产物扩展名.includes(extension) || /^(png|jpe?g|gif|webp|svg|avif|bmp|html?|pdf|mp4|webm|mov|mp3|wav|ogg|m4a)$/.test(extension)
68
+ // 音视频交给系统播放器(Mac 是 QuickTime),不在 Blueprint 里另搭浏览器放:dsh 预览栏本来就没有播放器,
69
+ // dsh 桌面版里拼出的预览网页地址也开不了(11-22 用户:「是不是这些应该直接链接用户的播放器」)。点名 preview 仍可在网页里放。
70
+ const systemOpenable = /^(app|command|exe|bat|cmd|ppt|pptx|odp|doc|docx|xls|xlsx|csv|mp4|webm|mov|m4v|mp3|wav|ogg|m4a|aac|flac)$/.test(extension)
71
+ if (url) {
72
+ if (!['auto','browser'].includes(opening)) throw new Error('网页地址只能在浏览器打开')
73
+ opening = 'browser'
74
+ } else if (opening === 'auto') opening = previewable && !systemOpenable && !local.directory ? 'preview' : 'system'
75
+ else if (opening === 'preview' && (local.directory || !previewable)) throw new Error('该格式请使用 reveal 定位文件')
76
+ else if (opening === 'browser' && !/^html?$/.test(extension)) throw new Error('browser 需要网页地址或 HTML 文件')
77
+ const title = input.title === undefined ? (url ? new URL(url).hostname : basename(local.path)) : input.title
78
+ if (typeof title !== 'string' || !title.trim() || title.length > 160) throw new Error('title 须为 1–160 字')
79
+ if (input.description !== undefined && (typeof input.description !== 'string' || input.description.length > 600)) throw new Error('description 须不超过 600 字')
80
+ let coverPath
81
+ if (input.cover) {
82
+ const cover = await 本地入口(root, input.cover, options)
83
+ if (cover.directory || !/\.(png|jpe?g|webp|gif|avif)$/i.test(cover.path)) throw new Error('封面须为项目内的图片文件')
84
+ coverPath = cover.path
85
+ }
86
+ return {path:url || local.path, title:title.trim(), description:input.description || '', opening, coverPath, declared:true, directory:!!local?.directory}
87
+ }