dsh-plugin-tool-management 0.22.4 → 0.22.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -56,10 +56,11 @@ export { isValidGroupSegment, isValidGroupPath, MEMORIES_INDEX_FILE, MEMORIES_TR
56
56
  // parseModeState 搬到了 index-io.ts,但 test/contracts.test.mjs 按原路径引它 —— 契约不能断。
57
57
  export { parseModeState } from './index-io.js';
58
58
  // 投影 / 渲染纯函数(抽到 ./projection.ts):索引 → 界面与注入看到的那份文本。
59
- import { enabledSceneOf, normalizeActive, resolveActiveScenes, sceneLabel, sceneOf, sceneOrderOf, } from './projection.js';
59
+ import { enabledSceneOf, normalizeActive, resolveActiveScenes, sceneLabel, sceneOf, sceneOrderOf, signatureOfIndex, } from './projection.js';
60
60
  // 索引 IO 组与发现/快照组(抽出)。
61
61
  import { writeFileAtomically, isIndexQuarantined, readIndex, readIndexSync, writeIndex, repairFromQuarantine, isAbsentError } from './index-io.js';
62
62
  import { deriveFromDoc, projectRule, relocateLegacyLayout, buildSnapshot, probeSceneFilesSync, renderSceneCatalog, renderSceneMemory } from './snapshot.js';
63
+ import { watchDirectories } from '../skills/dir-watch.js';
63
64
  // ── 目录常量与失败约定 ─────────────────────────────────────────────────────
64
65
  // 其余跨文件共用的常量与无依赖小工具(message / isValidGroupSegment / isValidGroupPath /
65
66
  // MEMORIES_INDEX_FILE)已下沉到 ./constants.ts,避免 index-io / snapshot 反向引本文件。
@@ -219,12 +220,92 @@ export function createMemoriesService(ctx, deps) {
219
220
  if (isIndexQuarantined(stateDir))
220
221
  throw new Error('记忆索引当前读不到,无法确定哪些记忆处于启用状态');
221
222
  };
223
+ // ── 探测结果缓存(目录监听 + TTL 兜底)────────────────────────────────────
224
+ //
225
+ // 为什么需要:`probeSceneFilesSync` 是一次**完整目录树**的 readdirSync + 每文件 statSync,
226
+ // 而注入通道每个 step 都要同步取一次文本(scene 与 memory 两域各一次,入参相同)。
227
+ // 实测 2000 个记忆文件 ≈ 23 ms/次,每步 46 ms 全在事件循环上。
228
+ //
229
+ // 为什么不能只靠监听:worker 崩溃 / 某个目录挂不上都**不会**回报(`attached()` 只说
230
+ // "有没有挂上过"),把"监听还在"当成前提,静默失效就会变成永久返回旧内容 —— 那正是
231
+ // 本模块一直在避免的形态。所以监听只用来**提前**失效,TTL 才是兜底:
232
+ // · 监听挂着 → 命中缓存,watcher 一报变化立刻清;最坏 TTL 过期。
233
+ // · 监听没挂上 → 不进缓存,保持原来的每次探测。
234
+ //
235
+ // 键 = memoriesRoot + 索引指纹 + 会话覆盖指纹(`probeSceneFilesSync` 的入参三要素),
236
+ // 值 = probe 结果。会话覆盖不同 → 不同条目,与两份段缓存同一口径。
237
+ const PROBE_CACHE_TTL_MS = 5000;
238
+ const probeCache = new Map();
239
+ /**
240
+ * 监听没挂上时多久重试一次。
241
+ *
242
+ * 为什么不能"试一次就认命":`watchDirectories` 在目录**当时不存在**时直接返回未挂上,
243
+ * 而全新用户的记忆根目录是在第一次写记忆时才建出来的 —— 一次性的装配会让这个进程
244
+ * 从此永远拿不到缓存(每步仍全树 stat)。也不能每步都重试:没挂上时每步新建一个
245
+ * worker。30s 是两者的折中:最坏多付 30s 的无缓存,之后自动回到稳态。
246
+ *
247
+ * 同时兼作"worker 已崩"的复活间隔 —— 崩溃同样只表现为 `attached()` 为 false。
248
+ */
249
+ const WATCH_RETRY_MS = 30000;
250
+ let memoriesWatch = null;
251
+ let memoriesWatchAt = 0;
252
+ /** 清空探测缓存(watcher 报变化 / 写操作后 / 索引不可信时)。 */
253
+ const clearProbeCache = () => { probeCache.clear(); };
254
+ /**
255
+ * 取数时确保监听在。**推迟到首次使用**:apply 期 `roots()` / 目录物化会读宿主目录,
256
+ * 而这里只需要一个已存在的目录。
257
+ *
258
+ * `attached()` 是异步回来的:刚建出来的那一两拍必然读到 false。所以"没挂上"的重试
259
+ * 只在距上次装配超过 `WATCH_RETRY_MS` 时发生 —— 否则每步都会拆了重建一个 worker。
260
+ */
261
+ const ensureMemoriesWatch = () => {
262
+ const now = Date.now();
263
+ if (memoriesWatch !== null) {
264
+ if (memoriesWatch.attached())
265
+ return;
266
+ if (now - memoriesWatchAt < WATCH_RETRY_MS)
267
+ return;
268
+ try {
269
+ memoriesWatch.dispose();
270
+ }
271
+ catch { /* 旧的拆不掉也不挡新建 */ }
272
+ memoriesWatch = null;
273
+ }
274
+ memoriesWatchAt = now;
275
+ try {
276
+ memoriesWatch = watchDirectories([memoriesRoot], clearProbeCache);
277
+ }
278
+ catch {
279
+ memoriesWatch = null; // 建不出 worker = 没有监听,缓存靠 TTL(见上面的取舍)
280
+ }
281
+ };
282
+ /** 探测:监听挂着时走缓存,否则直连(`clearProbeCache` 之后必然直连一次)。 */
283
+ function probeWithCache(index, override) {
284
+ ensureMemoriesWatch();
285
+ const watched = memoriesWatch !== null && memoriesWatch.attached();
286
+ if (!watched)
287
+ return probeSceneFilesSync(memoriesRoot, index, false, override);
288
+ const key = memoriesRoot + '\u0000' + signatureOfIndex(index) + '\u0000' + scopeKeyOf(override);
289
+ const hit = probeCache.get(key);
290
+ if (hit !== undefined && Date.now() - hit.at < PROBE_CACHE_TTL_MS)
291
+ return hit.value;
292
+ const value = probeSceneFilesSync(memoriesRoot, index, false, override);
293
+ probeCache.set(key, { at: Date.now(), value });
294
+ // 上限:键里带会话覆盖,会话多时会有很多条;100 条 LRU 足够(同一时刻活跃的会话远少于此)。
295
+ while (probeCache.size > 100) {
296
+ const oldest = probeCache.keys().next();
297
+ if (oldest.done === true)
298
+ break;
299
+ probeCache.delete(oldest.value);
300
+ }
301
+ return value;
302
+ }
222
303
  /** 记忆段:注入侧口径(索引不可信或目录读不动 → 抛)。 */
223
304
  function requireSceneMemory(scope) {
224
305
  const index = readIndexSync(stateDir);
225
306
  assertIndexReadable(); // 抛在这里 ⇒ 下面必然处于「索引可信」状态,无需再传 forceDisabled
226
307
  const override = { scene: scope?.scene, memory: scope?.memory };
227
- const probe = probeSceneFilesSync(memoriesRoot, index, false, override);
308
+ const probe = probeWithCache(index, override);
228
309
  const key = scopeKeyOf(scope);
229
310
  const hit = cacheGet(sceneCache, key);
230
311
  if (hit !== undefined && hit.signature === probe.signature)
@@ -253,7 +334,7 @@ export function createMemoriesService(ctx, deps) {
253
334
  const index = readIndexSync(stateDir);
254
335
  assertIndexReadable();
255
336
  const override = { scene: scope?.scene, memory: scope?.memory };
256
- const probe = probeSceneFilesSync(memoriesRoot, index, false, override);
337
+ const probe = probeWithCache(index, override);
257
338
  const key = scopeKeyOf(scope);
258
339
  const hit = cacheGet(sceneCatalogCache, key);
259
340
  if (hit !== undefined && hit.signature === probe.signature)
@@ -575,6 +656,8 @@ export function createMemoriesService(ctx, deps) {
575
656
  // 都可能不同(比如某条记忆被本会话覆盖关掉),逐条算哪几条受影响只会漏。
576
657
  sceneCache.clear();
577
658
  sceneCatalogCache.clear();
659
+ // 探测缓存同样清:写操作刚改了磁盘,下一拍必须重扫(监听会晚 200ms 才报,别等它)。
660
+ clearProbeCache();
578
661
  };
579
662
  /**
580
663
  * 场景档案引擎专用:读-改-写 mode/archives/active 切片(写队列内,保持与其余索引写串行)。
@@ -1038,6 +1121,14 @@ export function createMemoriesService(ctx, deps) {
1038
1121
  promptFiles,
1039
1122
  promptBaselineText: readGlobalAgentsMdSync,
1040
1123
  refresh,
1124
+ dispose: () => {
1125
+ try {
1126
+ memoriesWatch?.dispose();
1127
+ }
1128
+ catch { /* 卸载路径上不留抛错 */ }
1129
+ memoriesWatch = null;
1130
+ probeCache.clear();
1131
+ },
1041
1132
  patchIndex,
1042
1133
  saveArchive,
1043
1134
  readArchiveSlice,
@@ -37,6 +37,21 @@ const META_FILE = 'meta.json';
37
37
  * 一句用户提示"),但那是两个各自独立的预算,别当成同一个常量共用。
38
38
  */
39
39
  export const DEFAULT_PRESET_DESC_MAX_LENGTH = 300;
40
+ /**
41
+ * 预设正文的字节上限(256 KiB),与记忆正文的 `MAX_RULE_BYTES` 同档。
42
+ *
43
+ * 为什么需要:注入侧虽按 64 KiB 截断(`AGENTS_MD_MAX_BYTES`),但盘上可以无限大,
44
+ * 而每次读都要整份进内存。上限拦在**写**这一侧 —— 已存在的超大文件不阻断读取,
45
+ * 用户还能把它改小。
46
+ */
47
+ export const MAX_PRESET_BYTES = 256 * 1024;
48
+ /** 正文超限时的拒绝回执;没超返回 null。 */
49
+ function presetTooLarge(content) {
50
+ const bytes = Buffer.byteLength(String(content ?? ''), 'utf8');
51
+ if (bytes <= MAX_PRESET_BYTES)
52
+ return null;
53
+ return { ok: false, error: `提示词正文过大(${bytes} 字节,上限 ${MAX_PRESET_BYTES >> 10} KiB)` };
54
+ }
40
55
  /**
41
56
  * 压成一行并按上限截断。与 `normalizeMcpNote`(`../mcp/state-section.ts`)同形:两处都是
42
57
  * "给模型看的一句用户文字",口径必须一致,否则同一句在界面、段、工具里会是三个样子。
@@ -243,6 +258,10 @@ export function createPromptsService(_ctx, deps) {
243
258
  content = BLANK_TEMPLATE;
244
259
  }
245
260
  }
261
+ // 判在 mkdir 之前:拒绝时磁盘上不留空目录。
262
+ const tooLarge = presetTooLarge(content);
263
+ if (tooLarge)
264
+ return tooLarge;
246
265
  await mkdir(dir, { recursive: true });
247
266
  await writeFileAtomically(join(dir, FILENAME), content);
248
267
  await writeDescription(safeId, options?.description);
@@ -256,6 +275,10 @@ export function createPromptsService(_ctx, deps) {
256
275
  const bad = idError(id);
257
276
  if (bad)
258
277
  return { ok: false, error: '非法 id:' + bad };
278
+ // 判在任何落盘之前:否则改名会先发生,正文却被拒,目录停在新 id 上。
279
+ const tooLarge = presetTooLarge(content);
280
+ if (tooLarge)
281
+ return tooLarge;
259
282
  const safeId = String(id ?? '').trim();
260
283
  const dir = join(deps.presetsDir, safeId);
261
284
  try {
@@ -636,6 +659,10 @@ export function createPromptsService(_ctx, deps) {
636
659
  return { ok: false, error: 'id 已存在:' + safeId };
637
660
  }
638
661
  catch { /* 不存在,继续 */ }
