dsh-plugin-tool-management 0.22.4 → 0.22.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1624 -1395
- package/README.md +194 -177
- package/README_EN.md +194 -177
- package/docs/ARCHITECTURE.md +137 -0
- package/docs/COMPATIBILITY.md +112 -0
- package/docs/TROUBLESHOOTING.md +287 -0
- package/lib/client.js +14984 -12279
- package/lib/compat/capability-specs.js +66 -16
- package/lib/compat/host-contracts.js +14 -3
- package/lib/compat/host-roots.js +1 -1
- package/lib/compat/manual-review.js +1 -1
- package/lib/compat/preset-reach.js +1 -1
- package/lib/compat/probe.js +96 -11
- package/lib/confirm-gate.js +40 -6
- package/lib/context-inject-contract.js +31 -14
- package/lib/context-inject-delta.js +146 -0
- package/lib/context-inject-frame.js +38 -19
- package/lib/context-inject-select.js +33 -4
- package/lib/context-inject-surface.js +74 -22
- package/lib/context-inject.js +107 -15
- package/lib/evolution/cold.js +389 -0
- package/lib/evolution/config.js +507 -0
- package/lib/evolution/digest.js +48 -0
- package/lib/evolution/episodes.js +287 -0
- package/lib/evolution/evidence.js +167 -0
- package/lib/evolution/gates.js +874 -0
- package/lib/evolution/limits.js +21 -0
- package/lib/evolution/maintenance.js +516 -0
- package/lib/evolution/notes.js +328 -0
- package/lib/evolution/organize.js +118 -0
- package/lib/evolution/review.js +524 -0
- package/lib/evolution/route.js +91 -0
- package/lib/evolution/runtime.js +179 -0
- package/lib/evolution/scope-card.js +144 -0
- package/lib/evolution/state.js +514 -0
- package/lib/evolution/write.js +1773 -0
- package/lib/imports/unzip.js +144 -26
- package/lib/index.js +1371 -79
- package/lib/legacy-tool-names.js +19 -4
- package/lib/mcp/manager.js +1 -0
- package/lib/mcp/tool-visibility.js +204 -11
- package/lib/memories/catalog.js +215 -0
- package/lib/memories/constants.js +115 -7
- package/lib/memories/discovery.js +59 -25
- package/lib/memories/projection.js +116 -31
- package/lib/memories/render-auto.js +198 -0
- package/lib/memories/search.js +3 -5
- package/lib/memories/service.js +252 -17
- package/lib/memories/snapshot.js +174 -23
- package/lib/op-registry.js +59 -0
- package/lib/ops/compat.js +2 -0
- package/lib/ops/evolution.js +887 -0
- package/lib/ops/memory.js +95 -72
- package/lib/ops/trash.js +14 -2
- package/lib/prompts/service.js +30 -0
- package/lib/scope/workspace-key.js +39 -0
- package/lib/settings-sidecars.js +2 -2
- package/lib/skills/dir-watch.js +49 -22
- package/lib/skills/official.js +180 -36
- package/lib/skills/service.js +2 -2
- package/lib/subagents/run-provider.js +35 -22
- package/lib/text-width.js +59 -0
- package/lib/tool-table-switch.js +104 -16
- package/lib/tools/control.js +45 -12
- package/lib/tools/deps.js +2 -2
- package/lib/tools/mcp.js +6 -4
- package/lib/tools/memory.js +1045 -267
- package/lib/tools/note-ref.js +20 -0
- package/lib/tools/remove.js +1 -1
- package/lib/tools/scene.js +3 -3
- package/lib/tools/table.js +76 -20
- package/package.json +155 -152
- package/docs/UPDATE.md +0 -49
package/lib/legacy-tool-names.js
CHANGED
|
@@ -15,11 +15,17 @@
|
|
|
15
15
|
// 出厂口径;只开过其中一条的用户会看到合成的那条仍是关着的 —— 面板上一键就能开,
|
|
16
16
|
// 比原来分五条开省事。
|
|
17
17
|
export const LEGACY_TOOL_NAME_MAP = Object.freeze({
|
|
18
|
-
//
|
|
18
|
+
// 记忆族:write + update + save 三条并成 `memory_remember`(多对一)。
|
|
19
19
|
// (开发中途曾把整族改叫 `scene_memory_manager_*`,但那个名字**从未发布**,用户侧
|
|
20
20
|
// 不可能有它,因此不存在需要从它迁回来的数据。)
|
|
21
|
-
memory_manager_write: '
|
|
22
|
-
memory_manager_update: '
|
|
21
|
+
memory_manager_write: 'memory_remember',
|
|
22
|
+
memory_manager_update: 'memory_remember',
|
|
23
|
+
memory_manager_save: 'memory_remember',
|
|
24
|
+
// 清单并进 `memory_get`:用户显式关过清单的,升级后读取入口仍保持关闭。
|
|
25
|
+
// `memory_manager_read` / `_search` **不映射**:它们出厂就是关着的,映射到
|
|
26
|
+
// `memory_get` 会让升级用户的合并读取入口也变关 —— 那是唯一的发现路径。
|
|
27
|
+
// 旧名留在名单里只是死名,不影响任何工具。
|
|
28
|
+
memory_manager_list: 'memory_get',
|
|
23
29
|
mcp_manager_set_enabled: 'mcp_manager_switch',
|
|
24
30
|
mcp_manager_restart: 'mcp_manager_switch',
|
|
25
31
|
mcp_manager_add: 'mcp_manager_save',
|
|
@@ -29,7 +35,8 @@ export const LEGACY_TOOL_NAME_MAP = Object.freeze({
|
|
|
29
35
|
// 「拨一个开关」六域同形 —— `_set_enabled` → `_switch`(与 `mcp_manager_set_enabled`
|
|
30
36
|
// → `mcp_manager_switch` 同一条路)。**改的只是名字,参数不动**(仍是 `enabled` 布尔),
|
|
31
37
|
// 所以这里是一对一翻译、不涉及语义合并。
|
|
32
|
-
memory_manager_set_enabled: '
|
|
38
|
+
memory_manager_set_enabled: 'memory_switch',
|
|
39
|
+
memory_manager_switch: 'memory_switch',
|
|
33
40
|
skill_manager_set_enabled: 'skill_manager_switch',
|
|
34
41
|
subagent_manager_set_enabled: 'subagent_manager_switch',
|
|
35
42
|
// 删除族:五个域各一条 → 合成一条 `plugin_manager_remove`(**多对一**)。
|
|
@@ -39,6 +46,14 @@ export const LEGACY_TOOL_NAME_MAP = Object.freeze({
|
|
|
39
46
|
subagent_manager_remove: 'plugin_manager_remove',
|
|
40
47
|
scene_manager_remove: 'plugin_manager_remove',
|
|
41
48
|
prompt_manager_remove: 'plugin_manager_remove',
|
|
49
|
+
// 自主笔记:早期分开注册的四条,以及上一版合并后的 `memory_manager_auto`,都迁到
|
|
50
|
+
// `memory_note`。盘上的 `tool-table.json` / 场景快照可能留着旧名;任意一条被关过
|
|
51
|
+
// ⇒ 新工具也记成关过,别让旧名单变成一串永远认不出的死名。
|
|
52
|
+
memory_manager_learn: 'memory_note',
|
|
53
|
+
memory_manager_forget: 'memory_note',
|
|
54
|
+
memory_manager_organize: 'memory_note',
|
|
55
|
+
memory_manager_procedure_done: 'memory_note',
|
|
56
|
+
memory_manager_auto: 'memory_note',
|
|
42
57
|
});
|
|
43
58
|
/** 旧名 → 新名;不是旧名就原样返回。 */
|
|
44
59
|
export function translateLegacyToolName(name) {
|
package/lib/mcp/manager.js
CHANGED
|
@@ -445,6 +445,7 @@ export function createMcpManager(deps) {
|
|
|
445
445
|
const { readDisabledTools, readDisabledToolsResult, disabledToolsState, disabledToolsIssue, ensureDisabledToolsForensics, resetDisabledTools, readKnownMcpTools, writeKnownMcpTools, mutateKnownMcpTools, mergeLiveToolsInto, mcpmToolEnabled, applyToolRestrictions, scheduleToolRestrictions, attachAgent, detachAgent, setDisabledToolsCache, disabledToolsSnapshot, disposeVisibility, } = createToolVisibility({
|
|
446
446
|
readJsonFile, readJsonFileStrict, writeJsonFile, ensurePaths, withWriteLock, message, tools,
|
|
447
447
|
pluginHiddenTools: deps.pluginHiddenTools, carrierHiddenTools: deps.carrierHiddenTools,
|
|
448
|
+
isPluginToolName: deps.isPluginToolName,
|
|
448
449
|
sessionMcpOverlay: deps.sessionMcpOverlay,
|
|
449
450
|
sessionToolTableOverlay: deps.sessionToolTableOverlay,
|
|
450
451
|
normalizeKnownTools, mcpSidecar, SIDECAR_TTL_MS, MCP_DISABLED_TOOLS_FILE, MCP_KNOWN_TOOLS_FILE,
|
|
@@ -400,12 +400,34 @@ export function createToolVisibility(deps) {
|
|
|
400
400
|
let appliedNamesKey = null;
|
|
401
401
|
/** 当前期望的**全局** deny 名单(agent 晚到 / 重放时用它,再叠加该 agent 自己那份)。 */
|
|
402
402
|
let desiredNames = [];
|
|
403
|
+
/** 最近一次成功枚举的已注册工具名全集:agent 上线时复用,免去每个子代理各做一次全量深拷贝。 */
|
|
404
|
+
let registeredNames = null;
|
|
403
405
|
/** agent → 撤掉这层限制的 disposer。 */
|
|
404
406
|
const agentRestrictions = new Map();
|
|
405
407
|
/** agent → 已应用的**合并后**名单键(名单现在与 agent 有关,不能再只记一份全局的)。 */
|
|
406
408
|
const appliedByAgent = new Map();
|
|
407
409
|
/** 见过的 agent(重放时逐个重新应用;disposed 时移除)。 */
|
|
408
410
|
const seenAgents = new Set();
|
|
411
|
+
/**
|
|
412
|
+
* 已报过的装层失败:(agent, 名单, 原因) → 已报。
|
|
413
|
+
*
|
|
414
|
+
* 为什么要有:装层失败没有「键相同就跳过」的保护(没装上就得再试),
|
|
415
|
+
* 而 `tools/change` 空闲时也能到十几次/秒 —— 不去重的话同一份失败会刷满日志,
|
|
416
|
+
* 真正的新问题反而被淹没。名单或原因变了才算新问题,才会再报一行。
|
|
417
|
+
*
|
|
418
|
+
* 键里带 agent 身份:不同 scope 的失败是不同的事。
|
|
419
|
+
*/
|
|
420
|
+
const reportedRestrictFailures = new Map();
|
|
421
|
+
/** agent 的可读标识(给日志用;读不到就退化成空串,不影响判断)。 */
|
|
422
|
+
const agentIdOf = (agent) => {
|
|
423
|
+
try {
|
|
424
|
+
const id = agent?.id;
|
|
425
|
+
return id === undefined || id === null ? '' : String(id);
|
|
426
|
+
}
|
|
427
|
+
catch {
|
|
428
|
+
return '';
|
|
429
|
+
}
|
|
430
|
+
};
|
|
409
431
|
/**
|
|
410
432
|
* 重放代数:`carrierHiddenTools` 是异步的,算名单期间可能又来了新的一轮重放(或 agent
|
|
411
433
|
* 已经下线)。每次重放自增,回来时代数对不上就作废 —— 否则会用旧名单盖掉新的那一层。
|
|
@@ -427,8 +449,110 @@ export function createToolVisibility(deps) {
|
|
|
427
449
|
catch (e) { /* ignore */ }
|
|
428
450
|
}
|
|
429
451
|
}
|
|
430
|
-
/**
|
|
431
|
-
|
|
452
|
+
/**
|
|
453
|
+
* 同步段能算出的 deny 名单:全局名单 + 本会话模型工具表覆盖 + 载体让位。
|
|
454
|
+
*
|
|
455
|
+
* 子代理创建时,宿主在 `agent/created` 返回后立刻组装首轮工具表;限制层若等
|
|
456
|
+
* `tools.schemas()` 回来再装,那一轮就会先看到全部工具(子代理 fork 时表现为
|
|
457
|
+
* 「新增 24 / 移除 24」)。凡是判据本身同步可得的都必须在这里算完 ——
|
|
458
|
+
* 包括载体让位(`tools.get(name, agent)` 是同步的)。只有真的异步的(MCP 会话覆盖)
|
|
459
|
+
* 才留给随后的 `restrictAgent` 补齐。
|
|
460
|
+
*/
|
|
461
|
+
function syncDenyNamesFor(agent) {
|
|
462
|
+
const wanted = new Set(desiredNames);
|
|
463
|
+
// 启动早期 `desiredNames` 可能还没算出来;工具表设置本身是同步可读的,先并进来。
|
|
464
|
+
if (deps.pluginHiddenTools) {
|
|
465
|
+
try {
|
|
466
|
+
for (const name of deps.pluginHiddenTools())
|
|
467
|
+
wanted.add(name);
|
|
468
|
+
}
|
|
469
|
+
catch { /* 读设置失败 = 只装全局名单 */ }
|
|
470
|
+
}
|
|
471
|
+
// 载体让位(官方 `skill` 在场 → 藏 `skill_manager_read`)同样必须进同步段:
|
|
472
|
+
// 判据只是 `tools.get(name, agent)`,同步可得。漏掉这一条的后果与 issue #29 一模一样 ——
|
|
473
|
+
// 子代理首轮工具表里两条都在,随后异步段才摘掉一条,轨迹上就是「移除工具」。
|
|
474
|
+
//
|
|
475
|
+
// 单独收一份而不是并进 `wanted`:它**不受会话 allow 影响**。让位判的是"官方等价物
|
|
476
|
+
// 已经在场,这条只是重复",不是用户的可见性偏好 —— 会话把一条本不该在清单里的重复
|
|
477
|
+
// 工具重新打开,语义上说不通。并进 `wanted` 会让 allow 赢过它,而异步段
|
|
478
|
+
// (`restrictAgent`)的 `extra` 是加在 allow 之后的 —— 两段对同一份名单给出相反结论,
|
|
479
|
+
// 于是首轮有、第二步没,轨迹上又是一次「移除工具」。
|
|
480
|
+
const carrier = new Set();
|
|
481
|
+
if (deps.carrierHiddenTools) {
|
|
482
|
+
try {
|
|
483
|
+
const hidden = deps.carrierHiddenTools(agent);
|
|
484
|
+
// 异步实现拿不到这一轮结果:交给 `restrictAgent` 补(那一轮会重装并上报)。
|
|
485
|
+
if (typeof hidden?.then !== 'function') {
|
|
486
|
+
for (const name of hidden)
|
|
487
|
+
carrier.add(name);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
catch { /* 判据失败 = 不让位(宁可多花 token,也不让模型少一条路) */ }
|
|
491
|
+
}
|
|
492
|
+
let allow = [];
|
|
493
|
+
if (deps.sessionToolTableOverlay) {
|
|
494
|
+
try {
|
|
495
|
+
const ov = deps.sessionToolTableOverlay(agent);
|
|
496
|
+
// 覆盖实现是异步的时拿不到这一轮结果:只装全局名单,交给 `restrictAgent` 补。
|
|
497
|
+
if (ov !== undefined && typeof ov.then !== 'function') {
|
|
498
|
+
const sync = ov;
|
|
499
|
+
if (sync.allow !== undefined)
|
|
500
|
+
allow = sync.allow;
|
|
501
|
+
if (sync.deny !== undefined)
|
|
502
|
+
for (const name of sync.deny)
|
|
503
|
+
wanted.add(name);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
catch { /* 取不到 = 跟随全局 */ }
|
|
507
|
+
}
|
|
508
|
+
// 与 `restrictAgent` 同一条边界:停用表读不出来时,会话 allow 不得越过它把 mcp__* 放回来。
|
|
509
|
+
const allowSet = disabledToolsState() === 'unknown'
|
|
510
|
+
? new Set([...allow].filter((name) => !name.startsWith(MCP_TOOL_PREFIX)))
|
|
511
|
+
: new Set(allow);
|
|
512
|
+
// 与 `restrictAgent` 同形:会话 allow 只减全局那半边,载体让位加在它之后。
|
|
513
|
+
const names = [...new Set([...[...wanted].filter((name) => !allowSet.has(name)), ...carrier])];
|
|
514
|
+
// 官方 `restrict` 对认不出的名字是整份名单抛错。同步段没有注册全集可求交,
|
|
515
|
+
// 改问全局视图(同步、无 I/O);已被限制摘掉的名字在这里仍算 known。
|
|
516
|
+
return typeof deps.tools.get === 'function'
|
|
517
|
+
? names.filter((name) => { try {
|
|
518
|
+
return deps.tools.get(name) !== undefined;
|
|
519
|
+
}
|
|
520
|
+
catch {
|
|
521
|
+
return false;
|
|
522
|
+
} })
|
|
523
|
+
: names;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* 同步装层,赶在宿主组装首轮工具表之前(只给 `attachAgent` 用)。
|
|
527
|
+
*
|
|
528
|
+
* 失败不在这里上报:随后的 `restrictAgent` 会重试并如实上报,两处都失败才是问题。
|
|
529
|
+
*/
|
|
530
|
+
function installSyncRestriction(agent) {
|
|
531
|
+
const scoped = scopedToolsOf(agent);
|
|
532
|
+
if (!scoped || typeof scoped.restrict !== 'function')
|
|
533
|
+
return;
|
|
534
|
+
const denyNames = syncDenyNamesFor(agent);
|
|
535
|
+
const denyKey = denyNames.slice().sort().join('\u0000');
|
|
536
|
+
if (appliedByAgent.get(agent) === denyKey)
|
|
537
|
+
return;
|
|
538
|
+
liftRestriction(agent);
|
|
539
|
+
if (denyNames.length === 0)
|
|
540
|
+
return;
|
|
541
|
+
try {
|
|
542
|
+
const dispose = scoped.restrict({ deny: denyNames });
|
|
543
|
+
agentRestrictions.set(agent, typeof dispose === 'function' ? dispose : () => { });
|
|
544
|
+
appliedByAgent.set(agent, denyKey);
|
|
545
|
+
}
|
|
546
|
+
catch { /* 异步那一轮会重试并上报 */ }
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* 把该 agent 该背的名单装到它 scope 上(全局那份 ∓ 会话覆盖 ∪ 它自己那份;空名单 = 不碰它)。
|
|
550
|
+
*
|
|
551
|
+
* @param registered 这一轮 `applyToolRestrictions` 枚举到的已注册工具名全集。逐 agent
|
|
552
|
+
* 复用同一份 —— 覆盖判据要在"此刻注册着什么"上算全名,而每轮只该枚举一次
|
|
553
|
+
* (`schemas()` 是全量深拷贝,N 个 agent 就是 1+N 次)。
|
|
554
|
+
*/
|
|
555
|
+
async function restrictAgent(agent, registered) {
|
|
432
556
|
const mine = epoch;
|
|
433
557
|
let extra = [];
|
|
434
558
|
if (deps.carrierHiddenTools) {
|
|
@@ -442,12 +566,12 @@ export function createToolVisibility(deps) {
|
|
|
442
566
|
}
|
|
443
567
|
// 会话层的两个方向:`deny` 追加、`allow` 从全局名单里减掉 —— 允许**减**
|
|
444
568
|
// 是关键:全局停用表(含场景引擎写的收窄)关着的工具,本会话显式拨开 / 场景勾着时
|
|
445
|
-
// 要能重新看见,而全局一个字不动。名单已按注册全名算过(调用方用同一份
|
|
569
|
+
// 要能重新看见,而全局一个字不动。名单已按注册全名算过(调用方用同一份 registered),
|
|
446
570
|
// 这里照样过一遍 registered 过滤 —— 认不出的名字官方 restrict 会直接抛。
|
|
447
571
|
let allowSet = new Set();
|
|
448
572
|
if (deps.sessionMcpOverlay) {
|
|
449
573
|
try {
|
|
450
|
-
const ov = await deps.sessionMcpOverlay(agent);
|
|
574
|
+
const ov = await deps.sessionMcpOverlay(agent, registered);
|
|
451
575
|
if (ov) {
|
|
452
576
|
if (ov.deny !== undefined && ov.deny.length)
|
|
453
577
|
extra = [...extra, ...ov.deny];
|
|
@@ -481,7 +605,18 @@ export function createToolVisibility(deps) {
|
|
|
481
605
|
const effectiveAllow = disabledToolsState() === 'unknown'
|
|
482
606
|
? new Set([...allowSet].filter((name) => !name.startsWith(MCP_TOOL_PREFIX)))
|
|
483
607
|
: allowSet;
|
|
484
|
-
|
|
608
|
+
// 全局名单以 `desiredNames` 为底,再并一次当前的工具表设置:启动早期
|
|
609
|
+
// `applyToolRestrictions` 可能还没算出 `desiredNames`,而 `attachAgent` 的同步段
|
|
610
|
+
// 已经按设置装了一层 —— 两边必须同源,否则异步这一轮会把同步层撤掉。
|
|
611
|
+
const globalNames = new Set(desiredNames);
|
|
612
|
+
if (deps.pluginHiddenTools) {
|
|
613
|
+
try {
|
|
614
|
+
for (const name of deps.pluginHiddenTools())
|
|
615
|
+
globalNames.add(name);
|
|
616
|
+
}
|
|
617
|
+
catch { /* 读设置失败 = 只装已算出的全局名单 */ }
|
|
618
|
+
}
|
|
619
|
+
const names = [...new Set([...globalNames].filter((name) => !effectiveAllow.has(name)).concat(extra))];
|
|
485
620
|
const scoped = scopedToolsOf(agent);
|
|
486
621
|
if (!scoped || typeof scoped.restrict !== 'function') {
|
|
487
622
|
if (names.length === 0)
|
|
@@ -522,6 +657,21 @@ export function createToolVisibility(deps) {
|
|
|
522
657
|
agentRestrictions.set(agent, typeof dispose === 'function' ? dispose : () => { });
|
|
523
658
|
appliedByAgent.set(agent, denyKey);
|
|
524
659
|
clearRuntimeNote('mcp-tool-visibility');
|
|
660
|
+
// 成功路径此前完全静默,出问题时日志里看不到任何证据 —— 只能靠猜。
|
|
661
|
+
// 报这一行是为了让「工具表关掉了什么、这一层装上了没有」在命令行就能查。
|
|
662
|
+
//
|
|
663
|
+
// 只在**装上了非自家工具**时才打:工具表只管自家那批,deny 名单里出现别的东西
|
|
664
|
+
// 意味着有别的东西混进来了 —— 那是该查的异常。日常(全是自家工具 + MCP 工具)不刷屏。
|
|
665
|
+
const foreign = denyNames.filter((name) => {
|
|
666
|
+
if (name.startsWith(MCP_TOOL_PREFIX))
|
|
667
|
+
return false;
|
|
668
|
+
return deps.isPluginToolName ? !deps.isPluginToolName(name) : false;
|
|
669
|
+
});
|
|
670
|
+
if (foreign.length > 0) {
|
|
671
|
+
console.warn('[dsh-plugin-tool-management] restrict 已装上,但名单里有非本插件的工具:'
|
|
672
|
+
+ foreign.slice(0, 20).join('、')
|
|
673
|
+
+ '(工具表只该管自家工具,宿主工具归宿主 —— 这几条是谁放进来的?)');
|
|
674
|
+
}
|
|
525
675
|
}
|
|
526
676
|
catch (e) {
|
|
527
677
|
// 这个名字在这个 scope 里认不出 / scope 已经收了:可见性半边没生效。执行侧的 guard
|
|
@@ -535,14 +685,53 @@ export function createToolVisibility(deps) {
|
|
|
535
685
|
detailKey: 'mcp-tool-visibility.partial',
|
|
536
686
|
params: { reason: deps.message(e) },
|
|
537
687
|
});
|
|
688
|
+
// 失败也要落到日志:`noteRuntime` 只存进程内存,只能从兼容页看到,
|
|
689
|
+
// 命令行排查时等于没有。带上原因与名单长度 —— 官方 `restrict` 对认不出的名字是
|
|
690
|
+
// **整份名单抛错**,所以「装不上」往往意味着名单里有一条过期名字。
|
|
691
|
+
//
|
|
692
|
+
// 失败路径没有「键相同就跳过」那层保护(装不上就没装上,下一轮还要再试),
|
|
693
|
+
// 而 `tools/change` 在空闲时也能到十几次/秒 —— 每次都打一行会把日志刷爆。
|
|
694
|
+
// 按 (agent, 名单, 原因) 去重:同一份失败只报第一次,名单或原因变了才再报。
|
|
695
|
+
const failKey = agentIdOf(agent) + '\u0000' + denyKey + '\u0000' + deps.message(e);
|
|
696
|
+
if (reportedRestrictFailures.get(failKey) !== true) {
|
|
697
|
+
// 上限:失败是罕见路径,但 agent 会话来来去去,键会一直攒 —— 满了就清空重来
|
|
698
|
+
// (代价是旧失败可能再报一次,那也比无界增长好)。
|
|
699
|
+
if (reportedRestrictFailures.size >= 200)
|
|
700
|
+
reportedRestrictFailures.clear();
|
|
701
|
+
reportedRestrictFailures.set(failKey, true);
|
|
702
|
+
console.warn('[dsh-plugin-tool-management] restrict 装层失败(可见性半边没生效,执行侧拦截仍在拦):'
|
|
703
|
+
+ deps.message(e)
|
|
704
|
+
+ '|本次名单 ' + denyNames.length + ' 条');
|
|
705
|
+
}
|
|
538
706
|
}
|
|
539
707
|
}
|
|
540
|
-
/**
|
|
708
|
+
/**
|
|
709
|
+
* agent 上线(`agent/created` 或启动期的 agent 列表):登记,先同步装一层,再异步补齐。
|
|
710
|
+
*
|
|
711
|
+
* 同步那层是给宿主首轮工具表用的(见 `installSyncRestriction`);异步那层补 MCP 会话
|
|
712
|
+
* 覆盖与载体工具。注册全集优先复用 `registeredNames`,没有才枚举一次。事件频率是
|
|
713
|
+
* "每个会话一次",与 `tools/change` 那条热路径无关 —— 后者在 `applyToolRestrictions`
|
|
714
|
+
* 里共用一份。
|
|
715
|
+
*/
|
|
541
716
|
function attachAgent(agent) {
|
|
542
717
|
if (!agent || (typeof agent !== 'object' && typeof agent !== 'function'))
|
|
543
718
|
return;
|
|
544
719
|
seenAgents.add(agent);
|
|
545
|
-
|
|
720
|
+
// 先同步装一层:`agent/created` 返回后宿主就组装首轮工具表,等异步枚举回来已经晚了一轮。
|
|
721
|
+
installSyncRestriction(agent);
|
|
722
|
+
void (async () => {
|
|
723
|
+
let registered = registeredNames;
|
|
724
|
+
if (registered === null) {
|
|
725
|
+
try {
|
|
726
|
+
registered = new Set((await deps.tools.schemas()).map((schema) => String(schema.name)));
|
|
727
|
+
registeredNames = registered;
|
|
728
|
+
}
|
|
729
|
+
catch {
|
|
730
|
+
registered = new Set();
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
await restrictAgent(agent, registered);
|
|
734
|
+
})().catch(() => { });
|
|
546
735
|
}
|
|
547
736
|
/** agent 下线(`agent/disposed`):先撤限制再销登记。 */
|
|
548
737
|
function detachAgent(agent) {
|
|
@@ -565,14 +754,16 @@ export function createToolVisibility(deps) {
|
|
|
565
754
|
});
|
|
566
755
|
return;
|
|
567
756
|
}
|
|
568
|
-
//
|
|
569
|
-
//
|
|
570
|
-
|
|
757
|
+
// 走 TTL 缓存:写路径自己会 bump epoch 让缓存失效,外部手改最迟一个 TTL(3s)生效。
|
|
758
|
+
// 此前这里用 force,注释说"这条走 tools/change 路径,频率低" —— 而同一个文件记录了
|
|
759
|
+
// 空闲态能到 ~17.8 次/秒 tools/change,两处对同一事件的判断互相矛盾。
|
|
760
|
+
const read = await readDisabledToolsResult();
|
|
571
761
|
const unknown = read.status === 'corrupt' || read.status === 'unreadable';
|
|
572
762
|
const map = read.status === 'ok' ? read.value : emptyDisabledTools();
|
|
573
763
|
let registered;
|
|
574
764
|
try {
|
|
575
765
|
registered = new Set((await deps.tools.schemas()).map((schema) => String(schema.name)));
|
|
766
|
+
registeredNames = registered;
|
|
576
767
|
// 枚举成功 = 上一轮「schemas 失败」已恢复;no-restrict 也在前面那道检查里确认过。
|
|
577
768
|
// 逐 agent 的 partial 若仍成立,restrictAgent 会在下面重新上报。
|
|
578
769
|
clearRuntimeNote('mcp-tool-visibility');
|
|
@@ -643,8 +834,10 @@ export function createToolVisibility(deps) {
|
|
|
643
834
|
for (const agent of [...agentRestrictions.keys()])
|
|
644
835
|
if (!seenAgents.has(agent))
|
|
645
836
|
liftRestriction(agent);
|
|
837
|
+
// 逐 agent 复用上面那份 `registered`:`schemas()` 是全量深拷贝,每 agent 各枚举一次
|
|
838
|
+
// 就是 1+N 次,而它们要回答的只是"这个名字此刻注册着吗"。
|
|
646
839
|
for (const agent of seenAgents)
|
|
647
|
-
void restrictAgent(agent).catch(() => { });
|
|
840
|
+
void restrictAgent(agent, registered).catch(() => { });
|
|
648
841
|
}
|
|
649
842
|
function scheduleToolRestrictions() {
|
|
650
843
|
if (restrictTimer)
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// 自动记忆的注入索引(`evolution/catalog.json`)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要它:注入热路径不能读正文。300 条 × 2 KB 全读约 100–300ms,而只读这份派生索引
|
|
4
|
+
// 约 10ms。条数再多,注入成本也应该基本不变 —— 这是"记忆多了也不会变慢"的那一半。
|
|
5
|
+
//
|
|
6
|
+
// 为什么是**派生**数据:它全部可以从「磁盘文件 + evolution/state.json」重建。所以损坏了
|
|
7
|
+
// 直接重建,不做修复、不做迁移、不写墓碑。真源永远是文件与 state(见 docs 02-storage §4)。
|
|
8
|
+
//
|
|
9
|
+
// 为什么一条记忆一个 md 文件而不是合成一个大文件:合并省的是读取,丢的是单条回滚、并发写
|
|
10
|
+
// 和条目级回收;而且合并会诱导"读整文件 → 改 → 写整文件",那正是 ACE 实测的 context
|
|
11
|
+
// collapse 条件。读取的问题由这份索引解决,不用合并解决。
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { parseSkillDoc } from '../skills/core.js';
|
|
16
|
+
import { AUTO_ONELINE_MAX, LAYER_SCENE, LAYER_SESSION, LAYER_WORKSPACE, layerOfGroup } from './constants.js';
|
|
17
|
+
import { deriveFromDoc, discover } from './discovery.js';
|
|
18
|
+
import { sceneOf } from './projection.js';
|
|
19
|
+
import { excerptOf } from '../text-width.js';
|
|
20
|
+
/** hub 内相对路径。 */
|
|
21
|
+
export const CATALOG_FILE = 'evolution/catalog.json';
|
|
22
|
+
export const CATALOG_VERSION = 1;
|
|
23
|
+
/**
|
|
24
|
+
* catalog 的绝对落点。
|
|
25
|
+
*
|
|
26
|
+
* 由 `stateDir` 拼出来而不是走 `hubPath()`:服务可以注入自定义 stateDir(测试与多实例),
|
|
27
|
+
* 而 `hubPath()` 永远指向 `$DSH_HOME/tool-management`。两边各拼一次的话,注入 stateDir
|
|
28
|
+
* 时会出现"写在一处、读在另一处"——症状是学了但注入里永远看不见。
|
|
29
|
+
*/
|
|
30
|
+
export const catalogPathOf = (stateDir) => join(stateDir, CATALOG_FILE);
|
|
31
|
+
/**
|
|
32
|
+
* "会进上下文"的状态(P4 起含 playbook)。
|
|
33
|
+
*
|
|
34
|
+
* 散落在各处的 `status === 'active' || status === 'core'` 每加一级状态就要改一遍,漏一处
|
|
35
|
+
* 的症状很隐蔽:条目在清单里显示"生效",注入里却永远看不见。统一收在这里。
|
|
36
|
+
*/
|
|
37
|
+
export const INJECTABLE_STATUSES = ['active', 'core', 'playbook'];
|
|
38
|
+
export const isInjectableStatus = (status) => INJECTABLE_STATUSES.includes(status);
|
|
39
|
+
/** UTF-8 字节 → 估算 token。按 3 bytes/token(中文)算:对英文是高估,高估是安全的。 */
|
|
40
|
+
export const estimateTokens = (bytes) => Math.max(1, Math.ceil(bytes / 3));
|
|
41
|
+
/** 正文压成一行并按显示宽度截断;空正文返回空串。只用于列表扫读,注入用完整正文。 */
|
|
42
|
+
export function oneLineOf(text, max = AUTO_ONELINE_MAX) {
|
|
43
|
+
return excerptOf(text, max);
|
|
44
|
+
}
|
|
45
|
+
/** 一条记忆是否该进 catalog:只看来源,不看目录(目录只决定层)。 */
|
|
46
|
+
function isAutoOrigin(origin, layer) {
|
|
47
|
+
if (origin === 'auto')
|
|
48
|
+
return true;
|
|
49
|
+
if (origin === 'user')
|
|
50
|
+
return false;
|
|
51
|
+
// 没写 origin 时按目录判:工作区/会话层的文件默认就是 agent 写的(手写入口不会往这两层放,
|
|
52
|
+
// 除非用户显式指定,那时 save 会写 origin: user)。
|
|
53
|
+
return layer === LAYER_WORKSPACE || layer === LAYER_SESSION;
|
|
54
|
+
}
|
|
55
|
+
/** 目录名 → 归属键。 */
|
|
56
|
+
function ownerOf(group) {
|
|
57
|
+
const parts = String(group ?? '').split('/');
|
|
58
|
+
const head = parts[0];
|
|
59
|
+
const second = parts[1] ?? '';
|
|
60
|
+
if (head === '_ws')
|
|
61
|
+
return { workspace: second, session: '' };
|
|
62
|
+
if (head === '_session')
|
|
63
|
+
return { workspace: '', session: second };
|
|
64
|
+
return { workspace: '', session: '' };
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* 全量重建。
|
|
68
|
+
*
|
|
69
|
+
* 只在启动、版本不符、或条目数变化时跑(300 条约 40ms)。日常写入走增量更新 —— 那条路径
|
|
70
|
+
* 在 P1 的写入管线里(只改一条卡片再原子写)。
|
|
71
|
+
*/
|
|
72
|
+
export async function buildCatalog(memoriesRoot, index) {
|
|
73
|
+
const discovery = await discover(memoriesRoot);
|
|
74
|
+
const entries = {};
|
|
75
|
+
for (const entry of discovery.entries.values()) {
|
|
76
|
+
const layer = layerOfGroup(entry.group);
|
|
77
|
+
let text;
|
|
78
|
+
let info;
|
|
79
|
+
try {
|
|
80
|
+
const [raw, st] = await Promise.all([readFile(entry.docPath, 'utf8'), stat(entry.docPath)]);
|
|
81
|
+
text = raw;
|
|
82
|
+
info = { mtimeMs: st.mtimeMs, size: st.size };
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// 扫描与读取之间被删 / 读不动:跳过。下次重建会再校正。
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const doc = parseSkillDoc(text);
|
|
89
|
+
const derived = deriveFromDoc(entry, doc);
|
|
90
|
+
if (!isAutoOrigin(derived.origin, layer))
|
|
91
|
+
continue;
|
|
92
|
+
const idx = index.rules[entry.id];
|
|
93
|
+
const { workspace, session } = ownerOf(entry.group);
|
|
94
|
+
// 注入用完整正文;`oneLine` 只是列表摘要。字节按正文算 —— 进上下文的是它。
|
|
95
|
+
const body = String(doc.body ?? '').trim();
|
|
96
|
+
const oneLine = oneLineOf(body);
|
|
97
|
+
const bytes = Buffer.byteLength(body, 'utf8');
|
|
98
|
+
// `auto_title` 是 P4 才有的字段;旧条目没有时留空,注入侧会退回 key / 文件名。
|
|
99
|
+
const autoTitle = typeof doc.map.auto_title === 'string' ? String(doc.map.auto_title).trim() : '';
|
|
100
|
+
entries[entry.id] = {
|
|
101
|
+
id: entry.id,
|
|
102
|
+
layer,
|
|
103
|
+
workspace,
|
|
104
|
+
scene: layer === LAYER_SCENE ? sceneOf(entry.group) : layer === LAYER_WORKSPACE ? (derived.autoScene ?? '') : '',
|
|
105
|
+
session,
|
|
106
|
+
kind: derived.autoKind ?? '',
|
|
107
|
+
key: derived.autoKey ?? '',
|
|
108
|
+
...(autoTitle !== '' ? { title: autoTitle } : {}),
|
|
109
|
+
...(derived.autoBoundary !== undefined ? { boundary: derived.autoBoundary } : {}),
|
|
110
|
+
// 自动条目缺省 candidate:没有证据链的条目不该被当成 active 注入。
|
|
111
|
+
status: derived.autoStatus ?? 'candidate',
|
|
112
|
+
body,
|
|
113
|
+
oneLine,
|
|
114
|
+
bytes,
|
|
115
|
+
estTokens: estimateTokens(bytes),
|
|
116
|
+
enabled: idx?.enabled !== false,
|
|
117
|
+
mtime: info.mtimeMs,
|
|
118
|
+
size: info.size,
|
|
119
|
+
hash: createHash('sha256').update(text).digest('hex'),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return { version: CATALOG_VERSION, builtAt: new Date().toISOString(), entries };
|
|
123
|
+
}
|
|
124
|
+
/** 宽松读:结构不对就当没有(catalog 是派生数据,重建即可)。 */
|
|
125
|
+
export function normalizeCatalog(raw) {
|
|
126
|
+
const r = raw && typeof raw === 'object' ? raw : {};
|
|
127
|
+
if (r.version !== CATALOG_VERSION || !r.entries || typeof r.entries !== 'object') {
|
|
128
|
+
return { version: CATALOG_VERSION, builtAt: '', entries: {} };
|
|
129
|
+
}
|
|
130
|
+
const entries = {};
|
|
131
|
+
for (const [id, v] of Object.entries(r.entries)) {
|
|
132
|
+
if (!v || typeof v !== 'object' || typeof v.oneLine !== 'string')
|
|
133
|
+
continue;
|
|
134
|
+
entries[id] = {
|
|
135
|
+
id,
|
|
136
|
+
layer: v.layer,
|
|
137
|
+
workspace: typeof v.workspace === 'string' ? v.workspace : '',
|
|
138
|
+
scene: typeof v.scene === 'string' ? v.scene : '',
|
|
139
|
+
session: typeof v.session === 'string' ? v.session : '',
|
|
140
|
+
kind: typeof v.kind === 'string' ? v.kind : '',
|
|
141
|
+
key: typeof v.key === 'string' ? v.key : '',
|
|
142
|
+
status: typeof v.status === 'string' ? v.status : 'candidate',
|
|
143
|
+
// 旧 catalog 没有 `body`(那时注入的是 `oneLine`):退回它,别让条目在升级后
|
|
144
|
+
// 变成"有摘要、没正文"而注入失败。下次重建会写回完整正文。
|
|
145
|
+
body: typeof v.body === 'string' ? v.body : v.oneLine,
|
|
146
|
+
oneLine: v.oneLine,
|
|
147
|
+
bytes: typeof v.bytes === 'number' ? v.bytes : estimateTokens(0),
|
|
148
|
+
estTokens: typeof v.estTokens === 'number' ? v.estTokens : estimateTokens(0),
|
|
149
|
+
enabled: v.enabled !== false,
|
|
150
|
+
mtime: typeof v.mtime === 'number' ? v.mtime : 0,
|
|
151
|
+
size: typeof v.size === 'number' ? v.size : 0,
|
|
152
|
+
hash: typeof v.hash === 'string' ? v.hash : '',
|
|
153
|
+
// 只在有值时加键:深比较时多出 undefined 会被当成"变了"。
|
|
154
|
+
...(typeof v.title === 'string' && v.title !== '' ? { title: v.title } : {}),
|
|
155
|
+
...(typeof v.boundary === 'string' && v.boundary !== '' ? { boundary: v.boundary } : {}),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
return { version: CATALOG_VERSION, builtAt: typeof r.builtAt === 'string' ? r.builtAt : '', entries };
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* 按当前会话选可见条目。
|
|
162
|
+
*
|
|
163
|
+
* 过滤是**结构性的**:`session` 层只认自己的 sid,别的 sid 一条都选不到 —— 它们在磁盘上
|
|
164
|
+
* 也是独立目录,扫描阶段就进不来。这里再判一次是第二道保险(防止 catalog 被手工改过)。
|
|
165
|
+
*/
|
|
166
|
+
export function visibleEntries(catalog, scope) {
|
|
167
|
+
const out = [];
|
|
168
|
+
for (const e of Object.values(catalog.entries)) {
|
|
169
|
+
if (!e.enabled)
|
|
170
|
+
continue;
|
|
171
|
+
if (!isInjectableStatus(e.status))
|
|
172
|
+
continue;
|
|
173
|
+
if (e.layer === LAYER_WORKSPACE) {
|
|
174
|
+
if (scope.workspaceHash === undefined || e.workspace !== scope.workspaceHash)
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
else if (e.layer === LAYER_SESSION) {
|
|
178
|
+
if (scope.sessionId === undefined || e.session !== scope.sessionId)
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
else if (e.layer === LAYER_SCENE) {
|
|
182
|
+
if (!scope.enabledScenes || !scope.enabledScenes.has(e.scene))
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
out.push(e);
|
|
186
|
+
}
|
|
187
|
+
return out;
|
|
188
|
+
}
|
|
189
|
+
/** 写盘前的形状校验(P1 的写入管线与 UI 都会调用)。 */
|
|
190
|
+
export function catalogEntryOf(id, layer, fields) {
|
|
191
|
+
const body = String(fields.body ?? '').trim();
|
|
192
|
+
const oneLine = fields.oneLine !== undefined ? oneLineOf(fields.oneLine) : oneLineOf(body);
|
|
193
|
+
const bytes = Buffer.byteLength(body, 'utf8');
|
|
194
|
+
const { workspace, session } = ownerOf(id.slice(0, id.lastIndexOf('/')));
|
|
195
|
+
return {
|
|
196
|
+
id,
|
|
197
|
+
layer,
|
|
198
|
+
workspace: fields.workspace ?? workspace,
|
|
199
|
+
scene: fields.scene ?? '',
|
|
200
|
+
session: fields.session ?? session,
|
|
201
|
+
kind: fields.kind ?? '',
|
|
202
|
+
key: fields.key ?? '',
|
|
203
|
+
...(fields.title !== undefined && fields.title !== '' ? { title: fields.title } : {}),
|
|
204
|
+
...(fields.boundary !== undefined && fields.boundary !== '' ? { boundary: fields.boundary } : {}),
|
|
205
|
+
status: fields.status ?? 'candidate',
|
|
206
|
+
body,
|
|
207
|
+
oneLine,
|
|
208
|
+
bytes,
|
|
209
|
+
estTokens: estimateTokens(bytes),
|
|
210
|
+
enabled: fields.enabled !== false,
|
|
211
|
+
mtime: fields.mtime ?? 0,
|
|
212
|
+
size: fields.size ?? bytes,
|
|
213
|
+
hash: fields.hash ?? '',
|
|
214
|
+
};
|
|
215
|
+
}
|