dsh-submodel 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +249 -0
- package/README.md +228 -2
- package/cordis.patch.yml +3 -0
- package/lib/delegation.js +271 -0
- package/lib/index.js +502 -0
- package/lib/policy.js +683 -0
- package/lib/setup.js +253 -0
- package/package.json +50 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
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
|
+
isEconomyRoute,
|
|
48
|
+
roleOf,
|
|
49
|
+
routeFromAssembly,
|
|
50
|
+
routingTextFor,
|
|
51
|
+
} from './policy.js';
|
|
52
|
+
import { createDelegateTool, findNativeSubagent } from './delegation.js';
|
|
53
|
+
import { createSetupTool } from './setup.js';
|
|
54
|
+
|
|
55
|
+
export const name = 'dsh-submodel';
|
|
56
|
+
|
|
57
|
+
/** 用到的服务必须列全:apply 会等到它们可用才执行。 */
|
|
58
|
+
export const inject = ['tools', 'systemPrompt'];
|
|
59
|
+
|
|
60
|
+
export const Config = z.object({
|
|
61
|
+
/** 自动策略总开关。默认开启:公开版的目标就是"装上一次配好"。 */
|
|
62
|
+
enabled: z.boolean().default(true),
|
|
63
|
+
/** 只对这一个 composition 生效;其他 preset 不安装任何东西。 */
|
|
64
|
+
preset: z.string().default('standard'),
|
|
65
|
+
/** 能力门控工具名:该 scope 不可见时策略段不渲染(工具仍按注册门控安装)。 */
|
|
66
|
+
toolName: z.string().default('list_subagent_models'),
|
|
67
|
+
/** 段顺序;默认紧接 TOOL_SUBAGENT(2800)。 */
|
|
68
|
+
order: z.number().default(ROUTING_ORDER),
|
|
69
|
+
/**
|
|
70
|
+
* 执行路由(非 Flash 主脑的默认派工目标)。**唯一配置源**:执行期注入的 pair 由它派生,
|
|
71
|
+
* 正文里的执行路由也只经占位符从它渲染,不允许 YAML/JS 双写两个不同的路由名。
|
|
72
|
+
*/
|
|
73
|
+
executor: z.object({
|
|
74
|
+
provider: z.string().default(''),
|
|
75
|
+
model: z.string().default(''),
|
|
76
|
+
reasoningEffort: z.string().default('max'),
|
|
77
|
+
}).default({ provider: '', model: '', reasoningEffort: 'max' }),
|
|
78
|
+
/**
|
|
79
|
+
* 专家路由:升级时允许显式点名的 `{label, provider, model, reasoningEffort?}` 列表。
|
|
80
|
+
* 空数组时正文给出"未配置专家路由"提示,不渲染任何具体路由名。
|
|
81
|
+
*/
|
|
82
|
+
experts: z.array(z.object({
|
|
83
|
+
label: z.string(),
|
|
84
|
+
provider: z.string(),
|
|
85
|
+
model: z.string(),
|
|
86
|
+
reasoningEffort: z.string().default('max'),
|
|
87
|
+
})).default([]),
|
|
88
|
+
/**
|
|
89
|
+
* 正文覆盖:任一项非空时**整段替换**内置模板(替换后不再插值),方便用户写自己的话术。
|
|
90
|
+
*/
|
|
91
|
+
texts: z.object({
|
|
92
|
+
economize: z.string().default(''),
|
|
93
|
+
boss: z.string().default(''),
|
|
94
|
+
child: z.string().default(''),
|
|
95
|
+
}).default({ economize: '', boss: '', child: '' }),
|
|
96
|
+
/**
|
|
97
|
+
* 是否安装"非经济路由顶层用原生 subagent 时必须给完整显式 pair"的 guard。
|
|
98
|
+
* 默认开启;关掉后原生 subagent 的行为完全交给宿主。
|
|
99
|
+
*/
|
|
100
|
+
guardNativeSubagent: z.boolean().default(true),
|
|
101
|
+
/**
|
|
102
|
+
* 自动配置开关:root 且 `executor` 未配置时注册 `configure_submodel` 向导
|
|
103
|
+
* (探测宿主渠道/模型 → 一张卡确认 → 写插件配置 + 宿主授权表)。默认开启。
|
|
104
|
+
*/
|
|
105
|
+
autoConfigure: z.boolean().default(true),
|
|
106
|
+
/**
|
|
107
|
+
* 经济路由列表:主模型命中其中一项即走 economize 模式(不再要求模型名以 flash 结尾)。
|
|
108
|
+
* 每项 `{provider?, model}`;`provider` 为空时只比 model。为空数组时保留 flash 后缀兼容。
|
|
109
|
+
*/
|
|
110
|
+
economyRoutes: z.array(z.object({
|
|
111
|
+
provider: z.string().default(''),
|
|
112
|
+
model: z.string().min(1),
|
|
113
|
+
})).default([]),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
/** 判断一个 agent 是否属于本插件负责的 composition。 */
|
|
117
|
+
function belongsToComposition(agent, presetId, presetService) {
|
|
118
|
+
if (presetService === undefined) return false;
|
|
119
|
+
try {
|
|
120
|
+
return presetService.composedPreset(agent.ctx) === presetId;
|
|
121
|
+
} catch {
|
|
122
|
+
// 组合正在解散时 composedPreset 可能抛;视为"不属于",走卸载路径,
|
|
123
|
+
// 不把异常抛进事件回调。
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function apply(ctx, config) {
|
|
129
|
+
const enabled = config.enabled === true;
|
|
130
|
+
const presetId = config.preset ?? 'standard';
|
|
131
|
+
const toolName = config.toolName ?? 'list_subagent_models';
|
|
132
|
+
const order = config.order ?? ROUTING_ORDER;
|
|
133
|
+
const executor = {
|
|
134
|
+
provider: config.executor?.provider ?? '',
|
|
135
|
+
model: config.executor?.model ?? '',
|
|
136
|
+
reasoningEffort: config.executor?.reasoningEffort ?? 'max',
|
|
137
|
+
};
|
|
138
|
+
const experts = Array.isArray(config.experts) ? config.experts : [];
|
|
139
|
+
const texts = {
|
|
140
|
+
economize: config.texts?.economize ?? '',
|
|
141
|
+
boss: config.texts?.boss ?? '',
|
|
142
|
+
child: config.texts?.child ?? '',
|
|
143
|
+
};
|
|
144
|
+
const economyRoutes = Array.isArray(config.economyRoutes)
|
|
145
|
+
? config.economyRoutes
|
|
146
|
+
.filter(
|
|
147
|
+
(row) =>
|
|
148
|
+
row !== null &&
|
|
149
|
+
typeof row === 'object' &&
|
|
150
|
+
typeof row.model === 'string' &&
|
|
151
|
+
row.model !== '',
|
|
152
|
+
)
|
|
153
|
+
.map((row) => ({ provider: typeof row.provider === 'string' ? row.provider : '', model: row.model }))
|
|
154
|
+
: [];
|
|
155
|
+
const guardNativeSubagent = config.guardNativeSubagent !== false;
|
|
156
|
+
const autoConfigure = config.autoConfigure !== false;
|
|
157
|
+
/** 模式判定用的运行期策略(与 policy.js 纯函数同口径)。 */
|
|
158
|
+
const routingPolicy = { executor, economyRoutes };
|
|
159
|
+
/** 每次 assembly 现渲染正文用的运行期上下文(纯函数层只认它)。 */
|
|
160
|
+
const renderContext = { executor, experts, texts, economyRoutes };
|
|
161
|
+
/** 执行路由是否未配置(未配置时才注册自动配置向导)。 */
|
|
162
|
+
const executorIncomplete = executor.provider === '' || executor.model === '';
|
|
163
|
+
|
|
164
|
+
/** 每个 agent 的 assembly listener 装的文本解析器:`(resolved) => string|null`。 */
|
|
165
|
+
const textResolvers = new WeakMap();
|
|
166
|
+
|
|
167
|
+
// ── 全局唯一的段(只注册一次,绝不重复注册同名段) ─────────────────────────
|
|
168
|
+
ctx.systemPrompt.section({
|
|
169
|
+
name: ROUTING_SECTION,
|
|
170
|
+
order,
|
|
171
|
+
// enabled 时正文完全交给 per-agent listener;enabled=false 时保持空段,
|
|
172
|
+
// 不注册任何工具/guard(与"关闭即无感"一致)。
|
|
173
|
+
text: () => '',
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
if (!enabled) {
|
|
177
|
+
ctx.logger.info('dsh-submodel: enabled=false,策略未启用(只注册空段,不安装任何工具/guard)');
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ── fail-fast(只记日志、绝不抛) ──────────────────────────────────────────
|
|
182
|
+
if (executorIncomplete) {
|
|
183
|
+
ctx.logger.error(
|
|
184
|
+
'dsh-submodel: config.executor.provider/model 未配置,自动委派不可用;可调用 `configure_submodel` 自动配置或按 README 两步配置',
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
ctx.logger.info(
|
|
188
|
+
`dsh-submodel: 自动策略已启用(preset=${presetId}, executor=${executor.provider || '(未配置)'}/${executor.model || '(未配置)'}, experts=${experts.length})`,
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
// ── 逐 agent 安装 ──────────────────────────────────────────────────────────
|
|
192
|
+
const installed = new WeakMap();
|
|
193
|
+
const installing = new WeakSet();
|
|
194
|
+
const pendingInstalls = new WeakMap();
|
|
195
|
+
|
|
196
|
+
/** 每 agent 一次的诊断集合(plan §4.3:不得静默失效)。 */
|
|
197
|
+
const warnedNoPresets = new WeakSet();
|
|
198
|
+
const warnedNoNativeSubagent = new WeakSet();
|
|
199
|
+
const informedNoModelSelection = new WeakSet();
|
|
200
|
+
|
|
201
|
+
const presetService = () => ctx.get('agentPresets');
|
|
202
|
+
const agentsService = () => ctx.get('agents');
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 是否属于本插件的 composition。服务缺失时**每个 agent 记一次 warn**,
|
|
206
|
+
* 让"策略不生效"可诊断,而不是静默跳过。
|
|
207
|
+
*/
|
|
208
|
+
const isOurs = (agent) => {
|
|
209
|
+
const service = presetService();
|
|
210
|
+
if (service === undefined) {
|
|
211
|
+
if (!warnedNoPresets.has(agent)) {
|
|
212
|
+
warnedNoPresets.add(agent);
|
|
213
|
+
ctx.logger.warn('dsh-submodel: 当前 profile 无 agentPresets 服务,策略不生效');
|
|
214
|
+
}
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
return belongsToComposition(agent, presetId, service);
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
/** 卸载一个 agent 上本插件装的全部东西(只动记录过的项)。 */
|
|
221
|
+
const uninstallAgent = async (agent, reason) => {
|
|
222
|
+
const record = installed.get(agent);
|
|
223
|
+
textResolvers.delete(agent);
|
|
224
|
+
if (record === undefined) return;
|
|
225
|
+
installed.delete(agent);
|
|
226
|
+
for (const dispose of [...record.disposers].reverse()) {
|
|
227
|
+
try {
|
|
228
|
+
await dispose();
|
|
229
|
+
} catch (error) {
|
|
230
|
+
ctx.logger.warn(
|
|
231
|
+
`dsh-submodel: failed to dispose one registration for agent "${agent.id}" (${reason}): ${String(error)}`,
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
ctx.logger.info(`dsh-submodel: removed own install from agent "${agent.id}" (${reason})`);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* 为 agent 安装自动能力。幂等:已装直接返回;正在装共用同一 Promise。
|
|
240
|
+
*/
|
|
241
|
+
const installAgent = async (agent) => {
|
|
242
|
+
if (installed.has(agent)) return;
|
|
243
|
+
const existing = pendingInstalls.get(agent);
|
|
244
|
+
if (existing !== undefined) return existing;
|
|
245
|
+
if (installing.has(agent)) return undefined;
|
|
246
|
+
installing.add(agent);
|
|
247
|
+
const task = (async () => {
|
|
248
|
+
const scopedCtx = agent.ctx;
|
|
249
|
+
const disposers = [];
|
|
250
|
+
try {
|
|
251
|
+
// 观看作用域=**agent 对象本身**:`tools.view(agent)` 才是模型实际拿到的工具目录。
|
|
252
|
+
// 传 `agent.ctx` 会退化成 global 视图,永远查不到 subagent。
|
|
253
|
+
//
|
|
254
|
+
// **判据必须在 try 内**:原生 subagent 在 `agent/created` 那一刻可能还没注册好,
|
|
255
|
+
// 此时要**早退但清掉 installing 标记**——否则该 agent 被永久标记为"正在安装",
|
|
256
|
+
// 后续 reconcile 全部在守卫处返回,永远不再补装。
|
|
257
|
+
const nativeDefinition = findNativeSubagent(ctx.tools, agent);
|
|
258
|
+
if (nativeDefinition === undefined) {
|
|
259
|
+
if (!warnedNoNativeSubagent.has(agent)) {
|
|
260
|
+
warnedNoNativeSubagent.add(agent);
|
|
261
|
+
ctx.logger.warn('dsh-submodel: 原生 subagent 未暴露 provider/model,delegate_task 不安装');
|
|
262
|
+
}
|
|
263
|
+
return; // 无选模能力 → 什么都不装,等下一次 tools/change / pre-step 重试
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// **关键**:注册必须经 **agent 自己的 ctx**——既不能走插件顶层 ctx,也不能自建 scope。
|
|
267
|
+
// 经 `agent.ctx.tools` 注册时 traceable service 把 effect 落到 `scopeOf(agent.ctx)`,
|
|
268
|
+
// 既对该 agent 可见,也随 agent 一起释放。
|
|
269
|
+
const tools = agent.ctx.tools;
|
|
270
|
+
|
|
271
|
+
// 角色只在安装时判定一次:它来自 durable session header,agent 生命周期内不变。
|
|
272
|
+
// 改读 agent(而不是已作废的 EpochHeader)是为了修复"冷恢复子代永远判成 root"的缺陷。
|
|
273
|
+
const callerRole = roleOf(agent);
|
|
274
|
+
|
|
275
|
+
// ① 角色 guard:子代硬边界。**返回字符串即拒绝**(不是抛异常)。
|
|
276
|
+
const guard = (exec) => {
|
|
277
|
+
if (exec?.agent !== agent) return undefined;
|
|
278
|
+
const toolCallName = exec?.name;
|
|
279
|
+
if (typeof toolCallName !== 'string') return undefined;
|
|
280
|
+
if (callerRole !== 'child') return undefined;
|
|
281
|
+
const forbidden = CHILD_FORBIDDEN_TOOLS.includes(toolCallName) || toolCallName.startsWith('subagent');
|
|
282
|
+
if (!forbidden) return undefined;
|
|
283
|
+
return `dsh-submodel: tool "${toolCallName}" is unavailable to a delegated subagent. ${childDelegationRefusal()}`;
|
|
284
|
+
};
|
|
285
|
+
disposers.push(tools.guard(guard));
|
|
286
|
+
|
|
287
|
+
// ② 执行期硬边界的补充:非经济路由顶层用原生 subagent 但没给完整显式 pair 时,
|
|
288
|
+
// 拒绝并指向 delegate_task,防止模型绕开默认执行路由。
|
|
289
|
+
const nativeGuard = (exec) => {
|
|
290
|
+
if (exec?.agent !== agent) return undefined;
|
|
291
|
+
if (exec?.name !== 'subagent') return undefined;
|
|
292
|
+
if (callerRole !== 'root') return undefined;
|
|
293
|
+
// 执行期模式判定:取最新已接受 header 的 config,回退 agent.options。
|
|
294
|
+
if (isEconomyRoute(routeFromAgent(agent), routingPolicy)) return undefined; // 经济路由顶层原生调用不改变行为
|
|
295
|
+
const args = exec.arguments ?? {};
|
|
296
|
+
const hasProvider = args.provider !== undefined && args.provider !== null && args.provider !== '';
|
|
297
|
+
const hasModel = args.model !== undefined && args.model !== null && args.model !== '';
|
|
298
|
+
if (hasProvider && hasModel) return undefined; // 完整显式 pair:放行
|
|
299
|
+
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.';
|
|
300
|
+
};
|
|
301
|
+
if (guardNativeSubagent) disposers.push(tools.guard(nativeGuard));
|
|
302
|
+
|
|
303
|
+
// ③ assembly listener:先 await next(),再只替换自有段。
|
|
304
|
+
const listener = async (assembly, context, next) => {
|
|
305
|
+
const resolved = await next();
|
|
306
|
+
try {
|
|
307
|
+
const resolver = textResolvers.get(agent);
|
|
308
|
+
const text = resolver === undefined ? null : resolver(resolved);
|
|
309
|
+
if (text === null) return resolved;
|
|
310
|
+
return {
|
|
311
|
+
...resolved,
|
|
312
|
+
sections: resolved.sections.map((section) =>
|
|
313
|
+
section.name === ROUTING_SECTION
|
|
314
|
+
? { name: ROUTING_SECTION, text, interpolate: false }
|
|
315
|
+
: section,
|
|
316
|
+
),
|
|
317
|
+
};
|
|
318
|
+
} catch (error) {
|
|
319
|
+
ctx.logger.warn(`dsh-submodel: assembly section left unchanged for agent "${agent.id}": ${String(error)}`);
|
|
320
|
+
return resolved;
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
disposers.push(scopedCtx.on('system-prompt/assemble', listener));
|
|
324
|
+
|
|
325
|
+
// ④ 只有顶层注册统一委派入口(子代不再有委派能力)。
|
|
326
|
+
if (callerRole === 'root') {
|
|
327
|
+
disposers.push(
|
|
328
|
+
tools.register(
|
|
329
|
+
createDelegateTool({
|
|
330
|
+
ctx: agent.ctx,
|
|
331
|
+
nativeDefinition,
|
|
332
|
+
executor,
|
|
333
|
+
economyRoutes,
|
|
334
|
+
logger: ctx.logger,
|
|
335
|
+
}),
|
|
336
|
+
),
|
|
337
|
+
);
|
|
338
|
+
// ⑤ executor 未配置时注册自动配置向导(已配置/子代/autoConfigure=false 都不注册)。
|
|
339
|
+
// 向导走 agent.ctx.tools,随 agent 释放;它内部用插件顶层 ctx 取服务。
|
|
340
|
+
if (autoConfigure && executorIncomplete) {
|
|
341
|
+
disposers.push(tools.register(createSetupTool({ ctx, config, logger: ctx.logger })));
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// 正文解析器:角色安装时固定,模式每次 assembly 现判。
|
|
346
|
+
// `list_subagent_models` 不可见时**只门控正文段**(info 一次/agent),
|
|
347
|
+
// 工具仍按上面的注册门控安装。
|
|
348
|
+
textResolvers.set(agent, (resolved) => {
|
|
349
|
+
if (callerRole === 'child') return routingTextFor('child', undefined, renderContext);
|
|
350
|
+
if (ctx.tools.get(toolName, agent) === undefined) {
|
|
351
|
+
if (!informedNoModelSelection.has(agent)) {
|
|
352
|
+
informedNoModelSelection.add(agent);
|
|
353
|
+
ctx.logger.info(
|
|
354
|
+
'dsh-submodel: 本会话未启用官方 subagent 模型选择,策略段不渲染;请在设置中启用 subagent-model-selection',
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
return routingTextFor('root', resolveAssemblyRoute(ctx, agent, resolved), renderContext);
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
installed.set(agent, { disposers });
|
|
363
|
+
ctx.logger.info(`dsh-submodel: installed automatic routing on agent "${agent.id}" (role=${callerRole})`);
|
|
364
|
+
} catch (error) {
|
|
365
|
+
for (const dispose of [...disposers].reverse()) {
|
|
366
|
+
try {
|
|
367
|
+
await dispose();
|
|
368
|
+
} catch {
|
|
369
|
+
/* 清理失败不掩盖原始错误 */
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
ctx.logger.error(`dsh-submodel: failed to install automatic routing on agent "${agent.id}": ${String(error)}`);
|
|
373
|
+
throw error;
|
|
374
|
+
} finally {
|
|
375
|
+
installing.delete(agent);
|
|
376
|
+
}
|
|
377
|
+
})();
|
|
378
|
+
pendingInstalls.set(agent, task);
|
|
379
|
+
try {
|
|
380
|
+
await task;
|
|
381
|
+
} finally {
|
|
382
|
+
pendingInstalls.delete(agent);
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
/** 全量核对:属于本 composition 的装上,不属于的卸掉。 */
|
|
387
|
+
const reconcile = () => {
|
|
388
|
+
const agents = agentsService();
|
|
389
|
+
if (agents === undefined) return;
|
|
390
|
+
for (const candidate of agents.list()) {
|
|
391
|
+
if (isOurs(candidate)) {
|
|
392
|
+
installAgent(candidate).catch((error) => {
|
|
393
|
+
ctx.logger.error(`dsh-submodel: reconcile install failed for "${candidate.id}": ${String(error)}`);
|
|
394
|
+
});
|
|
395
|
+
} else {
|
|
396
|
+
void uninstallAgent(candidate, 'composition mismatch');
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
ctx.on('agent/created', async ({ agent: created }) => {
|
|
402
|
+
if (!isOurs(created)) return;
|
|
403
|
+
try {
|
|
404
|
+
await installAgent(created);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
// cordis 的事件发射不等待、也不捕获监听器返回的 Promise:这里必须自己兜住,
|
|
407
|
+
// 否则一次安装失败会变成 unhandled rejection(纯 Node CLI 下默认终止进程)。
|
|
408
|
+
// reconcile / pre-step 两条通道同样兜底,保证失败只上报、不炸宿主。
|
|
409
|
+
ctx.logger.error(`dsh-submodel: agent/created install failed for "${created.id}": ${String(error)}`);
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
ctx.on('agent/disposed', ({ agent: disposed }) => {
|
|
413
|
+
void uninstallAgent(disposed, 'agent disposed');
|
|
414
|
+
});
|
|
415
|
+
ctx.on('tools/change', reconcile);
|
|
416
|
+
/**
|
|
417
|
+
* 兜底重试(每一步开始前再核一次)。
|
|
418
|
+
*
|
|
419
|
+
* 原生 `subagent` 在 `agent/created` 那一刻**可能还没注册好**,而此后**不一定再有
|
|
420
|
+
* `tools/change`** → 只靠 `tools/change` 重试会永久漏装。`agent/pre-step` 是每个 agent
|
|
421
|
+
* 每一步都会过的 waterfall,天然覆盖"最迟在这一步装上";`installAgent` 幂等,已装时只是
|
|
422
|
+
* 一次 WeakMap 命中即返回。**必须是 waterfall 监听器:不接管决策就返回 `next()`。**
|
|
423
|
+
*/
|
|
424
|
+
ctx.on('agent/pre-step', ({ agent: stepping }, next) => {
|
|
425
|
+
if (stepping !== undefined && !installed.has(stepping) && isOurs(stepping)) {
|
|
426
|
+
void installAgent(stepping).catch((error) => {
|
|
427
|
+
ctx.logger.error(`dsh-submodel: pre-step install failed for "${stepping.id}": ${String(error)}`);
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
return next();
|
|
431
|
+
});
|
|
432
|
+
reconcile();
|
|
433
|
+
|
|
434
|
+
// 根插件 cleanup:等自有安装全部卸载,再删状态。
|
|
435
|
+
//
|
|
436
|
+
// cordis 的插件拆卸通知是 `internal/plugin` 事件,listener 的 Promise 是 fire-and-forget;
|
|
437
|
+
// 并没有名为 `dispose` 的事件被发射——因此原来的 `ctx.on('dispose', …)` 清理回调**永不执行**。
|
|
438
|
+
// 两个通道都保留——谁先来谁触发,幂等。
|
|
439
|
+
const cleanupAll = () => {
|
|
440
|
+
if (uninstallAllTask !== undefined) return uninstallAllTask;
|
|
441
|
+
const agents = agentsService();
|
|
442
|
+
if (agents === undefined) return undefined;
|
|
443
|
+
const tasks = [];
|
|
444
|
+
for (const candidate of agents.list()) {
|
|
445
|
+
tasks.push(uninstallAgent(candidate, 'plugin cleanup'));
|
|
446
|
+
textResolvers.delete(candidate);
|
|
447
|
+
}
|
|
448
|
+
uninstallAllTask = Promise.all(tasks).finally(() => { uninstallAllTask = undefined; });
|
|
449
|
+
return uninstallAllTask;
|
|
450
|
+
};
|
|
451
|
+
let uninstallAllTask;
|
|
452
|
+
ctx.on('dispose', cleanupAll);
|
|
453
|
+
ctx.on('internal/plugin', (fiber) => {
|
|
454
|
+
// 只在"自己这条 fiber 被拆掉"的那一刻触发(该事件正是 emitPluginDisposed 的载荷)。
|
|
455
|
+
if (fiber !== ctx.fiber) return;
|
|
456
|
+
void cleanupAll();
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* 解析"本次 assembly 用的路由"。
|
|
462
|
+
*
|
|
463
|
+
* 顺序(必须对齐 GUI 即将发起的那笔请求,不能用过期的创建期值):
|
|
464
|
+
* 1. `assembly.variables.provider` / `assembly.variables.model`——宿主 agent-loop 注册的
|
|
465
|
+
* 提示词变量,反映本次请求的路由;
|
|
466
|
+
* 2. `agent.options.provider` / `agent.options.model`——创建期值,仅作回退(例如 bundle 未注册变量)。
|
|
467
|
+
*
|
|
468
|
+
* 两处都拿不到 model 时**明确报错**,不猜模式(猜错会把整段策略换成另一套且不报错)。
|
|
469
|
+
* 注意这里**不读** `sessionController.agents.selectionFor`:DSH 0.2.2 没有该 service(死通道已删)。
|
|
470
|
+
*
|
|
471
|
+
* @param ctx - 插件顶层 ctx(保留参数位,当前实现不需要)。
|
|
472
|
+
* @param agent - 目标 agent。
|
|
473
|
+
* @param assembly - 已完成 next() 的 assembly。
|
|
474
|
+
* @returns `{provider, model}`。
|
|
475
|
+
*/
|
|
476
|
+
function resolveAssemblyRoute(ctx, agent, assembly) {
|
|
477
|
+
void ctx;
|
|
478
|
+
const variables = assembly?.variables;
|
|
479
|
+
const options = agent?.options ?? {};
|
|
480
|
+
const provider = typeof variables?.provider === 'string' ? variables.provider : options.provider;
|
|
481
|
+
const fromAssembly = typeof variables?.model === 'string' && variables.model !== '' ? variables.model : undefined;
|
|
482
|
+
const model = fromAssembly ?? options.model;
|
|
483
|
+
if (typeof model !== 'string' || model === '') {
|
|
484
|
+
// 两处都没有 model:走严格版本拿统一报错文案(不猜模式)。
|
|
485
|
+
return routeFromAssembly(assembly);
|
|
486
|
+
}
|
|
487
|
+
return { provider: typeof provider === 'string' ? provider : '', model };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* 执行期取"正在发起这笔工具调用的主脑路由":`session.requestHeader().config` 优先,
|
|
492
|
+
* `agent.options` 兜底。取不到 model 时返回空路由(守卫按 boss 处理,不抛)。
|
|
493
|
+
* @param agent - live agent。
|
|
494
|
+
* @returns `{provider, model}`(字段缺失时为空串/undefined)。
|
|
495
|
+
*/
|
|
496
|
+
function routeFromAgent(agent) {
|
|
497
|
+
const accepted = agent?.session?.requestHeader?.()?.config ?? agent?.options ?? {};
|
|
498
|
+
return {
|
|
499
|
+
provider: typeof accepted?.provider === 'string' ? accepted.provider : '',
|
|
500
|
+
model: typeof accepted?.model === 'string' ? accepted.model : '',
|
|
501
|
+
};
|
|
502
|
+
}
|