662
+ // 判在 mkdir 之前:拒绝时磁盘上不留空目录。
663
+ const tooLarge = presetTooLarge(content);
664
+ if (tooLarge)
665
+ return tooLarge;
639
666
  await mkdir(dir, { recursive: true });
640
667
  await writeFileAtomically(join(dir, FILENAME), String(content ?? ''));
641
668
  await writeDescription(safeId, description);
@@ -4,21 +4,24 @@
4
4
  // 写在它自己的注释里 —— Windows 上那条路会在目录被删除时静默卡死事件循环。
5
5
  import { existsSync } from 'node:fs';
6
6
  import { Worker } from 'node:worker_threads';
7
- // ── 文件监听:外部改动自动失效 ────────────────────────────────────────────
8
7
  /**
9
8
  * 监听目录,200ms 防抖后回调:在编辑器或其他工具里新增/修改/删除文件后,无需手动
10
- * 刷新即可看到变化。技能来源与规则根目录共用(见 src/memories/service.ts 的场景记忆段缓存)。
9
+ * 刷新即可看到变化。技能来源与记忆根目录共用。
11
10
  *
12
11
  * 为什么用 worker_threads:Windows 上 fs.watch(recursive) 的句柄在「被监听
13
12
  * 目录被删除」时会静默卡死事件循环(不触发 error、unref 也无效)——宿主
14
13
  * 进程将永远无法退出。把 watcher 放进独立的 worker 线程,主线程对 worker
15
14
  * unref(),无论目录发生什么,宿主与测试进程都能正常收尾;worker 内部失败
16
- * 也不影响主线程。目录不存在或平台不支持递归监听时静默跳过。
15
+ * 也不影响主线程。目录不存在或平台不支持递归监听时静默跳过(`attached: false`)。
16
+ *
17
+ * 已知边界:worker 崩溃或某个目录监听失败**不会**回报(它只是少了一条变化通知)。
18
+ * 所以依赖 `attached` 做缓存的调用方必须再叠一层 TTL —— 把"监听还在"当成前提,
19
+ * 静默失效就会变成永久返回旧内容。
17
20
  */
