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.
Files changed (45) hide show
  1. package/CHANGELOG.md +1415 -1363
  2. package/README.md +177 -176
  3. package/README_EN.md +177 -176
  4. package/docs/ARCHITECTURE.md +134 -0
  5. package/docs/COMPATIBILITY.md +107 -0
  6. package/docs/TROUBLESHOOTING.md +285 -0
  7. package/docs/UPDATE.md +50 -48
  8. package/lib/client.js +4693 -4626
  9. package/lib/compat/host-contracts.js +4 -2
  10. package/lib/confirm-gate.js +49 -18
  11. package/lib/context-inject-surface.js +45 -13
  12. package/lib/context-inject.js +1 -1
  13. package/lib/imports/unzip.js +144 -26
  14. package/lib/index.js +245 -93
  15. package/lib/legacy-tool-names.js +46 -0
  16. package/lib/mcp/manager.js +12 -1
  17. package/lib/mcp/secret-guard.js +27 -0
  18. package/lib/mcp/state-section.js +17 -8
  19. package/lib/mcp/tool-visibility.js +86 -10
  20. package/lib/memories/archive.js +44 -0
  21. package/lib/memories/index-io.js +4 -1
  22. package/lib/memories/service.js +94 -3
  23. package/lib/op-registry.js +5 -1
  24. package/lib/ops/scene-capture.js +72 -0
  25. package/lib/prompts/service.js +27 -0
  26. package/lib/scope/scope-overrides.js +9 -2
  27. package/lib/skills/catalog.js +18 -9
  28. package/lib/skills/dir-watch.js +49 -22
  29. package/lib/skills/service.js +2 -2
  30. package/lib/subagents/catalog.js +13 -7
  31. package/lib/subagents/run-provider.js +41 -10
  32. package/lib/subagents/tools.js +63 -7
  33. package/lib/tool-table-switch.js +41 -4
  34. package/lib/tools/control.js +158 -0
  35. package/lib/tools/deps.js +88 -0
  36. package/lib/tools/mcp.js +35 -10
  37. package/lib/tools/memory.js +9 -5
  38. package/lib/tools/prompt.js +7 -8
  39. package/lib/tools/remove.js +84 -65
  40. package/lib/tools/scene.js +179 -76
  41. package/lib/tools/skills.js +13 -8
  42. package/lib/tools/subagent.js +19 -10
  43. package/lib/tools/table.js +92 -57
  44. package/lib/trash-id.js +3 -2
  45. package/package.json +156 -152
@@ -1,12 +1,12 @@
1
1
  import { clearRuntimeNote, noteRuntime } from './compat/runtime-notes.js';
2
2
  import { hubPath } from './hub.js';
3
- import { addPreset, buildToolTableReport, classifyToolTableSettings, DEFAULT_HIDDEN_TOOLS, DEFAULT_TOOL_TABLE_SETTINGS, dropPreset, migrateLegacyToolNames, normalizeToolTableSettings, PRESET_MAX_COUNT, PRESET_NAME_MAX_LENGTH, } from './tools/table.js';
3
+ import { addPreset, applyToolTableToggles, buildToolTableReport, classifyToolTableSettings, DEFAULT_HIDDEN_TOOLS, DEFAULT_TOOL_TABLE_SETTINGS, dropPreset, migrateLegacyToolNames, normalizeToolTableSettings, PRESET_MAX_COUNT, PRESET_NAME_MAX_LENGTH, summarizeToolDescription, } from './tools/table.js';
4
4
  /** 模型工具表开关(侧车 `tool-table.json`):出厂默认名单、按会话 / 全局改可见集。 */
