dsh-plugin-tool-management 0.21.0 → 0.21.2

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 (106) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +47 -10
  3. package/README_EN.md +45 -10
  4. package/docs/images/1-EN.png +0 -0
  5. package/docs/images/1.png +0 -0
  6. package/docs/images/2-EN.png +0 -0
  7. package/docs/images/2.png +0 -0
  8. package/docs/images/3-EN.png +0 -0
  9. package/docs/images/3.png +0 -0
  10. package/docs/images/4-EN.png +0 -0
  11. package/docs/images/4.png +0 -0
  12. package/docs/images/5-EN.png +0 -0
  13. package/docs/images/5.png +0 -0
  14. package/docs/images/6-EN.png +0 -0
  15. package/docs/images/6.png +0 -0
  16. package/docs/images/7-EN.png +0 -0
  17. package/docs/images/7.png +0 -0
  18. package/docs/images/8-EN.png +0 -0
  19. package/docs/images/8.png +0 -0
  20. package/docs/images/icon.png +0 -0
  21. package/docs/images/icon.svg +1 -0
  22. package/docs/update.md +37 -35
  23. package/lib/boot/reconcile.js +157 -0
  24. package/lib/client.js +7166 -3084
  25. package/lib/compat/patch-dialect.js +14 -1
  26. package/lib/compat/probe.js +25 -21
  27. package/lib/context-inject-frame.js +62 -40
  28. package/lib/context-inject-select.js +59 -4
  29. package/lib/context-inject-surface.js +49 -3
  30. package/lib/context-inject.js +145 -22
  31. package/lib/diagnostics.js +77 -0
  32. package/lib/http-api.js +39 -23
  33. package/lib/http-fence.js +40 -5
  34. package/lib/imports/unzip.js +48 -0
  35. package/lib/imports/upload.js +8 -36
  36. package/lib/index.js +2933 -169
  37. package/lib/mcp/disabled-tools.js +96 -0
  38. package/lib/mcp/manager.js +559 -128
  39. package/lib/mcp/restart-marker.js +110 -0
  40. package/lib/mcp/state-section.js +132 -43
  41. package/lib/mcp/tool-visibility.js +348 -56
  42. package/lib/memories/archive-engine.js +39 -14
  43. package/lib/memories/discovery.js +30 -10
  44. package/lib/memories/index-io.js +217 -18
  45. package/lib/memories/projection.js +20 -3
  46. package/lib/memories/prompt-layer.js +37 -0
  47. package/lib/memories/search.js +86 -0
  48. package/lib/memories/service.js +327 -91
  49. package/lib/memories/snapshot.js +66 -19
  50. package/lib/op-registry.js +49 -4
  51. package/lib/ops/candidates.js +11 -3
  52. package/lib/ops/compat.js +46 -4
  53. package/lib/ops/memory.js +78 -9
  54. package/lib/ops/prompts.js +49 -5
  55. package/lib/ops/quick-prompts.js +24 -2
  56. package/lib/ops/scene-records.js +7 -0
  57. package/lib/ops/scene-sync.js +23 -4
  58. package/lib/ops/scope.js +1093 -0
  59. package/lib/ops/sessions.js +5 -2
  60. package/lib/ops/snapshot.js +55 -20
  61. package/lib/ops/state-doctor.js +39 -4
  62. package/lib/ops/trash.js +12 -1
  63. package/lib/paths.js +50 -3
  64. package/lib/prompts/preset-id.js +4 -0
  65. package/lib/prompts/project-instructions.js +162 -0
  66. package/lib/prompts/quick-service.js +5 -4
  67. package/lib/prompts/service.js +20 -9
  68. package/lib/request-gate.js +6 -4
  69. package/lib/scene-linkage.js +12 -0
  70. package/lib/scene-prompt-sync.js +1 -1
  71. package/lib/scenes/candidates.js +8 -1
  72. package/lib/scope/intent-store.js +105 -0
  73. package/lib/scope/intent.js +376 -0
  74. package/lib/scope/resolve.js +190 -0
  75. package/lib/scope/scope-overrides.js +894 -0
  76. package/lib/scope/store.js +262 -0
  77. package/lib/scope/workspace-key.js +64 -0
  78. package/lib/sessions/history.js +3 -2
  79. package/lib/settings-sidecars.js +82 -19
  80. package/lib/sidebar-settings.js +13 -0
  81. package/lib/skills/catalog.js +206 -33
  82. package/lib/skills/core.js +1 -1
  83. package/lib/skills/frontmatter.js +121 -0
  84. package/lib/skills/service.js +145 -20
  85. package/lib/stale-write.js +74 -0
  86. package/lib/subagents/catalog.js +47 -13
  87. package/lib/subagents/persona-parse.js +26 -5
  88. package/lib/subagents/persona-write.js +11 -7
  89. package/lib/subagents/service.js +3 -2
  90. package/lib/subagents/tools.js +78 -8
  91. package/lib/token-config.js +25 -5
  92. package/lib/tool-table-switch.js +141 -49
  93. package/lib/tools/deps.js +151 -5
  94. package/lib/tools/mcp.js +189 -39
  95. package/lib/tools/memory.js +103 -18
  96. package/lib/tools/prompt.js +61 -9
  97. package/lib/tools/remove.js +46 -21
  98. package/lib/tools/scene.js +120 -26
  99. package/lib/tools/skills.js +191 -30
  100. package/lib/tools/subagent.js +52 -20
  101. package/lib/tools/table.js +48 -11
  102. package/lib/trash-retention.js +3 -2
  103. package/lib/update-check.js +218 -0
  104. package/locale/en.json +6 -0
  105. package/locale/zh.json +6 -0
  106. package/package.json +19 -14
