@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,385 @@
1
+ /** Studio 的 API 连接管理:配置与 Key 仍由 dsh 的 settings / credentials 服务持久化。 */
2
+ import { randomUUID } from 'node:crypto'
3
+ import { readdir, readFile } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { createMediaManager, MEDIA_PRESETS, MEDIA_PROTOCOLS, MEDIA_OPERATIONS } from './借来的/媒体服务.js'
6
+
7
+ const NS = 'llm-pi-ai'
8
+ // dsh 0.2 原生 DeepSeek 的默认地址:Messages 兼容根(llm-deepseek 的 PUBLIC_BASE_URL)。
9
+ const NATIVE_BASE_URL = 'https://api.deepseek.com/anthropic'
10
+ const DELETED_KEY_PREFIX = 'BLUEPRINT_API_DELETED_'
11
+ const isDeleted = profile => profile?.apiKeyEnv?.startsWith(DELETED_KEY_PREFIX)
12
+ const PROTOCOLS = new Set(['openai-completions', 'openai-responses', 'anthropic-messages'])
13
+ const FORBIDDEN = new Set(['__proto__', 'prototype', 'constructor'])
14
+
15
+ /** 所有模型连接共用原生有界退避;显式设定过的策略继续沿用。 */
16
+ export function 补默认重试策略(profile) {
17
+ if (!profile || isDeleted(profile) || profile.retryPolicy !== undefined) return profile
18
+ return { ...profile, retryPolicy: {
19
+ mode: 'normal', maxRetries: 5,
20
+ backoff: { initialDelayMs: 10000, maxDelayMs: 60000, jitterRatio: 0.1 },
21
+ } }
22
+ }
23
+
24
+ /** App 开机时给已有模型连接补默认值,只写缺失的重试字段。 */
25
+ export async function 补已有连接重试策略(settings) {
26
+ if (!settings?.writable) return 0
27
+ let count = 0
28
+ for (const d of settings.describe().filter(x => [NS, 'llm-deepseek'].includes(x.ns))) {
29
+ const profiles = d.ns === NS ? Object.entries(d.value?.providers || {}).map(([id, profile]) => [profile, ['providers', id]]) : [[d.value, []]]
30
+ const ops = profiles.flatMap(([profile, path]) => {
31
+ const next = 补默认重试策略(profile)
32
+ return next === profile ? [] : [{ op: 'set', path: [...path, 'retryPolicy'], value: next.retryPolicy }]
33
+ })
34
+ if (ops.length) await settings.mutate(d.ns, ops, d.revision)
35
+ count += ops.length
36
+ }
37
+ return count
38
+ }
39
+ export const API_PRESETS = [
40
+ { id: 'deepseek', name: 'DeepSeek', baseURL: 'https://api.deepseek.com', api: 'openai-completions' },
41
+ { id: 'openai', name: 'OpenAI', baseURL: 'https://api.openai.com/v1', api: 'openai-responses' },
42
+ { id: 'anthropic', name: 'Anthropic', baseURL: 'https://api.anthropic.com', api: 'anthropic-messages' },
43
+ { id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', api: 'openai-completions' },
44
+ { id: 'local', name: '本地模型', baseURL: 'http://localhost:11434/v1', api: 'openai-completions' },
45
+ { id: 'custom', name: '自定义 API', baseURL: '', api: 'openai-completions' },
46
+ ]
47
+
48
+ function service(ctx, name) {
49
+ const value = ctx.get(name)
50
+ if (!value) throw new Error(`当前服务没有启用 ${name},无法管理 API 连接`)
51
+ return value
52
+ }
53
+ function at(object, path) { return path.reduce((v, k) => v?.[k], object) }
54
+ function descriptor(settings, ns) {
55
+ const d = settings.describe().find(x => x.ns === ns)
56
+ if (!d) throw new Error(`当前服务没有启用 ${ns} 配置`)
57
+ return d
58
+ }
59
+ function routeId(id) {
60
+ if (typeof id !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(id) || FORBIDDEN.has(id)) throw new Error('连接标识只能使用小写字母、数字和连字符,以字母开头,最多 64 字符')
61
+ return id
62
+ }
63
+ export function endpoint(value) {
64
+ let url
65
+ try { url = new URL(String(value || '').trim()) } catch { throw new Error('请填写完整的 API 地址,例如 https://api.example.com/v1') }
66
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.hash || url.search) throw new Error('API 地址须为 HTTP(S) 地址,不含密码、查询参数或片段')
67
+ return url.href.replace(/\/+$/, '')
68
+ }
69
+ function integer(value, label) {
70
+ if (value === '' || value === null || value === undefined) return undefined
71
+ const n = Number(value)
72
+ if (!Number.isSafeInteger(n) || n < 1 || n > 10_000_000) throw new Error(`${label}须为 1 到 10000000 的整数`)
73
+ return n
74
+ }
75
+ export function normalizeModels(models, previous = [], native = false) {
76
+ if (!Array.isArray(models) || !models.length || models.length > 200) throw new Error('请至少添加一个模型,最多 200 个')
77
+ const seen = new Set()
78
+ return models.map(m => {
79
+ const id = String(m.id || '').trim()
80
+ if (!id || id.length > 200 || /[\x00-\x1f]/.test(id)) throw new Error('模型 ID 不能为空,且须在 200 字符以内')
81
+ if (seen.has(id)) throw new Error(`模型 ID 重复:${id}`)
82
+ seen.add(id)
83
+ const old = previous.find(x => x.id === id) || {}
84
+ const next = { ...old, id, name: String(m.name || id).trim().slice(0, 200) }
85
+ for (const [k, label] of [['contextWindow', '上下文长度'], ['maxTokens', '最大输出']]) {
86
+ const n = integer(m[k], label)
87
+ if (n === undefined) delete next[k]; else next[k] = n
88
+ }
89
+ if (!native) {
90
+ if (m.input === 'image') next.input = [...new Set([...(old.input || []), 'text', 'image'])]
91
+ else if (m.input === 'text') next.input = [...new Set(['text', ...(old.input || []).filter(x => x !== 'image')])]
92
+ else if (m.input === 'auto') delete next.input
93
+ if (m.reasoning === 'off') next.reasoningEfforts = false
94
+ else if (m.reasoning === 'on') next.reasoningEfforts = old.reasoningEfforts && typeof old.reasoningEfforts === 'object' ? old.reasoningEfforts : { off: null, low: 'low', medium: 'medium', high: 'high' }
95
+ else if (m.reasoning === 'auto') delete next.reasoningEfforts
96
+ }
97
+ return next
98
+ })
99
+ }
100
+ function safeModel(m) {
101
+ return {
102
+ id: m.id, name: m.name || m.id, contextWindow: m.contextWindow, maxTokens: m.maxTokens,
103
+ input: m.input?.includes('image') ? 'image' : m.input?.length ? 'text' : 'auto',
104
+ reasoning: m.reasoningEfforts === false ? 'off' : m.reasoningEfforts ? 'on' : 'auto',
105
+ }
106
+ }
107
+ function publicError(error, secrets = []) {
108
+ let message = String(error?.message || error || '操作失败')
109
+ for (const key of secrets) if (key) message = message.split(key).join('[已隐藏]')
110
+ return message.replace(/\bsk-[A-Za-z0-9_-]{6,}/g, '[已隐藏]').slice(0, 600)
111
+ }
112
+ async function boundedJson(response) {
113
+ const reader = response.body?.getReader()
114
+ if (!reader) throw new Error('服务返回了空响应')
115
+ const chunks = []; let size = 0
116
+ try {
117
+ for (;;) {
118
+ const { value, done } = await reader.read()
119
+ if (done) break
120
+ size += value.byteLength
121
+ if (size > 4 * 1024 * 1024) throw new Error('服务返回的数据超过 4MB')
122
+ chunks.push(value)
123
+ }
124
+ } finally { await reader.cancel().catch(() => {}) }
125
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { throw new Error('服务返回的不是有效 JSON,请检查 API 地址和协议') }
126
+ }
127
+
128
+ export function createConnectionManager(ctx, { projectRoot, fetch: fetcher = globalThis.fetch } = {}) {
129
+ const media = createMediaManager(ctx)
130
+ let tail = Promise.resolve()
131
+ const exclusive = fn => { const run = tail.then(fn); tail = run.catch(() => {}); return run }
132
+ const directory = () => service(ctx, 'llm').listConfigurableProviders()
133
+ const find = id => {
134
+ const item = directory().find(x => x.provider === id)
135
+ if (!item || !['llm-deepseek', NS].includes(item.settingsNs)) throw new Error('这个连接不存在,或不属于可管理的 API 连接')
136
+ if (isDeleted(at(descriptor(service(ctx, 'settings'), item.settingsNs).value, item.settingsPath))) throw new Error('这个连接已删除')
137
+ return item
138
+ }
139
+ async function modelReferences(id) {
140
+ if (!projectRoot) return []
141
+ const roots = typeof projectRoot === 'function' ? projectRoot() : [projectRoot]
142
+ const names = await Promise.all(roots.map(async root => {
143
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
144
+ return Promise.all(entries.filter(e => e.isDirectory() && !e.isSymbolicLink()).map(async e => {
145
+ try { const model = JSON.parse(await readFile(join(root, e.name, '系统文档', '模型.json'), 'utf8')); return model.provider === id ? { name: e.name, model: model.model } : null } catch { return null }
146
+ }))
147
+ }))
148
+ return names.flat().filter(Boolean)
149
+ }
150
+ async function usedProjects(id) { return (await modelReferences(id)).map(x => x.name) }
151
+ async function modelCatalog() {
152
+ const descriptors = service(ctx, 'settings').describe()
153
+ const removed = new Set(directory().filter(item => ['llm-deepseek', NS].includes(item.settingsNs)
154
+ && isDeleted(at(descriptors.find(d => d.ns === item.settingsNs)?.value, item.settingsPath))).map(item => item.provider))
155
+ const cat = await service(ctx, 'sessionController').modelCatalog()
156
+ return {
157
+ ...cat,
158
+ default: cat.default && (cat.routableProviders || []).includes(cat.default.provider) && !removed.has(cat.default.provider) ? cat.default : null,
159
+ groups: (cat.groups || []).filter(g => !removed.has(g.id)),
160
+ failures: (cat.failures || []).filter(f => !removed.has(f.id)),
161
+ routableProviders: (cat.routableProviders || []).filter(id => !removed.has(id)),
162
+ removedProviders: [...removed],
163
+ }
164
+ }
165
+ async function list() {
166
+ const settings = service(ctx, 'settings'), credentials = service(ctx, 'credentials')
167
+ const descriptors = settings.describe(), cat = await modelCatalog(), active = new Set(cat.routableProviders || [])
168
+ const rows = []
169
+ for (const item of directory()) {
170
+ if (!['llm-deepseek', NS].includes(item.settingsNs)) continue
171
+ const d = descriptors.find(x => x.ns === item.settingsNs)
172
+ if (!d) continue
173
+ const profile = at(d.value, item.settingsPath)
174
+ if (isDeleted(profile)) continue
175
+ if (!profile && !active.has(item.provider)) continue
176
+ const p = profile || {}, group = (cat.groups || []).find(x => x.id === item.provider)
177
+ const ref = p.apiKeyEnv || (item.settingsNs === 'llm-deepseek' ? 'DEEPSEEK_API_KEY' : '')
178
+ const key = ref ? await credentials.describe(ref) : { configured: false, writable: true }
179
+ rows.push({
180
+ id: item.provider, name: p.displayName || item.displayName || item.provider, namespace: item.settingsNs,
181
+ revision: d.revision, native: item.settingsNs === 'llm-deepseek',
182
+ editable: settings.writable, deletable: settings.writable,
183
+ baseURL: p.baseURL || (item.settingsNs === 'llm-deepseek' ? NATIVE_BASE_URL : ''),
184
+ api: item.settingsNs === 'llm-deepseek' ? 'anthropic-messages' : p.api || 'openai-completions', defaultContextWindow: p.defaultContextWindow, defaultMaxTokens: p.defaultMaxTokens,
185
+ key: { configured: !!key.configured, writable: !!key.writable, source: key.source || '' },
186
+ models: (p.models?.length ? p.models : group?.models || []).map(safeModel),
187
+ active: active.has(item.provider), error: item.error ? publicError(item.error) : '', projects: await usedProjects(item.provider),
188
+ })
189
+ }
190
+ return { providers: [...rows,...await media.list()], presets: [...API_PRESETS,...MEDIA_PRESETS], mediaProtocols:MEDIA_PROTOCOLS, mediaOperations:MEDIA_OPERATIONS, default: cat.default, writable: settings.writable, revision: descriptors.find(x => x.ns === NS)?.revision }
191
+ }
192
+ async function save(body) {
193
+ return exclusive(async () => {
194
+ if (body.kind === 'media') {
195
+ if (directory().some(p=>p.provider === body.id)) throw new Error('连接标识已被对话 API 使用,请换一个')
196
+ return media.save(body)
197
+ }
198
+ if ((await media.list()).some(p=>p.id === body.id)) throw new Error('连接标识已被媒体 API 使用,请换一个')
199
+ const settings = service(ctx, 'settings'), credentials = service(ctx, 'credentials')
200
+ if (!settings.writable) throw new Error('当前配置只读,无法保存')
201
+ const id = routeId(body.id), item = body.existing ? find(id) : { provider: id, settingsNs: NS, settingsPath: ['providers', id] }
202
+ const d = descriptor(settings, item.settingsNs), stored = at(d.value, item.settingsPath), old = isDeleted(stored) ? {} : stored || {}
203
+ if (!body.existing && ((stored && !isDeleted(stored)) || directory().some(x => x.provider === id && x.settingsNs !== NS))) throw new Error('这个连接标识已被使用,请换一个')
204
+ const native = item.settingsNs === 'llm-deepseek'
205
+ // 原生 DeepSeek 的地址、协议和模型归 dsh 适配器(0.2 起走 Messages 接口);这里只换 Key,不把别的写进它的配置。
206
+ const profile = 补默认重试策略(native ? { ...old } : { ...old, baseURL: endpoint(body.baseURL), models: normalizeModels(body.models, old.models) })
207
+ if (body.existing && !native) {
208
+ const keep = new Set(profile.models.map(m => m.id)), removed = new Set((old.models || []).filter(m => !keep.has(m.id)).map(m => m.id))
209
+ const selection = ctx.get('agentDefaultModel')?.currentSelection()
210
+ if (selection?.provider === id && removed.has(selection.model)) throw new Error('请先切换新项目默认模型,再移除这个模型')
211
+ const inUse = (await modelReferences(id)).filter(x => removed.has(x.model))
212
+ if (inUse.length) throw new Error(`请先切换这些项目的模型,再移除模型:${inUse.slice(0, 5).map(x => x.name).join('、')}`)
213
+ }
214
+ if (!native) {
215
+ if (!PROTOCOLS.has(body.api)) throw new Error('请选择支持的 API 协议')
216
+ profile.api = body.api; profile.displayName = String(body.name || id).trim().slice(0, 100)
217
+ for (const key of ['defaultContextWindow', 'defaultMaxTokens']) {
218
+ const n = integer(body[key], key === 'defaultContextWindow' ? '默认上下文长度' : '默认最大输出')
219
+ if (n === undefined) delete profile[key]; else profile[key] = n
220
+ }
221
+ }
222
+ let key = typeof body.apiKey === 'string' ? body.apiKey.trim() : ''
223
+ if (!key && !old.apiKeyEnv && !native && ['localhost', '127.0.0.1', '[::1]'].includes(new URL(profile.baseURL).hostname)) key = 'local-no-auth'
224
+ if (key.length > 8192 || /[\r\n]/.test(key)) throw new Error('API Key 格式不正确')
225
+ let newRef, previous
226
+ if (key) {
227
+ newRef = `BLUEPRINT_API_${id.replace(/-/g, '_').toUpperCase()}_${randomUUID().slice(0, 8).toUpperCase()}`
228
+ previous = await credentials.resolve(newRef)
229
+ await credentials.set(newRef, key)
230
+ profile.apiKeyEnv = newRef
231
+ } else if (!profile.apiKeyEnv && !native) {
232
+ // 无 Key 的本地服务也显式声明其凭据入口,避免使用其他服务商的环境凭据。
233
+ profile.apiKeyEnv = `BLUEPRINT_API_${id.replace(/-/g, '_').toUpperCase()}`
234
+ }
235
+ try {
236
+ await settings.mutate(item.settingsNs, [{ op: 'set', path: item.settingsPath, value: profile }], body.revision ?? d.revision)
237
+ } catch (error) {
238
+ if (newRef) { try { if (previous?.value) await credentials.set(newRef, previous.value); else await credentials.unset(newRef) } catch { throw new Error('配置未保存,临时 Key 清理失败;请重新保存后检查凭据存储') } }
239
+ throw new Error(publicError(error, [key]))
240
+ }
241
+ // 只有本系统生成且没有其他连接引用的旧 Key 才回收,环境和外部凭据不改动。
242
+ let warning = ''
243
+ if (newRef && old.apiKeyEnv?.startsWith('BLUEPRINT_API_') && old.apiKeyEnv !== newRef) {
244
+ try { await cleanupKey(old.apiKeyEnv) } catch { warning = '连接已保存,旧 Key 未能清理' }
245
+ }
246
+ return { id, warning }
247
+ })
248
+ }
249
+ async function cleanupKey(ref) {
250
+ if (!ref?.startsWith('BLUEPRINT_API_')) return
251
+ const settings = service(ctx, 'settings')
252
+ for (const d of settings.describe()) {
253
+ if (d.ns === 'llm-deepseek' && d.value?.apiKeyEnv === ref) return
254
+ if (d.ns === NS && Object.values(d.value?.providers || {}).some(p => p.apiKeyEnv === ref)) return
255
+ }
256
+ const credentials = service(ctx, 'credentials'), info = await credentials.describe(ref)
257
+ if (info.writable) await credentials.unset(ref)
258
+ }
259
+ async function remove(body) {
260
+ return exclusive(async () => {
261
+ if ((await media.list()).some(p=>p.id === body.id)) return media.remove(body)
262
+ const item = find(routeId(body.id)), settings = service(ctx, 'settings'), d = descriptor(settings, item.settingsNs)
263
+ if (!settings.writable) throw new Error('当前配置只读,无法删除')
264
+ const profile = at(d.value, item.settingsPath)
265
+ // unset 会重新继承内置/部署层;用不带凭据的删除标记覆盖它,重启后仍保持删除。
266
+ const op = item.settingsNs === 'llm-deepseek' || at(d.base, item.settingsPath)
267
+ ? { op: 'set', path: item.settingsPath, value: { ...profile, apiKeyEnv: `${DELETED_KEY_PREFIX}${randomUUID().replaceAll('-', '').toUpperCase()}` } }
268
+ : { op: 'unset', path: item.settingsPath }
269
+ await settings.mutate(item.settingsNs, [op], body.revision ?? d.revision)
270
+ let warning = ''
271
+ try { await cleanupKey(profile?.apiKeyEnv) } catch { warning = '连接已删除,托管 Key 未能清理' }
272
+ return { id: body.id, warning }
273
+ })
274
+ }
275
+ async function draft(body) {
276
+ let stored = {}, native = false
277
+ if (body.existing) { const item = find(routeId(body.id)); stored = at(descriptor(service(ctx, 'settings'), item.settingsNs).value, item.settingsPath) || {}; native = item.settingsNs === 'llm-deepseek' }
278
+ const baseURL = endpoint(native ? stored.baseURL || NATIVE_BASE_URL : body.baseURL || stored.baseURL)
279
+ const api = native ? 'anthropic-messages' : body.api || stored.api
280
+ if (!PROTOCOLS.has(api)) throw new Error('请选择支持的 API 协议')
281
+ let apiKey = String(body.apiKey || '').trim()
282
+ if (!apiKey) {
283
+ const ref = stored.apiKeyEnv || (native ? 'DEEPSEEK_API_KEY' : '')
284
+ if (ref) apiKey = (await service(ctx, 'credentials').resolve(ref))?.value || ''
285
+ }
286
+ if (!apiKey && !['localhost', '127.0.0.1', '[::1]'].includes(new URL(baseURL).hostname)) throw new Error('请先填写 API Key')
287
+ const headers = { ...stored.headers, 'Content-Type': 'application/json' }
288
+ if (api === 'anthropic-messages') { headers['x-api-key'] = apiKey; headers['anthropic-version'] = '2023-06-01' }
289
+ else if (apiKey) headers.Authorization = `Bearer ${apiKey}`
290
+ return { baseURL, api, apiKey, headers, native }
291
+ }
292
+ async function request(spec, suffix, options = {}) {
293
+ const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000)
294
+ try {
295
+ const response = await fetcher(`${spec.baseURL}${suffix}`, { ...options, headers: spec.headers, signal: controller.signal, redirect: 'error' })
296
+ if (!response.ok) {
297
+ await response.body?.cancel()
298
+ const hints = { 401: 'API Key 无效或已过期', 403: 'API Key 没有权限,或账户受到限制', 404: '接口或模型不存在,请检查地址、协议和模型 ID', 429: '额度不足或请求受到限流' }
299
+ throw new Error(`${hints[response.status] || 'API 服务返回错误'}(HTTP ${response.status})`)
300
+ }
301
+ return await boundedJson(response)
302
+ } catch (error) {
303
+ if (controller.signal.aborted) throw new Error('连接超时,请检查 API 地址和网络')
304
+ throw new Error(publicError(error, [spec.apiKey, ...Object.values(spec.headers)]))
305
+ } finally { clearTimeout(timer) }
306
+ }
307
+ async function discover(body) {
308
+ if (body.kind === 'media') return media.discover(body,fetcher)
309
+ const spec = await draft(body)
310
+ const root = spec.api === 'anthropic-messages' ? spec.baseURL.replace(/\/v1$/, '') : spec.baseURL
311
+ const data = await request({ ...spec, baseURL: root }, spec.api === 'anthropic-messages' ? '/v1/models?limit=1000' : '/models')
312
+ if (!Array.isArray(data.data) && !Array.isArray(data.models)) throw new Error('服务没有返回模型列表,请手动添加模型 ID')
313
+ const seen = new Set(), models = []
314
+ for (const item of data.data || data.models) {
315
+ const id = item.id || item.name
316
+ if (typeof id !== 'string' || !id.trim() || id.length > 200 || seen.has(id)) continue
317
+ seen.add(id)
318
+ models.push({ id, name: item.display_name || item.name || id, contextWindow: item.context_length || item.context_window, maxTokens: item.max_output_tokens })
319
+ if (models.length >= 200) break
320
+ }
321
+ if (!models.length) throw new Error('服务返回了空模型列表,请手动添加模型 ID')
322
+ return { models, message: `已获取 ${models.length} 个模型;获取列表不会验证模型能否生成回复` }
323
+ }
324
+ async function test(body) {
325
+ if (body.kind === 'media') return media.check(body)
326
+ const spec = await draft(body), model = String(body.model || '').trim()
327
+ if (!model || model.length > 200) throw new Error('请先选择一个要测试的模型')
328
+ let suffix, payload
329
+ if (spec.api === 'anthropic-messages') {
330
+ spec.baseURL = spec.baseURL.replace(/\/v1$/, ''); suffix = '/v1/messages'
331
+ payload = { model, max_tokens: 16, messages: [{ role: 'user', content: 'Reply with OK.' }] }
332
+ // DeepSeek 的模型默认先思考,16 个 token 只够思考;验证只看能不能回话。
333
+ if (spec.native) payload.thinking = { type: 'disabled' }
334
+ } else if (spec.api === 'openai-responses') {
335
+ suffix = '/responses'; payload = { model, input: 'Reply with OK.', max_output_tokens: 64 }
336
+ } else {
337
+ suffix = '/chat/completions'; payload = { model, messages: [{ role: 'user', content: 'Reply with OK.' }], max_tokens: 32, stream: false }
338
+ if (new URL(spec.baseURL).hostname === 'api.deepseek.com') payload.thinking = { type: 'disabled' }
339
+ }
340
+ const start = Date.now(), data = await request(spec, suffix, { method: 'POST', body: JSON.stringify(payload) })
341
+ const valid = spec.api === 'openai-responses' ? Array.isArray(data.output) && data.output.length > 0 : spec.api === 'anthropic-messages' ? Array.isArray(data.content) && data.content.length > 0 : Array.isArray(data.choices) && data.choices.some(x => x.message)
342
+ if (!valid || data.error) throw new Error('服务虽返回成功状态,但没有有效的模型响应,请检查协议')
343
+ return { model, latency: Date.now() - start, message: '认证与模型响应正常' }
344
+ }
345
+ async function setDefault(body) {
346
+ return exclusive(async () => {
347
+ find(routeId(body.id))
348
+ const model = await service(ctx, 'llm').resolveCallConfig({ provider: routeId(body.id), model: String(body.model || '') })
349
+ await service(ctx, 'agentDefaultModel').saveSelection({ provider: model.provider, model: model.model, ...(model.reasoningEffort ? { reasoningEffort: model.reasoningEffort } : {}) })
350
+ return { provider: model.provider, model: model.model }
351
+ })
352
+ }
353
+ return { list, save, remove, discover, test, setDefault, modelCatalog }
354
+ }
355
+
356
+ /** 管理配置的浏览器请求只接受同源 JSON,不借用 Agent 的工具和权限。 */
357
+ export function validateConnectionRequest(req) {
358
+ const origin = req.headers.origin
359
+ if (origin) {
360
+ let host
361
+ try { host = new URL(origin).host } catch { throw new Error('请求来源不合法') }
362
+ if (host !== req.headers.host) throw new Error('不接受其他页面发起的 API 管理请求')
363
+ }
364
+ if (req.method === 'POST' && !String(req.headers['content-type'] || '').toLowerCase().startsWith('application/json')) throw new Error('API 管理请求须使用 JSON')
365
+ }
366
+ export function connectionHandler(manager, json) {
367
+ const methods = { save: manager.save, delete: manager.remove, discover: manager.discover, test: manager.test, default: manager.setDefault }
368
+ return async (req, res, rel) => {
369
+ let secret = ''
370
+ try {
371
+ validateConnectionRequest(req)
372
+ if (rel === '/api/connections' && req.method === 'GET') return json(res, 200, { ok: true, value: await manager.list() })
373
+ const action = rel.slice('/api/connections/'.length)
374
+ const method = Object.hasOwn(methods, action) ? methods[action] : null
375
+ if (!method || req.method !== 'POST') return json(res, 405, { ok: false, message: '不支持的 API 管理操作' })
376
+ let raw = '', size = 0
377
+ for await (const chunk of req) { size += Buffer.byteLength(chunk); if (size > 256 * 1024) throw new Error('提交的数据过大'); raw += chunk }
378
+ let body
379
+ try { body = JSON.parse(raw) } catch { throw new Error('请求不是有效 JSON') }
380
+ if (!body || Array.isArray(body) || typeof body !== 'object') throw new Error('请求须为 JSON 对象')
381
+ secret = typeof body.apiKey === 'string' ? body.apiKey : ''
382
+ return json(res, 200, { ok: true, value: await method(body) })
383
+ } catch (error) { return json(res, 400, { ok: false, message: publicError(error, [secret]) }) }
384
+ }
385
+ }
@@ -0,0 +1,160 @@
1
+ import { 恢复回答正文 } from './借来的/问答.js'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { 读名册 } from './新名册.js'
4
+
5
+ /** 查看只消除提醒,问题及原答复口继续保留;已读随原问题一起恢复。 */
6
+ export function 标记提醒已读(session, rpcIds, { pending, 持久问题, 写问答, send }) {
7
+ if (typeof session !== 'string' || !session || !Array.isArray(rpcIds)
8
+ || rpcIds.some(id => typeof id !== 'string')) throw new Error('未指定查看的节点和提醒')
9
+ const read = []
10
+ try {
11
+ for (const id of new Set(rpcIds)) {
12
+ const frame = pending.get(id)
13
+ if (!frame || frame.session !== session || frame.seen) continue
14
+ const record = 持久问题.get(id)
15
+ if (record) 写问答(record.root, { ...record, frame: { ...frame, seen: true } })
16
+ frame.seen = true
17
+ read.push(id)
18
+ }
19
+ } finally {
20
+ if (read.length) send({ type: 'blueprint.ask_seen', session, rpcIds: read })
21
+ }
22
+ return { rpcIds: read }
23
+ }
24
+
25
+ export function 接问答链(ctx, event, kind, deps) {
26
+ // 节点的提问都等用户答(co-create/solo 11-22 撤了);权限审批由系统放行一次(`自动批准`)。
27
+ const { 自动批准, 我是谁, 写问答, 持久问题, pending, 答复口, send, 送恢复回答, 记用户回答 } = deps
28
+ const 问话的错 = (message, code) => Object.assign(new Error(message), { name: 'UserQuestionError', code })
29
+ ctx.on(event, async function (request, next) {
30
+ const session = String(request.agent?.session?.id || request.agent?.id || '')
31
+ const 项目根 = () => request.agent?.session?.header?.cwd || ctx.sessions.get(session)?.header?.cwd
32
+ const 先答 = async () => kind === 'approval' ? 自动批准?.(ctx, request) : null
33
+ const 当场 = await 先答()
34
+ if (当场) return 当场
35
+ const rpcId = `studio-ask-${randomUUID()}`
36
+ const frame = kind === 'approval'
37
+ ? { type: 'blueprint.ask', kind, rpcId, session, approvalId: rpcId, toolName: request.toolName,
38
+ ...(request.callId ? { callId: String(request.callId) } : {}),
39
+ ...(request.reason ? { reason: request.reason } : {}) }
40
+ // 问题照原样送到界面,选项能点也能打字(11-10 他放开 11-09 的一律问答)。
41
+ : { type: 'blueprint.ask', kind, rpcId, session, questions: request.questions || [] }
42
+
43
+ let record = null
44
+ if (kind === 'question') {
45
+ const cwd = 项目根()
46
+ if (cwd && await 我是谁(ctx, session)) {
47
+ record = { root: String(cwd), frame }
48
+ 写问答(record.root, record)
49
+ 持久问题.set(rpcId, record)
50
+ }
51
+ }
52
+
53
+ /* 交下去的那一环(dsh 那张脸)要收得回来:我们这边先答了,它那边的框就该消失。
54
+ 它读的是 `request.signal`,所以换成一根「原信号断,或者我们答完」都会断的。
55
+ 上游不受影响:approval 在派发之前就把 signal 取走了;user-questions 派发的是一份拷贝。 */
56
+ const 原信号 = request.signal
57
+ const 收回 = new AbortController()
58
+ try { request.signal = 收回.signal } catch { /* 改不动就算了:只是 dsh 那张脸上的框晚一点消失 */ }
59
+
60
+ return new Promise((resolve, reject) => {
61
+ let 完 = false
62
+ const 存答复 = async value => {
63
+ if (kind !== 'question' || !record || !记用户回答) return
64
+ if (record.answer && JSON.stringify(record.answer) !== JSON.stringify(value)) throw new Error('回答已保存,请重试原回答')
65
+ record.answer = value
66
+ 写问答(record.root, record)
67
+ await 记用户回答(record, value)
68
+ }
69
+ const 结 = (outcome, 走, answer) => {
70
+ if (完) return
71
+ if (record) { 写问答(record.root, record, true); 持久问题.delete(rpcId) }
72
+ 完 = true
73
+ pending.delete(rpcId)
74
+ 答复口.delete(rpcId)
75
+ if (原信号) 原信号.removeEventListener('abort', 断了)
76
+ 收回.abort(new Error('Blueprint studio: 这一问已经有了结果'))
77
+ send({ type: 'blueprint.ask_done', kind, session, rpcId,
78
+ ...(kind === 'approval' ? { approvalId: rpcId } : {}), outcome,
79
+ ...(kind === 'question' && answer ? { answer } : {}) })
80
+ 走()
81
+ }
82
+ /* 问的那一方不等了(这一轮被停、被取消)。approval 自己会回 cancelled,这里只是把框收掉。 */
83
+ const 断了 = () => {
84
+ if (record && !完) {
85
+ 完 = true
86
+ 答复口.delete(rpcId)
87
+ 原信号?.removeEventListener('abort', 断了)
88
+ 收回.abort(new Error('提问已暂停,问题保留'))
89
+ send({ ...frame, 补发: true })
90
+ reject(问话的错('执行已暂停,未回答的问题仍保留,等待用户回答', 'ASK_ABORTED'))
91
+ return
92
+ }
93
+ 结('cancelled', () => kind === 'approval' ? resolve('cancelled') : reject(问话的错('ask_user_question was aborted before the user answered', 'ASK_ABORTED')))
94
+ }
95
+
96
+ 答复口.set(rpcId, {
97
+ kind,
98
+ 答: async (v) => {
99
+ await 存答复(v)
100
+ if (完 && record && 持久问题.has(rpcId)) {
101
+ record.answer = v
102
+ 写问答(record.root, record)
103
+ return 送恢复回答(record)
104
+ }
105
+ 结(kind === 'approval' ? v : 'answered', () => resolve(v), kind === 'question' ? v : null)
106
+ },
107
+ 撤: () => 结('cancelled', () => reject(问话的错('用户没答这一问,直接说了别的', 'ASK_CANCELLED'))),
108
+ })
109
+ pending.set(rpcId, frame)
110
+ send(frame)
111
+ if (原信号) {
112
+ if (原信号.aborted) return 断了()
113
+ 原信号.addEventListener('abort', 断了, { once: true })
114
+ }
115
+
116
+ // 先登记再核对一次:solo 可能在第一次读取之后打开,不能漏掉恰好新挂起的提问和权限审批。
117
+ Promise.resolve().then(async () => {
118
+ const answer = await 先答()
119
+ return answer || next()
120
+ }).then(async (v) => {
121
+ /* 链尾的兜底不是答复:approval 兜底回 'unavailable';user-questions 兜底抛 NO_PROVIDER(落进下面那个空分支)。 */
122
+ if (kind === 'approval' && v === 'unavailable') return
123
+ if (完) return
124
+ await 存答复(v)
125
+ if (完 && record && 持久问题.has(rpcId)) return 送恢复回答(record)
126
+ 结(kind === 'approval' ? v : 'answered', () => resolve(v), kind === 'question' ? v : null)
127
+ }, () => { /* 下一环没人答,或者被我们收回了 —— 继续等这张脸 */ }).catch(reject)
128
+ })
129
+ }, { prepend: true })
130
+ }
131
+
132
+
133
+ /** 回答原调用已终止的问题:以用户消息递交,固定 requestId 由 dsh 去重。 */
134
+ export async function 答复接手会话(record) {
135
+ const original = record.frame.session
136
+ if (!record.root) return original
137
+ const m = await 读名册(record.root)
138
+ const row = m?.rows.find(r => r.session === original || original in (r.calls || {}))
139
+ if (!row?.closing || row.status !== '完成') return original
140
+ const current = m.rows.find(r => r.id === row.id.split('.')[0])
141
+ return current?.session && current.status !== '完成' ? current.session : original
142
+ }
143
+
144
+ export function 创建恢复送答({ resume, prompt, close, target = 答复接手会话, beforeDeliver }) {
145
+ const sending = new Map()
146
+ return async record => {
147
+ const id = record.frame.rpcId
148
+ if (sending.has(id)) return sending.get(id)
149
+ const job = (async () => {
150
+ await beforeDeliver?.(record)
151
+ const sessionId = await target(record)
152
+ await resume(sessionId)
153
+ const source = sessionId !== record.frame.session ? `【前轮待决问题的${record.automatic ? '系统自动答复' : '用户回答'}】原提问会话 ${record.frame.session} 已因投入边界交回,以下回答交给当前接手节点,结合原问题与现状判断。\n` : ''
154
+ await prompt({ requestId: id, sessionId, mode: 'queue', content: [{ type: 'text', text: source + 恢复回答正文(record) }] })
155
+ close(record)
156
+ })()
157
+ sending.set(id, job)
158
+ try { return await job } finally { sending.delete(id) }
159
+ }
160
+ }
@@ -0,0 +1,67 @@
1
+ import { 听名册 } from './新名册.js'
2
+ import { readdir, realpath } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { 项目存储 } from './借来的/路径.js'
5
+ import { 项目删除中 } from './借来的/项目删除状态.js'
6
+ import { 创建名册读缓存 } from './名册读缓存.js'
7
+ import { 读项目名称, 项目显示名, 同步项目名称, 听项目名称 } from './借来的/项目名称.js'
8
+
9
+ /**
10
+ * 只登记工作区和标题;不为会话分组恢复、叫醒 Agent。保存位置里每个 Blueprint 项目(有 信息.db 的文件夹,零节点的也算)登记成 dsh 的一个工作区,
11
+ * 项目名单从这里列(index.js 的 项目们)。打开的已有文件夹在打开时登记,不在这里扫。
12
+ */
13
+ export function 接项目分组(ctx, projectRoot) {
14
+ ctx.inject(['workspaceRegistry', 'sessionTitle', 'sessions', 'sessionPersistence', 'sessionProjections'], scoped => {
15
+ const readRoster = 创建名册读缓存()
16
+ const roots = () => typeof projectRoot === 'function' ? projectRoot() : [projectRoot]
17
+ const owns = directory => roots().some(root => String(directory).startsWith(root + '/'))
18
+ let timer, reading = false, again = false, disposed = false
19
+ const warn = error => scoped.logger.warn(`Blueprint 项目分组:${error.message}`)
20
+ async function sync() {
21
+ if (disposed) return
22
+ if (reading) { again = true; return }
23
+ reading = true
24
+ try {
25
+ const headers = new Map((await scoped.sessionPersistence.list()).map(row => [String(row.header.id), row.header]))
26
+ for (const session of scoped.sessions.list()) headers.set(String(session.id), session.header)
27
+ for (const base of roots()) for (const entry of await readdir(base, { withFileTypes: true }).catch(error => { if (error.code !== 'ENOENT') warn(error); return [] })) {
28
+ if (!entry.isDirectory() || disposed) continue
29
+ const directory = join(base, entry.name)
30
+ if (项目删除中(directory)) continue
31
+ try {
32
+ const roster = await readRoster(directory)
33
+ if (!roster) continue
34
+ const canonical = await realpath(directory)
35
+ if (项目删除中(directory)) continue
36
+ const workspace = await scoped.workspaceRegistry.create(directory, 项目显示名(await 读项目名称(directory), entry.name))
37
+ if (项目删除中(directory) || await realpath(directory).catch(() => '') !== canonical) {
38
+ await scoped.workspaceRegistry.delete(workspace.id); continue
39
+ }
40
+ await 同步项目名称(directory, workspace)
41
+ const members = new Set(workspace.sessionIds)
42
+ // 注册归属按原生不可变 cwd 验证;包括同目录支线与子会话。
43
+ for (const [id, header] of headers) {
44
+ if (!header.cwd || members.has(id)) continue
45
+ if (await realpath(header.cwd).catch(() => '') === canonical) await workspace.attachSession(id)
46
+ }
47
+ for (const row of roster.rows) {
48
+ const session = row.session && scoped.sessions.get(String(row.session))
49
+ if (!session || !row.name) continue
50
+ // 原生 title 投影避免复制正文;用户或自动生成的已有标题照留。
51
+ const title = scoped.get('sessionProjections')?.snapshot(session, ['title']).values.title
52
+ if (!title && !scoped.sessionTitle.get(session)?.title) scoped.sessionTitle.rename(session, `${row.id} ${row.name}`)
53
+ }
54
+ } catch (error) { warn(error) }
55
+ }
56
+ } catch (error) { warn(error) }
57
+ finally { reading = false; if (again && !disposed) { again = false; schedule() } }
58
+ }
59
+ function schedule() { if (disposed) return; clearTimeout(timer); timer = setTimeout(() => void sync(), 250) }
60
+ scoped.on('session/created', schedule)
61
+ const offRoster = 听名册(root => { if (owns(root)) schedule() })
62
+ const offNames = 听项目名称(root => { if (owns(root)) schedule() })
63
+ const offStorage = 项目存储.subscribe(schedule)
64
+ void sync()
65
+ scoped.on('dispose', () => { disposed = true; clearTimeout(timer); offRoster(); offNames(); offStorage() })
66
+ })
67
+ }
@@ -0,0 +1,23 @@
1
+ import { 保存手动项目名称, 保存项目说明 } from './借来的/项目名称.js'
2
+
3
+ export function 项目名称HTTP(json, { projectRootOf, workspaceOf }) {
4
+ return async (req, res) => {
5
+ try {
6
+ const chunks = []; let size = 0
7
+ for await (const chunk of req) {
8
+ size += Buffer.byteLength(chunk)
9
+ if (size > 4096) return json(res, 413, { ok: false, message: '项目名称请求过长' })
10
+ chunks.push(Buffer.from(chunk))
11
+ }
12
+ const want = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
13
+ // 项目按文件夹(`项目`,零节点的项目只能这样认)或会话认;认不出、不是 Blueprint 项目,projectRootOf 会抛。
14
+ const root = await projectRootOf({ 项目: want.项目, session: want.session })
15
+ // 名字、说明(11-28)各自可以只给一样;都给就先存名字。
16
+ let value = null
17
+ if (want.name !== undefined) value = await 保存手动项目名称(root, want.name, await workspaceOf(root))
18
+ if (want.说明 !== undefined) value = await 保存项目说明(root, want.说明)
19
+ if (!value) throw new Error('没说要改什么')
20
+ return json(res, 200, { ok: true, value })
21
+ } catch (error) { return json(res, 200, { ok: false, message: error.message }) }
22
+ }
23
+ }