dsh-submodel 0.1.0 → 0.3.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/delegation.js CHANGED
@@ -5,27 +5,34 @@
5
5
  *
6
6
  * 原生的创建校验(allowlist / LLM preflight / permission / depth / persona / toolFilter)
7
7
  * 全部发生在 `@deepseek-ai/dsh-tool-subagent` 的 `execute` 内部,**在创建孩子之前**
8
- * (`dsh-tool-subagent/lib/index.js:491-506`)。绕过它去 `subagents.startContinuable(...)`
9
- * 就等于同时绕过授权与预检——那正是本模块**不能**做的事。
8
+ * (0.2.2:`dsh-tool-subagent/lib/index.js` 的 `subagent` 工具定义里,`execute(args, exec)`
9
+ * 先读 policy、再 assert 允许路由、再 preflight、最后才 `ctx.subagents.startActivation(...)`)。
10
+ * 绕过它去 `subagents.startActivation(...)` 就等于同时绕过授权与预检——那正是本模块**不能**做的事。
10
11
  *
11
- * 所以本工具只做两件事:**改参数** + **经公开 `ctx.tools.execute` 发起一次真正的原生调用**
12
- * (`dsh-tools/lib/index.js:3116` 是公开入口)。这样原生的一切校验照旧生效。
12
+ * 所以本工具只做两件事:**改参数** + **经公开 `ctx.tools.execute` 发起一次真正的原生调用**。
13
13
  *
14
- * ## 三个必须遵守的坑(都已在源码确认,别踩)
14
+ * ## 0.2.2 的四个契约(都已在本机安装版源码确认,别按 0.2.1 的记忆改)
15
15
  *
16
- * 1. **同层同名注册会冲突**(`dsh-tools:2878`),所以本工具叫 `delegate_task`,
17
- * 不叫 `subagent`,也不能去 shadow 它。
18
- * 2. **body 的返回值一律被当成"成功 value"**(`dsh-tools:3540`):直接 return 一个
19
- * `isError:true` 的子结果**不会**变成错误——外层仍是成功。所以 inner.isError 时
20
- * **必须抛 Error**,由外层统一materialize 成失败结果。
21
- * 3. **嵌套调用要带全 token 链**:`callId`(派生)、`rootCallId`(继承)、`parent`(exec.token)、
22
- * 同一个 `signal`。漏掉任一项,原生的事件归属或取消传播就会错位。
16
+ * 1. **工具执行 API 是批量签名**(0.2.2 起的硬变更):`ctx.tools.execute(input)`,
17
+ * `input = {calls:[{id,name,arguments}], signal, agent?, toolSet?, log?, maxParallelToolCalls?}`
18
+ * (`dsh-tools/lib/pipeline.js` 的 `executeToolBatch` 解构即证)。返回
19
+ * `{results:[{callId,result}], additionalContexts, concluded}`;
20
+ * `arguments` 必须是 **JSON 文本**(pipeline 里 `parseArguments` 会 `JSON.parse`),
21
+ * 单次调用就是"只含一个 call 的批量"。
22
+ * 2. **没有 `parent` / `rootCallId` 通道**:批量 API 不暴露它们,`exec` 里也没有 turn/step。
23
+ * 因此嵌套调用在事件归属上与顶层调用无法区分(`parent` 现在只有 PTC 内部用)。
24
+ * 本模块**不传 `log`**:0.2.1 的 `execute` 同样不写 `tool/call`/`tool/result`,不传才与旧行为一致。
25
+ * 3. **body 的返回值一律被当成"成功 value"**(`dsh-tools/lib/pipeline.js` 的
26
+ * `createSuccessResult` / `normalizeDispatchResult`):直接 return 一个 `isError:true` 的结果
27
+ * **不会**变成错误——外层仍是成功。所以取到的 result `isError` 时必须**抛 Error**,
28
+ * 由外层统一 materialize 成失败结果。
29
+ * 4. **同层同名注册会冲突**:所以本工具叫 `delegate_task`,不叫 `subagent`,也不能去 shadow 它。
23
30
  *
24
31
  * @module dsh-submodel/delegation
25
32
  */
26
33
  import {
27
34
  DELEGATE_TOOL_NAME,
28
- MODE_BOSS,
35
+ modeForRoute,
29
36
  resolveCallerRole,
30
37
  resolveDelegationArgs,
31
38
  } from './policy.js';
