dsh-submodel 0.3.0 → 0.4.1

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
@@ -93,6 +93,7 @@ export function isEconomyRoute(route, cfg) {
93
93
  if (executor?.provider && executor?.model && executor.provider === route.provider && executor.model === route.model) {
94
94
  return true;
95
95
  }
96
+ if (cfg?.modelGroups?.executors?.some(model => routeKey(model) === routeKey(route))) return true;
96
97
  const economyRoutes = Array.isArray(cfg?.economyRoutes) ? cfg.economyRoutes : [];
97
98
  if (
98
99
  economyRoutes.some(
@@ -188,11 +189,25 @@ export function classifyExplicitRoute(args) {
188
189
  return { kind: 'none' };
189
190
  }
190
191
 
192
+ /**
193
+ * 在两组里找 pair 所在行的默认档位。重合 pair 时专家优先(与 tier 判定同口径)。
194
+ * 未配置(空串/缺省)返回 undefined,表示交给模型自身默认。
195
+ */
196
+ function configuredRowEffort(groups, route) {
197
+ if (!groups) return undefined;
198
+ const search = (rows) => (Array.isArray(rows) ? rows : []).find(
199
+ (row) => row && row.provider === route.provider && row.model === route.model,
200
+ );
201
+ const row = search(groups.experts) ?? search(groups.executors);
202
+ return typeof row?.reasoningEffort === 'string' && row.reasoningEffort !== '' ? row.reasoningEffort : undefined;
203
+ }
204
+
191
205
  /**
192
206
  * 计算这次委派的最终子代参数。
193
207
  *
194
208
  * 规则(四类分支都要覆盖):
195
- * - **完整显式 pair**:原样保留,**不注入策略 effort**(让原生规则决定继承兼容 effort 或清掉不兼容的);
209
+ * - **完整显式 pair**:pair 原样保留;保存了两组列表且该模型配置了默认档位、调用又没点名时补上,
210
+ * 调用点名档位优先,未配置不动(交给原生规则决定继承兼容 effort 或清掉不兼容的);
196
211
  * - **只给一个**:失败(见 classifyExplicitRoute);
197
212
  * - **无显式路由 + economize 模式**:不补任何 provider/model(子代继承当前经济路由);
198
213
  * - **无显式路由 + boss 模式**:补配置的 executor pair;未给 reasoning_effort 时补 max,
@@ -204,14 +219,22 @@ export function classifyExplicitRoute(args) {
204
219
  * @param args - 原始工具入参(**只读,不修改**)。
205
220
  * @param mode - modeForRoute 的结果。
206
221
  * @param executor - 配置的 `{provider, model, reasoningEffort}`。
222
+ * @param modelGroups - 保存的两组有序列表;未保存时为 undefined,显式 pair 不补档位。
207
223
  * @returns `{ok:true, args: newArgs, applied: 'explicit'|'executor'|'inherit'}` 或 `{ok:false, reason}`。
208
224
  */
209
- export function resolveDelegationArgs(args, mode, executor) {
225
+ export function resolveDelegationArgs(args, mode, executor, modelGroups) {
210
226
  const route = classifyExplicitRoute(args);
211
227
  if (route.kind === 'invalid') return { ok: false, reason: route.reason };
212
228
  // 派生新对象:原 exec/arguments 由 tools runtime 冻结,改不得。
213
229
  const next = { ...args };
214
- if (route.kind === 'pair') return { ok: true, args: next, applied: 'explicit' };
230
+ if (route.kind === 'pair') {
231
+ const configured = configuredRowEffort(modelGroups, route);
232
+ if (configured !== undefined &&
233
+ (next.reasoning_effort === undefined || next.reasoning_effort === null || next.reasoning_effort === '')) {
234
+ next.reasoning_effort = configured;
235
+ }
236
+ return { ok: true, args: next, applied: 'explicit' };
237
+ }
215
238
  if (mode !== MODE_BOSS) {
216
239
  return { ok: true, args: next, applied: 'inherit' };
217
240
  }
@@ -221,8 +244,10 @@ export function resolveDelegationArgs(args, mode, executor) {
221
244
  next.provider = executor.provider;
222
245
  next.model = executor.model;
223
246
  if (next.reasoning_effort === undefined || next.reasoning_effort === null || next.reasoning_effort === '') {
224
- // 只在"没给"时补默认;给了就保留调用方/配置的原值。
225
- next.reasoning_effort = executor.reasoningEffort ?? 'max';
247
+ // Empty in the stored executor means the selected model's own default.
248
+ const effort = executor.reasoningEffort ?? 'max';
249
+ if (effort === '') delete next.reasoning_effort;
250
+ else next.reasoning_effort = effort;
226
251
  }
227
252
  return { ok: true, args: next, applied: 'executor' };
228
253
  }
@@ -238,12 +263,13 @@ const ECONOMIZE_TEMPLATE = `## 模型路由:Flash 主脑(主脑自己干,
238
263
  1. 问题本身属于**复杂代码/逻辑判断**——跨模块契约、状态机、并发与时序、不可逆数据变更、多方案权衡,且你自己无法自证;
239
264
  2. 任务本身超出你的执行上限(反复失败、需要更强推理才能推进)。
240
265
 
241
- 已配置的专家路由(升级时从这里点名,\`provider\` 与 \`model\` 必须成对传):
242
- {{expertRoutes}}
266
+ {{economyChoices}}
243
267
 
244
268
  **"需要独立审查/复核"本身不是升级理由**。复核默认交给普通子代理(\`delegate_task\` 不传 \`provider\`/\`model\`,子代继承当前路由);只有当**被复核的东西本身**满足上面第 1 条时才点名专家。
245
269
 
246
- 调用方式:普通任务统一走 \`delegate_task\`,它的参数与原生 \`subagent\` 相同,启动后立即返回子会话 id,完成时由运行时通知;不要反复轮询,查看/追加/停止子代理用 \`list_agents\` / \`send_message\` / \`interrupt_agent\`。\`provider\` 与 \`model\` 必须**成对**传,只给一个会立即失败。不确定有哪些授权路由时先调 \`list_subagent_models\`。\`reasoning_effort\` 以各路由支持的档位为准,不传时用配置缺省,显式档位优先。三个都不传就继承主模型路由,即默认路径。升级前先把证据收齐,并把已知事实、约束、已试过的方案写进 prompt——子智能体看不到本会话历史。
270
+ 调用方式:普通任务统一走 \`delegate_task\`,参数与原生 \`subagent\` 相同。启动后立即返回子代理名称,完成时由运行时通知。需要看护的显式专家任务也走 \`delegate_task\`。\`provider\` 与 \`model\` 必须**成对**传。三个选择参数都不传就继承主模型路由。升级前把已知事实、约束和已试方案写进 prompt,子代理看不到本会话历史。
271
+
272
+ {{controlTools}}
247
273
 
248
274
  需要多方校验或讨论时:在同一条消息里并发起两个 \`delegate_task\`,给**完全相同**的 brief 且**彼此不可见**,然后由你自己比对分歧、下判断;只有在出现实质分歧时,才把对方的**理由**回传给各自,要求逐条反驳或让步。
249
275
 
@@ -260,15 +286,14 @@ const BOSS_TEMPLATE = `## 模型路由:强主脑(你负责判断,可验证
260
286
  1. 问题本身属于**复杂代码/逻辑判断**——跨模块契约、状态机、并发与时序、不可逆数据变更、多方案权衡,且你自己无法自证;
261
287
  2. 任务本身超出你的执行上限(反复失败、需要更强推理才能推进)。
262
288
 
263
- 已配置的专家路由:
264
- {{expertRoutes}}
265
-
266
- 不确定有哪些授权路由时先调 \`list_subagent_models\`。
289
+ {{bossChoices}}
267
290
 
268
291
  **"需要独立审查/复核"本身不是升级理由**。复核默认交给普通子代理(\`delegate_task\` 不传 \`provider\`/\`model\`,走配置的执行路由);只有当**被复核的东西本身**满足上面第 1 条时才点名专家。
269
- \`delegate_task\` 启动后立即返回子会话 id,完成时由运行时通知;不要反复轮询。需要查看在线子代理、追加消息或停止时,用 \`list_agents\` / \`send_message\` / \`interrupt_agent\`。
292
+ \`delegate_task\` 启动后立即返回子代理名称,完成时由运行时通知。需要看护的显式专家任务也走 \`delegate_task\`。
293
+
294
+ {{controlTools}}
270
295
 
271
- 原生 \`subagent\` 仍是**显式专家入口**:在本模式下,它若不带**完整**的 provider/model 对会被拒绝并指向 \`delegate_task\`——这是为了不让"顺手用 subagent"绕过执行路由默认值。
296
+ 原生 \`subagent\` 仍可显式派专家:在本模式下,它若不带**完整**的 provider/model 对会被拒绝并指向 \`delegate_task\`。
272
297
 
273
298
  子代回来后按证据复核,不要只读它的结论。子智能体失败或超时时,明确标注"未获得该路线的结果"并降级为自证,不得假装已咨询过。`;
274
299
 
@@ -281,7 +306,21 @@ const CHILD_TEXT = `## 你的角色:被委派的执行 / 专家子智能体
281
306
  1. 只做被要求的事,不擅自扩大范围、不顺手重构;
282
307
  2. 需要读文件/跑命令就实际去读、去跑——**不要凭记忆或推断作答**;
283
308
  3. 汇报时给出**原始证据**:实际读了哪个文件(绝对路径)、实际命令与关键输出、关键行号,以及你验证过什么、没验证什么;
284
- 4. 结论与证据分开写。不确定就明说"不确定",不要用更像样的措辞掩盖没验证的部分。`;
309
+ 4. 结论与证据分开写。不确定就明说"不确定",不要用更像样的措辞掩盖没验证的部分。
310
+
311
+ {{controlTools}}`;
312
+
313
+ /** Only advertise tools the Host admitted for this assembly. */
314
+ function controlText(visibleTools) {
315
+ const visible = new Set(visibleTools);
316
+ const lines = ['以真实完成通知为准。空闲或等待超时只表示结果待核对。'];
317
+ if (visible.has('list_agents')) lines.push('用 `list_agents({})` 查看协作树,以行里的 `name` 寻址子代理。');
318
+ if (visible.has('send_message')) lines.push('用 `send_message({agent,message})` 发信。投递回执不是对方答复。');
319
+ if (visible.has('wait_agent')) lines.push('用 `wait_agent({timeout_ms})` 等待消息或完成通知,避免反复轮询。');
320
+ if (visible.has('interrupt_agent')) lines.push('用 `interrupt_agent({agent})` 请求停止自己的后代。停止是否完成,以实际结果为准。');
321
+ if (visible.has('list_subagent_models')) lines.push('用 `list_subagent_models` 查询已授权模型。');
322
+ return lines.join('\n');
323
+ }
285
324
 
286
325
  /** 执行路由的渲染形式;未配置时给可读占位而不是空串。 */
287
326
  function renderExecutorRoute(executor) {
@@ -303,19 +342,45 @@ export function renderExpertRoutes(experts) {
303
342
  return rows.join('\n');
304
343
  }
305
344
 
345
+ function renderGroupedModels(groups, role) {
346
+ const rows = groups[role];
347
+ if (rows.length === 0) return '- (未配置)';
348
+ return rows.map((row, index) => {
349
+ const note = typeof row.note === 'string' ? row.note.replace(/[\s\p{Cc}\p{Cf}]+/gu, ' ').trim() : '';
350
+ const choice = JSON.stringify({ provider: row.provider, model: row.model });
351
+ return `${index + 1}. ${choice}${note ? ` · 用途 ${JSON.stringify(note)}` : ''}`;
352
+ }).join('\n');
353
+ }
354
+
355
+ function groupedGuidance(groups) {
356
+ return [
357
+ '性价比模型(执行任务)', renderGroupedModels(groups, 'executors'),
358
+ '', '专家模型(需要升级判断时)', renderGroupedModels(groups, 'experts'),
359
+ '',
360
+ '主动选模型时,先选用途备注匹配的模型,没有匹配就选组内首位。用 `delegate_task` 指定完整 provider/model。省略它们时沿用本段的默认派活方式。',
361
+ '若已开启自动换模型,原模型用完重试(默认 5 次)后,符合条件的任务会从所选位置沿组内顺序继续。改派以通知为准。',
362
+ ].join('\n');
363
+ }
364
+
306
365
  /**
307
- * 用运行期配置渲染模板:只替换 `{{executorRoute}}` 与 `{{expertRoutes}}`,其余原样保留。
366
+ * 用运行期配置渲染模板:只替换识别的占位符。
308
367
  * @param template - 内置模板字符串。
309
368
  * @param renderContext - `{executor, experts, texts}`(缺字段按空处理)。
310
369
  * @returns 渲染后的正文。
311
370
  */
312
371
  export function renderTemplate(template, renderContext) {
313
372
  const context = renderContext ?? {};
314
- const executorRoute = renderExecutorRoute(context.executor);
315
373
  const expertRoutes = renderExpertRoutes(context.experts);
316
- return String(template)
317
- .split('{{executorRoute}}').join(executorRoute)
318
- .split('{{expertRoutes}}').join(expertRoutes);
374
+ const replacements = {
375
+ executorRoute: renderExecutorRoute(context.executor),
376
+ expertRoutes,
377
+ economyChoices: context.modelGroups ? groupedGuidance(context.modelGroups)
378
+ : '已配置的专家路由(升级时从这里点名,`provider` 与 `model` 必须成对传):\n' + expertRoutes,
379
+ bossChoices: context.modelGroups ? groupedGuidance(context.modelGroups) : '已配置的专家路由:\n' + expertRoutes,
380
+ controlTools: controlText(context.visibleTools),
381
+ };
382
+ return String(template).replace(/\{\{(\w+)\}\}/gu, (placeholder, name) =>
383
+ Object.hasOwn(replacements, name) ? replacements[name] : placeholder);
319
384
  }
320
385
 
321
386
  /**
@@ -334,7 +399,7 @@ export function routingTextFor(role, route, renderContext) {
334
399
  const texts = context.texts ?? {};
335
400
  if (role === 'child') {
336
401
  const override = typeof texts.child === 'string' ? texts.child : '';
337
- return override !== '' ? override : CHILD_TEXT;
402
+ return override !== '' ? override : renderTemplate(CHILD_TEXT, context);
338
403
  }
339
404
  const mode = modeForRoute(route, context);
340
405
  const override = mode === MODE_ECONOMIZE ? texts.economize : texts.boss;
@@ -381,6 +446,8 @@ export const SETUP_TOOL_NAME = 'configure_submodel';
381
446
  export const SETUP_QUESTION_EXECUTOR = 'executor';
382
447
  export const SETUP_QUESTION_EXPERTS = 'experts';
383
448
  export const SETUP_QUESTION_AUTHORIZE = 'authorize';
449
+ const AUTHORIZE_HOST = '同时授权';
450
+ const SAVE_PREFERENCES = '只保存偏好';
384
451
 
385
452
  /** 宿主「子代理模型选择」授权表的配置行 id。 */
386
453
  export const HOST_SELECTION_ENTRY_ID = 'subagent-model-selection-settings';
@@ -536,12 +603,12 @@ export function buildSetupQuestions(candidates) {
536
603
  question: '是否同时把以上路由写入宿主「子代理模型选择」授权表?',
537
604
  options: [
538
605
  {
539
- label: 'yes',
540
- description: '推荐:同时写宿主授权,新会话即可直接派工(不写的话首次派工会被宿主拒绝)。',
606
+ label: AUTHORIZE_HOST,
607
+ description: '把所选模型加入已有允许列表,让新会话可以派给这些模型。已有会话保持原授权。',
541
608
  },
542
609
  {
543
- label: 'no',
544
- description: '只写本插件配置;之后需要按 README 手动补宿主授权,否则派工报 is not allowed for this Session。',
610
+ label: SAVE_PREFERENCES,
611
+ description: '只保存这里的模型选择。需要派给未授权模型时,请到子代理设置里单独允许。',
545
612
  },
546
613
  ],
547
614
  multiSelect: false,
@@ -625,37 +692,37 @@ export function parseSetupAnswers(answers, candidates) {
625
692
  let authorize = false;
626
693
  if (authorizeSelected.length > 0) {
627
694
  const label = authorizeSelected[0];
628
- if (label !== 'yes' && label !== 'no') return { ok: false, reason: `无法识别的授权选项:${String(label)}` };
629
- authorize = label === 'yes';
695
+ if (authorizeSelected.length !== 1 || (label !== AUTHORIZE_HOST && label !== SAVE_PREFERENCES)) {
696
+ return { ok: false, reason: '无法识别的授权选项' };
697
+ }
698
+ authorize = label === AUTHORIZE_HOST && !authorizeAnswer?.custom?.trim();
630
699
  }
631
700
 
632
701
  return { ok: true, executor, experts: dedupedExperts, authorize, customRoutes };
633
702
  }
634
703
 
635
704
  /**
636
- * 合并出写入本插件配置行的下一个原始配置:保留其他字段,覆写 executor / experts / economyRoutes。
705
+ * 保留其他字段,以一笔写入保存两组模型与经济路由。
637
706
  * @param current - 插件行当前原始配置(`configEditor.edit` 的 curr)。
638
707
  * @param selection - `parseSetupAnswers` 的 selection。
639
708
  * @returns 下一个原始配置对象。
640
709
  */
641
710
  export function composeNextPluginConfig(current, selection) {
642
711
  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 }],
712
+ const executor = { provider: selection.executor.provider, model: selection.executor.model, note: '', reasoningEffort: '' };
713
+ const previous = base.modelGroups?.experts ?? (Array.isArray(base.experts) ? base.experts : []);
714
+ const modelGroups = {
715
+ executors: [executor],
716
+ experts: (selection.experts ?? []).map(({ provider, model }) => {
717
+ const existing = previous.find(row => row && routeKey(row) === routeKey({ provider, model }));
718
+ const note = existing?.note ?? existing?.label ?? '';
719
+ return { provider, model, note: note.slice(0, 120), reasoningEffort: existing?.reasoningEffort ?? '' };
720
+ }),
658
721
  };
722
+ const economyRoutes = Array.isArray(base.economyRoutes) && base.economyRoutes.length > 0
723
+ ? base.economyRoutes
724
+ : [{ provider: executor.provider, model: executor.model }];
725
+ return { ...base, economyRoutes, modelGroups };
659
726
  }
660
727
 
661
728
  /**
package/lib/setup.js CHANGED
@@ -1,33 +1,4 @@
1
- /**
2
- * dsh-submodel / setup.js —— 自动配置向导 `configure_submodel`。
3
- *
4
- * ## 为什么是「探测 + 一张确认卡」而不是纯自动
5
- *
6
- * 宿主 `llm` 服务的模型元数据只有 `id/name/description/context`,**没有价格字段**
7
- * (`resolveModelInfo` 的返回里也没有)。纯自动只能靠模型名猜贵贱,开源后一定会把活
8
- * 派错模型,而且不报错。所以这里把「探测」与「决定」拆开:本模块探测候选并预填顺序,
9
- * 用户点一次卡完成选择,同时把花钱风险交回用户。
10
- *
11
- * ## 为什么必须连宿主授权表一起写
12
- *
13
- * `dsh-tool-subagent` 在会话没有记录 model-selection policy 时只允许父路由;不写
14
- * `allowedModels`,执行路由与专家路由第一次调用就报
15
- * `child LLM route "…" is not allowed for this Session`——这是 README「5 行配置」不完整的根因。
16
- * 写入走官方 `configEditor`(带锁、原子写、失败回滚),不自改 YAML、不建私有状态文件。
17
- *
18
- * ## 写入顺序:先宿主、后插件
19
- *
20
- * 宿主字段是 `.volatile()`,写入即时生效且不重载插件;插件配置写入会重载本插件并销毁
21
- * 正在执行的本工具注册。因此宿主授权先写、插件配置最后写,返回文案在写之前拼好。
22
- * 写成功后本工具实例会被卸载——属预期,不是失败。
23
- *
24
- * ## 失败降级
25
- *
26
- * 任何宿主服务缺失/异常(llm、userQuestions、configEditor、宿主授权行)都**不抛**,
27
- * 降级为「未写入原因 + 手动两步 YAML」返回给模型;只有非 root 调用才抛错。
28
- *
29
- * @module dsh-submodel/setup
30
- */
1
+ import { CONFIG_ENTRY, SETUP_FIELDS, executorConfigured, settingOps } from './config.js';
31
2
  import {
32
3
  HOST_SELECTION_ENTRY_ID,
33
4
  SETUP_TOOL_NAME,
@@ -39,209 +10,149 @@ import {
39
10
  roleOf,
40
11
  } from './policy.js';
41
12
 
42
- /** 本插件在 profile 补丁里的配置行 id(cordis.patch.yml 的 insert 行)。 */
43
- const PLUGIN_ENTRY_ID = 'submodel';
13
+ const MANUAL_CONFIG = [
14
+ '请在插件页选择执行模型,再到「子代理」设置允许相应模型。新会话会读取保存的设置和授权。',
15
+ '没有设置页面时,可以按维护文档分别配置这两行:',
16
+ '',
17
+ '- id: subagent-model-selection-settings',
18
+ ' config:',
19
+ ' enabled: true',
20
+ ' allowedModels:',
21
+ ' - { provider: your-provider, model: your-model }',
22
+ '- id: submodel',
23
+ ' config:',
24
+ ' modelGroups:',
25
+ ' executors:',
26
+ ' - { provider: your-provider, model: your-model, note: "日常执行", reasoningEffort: "" }',
27
+ ' experts: []',
28
+ ].join('\n');
44
29
 
45
- /** 路由的展示文本。 */
46
- function routeText(route) {
47
- return `${route.provider}/${route.model}`;
48
- }
49
-
50
- /** 自动配置不可用时给用户的手动两步配置(示例路由零本机信息)。 */
51
- function manualConfigText() {
52
- return [
53
- '请在 profile 补丁层(cordis.patch.yml)手动完成两步配置,然后新开会话:',
54
- '',
55
- '① 宿主授权(加到已有行或新增该行):',
56
- '- id: subagent-model-selection-settings',
57
- ' config:',
58
- ' enabled: true',
59
- ' allowedModels:',
60
- ' - { provider: your-provider, model: your-model }',
61
- '',
62
- '② 本插件配置:',
63
- '- id: submodel',
64
- ' config:',
65
- ' executor:',
66
- ' provider: your-provider',
67
- ' model: your-model',
68
- ' reasoningEffort: max',
69
- ' experts: []',
70
- ' economyRoutes:',
71
- ' - { provider: your-provider, model: your-model }',
72
- ].join('\n');
73
- }
74
-
75
- /**
76
- * 收集宿主当前可用的 provider/model。
77
- * 单个 provider 的 `listModels` 失败只跳过该 provider,不影响整体(best-effort)。
78
- * @param llm - 宿主 llm 服务。
79
- * @returns `[{provider, model, name, description}]`。
80
- */
81
- async function collectRoutes(llm) {
30
+ async function collectRoutes(llm, signal) {
82
31
  const pack = [];
83
- let providers;
84
- try {
85
- providers = llm.listProviders();
86
- } catch {
87
- return pack;
88
- }
89
- for (const provider of Array.isArray(providers) ? providers : []) {
90
- const providerId = provider?.id;
91
- if (typeof providerId !== 'string' || providerId === '') continue;
92
- let models;
32
+ const providers = llm.listProviders();
33
+ for (const { id: provider } of providers) {
34
+ signal?.throwIfAborted();
93
35
  try {
94
- models = await llm.listModels(providerId);
36
+ const models = await llm.listModels(provider, signal);
37
+ for (const model of models) {
38
+ if (!model.id) continue;
39
+ pack.push({ provider, model: model.id, name: model.name ?? '' });
40
+ }
95
41
  } catch {
96
- continue;
97
- }
98
- for (const model of Array.isArray(models) ? models : []) {
99
- if (typeof model?.id !== 'string' || model.id === '') continue;
100
- pack.push({
101
- provider: providerId,
102
- model: model.id,
103
- name: typeof model.name === 'string' ? model.name : '',
104
- description: typeof model.description === 'string' ? model.description : '',
105
- });
42
+ signal?.throwIfAborted();
106
43
  }
107
44
  }
108
45
  return pack;
109
46
  }
110
47
 
111
- /**
112
- * 创建 `configure_submodel` 工具定义。
113
- *
114
- * @param options - 依赖注入:
115
- * - `ctx`:**插件顶层 ctx**(用 `ctx.get(...)` 取服务、`ctx.fiber.entry` 定位本插件配置行);
116
- * - `config`:插件原始配置(保留字段时用,允许为空);
117
- * - `logger`:日志器。
118
- * @returns 可直接 `agent.ctx.tools.register(...)` 的工具定义。
119
- */
48
+ function readableRow(rows, ns) {
49
+ const row = rows.find(item => item.ns === ns);
50
+ return Number.isSafeInteger(row?.revision) && row.value && typeof row.value === 'object' ? row : undefined;
51
+ }
52
+
53
+ function unavailable(reason) {
54
+ return `${reason}\n\n${MANUAL_CONFIG}`;
55
+ }
56
+
57
+ const REOPEN = '设置已在别处更新。请重新打开设置后确认修改。';
58
+ const GRANT_REVIEW = '请在「子代理」设置复查;授权对新会话生效。';
59
+
60
+ /** The two user decisions have separate revision fences and separate results. */
120
61
  export function createSetupTool({ ctx, config, logger }) {
121
- void config; // 写回值时以 configEditor 的当前原始配置为基准,不重新拼整个 config。
122
- /** 同一 agent 的并发保护:正在提问时第二次调用直接返回,不重复弹卡。 */
123
62
  let asking = false;
124
63
 
125
- /** 真正执行:所有失败降级为文本,不抛(非 root 调用由外层抛)。 */
126
64
  async function run(exec) {
127
- const signal = exec?.signal;
65
+ const { agent, signal } = exec;
66
+ const settings = ctx.get('settings');
128
67
  const llm = ctx.get('llm');
129
- if (llm === undefined || llm === null) {
130
- return `configure_submodel: 当前宿主没有可用的 llm 服务,无法自动探测路由,未写入任何配置。\n\n${manualConfigText()}`;
131
- }
132
68
  const userQuestions = ctx.get('userQuestions');
133
- if (userQuestions === undefined || userQuestions === null) {
134
- return `configure_submodel: 当前宿主没有提问服务(纯 CLI 会话常见),无法弹卡,未写入任何配置。\n\n${manualConfigText()}`;
135
- }
136
-
137
- // ① 探测候选(best-effort;空则引导用户先配置渠道)。
138
- const pack = await collectRoutes(llm);
139
- if (pack.length === 0) {
140
- return `configure_submodel: 还没有可用的渠道/模型(或它们全部无法列出)。请先在设置里配置渠道与密钥后重试。\n\n${manualConfigText()}`;
141
- }
69
+ if (!settings?.writable || !llm || !userQuestions) return unavailable('当前无法自动保存设置。');
142
70
 
143
- // ② 宿主当前授权状态(best-effort,仅用于候选排序与预填)。
144
- let host;
71
+ let pack;
72
+ let rows;
145
73
  try {
146
- host = ctx.get('subagentModelSelection')?.current?.();
74
+ pack = await collectRoutes(llm, signal);
75
+ rows = settings.describe();
147
76
  } catch {
148
- host = undefined;
77
+ return unavailable('暂时无法读取模型或设置。');
149
78
  }
79
+ if (executorConfigured(config)) return REOPEN;
80
+ const preferences = readableRow(rows, CONFIG_ENTRY);
81
+ const host = readableRow(rows, HOST_SELECTION_ENTRY_ID);
82
+ if (!preferences) return unavailable('当前找不到可写的插件设置。');
83
+ if (pack.length === 0) return unavailable('暂时没有可选模型。请先在模型设置中添加模型。');
150
84
 
151
- // ③ 一张卡问三题:执行路由 / 专家路由 / 是否写宿主授权。
152
- const candidates = deriveSetupCandidates(pack, host);
85
+ const candidates = deriveSetupCandidates(pack, host?.value);
153
86
  const questions = buildSetupQuestions(candidates);
154
- let answer;
87
+ let parsed;
155
88
  try {
156
- answer = await userQuestions.ask({ questions, agent: exec?.agent, signal });
157
- } catch (error) {
158
- const detail = error?.code ?? error?.message ?? String(error);
159
- return `configure_submodel: 未能完成提问(${String(detail)}),未写入任何配置。\n\n${manualConfigText()}`;
89
+ const result = await userQuestions.ask({ questions: questions.slice(0, 2), agent, signal });
90
+ parsed = parseSetupAnswers(result?.answers, candidates);
91
+ } catch {
92
+ return unavailable('模型选择未完成。');
160
93
  }
94
+ if (!parsed.ok) return unavailable('请重新选择一个有效的执行模型。');
161
95
 
162
- // ④ 解析回答:selected 必须来自候选;custom 只接受 provider/model,且要过 llm 存在性校验。
163
- const parsed = parseSetupAnswers(answer?.answers, candidates);
164
- if (!parsed.ok) {
165
- return `configure_submodel: 回答无效(${parsed.reason}),未写入任何配置。\n\n${manualConfigText()}`;
166
- }
167
96
  for (const route of parsed.customRoutes) {
168
97
  try {
169
- await llm.resolveModelInfo(route.provider, route.model, signal);
98
+ const model = await llm.resolveModelInfo(route.provider, route.model, signal);
99
+ if (model == null) return unavailable('找不到所填模型。');
170
100
  } catch {
171
- return `configure_submodel: 自定义路由 ${routeText(route)} 在宿主里不存在,未写入任何配置。\n\n${manualConfigText()}`;
101
+ return unavailable('暂时无法验证所填模型。');
172
102
  }
173
103
  }
174
104
 
175
- // ⑤ 定位本插件配置行(写插件配置会在成功后卸载本工具实例,属预期)。
176
- const editor = ctx.get('configEditor');
177
- if (editor === undefined || editor === null) {
178
- return `configure_submodel: 当前宿主没有配置编辑器(非 GUI / 只读 profile),无法自动写配置。\n\n${manualConfigText()}`;
179
- }
180
- let entries;
105
+ let confirmation;
181
106
  try {
182
- entries = editor.entries();
107
+ const result = await userQuestions.ask({ questions: questions.slice(2), agent, signal });
108
+ confirmation = parseSetupAnswers([
109
+ { id: 'executor', custom: `${parsed.executor.provider}/${parsed.executor.model}` },
110
+ ...(result?.answers ?? []).filter(answer => answer.id === 'authorize'),
111
+ ], candidates);
183
112
  } catch {
184
- entries = undefined;
185
- }
186
- if (!Array.isArray(entries)) {
187
- return `configure_submodel: 读取 profile 配置失败,未写入任何配置。\n\n${manualConfigText()}`;
188
- }
189
- const entry = ctx.fiber?.entry ?? entries.find((row) => row?.options?.id === PLUGIN_ENTRY_ID);
190
- if (entry === undefined) {
191
- return `configure_submodel: 找不到本插件(id=${PLUGIN_ENTRY_ID})的配置行,未写入任何配置。\n\n${manualConfigText()}`;
113
+ return unavailable('未完成授权选择,设置尚未保存。');
192
114
  }
115
+ if (!confirmation.ok || signal?.aborted) return unavailable('未完成授权选择,设置尚未保存。');
193
116
 
194
- // ⑥ 先写宿主授权(volatile、即时生效、不重载);失败只记录并继续写插件配置。
195
- const hostRoutes = [parsed.executor, ...parsed.experts];
196
- let hostNote;
197
- if (!parsed.authorize) {
198
- hostNote = '宿主授权未写入(按你的选择)';
199
- } else {
200
- const hostEntry = entries.find((row) => row?.options?.id === HOST_SELECTION_ENTRY_ID);
201
- if (hostEntry === undefined) {
202
- hostNote = '宿主授权行不存在,请按 README 手动添加该行';
117
+ let hostNote = '已保留原有授权。';
118
+ if (confirmation.authorize) {
119
+ if (!host) {
120
+ hostNote = '授权未写入。请在「子代理」设置手动允许所选模型。';
203
121
  } else {
204
122
  try {
205
- await editor.edit(hostEntry, (current) => composeNextHostConfig(current, hostRoutes));
206
- hostNote = '宿主授权已写入(只对新会话生效)';
123
+ const allowed = composeNextHostConfig(host.value, [parsed.executor, ...parsed.experts]);
124
+ await settings.mutate(HOST_SELECTION_ENTRY_ID, settingOps(['enabled', 'allowedModels'], allowed), host.revision);
125
+ hostNote = `已保存授权。${GRANT_REVIEW}`;
207
126
  } catch (error) {
208
- logger?.warn?.(`dsh-submodel: configure_submodel 写宿主授权失败: ${String(error)}`);
209
- hostNote = `宿主授权写入失败(${String(error?.message ?? error)}),请按 README 手动添加该行`;
127
+ logger?.warn?.('dsh-submodel: setup authorization write refused');
128
+ hostNote = error?.code === 'SETTINGS_CONFLICT'
129
+ ? `授权未写入。${REOPEN}`
130
+ : '授权未写入。请在「子代理」设置手动允许所选模型。';
210
131
  }
211
132
  }
212
133
  }
213
134
 
214
- // ⑦ 返回文案在写插件配置**之前**拼好:写入会卸载本实例,写后可能拿不到执行权。
215
- const summary =
216
- `已写入执行路由 ${routeText(parsed.executor)}、${parsed.experts.length} 条专家路由、` +
217
- `economyRoutes=[${routeText(parsed.executor)}];${hostNote}。新会话生效(宿主授权只对新会话生效)。`;
218
-
219
- // ⑧ 再写插件配置(触发本插件重载,放最后)。
135
+ if (signal?.aborted) return `插件设置尚未保存。${hostNote}`;
220
136
  try {
221
- await editor.edit(entry, (current) => composeNextPluginConfig(current, parsed));
137
+ const next = composeNextPluginConfig(preferences.value, parsed);
138
+ await settings.mutate(CONFIG_ENTRY, settingOps(SETUP_FIELDS, next), preferences.revision);
222
139
  } catch (error) {
223
- logger?.warn?.(`dsh-submodel: configure_submodel 写插件配置失败: ${String(error)}`);
224
- return `configure_submodel: 插件配置写入失败(${String(error?.message ?? error)});${hostNote}。\n\n${manualConfigText()}`;
140
+ logger?.warn?.('dsh-submodel: setup preference write refused');
141
+ const reason = error?.code === 'SETTINGS_CONFLICT' ? REOPEN : '插件设置未保存。请重试。';
142
+ return `${reason}${hostNote}`;
225
143
  }
226
- return summary;
144
+ return `已保存模型选择。新会话使用此配置。${hostNote}`;
227
145
  }
228
146
 
229
147
  return {
230
148
  name: SETUP_TOOL_NAME,
231
- description:
232
- 'Configure subagent routing by asking the user once: pick the executor route, pick expert routes, ' +
233
- 'and optionally authorize those routes in the host subagent model-selection table. ' +
234
- 'Only available while no executor route is configured.',
235
- parameters: {},
236
- output: {
237
- schema: { type: 'string' },
238
- render: (_args, value) => [{ type: 'text', text: String(value) }],
239
- },
149
+ description: 'Set the execution model for new sessions. Ask separately before adding model authorization.',
150
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
151
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
240
152
  async execute(_args, exec) {
241
- if (roleOf(exec?.agent) !== 'root') {
242
- throw new Error('configure_submodel is only available to a top-level agent (delegated subagents cannot configure routing)');
243
- }
244
- if (asking) return 'configure_submodel: 配置进行中,请先回答当前弹卡;不要重复调用。';
153
+ if (!exec?.agent || roleOf(exec.agent) !== 'root') throw new Error('Only the main conversation can configure delegation.');
154
+ if (executorConfigured(config)) return REOPEN;
155
+ if (asking) return '配置进行中,请先回答当前问题。';
245
156
  asking = true;
246
157
  try {
247
158
  return await run(exec);