dsh-model-fleet 0.0.0-stage → 0.1.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.
package/lib/index.js ADDED
@@ -0,0 +1,806 @@
1
+ /**
2
+ * dsh-model-fleet — 一主多副的模型编队(Host 侧)。
3
+ *
4
+ * 设计约束(为什么写成这样):
5
+ * 1. 这个文件**没有任何 import**。副模型全部经由 `ctx.llm` 服务调用,注册表经由
6
+ * `ctx.tools` / `ctx.systemPrompt` / `ctx.webServer` 获取,所以插件不依赖任何
7
+ * harness 包,也就不会因为某个 peer 解析不到而让整个 profile 启动失败。
8
+ * 2. 成员表是纯配置。加一个副模型 = 在 cordis.patch.yml 里加一行 provider/model,
9
+ * 代码一行都不用改。provider 必须先由某个 llm 适配器插件注册好。
10
+ * 3. 主模型只在「自己办不到」时才调用 ask_member;编队名册通过 systemPrompt 段
11
+ * 动态提供,改了配置不需要重装插件。
12
+ * 4. 委派出去的每一次调用都不进会话 token 记账(`ctx.llm.stream` 是直接调用),
13
+ * 所以这里自己记一份调用元数据,面板能看见用了多少。
14
+ */
15
+
16
+ export const name = 'dsh-model-fleet'
17
+
18
+ /** 只声明真正必需的服务;缺一个就保持不激活,而不是抛错把启动拖垮。 */
19
+ export const inject = ['tools', 'llm']
20
+
21
+ const TOOL_NAME = 'ask_member'
22
+ const API_PREFIX = '/dsh-model-fleet/api'
23
+ const ROSTER_SECTION = 'model-fleet:roster'
24
+
25
+ const DEFAULT_MAX_TOKENS = 4096
26
+ const DEFAULT_TIMEOUT_MS = 180_000
27
+ const MAX_TASK_CHARS = 8_000
28
+ const MAX_CONTEXT_CHARS = 16_000
29
+ const MAX_OUTPUT_CHARS = 12_000
30
+ const HISTORY_LIMIT = 40
31
+
32
+ /** 副模型收到的系统提示:它是一次委派的执行者,不是对话者。 */
33
+ const MEMBER_SYSTEM_PROMPT = [
34
+ 'You are executing one small step on behalf of another model.',
35
+ 'Return only the deliverable that was asked for: no greeting, no restating of the task,',
36
+ 'no narration of your process, no suggestions for what to do next, and no commentary about',
37
+ 'being a model.',
38
+ 'If the step cannot be completed without information that was not provided, say exactly what',
39
+ 'is missing instead of guessing.',
40
+ ].join(' ')
41
+
42
+ // ── 小工具 ────────────────────────────────────────────────────────────────
43
+
44
+ function str(value, fallback = '') {
45
+ return typeof value === 'string' ? value.trim() : fallback
46
+ }
47
+
48
+ function clampInt(value, fallback, min, max) {
49
+ const n = Number(value)
50
+ if (!Number.isFinite(n)) return fallback
51
+ return Math.min(max, Math.max(min, Math.round(n)))
52
+ }
53
+
54
+ function sliceHead(value, max) {
55
+ const s = String(value ?? '')
56
+ return s.length > max ? `${s.slice(0, Math.max(1, max - 1))}…` : s
57
+ }
58
+
59
+ const ID_PATTERN = /^[a-zA-Z0-9._-]{1,40}$/
60
+
61
+ /**
62
+ * 由 provider/model 推一个能用的 id。`qwen2.5-coder:14b` 这种带冒号的模型名是常态,
63
+ * 直接拼接会得到非法 id——所以先过一遍白名单,再兜底。
64
+ */
65
+ function slugId(source) {
66
+ const slug = String(source ?? '')
67
+ .replace(/[^a-zA-Z0-9._-]/g, '-')
68
+ .replace(/-{2,}/g, '-')
69
+ .replace(/^[-.]+|[-.]+$/g, '')
70
+ .slice(0, 40)
71
+ return /[a-z0-9]/i.test(slug) ? slug : 'member'
72
+ }
73
+
74
+ function log(ctx, level, ...args) {
75
+ try {
76
+ const logger = typeof ctx.logger === 'function' ? ctx.logger(name) : undefined
77
+ if (logger && typeof logger[level] === 'function') logger[level](...args)
78
+ } catch {
79
+ /* 日志永远不该影响功能 */
80
+ }
81
+ }
82
+
83
+ // ── 配置 → 成员表 ────────────────────────────────────────────────────────
84
+
85
+ /**
86
+ * 把用户配置的行规整成成员表。非法行只跳过并记录,不抛错——一行写错
87
+ * 不应该让整个插件加载失败。
88
+ */
89
+ function normalizeMembers(raw, ctx) {
90
+ const input = Array.isArray(raw) ? raw : []
91
+ const members = []
92
+ const seen = new Set()
93
+
94
+ for (const entry of input) {
95
+ if (!entry || typeof entry !== 'object') {
96
+ log(ctx, 'warn', '跳过非对象成员配置:', JSON.stringify(entry))
97
+ continue
98
+ }
99
+ const provider = str(entry.provider)
100
+ const model = str(entry.model)
101
+ if (!provider || !model) {
102
+ log(ctx, 'warn', '跳过缺少 provider/model 的成员:', JSON.stringify(entry))
103
+ continue
104
+ }
105
+ const id = str(entry.id) || `${provider}-${model}`.replace(/[^a-zA-Z0-9._-]/g, '-')
106
+ if (seen.has(id)) {
107
+ log(ctx, 'warn', `成员 id 重复,保留第一项: ${id}`)
108
+ continue
109
+ }
110
+ seen.add(id)
111
+
112
+ const temperature = Number(entry.temperature)
113
+ members.push({
114
+ id,
115
+ label: str(entry.label) || `${provider}/${model}`,
116
+ provider,
117
+ model,
118
+ note: str(entry.note),
119
+ maxTokens: clampInt(entry.maxTokens, DEFAULT_MAX_TOKENS, 64, 200_000),
120
+ timeoutMs: clampInt(entry.timeoutMs, DEFAULT_TIMEOUT_MS, 5_000, 900_000),
121
+ ...(Number.isFinite(temperature) ? { temperature: Math.min(2, Math.max(0, temperature)) } : {}),
122
+ ...(str(entry.reasoningEffort) ? { reasoningEffort: str(entry.reasoningEffort) } : {}),
123
+ })
124
+ }
125
+
126
+ return members
127
+ }
128
+
129
+ function limitsOf(config) {
130
+ const source = config && typeof config === 'object' ? config : {}
131
+ return {
132
+ maxOutputChars: clampInt(source.maxOutputChars, MAX_OUTPUT_CHARS, 500, 40_000),
133
+ }
134
+ }
135
+
136
+ // ── 名册(进入系统提示词)──────────────────────────────────────────────────
137
+
138
+ function rosterText(members) {
139
+ if (members.length === 0) return ''
140
+
141
+ const lines = [
142
+ '## Model fleet',
143
+ '',
144
+ 'You are the main model. You do the work yourself. This fleet exists only for the steps you',
145
+ 'genuinely cannot take with what you already have — an image you cannot see, a strength another',
146
+ 'model has and you do not, or one independent second opinion on a decision that matters.',
147
+ '',
148
+ 'Do not delegate work you can already do. Do not delegate to look thorough. A delegated call',
149
+ 'costs the user real money and time.',
150
+ '',
151
+ 'Available members:',
152
+ ]
153
+
154
+ for (const member of members) {
155
+ const note = member.note ? ` — ${member.note}` : ''
156
+ lines.push(`- \`${member.id}\` (${member.label}) ${member.provider}/${member.model}${note}`)
157
+ }
158
+
159
+ lines.push(
160
+ '',
161
+ 'How to call:',
162
+ `- Use \`${TOOL_NAME}\` with \`member\` set to an id above and \`task\` describing exactly the single`,
163
+ ' step you need. Do not paste your whole plan or your own reasoning into `task`.',
164
+ '- Put any material the member must read (text to analyze, data to transform) in `context`.',
165
+ '- What comes back is raw material, not an answer. Judge it, correct it, and integrate it.',
166
+ '- Report the final result as your own work. Never tell the user "another model said…".',
167
+ '- If a member fails, say what failed once and continue without it; do not retry in a loop.',
168
+ )
169
+
170
+ return lines.join('\n')
171
+ }
172
+
173
+ // ── 工具定义 ──────────────────────────────────────────────────────────────
174
+
175
+ function buildToolParameters(members) {
176
+ return {
177
+ type: 'object',
178
+ properties: {
179
+ member: {
180
+ type: 'string',
181
+ description: `Id of the fleet member to use. One of: ${members.map((m) => m.id).join(', ')}.`,
182
+ },
183
+ task: {
184
+ type: 'string',
185
+ description:
186
+ 'The single step to perform, phrased as an instruction to an executor. Say exactly what output you need back.',
187
+ },
188
+ context: {
189
+ type: 'string',
190
+ description:
191
+ 'Optional material the member needs to perform the step, such as the text to analyze or the data to transform.',
192
+ },
193
+ },
194
+ required: ['member', 'task'],
195
+ additionalProperties: false,
196
+ }
197
+ }
198
+
199
+ const OUTPUT_SCHEMA = {
200
+ type: 'object',
201
+ properties: {
202
+ member: { type: 'string' },
203
+ label: { type: 'string' },
204
+ provider: { type: 'string' },
205
+ model: { type: 'string' },
206
+ text: { type: 'string' },
207
+ inputTokens: { type: 'number' },
208
+ outputTokens: { type: 'number' },
209
+ elapsedMs: { type: 'number' },
210
+ truncated: { type: 'boolean' },
211
+ },
212
+ required: ['member', 'text'],
213
+ }
214
+
215
+ /**
216
+ * 一次委派:把 task(+context) 交给成员模型,收回文本。
217
+ * 取消、超时、成员侧报错都转成带说明的异常,交给工具层渲染成 Error。
218
+ */
219
+ async function runMember(ctx, member, args, exec, limits) {
220
+ const llm = ctx.get('llm')
221
+ if (!llm || typeof llm.stream !== 'function') {
222
+ throw new Error('the llm service is unavailable, so no fleet member can be called')
223
+ }
224
+
225
+ const task = sliceHead(str(args.task), MAX_TASK_CHARS)
226
+ if (!task) throw new Error('task is empty; describe the single step you need')
227
+
228
+ const context = sliceHead(str(args.context), MAX_CONTEXT_CHARS)
229
+ const prompt = context ? `${task}\n\n---\n\n${context}` : task
230
+
231
+ const controller = new AbortController()
232
+ const callerSignal = exec && exec.signal
233
+ const onCallerAbort = () => controller.abort(callerSignal.reason)
234
+ if (callerSignal && typeof callerSignal.addEventListener === 'function') {
235
+ if (callerSignal.aborted) controller.abort(callerSignal.reason)
236
+ else callerSignal.addEventListener('abort', onCallerAbort, { once: true })
237
+ }
238
+ const timer = setTimeout(
239
+ () => controller.abort(new Error(`${member.id} timed out after ${member.timeoutMs}ms`)),
240
+ member.timeoutMs,
241
+ )
242
+
243
+ const startedAt = Date.now()
244
+ let text = ''
245
+ let usage = null
246
+
247
+ try {
248
+ const stream = llm.stream({
249
+ provider: member.provider,
250
+ model: member.model,
251
+ system: MEMBER_SYSTEM_PROMPT,
252
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
253
+ maxTokens: member.maxTokens,
254
+ ...(member.temperature !== undefined ? { temperature: member.temperature } : {}),
255
+ ...(member.reasoningEffort ? { reasoningEffort: member.reasoningEffort } : {}),
256
+ signal: controller.signal,
257
+ })
258
+
259
+ for await (const chunk of stream) {
260
+ if (!chunk) continue
261
+ if (chunk.type === 'text-delta' && chunk.text) {
262
+ text += chunk.text
263
+ } else if (chunk.type === 'usage' && chunk.usage) {
264
+ usage = chunk.usage
265
+ } else if (chunk.type === 'finish') {
266
+ const kind = chunk.reason && chunk.reason.kind
267
+ if (kind === 'error' || kind === 'aborted') {
268
+ const failure = chunk.reason && chunk.reason.failure
269
+ const message = (failure && failure.message) || (kind === 'aborted' ? 'the call was cancelled' : 'the call failed')
270
+ const error = new Error(`${member.id} failed: ${message}`)
271
+ if (failure && failure.code) error.code = failure.code
272
+ throw error
273
+ }
274
+ }
275
+ }
276
+ } catch (error) {
277
+ // 一个字都没吐出来才当成整体失败;有半截内容就让上层自己判断。
278
+ if (!text) throw error
279
+ } finally {
280
+ clearTimeout(timer)
281
+ if (callerSignal && typeof callerSignal.removeEventListener === 'function') {
282
+ callerSignal.removeEventListener('abort', onCallerAbort)
283
+ }
284
+ }
285
+
286
+ const cleaned = str(text)
287
+ if (!cleaned) throw new Error(`${member.id} returned nothing`)
288
+
289
+ const truncated = cleaned.length > limits.maxOutputChars
290
+ const body = truncated
291
+ ? `${sliceHead(cleaned, limits.maxOutputChars)}\n\n[output truncated at ${limits.maxOutputChars} characters]`
292
+ : cleaned
293
+
294
+ return {
295
+ member: member.id,
296
+ label: member.label,
297
+ provider: member.provider,
298
+ model: member.model,
299
+ text: body,
300
+ ...(usage ? {
301
+ ...(Number.isFinite(usage.inputTokens) ? { inputTokens: usage.inputTokens } : {}),
302
+ ...(Number.isFinite(usage.outputTokens) ? { outputTokens: usage.outputTokens } : {}),
303
+ } : {}),
304
+ elapsedMs: Date.now() - startedAt,
305
+ ...(truncated ? { truncated: true } : {}),
306
+ }
307
+ }
308
+
309
+ function createAskMemberTool(ctx, resolveMembers, initialMembers, limits, record) {
310
+ return {
311
+ name: TOOL_NAME,
312
+ description: [
313
+ 'Hand one small, self-contained step to another model in this fleet and get its raw output back.',
314
+ 'Use it only when you cannot do the step yourself: reading an image, using a strength another',
315
+ 'model has, or getting one independent second opinion. Work you can already do, you must do',
316
+ 'yourself. The reply is material rather than an answer — judge it, integrate it, and report the',
317
+ 'final result to the user in your own words.',
318
+ ].join(' '),
319
+ parameters: buildToolParameters(initialMembers),
320
+ output: {
321
+ schema: OUTPUT_SCHEMA,
322
+ render(_args, value) {
323
+ return [{ type: 'text', text: value.text }]
324
+ },
325
+ },
326
+ async execute(args, exec) {
327
+ // 每次执行都重新解析成员表:面板写过之后配置会变,闭包里那份可能已经过期。
328
+ const members = resolveMembers()
329
+ const requested = str(args && args.member)
330
+ const member = members.find((entry) => entry.id === requested)
331
+ if (!member) {
332
+ throw new Error(
333
+ `unknown fleet member "${requested}"; available: ${members.map((m) => m.id).join(', ')}`,
334
+ )
335
+ }
336
+ const outcome = await runMember(ctx, member, args, exec, limits)
337
+ record(member, outcome)
338
+ return outcome
339
+ },
340
+ }
341
+ }
342
+
343
+ // ── 调用台账 ──────────────────────────────────────────────────────────────
344
+
345
+ /**
346
+ * 一次委派的元数据。只存在内存里——会话日志才是真相来源,插件不往里写
347
+ * 新事件类型(那会让会话打不开)。面板读的是「本进程发生过什么」。
348
+ */
349
+ function createLedger() {
350
+ const calls = []
351
+ let seq = 0
352
+ return {
353
+ push(member, outcome) {
354
+ seq += 1
355
+ calls.push({
356
+ seq,
357
+ at: new Date().toISOString(),
358
+ member: member.id,
359
+ label: member.label,
360
+ provider: member.provider,
361
+ model: member.model,
362
+ inputTokens: outcome.inputTokens ?? null,
363
+ outputTokens: outcome.outputTokens ?? null,
364
+ elapsedMs: outcome.elapsedMs,
365
+ ok: true,
366
+ })
367
+ if (calls.length > HISTORY_LIMIT) calls.splice(0, calls.length - HISTORY_LIMIT)
368
+ },
369
+ fail(member, message) {
370
+ seq += 1
371
+ calls.push({
372
+ seq,
373
+ at: new Date().toISOString(),
374
+ member: member.id,
375
+ label: member.label,
376
+ provider: member.provider,
377
+ model: member.model,
378
+ inputTokens: null,
379
+ outputTokens: null,
380
+ elapsedMs: 0,
381
+ ok: false,
382
+ error: sliceHead(message, 200),
383
+ })
384
+ if (calls.length > HISTORY_LIMIT) calls.splice(0, calls.length - HISTORY_LIMIT)
385
+ },
386
+ snapshot() {
387
+ return calls.slice()
388
+ },
389
+ }
390
+ }
391
+
392
+ // ── 面板数据接口 ──────────────────────────────────────────────────────────
393
+
394
+ function sendJson(res, status, body) {
395
+ const payload = JSON.stringify(body)
396
+ res.statusCode = status
397
+ res.setHeader('content-type', 'application/json; charset=utf-8')
398
+ res.setHeader('cache-control', 'no-store')
399
+ res.end(payload)
400
+ }
401
+
402
+ function originOf(value) {
403
+ try {
404
+ return new URL(String(value ?? '')).origin
405
+ } catch {
406
+ return null
407
+ }
408
+ }
409
+
410
+ /** 只接受本机回环 + 同源 GET:这是只读面板数据,不暴露给跨站页面。 */
411
+ function isTrustedRequest(req) {
412
+ const remote = req.socket && req.socket.remoteAddress
413
+ const loopback = !remote || remote === '127.0.0.1' || remote === '::1' || remote === '::ffff:127.0.0.1'
414
+ if (!loopback) return false
415
+
416
+ const fetchSite = String((req.headers && req.headers['sec-fetch-site']) ?? '').toLowerCase()
417
+ if (fetchSite === 'cross-site') return false
418
+
419
+ const origin = originOf(req.headers && req.headers.origin)
420
+ if (!origin) return true
421
+ // 只比 authority,不比 scheme:TLS 可能在反向代理上终止,页面是 https 而
422
+ // 上游是 http,拿 scheme 比较会把合法的同源请求挡掉。
423
+ try {
424
+ const host = String((req.headers && req.headers.host) ?? '')
425
+ return new URL(origin).host === host
426
+ } catch {
427
+ return false
428
+ }
429
+ }
430
+
431
+ function registerRoutes(ctx, snapshot, rememberMembers) {
432
+ const web = ctx.get('webServer')
433
+ if (!web || typeof web.register !== 'function') {
434
+ log(ctx, 'warn', '没有 webServer 服务,面板数据接口未注册(工具本身照常可用)')
435
+ return
436
+ }
437
+
438
+ const route = web.register({
439
+ kind: 'exact',
440
+ path: `${API_PREFIX}/members`,
441
+ async handler(req, res) {
442
+ const read = req.method === 'GET' || req.method === 'HEAD'
443
+ if (!read && req.method !== 'POST') {
444
+ sendJson(res, 405, { ok: false, error: 'method not allowed' })
445
+ return
446
+ }
447
+ if (!isTrustedRequest(req)) {
448
+ sendJson(res, 403, { ok: false, error: 'forbidden' })
449
+ return
450
+ }
451
+ // 走 DSH 自己的连接认证 seam:浏览器没带 cookie 的请求在这里被挡下。
452
+ // 少了这一步,同机任何进程都能读到成员表、也能改它。
453
+ try {
454
+ const connection = ctx.get('connection')
455
+ if (connection && typeof connection.requestRejection === 'function') {
456
+ const code = connection.requestRejection(req)
457
+ if (code !== undefined && code !== null && code !== false) {
458
+ sendJson(res, typeof code === 'number' ? code : 403, { ok: false, error: 'unauthorized' })
459
+ return
460
+ }
461
+ }
462
+ } catch {
463
+ /* 没有 connection 服务时退回本机回环检查 */
464
+ }
465
+
466
+ if (read) {
467
+ sendJson(res, 200, { ok: true, ...snapshot() })
468
+ return
469
+ }
470
+
471
+ // —— POST:整表替换。写入走 configEditor,落到 profile 的 Cordis patch,
472
+ // 然后由 loader 重新组合这个条目——所以面板改完,工具和名册一起换新。
473
+ const contentType = String((req.headers && req.headers['content-type']) ?? '').toLowerCase()
474
+ if (!contentType.includes('application/json')) {
475
+ sendJson(res, 415, { ok: false, error: 'content-type must be application/json' })
476
+ return
477
+ }
478
+
479
+ let body
480
+ try {
481
+ body = await readJsonBody(req)
482
+ } catch (error) {
483
+ sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
484
+ return
485
+ }
486
+
487
+ let next
488
+ try {
489
+ next = parseMembersInput(body && body.members)
490
+ } catch (error) {
491
+ sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
492
+ return
493
+ }
494
+
495
+ try {
496
+ await writeMembers(ctx, next)
497
+ } catch (error) {
498
+ log(ctx, 'warn', '面板写入成员表失败:', String((error && error.message) || error))
499
+ sendJson(res, 500, { ok: false, error: String((error && error.message) || error) })
500
+ return
501
+ }
502
+
503
+ rememberMembers(next)
504
+ sendJson(res, 200, { ok: true, members: next })
505
+ },
506
+ })
507
+ ctx.effect(() => route, `${name}: api route`)
508
+ }
509
+
510
+ // ── provider 目录(面板下拉用)────────────────────────────────────────────
511
+
512
+ /**
513
+ * 把 llm 服务里已经注册的 provider 投影成面板能用的形状。
514
+ *
515
+ * 成员表里只存 provider 的**名字**——api key 属于 provider(一个 endpoint 一把钥匙),
516
+ * 不属于成员:同一个 provider 下的几个模型共用一个 key,而 key 本身在凭据存储里,
517
+ * 配置文件里只写引用名(apiKeyEnv)。面板把 key 抄进成员表就等于把密钥复制成 N 份。
518
+ * 所以这里只列 provider,让用户从里面挑。
519
+ */
520
+ function describeProviders(llm, ctx) {
521
+ const out = []
522
+ const seen = new Set()
523
+
524
+ const push = (entry, dormant) => {
525
+ if (!entry || typeof entry !== 'object') return
526
+ const id = str(entry.id || entry.provider)
527
+ if (!id || seen.has(id)) return
528
+ seen.add(id)
529
+
530
+ let models = []
531
+ try {
532
+ const raw = typeof entry.getModels === 'function' ? entry.getModels() : entry.models
533
+ for (const model of Array.isArray(raw) ? raw : []) {
534
+ const modelId = str(model && model.id)
535
+ if (modelId) models.push(modelId)
536
+ }
537
+ } catch {
538
+ /* provider 自己的模型表读不到就留空,客户端还能手填 */
539
+ }
540
+
541
+ out.push({
542
+ id,
543
+ label: str(entry.displayName || entry.name) || id,
544
+ models,
545
+ ...(dormant ? { dormant: true } : {}),
546
+ })
547
+ }
548
+
549
+ try {
550
+ if (llm && typeof llm.listProviders === 'function') {
551
+ for (const entry of llm.listProviders() || []) push(entry, false)
552
+ }
553
+ } catch (error) {
554
+ log(ctx, 'warn', '列出已注册 provider 失败:', String((error && error.message) || error))
555
+ }
556
+
557
+ try {
558
+ // 声明了但没启用的:用户改配置后能在这里看到「我配了但没生效」。
559
+ if (llm && typeof llm.listConfigurableProviders === 'function') {
560
+ for (const entry of llm.listConfigurableProviders() || []) push(entry, true)
561
+ }
562
+ } catch {
563
+ /* 可选能力,读不到就算了 */
564
+ }
565
+
566
+ return out
567
+ }
568
+
569
+ // ── 写入路径 ──────────────────────────────────────────────────────────────
570
+ const ENTRY_ID = 'model-fleet'
571
+ const MAX_BODY_BYTES = 64 * 1024
572
+
573
+ /** 面板提交的是**整张**成员表,所以这里严格校验:宁可 400,也不要静默丢掉用户填的那行。 */
574
+ function parseMembersInput(raw) {
575
+ if (!Array.isArray(raw)) throw new Error('members must be an array')
576
+ if (raw.length > 32) throw new Error('too many members (max 32)')
577
+
578
+ const out = []
579
+ const seen = new Set()
580
+ raw.forEach((entry, index) => {
581
+ const at = `members[${index}]`
582
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw new Error(`${at} must be an object`)
583
+
584
+ const provider = str(entry.provider).trim()
585
+ const model = str(entry.model).trim()
586
+ if (!provider) throw new Error(`${at}.provider is required`)
587
+ if (!model) throw new Error(`${at}.model is required`)
588
+
589
+ const rawId = str(entry.id).trim()
590
+ const suggested = slugId(`${provider}-${model}`)
591
+ if (rawId && !/^[a-zA-Z0-9._-]{1,40}$/.test(rawId)) {
592
+ const bad = [...new Set(rawId.replace(/[a-zA-Z0-9._-]/g, ''))].slice(0, 6).join(' ')
593
+ throw new Error(
594
+ `members[${index}].id「${rawId}」不能用作 id:只能用英文字母、数字、点、下划线、短横线,最多 40 个字符` +
595
+ (bad ? `(这里有:${bad})` : '') +
596
+ `。留空会自动生成「${suggested}」。`,
597
+ )
598
+ }
599
+ const id = rawId || suggested
600
+ if (seen.has(id)) throw new Error(`duplicate member id "${id}"`)
601
+ seen.add(id)
602
+
603
+ const member = {
604
+ id,
605
+ label: str(entry.label).trim() || `${provider}/${model}`,
606
+ provider,
607
+ model,
608
+ note: str(entry.note).trim(),
609
+ }
610
+ // 面板没暴露这三个字段,但整表替换时必须原样带回去,否则一编辑就把它们抹了。
611
+ const maxTokens = Number(entry.maxTokens)
612
+ if (Number.isFinite(maxTokens)) member.maxTokens = clampInt(maxTokens, DEFAULT_MAX_TOKENS, 64, 200_000)
613
+ const timeoutMs = Number(entry.timeoutMs)
614
+ if (Number.isFinite(timeoutMs)) member.timeoutMs = clampInt(timeoutMs, DEFAULT_TIMEOUT_MS, 5_000, 900_000)
615
+ const temperature = Number(entry.temperature)
616
+ if (Number.isFinite(temperature)) member.temperature = Math.min(2, Math.max(0, temperature))
617
+ if (str(entry.reasoningEffort)) member.reasoningEffort = str(entry.reasoningEffort)
618
+ out.push(member)
619
+ })
620
+ return out
621
+ }
622
+
623
+ function readJsonBody(req) {
624
+ return new Promise((resolve, reject) => {
625
+ const chunks = []
626
+ let size = 0
627
+ let done = false
628
+ const finish = (fn, value) => {
629
+ if (done) return
630
+ done = true
631
+ fn(value)
632
+ }
633
+ req.on('data', (chunk) => {
634
+ size += chunk.length
635
+ if (size > MAX_BODY_BYTES) {
636
+ finish(reject, new Error('request body too large'))
637
+ req.destroy?.()
638
+ return
639
+ }
640
+ chunks.push(chunk)
641
+ })
642
+ req.on('end', () => {
643
+ const text = Buffer.concat(chunks).toString('utf8')
644
+ try {
645
+ finish(resolve, text ? JSON.parse(text) : {})
646
+ } catch {
647
+ finish(reject, new Error('body is not valid JSON'))
648
+ }
649
+ })
650
+ req.on('error', (error) => finish(reject, error))
651
+ })
652
+ }
653
+
654
+ /**
655
+ * 把成员表写回 profile 的 Cordis patch。
656
+ *
657
+ * 用 configEditor 而不是自己拼 YAML:它负责保留注释、缩进和未被改动的字段,
658
+ * 也是 GUI 配置编辑器用的同一条路径。写完 loader 会重新组合这个条目,
659
+ * 所以下一次 apply() 读到的就是新配置——不存在第二份真相。
660
+ */
661
+ async function writeMembers(ctx, next) {
662
+ const editor = ctx.get('configEditor')
663
+ if (!editor || typeof editor.edit !== 'function' || typeof editor.entries !== 'function') {
664
+ throw new Error('configEditor 服务不可用,无法从面板写入配置')
665
+ }
666
+ const entry = editor.entries().find((row) => row && row.options && row.options.id === ENTRY_ID)
667
+ if (!entry) throw new Error(`找不到 loader 条目 "${ENTRY_ID}",无法写入配置`)
668
+ try {
669
+ await editor.edit(entry, (raw, inherited) => ({
670
+ ...(inherited || {}),
671
+ ...(raw || {}),
672
+ members: next,
673
+ }))
674
+ } catch (error) {
675
+ // loader 会重新解析整个 patch 文件再组合条目,所以报错可能和成员表本身无关——
676
+ // 把「这多半是文件坏了」写进消息里,省得用户去猜 "Unexpected scalar" 是什么。
677
+ const message = String((error && error.message) || error)
678
+ if (/line \d+|column \d+|unexpected|parse/i.test(message)) {
679
+ let where = ''
680
+ try {
681
+ if (typeof editor.documentPath === 'string') where = editor.documentPath
682
+ else if (typeof editor.documentPath === 'function') where = String(editor.documentPath() || '')
683
+ } catch {
684
+ /* 拿不到路径也能报 */
685
+ }
686
+ throw new Error(
687
+ `${where || 'profile 的 cordis.patch.yml'} 解析失败,这次改动没有写进去:${message} ` +
688
+ '(是配置文件本身坏了——常见是开头带了 BOM、缩进混了制表符,或手工编辑留下的残缺行;不是成员表的内容问题。修好那处 YAML 再保存一次。)',
689
+ )
690
+ }
691
+ throw error
692
+ }
693
+ }
694
+
695
+ // ── 入口 ──────────────────────────────────────────────────────────────────
696
+
697
+ export function apply(ctx, config = {}) {
698
+ const members = normalizeMembers(config && config.members, ctx)
699
+ const limits = limitsOf(config)
700
+ const ledger = createLedger()
701
+
702
+ // 面板写过之后配置会变。正常情况下 loader 会重新组合这个条目、apply() 再跑一遍,
703
+ // 但那一步是异步的;用一个可变持有者让读侧(名册、面板、工具执行)立刻看到新值。
704
+ let live = members
705
+ const resolveMembers = () => live
706
+
707
+ // provider 目录每次读快照时重算:用户可能刚在模型页加了一个 provider。
708
+ let providers = []
709
+
710
+ const snapshot = () => {
711
+ let active = null
712
+ let llm = null
713
+ try {
714
+ llm = ctx.get('llm')
715
+ } catch {
716
+ /* 没 llm 就没有 provider 目录,成员表照样显示 */
717
+ }
718
+ providers = describeProviders(llm, ctx)
719
+ try {
720
+ const selection = ctx.get('agentDefaultModel')
721
+ const current = selection && typeof selection.currentSelection === 'function'
722
+ ? selection.currentSelection()
723
+ : null
724
+ if (current && current.provider && current.model) {
725
+ active = { provider: current.provider, model: current.model }
726
+ }
727
+ } catch {
728
+ /* 读不到主模型就只是不显示 */
729
+ }
730
+ return {
731
+ members: live.map((member) => ({
732
+ id: member.id,
733
+ label: member.label,
734
+ provider: member.provider,
735
+ model: member.model,
736
+ note: member.note,
737
+ maxTokens: member.maxTokens,
738
+ timeoutMs: member.timeoutMs,
739
+ ...(member.temperature === undefined ? {} : { temperature: member.temperature }),
740
+ ...(member.reasoningEffort === undefined ? {} : { reasoningEffort: member.reasoningEffort }),
741
+ })),
742
+ providers,
743
+ calls: ledger.snapshot(),
744
+ main: active,
745
+ }
746
+ }
747
+
748
+ // 每一块集成都单独兜住:插件加载失败会把整个 profile 拖下水(DSH 启动是全有全无),
749
+ // 所以这里宁可少一个能力并留下 warn,也绝不把异常抛出去。
750
+ try {
751
+ registerRoutes(ctx, snapshot, (next) => {
752
+ live = next
753
+ })
754
+ } catch (error) {
755
+ log(ctx, 'warn', '面板数据接口注册失败(工具不受影响):', String((error && error.message) || error))
756
+ }
757
+
758
+ if (members.length === 0) {
759
+ log(ctx, 'warn', '没有任何副模型配置,ask_member 未注册。可以在「模型编队」面板里添加,或直接改 cordis.patch.yml。')
760
+ return
761
+ }
762
+
763
+ try {
764
+ const tool = createAskMemberTool(ctx, resolveMembers, members, limits, (member, outcome) => ledger.push(member, outcome))
765
+ ctx.tools.register(tool)
766
+ } catch (error) {
767
+ log(ctx, 'error', 'ask_member 注册失败:', String((error && error.message) || error))
768
+ return
769
+ }
770
+
771
+ try {
772
+ const systemPrompt = ctx.get('systemPrompt')
773
+ if (systemPrompt && typeof systemPrompt.section === 'function') {
774
+ const dispose = systemPrompt.section({
775
+ name: ROSTER_SECTION,
776
+ order: 3000,
777
+ text: () => rosterText(resolveMembers()),
778
+ })
779
+ if (typeof dispose === 'function') ctx.effect(() => dispose, `${name}: roster section`)
780
+ } else {
781
+ log(ctx, 'warn', '没有 systemPrompt 服务,主模型看不到编队名册(工具仍然注册)')
782
+ }
783
+ } catch (error) {
784
+ log(ctx, 'warn', '编队名册未注入系统提示词(工具仍然可用):', String((error && error.message) || error))
785
+ }
786
+
787
+ log(ctx, 'info', `模型编队已就绪:${members.map((m) => m.id).join(', ')}`)
788
+
789
+ // 一条诊断:面板能不能写,取决于 configEditor 在不在、能不能定位到这个条目。
790
+ try {
791
+ const editor = ctx.get('configEditor')
792
+ const writable =
793
+ Boolean(editor) &&
794
+ typeof editor.entries === 'function' &&
795
+ editor.entries().some((row) => row && row.options && row.options.id === ENTRY_ID)
796
+ log(
797
+ ctx,
798
+ writable ? 'info' : 'warn',
799
+ writable
800
+ ? `面板可以改成员表(写回 profile 的 Cordis patch,条目 ${ENTRY_ID})`
801
+ : `面板只读:找不到 configEditor 或 loader 条目 "${ENTRY_ID}",改成员请直接编辑 cordis.patch.yml`,
802
+ )
803
+ } catch (error) {
804
+ log(ctx, 'warn', '面板可写性探测失败(不影响工具):', String((error && error.message) || error))
805
+ }
806
+ }