dsh-submodel 0.1.0 → 0.2.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/policy.js CHANGED
@@ -7,16 +7,19 @@
7
7
  *
8
8
  * 两条正交的判定(不要合并,它们回答不同的问题):
9
9
  *
10
- * 1. **模式(mode)**:只由「本次 assembly 的主模型 ID 是否以 `flash` 结尾」决定。
11
- * 用户在 GUI 里选的是主模型;主模型是 Flash → 走 `economize`(自己干日常,委派继承自己);
12
- * 不是 Flash → 走 `boss`(强主脑理解/判断/写作,可验证的执行块默认派执行路由)。
13
- * **只看模型 id,不看 provider、显示名或价格**——这是用户约定的唯一规则。
10
+ * 1. **模式(mode)**:由「本次请求的路由是否属于经济路由」决定(见 `isEconomyRoute`)。
11
+ * 主模型就是配置的执行路由 → 走 `economize`(自己干日常,委派继承自己);
12
+ * 否则走 `boss`(强主脑理解/判断/写作,可验证的执行块默认派执行路由)。
13
+ * 经济路由的来源:① 与 `cfg.executor` 完全相同的 provider+model;② 命中 `cfg.economyRoutes`
14
+ * 列表;③ 未配置 `economyRoutes` 时保留旧规则「模型 ID 以 `flash` 结尾」作兼容。
15
+ * **不看显示名或价格**(宿主元数据没有价格字段),只看路由与配置的显式匹配。
14
16
  *
15
- * 2. **角色(role)**:`root` 还是 `child`,由 header 的 `origin`/`delegationDepth` 判定。
16
- * 子代是执行/专家角色,**不再**按 Flash 后缀切换主脑策略;子代永远禁止再委派。
17
+ * 2. **角色(role)**:`root` 还是 `child`,由 `agent.session.header` 的 `origin`/`delegationDepth`
18
+ * 判定,`agent.options.subagentDepth` 兜底(与宿主 `delegationDepthOf` 同口径)。
19
+ * 子代是执行/专家角色,**不再**按主脑模式切换策略;子代永远禁止再委派。
17
20
  *
18
21
  * 为什么两个时点分别用不同来源(别改成"都用同一个"):
19
- * - **提示词阶段**用 `assembly.variables.model`——它描述"GUI 即将发起的这笔请求",
22
+ * - **提示词阶段**用 `assembly.variables.provider/model`——它描述"GUI 即将发起的这笔请求",
20
23
  * 首轮和刚换模都能立刻对齐;
21
24
  * - **执行阶段**用"最新已接受的 request header config"——它描述"正在发起这笔工具调用的主脑",
22
25
  * 不会读到 GUI 里那个还没提交的 pending 选择。
@@ -52,45 +55,97 @@ export const CHILD_FORBIDDEN_TOOLS = Object.freeze([
52
55
  ]);
53
56
 
54
57
  /**
55
- * 唯一规则:模型 ID 以 `flash` 结尾即 Flash 模式。
58
+ * 旧规则(legacy 兼容):模型 ID 以 `flash` 结尾即视作经济路由。
59
+ * 只在 `cfg.economyRoutes` 为空时参与判定(见 `isEconomyRoute`)。
56
60
  * 大小写不敏感、必须是**后缀**(`flash-lite` 不算),空值/非字符串不算。
57
61
  * @param model - 模型 ID(可能来自 GUI 选择、header、或 undefined)。
58
- * @returns 是否为 Flash 主脑。
62
+ * @returns 是否命中旧 Flash 后缀规则。
59
63
  */
60
64
  export function isFlashModel(model) {
61
65
  return typeof model === 'string' && model.toLowerCase().endsWith('flash');
62
66
  }
63
67
 