package/lib/tools/deps.js CHANGED
@@ -37,16 +37,16 @@ export function toolNameList(list) {
37
37
  export async function locateSkillRoot(skillsOps, name) {
38
38
  const wanted = String(name || '').trim();
39
39
  if (wanted === '')
40
- return { ok: true, root: null, roots: [] };
40
+ return { ok: true, root: null, canonical: null, roots: [], matches: [] };
41
41
  let state;
42
42
  try {
43
43
  state = await skillsOps['skill-state']({});
44
44
  }
45
45
  catch {
46
- return { ok: false, root: null, roots: [] };
46
+ return { ok: false, root: null, canonical: null, roots: [], matches: [] };
47
47
  }
48
48
  if (!state || state.ok === false)
49
- return { ok: false, root: null, roots: [] };
49
+ return { ok: false, root: null, canonical: null, roots: [], matches: [] };
50
50
  const roots = [];
51
51
  const hits = [];
52
52
  for (const root of (state.data && state.data.roots) || []) {
@@ -56,11 +56,157 @@ export async function locateSkillRoot(skillsOps, name) {
56
56
  if (String(skill.declaredName || skill.name || '') !== wanted && String(skill.name || '') !== wanted)
57
57
  continue;
58
58
  hits.push({
59
- rootKey: String(root.key || ''),
59
+ root: String(root.key || ''),
60
+ canonical: String(skill.declaredName || skill.name || wanted),
60
61
  shadowedBy: skill.shadowedBy && skill.shadowedBy.root ? String(skill.shadowedBy.root) : '',
61
62
  });
62
63
  }
63
64
  }
64
65
  const winner = hits.find((hit) => hit.shadowedBy === '') || hits[0];
65
- return { ok: true, root: winner ? winner.rootKey : null, roots };
66
+ return { ok: true, root: winner ? winner.root : null, canonical: winner ? winner.canonical : null, roots, matches: hits };
67
+ }
68
+ /**
69
+ * 取本会话的身份与覆盖。宿主没接这条通道、或取不到会话 → `null`(= 按全局)。
70
+ *
71
+ * 与 `overridesOfExec`(subagents/tools.ts)同一条纪律:解析失败不抛给模型 ——
72
+ * 一次"读不到会话"不该让列表工具整个失败。
73
+ */
74
+ export function sessionScopeOf(deps, agent) {
75
+ if (deps.sessionScope === undefined)
76
+ return null;
77
+ try {
78
+ return deps.sessionScope(agent);
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ /**
85
+ * 全局动作的回执尾注(0.21.2):**只在这个对话真有该域覆盖时**才出现。
86
+ *
87
+ * 为什么需要:`*_save` / `*_remove` / `prompt_manager_*` 动的是磁盘上的那一份 —— 技能、
88
+ * 人设、场景、MCP 服务器、提示词预设都是**机器级**对象,没有"本会话的一份"。模型据此
89
+ * 回一句"已删除"时,用户很容易读成"只在这个对话里删掉了"。而这一层恰恰最容易撞上
90
+ * 会话覆盖:本会话把它关着、用户说"删了吧",删完之后那条覆盖还留着(读时忽略,对账才清),
91
+ * 界面上那一格仍标着「本会话」。
92
+ *
93
+ * 没有覆盖时返回 `''` —— 绝大多数调用走这条路,一个字都不多付。
94
+ */
95
+ export function globalActionNote(deps, agent, domain, noun) {
96
+ const scoped = sessionScopeOf(deps, agent);
97
+ const n = domain === 'scene'
98
+ ? (scoped?.scope?.scene === undefined ? 0 : 1)
99
+ : (() => {
100
+ const map = scoped?.scope?.[domain];
101
+ return map === undefined ? 0 : Object.keys(map).length;
102
+ })();
103
+ if (n === 0)
104
+ return '';
105
+ return '\nnote: this is a global change (every conversation). This conversation has ' + n +
106
+ ' of its own ' + noun + ' switch(es), which still take precedence here — clear them if this change should apply to it too.';
107
+ }
108
+ /**
109
+ * 一条工具这次的 `scope` 到底走哪条路(0.21.2+ 全局粒度)。
110
+ *
111
+ * 唯一的判定点。三种粒度下 `scope` 的**默认值**不同:
112
+ *
113
+ * · `global` —— 省略 / `"session"` / `"global"` 全部走全局。会话层根本不存在,
114
+ * 没有"只改这一处"这回事;把 session 当全局是**正确**而非宽松。
115
+ * · `session` —— 省略 = 本对话;`"global"` = 机器级。
116
+ * · `workspace` —— 省略 = 本工作区(键是 `ws:<cwd>`);`"global"` = 机器级。
117
+ *
118
+ * 为什么收成一处:10 个工具各写一遍 `String(args.scope || 'session') !== 'global'`,
119
+ * 加粒度时必然漏掉一两处 —— 漏掉的那处会在全局粒度下静默写进空键。
120
+ */
121
+ export function effectiveScope(deps, args) {
122
+ const raw = args?.scope;
123
+ if (deps.scopeMode?.() === 'global')
124
+ return 'global';
125
+ return raw === 'global' ? 'global' : 'session';
126
+ }
127
+ /** 会话层此刻存在吗(全局粒度下不存在)。用于回执措辞与"要不要过会话锁"。 */
128
+ export function sessionLayerOn(deps) {
129
+ return deps.scopeMode?.() !== 'global';
130
+ }
131
+ /**
132
+ * 全局动作的**歧义守卫**(0.21.2,计划 §8.2 的「会话层下拒绝并说明」)。
133
+ *
134
+ * 只加在**有会话层同胞**的那几条上:技能 / 人设 / 场景 / MCP 服务器各自都有一条
135
+ * `*_manager_switch` 能按会话改「看不看得到」,于是「删掉它」在会话语境里天然有歧义 ——
136
+ * 用户说的可能是「这个对话里别再用它」,而这条工具动的是磁盘上的那一份。
137
+ *
138
+ * **缺省不拒**(`scope` 省略 = 全局,与上一版逐字相同):这几条工具每个都要付 token,
139
+ * 而"每次删除都先失败一次再重试"是纯摩擦 —— 模型并不知道用户此刻在面板里编辑哪一层。
140
+ * 真正要挡的是**模型自己以为在改会话**:它显式写了 `scope: "session"` 时,这里当场纠回来,
141
+ * 而不是静默地改掉全局。
142
+ *
143
+ * 全局粒度下直接放行(`isolationOff`):那一档没有会话层,`scope: "session"` 的所指就是
144
+ * 全局,拒绝它只会让模型白跑一趟。
145
+ *
146
+ * 加在:技能 / 人设 / 场景 / MCP 四条 `*_save`、五条 `*_remove`。
147
+ * 不加在:`memory_manager_save`(落 `<场景>/<名字>`,写哪儿由 id 自己说清)、
148
+ * `*_manager_switch`(它们本来就按会话写,`scope` 是真的)。
149
+ * `prompt_manager_apply` 也从清单里去掉了(2026-10-21 审查 P2-2):它的参数表里没有
150
+ * `scope`,守卫读不到东西 —— 模型按 schema 不可能传,这条守卫等于永不触发,留着只会
151
+ * 让人以为它被守住了。提示词只有全局一层,参数表已经说清。
152
+ */
153
+ export function requireGlobalScope(args, what, isolationOff = false) {
154
+ if (isolationOff)
155
+ return;
156
+ const scope = args?.scope;
157
+ if (scope === undefined || scope === 'global')
158
+ return;
159
+ throw new Error('this is a global action (' + what + ' exist once for the whole machine, so there is no per-conversation version to change). '
160
+ + 'Drop scope, or pass scope="global", to change the machine-wide one. '
161
+ + 'To change what THIS conversation sees instead, use the matching *_manager_switch.');
162
+ }
163
+ /**
164
+ * 模型面 `scope` 参数的共同措辞(0.21.2 描述瘦身)。
165
+ *
166
+ * 为什么收成一处:同一件事(这一格只有全局一层)此前在 14 个参数上各写一套,最长的一条
167
+ * 563 字符 —— 这些字节每个请求都跟着工具表发一遍。可写会话层的那几条各域还要补自己的
168
+ * 存储名与租约语义,所以只收这一类。
169
+ *
170
+ * `unless isolation is off`(0.21.2+):全局粒度下没有会话层,`scope: "session"` 的所指
171
+ * 就是全局,守卫也放行 —— 只说"被拒"会让模型在一个合法的调用前先自我否决。
172
+ */
173
+ export function scopeGlobalOnlyDesc(what, instead) {
174
+ return 'Always global — ' + what + ' ("session" is refused unless isolation is off); ' + instead + '.';
175
+ }
176
+ /**
177
+ * 模型面「会话层」`scope` 参数的共同措辞(2026-10-21 审查 P0-1)。
178
+ *
179
+ * 为什么不能写死 "this conversation only":隔离粒度可切(`scope-mode-set`)。切到工作区后
180
+ * `session` 这一档写的是 `ws:<cwd>` 那一格 —— **同工作区的每个对话都读它**;关掉隔离
181
+ * (`global`)之后连这一格都没有,写的就是机器级那一份。
182
+ *
183
+ * 所以措辞必须**对三种粒度同时成立**:先点名「这个对话」,再补上两档更宽的情形。
184
+ * 原措辞 "this conversation only; invisible to other conversations" 在工作区粒度下
185
+ * 是假话 —— 用户说「只在这个对话关掉」,agent 照做,实际把同工作区另外几个对话一起关了。
186
+ *
187
+ * 尾注 `tail` 由各域自己补(租约语义、状态文件位置、是否切运行时)。
188
+ */
189
+ export function scopeSessionDesc(tail) {
190
+ return 'session (default) = this conversation; its whole workspace under workspace isolation; machine-wide once isolation is off. ' + tail;
191
+ }
192
+ /**
193
+ * 会话层写入回执的统一后缀(2026-10-21 审查 P0-1 延伸)。
194
+ *
195
+ * 与 `scopeSessionDesc` 同一件事,但用在**回执**上:原文五处都写 "**for this conversation
196
+ * only**",在工作区粒度下是同一个问题 —— 写的是 `ws:<cwd>` 那一格,同工作区的每个对话都读它。
197
+ *
198
+ * 只在会话层真的被写到时才用。全局粒度下 `effectiveScope` 会把所有写入导向全局,
199
+ * 回执走各域原有的"机器级"措辞,不会到这里。
200
+ *
201
+ * 回执不是常驻成本(只在调用时出现一次),所以这里可以写全,不必像工具描述那样抠字:
202
+ * agent 会把这句话原样转述给用户,含糊的措辞比长一点的措辞贵得多。
203
+ */
204
+ export function scopeOnlyNote() {
205
+ return ' **for this scope only** (this conversation, or every conversation in its workspace under workspace isolation)';
206
+ }
207
+ /** 全局粒度下写入回执的说明:让 agent 别把这句转述成"只影响这个对话"。 */
208
+ export function isolationOffNote(deps) {
209
+ return deps.scopeMode?.() === 'global'
210
+ ? ' Isolation is off (global mode), so this is the machine-wide setting — every conversation sees it.'
211
+ : '';
66
212
  }
package/lib/tools/mcp.js CHANGED
@@ -26,7 +26,7 @@
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 { text } from './deps.js';
29
+ import { effectiveScope, globalActionNote, isolationOffNote, requireGlobalScope, scopeGlobalOnlyDesc, scopeOnlyNote, scopeSessionDesc, sessionLayerOn, text } from './deps.js';
30
30
  /** 「去看清单」那句:`mcp_manager_list` 不在模型手里时不能点名它(调用方按 `toolVisibleFor` 决定给不给)。 */
31
31
  const MCP_LIST_HINT = ' (see mcp_manager_list — all=true also lists disabled ones)';
32
32
  /**
@@ -84,16 +84,16 @@ export function buildMcpTools(deps) {
84
84
  const listHint = (agent) => (deps.toolVisibleFor('mcp_manager_list', agent) ? MCP_LIST_HINT : '');
85
85
  register(defineTool({
86
86
  name: 'mcp_manager_list',
87
- // 注入段与本工具的关系要**如实说成筛过的视图**(而非"同一份清单"):注入段只列可用 +
88
- // 曾连上现掉线的服务器(停用的不进),也不带 level / loader / 工具数。把这个盲区写出来
89
- // 是行动依据 —— 模型要知道"停用的那台去哪查"就得靠这句(all=true)。
87
+ // 注入段与本工具的关系要**如实说成筛过的视图**(而非"同一份清单"):注入段只列当前真有
88
+ // 工具注册的服务器(停用与掉线的都不进),也不带 level / loader / 工具数。把这个盲区写出来
89
+ // 是行动依据 —— 模型要知道"停用 / 掉线的那台去哪查"就得靠这句(all=true)。
90
90
  //
91
91
  // 2026-10-15 注入文本审查:删掉两处白付的 token ——
92
- // ① 括号里那句把 "Current MCP servers" reminder 的**内容**逐项列了一遍(可用 / 曾连上 /
92
+ // ① 括号里那句把 "Current MCP servers" reminder 的**内容**逐项列了一遍(可用 / 工具全停 /
93
93
  // 备注 / 停用不进),而那段 reminder 每轮就在模型上下文里,它自己看得到;
94
94
  // ② `where loader:on:<phase> is the loader's current phase` —— 用自己解释自己
95
95
  // (phase 就是 phase),零信息。字段名本身留在输出里,模型照抄即可。
96
- description: 'List configured MCP servers (level project|global; enabled state; live loader status; tool count excluding switched-off tools; user hint). The "Current MCP servers" reminder is a filtered view; this tool is the raw one — defaults to enabled servers, all=true for every configured one. Pass tools=true to list each server\'s tool names.',
96
+ description: 'List configured MCP servers (level, enabled state, loader status, tool count excluding switched-off ones, hint). The "Current MCP servers" reminder is a filtered view; this is the full one — all=true also includes disabled servers. Pass tools=true for each server\'s tool names.',
97
97
  parameters: {
98
98
  all: { type: 'boolean', description: 'Include disabled servers (default false).' },
99
99
  tools: { type: 'boolean', description: 'Also list each server\'s tool names, marking the switched-off ones (default false).' },
@@ -112,14 +112,41 @@ export function buildMcpTools(deps) {
112
112
  const all = r.rows || [];
113
113
  // 默认只列「已启用」的(用户裁定 2026-09-16,与技能 / 记忆列表同口径):停用的服务器
114
114
  // 模型调不到,列出来只是噪音。表头给出全量口径,所以不会变成盲区。
115
- const shown = showAll ? all : all.filter((x) => !x.disabled);
115
+ // 会话层(0.21.2):本会话隐藏的服务器 —— 它们**此刻一条工具都调不到**,与全局停用同形。
116
+ // 默认口径下按停用处理(不列);`all=true` 时列出来并标注,否则模型会以为这台服务器不存在。
117
+ // 逐行问谓词(0.21.2):行数组就是全集,判据(覆盖 → 场景层 → 基线)在 index.ts 一份。
118
+ const offHere = new Set();
119
+ if (deps.sessionHiddenServer) {
120
+ for (const x of all) {
121
+ if (deps.sessionHiddenServer(exec && exec.agent, String(x.serverName)))
122
+ offHere.add(String(x.serverName));
123
+ }
124
+ }
125
+ const isOff = (x) => x.disabled === true || offHere.has(String(x.serverName));
126
+ const shown = showAll ? all : all.filter((x) => !isOff(x));
116
127
  const lines = [];
117
128
  for (const x of shown) {
118
129
  const note = normalizeMcpNote(x.notes, DEFAULT_MCP_NOTE_MAX_LENGTH);
119
130
  // 工具数 = 可用数(停用表扣减后):段里给模型的是同一个口径,模型据此与
120
131
  // 自己 schema 里的 `mcp__*` 工具对得上;被场景收窄 / 手动关掉的工具不算。
121
132
  const usableTools = typeof x.enabledToolCount === 'number' ? x.enabledToolCount : x.toolCount;
122
- lines.push('server:' + x.serverName + ' | level:' + x.level + ' | ' + (x.disabled ? 'disabled' : 'enabled') +
133
+ // 「本会话关掉」必须与「全局停用」分开说:前者换个对话就回来了,后者要改配置。
134
+ // 0.21.2 起还有第三种:**全局意图 off、但本会话认领着它**(租约)—— 对这里调用
135
+ // 模型的那个会话来说它是可用的,但别的对话看不到;不说清就会被读成"全局开着"。
136
+ const serverName = String(x.serverName);
137
+ const globalOn = x.intent === 'blocked' ? false : (typeof x.globalOn === 'boolean' ? x.globalOn : x.disabled !== true);
138
+ const sessionOff = offHere.has(serverName);
139
+ const leases = typeof x.leaseCount === 'number' ? x.leaseCount : 0;
140
+ const state = x.intent === 'blocked'
141
+ ? 'stopped-machine-wide (every conversation)'
142
+ : !globalOn
143
+ ? (sessionOff
144
+ ? 'disabled-globally' + (leases > 0 ? ' (kept running by ' + leases + ' conversation(s))' : '')
145
+ : 'enabled-in-this-conversation (global: off' + (leases > 0 ? ', kept running by ' + leases + ' conversation(s)' : '') + ')')
146
+ : sessionOff
147
+ ? 'off-here (global: enabled)'
148
+ : 'enabled';
149
+ lines.push('server:' + x.serverName + ' | level:' + x.level + ' | ' + state +
123
150
  (x.live ? ' | loader:' + (x.live.enabled ? 'on' : 'off') + (x.live.phase ? ':' + x.live.phase : '') : '') +
124
151
  (typeof usableTools === 'number' ? ' | tools:' + usableTools : '') +
125
152
  (note ? ' | user-hint:' + note : ''));
@@ -130,6 +157,11 @@ export function buildMcpTools(deps) {
130
157
  // **不调 `mcpm-tools-refresh`**:那个会临时起进程(npx 冷启动可能几十秒),
131
158
  // 那是界面上的显式动作,不该由一次列表调用顺手触发。
132
159
  const t = await deps.mcpmTools({ serverName: String(x.serverName) });
160
+ // 停用表读不出来:下面每一行都标 (off)(执行侧确实全拒),但必须说清原因 ——
161
+ // 否则模型会读成"用户把这些工具关了",进而去建议用户打开它们。
162
+ if (t && t.disabledState === 'unknown') {
163
+ lines.push(' (disabled-tools table unreadable: every mcp__ tool is refused until it is repaired)');
164
+ }
133
165
  const items = t && t.ok !== false ? (t.tools || []) : [];
134
166
  if (!items.length) {
135
167
  lines.push(' ' + (x.disabled ? '(tools not recorded: server is off)' : '(no tools recorded)'));
@@ -137,10 +169,18 @@ export function buildMcpTools(deps) {
137
169
  }
138
170
  lines.push(' tools: ' + items.map((it) => it.name + (it.enabled === false ? ' (off)' : '')).join(', '));
139
171
  }
172
+ // 会话层(0.21.2,计划 §8.2「mcp_manager_list 标注本会话可见性」):本会话停用的服务器
173
+ // 与全局停用**同形**(默认不列、all=true 标注),但两者的含义完全不同 —— 前者换个对话
174
+ // 就回来,后者要改配置。表头点一句,模型才不会把这份清单当成"这台机器的配置"。
175
+ const sessionLine = offHere.size === 0
176
+ ? ''
177
+ : '\n' + offHere.size + ' server(s) are switched off here (' +
178
+ [...offHere].join(', ') + ') — the connection is still up, and conversations outside this scope keep them.\n';
140
179
  const header = 'MCP servers: ' + (showAll
141
180
  ? all.length + ' configured'
142
181
  : shown.length + ' enabled of ' + all.length + ' configured' +
143
- (shown.length === all.length ? '' : ' (pass all=true for every configured server)')) + '\n';
182
+ (shown.length === all.length ? '' : ' (pass all=true for every configured server)')) +
183
+ (sessionLine === '' ? '\n' : sessionLine);
144
184
  // 注入边界:压制型预设(persona complete / 关闭运行时上下文,如极简)下本插件
145
185
  // 默认不注入 —— 模型只有 mcp__* 的工具名与参数,没有服务级信息。不说明的话,
146
186
  // 模型会把「能调用这些工具」当成「已经知道有哪些 server、用户给它们写了什么备注」。
@@ -155,32 +195,58 @@ export function buildMcpTools(deps) {
155
195
  // 让它在三个动词里选一个,比让它猜两个布尔的组合省一次往返。
156
196
  // `restart` 的含义只在 `action` 参数里说一次(2026-10-15 注入文本审查):描述里那句
157
197
  // "(reconnects and re-syncs tools)" 与参数说明逐字重复,而模型读参数时两处都在手上。
158
- description: 'Turn one configured MCP server on or off, or restart it. Pass `tool` to switch just that tool. Blocked while the active scene is locked — except restart, which is the recovery path. Only when the user asks or approves.',
198
+ 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). Only when the user asks or approves.',
159
199
  parameters: {
160
200
  // 出口必须指向**常驻**来源,不能指向 `mcp_manager_list`(2026-10-14 对抗性审查 P0-1):
161
201
  // 那条工具在出厂默认里就是关着的,`listHint()` 在它不可见时返回空串,于是猜错名字时的
162
202
  // 报错退化成「没有这台服务器:<你猜的>」—— 一个字都不告诉它还能去哪看。
163
203
  // 指向模型自己的工具表(`mcp__<server>__<tool>` 就在它的 schema 里)与常驻注入段,
164
204
  // 这两条**不需要任何工具可见**就成立。
165
- server: { type: 'string', required: true, description: 'Server name, as it appears in your own `mcp__<server>__<tool>` tool names (the "Current MCP servers" reminder lists the usable ones).' },
166
- action: { type: 'string', required: true, enum: ['on', 'off', 'restart'], description: 'on = enable, off = disable, restart = reconnect and re-sync tools.' },
205
+ server: { type: 'string', required: true, description: 'Server name — the one in your own `mcp__<server>__<tool>` names.' },
206
+ action: { type: 'string', required: true, enum: ['on', 'off', 'restart', 'stop'], description: 'on = enable, off = disable, restart = reconnect and re-sync tools, stop = disable and disconnect anything still using it.' },
167
207
  level: { type: 'string', description: 'project or global — only to disambiguate same-name servers.' },
168
- tool: { type: 'string', description: 'One tool name on that server (no mcp__ prefix). Only for on/off.' },
208
+ // 支持数组(2026-10-21 审查 P2-3):关 8 个工具原本要 8 次调用,每次都带着整份工具表
209
+ // 重新推理一遍 —— 那是这份工具集里最贵的开销,而工具描述本身只占百分之几。
210
+ tool: { type: 'array', items: { type: 'string' }, description: 'Tool name(s) on that server (no mcp__ prefix) — one or several. Only for on/off.' },
211
+ // 决策 10(2026-10-19):默认只改**这个对话**,别的对话不受影响。写全局要显式说明。
212
+ // 0.21.2:开启一台机器级关着的服务器时,那一步在全局发生(连接是进程级的)—— 租约
213
+ // 这个词一句带过就够,别的对话看不到它。
214
+ scope: { type: 'string', enum: ['session', 'global'], description: scopeSessionDesc('a server it turns on runs as a lease, invisible outside that scope (isolation on only). global = every conversation (off keeps leased connections running, stop cuts them). restart / stop are always global.') },
169
215
  },
170
216
  output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
171
217
  async execute(args, exec) {
172
218
  const action = String((args && args.action) || '');
173
- if (action !== 'on' && action !== 'off' && action !== 'restart') {
174
- throw new Error('action must be on / off / restart (got: ' + (action || '(empty)') + ')');
219
+ if (action !== 'on' && action !== 'off' && action !== 'restart' && action !== 'stop') {
220
+ throw new Error('action must be on / off / restart / stop (got: ' + (action || '(empty)') + ')');
175
221
  }
176
222
  const server = String((args && args.server) || '').trim();
177
- const tool = args && args.tool !== undefined ? String(args.tool).trim() : '';
178
- if (tool !== '' && action === 'restart') {
179
- throw new Error('restart is a whole-server action (off, wait for it to drop, then back on at its previous state); a single tool cannot be restarted');
223
+ // 单值仍然接受(旧提示词 / 手写调用),数组是新增的批量形态。
224
+ const rawTool = args && args.tool !== undefined && args.tool !== null ? args.tool : undefined;
225
+ const tools = (Array.isArray(rawTool) ? rawTool : rawTool === undefined ? [] : [rawTool])
226
+ .map((t) => String(t).trim())
227
+ .filter((t) => t !== '');
228
+ if (tools.length > 0 && (action === 'restart' || action === 'stop')) {
229
+ throw new Error('restart and stop are whole-server actions (' + (action === 'stop' ? 'stopping cuts off every conversation using it' : 'off, wait for it to drop, then back on at its previous state') + '); a single tool cannot be ' + action + 'ped');
180
230
  }
231
+ // 决策 10:默认写**本会话**(别的对话不受影响),`scope: "global"` 才改补丁。
232
+ // 两条边界决定了这里的分支:
233
+ // · restart 是进程级动作(要真停一次再起),没有会话版本 —— 永远走全局;
234
+ // · 会话层写不碰补丁、不进场景档案,所以不需要冻结守卫与 syncSwitchToScene
235
+ // —— 例外是"在本会话里打开一台全局关着的服务器":连接是进程级的,那一步把它
236
+ // 作为本会话的租约跑起来(见下面的 sessionOnly 分支)。
237
+ const scope = effectiveScope(deps, args);
238
+ // 调用方是否**以为**自己在改会话层(省略 scope 也算)。全局粒度下这个以为会落空,
239
+ // 回执必须点出来 —— 否则 agent 会把"机器级改动"转述成"只影响这个对话"。
240
+ const askedForSession = (args && args.scope) !== 'global';
241
+ // restart 与 stop 都是机器级动作(重启要真停一次;彻底停止定义上就压过所有会话),
242
+ // 没有会话版本 —— 与 restart 同一条,忽略 scope 并如实点出来。
243
+ const sessionOnly = scope !== 'global' && action !== 'restart' && action !== 'stop';
181
244
  // on|off 会写补丁(`mcpm-set-enabled` / `mcpm-tool-enabled` 在登记表里是 frozen),
182
245
  // 所以过场景冻结守卫;restart 不过 —— 它是锁定期间唯一的恢复入口(见文件头)。
183
- if (action !== 'restart') {
246
+ // 会话层写入(`sessionOnly`)也不被场景锁挡住:它写的是侧车,与全局状态无关
247
+ // (决策 11,与面板的 `scopeWriteLocked()` 同口径)。那个"租约跑起来"的例外
248
+ // 同样不受场景锁管:它是进入本会话的前置条件,不是一次独立的全局配置改动。
249
+ if (action !== 'restart' && !sessionOnly) {
184
250
  const blocked = await deps.lockedSceneGuard();
185
251
  if (blocked)
186
252
  throw new Error(blocked);
@@ -191,24 +257,101 @@ export function buildMcpTools(deps) {
191
257
  const level = args && args.level !== undefined ? String(args.level) : undefined;
192
258
  const row = locate(list.rows || [], server, level, listHint(exec && exec.agent));
193
259
  const enabled = action === 'on';
194
- if (tool !== '') {
195
- const r = await deps.mcpmToolEnabled({ serverName: String(row.serverName), tool, enabled });
196
- if (!r || r.ok === false)
197
- throw new Error((r && r.error) || 'failed to switch this tool');
198
- // 与面板同一条同步:`mcpm-tool-enabled` 在登记表里带 syncsArchive,漏了就是
199
- // "页面拨的进档案、模型拨的不进"。
200
- const syncErr = await deps.syncSwitchToScene('mcpm-tool-enabled', { serverName: String(row.serverName), tool, enabled });
260
+ if (sessionOnly) {
261
+ const setter = deps.sessionScopeSet;
262
+ if (setter === undefined)
263
+ throw new Error('per-conversation switches are unavailable in this host: pass scope="global" to change the config for every conversation');
264
+ // 开启一台全局关着的服务器时,op 侧把它作为本会话的租约跑起来(连接是进程级的,
265
+ // 没有会话版本)—— 用户裁定「仍按租约运行」。那一步的影响由回执里的 `warnings`
266
+ // 如实带出来(哪些临时跑起来了),这里不重写一份判定。
267
+ const one = async (domain, key) => {
268
+ const r = await setter(exec && exec.agent, domain, key, enabled);
269
+ if (!r || r.ok === false)
270
+ throw new Error((r && r.error) || 'failed to switch this here');
271
+ return r;
272
+ };
273
+ const globalNote = ' Pass scope="global" to change it for every conversation.';
274
+ // 回执必须说清写的是哪一层:用户看到「已停用」而全局其实没变时,才不会以为别的对话也变了。
275
+ // 措辞用 `scopeOnlyNote()`(不再写死「本对话」,见 2026-10-21 审查 P0-1)。
276
+ if (tools.length === 0) {
277
+ const r = await one('mcp', String(row.serverName));
278
+ const warnings = r.warnings !== undefined && r.warnings.length > 0 ? '\n' + r.warnings.join('\n') : '';
279
+ return 'OK: ' + String(row.serverName) + ' now ' + (enabled ? 'enabled' : 'disabled') + scopeOnlyNote() +
280
+ (r.cleared === true ? ' (that matches what this scope would see anyway, so the override was removed)' : '') + warnings +
281
+ (warnings === '' ? '\nThe global setting is unchanged; conversations outside this scope keep theirs.' : '') + globalNote;
282
+ }
283
+ let cleared = 0;
284
+ const warningsAll = [];
285
+ for (const t of tools) {
286
+ const r = await one('mcpTools', String(row.serverName) + '/' + t);
287
+ if (r.cleared === true)
288
+ cleared += 1;
289
+ if (r.warnings !== undefined)
290
+ warningsAll.push(...r.warnings);
291
+ }
292
+ const what = tools.length === 1
293
+ ? 'tool ' + tools[0] + ' on ' + String(row.serverName)
294
+ : tools.length + ' tools on ' + String(row.serverName) + ' (' + tools.join(', ') + ')';
295
+ const warnings = warningsAll.length > 0 ? '\n' + warningsAll.join('\n') : '';
296
+ return 'OK: ' + what + ' now ' + (enabled ? 'enabled' : 'disabled') + scopeOnlyNote() +
297
+ (cleared === tools.length ? ' (that matches what this scope would see anyway, so the overrides were removed)' : '') + warnings +
298
+ (warnings === '' ? '\nThe global setting is unchanged; conversations outside this scope keep theirs.' : '') + globalNote;
299
+ }
300
+ // 走到这里说明这次是**全局**动作:显式 scope="global"、restart / stop(它们没有
301
+ // 会话版本),或者隔离被关掉了(全局粒度)。默认值是 session,所以模型很可能以为
302
+ // 自己在改本会话;不点一句就是一次静默的「改了全局」。
303
+ const scopeIgnored = action === 'restart'
304
+ ? '\nnote: this one is global (a restart has no per-conversation version); every conversation is affected.'
305
+ : action === 'stop'
306
+ ? '\nnote: stop is global — it ends the server even for conversations still using it.'
307
+ : (scope === 'global' && askedForSession ? isolationOffNote(deps) : '');
308
+ if (tools.length > 0) {
309
+ // 批量时逐条写、逐条同步场景档案;任一失败就抛,回执里说清是哪一条。
310
+ const syncErrs = [];
311
+ for (const t of tools) {
312
+ const r = await deps.mcpmToolEnabled({ serverName: String(row.serverName), tool: t, enabled });
313
+ if (!r || r.ok === false)
314
+ throw new Error('failed to switch tool ' + t + ': ' + ((r && r.error) || 'unknown error'));
315
+ // 与面板同一条同步:`mcpm-tool-enabled` 在登记表里带 syncsArchive,漏了就是
316
+ // "页面拨的进档案、模型拨的不进"。
317
+ const syncErr = await deps.syncSwitchToScene('mcpm-tool-enabled', { serverName: String(row.serverName), tool: t, enabled });
318
+ if (syncErr)
319
+ syncErrs.push(tools.length === 1 ? String(syncErr) : t + ': ' + String(syncErr));
320
+ }
201
321
  // 整台停用时,工具级开关在运行时本来就不生效(那个工具压根不存在)—— 不说的话
202
322
  // 模型会以为已经生效。与记忆族"启用了一条不在启用场景里的记忆"同一条理由。
203
323
  const offNote = row.disabled ? ' (note: the whole server is off right now, so this tool-level switch only takes effect once the server is on)' : '';
204
- return 'OK: ' + String(row.serverName) + ' tool ' + tool + ' now ' + (enabled ? 'enabled' : 'disabled') + offNote +
205
- (syncErr ? '\nWARN: the current scene archive was not synced (' + syncErr + ')' : '');
324
+ const what = tools.length === 1
325
+ ? 'tool ' + tools[0]
326
+ : tools.length + ' tools (' + tools.join(', ') + ')';
327
+ return 'OK: ' + String(row.serverName) + ' ' + what + ' now ' + (enabled ? 'enabled' : 'disabled') + offNote +
328
+ (syncErrs.length > 0 ? '\nWARN: the current scene archive was not synced (' + syncErrs.join('; ') + ')' : '') + scopeIgnored;
206
329
  }
207
330
  if (action === 'restart') {
208
331
  const r = await deps.mcpmRestart({ id: row.id, level: row.level });
209
332
  if (!r || r.ok === false)
210
333
  throw new Error((r && r.error) || 'restart failed');
211
- return 'OK: ' + String(row.serverName) + ' (' + row.level + ') restarted';
334
+ return 'OK: ' + String(row.serverName) + ' (' + row.level + ') restarted' + scopeIgnored;
335
+ }
336
+ // 全局开关 = **意图**(0.21.2):off 不再立刻停 —— 还在用它的会话会按租约继续跑,
337
+ // 只有 stop(blocked)会连它们一起切断。直接写补丁会让"谁也看不到"与"连接停不停"
338
+ // 变成同一件事,那正是会话级开启串到新会话里的根源。
339
+ if (deps.scopeIntentSet) {
340
+ const value = action === 'stop' ? 'blocked' : enabled ? 'on' : 'off';
341
+ // 这一条走的是 handlers 表(与面板同一条路径):场景档案同步由那层包装做,
342
+ // 回执里的 `sceneSyncError` 才是"档案没跟上"的真相。
343
+ const r = await deps.scopeIntentSet('mcp', [String(row.serverName)], value);
344
+ if (!r || r.ok === false)
345
+ throw new Error((r && r.error) || 'failed to switch this server');
346
+ const syncErr = r.sceneSyncError ? String(r.sceneSyncError) : null;
347
+ const warnings = r.warnings !== undefined && r.warnings.length > 0 ? '\n' + r.warnings.join('\n') : '';
348
+ const what = action === 'stop'
349
+ ? 'stopped machine-wide (every conversation, including any that still had it on)'
350
+ : enabled
351
+ ? 'enabled for every conversation'
352
+ : 'disabled globally (conversations already using it keep the connection until none does; use stop to cut them off now)';
353
+ return 'OK: ' + String(row.serverName) + ' (' + row.level + ') now ' + what + warnings +
354
+ (syncErr ? '\nWARN: the current scene archive was not synced (' + syncErr + ')' : '') + scopeIgnored;
212
355
  }
213
356
  const r = await deps.mcpmSetEnabled({ id: row.id, level: row.level, enabled });
214
357
  if (!r || r.ok === false)
@@ -221,27 +364,31 @@ export function buildMcpTools(deps) {
221
364
  }));
222
365
  register(defineTool({
223
366
  name: 'mcp_manager_save',
224
- 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` to add a usage hint or fallback note. Blocked while the active scene is locked. Only on the user\'s instruction.',
367
+ 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.',
225
368
  parameters: {
226
369
  server: { type: 'string', required: true, description: 'Server name (1-32 chars, [A-Za-z0-9_-]) — the name the mcp__<server>__ tools use.' },
227
- transport: { type: 'string', description: 'streamable-http or stdio. Required when creating; omit = keep.' },
228
- url: { type: 'string', description: 'Server URL (streamable-http). Omit = keep.' },
229
- command: { type: 'string', description: 'Executable to spawn (stdio). Omit = keep.' },
230
- args: { type: 'string', description: 'Arguments, space or comma separated (stdio). Omit = keep.' },
231
- headers: { type: 'string', description: 'Extra headers, key=value per line (streamable-http). Omit = keep — omitting is what preserves the real secrets.' },
232
- env: { type: 'string', description: 'Extra env vars, key=value per line (stdio). Omit = keep.' },
370
+ transport: { type: 'string', description: 'streamable-http or stdio. Required when creating.' },
371
+ url: { type: 'string', description: 'Server URL (streamable-http).' },
372
+ command: { type: 'string', description: 'Executable to spawn (stdio).' },
373
+ args: { type: 'string', description: 'Arguments, space or comma separated (stdio).' },
374
+ headers: { type: 'string', description: 'Extra headers, key=value per line (streamable-http). Omitting it is what preserves the real secrets.' },
375
+ env: { type: 'string', description: 'Extra env vars, key=value per line (stdio).' },
233
376
  level: { type: 'string', description: 'project or global (project when creating); only needed for same-name servers.' },
234
377
  // 名字与注入段对齐(2026-10-14 对抗性审查 P1-2):注入段与工具输出都写 `user-hint`
235
378
  // (对应注入行里那句 `user hint:`),参数名跟着叫 `hint`,一份数据三个面一个词。
236
379
  // 「写什么」那半句已经由注入框架的 `how` 行逐字说过("选服务器之前先看一眼"),
237
380
  // 这里只留参数独有的信息:长度上限与截断行为(2026-10-14 审查 P2-4)。
238
- hint: { type: 'string', description: "Short hint for later (≤300 chars; longer is stored whole but truncated in listings). '' clears the existing hint; omit = keep." },
381
+ hint: { type: 'string', description: "Short hint for later (≤300 chars; longer is stored whole but truncated in listings). '' clears the existing hint." },
382
+ // 0.21.2:MCP 服务器是**机器级**配置(cordis 补丁),没有「本会话的一份」。这个参数只为一件事:
383
+ // 模型以为自己在改会话时,当场纠回来(见 deps.ts 的 requireGlobalScope)。
384
+ scope: { type: 'string', enum: ['session', 'global'], description: scopeGlobalOnlyDesc('the server config is machine-wide', 'hide a server here with mcp_manager_switch') },
239
385
  },
240
386
  output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
241
387
  async execute(args, exec) {
242
388
  const blocked = await deps.lockedSceneGuard();
243
389
  if (blocked)
244
390
  throw new Error(blocked);
391
+ requireGlobalScope(args, 'MCP servers', !sessionLayerOn(deps));
245
392
  const server = String((args && args.server) || '').trim();
246
393
  if (!server)
247
394
  throw new Error('missing argument: server (the server name)');
@@ -292,7 +439,9 @@ export function buildMcpTools(deps) {
292
439
  if (!n || n.ok === false)
293
440
  warn = '\nWARN: the server was created, but the hint was not written (' + ((n && n.error) || 'unknown reason') + ')';
294
441
  }
295
- return 'OK: created ' + r.row.id + ' at ' + r.row.level + warn;
442
+ // 会话层(0.21.2):服务器是**机器级**配置(cordis 补丁),本会话只能把它藏起来。
443
+ return 'OK: created ' + r.row.id + ' at ' + r.row.level + warn +
444
+ globalActionNote(deps, exec && exec.agent, 'mcp', 'MCP');
296
445
  }
297
446
  // ── 改:省略 = 保持,且必须**显式填回**(见文件头那条 parseKv 的坑)────────
298
447
  const cur = locate(hits, server, levelArg, listHint(exec && exec.agent));
@@ -392,7 +541,8 @@ export function buildMcpTools(deps) {
392
541
  if (ignored.length) {
393
542
  warn += '\nWARN: ' + ignored.join(' / ') + ' do not apply to the current transport (' + transport + ') and were ignored';
394
543
  }
395
- return 'OK: updated ' + String(cur.serverName) + ' (changed ' + changed.join(', ') + ')' + warn;
544
+ return 'OK: updated ' + String(cur.serverName) + ' (changed ' + changed.join(', ') + ')' + warn +
545
+ globalActionNote(deps, exec && exec.agent, 'mcp', 'MCP');
396
546
  },
397
547
  }));
398
548
  }