5
5
  export function createToolTableSwitch(deps) {
6
6
  // ---------- 模型工具表开关(侧车 `tool-table.json`,界面在「兼容」页)----------
7
- // 工具表按**每个请求**付钱:20 个工具的整份定义合计 ≈3,769 tok 每轮都在。关掉某几个,
8
- // 它们整份不进请求(实测口径与取舍见 src/tools/table.ts 的文件头)。**出厂就已经关了十四条**
9
- // (20 条里实发 6 条)—— 名单、判据与代价在 `DEFAULT_HIDDEN_TOOLS`,只在这个人从没记过
7
+ // 工具表按**每个请求**付钱:整张表的定义合计 ≈6.1k tok 每轮都在。关掉某几个,
8
+ // 它们整份不进请求(实测口径与取舍见 src/tools/table.ts 的文件头)。**出厂就已经关了十八条**
9
+ // (24 条里实发 6 条)—— 名单、判据与代价在 `DEFAULT_HIDDEN_TOOLS`,只在这个人从没记过
10
10
  // 选择时铺(见下面的 `toolTableSettingsFrom`)。
11
11
  //
12
12
  // 为什么放在目录之前:两个目录的「用 `X` 查」提示要跟着这份设置变(工具关掉后那句话
@@ -15,6 +15,17 @@ export function createToolTableSwitch(deps) {
15
15
  const TOOL_TABLE_TTL_MS = 3000;
16
16
  /** 注册时量到的工具体积(只记真进了表的那些;量的是 register 收到的整份定义)。 */
17
17
  const toolTableSizes = new Map();
18
+ /** 工具名 → 一句话用途(描述的首句)。 */
19
+ const toolTableSummaries = new Map();
20
+ /**
21
+ * 一句话用途:描述里第一行非空行,截到 {@link TOOL_SUMMARY_MAX} 字符。
22
+ *
23
+ * 为什么只取第一行:各工具描述的组织惯例是「是什么 → 怎么做 → 何时用」,首句就是
24
+ * 「是什么」。整段描述在模型读 schema 时已经在上下文里,重复贴一遍只是把回执撑大。
25
+ */
26
+ function summarizeTool(def) {
27
+ return summarizeToolDescription(def.description);
28
+ }
18
29
  function recordToolSize(def) {
19
30
  try {
20
31
  const name = String(def.name ?? '');
@@ -23,6 +34,7 @@ export function createToolTableSwitch(deps) {
23
34
  // 与宿主同一口径(dsh-token-meter 的 estimateToolsTokens 就是把 tools 整份
24
35
  // JSON.stringify 后除以 4),所以这里量整份定义,不只量 description。
25
36
  toolTableSizes.set(name, JSON.stringify(def).length);
37
+ toolTableSummaries.set(name, summarizeTool(def));
26
38
  }
27
39
  catch { /* 量不出来就不记:它只影响界面上的估算数字 */ }
28
40
  }
@@ -223,6 +235,30 @@ export function createToolTableSwitch(deps) {
223
235
  }
224
236
  return toolTablePayload(await readToolTableSettings());
225
237
  }
238
+ // 逐条改(`toggle`):改动落在**当前这份**名单上,在写锁里现读现改 ——
239
+ // 整份替换要先把名单读出来再算差量,读与写之间有窗口,两个写者会互相覆盖。
240
+ if (Array.isArray(args.toggle) && args.toggle.length > 0) {
241
+ const toggles = args.toggle
242
+ .filter((t) => t && typeof t.name === 'string' && t.name !== '')
243
+ .map((t) => ({ name: String(t.name), hidden: t.hidden === true }))
244
+ // 只收**已注册**的名字:写进来的陌生名字在下一次 restrict 时会让官方抛错。
245
+ .filter((t) => toolTableSizes.has(t.name));
246
+ if (toggles.length === 0) {
247
+ return { ok: false, error: 'none of these are this plugin\'s tools: ' + args.toggle.map((t) => String(t && t.name)).join(', ') };
248
+ }
249
+ const outcome = await mutateToolTableSettings((current) => ({
250
+ hidden: applyToolTableToggles(current.hidden, toggles),
251
+ presets: current.presets,
252
+ }));
253
+ if (!outcome.ok)
254
+ return outcome;
255
+ deps.mcp.scheduleToolRestrictions();
256
+ await Promise.all([
257
+ deps.skillCatalog.refresh().catch(() => { }),
258
+ deps.subagentCatalog.refresh().catch(() => { }),
259
+ ]);
260
+ return toolTablePayload(outcome.settings);
261
+ }
226
262
  // 只收**已注册**的名字:写进来的陌生名字在下一次 restrict 时会让官方抛错
227
263
  // ("names unknown global tool")。注册失败的工具本来也不在表里。
228
264
  const outcome = await mutateToolTableSettings((current) => {
@@ -243,6 +279,7 @@ export function createToolTableSwitch(deps) {
243
279
  }
244
280
  return {
245
281
  toolTableSizes,
282
+ toolTableSummaries,
246
283
  recordToolSize,
247
284
  readToolTableSettings,
248
285
  toolTableState: () => ({ state: toolTableStateValue, issue: toolTableIssueValue }),
@@ -0,0 +1,158 @@
1
+ // 控制面工具 `tool_manager_tools`:模型自己看得到哪些工具、能不能自己打开。
2
+ //
3
+ // 为什么要有它:插件出厂只发 6 条工具(`src/tools/table.ts` 的 `DEFAULT_HIDDEN_TOOLS`
4
+ // 关掉 18 条)。场景那一族**四条全关**,而场景目录注入只列**当前已启用的**场景 ——
5
+ // 一个都没启用时整段不注入(`src/memories/constants.ts` 的 `SCENE_CATALOG_MAX_BYTES` 注释)。
6
+ // 于是「用户说进入编程场景」这件事,模型既不知道有哪些场景,也没有开关工具:
7
+ // 零信息 + 零手段,是死局。
8
+ //
9
+ // 这条工具把那个死局解开:**按需**查(列清单)、**按需**开(只对本对话)。
10
+ // 它是唯一必须常驻的一条(其余能力一律按需调用,不进每轮的 schema)。
11
+ //
12
+ // 边界(有意不做的事):
13
+ // · 只写**管着这个对话的那一层**:按会话 = 这个对话;按工作区 = 这个工作区(那一层本来就
14
+ // 是同工作区共享的);隔离关掉(全局)时没有会话层,管着这个对话的就是全局那一份 ——
15
+ // 那一档是机器级改动,调用前会被确认卡问过。
16
+ // · 只认本插件注册过的工具名:MCP 工具归 MCP 停用表管,混进来会写出官方 restrict 认不出的名字。
17
+ // · 自己不可被关:唯一的回头路不能被自己关掉(面板仍然可以关)。
18
+ import { text } from './deps.js';
19
+ import { governingScopeNote } from './deps.js';
20
+ import { applyToolTableToggles, estimateTok } from './table.js';
21
+ /** 一行清单:名字 · 用途 · ≈token。 */
22
+ function toolLine(name, summary, bytes) {
23
+ const purpose = summary === '' ? '' : ' — ' + summary;
24
+ return '- ' + name + purpose + ' (≈' + estimateTok(bytes) + ' tok/turn)';
25
+ }
26
+ /** 这条工具自己的名字(自己不可被关的那条判据用)。 */
27
+ const CONTROL_TOOL_NAME = 'tool_manager_tools';
28
+ /**
29
+ * 注册控制面工具(`tool_manager_tools`)。
30
+ *
31
+ * 只做三件事:列清单、开工具、关工具。**没有第四件** ——
32
+ * 「打开之后立刻用那条工具」的动作没有做:它要么绕过宿主的工具执行管线
33
+ * (审批、输出校验都在那条管线上),要么依赖宿主「每个模型请求重新解析一次工具集」
34
+ * 这个尚未核实的时序。前者不安全,后者大概率不需要(工具表是**作用域级**的限制,
35
+ * 放开之后下一次请求组 schema 时就带上了)。
36
+ */
37
+ export function buildControlTools(deps) {
38
+ const { defineTool, register } = deps;
39
+ try {
40
+ register(defineTool({
41
+ name: CONTROL_TOOL_NAME,
42
+ description: 'Turn this plugin\'s own tools on or off for the scope that governs this conversation '
43
+ + '(this conversation, its whole workspace under workspace isolation, or every conversation once isolation is off). '
44
+ + 'Call `list` when the user asks for something this conversation cannot do yet (e.g. switching scene while the scene tools are off): it returns the tools that are off here, one line each. '
45
+ + '`enable`/`disable` take one or more names and apply from the next request.',
46
+ parameters: {
47
+ action: {
48
+ type: 'string',
49
+ required: true,
50
+ enum: ['list', 'enable', 'disable', 'repair'],
51
+ description: 'list = tools off here; enable / disable = turn them on / off here; repair = fix a broken sidecar.',
52
+ },
53
+ tools: {
54
+ type: 'array',
55
+ items: { type: 'string' },
56
+ description: 'Names from `list`.',
57
+ },
58
+ target: {
59
+ type: 'string',
60
+ enum: ['memory-index', 'scope', 'mcp-disabled'],
61
+ description: 'For repair: memory-index | scope | mcp-disabled.',
62
+ },
63
+ },
64
+ output: { schema: { type: 'string' }, render: (_a, v) => text(String(v)) },
65
+ async execute(args, exec) {
66
+ const action = String((args && args.action) || '').trim();
67
+ const agent = exec && exec.agent;
68
+ if (action === 'list')
69
+ return listTools(deps, agent);
70
+ if (action === 'repair')
71
+ return repairState(deps, args);
72
+ if (action !== 'enable' && action !== 'disable') {
73
+ throw new Error('unknown action: ' + (action === '' ? '(missing)' : action) + ' — use list, enable, disable or repair');
74
+ }
75
+ const requested = (Array.isArray(args && args.tools) ? args.tools : [])
76
+ .map((n) => String(n ?? '').trim())
77
+ .filter((n) => n !== '');
78
+ if (requested.length === 0)
79
+ throw new Error('missing argument: tools — the names of the tools to ' + action);
80
+ // 只认本插件注册过的名字:陌生名字写进关停名单会让官方的 restrict 抛错。
81
+ const known = requested.filter((n) => deps.toolTableSizes.has(n));
82
+ const unknown = requested.filter((n) => !deps.toolTableSizes.has(n));
83
+ if (known.length === 0) {
84
+ throw new Error('none of these are this plugin\'s tools: ' + requested.join(', ') +
85
+ ' — call list to see the names');
86
+ }
87
+ // 自己不可被关:这条工具是模型唯一的回头路,关掉它就再也开不回来
88
+ // (面板仍然可以关 —— 用户说了算)。
89
+ if (action === 'disable' && known.includes(CONTROL_TOOL_NAME)) {
90
+ throw new Error('this tool cannot switch itself off — it is the only way back to the others. Only the user can disable it (in the panel).');
91
+ }
92
+ const hidden = deps.hiddenForSession(agent);
93
+ // 逐条改:每一处改动是一个「关掉 / 打开某一条」,写侧在锁里现读现改。
94
+ const changes = known.map((name) => ({ name, hidden: action === 'disable' }));
95
+ const next = applyToolTableToggles([...hidden], changes);
96
+ const saved = await deps.applyToolTable(agent, changes);
97
+ if (!saved.ok)
98
+ throw new Error(saved.error || 'failed to save the tool table for this conversation');
99
+ const changed = changes.filter((c) => (c.hidden ? !hidden.has(c.name) : hidden.has(c.name))).map((c) => c.name);
100
+ const lines = [
101
+ 'OK: ' + (action === 'enable' ? 'enabled' : 'disabled') + ': ' + (changed.join(', ') || '(nothing changed)')
102
+ + governingScopeNote(deps) + '.',
103
+ 'These take effect from the next request.',
104
+ ];
105
+ if (unknown.length > 0)
106
+ lines.push('not this plugin\'s tools (ignored): ' + unknown.join(', '));
107
+ // 说清「这一层看得见的条数」:模型据此判断自己还有没有别的路。
108
+ const total = deps.toolTableSizes.size;
109
+ lines.push((total - next.length) + ' of ' + total + ' tools are available here now.');
110
+ return lines.join('\n');
111
+ },
112
+ }));
113
+ }
114
+ catch (e) {
115
+ console.error('[dsh-plugin-tool-management] control tool registration failed:', deps.message(e));
116
+ }
117
+ }
118
+ /**
119
+ * 修复动作:把已损坏的侧车改名留存、按空表继续。
120
+ *
121
+ * 回执要把「修好了什么」和「原来的数据去哪了」都写出来:被隔离的文件还在(改名留存),
122
+ * 但插件从此不再读它 —— 模型说「已修复」时,用户得知道代价是什么。
123
+ */
124
+ async function repairState(deps, args) {
125
+ const target = String((args && args.target) || '').trim();
126
+ if (target !== 'memory-index' && target !== 'scope' && target !== 'mcp-disabled') {
127
+ throw new Error('missing argument: target — memory-index, scope or mcp-disabled');
128
+ }
129
+ const r = await deps.repair(target);
130
+ if (!r || r.ok === false)
131
+ throw new Error((r && r.error) || 'repair failed');
132
+ const lines = ['OK: repaired ' + target + '.'];
133
+ if (r.message)
134
+ lines.push(String(r.message));
135
+ lines.push('The damaged file was renamed aside, not deleted; the plugin now continues with an empty table, so whatever it held no longer applies.');
136
+ return lines.join('\n');
137
+ }
138
+ /**
139
+ * 列出本对话现在**关着**的工具(能打开的那些)。
140
+ *
141
+ * 只列关着的:看得见的那些模型手里已经有 schema了,重复列一遍只是浪费上下文。
142
+ */
143
+ function listTools(deps, agent) {
144
+ const hidden = deps.hiddenForSession(agent);
145
+ const rows = [];
146
+ for (const [name, bytes] of deps.toolTableSizes) {
147
+ if (!hidden.has(name))
148
+ continue;
149
+ rows.push(toolLine(name, deps.toolTableSummaries.get(name) ?? '', bytes));
150
+ }
151
+ const total = deps.toolTableSizes.size;
152
+ if (rows.length === 0) {
153
+ return 'every tool of this plugin is already on here (' + total + ' tools); nothing to enable.';
154
+ }
155
+ return 'tools switched off here (' + rows.length + ' of ' + total + '):\n' +
156
+ rows.join('\n') +
157
+ '\ncall this tool with action="enable" and the names you need (one or more).';
158
+ }
package/lib/tools/deps.js CHANGED
@@ -73,6 +73,75 @@ export function toolOrNeutral(deps, agent, tool, named, neutral) {
73
73
  }
74
74
  return visible ? named : neutral;
75
75
  }
76
+ /**
77
+ * 控制面工具的名字(模型自己开关工具表的那条)。
78
+ *
79
+ * 定义在这一层而不是 `tools/control.ts`:回执与报错常要问「模型能不能自己打开某条工具」,
80
+ * 那问的就是这条的名字 —— 两处各写一个字面量,改名时就分叉了。
81
+ */
82
+ export const CONTROL_TOOL_NAME = 'tool_manager_tools';
83
+ /**
84
+ * 判定模型自己能不能弄到 `fixer`(那条能修好问题的工具)。
85
+ *
86
+ * @param deps 判据面(只需 `toolVisibleFor`,见 {@link ToolVisibilityJudge})。
87
+ * @param fixer 能修好问题的工具名(如 `subagent_manager_switch`)。
88
+ * @param agent 当前会话的 agent(工具表按对话解析,判据要跟着它走)。
89
+ */
90
+ export function toolAccessRoute(deps, fixer, agent) {
91
+ const visible = (name) => {
92
+ try {
93
+ return deps.toolVisibleFor(name, agent);
94
+ }
95
+ catch {
96
+ return false;
97
+ }
98
+ };
99
+ if (visible(fixer))
100
+ return 'direct';
101
+ if (visible(CONTROL_TOOL_NAME))
102
+ return 'via-control';
103
+ return 'none';
104
+ }
105
+ /**
106
+ * {@link toolAccessRoute} 的英文句子版(给英文回执用)。
107
+ *
108
+ * `fallback` 是模型确实没有别的路时的那句(各调用点的措辞不同:永久删除与改绑不是一回事)。
109
+ */
110
+ export function toolAccessSentence(deps, fixer, agent, fallback) {
111
+ const route = toolAccessRoute(deps, fixer, agent);
112
+ if (route === 'direct')
113
+ return 'use ' + fixer;
114
+ if (route === 'via-control') {
115
+ return 'enable ' + fixer + ' with tool_manager_tools (action="enable", tools:["' + fixer + '"]), then use it';
116
+ }
117
+ return fallback;
118
+ }
119
+ /** 列表类工具一次默认返回多少条。 */
120
+ export const LIST_LIMIT_DEFAULT = 50;
121
+ /** 列表类工具一次最多返回多少条。 */
122
+ export const LIST_LIMIT_MAX = 100;
123
+ /**
124
+ * 列表类工具的 `limit` 参数归一:夹到 [1, {@link LIST_LIMIT_MAX}],缺省给默认值。
125
+ *
126
+ * 为什么要有上限:返回值进上下文,而**工具表管不着这一笔**(工具表只管 schema)。
127
+ * 模型爱「先全列出来看看」,一次就是几千 token —— 而它省下的那点(不用再调一次)
128
+ * 远不抵。`memory_manager_search` 早就带这个上限了,list 那几条没有 —— 同一族里
129
+ * 只有一条有限,不一致。
130
+ */
131
+ export function listLimit(raw) {
132
+ const n = Math.floor(Number(raw));
133
+ if (!Number.isFinite(n) || n <= 0)
134
+ return LIST_LIMIT_DEFAULT;
135
+ return Math.min(n, LIST_LIMIT_MAX);
136
+ }
137
+ /**
138
+ * 「还有 N 条没列」那句:超限时必须说,否则模型会以为那就是全部。
139
+ */
140
+ export function moreNotShown(total, shown) {
141
+ return total > shown
142
+ ? '\n' + (total - shown) + ' more not shown; pass a higher limit or narrow the filter.'
143
+ : '';
144
+ }
76
145
  /**
77
146
  * 按名字找技能落在哪个来源(root)。
78
147
  *
@@ -269,6 +338,25 @@ export function scopeOnlyNote(deps) {
269
338
  return ' **for this conversation only**';
270
339
  return ' **for this scope only** (this conversation, or every conversation in its workspace under workspace isolation)';
271
340
  }
341
+ /**
342
+ * 「**管着这个对话的那一层**」的写入回执后缀。
343
+ *
344
+ * 与 {@link scopeOnlyNote} 的区别:那条说的是「本对话那一层」—— `_switch` 家族写的就是它,
345
+ * 而那几条在全局粒度下压根不写这一层(`effectiveScope` 把一切导向全局,走各自的机器级措辞)。
346
+ * 这条说的是**真正被写到的那一层**:隔离关掉时没有会话层,管着这个对话的就是全局那一份,
347
+ * 说成「只影响这个对话」就是假话。
348
+ *
349
+ * 三档各说各的,别混:按会话 = 这个对话;按工作区 = 这个工作区里的每个对话;
350
+ * 全局 = 每个对话(且这一档必然是机器级,调用前会被确认卡问过)。
351
+ */
352
+ export function governingScopeNote(deps) {
353
+ const mode = deps.scopeMode?.();
354
+ if (mode === 'global')
355
+ return ' **for every conversation** (isolation is off — there is no per-conversation layer)';
356
+ if (mode === 'workspace')
357
+ return ' **for this whole workspace only** (every conversation in it)';
358
+ return ' **for this conversation only**';
359
+ }
272
360
  /**
273
361
  * 「全局没动、别人不受影响」那句:谁算「别人」由粒度决定。
274
362
  *
package/lib/tools/mcp.js CHANGED
@@ -26,7 +26,14 @@
26
26
  // `mcpm-edit` 里那句 `if (row[field] === undefined) return` 就不会生效,于是
27
27
  // `resolveMaskedKv({}, 旧值)` 把整份 headers / env 静默清空、连 warning 都不给。
28
28
  import { DEFAULT_MCP_NOTE_MAX_LENGTH, normalizeMcpNote } from '../mcp/state-section.js';
29
- import { candidateNote, effectiveScope, existingNote, globalActionNote, globalUnchangedNote, isolationOffNote, requireGlobalScope, scopeGlobalOnlyDesc, scopeOnlyNote, scopeSessionDesc, sessionLayerOn, text } from './deps.js';
29
+ /**
30
+ * 一台服务器最多列多少个工具名(`mcp_manager_list` 的 `tools=true`)。
31
+ *
32
+ * 为什么要有上限:一次列十几台 × 二十来个工具 ≈ 3k token,而返回值进上下文、
33
+ * 工具表管不着这一笔。超出的部分用「(+N more)」点名,模型知道还有就行。
34
+ */
35
+ const MCP_TOOL_NAMES_MAX = 40;
36
+ import { candidateNote, effectiveScope, existingNote, globalActionNote, globalUnchangedNote, isolationOffNote, listLimit, moreNotShown, requireGlobalScope, scopeGlobalOnlyDesc, scopeOnlyNote, scopeSessionDesc, sessionLayerOn, text } from './deps.js';
30
37
  /** 「去看清单」那句:`mcp_manager_list` 不在模型手里时不能点名它(调用方按 `toolVisibleFor` 决定给不给)。 */
31
38
  const MCP_LIST_HINT = ' (see mcp_manager_list — all=true also lists disabled ones)';
32
39
  /**
@@ -118,6 +125,7 @@ export function buildMcpTools(deps) {
118
125
  parameters: {
119
126
  all: { type: 'boolean', description: 'Include disabled servers (default false).' },
120
127
  tools: { type: 'boolean', description: 'Also list each server\'s tool names, marking the switched-off ones (default false).' },
128
+ limit: { type: 'number', description: 'Max servers (default 50, max 100).' },
121
129
  },
122
130
  output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
123
131
  async execute(args, exec) {
@@ -144,7 +152,10 @@ export function buildMcpTools(deps) {
144
152
  }
145
153
  }
146
154
  const isOff = (x) => x.disabled === true || offHere.has(String(x.serverName));
147
- const shown = showAll ? all : all.filter((x) => !isOff(x));
155
+ const allShown = showAll ? all : all.filter((x) => !isOff(x));
156
+ // 返回体也要有上限:返回值进上下文,工具表只管 schema —— 这一笔它管不着。
157
+ const limit = listLimit(args && args.limit);
158
+ const shown = allShown.slice(0, limit);
148
159
  const lines = [];
149
160
  for (const x of shown) {
150
161
  const note = normalizeMcpNote(x.notes, DEFAULT_MCP_NOTE_MAX_LENGTH);
@@ -170,6 +181,10 @@ export function buildMcpTools(deps) {
170
181
  lines.push('server:' + x.serverName + ' | level:' + x.level + ' | ' + state +
171
182
  (x.live ? ' | loader:' + (x.live.enabled ? 'on' : 'off') + (x.live.phase ? ':' + x.live.phase : '') : '') +
172
183
  (typeof usableTools === 'number' ? ' | tools:' + usableTools : '') +
184
+ // **还缺哪几把钥匙**:这台声明了环境变量 / 请求头但值是空的(只有键名)。
185
+ // MCP 认证失败最常见的原因就是这个,而模型看不到界面上的空框。
186
+ (Array.isArray(x.missingEnv) && x.missingEnv.length ? ' | missing-env:' + x.missingEnv.join(',') : '') +
187
+ (Array.isArray(x.missingHeaders) && x.missingHeaders.length ? ' | missing-header:' + x.missingHeaders.join(',') : '') +
173
188
  (note ? ' | user-hint:' + note : ''));
174
189
  if (!showTools)
175
190
  continue;
@@ -185,10 +200,20 @@ export function buildMcpTools(deps) {
185
200
  }
186
201
  const items = t && t.ok !== false ? (t.tools || []) : [];
187
202
  if (!items.length) {
188
- lines.push(' ' + (x.disabled ? '(tools not recorded: server is off)' : '(no tools recorded)'));
203
+ // 「一个工具都没有」最常见的原因就是**钥匙没填**:声明了环境变量而值是空的。
204
+ // 不说清的话模型只能报「这台没有工具」,用户也不知道该去填哪一格。
205
+ const missing = [
206
+ ...(Array.isArray(x.missingEnv) ? x.missingEnv.map((k) => 'env ' + k) : []),
207
+ ...(Array.isArray(x.missingHeaders) ? x.missingHeaders.map((k) => 'header ' + k) : []),
208
+ ];
209
+ lines.push(' ' + (x.disabled ? '(tools not recorded: server is off)' : '(no tools recorded)') +
210
+ (missing.length ? ' — not filled in yet: ' + missing.join(', ') : ''));
189
211
  continue;
190
212
  }
191
- lines.push(' tools: ' + items.map((it) => {
213
+ // 每台的工具名清单也要有上限:十几台 × 二十来个工具 ≈ 一次 3k token,
214
+ // 而这一笔工具表管不着(工具表只管 schema)。超出的部分点名说清还剩多少。
215
+ const named = items.slice(0, MCP_TOOL_NAMES_MAX);
216
+ lines.push(' tools: ' + named.map((it) => {
192
217
  // 服务器在这一层整个不可用时,逐工具不再重复标注:上面那行已经说了它不可用。
193
218
  // 停用表读不出来时同理 —— 那一档执行侧全拒,(on here) 会与上面那句打架。
194
219
  const here = offHere.has(String(x.serverName)) || (t && t.disabledState === 'unknown')
@@ -198,7 +223,7 @@ export function buildMcpTools(deps) {
198
223
  if (!off)
199
224
  return String(it.name) + (it.enabled === false ? ' (on here)' : '');
200
225
  return String(it.name) + (it.enabled === false ? ' (off)' : ' (off here)');
201
- }).join(', '));
226
+ }).join(', ') + (items.length > named.length ? ' (+' + (items.length - named.length) + ' more)' : ''));
202
227
  }
203
228
  // 会话层(`mcp_manager_list` 标注本会话可见性):本会话停用的服务器
204
229
  // 与全局停用**同形**(默认不列、all=true 标注),但两者的含义完全不同 —— 前者换个对话
@@ -209,15 +234,15 @@ export function buildMcpTools(deps) {
209
234
  [...offHere].join(', ') + ') — the connection is still up, and conversations outside this scope keep them.\n';
210
235
  const header = 'MCP servers: ' + (showAll
211
236
  ? all.length + ' configured'
212
- : shown.length + ' enabled of ' + all.length + ' configured' +
213
- (shown.length === all.length ? '' : ' (pass all=true for every configured server)')) +
237
+ : allShown.length + ' enabled of ' + all.length + ' configured' +
238
+ (allShown.length === all.length ? '' : ' (pass all=true for every configured server)')) +
214
239
  (sessionLine === '' ? '\n' : sessionLine);
215
240
  // 注入边界:压制型预设(persona complete / 关闭运行时上下文,如极简)下本插件
216
241
  // 默认不注入 —— 模型只有 mcp__* 的工具名与参数,没有服务级信息。不说明的话,
217
242
  // 模型会把「能调用这些工具」当成「已经知道有哪些 server、用户给它们写了什么备注」。
218
243
  // 提示本身不点名任何工具,所以挂在哪个发现型工具上都不会出现循环指引。
219
244
  const notice = await deps.reachNoticeForAgent(deps.presetRoster(), exec && exec.agent && exec.agent.ctx, deps.injectNoticeOptions());
220
- return header + (lines.join('\n') || '(none)') + notice;
245
+ return header + (lines.join('\n') || '(none)') + moreNotShown(allShown.length, shown.length) + notice;
221
246
  },
222
247
  }));
223
248
  register(defineTool({
@@ -233,7 +258,7 @@ export function buildMcpTools(deps) {
233
258
  // 紧挨着的 "Only when the user asks or approves" 就被读成对别的动作说的 —— 模型可能理解成
234
259
  // 「restart 是我的自愈手段,不用问」。`the lock skips it, approval does not` 把两个主语
235
260
  // 摆在一起,豁免只剥掉锁那一层。
236
- description: 'Turn one MCP server on or off, restart it, or stop it machine-wide; pass `tool` to target named tools on it. `off` leaves a server running while any conversation still uses it, `stop` ends it for them too. Blocked while the active scene is locked, except restart (the recovery path; the lock skips it, approval does not). Only when the user asks or approves.',
261
+ description: 'Turn one MCP server on or off, restart it, or stop it machine-wide; pass `tool` to target named tools on it. `off` leaves a server running while any conversation still uses it, `stop` ends it for them too. Blocked while the active scene is locked, except restart (the recovery path; the lock skips it, approval does not). Stopping and a machine-wide on/off ask the user to confirm; a per-conversation switch and restart do not. Only when the user asks or approves.',
237
262
  parameters: {
238
263
  // 出口必须指向**常驻**来源,不能指向 `mcp_manager_list`:
239
264
  // 那条工具在出厂默认里就是关着的,`listHint()` 在它不可见时返回空串,于是猜错名字时的
@@ -410,7 +435,7 @@ export function buildMcpTools(deps) {
410
435
  }));
411
436
  register(defineTool({
412
437
  name: 'mcp_manager_save',
413
- description: 'Add a new MCP server, or update the one with this name — the receipt says which. Omitted fields keep their current values, so never restate the whole server. Pass `hint` for a usage note. Blocked while the active scene is locked. Only on the user\'s instruction.',
438
+ description: 'Add a new MCP server, or update the one with this name — the receipt says which. Omitted fields keep their current values, so never restate the whole server. Pass `hint` for a usage note. Blocked while the active scene is locked. Asks the user to confirm before it runs. Only on the user\'s instruction.',
414
439
  parameters: {
415
440
  server: { type: 'string', required: true, description: 'Server name (1-32 chars, [A-Za-z0-9_-]) — the name the mcp__<server>__ tools use.' },
416
441
  transport: { type: 'string', description: 'streamable-http or stdio. Required when creating.' },
@@ -19,7 +19,7 @@
19
19
  // 本身。memory_manager_save 受 tools/pre-execute 审批门禁。
20
20
  // 路径锚点:$DSH_HOME/tool-management/memories/<场景>/…(场景 `global` = 界面「全局」)。
21
21
  import { GLOBAL_SCENE, SHARED_GROUP } from '../memories/constants.js';
22
- import { candidateNote, effectiveScope, existingNote, globalActionNote, globalUnchangedNote, isolationOffNote, scopeOnlyNote, scopeSessionDesc, sessionScopeOf, text } from './deps.js';
22
+ import { candidateNote, effectiveScope, existingNote, globalActionNote, globalUnchangedNote, isolationOffNote, listLimit, moreNotShown, scopeOnlyNote, scopeSessionDesc, sessionScopeOf, text } from './deps.js';
23
23
  /** 注册记忆域的 model 工具(列表 / 读取 / 检索 / 切换 / 保存)。 */
24
24
  export function buildMemoryTools(deps) {
25
25
  const { defineTool, register } = deps;
@@ -33,8 +33,9 @@ export function buildMemoryTools(deps) {
33
33
  // 而 `scene` 是它在 `scene_manager_*`、`<scene>/<name>` 与注入段标题里的叫法。
34
34
  // op 的内部契约字段仍是 `group`(`rules-list` 与界面侧调用方都读它),所以 execute 里
35
35
  // 显式映射一次 —— 改 op 的字段名要动界面,那不是这一条能顺手做的事。
36
- scene: { type: 'string', description: 'Optional scene filter; `global` is the always-on scene.' },
36
+ scene: { type: 'string', description: 'Optional scene filter; `global` and `_shared` are the always-on scenes.' },
37
37
  all: { type: 'boolean', description: 'Include memories that are off, in an inactive scene, or shadowed (default false).' },
38
+ limit: { type: 'number', description: 'Max entries (default 50, max 100).' },
38
39
  },
39
40
  output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
40
41
  async execute(args, exec) {
@@ -76,7 +77,10 @@ export function buildMemoryTools(deps) {
76
77
  };
77
78
  const rows = (r.rules || []).map((x) => ({ x, ...stateOf(x) }));
78
79
  const shown = showAll ? rows : rows.filter((row) => row.injects);
79
- const lines = shown.map(({ x, label }) => ('- ' + x.id + ' [' + (x.group || 'no scene') + '] ' + label +
80
+ // 返回体也要有上限:返回值进上下文,而工具表只管 schema —— 这一笔它管不着。
81
+ const limit = listLimit(args && args.limit);
82
+ const visible = shown.slice(0, limit);
83
+ const lines = visible.map(({ x, label }) => ('- ' + x.id + ' [' + (x.group || 'no scene') + '] ' + label +
80
84
  // 形态与附件:此前不报,模型分不清哪条是 bundle、更不知道它带了几个附件
81
85
  // (`rules-list` 早就把 `form` 与 bundle 的附件摘要给了出来,只是这里没渲染)。
82
86
  (x.form === 'bundle'
@@ -108,7 +112,7 @@ export function buildMemoryTools(deps) {
108
112
  // 注入边界:压制型预设(persona complete / 关闭运行时上下文)下本插件默认不注入,
109
113
  // 此时列出的记忆**不在**模型上下文里。必须说出来,否则模型会假设自己已经看到正文。
110
114
  const notice = await deps.reachNoticeForAgent(deps.presetRoster(), exec && exec.agent && exec.agent.ctx, deps.injectNoticeOptions());
111
- return header + (lines.join('\n') || '(none)') + notice;
115
+ return header + (lines.join('\n') || '(none)') + moreNotShown(shown.length, visible.length) + notice;
112
116
  },
113
117
  }));
114
118
  register(defineTool({
@@ -261,7 +265,7 @@ export function buildMemoryTools(deps) {
261
265
  // (场景段 128 KiB),而模型很乐意把「这个项目用 pnpm」记一条 —— 那看一眼 `package.json`
262
266
  // 就知道,记下来却永久占着每一轮请求。合并 write/update 后这两句更要留:upsert 降低了
263
267
  // "再记一条"的摩擦,而摩擦正是这里唯一拦得住它的东西。
264
- description: 'Create a memory, or update the one with this id — the receipt says which. Memories cost context on every later request: record only what cannot be re-derived from code, config or git, and update an existing one rather than adding a near-duplicate. Blocked while the active scene is locked. Only on the user\'s instruction.',
268
+ description: 'Create a memory, or update the one with this id — the receipt says which. Memories cost context on every later request: record only what cannot be re-derived from code, config or git, and update an existing one rather than adding a near-duplicate. Blocked while the active scene is locked. Asks the user to confirm before it runs. Only on the user\'s instruction.',
265
269
  parameters: {
266
270
  memory: { type: 'string', required: true, description: 'Memory id like <scene>/<name> — copy it from the list. `global` is the always-on scene.' },
267
271
  description: { type: 'string', description: 'One-sentence description (<=500 chars). Required when creating. Empty string = drop it and re-derive from the body; omit = keep.' },
@@ -4,15 +4,15 @@
4
4
  // 模型可查、可切;**不能造** —— 预设正文是用户自己写的一份长文(`AGENTS.md`),
5
5
  // 模型没有创建入口,要新建只能由用户在面板里写。
6
6
  //
7
- // 删除在 `tools/remove.ts` 的 `prompt_manager_remove`(加)。此前这里写的是
7
+ // 删除在 `tools/remove.ts` 的 `plugin_manager_remove`(加)。此前这里写的是
8
8
  // 「不能造 / **不能删** —— 避免模型乱删用户预设」,那条理由针对的是**不可恢复**的删除:
9
- // 预设正文是用户手写的、删了就得重写。回收站把它的前提消掉了 —— 五条 `*_manager_remove`
10
- // 一律「进回收站、可恢复、需用户指令、过场景冻结守卫」,永久删除仍只留在面板。
9
+ // 预设正文是用户手写的、删了就得重写。回收站把它的前提消掉了 —— 那条删除工具
10
+ // 「进回收站、可恢复、需用户指令、过场景冻结守卫」,永久删除仍只留在面板。
11
11
  // 换句话说:**能删的是可恢复的那一步,不可逆的那一步照旧不给模型。**
12
12
  import { join } from 'node:path';
13
13
  import { normalizePresetDescription } from '../prompts/service.js';
14
14
  import { hasPromptOverride } from '../scope/scope-overrides.js';
15
- import { candidateNote, sessionScopeOf, text } from './deps.js';
15
+ import { candidateNote, sessionScopeOf, text, toolAccessSentence } from './deps.js';
16
16
  /** 注册提示词域的 model 工具(列表 / 读取 / 应用)。 */
17
17
  export function buildPromptTools(deps) {
18
18
  const { defineTool, register } = deps;
@@ -78,7 +78,7 @@ export function buildPromptTools(deps) {
78
78
  }));
79
79
  register(defineTool({
80
80
  name: 'prompt_manager_apply',
81
- description: 'Apply one AGENTS.md preset by id; effective next turn. When a scene drives the baseline this does not refuse — it rebinds that scene, so tell the user which one. A locked scene blocks the call. apply=false cancels instead: AGENTS.md goes back to what it was before this run of applies (removed if there was none), which a scene-driven baseline refuses — rebind the scene instead. Only on the user\'s instruction.',
81
+ description: 'Apply one AGENTS.md preset by id; effective next turn. When a scene drives the baseline this does not refuse — it rebinds that scene, so tell the user which one. A locked scene blocks the call. apply=false cancels instead: AGENTS.md goes back to what it was before this run of applies (removed if there was none), which a scene-driven baseline refuses — rebind the scene instead. Applying asks the user to confirm first; cancelling (apply=false) does not. Only on the user\'s instruction.',
82
82
  parameters: {
83
83
  // `id` 从 required 摘掉:描述一直写着 "Ignored when
84
84
  // apply=false",schema 却把它标成必填 —— 模型照描述「取消不用给 id」操作,先被 schema
@@ -142,9 +142,8 @@ export function buildPromptTools(deps) {
142
142
  : pinned === target
143
143
  ? '\nnote: that is the scene pinned here, so this scope follows it.'
144
144
  : '\nnote: this scope pins scene "' + pinned + '", so what it gets here is unchanged — this call rebound the machine-wide scene "' + shown + '". '
145
- + (deps.toolVisibleFor('scene_manager_save', exec && exec.agent)
146
- ? 'To change the binding that applies here, save scene "' + pinned + '" with that preset (scene_manager_save).'
147
- : 'To change the binding that applies here, the user has to rebind scene "' + pinned + '" in the panel.');
145
+ + 'To change the binding that applies here, save scene "' + pinned + '" with that preset'
146
+ + ' — ' + toolAccessSentence(deps, 'scene_manager_save', exec && exec.agent, 'the user has to rebind that scene in the panel') + '.';
148
147
  return 'OK: preset ' + id + ' is now the prompt binding of scene "' + shown + '" and the scene was re-synced (effective next turn; ~/.dsh/AGENTS.md now carries that scene\'s binding).' + scopeNote;
149
148
  }
150
149
  // 生效时机与宿主行为对齐(index.ts 提示词服务一节考证过):dsh-agent-instructions