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
|
@@ -0,0 +1,271 @@
|
|
|
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
|
+
* (0.2.2:`dsh-tool-subagent/lib/index.js` 的 `subagent` 工具定义里,`execute(args, exec)`
|
|
9
|
+
* 先读 policy、再 assert 允许路由、再 preflight、最后才 `ctx.subagents.startActivation(...)`)。
|
|
10
|
+
* 绕过它去 `subagents.startActivation(...)` 就等于同时绕过授权与预检——那正是本模块**不能**做的事。
|
|
11
|
+
*
|
|
12
|
+
* 所以本工具只做两件事:**改参数** + **经公开 `ctx.tools.execute` 发起一次真正的原生调用**。
|
|
13
|
+
*
|
|
14
|
+
* ## 0.2.2 的四个契约(都已在本机安装版源码确认,别按 0.2.1 的记忆改)
|
|
15
|
+
*
|
|
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 它。
|
|
30
|
+
*
|
|
31
|
+
* @module dsh-submodel/delegation
|
|
32
|
+
*/
|
|
33
|
+
import {
|
|
34
|
+
DELEGATE_TOOL_NAME,
|
|
35
|
+
modeForRoute,
|
|
36
|
+
resolveCallerRole,
|
|
37
|
+
resolveDelegationArgs,
|
|
38
|
+
} from './policy.js';
|
|
39
|
+
|
|
40
|
+
/** 子调用 callId 的后缀:既能被日志一眼认出,又不会和原生 callId 撞(原生用随机 id)。 */
|
|
41
|
+
const NESTED_CALL_SUFFIX = ':delegate';
|
|
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
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 从原生 `subagent` 的工具定义深拷贝参数 schema。
|
|
56
|
+
*
|
|
57
|
+
* **必须是"每次安装时从本轮 native 定义取"**,不能把 schema 写死在源码里:native 定义
|
|
58
|
+
* 会随 DSH 升级增删参数,写死就等于把新参数悄悄丢掉。`parameters` 是结构化 JSON Schema
|
|
59
|
+
* (普通对象),可安全深拷贝。
|
|
60
|
+
*
|
|
61
|
+
* @param nativeDefinition - 本会话可见的原生 subagent 工具定义。
|
|
62
|
+
* @returns 参数 schema 深拷贝。
|
|
63
|
+
*/
|
|
64
|
+
export function cloneNativeParameters(nativeDefinition) {
|
|
65
|
+
const parameters = nativeDefinition?.parameters;
|
|
66
|
+
if (parameters === undefined || parameters === null || typeof parameters !== 'object') {
|
|
67
|
+
throw new Error('delegate_task: the native `subagent` definition exposes no parameters to clone');
|
|
68
|
+
}
|
|
69
|
+
return structuredClone(parameters);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 检查本会话是否具备"能选模的委派能力":原生 subagent 可见 + 参数里真的有 provider/model。
|
|
74
|
+
* 缺任一项就不装 `delegate_task`——装了也是个只会失败的入口。
|
|
75
|
+
*
|
|
76
|
+
* **判据读 `parameters.properties`,不是 `parameters` 顶层**:宿主 `defineTool` 交付的是
|
|
77
|
+
* JSON Schema(`{type:'object', properties:{…}, required:[…]}`)。2026-10-05 真实宿主实测:
|
|
78
|
+
* `hasTopLevelProvider=false` / `hasPropertiesProvider=true`;读顶层会恒为 false,于是本函数
|
|
79
|
+
* 永远返回 undefined、整条安装路径静默跳过(四个工具一个都不出现)。
|
|
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
|
+
*
|
|
86
|
+
* @param tools - 工具注册表(ctx.tools)。
|
|
87
|
+
* @param scope - 观看作用域:**传 agent 对象本身**。宿主自己的调用范式就是这样
|
|
88
|
+
* (`dsh-tool-subagent/lib/index.js` 的系统提示段也写 `ctx.tools.get(tool.name, context.scope)`)。
|
|
89
|
+
* @returns 原生定义或 undefined。
|
|
90
|
+
*/
|
|
91
|
+
export function findNativeSubagent(tools, scope) {
|
|
92
|
+
const definition = tools.get?.(NESTED_TOOL_NAME, scope);
|
|
93
|
+
if (definition === undefined) return undefined;
|
|
94
|
+
const properties = definition.parameters?.properties;
|
|
95
|
+
const hasRouteParams = properties?.provider !== undefined && properties?.model !== undefined;
|
|
96
|
+
return hasRouteParams ? definition : undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 组装嵌套调用要用的批量输入。**纯计算**,便于单测。
|
|
101
|
+
*
|
|
102
|
+
* 0.2.2 只认批量形状:`calls[].arguments` 是 JSON 文本,返回结果按 `callId` 对回。
|
|
103
|
+
* `toolSet` 只在存在时透传(与当前步的准入集一致;`toolSet.view(scope)` 在 scope 不匹配时
|
|
104
|
+
* 返回空 Map,所以 `agent` 必须是本步 resolve 时的同一个 agent 对象)。
|
|
105
|
+
*
|
|
106
|
+
* @param outerExec - 外层(delegate_task 自己的)exec。
|
|
107
|
+
* @param newArgs - 已解析好的子代参数。
|
|
108
|
+
* @returns `ToolBatchInput` 片段(可直接交给 `ctx.tools.execute`)。
|
|
109
|
+
*/
|
|
110
|
+
export function buildNestedCall(outerExec, newArgs) {
|
|
111
|
+
return {
|
|
112
|
+
calls: [
|
|
113
|
+
{
|
|
114
|
+
id: `${outerExec.callId}${NESTED_CALL_SUFFIX}`,
|
|
115
|
+
name: NESTED_TOOL_NAME,
|
|
116
|
+
arguments: JSON.stringify(newArgs),
|
|
117
|
+
},
|
|
118
|
+
],
|
|
119
|
+
agent: outerExec.agent,
|
|
120
|
+
signal: outerExec.signal,
|
|
121
|
+
...(outerExec.toolSet === undefined ? {} : { toolSet: outerExec.toolSet }),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
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
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 把子的失败结果转成一段**可读诊断**(保留原始信息,不吞)。
|
|
139
|
+
* @param inner - 原生调用返回的结果快照。
|
|
140
|
+
* @returns 错误文本。
|
|
141
|
+
*/
|
|
142
|
+
export function describeInnerFailure(inner) {
|
|
143
|
+
const parts = [];
|
|
144
|
+
const message = inner?.error?.message;
|
|
145
|
+
if (typeof message === 'string' && message !== '') parts.push(message);
|
|
146
|
+
const info = inner?.error?.info;
|
|
147
|
+
if (info !== undefined && info !== null) {
|
|
148
|
+
try {
|
|
149
|
+
parts.push(typeof info === 'string' ? info : JSON.stringify(info));
|
|
150
|
+
} catch {
|
|
151
|
+
parts.push('[unserializable error.info]');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const content = Array.isArray(inner?.content) ? inner.content : [];
|
|
155
|
+
for (const block of content) {
|
|
156
|
+
if (block?.type === 'text' && typeof block.text === 'string' && block.text !== '') parts.push(block.text);
|
|
157
|
+
}
|
|
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
|
+
}
|
|
182
|
+
return parts.join('\n');
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* 创建 `delegate_task` 的工具定义。
|
|
187
|
+
*
|
|
188
|
+
* @param options - 依赖注入(全部来自 live agent 的 scope):
|
|
189
|
+
* - `ctx`:该 agent 的 runtime context(提供 tools)
|
|
190
|
+
* - `nativeDefinition`:本轮原生 subagent 定义(参数与 output 的来源)
|
|
191
|
+
* - `executor`:配置的执行路由 `{provider, model, reasoningEffort}`
|
|
192
|
+
* - `economyRoutes`:配置的经济路由列表(执行期模式判定用)
|
|
193
|
+
* - `logger`:日志器
|
|
194
|
+
* @returns 可直接 `ctx.tools.register(...)` 的工具定义。
|
|
195
|
+
*/
|
|
196
|
+
export function createDelegateTool({ ctx, nativeDefinition, executor, economyRoutes = [], logger }) {
|
|
197
|
+
/** 执行期模式判定用的运行期策略(与 policy.js 纯函数同口径)。 */
|
|
198
|
+
const routingPolicy = { executor, economyRoutes: Array.isArray(economyRoutes) ? economyRoutes : [] };
|
|
199
|
+
const parameters = cloneNativeParameters(nativeDefinition);
|
|
200
|
+
// output 同样复用原生 schema/render,保持 runId/agentId 与 foreground/continuable 格式一致。
|
|
201
|
+
const output = nativeDefinition.output;
|
|
202
|
+
if (output === undefined || output === null) {
|
|
203
|
+
throw new Error('delegate_task: the native `subagent` definition exposes no output contract to reuse');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
name: DELEGATE_TOOL_NAME,
|
|
208
|
+
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.',
|
|
215
|
+
parameters,
|
|
216
|
+
output,
|
|
217
|
+
async execute(args, exec) {
|
|
218
|
+
// ① 调用方身份必须是 live Agent,且必须是合格 standard 顶层。
|
|
219
|
+
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}")`);
|
|
222
|
+
|
|
223
|
+
// ② 同步快照执行期模式,再 await:描述"当前发起这笔调用的主脑",
|
|
224
|
+
// 不读 GUI 里可能中途变化的 pending selection。
|
|
225
|
+
const accepted = caller.header?.config ?? caller.agent.options ?? {};
|
|
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);
|
|
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)}`);
|
|
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
|
+
}
|
|
258
|
+
|
|
259
|
+
// ⑤ inner.isError 必须**抛出**:body 返回 error 对象会被当成功 value(见文件头契约 3)。
|
|
260
|
+
if (inner.isError === true) {
|
|
261
|
+
throw new Error(describeInnerFailure(inner));
|
|
262
|
+
}
|
|
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
|
+
},
|
|
270
|
+
};
|
|
271
|
+
}
|