dsh-submodel 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 angel291592
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # dsh-submodel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **官方 subagent 的默认策略包**:装上一次配好「什么时候自己干、什么时候派出去、派给谁」。
4
+
5
+ 它**不新建 provider 体系**——只读你 profile 里已有的渠道与模型配置,把委派策略写进系统提示词,
6
+ 并给官方 `subagent` 补一个统一的委派入口 `delegate_task`。本机实测于 DeepSeek Harness `0.2.1-rc.5`。
7
+
8
+ ## 安装
9
+
10
+ ```bash
11
+ dsh plugin --profile <你的 profile> add dsh-submodel
12
+ ```
13
+
14
+ ## 配置(5 行)
15
+
16
+ 在你的 profile 补丁层(`~/.dsh/profiles/<你的 profile>/cordis.patch.yml`)里按 id 覆盖配置。
17
+ 该文件默认是空数组 `[]`:**把 `[]` 替换成下面的条目**;已有其他条目时,把它追加到数组里。
18
+
19
+ ```yaml
20
+ - id: submodel
21
+ config:
22
+ executor:
23
+ provider: <执行渠道>
24
+ model: <执行模型>
25
+ ```
26
+
27
+ 注意:profile 补丁对某一条目的 `config` 是**整段替换**——没写的字段回落到默认值(见下表),
28
+ 不会和内置默认值逐字段合并。
29
+
30
+ 完整字段:
31
+
32
+ | 字段 | 默认值 | 说明 |
33
+ |---|---|---|
34
+ | `enabled` | `true` | 总开关;`false` 时只注册一个空段,不装任何工具/guard |
35
+ | `preset` | `standard` | 只对这个 composition 生效 |
36
+ | `executor.provider` / `executor.model` | 空 | 非 Flash 主脑的默认派工目标;**留空会记 error 日志**(见故障排查) |
37
+ | `executor.reasoningEffort` | `max` | 只在调用方没显式指定档位时作缺省 |
38
+ | `experts` | `[]` | 允许升级时显式点名的专家路由列表,每项 `{label, provider, model, reasoningEffort?}`;`reasoningEffort` 目前为预留字段,不影响派工 |
39
+ | `texts.economize` / `texts.boss` / `texts.child` | 空 | 非空时整段替换内置正文(替换后不再插值) |
40
+ | `toolName` | `list_subagent_models` | 策略段的能力门控工具名 |
41
+ | `order` | `2850` | 策略段在系统提示词里的顺序 |
42
+ | `guardNativeSubagent` | `true` | 是否拦截"非 Flash 顶层用原生 `subagent` 却不给完整 provider/model" |
43
+
44
+ ## 它做什么
45
+
46
+ - **Flash 主脑**:默认自己干;普通子任务用 `delegate_task`(不传 provider/model,子代继承当前路由);
47
+ 只有"问题本身够复杂"或"超出执行上限"时才升级,升级时从 `experts` 里点名。
48
+ - **非 Flash 主脑**:理解/判断/写作自己来;可验证的执行块默认派给 `executor` 配置的执行路由。
49
+ - **子代**:硬边界——`delegate_task` / `subagent` / `subagent_fork` / `workflow` / `spawn_teammate`
50
+ 一律不可用,防止递归派活。
51
+ - **`delegate_task`**:参数与原生 `subagent` 相同;`provider` 与 `model` 必须成对传;经
52
+ `ctx.tools.execute` 发起真正的原生调用,宿主的 allowlist / 预检 / 权限照旧生效。
53
+
54
+ ## 与官方插件的边界
55
+
56
+ | 能力 | 提供方 |
57
+ |---|---|
58
+ | 状态查看 `list_agents`、追加消息 `send_message`、停止 `interrupt_agent` | 官方 `@deepseek-ai/dsh-tool-subagent-control`(本包**不重复注册**) |
59
+ | 策略正文、`delegate_task`、子代 guard | 本包 |
60
+ | 模型选择能力本身(`subagent` 的 `provider`/`model` 参数) | 官方 subagent(本包只消费) |
61
+
62
+ ## 兼容性
63
+
64
+ | DSH 版本 | 状态 |
65
+ |---|---|
66
+ | `0.2.1-rc.5` | ✅ 实测通过(安装、`--dump-config`、启动均实测) |
67
+ | 其他 rc / 正式版 | 未逐一实测(`engines.dsh` 声明 `>=0.2.1-rc.3 <0.3.0`,不作宽承诺) |
68
+
69
+ ## 故障排查(fail-fast:只记日志,绝不抛)
70
+
71
+ | 现象(日志) | 级别 | 含义与处理 |
72
+ |---|---|---|
73
+ | `config.executor.provider/model 未配置,自动委派不可用` | `error` | 非 Flash 主脑没有默认派工目标;按上面的 5 行配置补上 |
74
+ | `当前 profile 无 agentPresets 服务,策略不生效` | `warn` | 该 profile 没有 agentPresets 服务;换一个支持 composition 的 profile |
75
+ | `原生 subagent 未暴露 provider/model,delegate_task 不安装` | `warn` | 本会话的原生 `subagent` 没有选模参数:该 agent 上**整套安装**(策略段 / guard / `delegate_task`)都会跳过,等能力出现后由 `tools/change` 或 `agent/pre-step` 自动补装 |
76
+ | `本会话未启用官方 subagent 模型选择,策略段不渲染` | `info` | 去设置里启用 `subagent-model-selection`;工具本身仍按注册门控安装 |
77
+
78
+ ## 已知限制
79
+
80
+ - 只对 `preset` 指定的 composition 生效(默认 `standard`)。
81
+ - 不提供预算护栏 / 催收 / 故障改派(watchdog)——v0.2 候选。
82
+ - 不提供英文文案与 locale:默认中文,可用 `texts.*` 整段覆盖(工具描述与 guard 拒绝理由仍为英文)。
83
+ - 正文里的执行路由与专家路由全部来自你的配置,本包内置模板**不含任何具体渠道/模型名**。
84
+
85
+ ## 回滚
86
+
87
+ ```bash
88
+ dsh plugin --profile <你的 profile> remove dsh-submodel
89
+ ```
90
+
91
+ ## 开发与验证
92
+
93
+ ```bash
94
+ node tests/unit/flash-routing-fixture.mjs ./lib # 纯函数 + 生命周期回归(71 条断言)
95
+ python -m unittest discover -s tests/unit # 包根执行(7 个用例)
96
+ node tests/unit/public-profile-smoke.mjs # 干净用户配置的确定性冒烟(5 条断言)
97
+ ```
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: submodel
3
+ name: 'dsh-submodel'
@@ -0,0 +1,187 @@
1
+ /**
2
+ * dsh-submodel / delegation.js —— 统一委派入口 `delegate_task`。
3
+ *
4
+ * ## 为什么是"再调一次原生 subagent",而不是自己创建子代
5
+ *
6
+ * 原生的创建校验(allowlist / LLM preflight / permission / depth / persona / toolFilter)
7
+ * 全部发生在 `@deepseek-ai/dsh-tool-subagent` 的 `execute` 内部,**在创建孩子之前**
8
+ * (`dsh-tool-subagent/lib/index.js:491-506`)。绕过它去 `subagents.startContinuable(...)`
9
+ * 就等于同时绕过授权与预检——那正是本模块**不能**做的事。
10
+ *
11
+ * 所以本工具只做两件事:**改参数** + **经公开 `ctx.tools.execute` 发起一次真正的原生调用**
12
+ * (`dsh-tools/lib/index.js:3116` 是公开入口)。这样原生的一切校验照旧生效。
13
+ *
14
+ * ## 三个必须遵守的坑(都已在源码确认,别踩)
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`。漏掉任一项,原生的事件归属或取消传播就会错位。
23
+ *
24
+ * @module dsh-submodel/delegation
25
+ */
26
+ import {
27
+ DELEGATE_TOOL_NAME,
28
+ MODE_BOSS,
29
+ resolveCallerRole,
30
+ resolveDelegationArgs,
31
+ } from './policy.js';
32
+
33
+ /** 子调用 callId 的后缀:既能被日志一眼认出,又不会和原生 callId 撞(原生用随机 id)。 */
34
+ const NESTED_CALL_SUFFIX = ':delegate';
35
+
36
+ /**
37
+ * 从原生 `subagent` 的工具定义深拷贝参数 schema。
38
+ *
39
+ * **必须是"每次安装时从本轮 native 定义取"**,不能把 schema 写死在源码里:native 定义
40
+ * 会随 DSH 升级增删参数,写死就等于把新参数悄悄丢掉。`parameters` 是结构化的普通对象
41
+ * (`structuredClone` 在 `dsh-system-prompt:327` 也是这么拷的),可安全深拷贝。
42
+ *
43
+ * @param nativeDefinition - 本会话可见的原生 subagent 工具定义。
44
+ * @returns 参数 schema 深拷贝。
45
+ */
46
+ export function cloneNativeParameters(nativeDefinition) {
47
+ const parameters = nativeDefinition?.parameters;
48
+ if (parameters === undefined || parameters === null || typeof parameters !== 'object') {
49
+ throw new Error('delegate_task: the native `subagent` definition exposes no parameters to clone');
50
+ }
51
+ return structuredClone(parameters);
52
+ }
53
+
54
+ /**
55
+ * 检查本会话是否具备"能选模的委派能力":原生 subagent 可见 + 参数里真的有 provider/model。
56
+ * 缺任一项就不装 `delegate_task`——装了也是个只会失败的入口。
57
+ *
58
+ * **判据读 `parameters.properties`,不是 `parameters` 顶层**:宿主 `defineTool` 交付的是
59
+ * JSON Schema(`{type:'object', properties:{…}, required:[…]}`)。2026-10-05 真实宿主实测:
60
+ * `hasTopLevelProvider=false` / `hasPropertiesProvider=true`;读顶层会恒为 false,于是本函数
61
+ * 永远返回 undefined、整条安装路径静默跳过(四个工具一个都不出现)。
62
+ *
63
+ * @param tools - 工具注册表(ctx.tools)。
64
+ * @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 工具。
67
+ * @returns 原生定义或 undefined。
68
+ */
69
+ export function findNativeSubagent(tools, scope) {
70
+ const definition = tools.get?.('subagent', scope);
71
+ if (definition === undefined) return undefined;
72
+ const properties = definition.parameters?.properties;
73
+ const hasRouteParams = properties?.provider !== undefined && properties?.model !== undefined;
74
+ return hasRouteParams ? definition : undefined;
75
+ }
76
+
77
+ /**
78
+ * 组装嵌套调用要用的子参数与 token 链。**纯计算**,便于单测。
79
+ * @param outerExec - 外层(delegate_task 自己的)exec。
80
+ * @param newArgs - 已解析好的子代参数。
81
+ * @returns `{callId, rootCallId, name, arguments, agent, parent, signal}`。
82
+ */
83
+ export function buildNestedCall(outerExec, newArgs) {
84
+ return {
85
+ callId: `${outerExec.callId}${NESTED_CALL_SUFFIX}`,
86
+ rootCallId: outerExec.rootCallId ?? outerExec.callId,
87
+ name: 'subagent',
88
+ arguments: newArgs,
89
+ agent: outerExec.agent,
90
+ parent: outerExec.token,
91
+ signal: outerExec.signal,
92
+ };
93
+ }
94
+
95
+ /**
96
+ * 把子的失败结果转成一段**可读诊断**(保留原始信息,不吞)。
97
+ * @param inner - 原生调用返回的结果快照。
98
+ * @returns 错误文本。
99
+ */
100
+ export function describeInnerFailure(inner) {
101
+ const parts = [];
102
+ const message = inner?.error?.message;
103
+ if (typeof message === 'string' && message !== '') parts.push(message);
104
+ const info = inner?.error?.info;
105
+ if (info !== undefined && info !== null) {
106
+ try {
107
+ parts.push(typeof info === 'string' ? info : JSON.stringify(info));
108
+ } catch {
109
+ parts.push('[unserializable error.info]');
110
+ }
111
+ }
112
+ const content = Array.isArray(inner?.content) ? inner.content : [];
113
+ for (const block of content) {
114
+ if (block?.type === 'text' && typeof block.text === 'string' && block.text !== '') parts.push(block.text);
115
+ }
116
+ if (parts.length === 0) parts.push('the nested subagent call failed without a diagnostic');
117
+ return parts.join('\n');
118
+ }
119
+
120
+ /**
121
+ * 创建 `delegate_task` 的工具定义。
122
+ *
123
+ * @param options - 依赖注入(全部来自 live agent 的 scope):
124
+ * - `ctx`:该 agent 的 runtime context(提供 tools/subagents)
125
+ * - `nativeDefinition`:本轮原生 subagent 定义(参数与 output 的来源)
126
+ * - `executor`:配置的执行路由 `{provider, model, reasoningEffort}`
127
+ * - `logger`:日志器
128
+ * @returns 可直接 `ctx.tools.register(...)` 的工具定义。
129
+ */
130
+ export function createDelegateTool({ ctx, nativeDefinition, executor, logger }) {
131
+ const parameters = cloneNativeParameters(nativeDefinition);
132
+ // output 同样复用原生 schema/render,保持 runId/agentId 与 foreground/continuable 格式一致。
133
+ const output = nativeDefinition.output;
134
+ if (output === undefined || output === null) {
135
+ throw new Error('delegate_task: the native `subagent` definition exposes no output contract to reuse');
136
+ }
137
+
138
+ return {
139
+ name: DELEGATE_TOOL_NAME,
140
+ description:
141
+ 'Delegate one independent task to a subagent and return its result. ' +
142
+ '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). ' +
144
+ 'An explicit route must name provider AND model together. ' +
145
+ 'Prefer this over the raw `subagent` tool for ordinary delegation.',
146
+ parameters,
147
+ output,
148
+ async execute(args, exec) {
149
+ // ① 调用方身份必须是 live Agent,且必须是合格 standard 顶层。
150
+ const caller = resolveCallerRole(exec);
151
+ if (!caller.ok) throw new Error(caller.reason);
152
+ if (caller.role !== 'root') throw new Error(`delegate_task is only available to a top-level agent (got role "${caller.role}")`);
153
+
154
+ // ② 同步快照执行期模式,再 await:描述"当前发起这笔调用的主脑",
155
+ // 不读 GUI 里可能中途变化的 pending selection。
156
+ 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
+ })();
161
+
162
+ // ③ 解析最终子代参数(原 exec/arguments 不可变,派生新对象)。
163
+ const resolved = resolveDelegationArgs(args, mode, executor);
164
+ if (!resolved.ok) throw new Error(resolved.reason);
165
+
166
+ logger.info(
167
+ `dsh-submodel: delegate_task session=${caller.header?.id ?? '?'} call=${exec.callId} mode=${mode} ` +
168
+ `route=${resolved.applied} -> ${resolved.args.provider ?? '(inherit)'}/${resolved.args.model ?? '(inherit)'}`,
169
+ );
170
+
171
+ // ④ 发起一次真正的原生调用:保留它的全部校验与事件链。
172
+ const nested = buildNestedCall(exec, resolved.args);
173
+ const inner = await ctx.tools.execute(nested);
174
+
175
+ // ⑤ inner.isError 必须**抛出**:body 返回 error 对象会被当成功 value(dsh-tools:3540)。
176
+ if (inner?.isError === true) {
177
+ throw new Error(describeInnerFailure(inner));
178
+ }
179
+
180
+ // ⑥ 转移延迟上下文 / 结论标记,再只返回 inner.value。
181
+ for (const context of inner?.additionalContexts ?? []) exec.deferContext(context);
182
+ if (inner?.concludesTurn === true) exec.concludeTurn();
183
+
184
+ return inner.value;
185
+ },
186
+ };
187
+ }
package/lib/index.js ADDED
@@ -0,0 +1,450 @@
1
+ /**
2
+ * dsh-submodel / index.js —— 插件入口(v0.1.0)。
3
+ *
4
+ * 职责:全局注册**唯一的策略提示词段**;`enabled` 时再对每个合格的 standard agent 安装
5
+ * scoped 能力(提示词段正文替换、角色 guard、统一委派入口 `delegate_task`),并在
6
+ * Agent 释放 / 组合变化 / 配置重载时**准确卸载自己装的东西**。
7
+ *
8
+ * ## 与官方工具的分工(本包**不发布**任何控制工具)
9
+ *
10
+ * 状态查看 `list_agents`、追加消息 `send_message`、停止 `interrupt_agent` 由官方
11
+ * `@deepseek-ai/dsh-tool-subagent-control` 提供;本包只做"什么时候自己干、什么时候派出去、
12
+ * 派给谁"的策略层。重复注册同名工具会冲突,也没有理由让用户为重复功能付费注意力。
13
+ *
14
+ * ## 为什么逐 agent 安装,而不是全局注册这些工具
15
+ *
16
+ * 原生 subagent 的选模能力是**按会话**授予并 Recorded 进会话的。同一时刻有的会话有该能力、
17
+ * 有的没有(例如恢复型旧会话)。只有在"该 agent 自己的 scope 里确实看得见原生 subagent 且
18
+ * 参数含 provider/model"时才装,模型才不会拿到一个必然失败的按钮。
19
+ *
20
+ * ## 安装纪律
21
+ *
22
+ * - 先标 `installing` 再注册,避免 `tools/change` 重入;
23
+ * - 同一个 agent 的并发安装**共用一个 Promise**;
24
+ * - 失败清理**部分注册**并上报,不吞异常;
25
+ * - 卸载只动自己装的东西,绝不碰别的 Session / 标准插件。
26
+ *
27
+ * ## 两个已确认的宿主契约(写错即静默失效,别凭直觉改)
28
+ *
29
+ * 1. **`ctx.tools.guard(fn)` 靠"返回字符串"拒绝**,不是抛异常("a returned string denies
30
+ * the execution")。抛异常会被当成 guard 自身故障。且 guard 是**同步**检查。
31
+ * 2. **`ctx.tools.restrict()` 不能点名 scope-local 工具**(只认 `restrictableNames`)。
32
+ * 所以子代的工具面收敛只走 guard 这个执行期硬边界,**不用 restrict**。
33
+ *
34
+ * ## fail-fast(v0.1.0 新增,只记日志、绝不抛)
35
+ *
36
+ * 公开版默认 `enabled:true`:缺前置时必须在日志里**明确**说清哪一项不可用,把"装完零感知"
37
+ * 变成"可诊断"。级别与文案见 README 的「故障排查」一节。
38
+ *
39
+ * @module dsh-submodel
40
+ */
41
+ import z from '@deepseek-ai/schemastery';
42
+ import {
43
+ CHILD_FORBIDDEN_TOOLS,
44
+ ROUTING_ORDER,
45
+ ROUTING_SECTION,
46
+ childDelegationRefusal,
47
+ modelFromAssembly,
48
+ roleOf,
49
+ routingTextFor,
50
+ } from './policy.js';
51
+ import { createDelegateTool, findNativeSubagent } from './delegation.js';
52
+
53
+ export const name = 'dsh-submodel';
54
+
55
+ /** 用到的服务必须列全:apply 会等到它们可用才执行。 */
56
+ export const inject = ['tools', 'systemPrompt'];
57
+
58
+ export const Config = z.object({
59
+ /** 自动策略总开关。默认开启:公开版的目标就是"装上一次配好"。 */
60
+ enabled: z.boolean().default(true),
61
+ /** 只对这一个 composition 生效;其他 preset 不安装任何东西。 */
62
+ preset: z.string().default('standard'),
63
+ /** 能力门控工具名:该 scope 不可见时策略段不渲染(工具仍按注册门控安装)。 */
64
+ toolName: z.string().default('list_subagent_models'),
65
+ /** 段顺序;默认紧接 TOOL_SUBAGENT(2800)。 */
66
+ order: z.number().default(ROUTING_ORDER),
67
+ /**
68
+ * 执行路由(非 Flash 主脑的默认派工目标)。**唯一配置源**:执行期注入的 pair 由它派生,
69
+ * 正文里的执行路由也只经占位符从它渲染,不允许 YAML/JS 双写两个不同的路由名。
70
+ */
71
+ executor: z.object({
72
+ provider: z.string().default(''),
73
+ model: z.string().default(''),
74
+ reasoningEffort: z.string().default('max'),
75
+ }).default({ provider: '', model: '', reasoningEffort: 'max' }),
76
+ /**
77
+ * 专家路由:升级时允许显式点名的 `{label, provider, model, reasoningEffort?}` 列表。
78
+ * 空数组时正文给出"未配置专家路由"提示,不渲染任何具体路由名。
79
+ */
80
+ experts: z.array(z.object({
81
+ label: z.string(),
82
+ provider: z.string(),
83
+ model: z.string(),
84
+ reasoningEffort: z.string().default('max'),
85
+ })).default([]),
86
+ /**
87
+ * 正文覆盖:任一项非空时**整段替换**内置模板(替换后不再插值),方便用户写自己的话术。
88
+ */
89
+ texts: z.object({
90
+ economize: z.string().default(''),
91
+ boss: z.string().default(''),
92
+ child: z.string().default(''),
93
+ }).default({ economize: '', boss: '', child: '' }),
94
+ /**
95
+ * 是否安装"非 Flash 顶层用原生 subagent 时必须给完整显式 pair"的 guard。
96
+ * 默认开启;关掉后原生 subagent 的行为完全交给宿主。
97
+ */
98
+ guardNativeSubagent: z.boolean().default(true),
99
+ });
100
+
101
+ /** 判断一个 agent 是否属于本插件负责的 composition。 */
102
+ function belongsToComposition(agent, presetId, presetService) {
103
+ if (presetService === undefined) return false;
104
+ try {
105
+ return presetService.composedPreset(agent.ctx) === presetId;
106
+ } catch {
107
+ // 组合正在解散时 composedPreset 可能抛;视为"不属于",走卸载路径,
108
+ // 不把异常抛进事件回调。
109
+ return false;
110
+ }
111
+ }
112
+
113
+ export function apply(ctx, config) {
114
+ const enabled = config.enabled === true;
115
+ const presetId = config.preset ?? 'standard';
116
+ const toolName = config.toolName ?? 'list_subagent_models';
117
+ const order = config.order ?? ROUTING_ORDER;
118
+ const executor = {
119
+ provider: config.executor?.provider ?? '',
120
+ model: config.executor?.model ?? '',
121
+ reasoningEffort: config.executor?.reasoningEffort ?? 'max',
122
+ };
123
+ const experts = Array.isArray(config.experts) ? config.experts : [];
124
+ const texts = {
125
+ economize: config.texts?.economize ?? '',
126
+ boss: config.texts?.boss ?? '',
127
+ child: config.texts?.child ?? '',
128
+ };
129
+ const guardNativeSubagent = config.guardNativeSubagent !== false;
130
+ /** 每次 assembly 现渲染正文用的运行期上下文(纯函数层只认它)。 */
131
+ const renderContext = { executor, experts, texts };
132
+
133
+ /** 每个 agent 的 assembly listener 装的文本解析器:`(resolved) => string|null`。 */
134
+ const textResolvers = new WeakMap();
135
+
136
+ // ── 全局唯一的段(只注册一次,绝不重复注册同名段) ─────────────────────────
137
+ ctx.systemPrompt.section({
138
+ name: ROUTING_SECTION,
139
+ order,
140
+ // enabled 时正文完全交给 per-agent listener;enabled=false 时保持空段,
141
+ // 不注册任何工具/guard(与"关闭即无感"一致)。
142
+ text: () => '',
143
+ });
144
+
145
+ if (!enabled) {
146
+ ctx.logger.info('dsh-submodel: enabled=false,策略未启用(只注册空段,不安装任何工具/guard)');
147
+ return;
148
+ }
149
+
150
+ // ── fail-fast(只记日志、绝不抛) ──────────────────────────────────────────
151
+ if (executor.provider === '' || executor.model === '') {
152
+ ctx.logger.error('dsh-submodel: config.executor.provider/model 未配置,自动委派不可用;请按 README 配置');
153
+ }
154
+ ctx.logger.info(
155
+ `dsh-submodel: 自动策略已启用(preset=${presetId}, executor=${executor.provider || '(未配置)'}/${executor.model || '(未配置)'}, experts=${experts.length})`,
156
+ );
157
+
158
+ // ── 逐 agent 安装 ──────────────────────────────────────────────────────────
159
+ const installed = new WeakMap();
160
+ const installing = new WeakSet();
161
+ const pendingInstalls = new WeakMap();
162
+
163
+ /** 每 agent 一次的诊断集合(plan §4.3:不得静默失效)。 */
164
+ const warnedNoPresets = new WeakSet();
165
+ const warnedNoNativeSubagent = new WeakSet();
166
+ const informedNoModelSelection = new WeakSet();
167
+
168
+ const presetService = () => ctx.get('agentPresets');
169
+ const agentsService = () => ctx.get('agents');
170
+
171
+ /**
172
+ * 是否属于本插件的 composition。服务缺失时**每个 agent 记一次 warn**,
173
+ * 让"策略不生效"可诊断,而不是静默跳过。
174
+ */
175
+ const isOurs = (agent) => {
176
+ const service = presetService();
177
+ if (service === undefined) {
178
+ if (!warnedNoPresets.has(agent)) {
179
+ warnedNoPresets.add(agent);
180
+ ctx.logger.warn('dsh-submodel: 当前 profile 无 agentPresets 服务,策略不生效');
181
+ }
182
+ return false;
183
+ }
184
+ return belongsToComposition(agent, presetId, service);
185
+ };
186
+
187
+ /** 卸载一个 agent 上本插件装的全部东西(只动记录过的项)。 */
188
+ const uninstallAgent = async (agent, reason) => {
189
+ const record = installed.get(agent);
190
+ textResolvers.delete(agent);
191
+ if (record === undefined) return;
192
+ installed.delete(agent);
193
+ for (const dispose of [...record.disposers].reverse()) {
194
+ try {
195
+ await dispose();
196
+ } catch (error) {
197
+ ctx.logger.warn(
198
+ `dsh-submodel: failed to dispose one registration for agent "${agent.id}" (${reason}): ${String(error)}`,
199
+ );
200
+ }
201
+ }
202
+ ctx.logger.info(`dsh-submodel: removed own install from agent "${agent.id}" (${reason})`);
203
+ };
204
+
205
+ /**
206
+ * 为 agent 安装自动能力。幂等:已装直接返回;正在装共用同一 Promise。
207
+ */
208
+ const installAgent = async (agent) => {
209
+ if (installed.has(agent)) return;
210
+ const existing = pendingInstalls.get(agent);
211
+ if (existing !== undefined) return existing;
212
+ if (installing.has(agent)) return undefined;
213
+ installing.add(agent);
214
+ const task = (async () => {
215
+ const scopedCtx = agent.ctx;
216
+ const disposers = [];
217
+ try {
218
+ // 观看作用域=**agent 对象本身**:`tools.view(agent)` 才是模型实际拿到的工具目录。
219
+ // 传 `agent.ctx` 会退化成 global 视图,永远查不到 subagent。
220
+ //
221
+ // **判据必须在 try 内**:原生 subagent 在 `agent/created` 那一刻可能还没注册好,
222
+ // 此时要**早退但清掉 installing 标记**——否则该 agent 被永久标记为"正在安装",
223
+ // 后续 reconcile 全部在守卫处返回,永远不再补装。
224
+ const nativeDefinition = findNativeSubagent(ctx.tools, agent);
225
+ if (nativeDefinition === undefined) {
226
+ if (!warnedNoNativeSubagent.has(agent)) {
227
+ warnedNoNativeSubagent.add(agent);
228
+ ctx.logger.warn('dsh-submodel: 原生 subagent 未暴露 provider/model,delegate_task 不安装');
229
+ }
230
+ return; // 无选模能力 → 什么都不装,等下一次 tools/change / pre-step 重试
231
+ }
232
+
233
+ // **关键**:注册必须经 **agent 自己的 ctx**——既不能走插件顶层 ctx,也不能自建 scope。
234
+ // 经 `agent.ctx.tools` 注册时 traceable service 把 effect 落到 `scopeOf(agent.ctx)`,
235
+ // 既对该 agent 可见,也随 agent 一起释放。
236
+ const tools = agent.ctx.tools;
237
+
238
+ // ① 角色 guard:子代硬边界。**返回字符串即拒绝**(不是抛异常)。
239
+ const guard = (exec) => {
240
+ if (exec?.agent !== agent) return undefined;
241
+ const toolCallName = exec?.name;
242
+ if (typeof toolCallName !== 'string') return undefined;
243
+ const callerRole = roleOf(agent.session?.requestHeader?.(), agent.options);
244
+ if (callerRole !== 'child') return undefined;
245
+ const forbidden = CHILD_FORBIDDEN_TOOLS.includes(toolCallName) || toolCallName.startsWith('subagent');
246
+ if (!forbidden) return undefined;
247
+ return `dsh-submodel: tool "${toolCallName}" is unavailable to a delegated subagent. ${childDelegationRefusal()}`;
248
+ };
249
+ disposers.push(tools.guard(guard));
250
+
251
+ // ② 执行期硬边界的补充:非 Flash 顶层用原生 subagent 但没给完整显式 pair 时,
252
+ // 拒绝并指向 delegate_task,防止模型绕开默认执行路由。
253
+ const nativeGuard = (exec) => {
254
+ if (exec?.agent !== agent) return undefined;
255
+ if (exec?.name !== 'subagent') return undefined;
256
+ const callerRole = roleOf(agent.session?.requestHeader?.(), agent.options);
257
+ 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 顶层原生调用不改变行为
260
+ const args = exec.arguments ?? {};
261
+ const hasProvider = args.provider !== undefined && args.provider !== null && args.provider !== '';
262
+ const hasModel = args.model !== undefined && args.model !== null && args.model !== '';
263
+ if (hasProvider && hasModel) return undefined; // 完整显式 pair:放行
264
+ return 'dsh-submodel: the native `subagent` tool needs an explicit and COMPLETE provider/model pair here. Omit the raw tool and use `delegate_task` for ordinary delegation (it applies the configured executor route), or name both provider and model.';
265
+ };
266
+ if (guardNativeSubagent) disposers.push(tools.guard(nativeGuard));
267
+
268
+ // ③ assembly listener:先 await next(),再只替换自有段。
269
+ const listener = async (assembly, context, next) => {
270
+ const resolved = await next();
271
+ try {
272
+ const resolver = textResolvers.get(agent);
273
+ const text = resolver === undefined ? null : resolver(resolved);
274
+ if (text === null) return resolved;
275
+ return {
276
+ ...resolved,
277
+ sections: resolved.sections.map((section) =>
278
+ section.name === ROUTING_SECTION
279
+ ? { name: ROUTING_SECTION, text, interpolate: false }
280
+ : section,
281
+ ),
282
+ };
283
+ } catch (error) {
284
+ ctx.logger.warn(`dsh-submodel: assembly section left unchanged for agent "${agent.id}": ${String(error)}`);
285
+ return resolved;
286
+ }
287
+ };
288
+ disposers.push(scopedCtx.on('system-prompt/assemble', listener));
289
+
290
+ // ④ 只有顶层注册统一委派入口(子代不再有委派能力)。
291
+ const callerRole = roleOf(agent.session?.requestHeader?.(), agent.options);
292
+ if (callerRole === 'root') {
293
+ disposers.push(
294
+ tools.register(createDelegateTool({ ctx: agent.ctx, nativeDefinition, executor, logger: ctx.logger })),
295
+ );
296
+ }
297
+
298
+ // 正文解析器:角色固定,模式每次 assembly 现判。
299
+ // `list_subagent_models` 不可见时**只门控正文段**(info 一次/agent),
300
+ // 工具仍按上面的注册门控安装。
301
+ textResolvers.set(agent, (resolved) => {
302
+ const role = roleOf(agent.session?.requestHeader?.(), agent.options);
303
+ if (role === 'child') return routingTextFor('child', '', renderContext);
304
+ if (ctx.tools.get(toolName, agent) === undefined) {
305
+ if (!informedNoModelSelection.has(agent)) {
306
+ informedNoModelSelection.add(agent);
307
+ ctx.logger.info(
308
+ 'dsh-submodel: 本会话未启用官方 subagent 模型选择,策略段不渲染;请在设置中启用 subagent-model-selection',
309
+ );
310
+ }
311
+ return null;
312
+ }
313
+ return routingTextFor('root', resolveAssemblyModel(ctx, agent, resolved), renderContext);
314
+ });
315
+
316
+ installed.set(agent, { disposers });
317
+ ctx.logger.info(`dsh-submodel: installed automatic routing on agent "${agent.id}" (role=${callerRole})`);
318
+ } catch (error) {
319
+ for (const dispose of [...disposers].reverse()) {
320
+ try {
321
+ await dispose();
322
+ } catch {
323
+ /* 清理失败不掩盖原始错误 */
324
+ }
325
+ }
326
+ ctx.logger.error(`dsh-submodel: failed to install automatic routing on agent "${agent.id}": ${String(error)}`);
327
+ throw error;
328
+ } finally {
329
+ installing.delete(agent);
330
+ }
331
+ })();
332
+ pendingInstalls.set(agent, task);
333
+ try {
334
+ await task;
335
+ } finally {
336
+ pendingInstalls.delete(agent);
337
+ }
338
+ };
339
+
340
+ /** 全量核对:属于本 composition 的装上,不属于的卸掉。 */
341
+ const reconcile = () => {
342
+ const agents = agentsService();
343
+ if (agents === undefined) return;
344
+ for (const candidate of agents.list()) {
345
+ if (isOurs(candidate)) {
346
+ installAgent(candidate).catch((error) => {
347
+ ctx.logger.error(`dsh-submodel: reconcile install failed for "${candidate.id}": ${String(error)}`);
348
+ });
349
+ } else {
350
+ void uninstallAgent(candidate, 'composition mismatch');
351
+ }
352
+ }
353
+ };
354
+
355
+ ctx.on('agent/created', async ({ agent: created }) => {
356
+ if (!isOurs(created)) return;
357
+ try {
358
+ await installAgent(created);
359
+ } catch (error) {
360
+ // cordis 的事件发射不等待、也不捕获监听器返回的 Promise:这里必须自己兜住,
361
+ // 否则一次安装失败会变成 unhandled rejection(纯 Node CLI 下默认终止进程)。
362
+ // reconcile / pre-step 两条通道同样兜底,保证失败只上报、不炸宿主。
363
+ ctx.logger.error(`dsh-submodel: agent/created install failed for "${created.id}": ${String(error)}`);
364
+ }
365
+ });
366
+ ctx.on('agent/disposed', ({ agent: disposed }) => {
367
+ void uninstallAgent(disposed, 'agent disposed');
368
+ });
369
+ ctx.on('tools/change', reconcile);
370
+ /**
371
+ * 兜底重试(每一步开始前再核一次)。
372
+ *
373
+ * 原生 `subagent` 在 `agent/created` 那一刻**可能还没注册好**,而此后**不一定再有
374
+ * `tools/change`** → 只靠 `tools/change` 重试会永久漏装。`agent/pre-step` 是每个 agent
375
+ * 每一步都会过的 waterfall,天然覆盖"最迟在这一步装上";`installAgent` 幂等,已装时只是
376
+ * 一次 WeakMap 命中即返回。**必须是 waterfall 监听器:不接管决策就返回 `next()`。**
377
+ */
378
+ ctx.on('agent/pre-step', ({ agent: stepping }, next) => {
379
+ if (stepping !== undefined && !installed.has(stepping) && isOurs(stepping)) {
380
+ void installAgent(stepping).catch((error) => {
381
+ ctx.logger.error(`dsh-submodel: pre-step install failed for "${stepping.id}": ${String(error)}`);
382
+ });
383
+ }
384
+ return next();
385
+ });
386
+ reconcile();
387
+
388
+ // 根插件 cleanup:等自有安装全部卸载,再删状态。
389
+ //
390
+ // cordis 的插件拆卸通知是 `internal/plugin` 事件,listener 的 Promise 是 fire-and-forget;
391
+ // 并没有名为 `dispose` 的事件被发射——因此原来的 `ctx.on('dispose', …)` 清理回调**永不执行**。
392
+ // 两个通道都保留——谁先来谁触发,幂等。
393
+ const cleanupAll = () => {
394
+ if (uninstallAllTask !== undefined) return uninstallAllTask;
395
+ const agents = agentsService();
396
+ if (agents === undefined) return undefined;
397
+ const tasks = [];
398
+ for (const candidate of agents.list()) {
399
+ tasks.push(uninstallAgent(candidate, 'plugin cleanup'));
400
+ textResolvers.delete(candidate);
401
+ }
402
+ uninstallAllTask = Promise.all(tasks).finally(() => { uninstallAllTask = undefined; });
403
+ return uninstallAllTask;
404
+ };
405
+ let uninstallAllTask;
406
+ ctx.on('dispose', cleanupAll);
407
+ ctx.on('internal/plugin', (fiber) => {
408
+ // 只在"自己这条 fiber 被拆掉"的那一刻触发(该事件正是 emitPluginDisposed 的载荷)。
409
+ if (fiber !== ctx.fiber) return;
410
+ void cleanupAll();
411
+ });
412
+ }
413
+
414
+ /**
415
+ * 解析"本次 assembly 用的主模型"。
416
+ *
417
+ * 顺序(必须对齐 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`——最后的兜底。
423
+ *
424
+ * 三条都拿不到时**明确报错**,不猜模型(猜错会把整段策略换成另一套且不报错)。
425
+ *
426
+ * @param ctx - 插件顶层 ctx(用于取 sessionController)。
427
+ * @param agent - 目标 agent。
428
+ * @param assembly - 已完成 next() 的 assembly。
429
+ * @returns 模型 ID。
430
+ */
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。
438
+ }
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); // 抛出明确配置错误
444
+ }
445
+
446
+ /** 宽松取 `assembly.variables.model`;缺失返回 undefined(不抛)。 */
447
+ function assemblyModelOrUndefined(assembly) {
448
+ const model = assembly?.variables?.model;
449
+ return typeof model === 'string' && model !== '' ? model : undefined;
450
+ }
package/lib/policy.js ADDED
@@ -0,0 +1,312 @@
1
+ /**
2
+ * dsh-submodel / policy.js —— 纯函数层:角色与模式判定、统一入口的路由默认值、正文模板与渲染。
3
+ *
4
+ * 这里是**没有副作用、不 import 任何 runtime helper** 的一层,唯一目的就是能被单测直接喂输入、
5
+ * 断言输出。宿主对象(tool 定义、Service、fiber)一律不进这个文件——否则纯函数测试就得先造
6
+ * 一整套假 Host,测试本身会变成对 mock 的测试。
7
+ *
8
+ * 两条正交的判定(不要合并,它们回答不同的问题):
9
+ *
10
+ * 1. **模式(mode)**:只由「本次 assembly 的主模型 ID 是否以 `flash` 结尾」决定。
11
+ * 用户在 GUI 里选的是主模型;主模型是 Flash → 走 `economize`(自己干日常,委派继承自己);
12
+ * 不是 Flash → 走 `boss`(强主脑理解/判断/写作,可验证的执行块默认派执行路由)。
13
+ * **只看模型 id,不看 provider、显示名或价格**——这是用户约定的唯一规则。
14
+ *
15
+ * 2. **角色(role)**:`root` 还是 `child`,由 header 的 `origin`/`delegationDepth` 判定。
16
+ * 子代是执行/专家角色,**不再**按 Flash 后缀切换主脑策略;子代永远禁止再委派。
17
+ *
18
+ * 为什么两个时点分别用不同来源(别改成"都用同一个"):
19
+ * - **提示词阶段**用 `assembly.variables.model`——它描述"GUI 即将发起的这笔请求",
20
+ * 首轮和刚换模都能立刻对齐;
21
+ * - **执行阶段**用"最新已接受的 request header config"——它描述"正在发起这笔工具调用的主脑",
22
+ * 不会读到 GUI 里那个还没提交的 pending 选择。
23
+ * 用错任一个都会在"刚换模但还没发请求"的窗口里判错模式。
24
+ *
25
+ * **正文与路由解耦**:本文件内置的模板里**不得出现任何具体 provider/model 名**。执行路由与
26
+ * 专家路由只经 `{{executorRoute}}` / `{{expertRoutes}}` 占位符注入(见 renderTemplate),
27
+ * 这样同一份代码既能在任意用户的模型体系下工作,也不会把某个部署的私有路由泄进公版正文。
28
+ *
29
+ * @module dsh-submodel/policy
30
+ */
31
+
32
+ /** 模式取值:Flash 主脑(低成本主脑+专家)/ 非 Flash 主脑(强主脑+执行路由)。 */
33
+ export const MODE_ECONOMIZE = 'economize';
34
+ export const MODE_BOSS = 'boss';
35
+
36
+ /** 统一委派入口的工具名(唯一顶层注册)。 */
37
+ export const DELEGATE_TOOL_NAME = 'delegate_task';
38
+
39
+ /** 本模块全局注册的唯一提示词段名。 */
40
+ export const ROUTING_SECTION = 'tool:model-routing';
41
+
42
+ /** 段顺序:紧接 SECTION_ORDERS.TOOL_SUBAGENT(2800)、TOOL_REPORT(2900)之前。 */
43
+ export const ROUTING_ORDER = 2850;
44
+
45
+ /** 递归限制要隐去的工具面(子代硬边界)。 */
46
+ export const CHILD_FORBIDDEN_TOOLS = Object.freeze([
47
+ DELEGATE_TOOL_NAME,
48
+ 'subagent',
49
+ 'subagent_fork',
50
+ 'workflow',
51
+ 'spawn_teammate',
52
+ ]);
53
+
54
+ /**
55
+ * 唯一规则:模型 ID 以 `flash` 结尾即 Flash 模式。
56
+ * 大小写不敏感、必须是**后缀**(`flash-lite` 不算),空值/非字符串不算。
57
+ * @param model - 模型 ID(可能来自 GUI 选择、header、或 undefined)。
58
+ * @returns 是否为 Flash 主脑。
59
+ */
60
+ export function isFlashModel(model) {
61
+ return typeof model === 'string' && model.toLowerCase().endsWith('flash');
62
+ }
63
+
64
+ /**
65
+ * 由模型 ID 判定本次顶层模式。
66
+ * @param model - 模型 ID。
67
+ * @returns {MODE_ECONOMIZE} 或 {MODE_BOSS}。
68
+ */
69
+ export function modeForModel(model) {
70
+ return isFlashModel(model) ? MODE_ECONOMIZE : MODE_BOSS;
71
+ }
72
+
73
+ /**
74
+ * 判定调用者角色。**子代**的判据是 header 的 `origin === 'subagent'` 或正的 delegationDepth;
75
+ * 刻意不用 `parentSession`(普通用户 fork 也带 parentSession,那不是子代)。
76
+ * @param header - session header(可为 undefined)。
77
+ * @param options - agent options(作为 depth 的兜底来源,可为 undefined)。
78
+ * @returns {'child'|'root'}。
79
+ */
80
+ export function roleOf(header, options) {
81
+ if (header !== undefined && header !== null) {
82
+ if (header.origin === 'subagent') return 'child';
83
+ const depth = header.delegationDepth;
84
+ if (typeof depth === 'number' && Number.isFinite(depth) && depth > 0) return 'child';
85
+ }
86
+ const optionDepth = options?.subagentDepth;
87
+ if (typeof optionDepth === 'number' && Number.isFinite(optionDepth) && optionDepth > 0) return 'child';
88
+ return 'root';
89
+ }
90
+
91
+ /**
92
+ * 从 execution context 判定角色。`exec.agent` 是唯一权威来源:
93
+ * 它必须存在且是 live Agent(有 session.requestHeader 与 options)。
94
+ * @param exec - 工具执行输入(含 agent)。
95
+ * @returns {{ok: true, role: 'root'|'child', header: object|undefined, agent: object}}
96
+ * 或 `{ok: false, reason: string}`。
97
+ */
98
+ export function resolveCallerRole(exec) {
99
+ const agent = exec?.agent;
100
+ if (agent === undefined || agent === null) {
101
+ return { ok: false, reason: 'delegate_task requires a calling agent (exec.agent was undefined)' };
102
+ }
103
+ if (typeof agent.session?.requestHeader !== 'function') {
104
+ return { ok: false, reason: 'delegate_task requires a live Agent with a session header (exec.agent looked stale)' };
105
+ }
106
+ const header = agent.session.requestHeader();
107
+ const role = roleOf(header, agent.options);
108
+ return { ok: true, role, header, agent };
109
+ }
110
+
111
+ /**
112
+ * 显式路由的成对性校验。**只给一个必须立即失败**,绝不偷偷补另一个(那会让"我只想换模型"
113
+ * 变成"换到某条我从没授权的渠道")。
114
+ * @param args - 工具入参(含可选 provider/model/reasoning_effort)。
115
+ * @returns `{kind:'none'}` / `{kind:'pair', provider, model}` / `{kind:'invalid', reason}`。
116
+ */
117
+ export function classifyExplicitRoute(args) {
118
+ const provider = args?.provider;
119
+ const model = args?.model;
120
+ const hasProvider = provider !== undefined && provider !== null && provider !== '';
121
+ const hasModel = model !== undefined && model !== null && model !== '';
122
+ if (hasProvider && hasModel) {
123
+ return { kind: 'pair', provider: String(provider), model: String(model) };
124
+ }
125
+ if (hasProvider || hasModel) {
126
+ const given = hasProvider ? `provider "${String(provider)}"` : `model "${String(model)}"`;
127
+ const missing = hasProvider ? 'model' : 'provider';
128
+ return {
129
+ kind: 'invalid',
130
+ reason: `delegate_task received ${given} without ${missing}: an explicit child route must name provider AND model together`,
131
+ };
132
+ }
133
+ return { kind: 'none' };
134
+ }
135
+
136
+ /**
137
+ * 计算这次委派的最终子代参数。
138
+ *
139
+ * 规则(四类分支都要覆盖):
140
+ * - **完整显式 pair**:原样保留,**不注入策略 effort**(让原生规则决定继承兼容 effort 或清掉不兼容的);
141
+ * - **只给一个**:失败(见 classifyExplicitRoute);
142
+ * - **无显式路由 + Flash 主脑**:不补任何 provider/model(子代继承当前 Flash);
143
+ * - **无显式路由 + 非 Flash 主脑**:补配置的 executor pair;未给 reasoning_effort 时补 max,
144
+ * 给了就保留——max 仅作缺省,不覆盖调用方已指定的档位。
145
+ *
146
+ * 专家路由完全由配置决定:本函数不认识任何具体 provider/model 名,也不做"某条路由只能兜底"
147
+ * 之类的硬编码特判(那会把某个部署的私有约定写进公版代码)。
148
+ *
149
+ * @param args - 原始工具入参(**只读,不修改**)。
150
+ * @param mode - modeForModel 的结果。
151
+ * @param executor - 配置的 `{provider, model, reasoningEffort}`。
152
+ * @returns `{ok:true, args: newArgs, applied: 'explicit'|'executor'|'inherit'}` 或 `{ok:false, reason}`。
153
+ */
154
+ export function resolveDelegationArgs(args, mode, executor) {
155
+ const route = classifyExplicitRoute(args);
156
+ if (route.kind === 'invalid') return { ok: false, reason: route.reason };
157
+ // 派生新对象:原 exec/arguments 由 tools runtime 冻结,改不得。
158
+ const next = { ...args };
159
+ if (route.kind === 'pair') return { ok: true, args: next, applied: 'explicit' };
160
+ if (mode !== MODE_BOSS) {
161
+ return { ok: true, args: next, applied: 'inherit' };
162
+ }
163
+ 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)' };
165
+ }
166
+ next.provider = executor.provider;
167
+ next.model = executor.model;
168
+ if (next.reasoning_effort === undefined || next.reasoning_effort === null || next.reasoning_effort === '') {
169
+ // 只在"没给"时补默认;给了就保留调用方/配置的原值。
170
+ next.reasoning_effort = executor.reasoningEffort ?? 'max';
171
+ }
172
+ return { ok: true, args: next, applied: 'executor' };
173
+ }
174
+
175
+ // ── 正文模板与渲染 ────────────────────────────────────────────────────────────
176
+
177
+ /** 顶层 Flash(economize):主脑自己干日常,委派继承自己,只在瓶颈时显式点名专家。 */
178
+ const ECONOMIZE_TEMPLATE = `## 模型路由:Flash 主脑(主脑自己干,瓶颈才升级)
179
+
180
+ 当前主模型是 Flash 档。默认路径=**你自己完成**:事实性查证、读写代码、跑命令与测试、检索汇总、拆解编排,以及把可并行的取证/执行子任务交给 \`delegate_task\`(**不传 provider/model**,子代继承当前 Flash 路由,省 token)。这些任务不要动用专家模型。
181
+
182
+ 只有下面两种情况才升级;需要升级时再按领域**显式**选模型:
183
+ 1. 问题本身属于**复杂代码/逻辑判断**——跨模块契约、状态机、并发与时序、不可逆数据变更、多方案权衡,且你自己无法自证;
184
+ 2. 任务本身超出你的执行上限(反复失败、需要更强推理才能推进)。
185
+
186
+ 已配置的专家路由(升级时从这里点名,\`provider\` 与 \`model\` 必须成对传):
187
+ {{expertRoutes}}
188
+
189
+ **"需要独立审查/复核"本身不是升级理由**。复核默认交给普通子代理(\`delegate_task\` 不传 \`provider\`/\`model\`,子代继承当前路由);只有当**被复核的东西本身**满足上面第 1 条时才点名专家。
190
+
191
+ 调用方式:普通任务统一走 \`delegate_task\`,它的参数与原生 \`subagent\` 相同;\`provider\` 与 \`model\` 必须**成对**传,只给一个会立即失败。不确定有哪些授权路由时先调 \`list_subagent_models\`。\`reasoning_effort\` 以各路由支持的档位为准,不传时用配置缺省,显式档位优先。三个都不传就继承主模型路由,即默认路径。升级前先把证据收齐,并把已知事实、约束、已试过的方案写进 prompt——子智能体看不到本会话历史。
192
+
193
+ 需要多方校验或讨论时:在同一条消息里并发起两个 \`delegate_task\`,给**完全相同**的 brief 且**彼此不可见**,然后由你自己比对分歧、下判断;只有在出现实质分歧时,才把对方的**理由**回传给各自,要求逐条反驳或让步。
194
+
195
+ 纪律:专家结论必须被明确处置——要么采纳,要么写出驳回理由及依据,不得静默忽略。子智能体失败或超时时,明确标注"未获得专家意见"并降级为自证,不得假装已咨询过。`;
196
+
197
+ /** 顶层非 Flash(boss):主脑负责理解/判断/写作,可验证的执行块默认派执行路由。 */
198
+ const BOSS_TEMPLATE = `## 模型路由:强主脑(你负责判断,可验证的执行块默认派执行路由)
199
+
200
+ 当前主模型是强主脑档。**理解、拆解、关键判断、关键代码与最终写作由你自己完成**——不要把这些外包出去。
201
+
202
+ 可验证的**执行块**默认用 \`delegate_task\` 派给配置的执行路由(**不传 provider/model**:会自动补 \`{{executorRoute}}\`,未点名档位时用配置缺省,显式档位优先):检索、读取、批量命令、结构化的资料整理、边界清晰的局部实现。不是每一个 \`read\`/\`pwd\` 都要派工——**按"块"委派并收回原始证据**,别把关键推理整体外包。
203
+
204
+ 需要更强模型时**显式**点名——判据是**问题本身的复杂度**,不是"要不要复核"(\`provider\` 与 \`model\` 必须成对传,只给一个立即失败;完整显式路线不会被改写):
205
+ 1. 问题本身属于**复杂代码/逻辑判断**——跨模块契约、状态机、并发与时序、不可逆数据变更、多方案权衡,且你自己无法自证;
206
+ 2. 任务本身超出你的执行上限(反复失败、需要更强推理才能推进)。
207
+
208
+ 已配置的专家路由:
209
+ {{expertRoutes}}
210
+
211
+ 不确定有哪些授权路由时先调 \`list_subagent_models\`。
212
+
213
+ **"需要独立审查/复核"本身不是升级理由**。复核默认交给普通子代理(\`delegate_task\` 不传 \`provider\`/\`model\`,走配置的执行路由);只有当**被复核的东西本身**满足上面第 1 条时才点名专家。
214
+ 派出子代理后不要反复轮询:\`delegate_task\` 前台调用会直接返回结果;需要查看在线子代理、追加消息或停止时,用 \`list_agents\` / \`send_message\` / \`interrupt_agent\`。
215
+
216
+ 原生 \`subagent\` 仍是**显式专家入口**:在本模式下,它若不带**完整**的 provider/model 对会被拒绝并指向 \`delegate_task\`——这是为了不让"顺手用 subagent"绕过执行路由默认值。
217
+
218
+ 子代回来后按证据复核,不要只读它的结论。子智能体失败或超时时,明确标注"未获得该路线的结果"并降级为自证,不得假装已咨询过。`;
219
+
220
+ /** 子代正文:**固定执行职责**,不含任何主脑升级策略(子代不再切换主脑策略,也禁止再派工)。 */
221
+ const CHILD_TEXT = `## 你的角色:被委派的执行 / 专家子智能体
222
+
223
+ 你没有再次委派的能力:\`delegate_task\`、\`subagent\`、\`subagent_fork\`、\`workflow\`、\`spawn_teammate\` 在本会话都不可用,调用会被拒绝。任务超出你的能力或权限时,**不要重试被拒绝的操作**,直接在回复里说明限制,交给父代处理。
224
+
225
+ 你收到的是一次**边界清晰的任务**,不是整个会话的上下文。请:
226
+ 1. 只做被要求的事,不擅自扩大范围、不顺手重构;
227
+ 2. 需要读文件/跑命令就实际去读、去跑——**不要凭记忆或推断作答**;
228
+ 3. 汇报时给出**原始证据**:实际读了哪个文件(绝对路径)、实际命令与关键输出、关键行号,以及你验证过什么、没验证什么;
229
+ 4. 结论与证据分开写。不确定就明说"不确定",不要用更像样的措辞掩盖没验证的部分。`;
230
+
231
+ /** 执行路由的渲染形式;未配置时给可读占位而不是空串。 */
232
+ function renderExecutorRoute(executor) {
233
+ if (executor === undefined || executor === null || !executor.provider || !executor.model) return '(未配置)';
234
+ return `provider: "${executor.provider}", model: "${executor.model}"`;
235
+ }
236
+
237
+ /**
238
+ * 把配置的专家路由渲染成正文里的一段列表。
239
+ * @param experts - 配置的专家数组(每项 `{label, provider, model, reasoningEffort?}`)。
240
+ * @returns 逐行列表;空数组返回"未配置"提示行(不渲染空段)。
241
+ */
242
+ export function renderExpertRoutes(experts) {
243
+ const list = Array.isArray(experts) ? experts : [];
244
+ const rows = list
245
+ .filter((expert) => expert !== undefined && expert !== null)
246
+ .map((expert) => `- \`${expert.label ?? ''}\` → \`provider: "${expert.provider ?? ''}"\`, \`model: "${expert.model ?? ''}"\``);
247
+ if (rows.length === 0) return '- (未配置专家路由;升级时请显式传 provider/model)';
248
+ return rows.join('\n');
249
+ }
250
+
251
+ /**
252
+ * 用运行期配置渲染模板:只替换 `{{executorRoute}}` 与 `{{expertRoutes}}`,其余原样保留。
253
+ * @param template - 内置模板字符串。
254
+ * @param renderContext - `{executor, experts, texts}`(缺字段按空处理)。
255
+ * @returns 渲染后的正文。
256
+ */
257
+ export function renderTemplate(template, renderContext) {
258
+ const context = renderContext ?? {};
259
+ const executorRoute = renderExecutorRoute(context.executor);
260
+ const expertRoutes = renderExpertRoutes(context.experts);
261
+ return String(template)
262
+ .split('{{executorRoute}}').join(executorRoute)
263
+ .split('{{expertRoutes}}').join(expertRoutes);
264
+ }
265
+
266
+ /**
267
+ * 按角色与模式取本段正文。子代永远走固定执行职责文本。
268
+ *
269
+ * `renderContext.texts.*` 非空时**整段替换**内置模板(替换后不再插值,用户写什么就是什么);
270
+ * 为空时用内置模板 + 占位符渲染。
271
+ *
272
+ * @param role - 'root' 或 'child'。
273
+ * @param model - 本次 assembly 的模型 ID。
274
+ * @param renderContext - `{executor, experts, texts}`;纯函数调用时可省略。
275
+ * @returns 该段应渲染的文本。
276
+ */
277
+ export function routingTextFor(role, model, renderContext) {
278
+ const context = renderContext ?? {};
279
+ const texts = context.texts ?? {};
280
+ if (role === 'child') {
281
+ const override = typeof texts.child === 'string' ? texts.child : '';
282
+ return override !== '' ? override : CHILD_TEXT;
283
+ }
284
+ const mode = modeForModel(model);
285
+ const override = mode === MODE_ECONOMIZE ? texts.economize : texts.boss;
286
+ if (typeof override === 'string' && override !== '') return override;
287
+ const template = mode === MODE_ECONOMIZE ? ECONOMIZE_TEMPLATE : BOSS_TEMPLATE;
288
+ return renderTemplate(template, context);
289
+ }
290
+
291
+ /**
292
+ * 取本次 assembly 的主模型。缺失/空值必须**明确报错**,不许猜模型
293
+ * (猜错会把整段策略换成另一套,而且不报错)。
294
+ * @param assembly - 已完成 `await next()` 的提示词 assembly。
295
+ * @returns 模型 ID 字符串。
296
+ * @throws 当 `assembly.variables.model` 缺失或为空时。
297
+ */
298
+ export function modelFromAssembly(assembly) {
299
+ const model = assembly?.variables?.model;
300
+ if (typeof model !== 'string' || model === '') {
301
+ throw new Error('dsh-submodel: system-prompt assembly has no `variables.model`; cannot classify the top-level mode without it');
302
+ }
303
+ return model;
304
+ }
305
+
306
+ /**
307
+ * 构建普通子代的"适用范围"说明,供 guard 拒绝时给出可读诊断。
308
+ * @returns 一句面向模型的说明。
309
+ */
310
+ export function childDelegationRefusal() {
311
+ return 'this session is a delegated subagent: it cannot delegate further. Report the limitation to your parent instead of retrying.';
312
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "dsh-submodel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "官方 subagent 的默认策略包:装上一次配好「什么时候自己干、什么时候派出去、派给谁」。",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./cordis.patch.yml": "./cordis.patch.yml",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/angel291592/dsh-submodel.git"
16
+ },
17
+ "dsh": {
18
+ "bundle": {
19
+ "patch": "./cordis.patch.yml"
20
+ }
21
+ },
22
+ "engines": {
23
+ "dsh": ">=0.2.1-rc.3 <0.3.0"
24
+ },
25
+ "peerDependencies": {
26
+ "@deepseek-ai/schemastery": "~3.18.4"
27
+ },
28
+ "files": [
29
+ "lib",
30
+ "cordis.patch.yml",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "keywords": [
35
+ "dsh",
36
+ "dsh-plugin",
37
+ "deepseek-harness",
38
+ "subagent",
39
+ "delegation",
40
+ "policy",
41
+ "model-routing"
42
+ ]
43
+ }