64
68
  /**
65
- * 由模型 ID 判定本次顶层模式。
66
- * @param model - 模型 ID。
69
+ * 稳定的路由身份键:`provider\0model`,用于去重与比较。
70
+ * @param route - `{provider, model}`(字段可为空)。
71
+ * @returns 字符串键。
72
+ */
73
+ export function routeKey(route) {
74
+ return `${route?.provider ?? ''}\0${route?.model ?? ''}`;
75
+ }
76
+
77
+ /**
78
+ * 判定一条路由是否属于「经济路由」(economize 模式)。
79
+ *
80
+ * 顺序:
81
+ * 1. 与 `cfg.executor` 的 provider+model 完全相等 → 是;
82
+ * 2. 命中 `cfg.economyRoutes`:双方 provider 都非空时两者都比,任一方为空时只比 model → 是;
83
+ * 3. `cfg.economyRoutes` 为空时回退旧规则:模型 ID 以 `flash` 结尾 → 是;
84
+ * 4. 否则不是。
85
+ *
86
+ * @param route - 待判定的 `{provider, model}`;model 缺失/空时返回 false。
87
+ * @param cfg - 运行期配置(至少含 `executor` / `economyRoutes`)。
88
+ * @returns 是否为经济路由。
89
+ */
90
+ export function isEconomyRoute(route, cfg) {
91
+ if (!route || typeof route.model !== 'string' || route.model === '') return false;
92
+ const executor = cfg?.executor;
93
+ if (executor?.provider && executor?.model && executor.provider === route.provider && executor.model === route.model) {
94
+ return true;
95
+ }
96
+ const economyRoutes = Array.isArray(cfg?.economyRoutes) ? cfg.economyRoutes : [];
97
+ if (
98
+ economyRoutes.some(
99
+ (row) =>
100
+ row !== null &&
101
+ typeof row === 'object' &&
102
+ row.model === route.model &&
103
+ (row.provider === '' || row.provider === undefined || route.provider === '' || row.provider === route.provider),
104
+ )
105
+ ) {
106
+ return true;
107
+ }
108
+ return economyRoutes.length === 0 && isFlashModel(route.model);
109
+ }
110
+
111
+ /**
112
+ * 由本次请求的路由判定本次顶层模式。
113
+ * @param route - `{provider, model}`(来自 assembly 变量或 request header config)。
114
+ * @param cfg - 运行期配置(至少含 `executor` / `economyRoutes`)。
67
115
  * @returns {MODE_ECONOMIZE} 或 {MODE_BOSS}。
68
116
  */
