dsh-plugin-tool-management 0.22.3 → 0.22.5
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/CHANGELOG.md +1415 -1363
- package/README.md +177 -176
- package/README_EN.md +177 -176
- package/docs/ARCHITECTURE.md +134 -0
- package/docs/COMPATIBILITY.md +107 -0
- package/docs/TROUBLESHOOTING.md +285 -0
- package/docs/UPDATE.md +50 -48
- package/lib/client.js +4693 -4626
- package/lib/compat/host-contracts.js +4 -2
- package/lib/confirm-gate.js +49 -18
- package/lib/context-inject-surface.js +45 -13
- package/lib/context-inject.js +1 -1
- package/lib/imports/unzip.js +144 -26
- package/lib/index.js +245 -93
- package/lib/legacy-tool-names.js +46 -0
- package/lib/mcp/manager.js +12 -1
- package/lib/mcp/secret-guard.js +27 -0
- package/lib/mcp/state-section.js +17 -8
- package/lib/mcp/tool-visibility.js +86 -10
- package/lib/memories/archive.js +44 -0
- package/lib/memories/index-io.js +4 -1
- package/lib/memories/service.js +94 -3
- package/lib/op-registry.js +5 -1
- package/lib/ops/scene-capture.js +72 -0
- package/lib/prompts/service.js +27 -0
- package/lib/scope/scope-overrides.js +9 -2
- package/lib/skills/catalog.js +18 -9
- package/lib/skills/dir-watch.js +49 -22
- package/lib/skills/service.js +2 -2
- package/lib/subagents/catalog.js +13 -7
- package/lib/subagents/run-provider.js +41 -10
- package/lib/subagents/tools.js +63 -7
- package/lib/tool-table-switch.js +41 -4
- package/lib/tools/control.js +158 -0
- package/lib/tools/deps.js +88 -0
- package/lib/tools/mcp.js +35 -10
- package/lib/tools/memory.js +9 -5
- package/lib/tools/prompt.js +7 -8
- package/lib/tools/remove.js +84 -65
- package/lib/tools/scene.js +179 -76
- package/lib/tools/skills.js +13 -8
- package/lib/tools/subagent.js +19 -10
- package/lib/tools/table.js +92 -57
- package/lib/trash-id.js +3 -2
- package/package.json +156 -152
package/lib/prompts/service.js
CHANGED
|
@@ -37,6 +37,21 @@ const META_FILE = 'meta.json';
|
|
|
37
37
|
* 一句用户提示"),但那是两个各自独立的预算,别当成同一个常量共用。
|
|
38
38
|
*/
|
|
39
39
|
export const DEFAULT_PRESET_DESC_MAX_LENGTH = 300;
|
|
40
|
+
/**
|
|
41
|
+
* 预设正文的字节上限(256 KiB),与记忆正文的 `MAX_RULE_BYTES` 同档。
|
|
42
|
+
*
|
|
43
|
+
* 为什么需要:注入侧虽按 64 KiB 截断(`AGENTS_MD_MAX_BYTES`),但盘上可以无限大,
|
|
44
|
+
* 而每次读都要整份进内存。上限拦在**写**这一侧 —— 已存在的超大文件不阻断读取,
|
|
45
|
+
* 用户还能把它改小。
|
|
46
|
+
*/
|
|
47
|
+
export const MAX_PRESET_BYTES = 256 * 1024;
|
|
48
|
+
/** 正文超限时的拒绝回执;没超返回 null。 */
|
|
49
|
+
function presetTooLarge(content) {
|
|
50
|
+
const bytes = Buffer.byteLength(String(content ?? ''), 'utf8');
|
|
51
|
+
if (bytes <= MAX_PRESET_BYTES)
|
|
52
|
+
return null;
|
|
53
|
+
return { ok: false, error: `提示词正文过大(${bytes} 字节,上限 ${MAX_PRESET_BYTES >> 10} KiB)` };
|
|
54
|
+
}
|
|
40
55
|
/**
|
|
41
56
|
* 压成一行并按上限截断。与 `normalizeMcpNote`(`../mcp/state-section.ts`)同形:两处都是
|
|
42
57
|
* "给模型看的一句用户文字",口径必须一致,否则同一句在界面、段、工具里会是三个样子。
|
|
@@ -243,6 +258,10 @@ export function createPromptsService(_ctx, deps) {
|
|
|
243
258
|
content = BLANK_TEMPLATE;
|
|
244
259
|
}
|
|
245
260
|
}
|
|
261
|
+
// 判在 mkdir 之前:拒绝时磁盘上不留空目录。
|
|
262
|
+
const tooLarge = presetTooLarge(content);
|
|
263
|
+
if (tooLarge)
|
|
264
|
+
return tooLarge;
|
|
246
265
|
await mkdir(dir, { recursive: true });
|
|
247
266
|
await writeFileAtomically(join(dir, FILENAME), content);
|
|
248
267
|
await writeDescription(safeId, options?.description);
|
|
@@ -256,6 +275,10 @@ export function createPromptsService(_ctx, deps) {
|
|
|
256
275
|
const bad = idError(id);
|
|
257
276
|
if (bad)
|
|
258
277
|
return { ok: false, error: '非法 id:' + bad };
|
|
278
|
+
// 判在任何落盘之前:否则改名会先发生,正文却被拒,目录停在新 id 上。
|
|
279
|
+
const tooLarge = presetTooLarge(content);
|
|
280
|
+
if (tooLarge)
|
|
281
|
+
return tooLarge;
|
|
259
282
|
const safeId = String(id ?? '').trim();
|
|
260
283
|
const dir = join(deps.presetsDir, safeId);
|
|
261
284
|
try {
|
|
@@ -636,6 +659,10 @@ export function createPromptsService(_ctx, deps) {
|
|
|
636
659
|
return { ok: false, error: 'id 已存在:' + safeId };
|
|
637
660
|
}
|
|
638
661
|
catch { /* 不存在,继续 */ }
|
|
662
|
+
// 判在 mkdir 之前:拒绝时磁盘上不留空目录。
|
|
663
|
+
const tooLarge = presetTooLarge(content);
|
|
664
|
+
if (tooLarge)
|
|
665
|
+
return tooLarge;
|
|
639
666
|
await mkdir(dir, { recursive: true });
|
|
640
667
|
await writeFileAtomically(join(dir, FILENAME), String(content ?? ''));
|
|
641
668
|
await writeDescription(safeId, description);
|
|
@@ -46,6 +46,7 @@
|
|
|
46
46
|
// 本来就是这个形状,拆成一格一覆盖只会多出第二份真相。取数顺序也不同 ——
|
|
47
47
|
// 本对话那份 → 创建时抄的基线 → 实时全局(老会话的兜底),全局只给新对话当默认模板。
|
|
48
48
|
// 场景绑定的方案在**进入那一次**套到本对话(不是常驻的一层),退出时连场景里改的一起清掉。
|
|
49
|
+
import { translateLegacyToolName } from '../legacy-tool-names.js';
|
|
49
50
|
import { normalizePresetId } from '../prompts/preset-id.js';
|
|
50
51
|
/** 布尔型覆盖域:一个域一张 `key → 开/关` 表。 */
|
|
51
52
|
export const SCOPE_FLAG_DOMAINS = ['skills', 'subagents', 'memory', 'quickPrompts', 'mcp', 'mcpTools', 'skillSources'];
|
|
@@ -140,6 +141,11 @@ export function normalizeScopeOverrides(raw) {
|
|
|
140
141
|
/**
|
|
141
142
|
* 夹一份工具名名单。与 `normalizeFlagMap` 不同,**空数组是有效值**("一个都不关"),
|
|
142
143
|
* 只有"不是数组"才返回 undefined(这一层没话说)。
|
|
144
|
+
*
|
|
145
|
+
* 顺手做**旧名 → 新名**的翻译(`translateLegacyToolName`):这份名单是整份工具表的快照,
|
|
146
|
+
* 盘上可能留着改名前的名字 —— 而这一层是**整份替换**全局名单的,不翻译的话,
|
|
147
|
+
* 升级后老会话里的那份旧名单会把已经并成一条的新工具漏出去(新的那条照旧每轮发)。
|
|
148
|
+
* 翻译在这一层做(而不是只在全局侧车那侧)是因为会话侧车与场景快照各有各的盘。
|
|
143
149
|
*/
|
|
144
150
|
function normalizeToolNameList(raw) {
|
|
145
151
|
if (!Array.isArray(raw))
|
|
@@ -148,8 +154,9 @@ function normalizeToolNameList(raw) {
|
|
|
148
154
|
for (const item of raw) {
|
|
149
155
|
if (!validKey(item))
|
|
150
156
|
continue;
|
|
151
|
-
|
|
152
|
-
|
|
157
|
+
const name = translateLegacyToolName(String(item));
|
|
158
|
+
if (out.indexOf(name) < 0)
|
|
159
|
+
out.push(name);
|
|
153
160
|
}
|
|
154
161
|
return out;
|
|
155
162
|
}
|
package/lib/skills/catalog.js
CHANGED
|
@@ -55,7 +55,13 @@ export function renderSkillCatalog(data, maxEntries = SKILL_CATALOG_MAX_ENTRIES,
|
|
|
55
55
|
* 结果,一次扫描服务所有会话;按会话过滤只是"这一份清单里哪些该出现",纯字符串运算。
|
|
56
56
|
* 反过来把会话塞进 `state()` 就得为每个会话各扫一遍磁盘。
|
|
57
57
|
*/
|
|
58
|
-
layer
|
|
58
|
+
layer,
|
|
59
|
+
/**
|
|
60
|
+
* 控制面工具(`tool_manager_tools`)在这个 agent 手里吗:截断尾句的中间档出口。
|
|
61
|
+
* 与 `listToolVisible` 同一判据来源(按 agent);缺席时按"在手里"算,
|
|
62
|
+
* 与 `listToolVisible` 的缺省口径一致 —— 它出厂常驻,且模型自己关不掉它。
|
|
63
|
+
*/
|
|
64
|
+
controlVisible = true) {
|
|
59
65
|
const roots = (data && typeof data === 'object' ? data.roots : undefined) ?? [];
|
|
60
66
|
const byName = new Map();
|
|
61
67
|
if (Array.isArray(roots)) {
|
|
@@ -115,13 +121,15 @@ layer) {
|
|
|
115
121
|
// 占一行。空行把它断成独立段落。
|
|
116
122
|
const enveloped = ['<available_skills>', '', ...out, '', '</available_skills>'];
|
|
117
123
|
if (hidden > 0) {
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
//
|
|
124
|
+
// 截断尾句三档:清单工具在手 → 点名它;不在手但控制面工具在(出厂常驻、模型关不掉
|
|
125
|
+
// 自己的回头路)→ 指自举;两者都关(面板动了手)→ 才指向用户。被截掉的部分不能在
|
|
126
|
+
// 模型看来"不存在",数量照报 —— 那是实话。中间档必须带上清单工具的名字:
|
|
127
|
+
// 模型手里没有它,光说"listing tool"它连要开哪条都不知道。
|
|
122
128
|
enveloped.push('', listToolVisible
|
|
123
129
|
? `(${hidden} more not listed — see them with \`skill_manager_list\`.)`
|
|
124
|
-
:
|
|
130
|
+
: controlVisible
|
|
131
|
+
? `(${hidden} more not listed — \`skill_manager_list\` is disabled in this session; enable it with \`tool_manager_tools\` to see them.)`
|
|
132
|
+
: `(${hidden} more not listed — \`skill_manager_list\` is disabled in this session; ask the user to enable it.)`);
|
|
125
133
|
}
|
|
126
134
|
return enveloped.join('\n');
|
|
127
135
|
}
|
|
@@ -280,6 +288,7 @@ export function createSkillCatalog(deps, opts = {}) {
|
|
|
280
288
|
void revalidate(key);
|
|
281
289
|
touch(key);
|
|
282
290
|
const visible = deps.listToolVisible ? deps.listToolVisible(agent) : true;
|
|
291
|
+
const control = deps.controlVisible ? deps.controlVisible(agent) : true;
|
|
283
292
|
const layer = deps.layerFor ? deps.layerFor(agent) : undefined;
|
|
284
293
|
// 上限每次渲染现取(设置有 TTL 缓存,这里只是转发);缺省回落厂值。
|
|
285
294
|
const maxEntries = resolveCap(opts.maxEntries) ?? SKILL_CATALOG_MAX_ENTRIES;
|
|
@@ -288,11 +297,11 @@ export function createSkillCatalog(deps, opts = {}) {
|
|
|
288
297
|
// 也不拿 A 的目录糊弄 B。
|
|
289
298
|
const layerKey = deps.layerKeyFor ? deps.layerKeyFor(agent) : '';
|
|
290
299
|
const cacheable = layer === undefined || deps.layerKeyFor !== undefined;
|
|
291
|
-
//
|
|
292
|
-
const keyOfRender = key + '\u0000' + maxEntries + '\u0000' + maxDescription + '\u0000' + (visible ? '1' : '0') + '\u0000' + layerKey;
|
|
300
|
+
// 缓存键必须带上两个上限与两档可见性:改了设置/开关而键没变的话,渲染缓存会一直发旧文本。
|
|
301
|
+
const keyOfRender = key + '\u0000' + maxEntries + '\u0000' + maxDescription + '\u0000' + (visible ? '1' : '0') + (control ? '1' : '0') + '\u0000' + layerKey;
|
|
293
302
|
if (cacheable && rendered && rendered.key === keyOfRender)
|
|
294
303
|
return rendered.text;
|
|
295
|
-
const out = renderSkillCatalog(hit.data, maxEntries, maxDescription, visible, layer);
|
|
304
|
+
const out = renderSkillCatalog(hit.data, maxEntries, maxDescription, visible, layer, control);
|
|
296
305
|
if (cacheable)
|
|
297
306
|
rendered = { key: keyOfRender, text: out };
|
|
298
307
|
return out;
|
package/lib/skills/dir-watch.js
CHANGED
|
@@ -4,21 +4,24 @@
|
|
|
4
4
|
// 写在它自己的注释里 —— Windows 上那条路会在目录被删除时静默卡死事件循环。
|
|
5
5
|
import { existsSync } from 'node:fs';
|
|
6
6
|
import { Worker } from 'node:worker_threads';
|
|
7
|
-
// ── 文件监听:外部改动自动失效 ────────────────────────────────────────────
|
|
8
7
|
/**
|
|
9
8
|
* 监听目录,200ms 防抖后回调:在编辑器或其他工具里新增/修改/删除文件后,无需手动
|
|
10
|
-
*
|
|
9
|
+
* 刷新即可看到变化。技能来源与记忆根目录共用。
|
|
11
10
|
*
|
|
12
11
|
* 为什么用 worker_threads:Windows 上 fs.watch(recursive) 的句柄在「被监听
|
|
13
12
|
* 目录被删除」时会静默卡死事件循环(不触发 error、unref 也无效)——宿主
|
|
14
13
|
* 进程将永远无法退出。把 watcher 放进独立的 worker 线程,主线程对 worker
|
|
15
14
|
* unref(),无论目录发生什么,宿主与测试进程都能正常收尾;worker 内部失败
|
|
16
|
-
*
|
|
15
|
+
* 也不影响主线程。目录不存在或平台不支持递归监听时静默跳过(`attached: false`)。
|
|
16
|
+
*
|
|
17
|
+
* 已知边界:worker 崩溃或某个目录监听失败**不会**回报(它只是少了一条变化通知)。
|
|
18
|
+
* 所以依赖 `attached` 做缓存的调用方必须再叠一层 TTL —— 把"监听还在"当成前提,
|
|
19
|
+
* 静默失效就会变成永久返回旧内容。
|
|
17
20
|
*/
|
|
18
21
|
export function watchDirectories(paths, invalidate) {
|
|
19
22
|
const valid = paths.filter((dir) => dir && existsSync(dir));
|
|
20
23
|
if (!valid.length)
|
|
21
|
-
return () => { };
|
|
24
|
+
return { dispose: () => { }, attached: () => false };
|
|
22
25
|
let timer = null;
|
|
23
26
|
const fire = () => {
|
|
24
27
|
if (timer)
|
|
@@ -32,40 +35,64 @@ export function watchDirectories(paths, invalidate) {
|
|
|
32
35
|
}, 200);
|
|
33
36
|
};
|
|
34
37
|
let worker = null;
|
|
38
|
+
let attached = false;
|
|
35
39
|
try {
|
|
36
40
|
// eval 模式内联 worker 代码:无需额外文件与构建步骤。worker 事件循环独立,
|
|
37
41
|
// 主线程 unref 后完全不参与宿主进程的退出判定。
|
|
38
42
|
const src = `
|
|
39
43
|
const { watch } = require('node:fs');
|
|
40
44
|
const { parentPort, workerData } = require('node:worker_threads');
|
|
45
|
+
let live = 0;
|
|
41
46
|
for (const dir of workerData.paths) {
|
|
42
47
|
try {
|
|
43
|
-
|
|
48
|
+
// persistent: true 是必需的:worker 里若唯一的句柄是 non-persistent 的 watch,
|
|
49
|
+
// 事件循环当场空掉、worker 自己退出 —— 消息一条都收不到(实测)。不挡宿主退出
|
|
50
|
+
// 靠的是主线程对 worker 的 unref(),不是这里的 persistent。
|
|
51
|
+
const w = watch(dir, { recursive: true, persistent: true }, () => {
|
|
44
52
|
try { parentPort.postMessage('change') } catch { /* worker 正在关闭 */ }
|
|
45
53
|
});
|
|
46
54
|
w.on('error', () => { /* 目录被移除等:忽略,不向主线程传播 */ });
|
|
55
|
+
live += 1;
|
|
47
56
|
} catch { /* 不可监听(权限/平台)时跳过该目录 */ }
|
|
48
57
|
}
|
|
58
|
+
parentPort.postMessage({ attached: live > 0 });
|
|
49
59
|
`;
|
|
50
|
-
|
|
60
|
+
// `execArgv: []` 是必需的,不是洁癖:worker 默认**继承**父进程的 execArgv,
|
|
61
|
+
// 而 eval 模式的代码是 CommonJS(用了 `require`)。父进程若带着 `--input-type=module`
|
|
62
|
+
// (`node -e` / 测试用 `--input-type` 跑),那段代码会被当成 ESM 求值,
|
|
63
|
+
// `require is not defined` —— 表现为"监听静默没挂上",而这里的所有失败都是静默的。
|
|
64
|
+
worker = new Worker(src, { eval: true, workerData: { paths: valid }, execArgv: [] });
|
|
51
65
|
worker.unref();
|
|
52
|
-
worker.on('message', () =>
|
|
53
|
-
|
|
66
|
+
worker.on('message', (msg) => {
|
|
67
|
+
if (msg && typeof msg === 'object' && 'attached' in msg) {
|
|
68
|
+
attached = msg.attached === true;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
fire();
|
|
72
|
+
});
|
|
73
|
+
// 崩溃 / 意外退出必须把 `attached` 降回 false:否则调用方会一直以为监听还挂着,
|
|
74
|
+
// 只靠 TTL 兜底,而重试逻辑(见记忆服务的 `ensureMemoriesWatch`)永远等不到复活机会。
|
|
75
|
+
// `dispose()` 先 `removeAllListeners()`,所以主动终止不会走到这里。
|
|
76
|
+
worker.on('error', () => { attached = false; });
|
|
77
|
+
worker.on('exit', () => { attached = false; });
|
|
54
78
|
}
|
|
55
|
-
catch { /* worker
|
|
56
|
-
return
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
timer
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
worker
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
79
|
+
catch { /* worker 不可用时静默跳过,功能退化为依赖调用方自己的 TTL */ }
|
|
80
|
+
return {
|
|
81
|
+
attached: () => attached,
|
|
82
|
+
dispose: () => {
|
|
83
|
+
if (timer) {
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
timer = null;
|
|
86
|
+
}
|
|
87
|
+
if (worker) {
|
|
88
|
+
const w = worker;
|
|
89
|
+
worker = null;
|
|
90
|
+
try {
|
|
91
|
+
w.removeAllListeners();
|
|
92
|
+
w.terminate();
|
|
93
|
+
}
|
|
94
|
+
catch { /* ignore */ }
|
|
67
95
|
}
|
|
68
|
-
|
|
69
|
-
}
|
|
96
|
+
},
|
|
70
97
|
};
|
|
71
98
|
}
|
package/lib/skills/service.js
CHANGED
|
@@ -332,7 +332,7 @@ export function createSkillsService(ctx, deps = {}) {
|
|
|
332
332
|
.filter((root) => root.key !== 'official')
|
|
333
333
|
.map((root) => String((root && root.path) || ''))
|
|
334
334
|
.filter(Boolean);
|
|
335
|
-
add(watchDirectories(watchPaths, invalidateSkills));
|
|
335
|
+
add(watchDirectories(watchPaths, invalidateSkills).dispose);
|
|
336
336
|
// 自定义目录在状态文件里,注册时读取一次并一并监听(后添加的目录由
|
|
337
337
|
// provider 首次 list 天然覆盖,等插件重载后才有 watcher)。
|
|
338
338
|
return readManagerState();
|
|
@@ -344,7 +344,7 @@ export function createSkillsService(ctx, deps = {}) {
|
|
|
344
344
|
.map((root) => String((root && root.path) || ''))
|
|
345
345
|
.filter(Boolean);
|
|
346
346
|
if (customPaths.length)
|
|
347
|
-
add(watchDirectories(customPaths, invalidateSkills));
|
|
347
|
+
add(watchDirectories(customPaths, invalidateSkills).dispose);
|
|
348
348
|
})
|
|
349
349
|
.catch((e) => {
|
|
350
350
|
console.error('[dsh-plugin-tool-management] skill watcher setup failed:', message(e));
|
package/lib/subagents/catalog.js
CHANGED
|
@@ -44,7 +44,9 @@ export function catalogDescription(value, maxLength) {
|
|
|
44
44
|
* (`- **名字** — 描述`),"这是什么 + 该拿它做什么"整句交给注入通道的引导语。于是这里
|
|
45
45
|
* 既没有标题也没有"可委派给下列子智能体"那句:一处内容只有一个出处。
|
|
46
46
|
*/
|
|
47
|
-
export function renderSubagentCatalog(allowed, maxEntries = DEFAULT_CATALOG_MAX_ENTRIES, maxDescription = DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH, listToolVisible = true
|
|
47
|
+
export function renderSubagentCatalog(allowed, maxEntries = DEFAULT_CATALOG_MAX_ENTRIES, maxDescription = DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH, listToolVisible = true,
|
|
48
|
+
/** 控制面工具在不在手里:截断尾句中间档(指自举)的前提。缺席按在手里算。 */
|
|
49
|
+
controlVisible = true) {
|
|
48
50
|
if (!allowed.length)
|
|
49
51
|
return '';
|
|
50
52
|
const sorted = [...allowed].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
@@ -60,11 +62,14 @@ export function renderSubagentCatalog(allowed, maxEntries = DEFAULT_CATALOG_MAX_
|
|
|
60
62
|
// 「确认一遍」去调它(没列出来的就是当前不想要的)。与 MCP 状态段的
|
|
61
63
|
// `(${N} more not listed.)` 同一句式,但这里多给一个出口——不给人设就真的找不回来了。
|
|
62
64
|
if (hidden > 0) {
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
+
// 与技能目录同一条三档纪律:清单工具在手 → 点名它;不在手但控制面工具在 → 指自举;
|
|
66
|
+
// 两者都关 → 才指向用户。中间档带上清单工具的名字 —— 模型手里没有它,
|
|
67
|
+
// 光说"listing tool"它连要开哪条都不知道。数量照报,那是实话。
|
|
65
68
|
out.push('', listToolVisible
|
|
66
69
|
? `(${hidden} more not listed — see them with \`subagent_manager_list\`.)`
|
|
67
|
-
:
|
|
70
|
+
: controlVisible
|
|
71
|
+
? `(${hidden} more not listed — \`subagent_manager_list\` is disabled in this session; enable it with \`tool_manager_tools\` to see them.)`
|
|
72
|
+
: `(${hidden} more not listed — \`subagent_manager_list\` is disabled in this session; ask the user to enable it.)`);
|
|
68
73
|
}
|
|
69
74
|
return out.join('\n');
|
|
70
75
|
}
|
|
@@ -136,6 +141,7 @@ export function createSubagentCatalog(deps, opts = {}) {
|
|
|
136
141
|
void revalidate();
|
|
137
142
|
const depth = subagentDepthOf(agent);
|
|
138
143
|
const visible = deps.listToolVisible ? deps.listToolVisible(agent) : true;
|
|
144
|
+
const control = deps.controlVisible ? deps.controlVisible(agent) : true;
|
|
139
145
|
// 上限每次渲染现取(设置有 TTL 缓存,这里只是转发);缺省回落厂值。
|
|
140
146
|
const maxEntries = resolveCap(opts.maxEntries) ?? maxEntriesDefault;
|
|
141
147
|
const maxDescription = resolveCap(opts.maxDescription) ?? maxDescriptionDefault;
|
|
@@ -143,14 +149,14 @@ export function createSubagentCatalog(deps, opts = {}) {
|
|
|
143
149
|
// 有会话层但装配层没给指纹(老装配 / 测试)时不走渲染缓存:宁可多算一次。
|
|
144
150
|
const cacheable = !hasLayer || deps.layerKeyFor !== undefined;
|
|
145
151
|
const layerKey = deps.layerKeyFor ? deps.layerKeyFor(agent) : '';
|
|
146
|
-
//
|
|
147
|
-
const key = layerKey + '\u0000' + depth + '|' + (visible ? '1' : '0') + '\u0000' + maxEntries + '\u0000' + maxDescription;
|
|
152
|
+
// 缓存键必须带上两个上限与两档可见性:改了设置/开关而键没变的话,渲染缓存会一直发旧文本。
|
|
153
|
+
const key = layerKey + '\u0000' + depth + '|' + (visible ? '1' : '0') + (control ? '1' : '0') + '\u0000' + maxEntries + '\u0000' + maxDescription;
|
|
148
154
|
if (cacheable) {
|
|
149
155
|
const cached = rendered.get(key);
|
|
150
156
|
if (cached !== undefined)
|
|
151
157
|
return cached;
|
|
152
158
|
}
|
|
153
|
-
const out = renderSubagentCatalog(listedFor(agent, depth), maxEntries, maxDescription, visible);
|
|
159
|
+
const out = renderSubagentCatalog(listedFor(agent, depth), maxEntries, maxDescription, visible, control);
|
|
154
160
|
if (cacheable)
|
|
155
161
|
rendered.set(key, out);
|
|
156
162
|
return out;
|
|
@@ -172,7 +172,14 @@ export function createRunProvider(deps) {
|
|
|
172
172
|
catch { /* effect 不可用 → 只影响清理,不影响本次委派 */ }
|
|
173
173
|
}
|
|
174
174
|
installChildPresetCleanup();
|
|
175
|
-
|
|
175
|
+
/**
|
|
176
|
+
* 一次委派的**启动**阶段:走到子代理跑起来为止,不等它跑完。
|
|
177
|
+
*
|
|
178
|
+
* 为什么要拆成两段:等待段(`activation.result`)是纯等待,而启动段会碰共享状态
|
|
179
|
+
* (provider 挂载、临时子预设的注册、官方 `startActivation`)。串行只该护住启动段 ——
|
|
180
|
+
* 整趟串行会让"同时派三个人设"退化成排队,而那正是并行派活要解决的问题。
|
|
181
|
+
*/
|
|
182
|
+
async function startRun(parentAgent, p, task, signal, toolFilter, inherit) {
|
|
176
183
|
// 这里**刻意没有**"预算用尽就拒绝"的前置检查:宿主统一决定委派深度
|
|
177
184
|
// (当前默认 maxDepth=1),本工具不传 maxDepth,也不自行判断能否继续委派。
|
|
178
185
|
//
|
|
@@ -308,8 +315,23 @@ export function createRunProvider(deps) {
|
|
|
308
315
|
throw new Error(`failed to apply the subagent tool restriction: ${restrictionFailure.message}`);
|
|
309
316
|
}
|
|
310
317
|
if (p.continuable === true) {
|
|
311
|
-
|
|
318
|
+
// 允许追问的子代理是**后台**跑的:产出不在这里,启动完就交回控制权。
|
|
319
|
+
// 这次激活不 dispose、临时预设也不释放 —— 追问要靠它们恢复(见 presetLeases 的注释)。
|
|
320
|
+
return { continuable: true, runId: String(activation.childId ?? '') };
|
|
312
321
|
}
|
|
322
|
+
return { continuable: false, activation, releasePreset };
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* 一次委派的**等待**阶段:等子代理跑完,取结果并收尾。
|
|
326
|
+
*
|
|
327
|
+
* 与启动段分开,是为了让多次委派的**等待**能重叠:等待是纯等待,不碰共享状态。
|
|
328
|
+
*/
|
|
329
|
+
async function finishRun(handle) {
|
|
330
|
+
if (handle.continuable === true) {
|
|
331
|
+
return { text: '', runId: handle.runId, stopReason: 'started', continuable: true };
|
|
332
|
+
}
|
|
333
|
+
const activation = handle.activation;
|
|
334
|
+
const releasePreset = handle.releasePreset;
|
|
313
335
|
try {
|
|
314
336
|
const result = await activation.result; // 官方契约:child 级失败不 reject(stopReason 体现)
|
|
315
337
|
// 只取 `text` 块(见 textOfBlocks)。此前这里只判了 `typeof b.text === 'string'`,
|
|
@@ -332,18 +354,27 @@ export function createRunProvider(deps) {
|
|
|
332
354
|
await releasePreset?.().catch(() => undefined);
|
|
333
355
|
}
|
|
334
356
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
357
|
+
/** 启动 + 等待走一遍(不重叠的那条路;并行通道见 runSerial)。 */
|
|
358
|
+
async function runOnce(parentAgent, p, task, signal, toolFilter, inherit) {
|
|
359
|
+
return finishRun(await startRun(parentAgent, p, task, signal, toolFilter, inherit));
|
|
360
|
+
}
|
|
361
|
+
// 启动串行、等待重叠:同一时刻至多一次**启动**在途,启动完之后子代理们各自跑各自的。
|
|
362
|
+
// ⚠️ 这条不等于"至多一个子代理在跑":允许追问(`continuable`)的子代理在 `startActivation()`
|
|
363
|
+
// 返回后仍在后台运行,而这里只串行化"启动"这一步。这是官方通道的固有语义(后台子级本来就
|
|
364
|
+
// 允许并存),不是本插件放宽了限制。
|
|
365
|
+
// 串行只护住启动段,是因为它会碰共享状态:provider 挂载(`ensureProvider` 的检查-执行不是
|
|
366
|
+
// 原子的)、临时子预设的注册(官方对重名直接报 `Duplicate agent preset`)、官方
|
|
367
|
+
// `startActivation`。等待段是纯等待,挂在链上只会让"同时派三个人设"退化成排队。
|
|
339
368
|
// `continuable: true` 的返回值是 `{ text: '', stopReason: 'started' }` —— 产出不在这里,
|
|
340
369
|
// 而由官方的结算通知在子代理结束时送到父代理(见 persona-types.ts 的 continuable 注释)。
|
|
341
370
|
let chain = Promise.resolve();
|
|
342
371
|
const runSerial = (parentAgent, p, task, signal, toolFilter, inherit) => {
|
|
343
|
-
const start = () =>
|
|
344
|
-
const
|
|
345
|
-
|
|
346
|
-
|
|
372
|
+
const start = () => startRun(parentAgent, p, task, signal, toolFilter, inherit);
|
|
373
|
+
const started = chain.then(start, start);
|
|
374
|
+
// 链上只挂**启动**这一段:等待不占链(否则并行批次里的第二个人设仍要排队等第一个跑完)。
|
|
375
|
+
// 失败不污染链:启动抛错与等待抛错都不该让后面的委派一起挂掉。
|
|
376
|
+
chain = started.then(() => undefined, () => undefined);
|
|
377
|
+
return started.then(finishRun);
|
|
347
378
|
};
|
|
348
379
|
return { PROVIDER_PACKAGES, providerMounts, hasProvider, ensureProvider, runOnce, runSerial };
|
|
349
380
|
}
|
package/lib/subagents/tools.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// defineTool() 编译后再 register —— 裸 register 会把未编译的参数声明直接发给模型 API。
|
|
4
4
|
// 参数与 output schema 用 as const 保留字面量类型,defineTool 才能推断出参数表。
|
|
5
5
|
import { CONTINUABLE_MARK } from './service.js';
|
|
6
|
+
import { listLimit, moreNotShown, toolAccessSentence } from '../tools/deps.js';
|
|
6
7
|
/** 把一段文本包成工具回执要的内容块数组(各工具域共用这一份形状)。 */
|
|
7
8
|
export function text(v) {
|
|
8
9
|
return [{ type: 'text', text: v }];
|
|
@@ -83,6 +84,7 @@ export function defineSubagentManagerListTool(subagents) {
|
|
|
83
84
|
description: 'List personas (pre-configured subagent profiles) with descriptions and the file holding each body (read it with your file tools). The "Current subagents" reminder carries a view of the same catalog; call this for the always-current full list, or all=true to include disabled personas and ones outside the active scene.',
|
|
84
85
|
parameters: {
|
|
85
86
|
all: { type: 'boolean', description: 'Include disabled personas and ones outside the active scene (default false). Listed ≠ delegable: `run` still refuses those.' },
|
|
87
|
+
limit: { type: 'number', description: 'Max entries (default 50, max 100).' },
|
|
86
88
|
},
|
|
87
89
|
output: {
|
|
88
90
|
schema: { type: 'string' },
|
|
@@ -117,9 +119,26 @@ export function defineSubagentManagerListTool(subagents) {
|
|
|
117
119
|
// 放在行尾而不是表头给一个目录模板:模型拼 `<dir>/<name>.md` 要多一步推理,路径里
|
|
118
120
|
// 有空格或非 ASCII 目录名时还可能拼错;每条一个完整路径是零歧义,代价只在调用时付
|
|
119
121
|
// (不是每轮的 schema 成本)。
|
|
120
|
-
|
|
122
|
+
// 返回体也要有上限:返回值进上下文,工具表只管 schema —— 这一笔它管不着。
|
|
123
|
+
const limit = listLimit(args?.limit);
|
|
124
|
+
const visible = allowed.slice(0, limit);
|
|
125
|
+
// 人设勾的工具里有多少条在这个对话里被关着:子代理的实际工具集是
|
|
126
|
+
// 「人设的限制 ∩ 本对话看得见的」,不说的话用户看到人设勾着它却用不了。
|
|
127
|
+
const visibleTool = (name) => {
|
|
128
|
+
if (typeof subagents.toolVisibleFor !== 'function')
|
|
129
|
+
return true;
|
|
130
|
+
try {
|
|
131
|
+
return subagents.toolVisibleFor(name, exec?.agent);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
const offTools = (p) => (Array.isArray(p.tools) ? p.tools : []).filter((t) => !visibleTool(String(t))).length;
|
|
138
|
+
const lines = visible.map((p) => '- ' + p.name + ' — ' + (p.description || '(no description)') +
|
|
121
139
|
(p.continuable === true ? CONTINUABLE_MARK : '') +
|
|
122
140
|
(includeUnavailable ? (!decideInSession(p, flag, boundSet) ? ' (disabled — turn it on first)' : '') : '') +
|
|
141
|
+
(offTools(p) > 0 ? ' (' + offTools(p) + ' of its tools are off in this conversation)' : '') +
|
|
123
142
|
(p.path ? ' · ' + p.path : ''));
|
|
124
143
|
// 默认口径下有多少个没列出来(停用的 + 不在启用场景里的):不报的话,模型看到一份短名单
|
|
125
144
|
// 会当成"本机只有这些人设"。数量照报,与另外三个 list 的表头同一口径。
|
|
@@ -143,7 +162,8 @@ export function defineSubagentManagerListTool(subagents) {
|
|
|
143
162
|
const header = 'persona subagents (' + allowed.length + ')' +
|
|
144
163
|
(hiddenCount > 0 ? ' (' + hiddenCount + ' more are disabled or outside the current scene; pass all=true to see them)' : '') +
|
|
145
164
|
(offHere > 0 ? ' (' + offHere + ' switched off here only)' : '') + ':\n';
|
|
146
|
-
return header + (lines.join('\n') || '(none)') + (
|
|
165
|
+
return header + (lines.join('\n') || '(none)') + moreNotShown(allowed.length, visible.length)
|
|
166
|
+
+ (reason ? '\nnote: ' + reason : '') + notice;
|
|
147
167
|
},
|
|
148
168
|
};
|
|
149
169
|
}
|
|
@@ -175,7 +195,7 @@ export function defineSubagentManagerRunTool(subagents) {
|
|
|
175
195
|
// 那两个"这层分界就没人说了。
|
|
176
196
|
//
|
|
177
197
|
// `inherit` 那句"轮中委派拿不到当前轮"必须留 —— 它是这条参数唯一会让人写错 task 的地方。
|
|
178
|
-
description: 'Run a named persona as a subagent: it gets the persona as its system prompt, works on `task`, and returns only its final output. A persona marked `(continuable)` returns an agent id and runs in the background — continue it with `send_message`.\n\nBy default the child cannot see this conversation, so `task` must be self-contained; `inherit: true` also hands it this conversation\'s **finished** turns (never the current one). `task` = the goal plus the context it needs; leave method and output format to the persona.\n\nUse it when the work matches a persona in the "Current subagents" reminder and the detail should not sit in your own context. Not for reading a file (Read), finding a definition (Grep/Glob), or touching two or three files.',
|
|
198
|
+
description: 'Run a named persona as a subagent: it gets the persona as its system prompt, works on `task`, and returns only its final output. A persona marked `(continuable)` returns an agent id and runs in the background — continue it with `send_message`.\n\nBy default the child cannot see this conversation, so `task` must be self-contained; `inherit: true` also hands it this conversation\'s **finished** turns (never the current one). `task` = the goal plus the context it needs; leave method and output format to the persona.\n\nUse it when the work matches a persona in the "Current subagents" reminder and the detail should not sit in your own context. Not for reading a file (Read), finding a definition (Grep/Glob), or touching two or three files. Asks the user to confirm before the subagent starts.',
|
|
179
199
|
parameters: {
|
|
180
200
|
agent: { type: 'string', required: true, description: 'Persona name — see the "Current subagents" reminder.' },
|
|
181
201
|
// `task` 的说明只留"这是什么":描述里已经写过"把方法与输出格式留给人设",
|
|
@@ -187,6 +207,19 @@ export function defineSubagentManagerRunTool(subagents) {
|
|
|
187
207
|
schema: { type: 'string' },
|
|
188
208
|
render: (_a, v) => text(String(v)),
|
|
189
209
|
},
|
|
210
|
+
/**
|
|
211
|
+
* 并行准入:这一条**允许**与同批的兄弟调用并发跑(宿主的 `isConcurrencySafe` 契约:
|
|
212
|
+
* 只有 `true` 才进并行批次,缺省即独占)。
|
|
213
|
+
*
|
|
214
|
+
* 为什么可以并发:委派跑的是**独立的子会话**(spawn 通道),不改父会话的任何状态;
|
|
215
|
+
* 插件自己的共享写入(记忆索引、场景档案)都在 hub 写锁下面,与并发子代理无关。
|
|
216
|
+
* 运行侧也为此把「启动串行 + 等待重叠」拆开了(run-provider 的 runSerial)——
|
|
217
|
+
* 不拆的话这里标了 `true` 也只是形式上并行,实际仍在排队。
|
|
218
|
+
*
|
|
219
|
+
* 为什么 `inherit` 那支不给并发:fork 通道继承的是**本次会话的上下文**,两个 fork
|
|
220
|
+
* 同时读同一个父会话,是本插件判不准的那一类共享状态。宁可它排队。
|
|
221
|
+
*/
|
|
222
|
+
isConcurrencySafe: (args) => args?.inherit !== true,
|
|
190
223
|
async execute(args, exec) {
|
|
191
224
|
const name = String((args && args.agent) || '').trim();
|
|
192
225
|
const task = String((args && args.task) || '').trim();
|
|
@@ -210,8 +243,15 @@ export function defineSubagentManagerRunTool(subagents) {
|
|
|
210
243
|
if (!persona) {
|
|
211
244
|
// 关掉的人设要单独说清 —— 否则模型会以为"这个人设不存在",转而去编一个名字。
|
|
212
245
|
const offHere = docs.some((p) => p.name === name);
|
|
213
|
-
if (offHere)
|
|
214
|
-
|
|
246
|
+
if (offHere) {
|
|
247
|
+
// 模型自己有出路就别推给用户:它能开这条人设,或者用控制面工具先把那条工具打开。
|
|
248
|
+
// 三档判据在 toolAccessSentence —— 与工具面各处回执同一份,不再这里手写一份。
|
|
249
|
+
const vis = subagents.toolVisibleFor;
|
|
250
|
+
const fix = typeof vis === 'function'
|
|
251
|
+
? toolAccessSentence({ toolVisibleFor: vis }, 'subagent_manager_switch', exec && exec.agent, 'the user can enable it')
|
|
252
|
+
: 'the user can enable it';
|
|
253
|
+
throw new Error('persona unavailable: ' + name + ' (turned off — here, by its global switch, or outside the active scene; ' + fix + ')');
|
|
254
|
+
}
|
|
215
255
|
const available = allowed.map((p) => p.name).join(', ') || '(none)';
|
|
216
256
|
throw new Error('persona unavailable: ' + name + (reason ? ' (' + reason + ')' : ' (available: ' + available + ')'));
|
|
217
257
|
}
|
|
@@ -230,6 +270,22 @@ export function defineSubagentManagerRunTool(subagents) {
|
|
|
230
270
|
const r = await subagents.runSerial(exec.agent, persona, task, exec.signal, decision === undefined ? undefined : decision.filter, inherit);
|
|
231
271
|
const prefix = r.stopReason && r.stopReason !== 'completed' ? `[stopReason: ${r.stopReason}]\n` : '';
|
|
232
272
|
const note = decision && decision.note ? `⚠ ${decision.note}\n\n` : '';
|
|
273
|
+
// 这个人设勾的工具里,有几条被**这个对话**的工具表关着 —— 子代理实际能用的是
|
|
274
|
+
// 「人设的限制 ∩ 本对话看得见的」,不说的话用户看到人设勾着它却调不动。
|
|
275
|
+
let offToolsNote = '';
|
|
276
|
+
if (typeof subagents.toolVisibleFor === 'function' && Array.isArray(persona.tools) && persona.tools.length > 0) {
|
|
277
|
+
const off = persona.tools.filter((t) => {
|
|
278
|
+
try {
|
|
279
|
+
return !subagents.toolVisibleFor(String(t), exec.agent);
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
if (off.length > 0) {
|
|
286
|
+
offToolsNote = 'note: ' + off.length + ' of this persona\'s tools are switched off in this conversation, so the subagent cannot call them (' + off.join(', ') + ').\n';
|
|
287
|
+
}
|
|
288
|
+
}
|
|
233
289
|
// 允许追问通道(人设 `continuable: true`):产出是**异步**到达的,这里只拿到子会话 id。
|
|
234
290
|
// 回执必须把"id + 产出怎么回来 + 怎么追问 + 怎么中止"写全 —— 少写一句,模型就会把
|
|
235
291
|
// "没拿到结果"读成"委派失败"而重试一次(那会再起一个后台子代理,白白翻倍)。
|
|
@@ -240,13 +296,13 @@ export function defineSubagentManagerRunTool(subagents) {
|
|
|
240
296
|
// 要求它在收尾前把自包含结果发给父代理),不是产出的唯一来路 —— 回执不能只说前者,
|
|
241
297
|
// 否则子代理没主动发消息时父代理会把"还没收到结果"当成"还在跑"。
|
|
242
298
|
if (r.continuable === true) {
|
|
243
|
-
return note + 'started the continuable subagent "' + name + '" (running in the background)\n'
|
|
299
|
+
return offToolsNote + note + 'started the continuable subagent "' + name + '" (running in the background)\n'
|
|
244
300
|
+ 'agent_id: ' + r.runId + '\n\n'
|
|
245
301
|
+ 'you will get a notification carrying its final output when it settles. To follow up: '
|
|
246
302
|
+ 'send_message({ agent_id: "' + r.runId + '", message: "..." }), '
|
|
247
303
|
+ 'To stop it: interrupt_agent({ agent_id: "' + r.runId + '" }).';
|
|
248
304
|
}
|
|
249
|
-
return note + prefix + r.text;
|
|
305
|
+
return offToolsNote + note + prefix + r.text;
|
|
250
306
|
},
|
|
251
307
|
};
|
|
252
308
|
}
|