dsh-submodel 0.3.0 → 0.4.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
@@ -32,9 +32,11 @@
32
32
  */
33
33
  import {
34
34
  DELEGATE_TOOL_NAME,
35
+ classifyExplicitRoute,
35
36
  modeForRoute,
36
37
  resolveCallerRole,
37
38
  resolveDelegationArgs,
39
+ routeKey,
38
40
  } from './policy.js';
39
41
 
40
42
  /** 子调用 callId 的后缀:既能被日志一眼认出,又不会和原生 callId 撞(原生用随机 id)。 */
@@ -193,9 +195,8 @@ export function describeBatchFailure(error) {
193
195
  * - `logger`:日志器
194
196
  * @returns 可直接 `ctx.tools.register(...)` 的工具定义。
195
197
  */
196
- export function createDelegateTool({ ctx, nativeDefinition, executor, economyRoutes = [], logger }) {
197
- /** 执行期模式判定用的运行期策略(与 policy.js 纯函数同口径)。 */
198
- const routingPolicy = { executor, economyRoutes: Array.isArray(economyRoutes) ? economyRoutes : [] };
198
+ export function createDelegateTool({ ctx, nativeDefinition, executor, experts = [], modelGroups, economyRoutes = [], watchdog, logger }) {
199
+ const routingPolicy = { executor, modelGroups, economyRoutes: Array.isArray(economyRoutes) ? economyRoutes : [] };
199
200
  const parameters = cloneNativeParameters(nativeDefinition);
200
201
  // output 同样复用原生 schema/render,保持 runId/agentId 与 foreground/continuable 格式一致。
201
202
  const output = nativeDefinition.output;
@@ -206,66 +207,63 @@ export function createDelegateTool({ ctx, nativeDefinition, executor, economyRou
206
207
  return {
207
208
  name: DELEGATE_TOOL_NAME,
208
209
  description:
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. ' +
211
- 'Parameters are identical to the native `subagent` tool. Omit provider/model to inherit the ' +
212
- 'current route or use the configured execution route. ' +
213
- 'An explicit route must name provider AND model together. ' +
214
- 'Prefer this over the raw `subagent` tool for ordinary delegation.',
210
+ 'Start an independent subagent and get its name. The runtime delivers a completion notice. ' +
211
+ 'Omit provider and model for ordinary delegation, or supply both to select a model.',
215
212
  parameters,
216
213
  output,
217
214
  async execute(args, exec) {
218
- // ① 调用方身份必须是 live Agent,且必须是合格 standard 顶层。
219
215
  const caller = resolveCallerRole(exec);
220
- if (!caller.ok) throw new Error(caller.reason);
221
- if (caller.role !== 'root') throw new Error(`delegate_task is only available to a top-level agent (got role "${caller.role}")`);
216
+ if (!caller.ok) throw new Error('This delegation needs an active main conversation.');
217
+ if (caller.role !== 'root') throw new Error('Only the main conversation can delegate work.');
222
218
 
223
- // ② 同步快照执行期模式,再 await:描述"当前发起这笔调用的主脑",
224
- // 不读 GUI 里可能中途变化的 pending selection。
225
219
  const accepted = caller.header?.config ?? caller.agent.options ?? {};
226
220
  const route = {
227
- provider: typeof accepted?.provider === 'string' ? accepted.provider : '',
228
- model: typeof accepted?.model === 'string' ? accepted.model : '',
221
+ provider: typeof accepted.provider === 'string' ? accepted.provider : '',
222
+ model: typeof accepted.model === 'string' ? accepted.model : '',
229
223
  };
230
224
  const mode = modeForRoute(route, routingPolicy);
231
-
232
- // ③ 解析最终子代参数(原 exec/arguments 不可变,派生新对象)。
233
- const resolved = resolveDelegationArgs(args, mode, executor);
234
- if (!resolved.ok) throw new Error(resolved.reason);
235
-
236
- logger.info(
237
- `dsh-submodel: delegate_task session=${caller.header?.id ?? '?'} call=${exec.callId} mode=${mode} ` +
238
- `route=${resolved.applied} -> ${resolved.args.provider ?? '(inherit)'}/${resolved.args.model ?? '(inherit)'}`,
239
- );
240
-
241
- // ④ 发起一次真正的原生调用:保留它的全部校验与事件链(0.2.2 批量签名)。
242
- const nested = buildNestedCall(exec, resolved.args);
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)}`);
225
+ const resolved = resolveDelegationArgs(args, mode, executor, modelGroups);
226
+ if (!resolved.ok) {
227
+ throw new Error(classifyExplicitRoute(args).kind === 'invalid'
228
+ ? 'To select a model, provide both its provider and model.'
229
+ : 'Choose an execution model in the plugin settings or run the setup tool.');
249
230
  }
250
231
 
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
- }
258
-
259
- // ⑤ inner.isError 必须**抛出**:body 返回 error 对象会被当成功 value(见文件头契约 3)。
260
- if (inner.isError === true) {
261
- throw new Error(describeInnerFailure(inner));
232
+ const childRoute = resolved.applied === 'inherit' ? route : resolved.args;
233
+ const childKey = routeKey(childRoute);
234
+ const explicitExpert = resolved.applied === 'explicit' && experts.some(expert => routeKey(expert) === childKey);
235
+ const isExecutor = modelGroups ? modelGroups.executors.some(model => routeKey(model) === childKey)
236
+ : childKey === routeKey(executor);
237
+ const tier = explicitExpert ? 'expert' : isExecutor ? 'executor' : undefined;
238
+ let ticket;
239
+ try { ticket = watchdog?.begin(resolved.args, childRoute, tier, exec); }
240
+ catch { logger?.warn?.('dsh-submodel: monitoring could not start'); }
241
+ let receipt;
242
+ try {
243
+ const nested = buildNestedCall(exec, ticket?.args ?? resolved.args);
244
+ let batch;
245
+ try { batch = await ctx.tools.execute(nested); }
246
+ catch {
247
+ throw new Error('Delegation could not start. Check the subagent panel before trying again.');
248
+ }
249
+ const inner = resultOfNestedCall(batch, nested.calls[0].id);
250
+ if (inner === undefined) {
251
+ throw new Error('Delegation returned no confirmation. Check the subagent panel before trying again.');
252
+ }
253
+ if (inner.isError === true) {
254
+ if (describeInnerFailure(inner).includes('is not allowed for this Session')) {
255
+ throw new Error('This model is not allowed for the current conversation. Check the subagent settings and start a new conversation.');
256
+ }
257
+ throw new Error('Delegation was refused. Check model availability and permission in the subagent settings.');
258
+ }
259
+ receipt = inner.value;
260
+ for (const context of inner.additionalContexts ?? []) exec.deferContext(context);
261
+ if (inner.concludesTurn === true) exec.concludeTurn();
262
+ return receipt;
263
+ } finally {
264
+ try { watchdog?.finish(ticket, receipt); }
265
+ catch { logger?.warn?.('dsh-submodel: monitoring could not confirm the start'); }
262
266
  }
263
-
264
- // ⑥ 转移延迟上下文 / 结论标记,再只返回 inner.value。
265
- for (const context of inner.additionalContexts ?? []) exec.deferContext(context);
266
- if (inner.concludesTurn === true) exec.concludeTurn();
267
-
268
- return inner.value;
269
267
  },
270
268
  };
271
269
  }
package/lib/index.js CHANGED
@@ -38,7 +38,9 @@
38
38
  *
39
39
  * @module dsh-submodel
40
40
  */
41
- import z from '@deepseek-ai/schemastery';
41
+ import { executorConfigured, routingSnapshot } from './config.js';
42
+ export { Config } from './config.js';
43
+ import { installWatchdog } from './watchdog.js';
42
44
  import {
43
45
  CHILD_FORBIDDEN_TOOLS,
44
46
  ROUTING_ORDER,
@@ -58,64 +60,6 @@ export const name = 'dsh-submodel';
58
60
  /** 用到的服务必须列全:apply 会等到它们可用才执行。 */
59
61
  export const inject = ['tools', 'systemPrompt'];
60
62
 
61
- export const Config = z.object({
62
- /** 自动策略总开关。默认开启:公开版的目标就是"装上一次配好"。 */
63
- enabled: z.boolean().default(true),
64
- /** 只对这一个 composition 生效;其他 preset 不安装任何东西。 */
65
- preset: z.string().default('standard'),
66
- /** 团队队形自检单独启用,且服从自动策略总开关。 */
67
- teamFit: z.object({ enabled: z.boolean().default(false) }).default({ enabled: false }),
68
- /** 能力门控工具名:该 scope 不可见时策略段不渲染(工具仍按注册门控安装)。 */
69
- toolName: z.string().default('list_subagent_models'),
70
- /** 段顺序;默认紧接 TOOL_SUBAGENT(2800)。 */
71
- order: z.number().default(ROUTING_ORDER),
72
- /**
73
- * 执行路由(非 Flash 主脑的默认派工目标)。**唯一配置源**:执行期注入的 pair 由它派生,
74
- * 正文里的执行路由也只经占位符从它渲染,不允许 YAML/JS 双写两个不同的路由名。
75
- */
76
- executor: z.object({
77
- provider: z.string().default(''),
78
- model: z.string().default(''),
79
- reasoningEffort: z.string().default('max'),
80
- }).default({ provider: '', model: '', reasoningEffort: 'max' }),
81
- /**
82
- * 专家路由:升级时允许显式点名的 `{label, provider, model, reasoningEffort?}` 列表。
83
- * 空数组时正文给出"未配置专家路由"提示,不渲染任何具体路由名。
84
- */
85
- experts: z.array(z.object({
86
- label: z.string(),
87
- provider: z.string(),
88
- model: z.string(),
89
- reasoningEffort: z.string().default('max'),
90
- })).default([]),
91
- /**
92
- * 正文覆盖:任一项非空时**整段替换**内置模板(替换后不再插值),方便用户写自己的话术。
93
- */
94
- texts: z.object({
95
- economize: z.string().default(''),
96
- boss: z.string().default(''),
97
- child: z.string().default(''),
98
- }).default({ economize: '', boss: '', child: '' }),
99
- /**
100
- * 是否安装"非经济路由顶层用原生 subagent 时必须给完整显式 pair"的 guard。
101
- * 默认开启;关掉后原生 subagent 的行为完全交给宿主。
102
- */
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([]),
117
- });
118
-
119
63
  /** 判断一个 agent 是否属于本插件负责的 composition。 */
120
64
  function belongsToComposition(agent, presetId, presetService) {
121
65
  if (presetService === undefined) return false;
@@ -144,38 +88,11 @@ export function apply(ctx, config) {
144
88
  const presetId = config.preset ?? 'standard';
145
89
  const toolName = config.toolName ?? 'list_subagent_models';
146
90
  const order = config.order ?? ROUTING_ORDER;
147
- const executor = {
148
- provider: config.executor?.provider ?? '',
149
- model: config.executor?.model ?? '',
150
- reasoningEffort: config.executor?.reasoningEffort ?? 'max',
151
- };
152
- const experts = Array.isArray(config.experts) ? config.experts : [];
153
- const texts = {
154
- economize: config.texts?.economize ?? '',
155
- boss: config.texts?.boss ?? '',
156
- child: config.texts?.child ?? '',
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
- : [];
169
- const guardNativeSubagent = config.guardNativeSubagent !== false;
170
91
  const autoConfigure = config.autoConfigure !== false;
171
- /** 模式判定用的运行期策略(与 policy.js 纯函数同口径)。 */
172
- const routingPolicy = { executor, economyRoutes };
173
- /** 每次 assembly 现渲染正文用的运行期上下文(纯函数层只认它)。 */
174
- const renderContext = { executor, experts, texts, economyRoutes };
175
- /** 执行路由是否未配置(未配置时才注册自动配置向导)。 */
176
- const executorIncomplete = executor.provider === '' || executor.model === '';
92
+ ctx.inject?.(['settings'], (bound) => {
93
+ bound.effect(() => bound.settings.configure({ auto: false }, ctx.fiber));
94
+ });
177
95
 
178
- /** 每个 agent 的 assembly listener 装的文本解析器:`(resolved) => string|null`。 */
179
96
  const textResolvers = new WeakMap();
180
97
 
181
98
  // ── 全局唯一的段(只注册一次,绝不重复注册同名段) ─────────────────────────
@@ -222,17 +139,18 @@ export function apply(ctx, config) {
222
139
  }
223
140
 
224
141
  // ── fail-fast(只记日志、绝不抛) ──────────────────────────────────────────
225
- if (executorIncomplete) {
142
+ if (!executorConfigured(config)) {
226
143
  ctx.logger.error(
227
144
  'dsh-submodel: config.executor.provider/model 未配置,自动委派不可用;可调用 `configure_submodel` 自动配置或按 README 两步配置',
228
145
  );
229
146
  }
230
147
  ctx.logger.info(
231
- `dsh-submodel: 自动策略已启用(preset=${presetId}, executor=${executor.provider || '(未配置)'}/${executor.model || '(未配置)'}, experts=${experts.length})`,
148
+ 'dsh-submodel: automatic delegation policy enabled',
232
149
  );
233
150
 
234
151
  // ── 逐 agent 安装 ──────────────────────────────────────────────────────────
235
- const installed = new WeakMap();
152
+ const installed = new Map();
153
+ let closed = false;
236
154
  const installing = new WeakSet();
237
155
  const pendingInstalls = new WeakMap();
238
156
 
@@ -282,7 +200,7 @@ export function apply(ctx, config) {
282
200
  * 为 agent 安装自动能力。幂等:已装直接返回;正在装共用同一 Promise。
283
201
  */
284
202
  const installAgent = async (agent) => {
285
- if (installed.has(agent)) return;
203
+ if (closed || installed.has(agent)) return;
286
204
  const existing = pendingInstalls.get(agent);
287
205
  if (existing !== undefined) return existing;
288
206
  if (installing.has(agent)) return undefined;
@@ -314,6 +232,7 @@ export function apply(ctx, config) {
314
232
  // 角色只在安装时判定一次:它来自 durable session header,agent 生命周期内不变。
315
233
  // 改读 agent(而不是已作废的 EpochHeader)是为了修复"冷恢复子代永远判成 root"的缺陷。
316
234
  const callerRole = roleOf(agent);
235
+ const snapshot = routingSnapshot(config);
317
236
 
318
237
  // ① 角色 guard:子代硬边界。**返回字符串即拒绝**(不是抛异常)。
319
238
  const guard = (exec) => {
@@ -334,21 +253,21 @@ export function apply(ctx, config) {
334
253
  if (exec?.name !== 'subagent') return undefined;
335
254
  if (callerRole !== 'root') return undefined;
336
255
  // 执行期模式判定:取最新已接受 header 的 config,回退 agent.options。
337
- if (isEconomyRoute(routeFromAgent(agent), routingPolicy)) return undefined; // 经济路由顶层原生调用不改变行为
256
+ if (isEconomyRoute(routeFromAgent(agent), snapshot)) return undefined; // 经济路由顶层原生调用不改变行为
338
257
  const args = exec.arguments ?? {};
339
258
  const hasProvider = args.provider !== undefined && args.provider !== null && args.provider !== '';
340
259
  const hasModel = args.model !== undefined && args.model !== null && args.model !== '';
341
260
  if (hasProvider && hasModel) return undefined; // 完整显式 pair:放行
342
261
  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.';
343
262
  };
344
- if (guardNativeSubagent) disposers.push(tools.guard(nativeGuard));
263
+ if (snapshot.guardNativeSubagent) disposers.push(tools.guard(nativeGuard));
345
264
 
346
265
  // ③ assembly listener:先 await next(),再只替换自有段。
347
266
  const listener = async (assembly, context, next) => {
348
267
  const resolved = await next();
349
268
  try {
350
269
  const resolver = textResolvers.get(agent);
351
- const text = resolver === undefined ? null : resolver(resolved);
270
+ const text = resolver === undefined ? null : resolver(resolved, context.toolSet);
352
271
  if (text === null) return resolved;
353
272
  return {
354
273
  ...resolved,
@@ -367,30 +286,32 @@ export function apply(ctx, config) {
367
286
 
368
287
  // ④ 只有顶层注册统一委派入口(子代不再有委派能力)。
369
288
  if (callerRole === 'root') {
370
- disposers.push(
371
- tools.register(
372
- createDelegateTool({
373
- ctx: agent.ctx,
374
- nativeDefinition,
375
- executor,
376
- economyRoutes,
377
- logger: ctx.logger,
378
- }),
379
- ),
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 })));
289
+ const watchdog = installWatchdog({ ctx, parent: agent, config, nativeDefinition, modelGroups: snapshot.modelGroups });
290
+ if (watchdog) disposers.push(watchdog.dispose);
291
+ disposers.push(tools.register(createDelegateTool({
292
+ ctx: agent.ctx,
293
+ nativeDefinition,
294
+ executor: snapshot.executor,
295
+ experts: snapshot.experts,
296
+ modelGroups: snapshot.modelGroups,
297
+ economyRoutes: snapshot.economyRoutes,
298
+ watchdog,
299
+ logger: ctx.logger,
300
+ })));
301
+ if (autoConfigure) {
302
+ disposers.push(tools.register(createSetupTool({ ctx, config, logger: ctx.logger }), {
303
+ when: () => !executorConfigured(config),
304
+ }));
385
305
  }
386
306
  }
387
307
 
388
- // 正文解析器:角色安装时固定,模式每次 assembly 现判。
389
- // `list_subagent_models` 不可见时**只门控正文段**(info 一次/agent),
390
- // 工具仍按上面的注册门控安装。
391
- textResolvers.set(agent, (resolved) => {
308
+ textResolvers.set(agent, (resolved, toolSet) => {
309
+ const visibleTools = toolSet === undefined ? [] : [
310
+ 'list_agents', 'send_message', 'wait_agent', 'interrupt_agent', 'list_subagent_models',
311
+ ].filter(name => ctx.tools.get(name, agent, toolSet) !== undefined);
312
+ const renderContext = { ...snapshot, visibleTools };
392
313
  if (callerRole === 'child') return routingTextFor('child', undefined, renderContext);
393
- if (ctx.tools.get(toolName, agent) === undefined) {
314
+ if (ctx.tools.get(toolName, agent, toolSet) === undefined) {
394
315
  if (!informedNoModelSelection.has(agent)) {
395
316
  informedNoModelSelection.add(agent);
396
317
  ctx.logger.info(
@@ -474,24 +395,14 @@ export function apply(ctx, config) {
474
395
  });
475
396
  reconcile();
476
397
 
477
- // 根插件 cleanup:等自有安装全部卸载,再删状态。
478
- //
479
- // cordis 的插件拆卸通知是 `internal/plugin` 事件,listener 的 Promise 是 fire-and-forget;
480
- // 并没有名为 `dispose` 的事件被发射——因此原来的 `ctx.on('dispose', …)` 清理回调**永不执行**。
481
- // 两个通道都保留——谁先来谁触发,幂等。
398
+ let uninstallAllTask;
482
399
  const cleanupAll = () => {
483
- if (uninstallAllTask !== undefined) return uninstallAllTask;
484
- const agents = agentsService();
485
- if (agents === undefined) return undefined;
486
- const tasks = [];
487
- for (const candidate of agents.list()) {
488
- tasks.push(uninstallAgent(candidate, 'plugin cleanup'));
489
- textResolvers.delete(candidate);
490
- }
491
- uninstallAllTask = Promise.all(tasks).finally(() => { uninstallAllTask = undefined; });
400
+ if (closed) return uninstallAllTask;
401
+ closed = true;
402
+ uninstallAllTask = Promise.all([...installed.keys()].map(agent => uninstallAgent(agent, 'plugin cleanup')));
492
403
  return uninstallAllTask;
493
404
  };
494
- let uninstallAllTask;
405
+ ctx.effect?.(() => cleanupAll);
495
406
  ctx.on('dispose', cleanupAll);
496
407
  ctx.on('internal/plugin', (fiber) => {
497
408
  // 只在"自己这条 fiber 被拆掉"的那一刻触发(该事件正是 emitPluginDisposed 的载荷)。