69
- export function modeForModel(model) {
70
- return isFlashModel(model) ? MODE_ECONOMIZE : MODE_BOSS;
117
+ export function modeForRoute(route, cfg) {
118
+ return isEconomyRoute(route, cfg) ? MODE_ECONOMIZE : MODE_BOSS;
71
119
  }
72
120
 
73
121
  /**
74
- * 判定调用者角色。**子代**的判据是 header 的 `origin === 'subagent'` 或正的 delegationDepth;
75
- * 刻意不用 `parentSession`(普通用户 fork 也带 parentSession,那不是子代)。
76
- * @param header - session header(可为 undefined)。
77
- * @param options - agent options(作为 depth 的兜底来源,可为 undefined)。
122
+ * 判定调用者角色。**子代**的判据(按优先级):`session.header.origin === 'subagent'`、
123
+ * `session.header.delegationDepth > 0`、`options.subagentDepth > 0`(冷恢复兜底)。
124
+ * 刻意不用 `parentSession`(普通用户 fork 也带 parentSession,那不是子代);
125
+ * `session` 缺失时只用 options 判据,不抛。
126
+ * @param agent - live agent(含 `session.header` 与 `options`),可为 undefined。
78
127
  * @returns {'child'|'root'}。
79
128
  */
80
- export function roleOf(header, options) {
129
+ export function roleOf(agent) {
130
+ const header = agent?.session?.header;
81
131
  if (header !== undefined && header !== null) {
82
132
  if (header.origin === 'subagent') return 'child';
83
133
  const depth = header.delegationDepth;
84
134
  if (typeof depth === 'number' && Number.isFinite(depth) && depth > 0) return 'child';
85
135
  }
86
- const optionDepth = options?.subagentDepth;
136
+ const optionDepth = agent?.options?.subagentDepth;
87
137
  if (typeof optionDepth === 'number' && Number.isFinite(optionDepth) && optionDepth > 0) return 'child';
88
138
  return 'root';
89
139
  }
90
140
 
91
141
  /**
92
142
  * 从 execution context 判定角色。`exec.agent` 是唯一权威来源:
93
- * 它必须存在且是 live Agent(有 session.requestHeader 与 options)。
143
+ * 它必须存在且是 live Agent(有 session.requestHeader)。
144
+ *
145
+ * `header` 在这里取的是 `session.requestHeader()`(执行期 header,含 `config`);
146
+ * 角色判定本身走 `roleOf(agent)`——它读 `session.header`(durable header),
147
+ * 两者不是同一份数据,别合并。
148
+ *
94
149
  * @param exec - 工具执行输入(含 agent)。
95
150
  * @returns {{ok: true, role: 'root'|'child', header: object|undefined, agent: object}}
96
151
  * 或 `{ok: false, reason: string}`。
@@ -104,7 +159,7 @@ export function resolveCallerRole(exec) {
104
159
  return { ok: false, reason: 'delegate_task requires a live Agent with a session header (exec.agent looked stale)' };
105
160
  }
106
161
  const header = agent.session.requestHeader();
107
- const role = roleOf(header, agent.options);
162
+ const role = roleOf(agent);
108
163
  return { ok: true, role, header, agent };
109
164
  }
110
165
 
@@ -139,15 +194,15 @@ export function classifyExplicitRoute(args) {
139
194
  * 规则(四类分支都要覆盖):
140
195
  * - **完整显式 pair**:原样保留,**不注入策略 effort**(让原生规则决定继承兼容 effort 或清掉不兼容的);
141
196
  * - **只给一个**:失败(见 classifyExplicitRoute);
142
- * - **无显式路由 + Flash 主脑**:不补任何 provider/model(子代继承当前 Flash);
143
- * - **无显式路由 + 非 Flash 主脑**:补配置的 executor pair;未给 reasoning_effort 时补 max,
197
+ * - **无显式路由 + economize 模式**:不补任何 provider/model(子代继承当前经济路由);
198
+ * - **无显式路由 + boss 模式**:补配置的 executor pair;未给 reasoning_effort 时补 max,
144
199
  * 给了就保留——max 仅作缺省,不覆盖调用方已指定的档位。
145
200
  *
146
201
  * 专家路由完全由配置决定:本函数不认识任何具体 provider/model 名,也不做"某条路由只能兜底"
147
202
  * 之类的硬编码特判(那会把某个部署的私有约定写进公版代码)。
148
203
  *
149
204
  * @param args - 原始工具入参(**只读,不修改**)。
150
- * @param mode - modeForModel 的结果。
205
+ * @param mode - modeForRoute 的结果。
151
206
  * @param executor - 配置的 `{provider, model, reasoningEffort}`。
152
207
  * @returns `{ok:true, args: newArgs, applied: 'explicit'|'executor'|'inherit'}` 或 `{ok:false, reason}`。
153
208
  */
@@ -161,7 +216,7 @@ export function resolveDelegationArgs(args, mode, executor) {
161
216
  return { ok: true, args: next, applied: 'inherit' };
162
217
  }
163
218
  if (executor === undefined || executor === null || !executor.provider || !executor.model) {
164
- return { ok: false, reason: 'non-Flash delegation has no configured executor route (config.executor.provider/model is required)' };
219
+ return { ok: false, reason: 'boss-mode delegation has no configured executor route (config.executor.provider/model is required)' };
165
220
  }
166
221
  next.provider = executor.provider;
167
222
  next.model = executor.model;
@@ -188,7 +243,7 @@ const ECONOMIZE_TEMPLATE = `## 模型路由:Flash 主脑(主脑自己干,
188
243
 
189
244
  **"需要独立审查/复核"本身不是升级理由**。复核默认交给普通子代理(\`delegate_task\` 不传 \`provider\`/\`model\`,子代继承当前路由);只有当**被复核的东西本身**满足上面第 1 条时才点名专家。
190
245
 
191
- 调用方式:普通任务统一走 \`delegate_task\`,它的参数与原生 \`subagent\` 相同;\`provider\` 与 \`model\` 必须**成对**传,只给一个会立即失败。不确定有哪些授权路由时先调 \`list_subagent_models\`。\`reasoning_effort\` 以各路由支持的档位为准,不传时用配置缺省,显式档位优先。三个都不传就继承主模型路由,即默认路径。升级前先把证据收齐,并把已知事实、约束、已试过的方案写进 prompt——子智能体看不到本会话历史。
246
+ 调用方式:普通任务统一走 \`delegate_task\`,它的参数与原生 \`subagent\` 相同,启动后立即返回子会话 id,完成时由运行时通知;不要反复轮询,查看/追加/停止子代理用 \`list_agents\` / \`send_message\` / \`interrupt_agent\`。\`provider\` 与 \`model\` 必须**成对**传,只给一个会立即失败。不确定有哪些授权路由时先调 \`list_subagent_models\`。\`reasoning_effort\` 以各路由支持的档位为准,不传时用配置缺省,显式档位优先。三个都不传就继承主模型路由,即默认路径。升级前先把证据收齐,并把已知事实、约束、已试过的方案写进 prompt——子智能体看不到本会话历史。
192
247
 
193
248
  需要多方校验或讨论时:在同一条消息里并发起两个 \`delegate_task\`,给**完全相同**的 brief 且**彼此不可见**,然后由你自己比对分歧、下判断;只有在出现实质分歧时,才把对方的**理由**回传给各自,要求逐条反驳或让步。
194
249
 
@@ -211,7 +266,7 @@ const BOSS_TEMPLATE = `## 模型路由:强主脑(你负责判断,可验证
211
266
  不确定有哪些授权路由时先调 \`list_subagent_models\`。
212
267
 
213
268
  **"需要独立审查/复核"本身不是升级理由**。复核默认交给普通子代理(\`delegate_task\` 不传 \`provider\`/\`model\`,走配置的执行路由);只有当**被复核的东西本身**满足上面第 1 条时才点名专家。
214
- 派出子代理后不要反复轮询:\`delegate_task\` 前台调用会直接返回结果;需要查看在线子代理、追加消息或停止时,用 \`list_agents\` / \`send_message\` / \`interrupt_agent\`。
269
+ \`delegate_task\` 启动后立即返回子会话 id,完成时由运行时通知;不要反复轮询。需要查看在线子代理、追加消息或停止时,用 \`list_agents\` / \`send_message\` / \`interrupt_agent\`。
215
270
 
216
271
  原生 \`subagent\` 仍是**显式专家入口**:在本模式下,它若不带**完整**的 provider/model 对会被拒绝并指向 \`delegate_task\`——这是为了不让"顺手用 subagent"绕过执行路由默认值。
217
272
 
@@ -270,18 +325,18 @@ export function renderTemplate(template, renderContext) {
270
325
  * 为空时用内置模板 + 占位符渲染。
271
326
  *
272
327
  * @param role - 'root' 或 'child'。
273
- * @param model - 本次 assembly 的模型 ID。
274
- * @param renderContext - `{executor, experts, texts}`;纯函数调用时可省略。
328
+ * @param route - 本次请求的 `{provider, model}`(子代忽略)。
329
+ * @param renderContext - `{executor, economyRoutes, experts, texts}`;纯函数调用时可省略。
275
330
  * @returns 该段应渲染的文本。
276
331
  */
277
- export function routingTextFor(role, model, renderContext) {
332
+ export function routingTextFor(role, route, renderContext) {
278
333
  const context = renderContext ?? {};
279
334
  const texts = context.texts ?? {};
280
335
  if (role === 'child') {
281
336
  const override = typeof texts.child === 'string' ? texts.child : '';
282
337
  return override !== '' ? override : CHILD_TEXT;
283
338
  }
284
- const mode = modeForModel(model);
339
+ const mode = modeForRoute(route, context);
285
340
  const override = mode === MODE_ECONOMIZE ? texts.economize : texts.boss;
286
341
  if (typeof override === 'string' && override !== '') return override;
287
342
  const template = mode === MODE_ECONOMIZE ? ECONOMIZE_TEMPLATE : BOSS_TEMPLATE;
@@ -289,18 +344,20 @@ export function routingTextFor(role, model, renderContext) {
289
344
  }
290
345
 
291
346
  /**
292
- * 取本次 assembly 的主模型。缺失/空值必须**明确报错**,不许猜模型
293
- * (猜错会把整段策略换成另一套,而且不报错)。
347
+ * 取本次 assembly 的路由。`provider`/`model` 两个变量由宿主 agent-loop 注册
348
+ * (`systemPrompt.variable("provider"/"model")`);model 缺失/空值必须**明确报错**,
349
+ * 不许猜模型(猜错会把整段策略换成另一套,而且不报错)。
294
350
  * @param assembly - 已完成 `await next()` 的提示词 assembly。
295
- * @returns 模型 ID 字符串。
351
+ * @returns `{provider, model}`(provider 缺失时为空串)。
296
352
  * @throws 当 `assembly.variables.model` 缺失或为空时。
297
353
  */
298
- export function modelFromAssembly(assembly) {
354
+ export function routeFromAssembly(assembly) {
299
355
  const model = assembly?.variables?.model;
300
356
  if (typeof model !== 'string' || model === '') {
301
357
  throw new Error('dsh-submodel: system-prompt assembly has no `variables.model`; cannot classify the top-level mode without it');
302
358
  }
303
- return model;
359
+ const provider = assembly?.variables?.provider;
360
+ return { provider: typeof provider === 'string' ? provider : '', model };
304
361
  }
305
362
 
306
363
  /**
@@ -310,3 +367,317 @@ export function modelFromAssembly(assembly) {
310
367
  export function childDelegationRefusal() {
311
368
  return 'this session is a delegated subagent: it cannot delegate further. Report the limitation to your parent instead of retrying.';
312
369
  }
370
+
371
+ // ── 自动配置向导(`configure_submodel`)的纯函数层 ─────────────────────────────
372
+ //
373
+ // 这里只做**确定性推导**:候选排序、三问结构、答案解析、两处配置的合并。
374
+ // 宿主服务(llm / userQuestions / configEditor)一律留在 setup.js,本文件保持零 import,
375
+ // 这样向导最容易出错的部分(解析与写回值)可以纯函数单测。
376
+
377
+ /** 自动配置向导的工具名(root + autoConfigure + executor 未配置时唯一顶层注册)。 */
378
+ export const SETUP_TOOL_NAME = 'configure_submodel';
379
+
380
+ /** 向导三问的稳定 id(回答按 id 回填)。 */
381
+ export const SETUP_QUESTION_EXECUTOR = 'executor';
382
+ export const SETUP_QUESTION_EXPERTS = 'experts';
383
+ export const SETUP_QUESTION_AUTHORIZE = 'authorize';
384
+
385
+ /** 宿主「子代理模型选择」授权表的配置行 id。 */
386
+ export const HOST_SELECTION_ENTRY_ID = 'subagent-model-selection-settings';
387
+
388
+ /** 省钱/快档模型关键词(只用于预填顺序,不替用户决定)。 */
389
+ export const ECONOMY_KEYWORDS = Object.freeze([
390
+ 'flash',
391
+ 'lite',
392
+ 'mini',
393
+ 'nano',
394
+ 'air',
395
+ 'small',
396
+ 'fast',
397
+ 'turbo',
398
+ 'haiku',
399
+ ]);
400
+
401
+ /** 强推理/专家模型关键词(只用于预填顺序,不替用户决定)。 */
402
+ export const STRONG_KEYWORDS = Object.freeze([
403
+ 'opus',
404
+ 'pro',
405
+ 'max',
406
+ 'ultra',
407
+ 'reason',
408
+ 'deep',
409
+ 'sonnet',
410
+ 'o3',
411
+ 'o4',
412
+ 'r1',
413
+ 'gpt-6',
414
+ ]);
415
+
416
+ /** 路由的展示标签:`provider/model`(也是 options 的 label,回答时按它回填)。 */
417
+ function routeLabel(route) {
418
+ return `${route.provider}/${route.model}`;
419
+ }
420
+
421
+ /** 把文字拆成路由:只接受 `provider/model`(第一个 `/` 之前是 provider)。 */
422
+ function splitRouteLabel(text) {
423
+ if (typeof text !== 'string') return undefined;
424
+ const value = text.trim();
425
+ const index = value.indexOf('/');
426
+ if (index <= 0 || index === value.length - 1) return undefined;
427
+ const provider = value.slice(0, index).trim();
428
+ const model = value.slice(index + 1).trim();
429
+ if (provider === '' || model === '') return undefined;
430
+ return { provider, model };
431
+ }
432
+
433
+ /** 候选的确定性排序:分高优先,再按命中数与 provider/model 字典序兜底。 */
434
+ function compareCandidates(a, b) {
435
+ if (b.score !== a.score) return b.score - a.score;
436
+ if (b.economyHits !== a.economyHits) return b.economyHits - a.economyHits;
437
+ if (b.strongHits !== a.strongHits) return b.strongHits - a.strongHits;
438
+ if (a.provider !== b.provider) return a.provider < b.provider ? -1 : 1;
439
+ if (a.model !== b.model) return a.model < b.model ? -1 : 1;
440
+ return 0;
441
+ }
442
+
443
+ /**
444
+ * 把 `llm.listProviders()/listModels()` 的结果整理成向导候选。
445
+ *
446
+ * 打分只用于**预填顺序**(宿主模型元数据没有价格字段,无法可靠推断贵贱):
447
+ * - 经济关键词命中数 + 强推理关键词命中数 → 分组(economy / strong / unknown);
448
+ * - 命中宿主 `allowedModels` +3(已授权的路由优先出现,少一次手动授权);
449
+ * - 关键词只看 `model` 与 `name`,不看 `description`(描述里常见 "provider" 之类的误命中)。
450
+ *
451
+ * @param pack - `[{provider, model, name?, description?}]`(来自 llm 服务)。
452
+ * @param host - `{enabled, allowedModels:[{provider, model}]}` 或 undefined。
453
+ * @returns 候选数组(已排序);每项 `{provider, model, name, description, group, economyHits, strongHits, authorized, score}`。
454
+ */
455
+ export function deriveSetupCandidates(pack, host) {
456
+ const allowed = new Set(
457
+ (Array.isArray(host?.allowedModels) ? host.allowedModels : [])
458
+ .filter((route) => route !== null && typeof route === 'object')
459
+ .map((route) => routeKey(route)),
460
+ );
461
+ const candidates = [];
462
+ for (const entry of Array.isArray(pack) ? pack : []) {
463
+ if (entry === null || typeof entry !== 'object') continue;
464
+ const provider = typeof entry.provider === 'string' ? entry.provider : '';
465
+ const model = typeof entry.model === 'string' ? entry.model : '';
466
+ if (model === '') continue;
467
+ const name = typeof entry.name === 'string' ? entry.name : '';
468
+ const description = typeof entry.description === 'string' ? entry.description : '';
469
+ const haystack = `${model} ${name}`.toLowerCase();
470
+ const economyHits = ECONOMY_KEYWORDS.filter((keyword) => haystack.includes(keyword)).length;
471
+ const strongHits = STRONG_KEYWORDS.filter((keyword) => haystack.includes(keyword)).length;
472
+ const authorized = allowed.has(routeKey({ provider, model }));
473
+ // 平票时归经济组:强推理关键词含 `deep`,而 `deepseek-flash` 这类名字会同时命中
474
+ // `deep`(来自 deepseek)与 `flash`。若不把平票判成 economy,两者会互相抵消成 unknown,
475
+ // 结果这个最常见的执行路由既不进 executor 候选、也不进 experts 候选(只能手打 custom)。
476
+ const group = strongHits > economyHits ? 'strong' : economyHits > 0 ? 'economy' : 'unknown';
477
+ candidates.push({
478
+ provider,
479
+ model,
480
+ name,
481
+ description,
482
+ group,
483
+ economyHits,
484
+ strongHits,
485
+ authorized,
486
+ score: economyHits + strongHits + (authorized ? 3 : 0),
487
+ });
488
+ }
489
+ candidates.sort(compareCandidates);
490
+ return candidates;
491
+ }
492
+
493
+ /** 把一个候选渲染成问题选项(label 即回填键 `provider/model`)。 */
494
+ function candidateOption(candidate) {
495
+ const detail = [candidate.name, candidate.description].filter((part) => typeof part === 'string' && part !== '').join(' — ');
496
+ return {
497
+ label: routeLabel(candidate),
498
+ ...(detail === '' ? {} : { description: detail }),
499
+ };
500
+ }
501
+
502
+ /**
503
+ * 由候选构造向导的三问(中文;单选/多选/单选)。
504
+ *
505
+ * - `executor`:经济组前 8;不足时用强推理组补齐;
506
+ * - `experts`:强推理组前 10(可跳过;自定义文本可补一条 `provider/model`);
507
+ * - `authorize`:是否同时写宿主授权表(`yes` 推荐 / `no`)。
508
+ *
509
+ * @param candidates - `deriveSetupCandidates` 的结果。
510
+ * @returns 问题数组(顺序稳定)。
511
+ */
512
+ export function buildSetupQuestions(candidates) {
513
+ const list = Array.isArray(candidates) ? candidates : [];
514
+ const executorCandidates = list.filter((candidate) => candidate.group === 'economy').slice(0, 8);
515
+ if (executorCandidates.length < 8) {
516
+ executorCandidates.push(
517
+ ...list.filter((candidate) => candidate.group === 'strong').slice(0, 8 - executorCandidates.length),
518
+ );
519
+ }
520
+ const expertCandidates = list.filter((candidate) => candidate.group === 'strong').slice(0, 10);
521
+ return [
522
+ {
523
+ id: SETUP_QUESTION_EXECUTOR,
524
+ question: '选择「执行路由」:日常执行、批量检索与可并行的子任务默认派给它(便宜/快的模型)。',
525
+ options: executorCandidates.map(candidateOption),
526
+ multiSelect: false,
527
+ },
528
+ {
529
+ id: SETUP_QUESTION_EXPERTS,
530
+ question: '选择「专家路由」:需要更强推理时才升级用,可多选;不需要可直接跳过。',
531
+ options: expertCandidates.map(candidateOption),
532
+ multiSelect: true,
533
+ },
534
+ {
535
+ id: SETUP_QUESTION_AUTHORIZE,
536
+ question: '是否同时把以上路由写入宿主「子代理模型选择」授权表?',
537
+ options: [
538
+ {
539
+ label: 'yes',
540
+ description: '推荐:同时写宿主授权,新会话即可直接派工(不写的话首次派工会被宿主拒绝)。',
541
+ },
542
+ {
543
+ label: 'no',
544
+ description: '只写本插件配置;之后需要按 README 手动补宿主授权,否则派工报 is not allowed for this Session。',
545
+ },
546
+ ],
547
+ multiSelect: false,
548
+ },
549
+ ];
550
+ }
551
+
552
+ /**
553
+ * 解析向导回答。`selected` 必须是候选里出现过的选项标签;`custom` 只接受
554
+ * `provider/model` 形式(存在性由 setup.js 用 `llm.resolveModelInfo` 再校验)。
555
+ *
556
+ * 跳过语义(与官方 `ask_user_question` 一致):`selected` 为空且无 `custom` 表示用户跳过——
557
+ * executor 是必填所以报错,experts 视为不配,authorize 视为 `false`(不写宿主授权)。
558
+ *
559
+ * @param answers - `userQuestions.ask` 返回的 `answers` 数组。
560
+ * @param candidates - `deriveSetupCandidates` 的结果(用于校验 selected 属于候选)。
561
+ * @returns `{ok:true, executor, experts, authorize, customRoutes}` 或 `{ok:false, reason}`。
562
+ */
563
+ export function parseSetupAnswers(answers, candidates) {
564
+ const list = Array.isArray(answers) ? answers : [];
565
+ const known = new Set((Array.isArray(candidates) ? candidates : []).map((candidate) => routeKey(candidate)));
566
+ const byId = new Map();
567
+ for (const answer of list) {
568
+ if (answer === null || typeof answer !== 'object') continue;
569
+ if (typeof answer.id === 'string') byId.set(answer.id, answer);
570
+ }
571
+ const customRoutes = [];
572
+
573
+ const parseSelectedRoute = (label) => {
574
+ const route = splitRouteLabel(label);
575
+ if (route === undefined) return { ok: false, reason: `选项不是 provider/model 形式:${String(label)}` };
576
+ if (!known.has(routeKey(route))) return { ok: false, reason: `选项不在候选列表:${String(label)}` };
577
+ return { ok: true, route };
578
+ };
579
+
580
+ // ① 执行路由(必填单选):custom 覆盖 selected。
581
+ const executorAnswer = byId.get(SETUP_QUESTION_EXECUTOR);
582
+ let executor;
583
+ const executorCustom = typeof executorAnswer?.custom === 'string' ? executorAnswer.custom.trim() : '';
584
+ if (executorCustom !== '') {
585
+ const route = splitRouteLabel(executorCustom);
586
+ if (route === undefined) return { ok: false, reason: `执行路由必须是 provider/model 形式:${executorCustom}` };
587
+ executor = route;
588
+ customRoutes.push(route);
589
+ } else {
590
+ const selected = Array.isArray(executorAnswer?.selected) ? executorAnswer.selected : [];
591
+ if (selected.length === 0) return { ok: false, reason: '未选择执行路由' };
592
+ const parsed = parseSelectedRoute(selected[0]);
593
+ if (!parsed.ok) return { ok: false, reason: parsed.reason };
594
+ executor = parsed.route;
595
+ }
596
+
597
+ // ② 专家路由(可多选;custom 可补一条)。
598
+ const expertsAnswer = byId.get(SETUP_QUESTION_EXPERTS);
599
+ const selectedExperts = Array.isArray(expertsAnswer?.selected) ? expertsAnswer.selected : [];
600
+ const experts = [];
601
+ for (const label of selectedExperts) {
602
+ const parsed = parseSelectedRoute(label);
603
+ if (!parsed.ok) return { ok: false, reason: parsed.reason };
604
+ experts.push(parsed.route);
605
+ }
606
+ const expertsCustom = typeof expertsAnswer?.custom === 'string' ? expertsAnswer.custom.trim() : '';
607
+ if (expertsCustom !== '') {
608
+ const route = splitRouteLabel(expertsCustom);
609
+ if (route === undefined) return { ok: false, reason: `专家路由必须是 provider/model 形式:${expertsCustom}` };
610
+ experts.push(route);
611
+ customRoutes.push(route);
612
+ }
613
+ const seen = new Set();
614
+ const dedupedExperts = [];
615
+ for (const route of experts) {
616
+ const key = routeKey(route);
617
+ if (seen.has(key)) continue;
618
+ seen.add(key);
619
+ dedupedExperts.push(route);
620
+ }
621
+
622
+ // ③ 宿主授权(跳过视为不写;非法标签报错)。
623
+ const authorizeAnswer = byId.get(SETUP_QUESTION_AUTHORIZE);
624
+ const authorizeSelected = Array.isArray(authorizeAnswer?.selected) ? authorizeAnswer.selected : [];
625
+ let authorize = false;
626
+ if (authorizeSelected.length > 0) {
627
+ const label = authorizeSelected[0];
628
+ if (label !== 'yes' && label !== 'no') return { ok: false, reason: `无法识别的授权选项:${String(label)}` };
629
+ authorize = label === 'yes';
630
+ }
631
+
632
+ return { ok: true, executor, experts: dedupedExperts, authorize, customRoutes };
633
+ }
634
+
635
+ /**
636
+ * 合并出写入本插件配置行的下一个原始配置:保留其他字段,覆写 executor / experts / economyRoutes。
637
+ * @param current - 插件行当前原始配置(`configEditor.edit` 的 curr)。
638
+ * @param selection - `parseSetupAnswers` 的 selection。
639
+ * @returns 下一个原始配置对象。
640
+ */
641
+ export function composeNextPluginConfig(current, selection) {
642
+ const base = current !== null && typeof current === 'object' && !Array.isArray(current) ? current : {};
643
+ const executor = {
644
+ provider: selection.executor.provider,
645
+ model: selection.executor.model,
646
+ reasoningEffort: 'max',
647
+ };
648
+ const experts = (Array.isArray(selection.experts) ? selection.experts : []).map((route) => ({
649
+ label: routeLabel(route),
650
+ provider: route.provider,
651
+ model: route.model,
652
+ }));
653
+ return {
654
+ ...base,
655
+ executor,
656
+ experts,
657
+ economyRoutes: [{ provider: executor.provider, model: executor.model }],
658
+ };
659
+ }
660
+
661
+ /**
662
+ * 合并出写入宿主授权行的下一个原始配置:去重合并且保留原有顺序。
663
+ * @param current - 宿主行当前原始配置(`configEditor.edit` 的 curr)。
664
+ * @param routes - 本次要授权的路由数组(executor + experts)。
665
+ * @returns 下一个原始配置对象(`enabled: true` + 合并后的 `allowedModels`)。
666
+ */
667
+ export function composeNextHostConfig(current, routes) {
668
+ const base = current !== null && typeof current === 'object' && !Array.isArray(current) ? current : {};
669
+ const existing = Array.isArray(base.allowedModels) ? base.allowedModels : [];
670
+ const merged = [];
671
+ const seen = new Set();
672
+ for (const route of [...existing, ...(Array.isArray(routes) ? routes : [])]) {
673
+ if (route === null || typeof route !== 'object') continue;
674
+ const provider = typeof route.provider === 'string' ? route.provider : '';
675
+ const model = typeof route.model === 'string' ? route.model : '';
676
+ if (provider === '' || model === '') continue;
677
+ const key = routeKey({ provider, model });
678
+ if (seen.has(key)) continue;
679
+ seen.add(key);
680
+ merged.push({ provider, model });
681
+ }
682
+ return { ...base, enabled: true, allowedModels: merged };
683
+ }