dsh-plugin-tool-management 0.22.1 → 0.22.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -10,6 +10,7 @@
10
10
  import { symbols } from '@deepseek-ai/cordis';
11
11
  import { defineTool as hostDefineTool } from '@deepseek-ai/dsh-tools';
12
12
  import { createRequire } from 'node:module';
13
+ import { AsyncLocalStorage } from 'node:async_hooks';
13
14
  import { randomUUID } from 'node:crypto';
14
15
  import { createHistoryDomain } from './sessions/history.js';
15
16
  import { createSkillsService, pluginLog } from './skills/service.js';
@@ -45,6 +46,7 @@ import { clearRuntimeNote, noteRuntime } from './compat/runtime-notes.js';
45
46
  import { reachNoticeForAgent } from './compat/preset-reach.js';
46
47
  import { installHttpApi } from './http-api.js';
47
48
  import { createMcpManager } from './mcp/manager.js';
49
+ import { createMcpPromptShadow } from './mcp/prompt-shadow.js';
48
50
  // 确认卡回显"新 URL"时要打码(查询串里的凭据不该明文进卡片),口径与列表视图同一份实现。
49
51
  import { maskUrlQuery } from './mcp/secret-guard.js';
50
52
  import { createCandidates } from './scenes/candidates.js';
@@ -236,8 +238,25 @@ export default {
236
238
  // (停用表丢掉一条 = 已停用的 MCP 工具重新可调用)。
237
239
  const hubLock = createHubFileLock(hubPath());
238
240
  let writeChain = Promise.resolve();
241
+ /**
242
+ * 「本条异步调用链已经持有写锁」的标记。
243
+ *
244
+ * 为什么必须可重入:锁内确实会回调别的域 —— MCP 改名 / 删台在锁内调
245
+ * `memoriesService.patchIndex` 同步场景档案,而记忆域自己也取锁。没有这个标记,
246
+ * 那条 op 会排在**自己**后面:不是报错,是永远不返回。
247
+ *
248
+ * 用 `AsyncLocalStorage` 而不是一个布尔:多个请求并发共用同一个进程,布尔会让后到的
249
+ * 请求误以为自己也持锁,直接跳过排队。
250
+ *
251
+ * ⚠️ 由此派生的**游离任务**(在临界区里 `void` 起、活过外层临界区)也会被算作"已持锁",
252
+ * 这类任务不得写 hub;现有调用点没有这种形状。
253
+ */
254
+ const writeLockScope = new AsyncLocalStorage();
239
255
  function withWriteLock(fn) {
240
- const run = writeChain.then(() => hubLock.run(fn), () => hubLock.run(fn));
256
+ if (writeLockScope.getStore() === true)
257
+ return fn();
258
+ const enter = () => writeLockScope.run(true, fn);
259
+ const run = writeChain.then(() => hubLock.run(enter), () => hubLock.run(enter));
241
260
  writeChain = run.then(() => undefined, () => undefined);
242
261
  return run;
243
262
  }
@@ -246,7 +265,29 @@ export default {
246
265
  // 来源裁剪为 dsh/agents/codex/claude);服务层把 core 的结果适配成 { op, args }
247
266
  // 协议,并在全局层与每个活动 agent 的 scope 内注册 manager provider:
248
267
  // rank 覆盖实现不改源文件的启停;外部来源由 provider 接入。
249
- const skillsService = createSkillsService(ctx);
268
+ /**
269
+ * 技能 provider 的**会话层**:官方技能服务问 provider「有哪些技能」时,provider 按
270
+ * **查看方**(官方传进来的 `options.scope` = 调用方 agent)那一层的生效值回答。
271
+ *
272
+ * 为什么必须有:策略表 / 来源状态是**机器级**的 —— 会话 A 开一条全局关着的技能,那条
273
+ * 必须临时落进机器级那张表才加载得了(官方 `skill` 工具只认那张表),于是**每个**
274
+ * 会话的清单里都看得见它。注入目录早就按会话过滤了(`renderSkillCatalog` 的 layer),
275
+ * 官方那份清单(宿主 `/` 菜单的「技能」段、官方 `skill` 工具的候选)没有 —— 那条串味
276
+ * 就留在那里:A 会话开的技能出现在 B / C 会话的菜单里。
277
+ *
278
+ * 两格与注入目录**同一份判据**(`skillViewOf` / `skillSourceViewOf`),不多定义第二套。
279
+ * 全局粒度没有会话层(`scopeKeyForAgent` 返回 null)→ 按机器级那一份,与面板一致。
280
+ */
281
+ const skillProviderSessionViewOf = (viewer) => {
282
+ const scopeKey = scopeKeyForAgent(viewer);
283
+ if (!scopeKey)
284
+ return undefined;
285
+ return {
286
+ skill: (key) => skillViewOf(scopeKey, key).visible,
287
+ source: (rootKey) => skillSourceViewOf(scopeKey, rootKey).visible,
288
+ };
289
+ };
290
+ const skillsService = createSkillsService(ctx, { sessionViewOf: skillProviderSessionViewOf });
250
291
  try {
251
292
  ctx.effect(() => skillsService.registerProviders(), 'dsh-plugin-tool-management: skills providers');
252
293
  }
@@ -867,6 +908,52 @@ export default {
867
908
  return undefined;
868
909
  return mcpVerdictOf(ctx, parts);
869
910
  }
911
+ /**
912
+ * agent 作用域上的 `systemPrompt` 服务(取不到返回 undefined)。
913
+ *
914
+ * 必须从 **agent.ctx.get** 取:Cordis 的 traceable 代理会把方法调用时的 `this.ctx`
915
+ * 换成取服务的那个作用域,`systemPrompt.section()` 才会注册到该 agent 的 scoped 层。
916
+ * 从插件根 ctx 取会把遮蔽段注册到全局层 —— 那会遮蔽所有 agent,而不是只遮蔽本会话。
917
+ */
918
+ function systemPromptServiceOf(agent) {
919
+ try {
920
+ const agentCtx = agent?.ctx;
921
+ const service = agentCtx && typeof agentCtx.get === 'function' ? agentCtx.get('systemPrompt') : undefined;
922
+ const candidate = service;
923
+ return candidate !== undefined && typeof candidate.section === 'function' && typeof candidate.getSectionOrder === 'function'
924
+ ? candidate
925
+ : undefined;
926
+ }
927
+ catch {
928
+ return undefined;
929
+ }
930
+ }
931
+ /** 跨会话 prompt 隔离:按 agent 作用域同名遮蔽官方 MCP 段(见 mcp/prompt-shadow.ts)。 */
932
+ const mcpPromptShadow = createMcpPromptShadow(systemPromptServiceOf);
933
+ /** 把名册同步到某个 agent 的 prompt 遮蔽段;失败只记在本地(不拖垮工具可见性)。 */
934
+ function syncMcpPromptShadows(agent, roster, resourceAvailable) {
935
+ try {
936
+ mcpPromptShadow.sync(agent, [...roster.names], roster.visible, { resourceAvailable });
937
+ }
938
+ catch { /* best effort */ }
939
+ }
940
+ /**
941
+ * 预热某个 agent 的 prompt 遮蔽段。
942
+ *
943
+ * 工具可见性重排是异步的;agent 刚创建时先主动算一趟,避免首轮系统提示词在重排完成前
944
+ * 就带上别的对话的服务器名 / instructions。失败与重排那条路一样是 best effort。
945
+ */
946
+ function warmMcpPromptShadows(agent) {
947
+ void (async () => {
948
+ try {
949
+ const registered = MCP_RESOURCE_TOOL_NAMES.filter((name) => tools.get(name) !== undefined);
950
+ const roster = await visibleMcpServerNames(agent);
951
+ if (roster !== null)
952
+ syncMcpPromptShadows(agent, roster, registered.length > 0);
953
+ }
954
+ catch { /* best effort */ }
955
+ })();
956
+ }
870
957
  /**
871
958
  * MCP 服务器名册的短 TTL 快照(**与 agent 无关** —— 只有「可见性过滤」才逐 agent)。
872
959
  *
@@ -875,8 +962,9 @@ export default {
875
962
  *
876
963
  * TTL 取 3 秒,与侧车 TTL 同量级(服务器增删是罕见事件)。**陈旧的后果要说明白**:
877
964
  * 刚加的服务器晚 3 秒才进名册,这段时间名册缺它 —— 若名册里别的服务器在本会话都看不见,
878
- * 就会走到「一台都看不见」那一支;判据⑤会在新服务器**有工具**时拦下(全局工具表里已经有
879
- * 它的 `mcp__*`),只有无工具的服务器才会真被摘掉。恢复要等「TTL 到期后的下一次重排」
965
+ * 就会走到「一台都看不见」那一支;`rosterMissesRunningServer` 会在新服务器**有工具**时
966
+ * 拦下(全局工具表里已经有它的 `mcp__*`),只有无工具的服务器才会真被摘掉。恢复要等
967
+ * 「TTL 到期后的下一次重排」
880
968
  * —— 重排本身会触发,但 TTL 没到期时它重算的还是陈旧名册。
881
969
  */
882
970
  let configuredServerStatesCache = null;
@@ -893,7 +981,8 @@ export default {
893
981
  /**
894
982
  * 本作用域**看得见的** MCP 服务器名,名册里的全部名字,以及「名册读全了没有」。
895
983
  *
896
- * `visible` = 看得见的那些(与状态段 / `mcp_manager_list` 同一份判据)。
984
+ * `visible` = 补丁 / loader 里启用、且本作用域看得见的那些(与状态段 / `mcp_manager_list`
985
+ * 同一份判据)。停用的服务器没有运行中的 provider,不算「看得见」。
897
986
  * `names` = 名册里的全部名字(看得见 + 看不见)。
898
987
  * `complete` = 名册读全了没有:任一层读不动它就只少几条,返回值上与「名册本来就短」
899
988
  * 同形(读错误在 `configuredServerStates` 内部被吞成「跳过这一层」)。
@@ -917,6 +1006,8 @@ export default {
917
1006
  if (!name)
918
1007
  continue;
919
1008
  names.add(name);
1009
+ if (row.disabled === true)
1010
+ continue;
920
1011
  if (sessionServerHiddenOf(agent, name))
921
1012
  continue;
922
1013
  visible.push(name);
@@ -978,11 +1069,16 @@ export default {
978
1069
  async function resourceToolDenyFor(agent) {
979
1070
  try {
980
1071
  const registered = MCP_RESOURCE_TOOL_NAMES.filter((name) => tools.get(name) !== undefined);
981
- if (registered.length === 0)
982
- return [];
983
1072
  const roster = await visibleMcpServerNames(agent);
984
1073
  if (roster === null)
985
1074
  return [];
1075
+ // 同一趟名册顺带同步 prompt 遮蔽:工具表与系统提示词必须一起收窄,否则本会话会
1076
+ // 「看不到工具、却被提示词教着去调用」。名册不完整时只遮蔽已知的隐藏项,方向选
1077
+ // 不漏掉别的对话。资源工具没注册时仍要遮蔽 `mcp:<server>` 的 instructions ——
1078
+ // 那是另一个官方包注册的段,只是不合成资源段文本。
1079
+ syncMcpPromptShadows(agent, roster, registered.length > 0);
1080
+ if (registered.length === 0)
1081
+ return [];
986
1082
  if (!roster.complete)
987
1083
  return [];
988
1084
  if (roster.visible.length > 0)
@@ -1175,6 +1271,9 @@ export default {
1175
1271
  // 会话层覆盖:记忆域按会话投影场景与逐条开关。侧车归 scopeStore 管
1176
1272
  // (它有自己的 TTL 缓存),这里只转手 —— 记忆域不引第二份读取点。
1177
1273
  scopeOverrideOf: memoryScopeOfSession,
1274
+ // 跨进程写锁:索引是整份读-改-写,web 与 desktop 两个宿主共用同一个 hub 时
1275
+ // 没有这把锁就会互相覆盖(丢场景档案与记忆启停,且无报错)。
1276
+ withWriteLock,
1178
1277
  });
1179
1278
  // 场景记忆段的注册/生命周期由下面的注入通道统一管(memoriesService.memoryText / promptText)。
1180
1279
  // ---------- 场景档案引擎----------
@@ -1396,9 +1495,9 @@ export default {
1396
1495
  }
1397
1496
  }
1398
1497
  /**
1399
- * 场景应用写全局意图:`blocked`(统一关闭)是比场景更强的用户要求,场景不得覆盖它
1498
+ * 场景应用写全局意图:`blocked`(全部关闭)是比场景更强的用户要求,场景不得覆盖它
1400
1499
  * —— 只有全局意图开关(`scope-intent-set`)能解除。不挡的话,进一次包含这台服务器 /
1401
- * 这条技能的场景,就会把「统一关闭」悄悄降级成 off,之后任何会话的租约都能把它拉起来。
1500
+ * 这条技能的场景,就会把「全部关闭」悄悄降级成 off,之后任何会话的租约都能把它拉起来。
1402
1501
  */
1403
1502
  function withSceneIntent(current, domain, key, state) {
1404
1503
  if (intentOf(current, domain, key) === 'blocked')
@@ -1485,7 +1584,7 @@ export default {
1485
1584
  // 场景模式进出一次就会改写 state.json。意图那一格同口径。
1486
1585
  const { states, shadowed, unloadable, entryNames } = await skillScan();
1487
1586
  const intentSnap = intentStore.snapshot();
1488
- /** 全局「统一关闭」的技能:场景不得覆盖(见 `withSceneIntent`),物理启停也一并跳过。 */
1587
+ /** 全局「全部关闭」的技能:场景不得覆盖(见 `withSceneIntent`),物理启停也一并跳过。 */
1489
1588
  const blocked = new Set();
1490
1589
  const planned = [];
1491
1590
  const skipped = [];
@@ -1505,13 +1604,13 @@ export default {
1505
1604
  skipped.push(`${key}(已不存在)`);
1506
1605
  continue;
1507
1606
  }
1508
- // 全局统一关闭压过场景(与 `scope-set` 拒写「开」同一条):既不改意图也不动策略表。
1509
- // 技能还要看所在来源:来源被统一关闭时,技能级开关开着也加载不到(来源闸恒生效)。
1607
+ // 全局全部关闭压过场景(与 `scope-set` 拒写「开」同一条):既不改意图也不动策略表。
1608
+ // 技能还要看所在来源:来源被全部关闭时,技能级开关开着也加载不到(来源闸恒生效)。
1510
1609
  if (intentOf(intentSnap, 'skills', key) === 'blocked' ||
1511
1610
  intentOf(intentSnap, 'skillSources', key.slice(0, i)) === 'blocked') {
1512
1611
  blocked.add(key);
1513
1612
  if (on)
1514
- skipped.push(`${key}(已在全局「统一关闭」)`);
1613
+ skipped.push(`${key}(已在全局「全部关闭」)`);
1515
1614
  continue;
1516
1615
  }
1517
1616
  const wanted = on ? 'on' : 'off';
@@ -1600,7 +1699,7 @@ export default {
1600
1699
  const prev = wanted.get(name);
1601
1700
  wanted.set(name, prev === undefined ? s.enabled : prev || s.enabled);
1602
1701
  }
1603
- // 全局「统一关闭」压过场景:不改意图、不动补丁(见 `withSceneIntent`)。
1702
+ // 全局「全部关闭」压过场景:不改意图、不动补丁(见 `withSceneIntent`)。
1604
1703
  const blocked = new Set();
1605
1704
  for (const [name, enabled] of [...wanted]) {
1606
1705
  if (intentOf(intentSnap, 'mcp', name) !== 'blocked')
@@ -1608,7 +1707,7 @@ export default {
1608
1707
  wanted.delete(name);
1609
1708
  blocked.add(name);
1610
1709
  if (enabled)
1611
- ctx.logger?.warn?.(`场景要启用 MCP 服务器「${name}」,但它已在全局「统一关闭」:已跳过`);
1710
+ ctx.logger?.warn?.(`场景要启用 MCP 服务器「${name}」,但它已在全局「全部关闭」:已跳过`);
1612
1711
  }
1613
1712
  if (wanted.size > 0) {
1614
1713
  await intentStore.mutate((current) => {
@@ -1691,14 +1790,14 @@ export default {
1691
1790
  // 与 MCP 同一条:场景引擎改的是全局定义 → 先写意图,再改来源状态(见
1692
1791
  // applyMcpServerSwitches 的注释;运行态 = 意图 ∪ 租约)。
1693
1792
  const intentSnap = intentStore.snapshot();
1694
- // 全局「统一关闭」压过场景:不改意图、不动来源状态(见 `withSceneIntent`)。
1793
+ // 全局「全部关闭」压过场景:不改意图、不动来源状态(见 `withSceneIntent`)。
1695
1794
  const blocked = new Set();
1696
1795
  for (const s of switches) {
1697
1796
  if (intentOf(intentSnap, 'skillSources', s.root) !== 'blocked')
1698
1797
  continue;
1699
1798
  blocked.add(s.root);
1700
1799
  if (s.enabled)
1701
- ctx.logger?.warn?.(`场景要启用技能来源「${s.root}」,但它已在全局「统一关闭」:已跳过`);
1800
+ ctx.logger?.warn?.(`场景要启用技能来源「${s.root}」,但它已在全局「全部关闭」:已跳过`);
1702
1801
  }
1703
1802
  if (switches.length > 0) {
1704
1803
  await intentStore.mutate((current) => {
@@ -1932,6 +2031,11 @@ export default {
1932
2031
  // 场景绑定的排除项;没话说时目录自己落到全局口径(场景绑定 ∩ 全局启停)。
1933
2032
  flagFor: (agent) => flagResolverOfAgent(agent, 'subagents'),
1934
2033
  layerKeyFor: (agent) => layerKeyOfAgent(agent),
2034
+ }, {
2035
+ // 目录上限吃兼容页注入设置(`catalogCaps`):函数式取值,设置有 TTL 缓存,
2036
+ // 这里只是转发(目录在启动时建,传死数会让界面改完不生效)。
2037
+ maxEntries: () => injectSettingsSync().catalogCaps.subagents,
2038
+ maxDescription: () => injectSettingsSync().catalogCaps.subagentsDescription,
1935
2039
  });
1936
2040
  // ⚠️ 取数必须用 mcpmRowsWithNotes(false):true 会带上**未打码**的 url/headers/env(含明文密钥)。
1937
2041
  // 技能目录与提示词两个域是**官方载体的兜底**:预设挂得到官方
@@ -1958,6 +2062,10 @@ export default {
1958
2062
  return { skill, source };
1959
2063
  },
1960
2064
  layerKeyFor: (agent) => layerKeyOfAgent(agent),
2065
+ }, {
2066
+ // 目录上限吃兼容页注入设置(`catalogCaps`):与子智能体目录同一条理由 —— 函数式取值。
2067
+ maxEntries: () => injectSettingsSync().catalogCaps.skills,
2068
+ maxDescription: () => injectSettingsSync().catalogCaps.skillsDescription,
1961
2069
  });
1962
2070
  /**
1963
2071
  * 技能目录重算的**合并调度**。
@@ -2550,6 +2658,19 @@ export default {
2550
2658
  throw e;
2551
2659
  }
2552
2660
  }
2661
+ /**
2662
+ * 宿主平面 patch 文本(全局 + 当前 profile 两份 `cordis.patch.yml` 拼接)。
2663
+ *
2664
+ * 官方载体行(`dsh-tool-skill` / `dsh-agent-instructions`)预设事实的第二来源:
2665
+ * 组合文本里缺席时,注入侧(`candidates.presetFactsForAgent`)与兼容页矩阵
2666
+ * (`preset-reach` op)都拿它做并集判定,两处同一份文本、不会各说各话。
2667
+ * 不带缓存:调用方各有自己的节拍(注入事实 15s TTL、矩阵点开才算),缺文件返回空串。
2668
+ */
2669
+ async function patchCarrierText() {
2670
+ const paths = await ensurePaths();
2671
+ const [globalText, profileText] = await Promise.all([readPatch(paths.globalPatch), readPatch(paths.projectPatch)]);
2672
+ return globalText + '\n' + profileText;
2673
+ }
2553
2674
  // 每次写补丁前留一份带时间戳的副本:cordis.patch.yml 改坏能让 DSH 起不来,
2554
2675
  // 所以写前那份必须不靠 git 也能拿回来。
2555
2676
  const KEEP_PATCH_BACKUPS = 5;
@@ -2840,6 +2961,8 @@ export default {
2840
2961
  // 状态段尾句那句「用 `mcp_manager_list` 查」的前提:与技能 / 子智能体两个目录同一份判据
2841
2962
  // 。
2842
2963
  listToolVisible: (agent) => toolVisibleFor('mcp_manager_list', agent),
2964
+ // 状态段条数上限:与技能 / 子智能体两个目录同一份设置来源(`catalogCaps.mcp`)。
2965
+ catalogCaps: () => injectSettingsSync().catalogCaps,
2843
2966
  // 会话层:两半各管一头 ——
2844
2967
  // · `sessionMcpOverlay`(异步)给 restrictAgent:在**此刻注册着的**工具全名上算
2845
2968
  // allow / deny(deny 追加、allow 从全局停用名单里减掉,见 tool-visibility.ts);
@@ -2967,6 +3090,8 @@ export default {
2967
3090
  // 传 getter 而不是快照:登记发生在 apply 过程中(本行之后 600 余行),
2968
3091
  // 而这个工厂现在就要构造完。
2969
3092
  selfToolNames: () => selfToolNames,
3093
+ // 预设事实的 patch 第二来源:官方载体行挂在宿主平面 patch 时组合里没有那一行。
3094
+ profilePatchText: patchCarrierText,
2970
3095
  });
2971
3096
  // 提示词预设域的 op 表。单独提出来是为了让**模型工具**能复用同一份判定:
2972
3097
  // `prompt_manager_list` 以前直调 `promptsService.list()`,于是它报的「生效中」是
@@ -3138,7 +3263,7 @@ export default {
3138
3263
  //
3139
3264
  // 只问**全局关着**的那些格:开着的那些本来就该显示成开着,数它没有意义,而记忆这类域
3140
3265
  // 可能有几百条键 —— 每次读面板都全扫一遍是不必要的成本。
3141
- // 键集合的口径:**意图域**只数「意图不是 on」的键(全局开着不是租约,统一关闭没有
3266
+ // 键集合的口径:**意图域**只数「意图不是 on」的键(全局开着不是租约,全部关闭没有
3142
3267
  // 租约这回事);**纯视图域**只数「全局关着」的键。两句话都只回答"这一格该不该挂徽章"。
3143
3268
  const leaseKeys = {};
3144
3269
  for (const domain of SCOPE_FLAG_DOMAINS) {
@@ -3222,7 +3347,7 @@ export default {
3222
3347
  flags,
3223
3348
  unavailable,
3224
3349
  // 三态意图与租约计数(界面用):`flags` 把 blocked 投影成 false,分不出「关着」与
3225
- // 「统一关闭」;租约计数则是全局 off 却仍在跑的唯一解释。
3350
+ // 「全部关闭」;租约计数则是全局 off 却仍在跑的唯一解释。
3226
3351
  intent: { mcp: intentSnapshot.mcp, skillSources: intentSnapshot.skillSources, skills: intentSnapshot.skills },
3227
3352
  leases: {
3228
3353
  mcp: leaseCounts('mcp'),
@@ -3654,7 +3779,7 @@ export default {
3654
3779
  const rows = rowsIn.map((row) => {
3655
3780
  const name = String((row && (row.serverName || row.id)) || '');
3656
3781
  const state = intentOf(intent, 'mcp', name);
3657
- // 全局开着(`on`)不是租约;统一关闭(`blocked`)压过一切会话层 —— 两种都不挂徽章。
3782
+ // 全局开着(`on`)不是租约;全部关闭(`blocked`)压过一切会话层 —— 两种都不挂徽章。
3658
3783
  const leaseCount = state === 'on' || state === 'blocked' || scan === null ? 0 : (scan.claims.mcp.get(name) || []).length;
3659
3784
  return {
3660
3785
  ...row,
@@ -4133,6 +4258,8 @@ export default {
4133
4258
  // 先读一次:预热前 state 是乐观的 'ok',而这一行要回答的是"文件现在能不能读"。
4134
4259
  toolTableState: async () => { await readToolTableSettings(); return toolTableState(); },
4135
4260
  presetRoster: candidates.presetRoster,
4261
+ // 预设矩阵的 patch 第二来源:与注入侧同一份文本(`patchCarrierText`),口径不分叉。
4262
+ profilePatchText: patchCarrierText,
4136
4263
  listPatchBackups,
4137
4264
  cleanPatchBackups,
4138
4265
  getContextInjectorLive: () => contextInjectorLive,
@@ -4324,6 +4451,11 @@ export default {
4324
4451
  scheduleSkillCatalogRefresh();
4325
4452
  void subagentCatalog.refresh().catch(() => { });
4326
4453
  }
4454
+ // 会话层改了技能的启停 → 官方那份清单(宿主 `/` 菜单的「技能」段、官方 `skill`
4455
+ // 工具的候选)得重新算:它是按会话过滤的,缓存键里没有会话层,不作废就停在
4456
+ // 改动前那一份。机器级那张表没变时("本对话关掉一条全局开着的技能")尤其需要。
4457
+ if (domain === 'skills' || domain === 'skillSources' || domain === '')
4458
+ skillsService.invalidateSkills();
4327
4459
  },
4328
4460
  message,
4329
4461
  }),
@@ -5470,6 +5602,7 @@ export default {
5470
5602
  ctx.effect(() => {
5471
5603
  const stop = ctx.on('agent/created', (payload) => {
5472
5604
  mcp.attachAgent(payload && payload.agent);
5605
+ warmMcpPromptShadows(payload && payload.agent);
5473
5606
  // 技能目录按会话 cwd 取数:先热一份,否则该会话首轮注入会少掉整段目录。
5474
5607
  // 子代理热的是**所属用户会话**那一份:它的目录 / 覆盖都继承父会话(见 `sessionScopeIdOf`)。
5475
5608
  const scopeSid = sessionScopeIdOf(payload && payload.agent);
@@ -5486,13 +5619,16 @@ export default {
5486
5619
  ctx.effect(() => {
5487
5620
  const stop = ctx.on('agent/disposed', (payload) => {
5488
5621
  mcp.detachAgent(payload && payload.agent);
5622
+ mcpPromptShadow.dispose(payload && payload.agent);
5489
5623
  });
5490
5624
  return typeof stop === 'function' ? stop : () => { };
5491
5625
  }, 'dsh-plugin-tool-management: mcp visibility (agent disposed)');
5626
+ ctx.effect(() => () => { mcpPromptShadow.disposeAll(); }, 'dsh-plugin-tool-management: mcp prompt shadow cleanup');
5492
5627
  const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined;
5493
5628
  if (agents && typeof agents.list === 'function') {
5494
5629
  for (const agent of agents.list()) {
5495
5630
  mcp.attachAgent(agent);
5631
+ warmMcpPromptShadows(agent);
5496
5632
  const scopeSid = sessionScopeIdOf(agent);
5497
5633
  if (scopeSid !== null)
5498
5634
  void skillCatalog.warmSession(scopeSid);
@@ -143,6 +143,8 @@ export function createMcpManager(deps) {
143
143
  const mcpStateCatalog = createMcpStateCatalog({
144
144
  rows: () => mcpmRowsWithNotes(false),
145
145
  ...(deps.listToolVisible === undefined ? {} : { listToolVisible: deps.listToolVisible }),
146
+ // 条数上限吃兼容页注入设置(`catalogCaps.mcp`):函数式取值,设置有 TTL 缓存,这里只是转发。
147
+ ...(deps.catalogCaps === undefined ? {} : { maxEntries: () => deps.catalogCaps().mcp }),
146
148
  // 会话层:本会话隐藏的服务器整条不进段(理由见 state-section.ts)。逐行问谓词 ——
147
149
  // 行数组本身就是服务器全集,不需要另建一份。
148
150
  ...(deps.sessionHiddenServer === undefined ? {} : { sessionServerHidden: deps.sessionHiddenServer }),
@@ -1994,7 +1996,8 @@ export function createMcpManager(deps) {
1994
1996
  // ① 重扫 = 重新读取并解析两个补丁文件,N 条就是 N 次全量解析(行数多时平方级);
1995
1997
  // ② 顺带把「整批导入」变成对其它写者的原子操作,不再允许别的写插到条目之间。
1996
1998
  // 存在性判定仍留在锁内(TOCTOU 的初衷不变),改成从一次性快照增量维护。
1997
- // 注意 withWriteLock **不可重入**(它挂在同一条 writeChain 上),所以循环体里不能再包一层。
1999
+ // 注意 withWriteLock 在同一异步调用链上可重入(重入并入外层临界区、不再排队),
2000
+ // 循环体里仍不必再包一层:外层已经持锁。
1998
2001
  await withWriteLock(async () => {
1999
2002
  const existing = await collectAll();
2000
2003
  // 按 id / serverName 两张表维护同一份快照:覆盖模式会摘掉旧行,两张表必须同步。
@@ -0,0 +1,128 @@
1
+ // MCP 跨会话 prompt 隔离:用官方 `systemPrompt` 在 **agent 作用域**注册同名段,
2
+ // 遮蔽根作用域注册的 `mcp-resource-servers` 与 `mcp:<server>`。
3
+ //
4
+ // 为什么必须走同名段:这两类段由 `dsh-mcp-resources` / `dsh-mcp-client` 注册在根作用域,
5
+ // 官方只按「全局层 + 作用域链」解析 provider,不看插件的会话可见性。不能 patch 官方包,
6
+ // 而 `systemPrompt.section()` 的官方语义是「scoped section shadows a global section with
7
+ // the same name」—— 这是唯一能把别的对话的服务器名与 instructions 从本对话提示词里拿掉的
8
+ // 接缝。空文本段会在组装阶段被过滤(`dsh-system-prompt` 的 `renderSections` 只保留非空
9
+ // 文本),所以隐藏服务器的 instructions 直接消失;资源段则替换成只列本会话可见服务器的
10
+ // 等价文本,避免模型被提示去调用已经从工具表里摘掉的三个工具。
11
+ /** 官方共享资源段的名称。 */
12
+ export const MCP_RESOURCE_SECTION_NAME = 'mcp-resource-servers';
13
+ /** 官方 MCP 段使用的排序名(`systemPrompt.getSectionOrder` 的入参)。 */
14
+ export const MCP_SERVERS_SECTION_ORDER = 'MCP_SERVERS';
15
+ /** 官方 `mcp:<server>` 段的名称。 */
16
+ export function mcpServerSectionName(server) {
17
+ return 'mcp:' + server;
18
+ }
19
+ /**
20
+ * 按本会话可见的服务器名,算出要遮蔽哪些 prompt 段。
21
+ *
22
+ * 只有**存在隐藏服务器**时才替换资源段:全部可见时官方段的内容正好等于可见集合,
23
+ * 替换没有收益,反而会丢失官方后续的文案调整。
24
+ */
25
+ export function mcpPromptShadowPlan(names, visible) {
26
+ const shown = new Set(visible);
27
+ const hidden = names.filter((name) => !shown.has(name));
28
+ return { resource: names.length > 0 && hidden.length > 0, hidden };
29
+ }
30
+ /**
31
+ * 资源服务器段的等价文本。
32
+ *
33
+ * 文案与官方保持一致(标题 + 三个工具名 + server 名单),只把名单收窄到本会话可见的那些;
34
+ * 名单为空时返回空串,让组装阶段把整段过滤掉。
35
+ */
36
+ export function renderMcpResourceServersSection(visible) {
37
+ if (visible.length === 0)
38
+ return '';
39
+ const names = [...visible].sort();
40
+ return '## MCP resource servers\n\nUse list_mcp_resources, list_mcp_resource_templates, or read_mcp_resource with one of these names as the server argument: ' + JSON.stringify(names) + '.';
41
+ }
42
+ /**
43
+ * 创建提示词遮蔽器。
44
+ *
45
+ * @param systemPromptOf 从 agent 取 `systemPrompt` 服务;取不到时返回 undefined(该 agent 不遮蔽)。
46
+ * @returns 按 agent 差分注册 / 撤销段的句柄。
47
+ */
48
+ export function createMcpPromptShadow(systemPromptOf) {
49
+ const states = new Map();
50
+ function release(dispose) {
51
+ if (dispose === undefined)
52
+ return;
53
+ try {
54
+ dispose();
55
+ }
56
+ catch { /* agent 作用域已经释放 */ }
57
+ }
58
+ function sync(agent, names, visible, options) {
59
+ const systemPrompt = systemPromptOf(agent);
60
+ if (systemPrompt === undefined)
61
+ return;
62
+ const order = Number(systemPrompt.getSectionOrder(MCP_SERVERS_SECTION_ORDER));
63
+ if (!Number.isFinite(order))
64
+ return;
65
+ let state = states.get(agent);
66
+ if (state === undefined) {
67
+ state = { visible: [], servers: new Map() };
68
+ states.set(agent, state);
69
+ }
70
+ const current = state;
71
+ current.visible = [...visible];
72
+ const plan = mcpPromptShadowPlan(names, visible);
73
+ const wantResource = plan.resource && options?.resourceAvailable !== false;
74
+ if (wantResource) {
75
+ if (current.resource === undefined) {
76
+ try {
77
+ const dispose = systemPrompt.section({
78
+ name: MCP_RESOURCE_SECTION_NAME,
79
+ order,
80
+ interpolate: false,
81
+ text: () => renderMcpResourceServersSection(current.visible),
82
+ });
83
+ current.resource = typeof dispose === 'function' ? dispose : () => { };
84
+ }
85
+ catch { /* 同名段已被别的 scoped 层占用:保留官方段,不把功能弄坏 */ }
86
+ }
87
+ }
88
+ else if (current.resource !== undefined) {
89
+ release(current.resource);
90
+ current.resource = undefined;
91
+ }
92
+ const hidden = new Set(plan.hidden);
93
+ for (const [server, dispose] of [...current.servers]) {
94
+ if (hidden.has(server))
95
+ continue;
96
+ release(dispose);
97
+ current.servers.delete(server);
98
+ }
99
+ for (const server of plan.hidden) {
100
+ if (current.servers.has(server))
101
+ continue;
102
+ try {
103
+ const dispose = systemPrompt.section({
104
+ name: mcpServerSectionName(server),
105
+ order,
106
+ interpolate: false,
107
+ text: () => '',
108
+ });
109
+ current.servers.set(server, typeof dispose === 'function' ? dispose : () => { });
110
+ }
111
+ catch { /* 同上 */ }
112
+ }
113
+ }
114
+ function dispose(agent) {
115
+ const state = states.get(agent);
116
+ if (state === undefined)
117
+ return;
118
+ release(state.resource);
119
+ for (const disposeSection of state.servers.values())
120
+ release(disposeSection);
121
+ states.delete(agent);
122
+ }
123
+ function disposeAll() {
124
+ for (const agent of [...states.keys()])
125
+ dispose(agent);
126
+ }
127
+ return { sync, dispose, disposeAll };
128
+ }
@@ -44,8 +44,9 @@
44
44
  //
45
45
  // 同步性:`text()` 必须同步返回(renderPrompt 不接受 Promise),而 MCP 清单是异步读盘 →
46
46
  // 与子智能体目录同构的 stale-while-revalidate(见 src/subagents/catalog.ts)。
47
+ import { CATALOG_CAP_DEFAULTS } from '../catalog-caps.js';
47
48
  /** 段里最多列几台 server;超出部分只报数量。 */
48
- export const DEFAULT_MCP_MAX_ENTRIES = 50;
49
+ export const DEFAULT_MCP_MAX_ENTRIES = CATALOG_CAP_DEFAULTS.mcp;
49
50
  /**
50
51
  * 备注截断长度。界面上那两枚输入框(MCP 页与场景档案)用同一个数当字数上限,
51
52
  * 客户端镜像在 `42-shared-ui.js` 的 `MCP_NOTE_MAX` —— 改这里要一起改它。
@@ -194,13 +195,13 @@ sessionTools = { on: [], off: [] }) {
194
195
  const out = [...lines];
195
196
  const hidden = (usable.length + muted.length)
196
197
  - (shownUsable.length + shownMuted.length);
197
- // 超上限时给出口:技能与子智能体两个目录早就这么写了,这是唯一漏掉
198
- // 的一处。工具被关掉(兼容页 / 人设 toolsDeny)时不点名 —— 点名一个模型手里没有的工具,
199
- // 只会让它去猜名字;数量照报,那是实话。
198
+ // 超上限时给出口:工具可见就点名(技能与子智能体两个目录同款);被关掉时不点名"去调它"
199
+ // —— 点名一个模型手里没有的工具,只会让它去猜名字;但也不只报数量,补一句可转告的事实
200
+ // (工具是关着的、用户能开),别让被截掉的部分在模型看来"不存在"。数量照报,那是实话。
200
201
  if (hidden > 0) {
201
202
  out.push('', listToolVisible
202
203
  ? `(${hidden} more not listed — see them with \`mcp_manager_list\`.)`
203
- : `(${hidden} more not listed.)`);
204
+ : `(${hidden} more not listed — the listing tool is disabled in this session; ask the user to enable it.)`);
204
205
  }
205
206
  return out.join('\n');
206
207
  }
@@ -214,8 +215,8 @@ export function createMcpStateCatalog(deps, opts = {}) {
214
215
  let data = null;
215
216
  let loadedAt = Number.NEGATIVE_INFINITY;
216
217
  let inflight = null;
217
- // 渲染缓存键 = (尾句前提, 本会话停用的服务器)。两者都影响正文,少一个就会让 A 的段
218
- // 出现在 B 里(与技能 / 人设两个目录同一手法)。
218
+ // 渲染缓存键 = (尾句前提, 本会话停用的服务器, 逐工具判定, 条数上限)。全都影响正文,
219
+ // 少一个就会让 A 的段出现在 B 里,或让改完设置后的旧文本继续发(与技能 / 人设两个目录同一手法)。
219
220
  let rendered = null;
220
221
  /** 空清单按 `emptyTtlMs` 走,有行时仍按 `ttlMs`(判据见 `emptyTtlMs` 的注释)。 */
221
222
  const ttlFor = () => (data !== null && data.length === 0 ? emptyTtlMs : ttlMs);
@@ -301,16 +302,20 @@ export function createMcpStateCatalog(deps, opts = {}) {
301
302
  toolOff.length = 0;
302
303
  }
303
304
  }
305
+ // 上限每次渲染现取(设置有 TTL 缓存,这里只是转发);缺省回落厂值。
306
+ const maxEntries = (typeof opts.maxEntries === 'function' ? opts.maxEntries() : opts.maxEntries) ?? DEFAULT_MCP_MAX_ENTRIES;
304
307
  const key = (visible ? '1' : '0') +
305
308
  '\u0000' + sessionOff.slice().sort().join('\u0001') +
306
309
  '\u0002' + toolOn.slice().sort().join('\u0001') +
307
- '\u0003' + toolOff.slice().sort().join('\u0001');
310
+ '\u0003' + toolOff.slice().sort().join('\u0001') +
311
+ // 缓存键必须带上条数上限:改了设置而键没变的话,渲染缓存会一直发旧文本。
312
+ '\u0004' + maxEntries;
308
313
  if (rendered && rendered.key === key) {
309
314
  if (rendered.text !== '')
310
315
  markNonEmpty(agent);
311
316
  return rendered.text;
312
317
  }
313
- const out = renderMcpStateSection(data, opts, visible, sessionOff, { on: toolOn, off: toolOff });
318
+ const out = renderMcpStateSection(data, { ...opts, maxEntries }, visible, sessionOff, { on: toolOn, off: toolOff });
314
319
  rendered = { key, text: out };
315
320
  if (out !== '')
316
321
  markNonEmpty(agent);
@@ -295,7 +295,8 @@ export function createToolVisibility(deps) {
295
295
  *
296
296
  * `mutate` 收到的是**锁内刚读出来**的表(`force` 绕 TTL,否则拿到的还是锁外那份缓存);
297
297
  * 返回 `true` 表示有变化、需要落盘。
298
- * 注意:`withWriteLock` **不可重入** —— 调用方不得已经持有写锁。
298
+ * 注意:`withWriteLock` 在同一异步调用链上可重入(重入直接并入外层临界区、不再排队),
299
+ * 但重入不会重新读盘 —— 需要"锁内刚写下的值"时必须显式 `force`。
299
300
  */
300
301
  async function mutateKnownMcpTools(mutate) {
301
302
  return deps.withWriteLock(async () => {
@@ -497,18 +498,29 @@ export function createToolVisibility(deps) {
497
498
  });
498
499
  return;
499
500
  }
500
- const key = names.slice().sort().join('\u0000');
501
- if (appliedByAgent.get(agent) === key)
501
+ // 从枚举到装层之间可能过去一拍:服务器恰好停了 / 注册被摘掉,而官方 `restrict` 对
502
+ // 认不出的名字是**整份名单抛错**(不是跳过那一个)—— 一个过期名字就会让所有工具重新
503
+ // 出现在模型工具表里。装之前再问一次全局视图,把已经不存在的名字剔掉。
504
+ const denyNames = typeof deps.tools.get === 'function'
505
+ ? names.filter((name) => { try {
506
+ return deps.tools.get(name) !== undefined;
507
+ }
508
+ catch {
509
+ return false;
510
+ } })
511
+ : names;
512
+ const denyKey = denyNames.slice().sort().join('\u0000');
513
+ if (appliedByAgent.get(agent) === denyKey)
502
514
  return;
503
515
  liftRestriction(agent);
504
- if (names.length === 0) {
516
+ if (denyNames.length === 0) {
505
517
  clearRuntimeNote('mcp-tool-visibility');
506
518
  return;
507
519
  }
508
520
  try {
509
- const dispose = scoped.restrict({ deny: names });
521
+ const dispose = scoped.restrict({ deny: denyNames });
510
522
  agentRestrictions.set(agent, typeof dispose === 'function' ? dispose : () => { });
511
- appliedByAgent.set(agent, key);
523
+ appliedByAgent.set(agent, denyKey);
512
524
  clearRuntimeNote('mcp-tool-visibility');
513
525
  }
514
526
  catch (e) {