18
21
  export function watchDirectories(paths, invalidate) {
19
22
  const valid = paths.filter((dir) => dir && existsSync(dir));
20
23
  if (!valid.length)
21
- return () => { };
24
+ return { dispose: () => { }, attached: () => false };
22
25
  let timer = null;
23
26
  const fire = () => {
24
27
  if (timer)
@@ -32,40 +35,64 @@ export function watchDirectories(paths, invalidate) {
32
35
  }, 200);
33
36
  };
34
37
  let worker = null;
38
+ let attached = false;
35
39
  try {
36
40
  // eval 模式内联 worker 代码:无需额外文件与构建步骤。worker 事件循环独立,
37
41
  // 主线程 unref 后完全不参与宿主进程的退出判定。
38
42
  const src = `
39
43
  const { watch } = require('node:fs');
40
44
  const { parentPort, workerData } = require('node:worker_threads');
45
+ let live = 0;
41
46
  for (const dir of workerData.paths) {
42
47
  try {
43
- const w = watch(dir, { recursive: true, persistent: false }, () => {
48
+ // persistent: true 是必需的:worker 里若唯一的句柄是 non-persistent 的 watch,
49
+ // 事件循环当场空掉、worker 自己退出 —— 消息一条都收不到(实测)。不挡宿主退出
50
+ // 靠的是主线程对 worker 的 unref(),不是这里的 persistent。
51
+ const w = watch(dir, { recursive: true, persistent: true }, () => {
44
52
  try { parentPort.postMessage('change') } catch { /* worker 正在关闭 */ }
45
53
  });
46
54
  w.on('error', () => { /* 目录被移除等:忽略,不向主线程传播 */ });
55
+ live += 1;
47
56
  } catch { /* 不可监听(权限/平台)时跳过该目录 */ }
48
57
  }
58
+ parentPort.postMessage({ attached: live > 0 });
49
59
  `;
50
- worker = new Worker(src, { eval: true, workerData: { paths: valid } });
60
+ // `execArgv: []` 是必需的,不是洁癖:worker 默认**继承**父进程的 execArgv,
61
+ // 而 eval 模式的代码是 CommonJS(用了 `require`)。父进程若带着 `--input-type=module`
62
+ // (`node -e` / 测试用 `--input-type` 跑),那段代码会被当成 ESM 求值,
63
+ // `require is not defined` —— 表现为"监听静默没挂上",而这里的所有失败都是静默的。
64
+ worker = new Worker(src, { eval: true, workerData: { paths: valid }, execArgv: [] });
51
65
  worker.unref();
52
- worker.on('message', () => fire());
53
- worker.on('error', () => { });
66
+ worker.on('message', (msg) => {
67
+ if (msg && typeof msg === 'object' && 'attached' in msg) {
68
+ attached = msg.attached === true;
69
+ return;
70
+ }
71
+ fire();
72
+ });
73
+ // 崩溃 / 意外退出必须把 `attached` 降回 false:否则调用方会一直以为监听还挂着,
74
+ // 只靠 TTL 兜底,而重试逻辑(见记忆服务的 `ensureMemoriesWatch`)永远等不到复活机会。
75
+ // `dispose()` 先 `removeAllListeners()`,所以主动终止不会走到这里。
76
+ worker.on('error', () => { attached = false; });
77
+ worker.on('exit', () => { attached = false; });
54
78
  }