@@ -33,12 +40,23 @@ import {
33
40
  /** 子调用 callId 的后缀:既能被日志一眼认出,又不会和原生 callId 撞(原生用随机 id)。 */
34
41
  const NESTED_CALL_SUFFIX = ':delegate';
35
42
 
43
+ /** 子调用固定走原生 `subagent` 工具名。 */
44
+ const NESTED_TOOL_NAME = 'subagent';
45
+
46
+ /**
47
+ * 宿主拒绝显式路由时的追加提示:这是"宿主授权表没配置"的典型症状,不给出路模型只会重试。
48
+ * 与原生错误同语言(英文),并点名两个修复入口。
49
+ */
50
+ const SESSION_ROUTE_HINT =
51
+ 'hint: enable the host subagent model selection setting and add this route to its `allowedModels`, ' +
52
+ 'or run `configure_submodel` (or follow the README two-step configuration) to write both the plugin config and the host authorization.';
53
+
36
54
  /**
37
55
  * 从原生 `subagent` 的工具定义深拷贝参数 schema。
38
56
  *
39
57
  * **必须是"每次安装时从本轮 native 定义取"**,不能把 schema 写死在源码里:native 定义
40
- * 会随 DSH 升级增删参数,写死就等于把新参数悄悄丢掉。`parameters` 是结构化的普通对象
41
- * (`structuredClone` 在 `dsh-system-prompt:327` 也是这么拷的),可安全深拷贝。
58
+ * 会随 DSH 升级增删参数,写死就等于把新参数悄悄丢掉。`parameters` 是结构化 JSON Schema
59
+ * (普通对象),可安全深拷贝。
42
60
  *
43
61
  * @param nativeDefinition - 本会话可见的原生 subagent 工具定义。
44
62
  * @returns 参数 schema 深拷贝。
@@ -60,14 +78,18 @@ export function cloneNativeParameters(nativeDefinition) {
60
78
  * `hasTopLevelProvider=false` / `hasPropertiesProvider=true`;读顶层会恒为 false,于是本函数
61
79
  * 永远返回 undefined、整条安装路径静默跳过(四个工具一个都不出现)。
62
80
  *
81
+ * **0.2.2 复验(2026-11-10)**:`provider`/`model` 参数只在 `dsh-tool-subagent` 的
82
+ * `modelSelection:true` 时才加入 schema(Config 默认 false)。Desktop/Web preset 为 spawn
83
+ * 启用该开关,所以本机判据仍然成立;但它是**弱判据**——换了 `toolName` 或关掉
84
+ * `modelSelection` 的部署里会判不出,那时宁可不装。
85
+ *
63
86
  * @param tools - 工具注册表(ctx.tools)。
64
87
  * @param scope - 观看作用域:**传 agent 对象本身**。宿主自己的调用范式就是这样
65
- * (`dsh-file-reference-local:346` 的 `agent.ctx.tools.get("read", agent)`、`dsh-tools:3140`
66
- * 的 `this.get(name, agent)`);传 `agent.ctx` 会退化成 global 视图,永远查不到 scoped 工具。
88
+ * (`dsh-tool-subagent/lib/index.js` 的系统提示段也写 `ctx.tools.get(tool.name, context.scope)`)。
67
89
  * @returns 原生定义或 undefined。
68
90
  */
69
91
  export function findNativeSubagent(tools, scope) {
70
- const definition = tools.get?.('subagent', scope);
92
+ const definition = tools.get?.(NESTED_TOOL_NAME, scope);
71
93
  if (definition === undefined) return undefined;
72
94
  const properties = definition.parameters?.properties;
73
95
  const hasRouteParams = properties?.provider !== undefined && properties?.model !== undefined;
@@ -75,23 +97,43 @@ export function findNativeSubagent(tools, scope) {
75
97
  }
76
98
 
77
99
  /**
78
- * 组装嵌套调用要用的子参数与 token 链。**纯计算**,便于单测。
100
+ * 组装嵌套调用要用的批量输入。**纯计算**,便于单测。
101
+ *
102
+ * 0.2.2 只认批量形状:`calls[].arguments` 是 JSON 文本,返回结果按 `callId` 对回。
103
+ * `toolSet` 只在存在时透传(与当前步的准入集一致;`toolSet.view(scope)` 在 scope 不匹配时
104
+ * 返回空 Map,所以 `agent` 必须是本步 resolve 时的同一个 agent 对象)。
105
+ *
79
106
  * @param outerExec - 外层(delegate_task 自己的)exec。
80
107
  * @param newArgs - 已解析好的子代参数。
81
- * @returns `{callId, rootCallId, name, arguments, agent, parent, signal}`。
108
+ * @returns `ToolBatchInput` 片段(可直接交给 `ctx.tools.execute`)。
82
109
  */
83
110
  export function buildNestedCall(outerExec, newArgs) {
84
111
  return {
85
- callId: `${outerExec.callId}${NESTED_CALL_SUFFIX}`,
86
- rootCallId: outerExec.rootCallId ?? outerExec.callId,
87
- name: 'subagent',
88
- arguments: newArgs,
112
+ calls: [
113
+ {
114
+ id: `${outerExec.callId}${NESTED_CALL_SUFFIX}`,
115
+ name: NESTED_TOOL_NAME,
116
+ arguments: JSON.stringify(newArgs),
117
+ },
118
+ ],
89
119
  agent: outerExec.agent,
90
- parent: outerExec.token,
91
120
  signal: outerExec.signal,
121
+ ...(outerExec.toolSet === undefined ? {} : { toolSet: outerExec.toolSet }),
92
122
  };
93
123
  }
94
124
 
125
+ /**
126
+ * 从批量结果里取本次子调用的 result。找不到返回 undefined(调用方必须当失败处理)。
127
+ * @param batch - `ctx.tools.execute` 的返回值。
128
+ * @param callId - 本模块派生的子调用 id。
129
+ * @returns 子调用的 result 快照或 undefined。
130
+ */
131
+ export function resultOfNestedCall(batch, callId) {
132
+ const results = batch?.results;
133
+ if (!Array.isArray(results)) return undefined;
134
+ return results.find((entry) => entry?.callId === callId)?.result;
135
+ }
136
+
95
137
  /**
96
138
  * 把子的失败结果转成一段**可读诊断**(保留原始信息,不吞)。
97
139
  * @param inner - 原生调用返回的结果快照。
@@ -114,6 +156,29 @@ export function describeInnerFailure(inner) {
114
156
  if (block?.type === 'text' && typeof block.text === 'string' && block.text !== '') parts.push(block.text);
115
157
  }
116
158
  if (parts.length === 0) parts.push('the nested subagent call failed without a diagnostic');
159
+ const text = parts.join('\n');
160
+ // 宿主对"未授权路由"的拒绝是 0.2.x 最常见的失败;原样返回会让模型只是重试,补一句修复入口。
161
+ if (text.includes('is not allowed for this Session')) return `${text}\n${SESSION_ROUTE_HINT}`;
162
+ return text;
163
+ }
164
+
165
+ /**
166
+ * 把批量执行器抛出的内部错误转成可读诊断。
167
+ *
168
+ * 0.2.2 的 `executeToolBatch` 只把**调度器内部失败**包成 `ToolBatchExecutionError`,
169
+ * message 固定是 "Tool batch execution failed",根因在 `cause` 里——不把 cause 带出来,
170
+ * 模型就只会看到那句通用文案。
171
+ * @param error - 抛出的错误。
172
+ * @returns 诊断文本。
173
+ */
174
+ export function describeBatchFailure(error) {
175
+ const parts = [String(error?.message ?? error)];
176
+ let cause = error?.cause;
177
+ for (let depth = 0; cause !== undefined && cause !== null && depth < 3; depth += 1) {
178
+ const message = typeof cause?.message === 'string' ? cause.message : String(cause);
179
+ if (message !== '') parts.push(`caused by: ${message}`);
180
+ cause = cause?.cause;
181
+ }
117
182
  return parts.join('\n');
118
183
  }
119
184
 
@@ -121,13 +186,16 @@ export function describeInnerFailure(inner) {
121
186
  * 创建 `delegate_task` 的工具定义。
122
187
  *
123
188
  * @param options - 依赖注入(全部来自 live agent 的 scope):
124
- * - `ctx`:该 agent 的 runtime context(提供 tools/subagents)
189
+ * - `ctx`:该 agent 的 runtime context(提供 tools)
125
190
  * - `nativeDefinition`:本轮原生 subagent 定义(参数与 output 的来源)
126
191
  * - `executor`:配置的执行路由 `{provider, model, reasoningEffort}`
192
+ * - `economyRoutes`:配置的经济路由列表(执行期模式判定用)
127
193
  * - `logger`:日志器
128
194
  * @returns 可直接 `ctx.tools.register(...)` 的工具定义。
129
195
  */
130
- export function createDelegateTool({ ctx, nativeDefinition, executor, logger }) {
196
+ export function createDelegateTool({ ctx, nativeDefinition, executor, economyRoutes = [], logger }) {
197
+ /** 执行期模式判定用的运行期策略(与 policy.js 纯函数同口径)。 */
198
+ const routingPolicy = { executor, economyRoutes: Array.isArray(economyRoutes) ? economyRoutes : [] };
131
199
  const parameters = cloneNativeParameters(nativeDefinition);
132
200
  // output 同样复用原生 schema/render,保持 runId/agentId 与 foreground/continuable 格式一致。
133
201
  const output = nativeDefinition.output;
@@ -138,9 +206,10 @@ export function createDelegateTool({ ctx, nativeDefinition, executor, logger })
138
206
  return {
139
207
  name: DELEGATE_TOOL_NAME,
140
208
  description:
141
- 'Delegate one independent task to a subagent and return its result. ' +
209
+ 'Delegate one independent task to a subagent. It starts an independently managed subagent and ' +
210
+ 'immediately returns its id; the runtime notifies you when it finishes. ' +
142
211
  'Parameters are identical to the native `subagent` tool. Omit provider/model to inherit the ' +
143
- 'current route (Flash) or use the configured cheap executor route (non-Flash). ' +
212
+ 'current route or use the configured execution route. ' +
144
213
  'An explicit route must name provider AND model together. ' +
145
214
  'Prefer this over the raw `subagent` tool for ordinary delegation.',
146
215
  parameters,
@@ -154,10 +223,11 @@ export function createDelegateTool({ ctx, nativeDefinition, executor, logger })
154
223
  // ② 同步快照执行期模式,再 await:描述"当前发起这笔调用的主脑",
155
224
  // 不读 GUI 里可能中途变化的 pending selection。
156
225
  const accepted = caller.header?.config ?? caller.agent.options ?? {};
157
- const mode = (() => {
158
- const model = accepted.model;
159
- return typeof model === 'string' && model.toLowerCase().endsWith('flash') ? 'economize' : MODE_BOSS;
160
- })();
226
+ const route = {
227
+ provider: typeof accepted?.provider === 'string' ? accepted.provider : '',
228
+ model: typeof accepted?.model === 'string' ? accepted.model : '',
229
+ };
230
+ const mode = modeForRoute(route, routingPolicy);
161
231
 
162
232
  // ③ 解析最终子代参数(原 exec/arguments 不可变,派生新对象)。
163
233
  const resolved = resolveDelegationArgs(args, mode, executor);
@@ -168,18 +238,32 @@ export function createDelegateTool({ ctx, nativeDefinition, executor, logger })
168
238
  `route=${resolved.applied} -> ${resolved.args.provider ?? '(inherit)'}/${resolved.args.model ?? '(inherit)'}`,
169
239
  );
170
240
 
171
- // ④ 发起一次真正的原生调用:保留它的全部校验与事件链。
241
+ // ④ 发起一次真正的原生调用:保留它的全部校验与事件链(0.2.2 批量签名)。
172
242
  const nested = buildNestedCall(exec, resolved.args);
173
- const inner = await ctx.tools.execute(nested);
243
+ const callId = nested.calls[0].id;
244
+ let batch;
245
+ try {
246
+ batch = await ctx.tools.execute(nested);
247
+ } catch (error) {
248
+ throw new Error(`delegate_task: nested tool batch failed: ${describeBatchFailure(error)}`);
249
+ }
250
+
251
+ const inner = resultOfNestedCall(batch, callId);
252
+ if (inner === undefined) {
253
+ throw new Error(
254
+ 'delegate_task: the nested `subagent` call produced no result (the batch was aborted, ' +
255
+ 'or the tool was not admitted for this step)',
256
+ );
257
+ }
174
258
 
175
- // ⑤ inner.isError 必须**抛出**:body 返回 error 对象会被当成功 value(dsh-tools:3540)。
176
- if (inner?.isError === true) {
259
+ // ⑤ inner.isError 必须**抛出**:body 返回 error 对象会被当成功 value(见文件头契约 3)。
260
+ if (inner.isError === true) {
177
261
  throw new Error(describeInnerFailure(inner));
178
262
  }
179
263
 
180
264
  // ⑥ 转移延迟上下文 / 结论标记,再只返回 inner.value。
181
- for (const context of inner?.additionalContexts ?? []) exec.deferContext(context);
182
- if (inner?.concludesTurn === true) exec.concludeTurn();
265
+ for (const context of inner.additionalContexts ?? []) exec.deferContext(context);
266
+ if (inner.concludesTurn === true) exec.concludeTurn();
183
267
 
184
268
  return inner.value;
185
269
  },
package/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * dsh-submodel / index.js —— 插件入口(v0.1.0)。
3
3
  *
4
- * 职责:全局注册**唯一的策略提示词段**;`enabled` 时再对每个合格的 standard agent 安装
4
+ * 职责:全局注册策略提示词段及可选的团队队形自检段;`enabled` 时再对每个合格的 standard agent 安装
5
5
  * scoped 能力(提示词段正文替换、角色 guard、统一委派入口 `delegate_task`),并在
6
6
  * Agent 释放 / 组合变化 / 配置重载时**准确卸载自己装的东西**。
7
7
  *
@@ -44,11 +44,14 @@ import {
44
44
  ROUTING_ORDER,
45
45
  ROUTING_SECTION,
46
46
  childDelegationRefusal,
47
- modelFromAssembly,
47
+ isEconomyRoute,
48
48
  roleOf,
49
+ routeFromAssembly,
49
50
  routingTextFor,
50
51
  } from './policy.js';
52
+ import { TEAM_FIT_SECTION, teamFitTextFor } from './team-fit.js';
51
53
  import { createDelegateTool, findNativeSubagent } from './delegation.js';
54
+ import { createSetupTool } from './setup.js';
52
55
 
53
56
  export const name = 'dsh-submodel';
54
57
 
@@ -60,6 +63,8 @@ export const Config = z.object({
60
63
  enabled: z.boolean().default(true),
61
64
  /** 只对这一个 composition 生效;其他 preset 不安装任何东西。 */
62
65
  preset: z.string().default('standard'),
66
+ /** 团队队形自检单独启用,且服从自动策略总开关。 */
67
+ teamFit: z.object({ enabled: z.boolean().default(false) }).default({ enabled: false }),
63
68
  /** 能力门控工具名:该 scope 不可见时策略段不渲染(工具仍按注册门控安装)。 */
64
69
  toolName: z.string().default('list_subagent_models'),
65
70
  /** 段顺序;默认紧接 TOOL_SUBAGENT(2800)。 */
@@ -92,10 +97,23 @@ export const Config = z.object({
92
97
  child: z.string().default(''),
93
98
  }).default({ economize: '', boss: '', child: '' }),
94
99
  /**
95
- * 是否安装"非 Flash 顶层用原生 subagent 时必须给完整显式 pair"的 guard。
100
+ * 是否安装"非经济路由顶层用原生 subagent 时必须给完整显式 pair"的 guard。
96
101
  * 默认开启;关掉后原生 subagent 的行为完全交给宿主。
97
102
  */
98
103
  guardNativeSubagent: z.boolean().default(true),
104
+ /**
105
+ * 自动配置开关:root 且 `executor` 未配置时注册 `configure_submodel` 向导
106
+ * (探测宿主渠道/模型 → 一张卡确认 → 写插件配置 + 宿主授权表)。默认开启。
107
+ */
108
+ autoConfigure: z.boolean().default(true),
109
+ /**
110
+ * 经济路由列表:主模型命中其中一项即走 economize 模式(不再要求模型名以 flash 结尾)。
111
+ * 每项 `{provider?, model}`;`provider` 为空时只比 model。为空数组时保留 flash 后缀兼容。
112
+ */
113
+ economyRoutes: z.array(z.object({
114
+ provider: z.string().default(''),
115
+ model: z.string().min(1),
116
+ })).default([]),
99
117
  });
100
118
 
101
119
  /** 判断一个 agent 是否属于本插件负责的 composition。 */
@@ -110,6 +128,17 @@ function belongsToComposition(agent, presetId, presetService) {
110
128
  }
111
129
  }
112
130
 
131
+ /** 团队服务是首选。回退时只看本步获准的工具,注册表在团队关闭时也有同名工具。 */
132
+ function teamEnabledFor(ctx, agent, toolSet) {
133
+ try {
134
+ const teams = ctx.get('agentTeams');
135
+ if (teams != null) return teams.isEnabled(agent) === true;
136
+ } catch {
137
+ // 服务不可用时仍可从这次 assembly 的工具集合取得正向证据。
138
+ }
139
+ return toolSet != null && ctx.tools.get('team_task_create', agent, toolSet) !== undefined;
140
+ }
141
+
113
142
  export function apply(ctx, config) {
114
143
  const enabled = config.enabled === true;
115
144
  const presetId = config.preset ?? 'standard';
@@ -126,9 +155,25 @@ export function apply(ctx, config) {
126
155
  boss: config.texts?.boss ?? '',
127
156
  child: config.texts?.child ?? '',
128
157
  };
158
+ const economyRoutes = Array.isArray(config.economyRoutes)
159
+ ? config.economyRoutes
160
+ .filter(
161
+ (row) =>
162
+ row !== null &&
163
+ typeof row === 'object' &&
164
+ typeof row.model === 'string' &&
165
+ row.model !== '',
166
+ )
167
+ .map((row) => ({ provider: typeof row.provider === 'string' ? row.provider : '', model: row.model }))
168
+ : [];
129
169
  const guardNativeSubagent = config.guardNativeSubagent !== false;
170
+ const autoConfigure = config.autoConfigure !== false;
171
+ /** 模式判定用的运行期策略(与 policy.js 纯函数同口径)。 */
172
+ const routingPolicy = { executor, economyRoutes };
130
173
  /** 每次 assembly 现渲染正文用的运行期上下文(纯函数层只认它)。 */
131
- const renderContext = { executor, experts, texts };
174
+ const renderContext = { executor, experts, texts, economyRoutes };
175
+ /** 执行路由是否未配置(未配置时才注册自动配置向导)。 */
176
+ const executorIncomplete = executor.provider === '' || executor.model === '';
132
177
 
133
178
  /** 每个 agent 的 assembly listener 装的文本解析器:`(resolved) => string|null`。 */
134
179
  const textResolvers = new WeakMap();
@@ -147,9 +192,40 @@ export function apply(ctx, config) {
147
192
  return;
148
193
  }
149
194
 
195
+ // ── 可选的团队队形自检段(总开关与 teamFit.enabled 同时为 true 才注册一次) ──────
196
+ // 每次组装现判「主脑 / 目标预设 / 团队是否开启」,条件不满足或查询异常返回空串,
197
+ // 宿主会省略整段;提示词组装与重试都没有写入副作用。
198
+ if (config.teamFit?.enabled === true) {
199
+ ctx.systemPrompt.section({
200
+ name: TEAM_FIT_SECTION,
201
+ // 紧跟官方团队段:SECTION_ORDERS.TEAM_POLICY = 600,+1 让自检段排在它后面。
202
+ order: ctx.systemPrompt.getSectionOrder('TEAM_POLICY') + 1,
203
+ text: (context) => {
204
+ try {
205
+ const { agent, scope, toolSet } = context;
206
+ if (!agent?.ctx || scope !== agent) return '';
207
+ // session.header 在首轮前已验证;requestHeader() 要等第一次模型请求才有值。
208
+ const header = agent.session?.header;
209
+ if (typeof header?.id !== 'string' || header.id !== agent.session.id) return '';
210
+ // 本仓库的 roleOf(agent) 读的就是这份 durable header 与 options,
211
+ // 等价于参考实现的 roleOf(header, agent.options)。
212
+ const role = roleOf(agent);
213
+ if (role !== 'root') return '';
214
+ const preset = ctx.get('agentPresets')?.composedPreset(agent.ctx);
215
+ if (preset !== presetId) return '';
216
+ return teamFitTextFor({ role, preset, presetId, teamEnabled: teamEnabledFor(ctx, agent, toolSet) });
217
+ } catch {
218
+ return '';
219
+ }
220
+ },
221
+ });
222
+ }
223
+
150
224
  // ── fail-fast(只记日志、绝不抛) ──────────────────────────────────────────
151
- if (executor.provider === '' || executor.model === '') {
152
- ctx.logger.error('dsh-submodel: config.executor.provider/model 未配置,自动委派不可用;请按 README 配置');
225
+ if (executorIncomplete) {
226
+ ctx.logger.error(
227
+ 'dsh-submodel: config.executor.provider/model 未配置,自动委派不可用;可调用 `configure_submodel` 自动配置或按 README 两步配置',
228
+ );
153
229
  }
154
230
  ctx.logger.info(
155
231
  `dsh-submodel: 自动策略已启用(preset=${presetId}, executor=${executor.provider || '(未配置)'}/${executor.model || '(未配置)'}, experts=${experts.length})`,
@@ -235,12 +311,15 @@ export function apply(ctx, config) {
235
311
  // 既对该 agent 可见,也随 agent 一起释放。
236
312
  const tools = agent.ctx.tools;
237
313
 
314
+ // 角色只在安装时判定一次:它来自 durable session header,agent 生命周期内不变。
315
+ // 改读 agent(而不是已作废的 EpochHeader)是为了修复"冷恢复子代永远判成 root"的缺陷。
316
+ const callerRole = roleOf(agent);
317
+
238
318
  // ① 角色 guard:子代硬边界。**返回字符串即拒绝**(不是抛异常)。
239
319
  const guard = (exec) => {
240
320
  if (exec?.agent !== agent) return undefined;
241
321
  const toolCallName = exec?.name;
242
322
  if (typeof toolCallName !== 'string') return undefined;
243
- const callerRole = roleOf(agent.session?.requestHeader?.(), agent.options);
244
323
  if (callerRole !== 'child') return undefined;
245
324
  const forbidden = CHILD_FORBIDDEN_TOOLS.includes(toolCallName) || toolCallName.startsWith('subagent');
246
325
  if (!forbidden) return undefined;
@@ -248,15 +327,14 @@ export function apply(ctx, config) {
248
327
  };
249
328
  disposers.push(tools.guard(guard));
250
329
 
251
- // ② 执行期硬边界的补充:非 Flash 顶层用原生 subagent 但没给完整显式 pair 时,
330
+ // ② 执行期硬边界的补充:非经济路由顶层用原生 subagent 但没给完整显式 pair 时,
252
331
  // 拒绝并指向 delegate_task,防止模型绕开默认执行路由。
253
332
  const nativeGuard = (exec) => {
254
333
  if (exec?.agent !== agent) return undefined;
255
334
  if (exec?.name !== 'subagent') return undefined;
256
- const callerRole = roleOf(agent.session?.requestHeader?.(), agent.options);
257
335
  if (callerRole !== 'root') return undefined;
258
- const model = agent.session?.requestHeader?.()?.config?.model ?? agent.options?.model;
259
- if (typeof model === 'string' && model.toLowerCase().endsWith('flash')) return undefined; // Flash 顶层原生调用不改变行为
336
+ // 执行期模式判定:取最新已接受 header 的 config,回退 agent.options。
337
+ if (isEconomyRoute(routeFromAgent(agent), routingPolicy)) return undefined; // 经济路由顶层原生调用不改变行为
260
338
  const args = exec.arguments ?? {};
261
339
  const hasProvider = args.provider !== undefined && args.provider !== null && args.provider !== '';
262
340
  const hasModel = args.model !== undefined && args.model !== null && args.model !== '';
@@ -288,19 +366,30 @@ export function apply(ctx, config) {
288
366
  disposers.push(scopedCtx.on('system-prompt/assemble', listener));
289
367
 
290
368
  // ④ 只有顶层注册统一委派入口(子代不再有委派能力)。
291
- const callerRole = roleOf(agent.session?.requestHeader?.(), agent.options);
292
369
  if (callerRole === 'root') {
293
370
  disposers.push(
294
- tools.register(createDelegateTool({ ctx: agent.ctx, nativeDefinition, executor, logger: ctx.logger })),
371
+ tools.register(
372
+ createDelegateTool({
373
+ ctx: agent.ctx,
374
+ nativeDefinition,
375
+ executor,
376
+ economyRoutes,
377
+ logger: ctx.logger,
378
+ }),
379
+ ),
295
380
  );
381
+ // ⑤ executor 未配置时注册自动配置向导(已配置/子代/autoConfigure=false 都不注册)。
382
+ // 向导走 agent.ctx.tools,随 agent 释放;它内部用插件顶层 ctx 取服务。
383
+ if (autoConfigure && executorIncomplete) {
384
+ disposers.push(tools.register(createSetupTool({ ctx, config, logger: ctx.logger })));
385
+ }
296
386
  }
297
387
 
298
- // 正文解析器:角色固定,模式每次 assembly 现判。
388
+ // 正文解析器:角色安装时固定,模式每次 assembly 现判。
299
389
  // `list_subagent_models` 不可见时**只门控正文段**(info 一次/agent),
300
390
  // 工具仍按上面的注册门控安装。
301
391
  textResolvers.set(agent, (resolved) => {
302
- const role = roleOf(agent.session?.requestHeader?.(), agent.options);
303
- if (role === 'child') return routingTextFor('child', '', renderContext);
392
+ if (callerRole === 'child') return routingTextFor('child', undefined, renderContext);
304
393
  if (ctx.tools.get(toolName, agent) === undefined) {
305
394
  if (!informedNoModelSelection.has(agent)) {
306
395
  informedNoModelSelection.add(agent);
@@ -310,7 +399,7 @@ export function apply(ctx, config) {
310
399
  }
311
400
  return null;
312
401
  }
313
- return routingTextFor('root', resolveAssemblyModel(ctx, agent, resolved), renderContext);
402
+ return routingTextFor('root', resolveAssemblyRoute(ctx, agent, resolved), renderContext);
314
403
  });
315
404
 
316
405
  installed.set(agent, { disposers });
@@ -412,39 +501,45 @@ export function apply(ctx, config) {
412
501
  }
413
502
 
414
503
  /**
415
- * 解析"本次 assembly 用的主模型"。
504
+ * 解析"本次 assembly 用的路由"。
416
505
  *
417
506
  * 顺序(必须对齐 GUI 即将发起的那笔请求,不能用过期的创建期值):
418
- * 1. **session-local selection**——GUI 的 `selectModel` 走 `installModelSelection(agent.ctx, ...)`,
419
- * 这是唯一能反映"还没提交的新选择"的通道;
420
- * 2. `assembly.variables.model`——宿主的变量(注意它源自 `context.agent.options.model`,
421
- * 即创建期值,仅作回退);
422
- * 3. `agent.options.model`——最后的兜底。
507
+ * 1. `assembly.variables.provider` / `assembly.variables.model`——宿主 agent-loop 注册的
508
+ * 提示词变量,反映本次请求的路由;
509
+ * 2. `agent.options.provider` / `agent.options.model`——创建期值,仅作回退(例如 bundle 未注册变量)。
423
510
  *
424
- * 三条都拿不到时**明确报错**,不猜模型(猜错会把整段策略换成另一套且不报错)。
511
+ * 两处都拿不到 model 时**明确报错**,不猜模式(猜错会把整段策略换成另一套且不报错)。
512
+ * 注意这里**不读** `sessionController.agents.selectionFor`:DSH 0.2.2 没有该 service(死通道已删)。
425
513
  *
426
- * @param ctx - 插件顶层 ctx(用于取 sessionController)。
514
+ * @param ctx - 插件顶层 ctx(保留参数位,当前实现不需要)。
427
515
  * @param agent - 目标 agent。
428
516
  * @param assembly - 已完成 next() 的 assembly。
429
- * @returns 模型 ID。
517
+ * @returns `{provider, model}`。
430
518
  */
431
- function resolveAssemblyModel(ctx, agent, assembly) {
432
- try {
433
- const controller = ctx.get('sessionController');
434
- const selection = controller?.agents?.selectionFor?.(agent)?.current;
435
- if (typeof selection?.model === 'string' && selection.model !== '') return selection.model;
436
- } catch {
437
- // selectionFor 在投影未注册等边界会抛;回退到宿主变量,不中断 assembly。
519
+ function resolveAssemblyRoute(ctx, agent, assembly) {
520
+ void ctx;
521
+ const variables = assembly?.variables;
522
+ const options = agent?.options ?? {};
523
+ const provider = typeof variables?.provider === 'string' ? variables.provider : options.provider;
524
+ const fromAssembly = typeof variables?.model === 'string' && variables.model !== '' ? variables.model : undefined;
525
+ const model = fromAssembly ?? options.model;
526
+ if (typeof model !== 'string' || model === '') {
527
+ // 两处都没有 model:走严格版本拿统一报错文案(不猜模式)。
528
+ return routeFromAssembly(assembly);
438
529
  }
439
- const fromAssembly = assemblyModelOrUndefined(assembly);
440
- if (fromAssembly !== undefined) return fromAssembly;
441
- const fromOptions = agent?.options?.model;
442
- if (typeof fromOptions === 'string' && fromOptions !== '') return fromOptions;
443
- return modelFromAssembly(assembly); // 抛出明确配置错误
530
+ return { provider: typeof provider === 'string' ? provider : '', model };
444
531
  }
445
532
 
446
- /** 宽松取 `assembly.variables.model`;缺失返回 undefined(不抛)。 */
447
- function assemblyModelOrUndefined(assembly) {
448
- const model = assembly?.variables?.model;
449
- return typeof model === 'string' && model !== '' ? model : undefined;
533
+ /**
534
+ * 执行期取"正在发起这笔工具调用的主脑路由":`session.requestHeader().config` 优先,
535
+ * `agent.options` 兜底。取不到 model 时返回空路由(守卫按 boss 处理,不抛)。
536
+ * @param agent - live agent。
537
+ * @returns `{provider, model}`(字段缺失时为空串/undefined)。
538
+ */
539
+ function routeFromAgent(agent) {
540
+ const accepted = agent?.session?.requestHeader?.()?.config ?? agent?.options ?? {};
541
+ return {
542
+ provider: typeof accepted?.provider === 'string' ? accepted.provider : '',
543
+ model: typeof accepted?.model === 'string' ? accepted.model : '',
544
+ };
450
545
  }