55
- catch { /* worker 不可用时静默跳过,功能退化为依赖 op 全量扫描 */ }
56
- return () => {
57
- if (timer) {
58
- clearTimeout(timer);
59
- timer = null;
60
- }
61
- if (worker) {
62
- const w = worker;
63
- worker = null;
64
- try {
65
- w.removeAllListeners();
66
- w.terminate();
79
+ catch { /* worker 不可用时静默跳过,功能退化为依赖调用方自己的 TTL */ }
80
+ return {
81
+ attached: () => attached,
82
+ dispose: () => {
83
+ if (timer) {
84
+ clearTimeout(timer);
85
+ timer = null;
86
+ }
87
+ if (worker) {
88
+ const w = worker;
89
+ worker = null;
90
+ try {
91
+ w.removeAllListeners();
92
+ w.terminate();
93
+ }
94
+ catch { /* ignore */ }
67
95
  }
68
- catch { /* ignore */ }
69
- }
96
+ },
70
97
  };
71
98
  }
@@ -332,7 +332,7 @@ export function createSkillsService(ctx, deps = {}) {
332
332
  .filter((root) => root.key !== 'official')
333
333
  .map((root) => String((root && root.path) || ''))
334
334
  .filter(Boolean);
335
- add(watchDirectories(watchPaths, invalidateSkills));
335
+ add(watchDirectories(watchPaths, invalidateSkills).dispose);
336
336
  // 自定义目录在状态文件里,注册时读取一次并一并监听(后添加的目录由
337
337
  // provider 首次 list 天然覆盖,等插件重载后才有 watcher)。
338
338
  return readManagerState();
@@ -344,7 +344,7 @@ export function createSkillsService(ctx, deps = {}) {
344
344
  .map((root) => String((root && root.path) || ''))
345
345
  .filter(Boolean);
346
346
  if (customPaths.length)
347
- add(watchDirectories(customPaths, invalidateSkills));
347
+ add(watchDirectories(customPaths, invalidateSkills).dispose);
348
348
  })
349
349
  .catch((e) => {
350
350
  console.error('[dsh-plugin-tool-management] skill watcher setup failed:', message(e));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-tool-management",
3
- "version": "0.22.4",
3
+ "version": "0.22.5",
4
4
  "description": "一个设置面板,统一管理 MCP、技能、记忆、子智能体、提示词和归档会话;可自定义搭配场景,一个场景即可切换整个环境;Agent也能帮你操作这个插件。",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,6 +25,9 @@
25
25
  "LICENSE",
26
26
  "screenshots.json",
27
27
  "docs/images",
28
+ "docs/ARCHITECTURE.md",
29
+ "docs/COMPATIBILITY.md",
30
+ "docs/TROUBLESHOOTING.md",
28
31
  "docs/UPDATE.md"
29
32
  ],
30
33
  "engines": {
@@ -37,9 +40,10 @@
37
40
  },
38
41
  "scripts": {
39
42
  "build": "tsc -p tsconfig.json && node scripts/sync-client.mjs && node scripts/sync-profile.mjs",
40
- "prepublishOnly": "npm run build && npm run lint && npm run typecheck:client && node --test test/client-exports.test.mjs",
43
+ "prepublishOnly": "npm run build && npm run lint && npm run check:css && npm run typecheck:client && node --test test/client-exports.test.mjs",
41
44
  "lint": "node --check lib/client.js && node --check lib/index.js",
42
45
  "typecheck:client": "node scripts/sync-client.mjs && tsc -p tsconfig.client.json",
46
+ "check:css": "node scripts/check-css-chain.mjs",
43
47
  "check:i18n": "node scripts/check-i18n.mjs lib/client.js",
44
48
  "check:host": "node scripts/host-deps.mjs && node scripts/doctor.mjs",
45
49
  "check:strict": "node scripts/check-strict.mjs",
@@ -126,17 +130,17 @@
126
130
  },
127
131
  "devDependencies": {
128
132
  "@deepseek-ai/cordis": "^4.1.0",
129
- "@deepseek-ai/dsh-agent-preset-registry": "^0.2.2-rc.1",
130
- "@deepseek-ai/dsh-llm": "^0.2.2-rc.1",
131
- "@deepseek-ai/dsh-session": "^0.2.2-rc.1",
132
- "@deepseek-ai/dsh-session-projection-cache": "^0.2.2-rc.1",
133
- "@deepseek-ai/dsh-settings": "^0.2.2-rc.1",
134
- "@deepseek-ai/dsh-spill-local": "^0.2.2-rc.1",
135
- "@deepseek-ai/dsh-storage-domain": "^0.2.2-rc.1",
136
- "@deepseek-ai/dsh-subagent-fork-in-process": "^0.2.2-rc.1",
137
- "@deepseek-ai/dsh-subagent-spawn-in-process": "^0.2.2-rc.1",
138
- "@deepseek-ai/dsh-tools": "^0.2.2-rc.1",
139
- "@deepseek-ai/dsh-workspace": "^0.2.2-rc.1",
133
+ "@deepseek-ai/dsh-agent-preset-registry": ">=0.2.2-rc.1 <0.2.3",
134
+ "@deepseek-ai/dsh-llm": ">=0.2.2-rc.1 <0.2.3",
135
+ "@deepseek-ai/dsh-session": ">=0.2.2-rc.1 <0.2.3",
136
+ "@deepseek-ai/dsh-session-projection-cache": ">=0.2.2-rc.1 <0.2.3",
137
+ "@deepseek-ai/dsh-settings": ">=0.2.2-rc.1 <0.2.3",
138
+ "@deepseek-ai/dsh-spill-local": ">=0.2.2-rc.1 <0.2.3",
139
+ "@deepseek-ai/dsh-storage-domain": ">=0.2.2-rc.1 <0.2.3",
140
+ "@deepseek-ai/dsh-subagent-fork-in-process": ">=0.2.2-rc.1 <0.2.3",
141
+ "@deepseek-ai/dsh-subagent-spawn-in-process": ">=0.2.2-rc.1 <0.2.3",
142
+ "@deepseek-ai/dsh-tools": ">=0.2.2-rc.1 <0.2.3",
143
+ "@deepseek-ai/dsh-workspace": ">=0.2.2-rc.1 <0.2.3",
140
144
  "@types/js-yaml": "^4.0.9",
141
145
  "@types/node": "^24.0.0",
142
146
  "@types/semver": "^7.7.0",