dsh-plugin-tool-management 0.7.0 → 0.8.0

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 (36) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +16 -5
  3. package/README_EN.md +16 -5
  4. package/docs/images/1/345/234/272/346/231/257.png +0 -0
  5. package/docs/images/1/345/234/272/346/231/257_en.png +0 -0
  6. package/docs/images/2MCP.png +0 -0
  7. package/docs/images/2MCP_en.png +0 -0
  8. package/docs/images/3/346/212/200/350/203/275.png +0 -0
  9. package/docs/images/3/346/212/200/350/203/275_en.png +0 -0
  10. package/docs/images/4/345/255/220/346/231/272/350/203/275/344/275/223.png +0 -0
  11. package/docs/images/4/345/255/220/346/231/272/350/203/275/344/275/223_en.png +0 -0
  12. package/docs/images/5/346/217/220/347/244/272/350/257/215.png +0 -0
  13. package/docs/images/5/346/217/220/347/244/272/350/257/215_en.png +0 -0
  14. package/docs/images/6/350/256/260/345/277/206.png +0 -0
  15. package/docs/images/6/350/256/260/345/277/206_en.png +0 -0
  16. package/docs/images/7/344/274/232/350/257/235.png +0 -0
  17. package/docs/images/7/344/274/232/350/257/235_en.png +0 -0
  18. package/docs/images/8/345/205/274/345/256/271.png +0 -0
  19. package/docs/images/8/345/205/274/345/256/271_en.png +0 -0
  20. package/docs/update.md +17 -0
  21. package/lib/agents-md/service.js +41 -3
  22. package/lib/client.js +820 -375
  23. package/lib/compat/preset-reach.js +1 -1
  24. package/lib/compat/probe.js +8 -0
  25. package/lib/index.js +433 -10
  26. package/lib/mcp/state-section.js +90 -0
  27. package/lib/prompt-sections.js +148 -0
  28. package/lib/rules/archive-engine.js +99 -29
  29. package/lib/rules/archive.js +56 -28
  30. package/lib/rules/service.js +259 -39
  31. package/lib/skills/core.js +4 -1
  32. package/lib/subagents/catalog.js +89 -0
  33. package/lib/subagents/service.js +189 -20
  34. package/lib/subagents/tools.js +10 -3
  35. package/package.json +97 -97
  36. package/lib/rules/provider.js +0 -121
@@ -29,12 +29,12 @@ import { randomUUID } from 'node:crypto';
29
29
  import { readFileSync, readdirSync, statSync } from 'node:fs';
30
30
  import { copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
31
31
  import { basename, dirname, join, resolve } from 'node:path';
32
- import { parseSkillDoc, resolveDshHome, unquote } from '../skills/core.js';
32
+ import { parseSkillDoc, renameWithRetry, resolveDshHome, unquote } from '../skills/core.js';
33
33
  import { expandUploads, planMemoryImport } from '../imports/upload.js';
34
- import { createRuleProviderRegistrar } from './provider.js';
34
+ import { SECTION_ORDER, createPromptSectionRegistrar } from '../prompt-sections.js';
35
35
  import { normalizePresetId } from '../agents-md/preset-id.js';
36
- import { normalizeArchive, memoryAllowed } from './archive.js';
37
- import { listTrashEntries, moveToTrash, purgeTrashEntry, readTrashEntry } from '../hub.js';
36
+ import { normalizeArchive } from './archive.js';
37
+ import { listTrashEntries, moveOutOfTrash, moveToTrash, purgeTrashEntry, readTrashEntry } from '../hub.js';
38
38
  // ── 常量 ───────────────────────────────────────────────────────────────────
39
39
  const MAX_SOURCE_DEPTH = 64; // 与 core.js 一致
40
40
  const MAX_DIRECTORIES = 2000; // 目录预算
@@ -102,25 +102,68 @@ export const MEMORIES_DIR = 'memories';
102
102
  export const GLOBAL_SCENE = 'global';
103
103
  /** 保留场景在界面上的显示名(磁盘上仍用 ASCII 目录/文件名)。 */
104
104
  export const GLOBAL_SCENE_LABEL = '全局';
105
+ /**
106
+ * 记忆导出的落盘映射(`bundle-export` 的 `kind: 'memories'` 用,见 design-plan D14)。
107
+ *
108
+ * 记忆有两种形态(见文件头):flat = `<场景>/<name>.md`,bundle = `<场景>/<name>/SKILL.md`;
109
+ * 而且**场景名本身可含 `/`**(多段场景名,见 `isValidGroupPath`)。所以「按 id 的最后一个
110
+ * `/` 切出场景与名字、再拼 `.md`」是错的:bundle 会被读成 `<场景>/<name>.md` → 读不到 →
111
+ * 该项目静默丢失(只在 `missing` 里留个名,界面按「导出成功」显示)。
112
+ *
113
+ * 这里一律按索引里那条规则自己的 `path` 与 `form` 决定;bundle 只交出目录,由调用方
114
+ * 把目录内的文件全部打包(与技能分支同口径)。索引里没有、或已被同名 bundle 遮蔽的 id
115
+ * 进 `missing`——遮蔽的 flat 不会被加载,导出去只会让人以为它能用。
116
+ *
117
+ * 纯函数(不碰磁盘),可直接断言。
118
+ */
119
+ export function planMemoryExport(names, rules) {
120
+ const list = Array.isArray(names) ? names.map((n) => String(n).trim()).filter(Boolean) : [];
121
+ const byId = new Map();
122
+ for (const row of (Array.isArray(rules) ? rules : [])) {
123
+ const id = row && typeof row.id === 'string' ? row.id : '';
124
+ if (id !== '')
125
+ byId.set(id, row);
126
+ }
127
+ const entries = [];
128
+ const missing = [];
129
+ for (const id of list) {
130
+ const row = byId.get(id);
131
+ const abs = row && typeof row.path === 'string' ? row.path : '';
132
+ if (!row || abs === '' || row.shadowed === true) {
133
+ missing.push(id);
134
+ continue;
135
+ }
136
+ entries.push(row.form === 'bundle'
137
+ ? { id, zip: id, abs: dirname(abs), kind: 'dir' }
138
+ : { id, zip: `${id}.md`, abs, kind: 'file' });
139
+ }
140
+ return { entries, missing };
141
+ }
105
142
  // ── 文件工具 ───────────────────────────────────────────────────────────────
106
- /** 同目录临时文件 + rename 原子写(临时名 `.xxx.dsh-rules-<uuid>.tmp`)。 */
143
+ /**
144
+ * 同目录临时文件 + rename 原子写(临时名 `.xxx.dsh-rules-<uuid>.tmp`)。
145
+ * rename 走 `renameWithRetry`:Windows 上杀软/索引器会短暂占住目标文件报
146
+ * EPERM/EACCES/EBUSY(用户实测:进入/退出模式时 rules-index.json 被 rename 撞上,
147
+ * 运行时已切换但状态落盘失败,界面开关停在旧状态、还得再点一次)。这种占用是
148
+ * 瞬时的,重试几轮就能过去;全失败才清理临时文件并把错误抛出。
149
+ */
107
150
  async function writeFileAtomically(path, content) {
108
151
  const temp = join(dirname(path), `.${basename(path)}.dsh-rules-${randomUUID()}.tmp`);
109
152
  try {
110
153
  await writeFile(temp, content, 'utf8');
111
- await rename(temp, path);
154
+ await renameWithRetry(temp, path);
112
155
  }
113
156
  catch (error) {
114
157
  await rm(temp, { force: true }).catch(() => undefined);
115
158
  throw error;
116
159
  }
117
160
  }
118
- /** 二进制版原子写(附件用):临时文件 + rename,失败清理临时文件。 */
161
+ /** 二进制版原子写(附件用):临时文件 + rename(同样带瞬时占用重试),失败清理临时文件。 */
119
162
  async function writeFileAtomicBinary(path, data) {
120
163
  const temp = join(dirname(path), `.${basename(path)}.dsh-rules-${randomUUID()}.tmp`);
121
164
  try {
122
165
  await writeFile(temp, data);
123
- await rename(temp, path);
166
+ await renameWithRetry(temp, path);
124
167
  }
125
168
  catch (error) {
126
169
  await rm(temp, { force: true }).catch(() => undefined);
@@ -347,6 +390,9 @@ function parseSceneEntry(raw) {
347
390
  out.order = obj.order;
348
391
  if (typeof obj.createdAt === 'string' && obj.createdAt !== '')
349
392
  out.createdAt = obj.createdAt;
393
+ // 场景锁定(v0.8):读盘必须原样保留 —— 这里曾只重建已知字段,锁了也会被剥成未锁。
394
+ if (obj.locked === true)
395
+ out.locked = true;
350
396
  return out;
351
397
  }
352
398
  function parseScenes(raw) {
@@ -412,9 +458,29 @@ function parseModeState(raw) {
412
458
  list.push(tool);
413
459
  }
414
460
  }
461
+ // v2 快照的**服务器级 / 来源级**名单与 v0.8 的子智能体名单必须原样透传 ——
462
+ // 这里曾把它们剥掉,结果退出模式时两张恢复名单全是空的:服务器级 MCP 与技能来源
463
+ // 永远不回滚(用户报的「MCP 不复原」「技能目录不回退」),只有工具级 / 技能级能还原。
464
+ const mcpServers = (Array.isArray(snapshotRaw.mcpServers) ? snapshotRaw.mcpServers : [])
465
+ .filter((x) => !!x && typeof x === 'object')
466
+ .map((x) => ({ id: String(x.id || ''), level: String(x.level || ''), disabled: x.disabled === true }))
467
+ .filter((x) => x.id !== '' && (x.level === 'global' || x.level === 'project'));
468
+ const skillSources = (Array.isArray(snapshotRaw.skillSources) ? snapshotRaw.skillSources : [])
469
+ .filter((x) => !!x && typeof x === 'object')
470
+ .map((x) => ({ root: String(x.root || ''), enabled: x.enabled === true }))
471
+ .filter((x) => x.root !== '');
472
+ const subagents = (Array.isArray(snapshotRaw.subagents) ? snapshotRaw.subagents : []).map((x) => String(x)).filter(Boolean);
415
473
  return {
416
474
  scene,
417
- snapshot: scene ? { mcp, skills: toFlagMap(snapshotRaw.skills) } : null,
475
+ snapshot: scene
476
+ ? {
477
+ mcp,
478
+ skills: toFlagMap(snapshotRaw.skills),
479
+ ...(mcpServers.length ? { mcpServers } : {}),
480
+ ...(skillSources.length ? { skillSources } : {}),
481
+ ...(subagents.length ? { subagents } : {}),
482
+ }
483
+ : null,
418
484
  };
419
485
  }
420
486
  /** 解析 rules-index.json 原文;任何异常/版本不符 → 默认索引(容忍缺失,§9.3)。 */
@@ -881,9 +947,9 @@ function renderSceneMemory(probe, index, maxBytes) {
881
947
  // 保留场景 global 恒定生效(「全局」= 任何对话都注入);其余由 index.active 决定。
882
948
  if (file.scene !== GLOBAL_SCENE && !active.has(file.scene))
883
949
  continue;
884
- // 场景档案的记忆段(v3):该场景定过 memories 段 → 只有勾选的记忆进段(纯投影,不改文件)。
885
- if (!memoryAllowed(index.archives, file.scene, file.id))
886
- continue;
950
+ // ⚠️ 这里**不再**看场景档案的 memories 段:记忆的开关是**单一真相源** `rules[*].enabled`
951
+ // (见下方 enabled 判定)。档案弹窗里的记忆勾选就是同一个值,所以两边天然一致,
952
+ // 不存在「记忆页开了、档案页还显示未开」的两套状态。
887
953
  const list = buckets.get(file.scene);
888
954
  if (list)
889
955
  list.push(file);
@@ -1378,6 +1444,7 @@ export function createRulesService(ctx, deps) {
1378
1444
  prompt: index.scenes?.[name]?.prompt || '',
1379
1445
  // 单选模型下"能不能点开":已被别的场景占用时,这个开关要置灰。
1380
1446
  selectable: name !== SHARED_GROUP && name !== GLOBAL_SCENE && (enabledScene === null || enabledScene === name),
1447
+ locked: index.scenes?.[name]?.locked === true,
1381
1448
  }))
1382
1449
  .sort((a, b) => a.order - b.order || a.name.localeCompare(b.name));
1383
1450
  }
@@ -1391,6 +1458,8 @@ export function createRulesService(ctx, deps) {
1391
1458
  .sort((a, b) => a.group.localeCompare(b.group) || a.order - b.order || a.name.localeCompare(b.name));
1392
1459
  const groups = groupFilter ? snap.groups.filter((g) => g.name === groupFilter) : snap.groups;
1393
1460
  const scenes = sceneRows(snap, index);
1461
+ // 场景锁定状态(v0.8):任意一个场景锁定 = 五个管理域整体冻结。界面据此禁用各页的写控件。
1462
+ const anyLocked = Object.values(index.scenes || {}).some((s) => s.locked === true);
1394
1463
  const projection = sceneMemory();
1395
1464
  const promptProjection = scenePrompt();
1396
1465
  return {
@@ -1400,6 +1469,8 @@ export function createRulesService(ctx, deps) {
1400
1469
  groups: groups.map((g) => ({ ...g, key: g.name })),
1401
1470
  // 场景 = 显式记录(含保留场景 global 与尚无记忆的空场景);active = 是否参与注入。
1402
1471
  scenes,
1472
+ // 任一场景被锁定 = 五个管理域整体冻结(客户端据此禁用写控件;服务端 handlers 另有守卫)。
1473
+ anyLocked,
1403
1474
  activeMode: normalizeActive(index.active) === null ? 'all' : 'custom',
1404
1475
  // 单选模型:当前启用的那个场景(null = 只留 `_shared` 与 `global`)。
1405
1476
  activeScene: enabledSceneOf(index),
@@ -1606,7 +1677,9 @@ export function createRulesService(ctx, deps) {
1606
1677
  // id 恒为 `<场景>/<名>`(与 parseId 同构);场景记录此时必然已存在。
1607
1678
  const createdId = `${targetGroup}/${name}`;
1608
1679
  const index = indexForScene;
1609
- index.rules[createdId] = { order: DEFAULT_ORDER, enabled: true, updatedAt: new Date().toISOString() };
1680
+ // P5:新建记忆默认**不开启** —— 记忆的开关是单一真相源(`enabled`),
1681
+ // 用户裁定「创建的记忆默认不开启,在记忆页开启后对应的场景档案也要显示开启」。
1682
+ index.rules[createdId] = { order: DEFAULT_ORDER, enabled: false, updatedAt: new Date().toISOString() };
1610
1683
  if (!index.groups[targetGroup])
1611
1684
  index.groups[targetGroup] = { order: DEFAULT_GROUP_ORDER, label: targetGroup };
1612
1685
  await writeIndex(stateDir, index);
@@ -1714,7 +1787,8 @@ export function createRulesService(ctx, deps) {
1714
1787
  }
1715
1788
  // 索引记录:与 rules-create 同口径(order/enabled/updatedAt + 场景分组),用户既有设置不覆盖。
1716
1789
  const entry = index.rules[id];
1717
- index.rules[id] = { ...(entry || {}), order: entry?.order ?? DEFAULT_ORDER, enabled: entry?.enabled ?? true, updatedAt: new Date().toISOString() };
1790
+ // P5:导入的记忆同样默认**不开启**(与 rules-create 同一口径);已存在的条目保留原开关。
1791
+ index.rules[id] = { ...(entry || {}), order: entry?.order ?? DEFAULT_ORDER, enabled: entry?.enabled ?? false, updatedAt: new Date().toISOString() };
1718
1792
  if (!index.groups[item.group])
1719
1793
  index.groups[item.group] = { order: DEFAULT_GROUP_ORDER, label: item.group };
1720
1794
  // 场景记录补齐(导入进来的目录名此前可能没有记录)。
@@ -2168,8 +2242,15 @@ export function createRulesService(ctx, deps) {
2168
2242
  return { ok: true, scene: sceneRecordOf(name, next), ...(collapsed ? { collapsedActive: true } : {}) };
2169
2243
  }
2170
2244
  /**
2171
- * 更新场景记录(描述 / 显示名 / 顺序 / 绑定的提示词预设)。记忆文件不动。
2172
- * 这是「场景有描述」的写入口——旧版场景只有目录名,没有可编辑元数据。
2245
+ * 更新场景记录(描述 / 显示名 / 顺序 / 绑定的提示词预设),**可选改名**(nextName)。
2246
+ *
2247
+ * 场景名就是它的一级目录名(`memories/<场景>/…`),所以改名不是改一个字段:
2248
+ * ① 目录 `memories/<旧>` → `memories/<新>`;
2249
+ * ② 索引里的四处引用一起改:`scenes` 记录、`archives` 档案、`active` 启用集合、`mode.scene`。
2250
+ * 记忆正文一个字节都不动(只是换了所在目录名)。
2251
+ *
2252
+ * 拒绝的三种情况:保留场景 `global` / `_shared`;目标名已被占用(目录或记录);
2253
+ * 该场景正在当前模式里——模式快照是按场景名算的,改了名与快照就对不上(同删除的处理)。
2173
2254
  */
2174
2255
  async function rulesUpdateScene(args) {
2175
2256
  const name = String((args && args.name) || '').trim();
@@ -2219,13 +2300,106 @@ export function createRulesService(ctx, deps) {
2219
2300
  return fail('error.rules.invalidGroup', `非法排序值:${args.order}`);
2220
2301
  next.order = Math.floor(order);
2221
2302
  }
2222
- if (name === GLOBAL_SCENE)
2303
+ // ── 改名(可选):目录 + 索引里的四处引用一起动 ──
2304
+ let finalName = name;
2305
+ const nextRaw = args && args.nextName !== undefined ? String(args.nextName).trim() : '';
2306
+ if (nextRaw !== '' && nextRaw !== name) {
2307
+ if (!isValidGroupSegment(nextRaw)) {
2308
+ return fail('error.rules.invalidGroup', `新场景名非法:${nextRaw}(非空、≤${MAX_GROUP_SEGMENT_LENGTH} 字符、不含路径分隔符与 < > : " | ? *、不以 . 开头)`);
2309
+ }
2310
+ if (name === GLOBAL_SCENE)
2311
+ return fail('error.rules.reservedScene', '「全局」是保留场景,不可改名');
2312
+ if (name === SHARED_GROUP || nextRaw === SHARED_GROUP)
2313
+ return fail('error.rules.invalidGroup', '_shared 是保留场景名,不可改名');
2314
+ if ((index.scenes && index.scenes[nextRaw]) || (await pathExists(join(rulesRoot, nextRaw)))) {
2315
+ return fail('error.rules.nameTaken', `目标场景名已被占用:${nextRaw}`);
2316
+ }
2317
+ if (index.mode && index.mode.scene === name) {
2318
+ return fail('error.rules.sceneInMode', `场景「${name}」正处在当前模式,请先退出模式再改名`);
2319
+ }
2320
+ const fromDir = join(rulesRoot, name);
2321
+ const toDir = join(rulesRoot, nextRaw);
2322
+ let movedDir = false;
2323
+ if (await pathExists(fromDir)) {
2324
+ try {
2325
+ await rename(fromDir, toDir);
2326
+ movedDir = true;
2327
+ }
2328
+ catch (e) {
2329
+ return fail('error.rules.ioFailed', `场景目录改名失败:${message(e)}`);
2330
+ }
2331
+ }
2332
+ // 目录已经搬过去了:索引这一步失败就必须把目录搬回来,否则目录名与索引各说各话。
2333
+ try {
2334
+ const scenes = index.scenes || {};
2335
+ if (scenes[name]) {
2336
+ scenes[nextRaw] = scenes[name];
2337
+ delete scenes[name];
2338
+ }
2339
+ else {
2340
+ scenes[nextRaw] = { order: DEFAULT_GROUP_ORDER, createdAt: new Date().toISOString() };
2341
+ }
2342
+ index.scenes = scenes;
2343
+ if (index.archives && index.archives[name]) {
2344
+ index.archives[nextRaw] = index.archives[name];
2345
+ delete index.archives[name];
2346
+ }
2347
+ const act = normalizeActive(index.active);
2348
+ if (act !== null && act.indexOf(name) >= 0)
2349
+ index.active = act.map((n) => (n === name ? nextRaw : n));
2350
+ if (index.mode && index.mode.scene === name)
2351
+ index.mode = { ...index.mode, scene: nextRaw };
2352
+ }
2353
+ catch (e) {
2354
+ if (movedDir) {
2355
+ try {
2356
+ await rename(toDir, fromDir);
2357
+ }
2358
+ catch { /* 回滚失败:错误信息里如实带上原因 */ }
2359
+ }
2360
+ return fail('error.rules.ioFailed', `场景改名后索引更新失败:${message(e)}`);
2361
+ }
2362
+ finalName = nextRaw;
2363
+ }
2364
+ if (finalName === GLOBAL_SCENE)
2223
2365
  next.label = GLOBAL_SCENE_LABEL;
2224
- index.scenes[name] = next;
2366
+ index.scenes[finalName] = next;
2225
2367
  await writeIndex(stateDir, index);
2226
2368
  invalidateSnapshot();
2227
2369
  invalidateProviders();
2228
- return { ok: true, scene: sceneRecordOf(name, next) };
2370
+ return {
2371
+ ok: true,
2372
+ ...(finalName === name ? {} : { renamedFrom: name }),
2373
+ scene: sceneRecordOf(finalName, next),
2374
+ };
2375
+ }
2376
+ /**
2377
+ * 场景锁定(v0.8):锁定后五个管理域(MCP/技能/子智能体/记忆/提示词)整体只读 ——
2378
+ * 场景页的档案编辑与功能页的启停/编辑都被拒(index.ts 的 handlers 守卫 + 界面禁用),
2379
+ * 场景自身的启停(进/退模式)不受影响。`locked` 必须显式给布尔值(与 rules-toggle 同一口径)。
2380
+ * 保留场景 `global` 不在场景页出现,不可锁。
2381
+ */
2382
+ async function rulesSceneLock(args) {
2383
+ const name = String((args && args.scene) || '').trim();
2384
+ if (!isValidGroupPath(name))
2385
+ return fail('error.rules.invalidGroup', `场景名非法:${name || '(空)'}`);
2386
+ if (name === GLOBAL_SCENE || name === SHARED_GROUP)
2387
+ return fail('error.rules.reservedScene', '「全局 / _shared」是保留场景,不可锁定');
2388
+ if (typeof (args && args.locked) !== 'boolean') {
2389
+ return fail('error.rules.invalidArgs', '缺少参数:locked 必须是布尔值(只按传入值写入,不做"翻转"推断)');
2390
+ }
2391
+ const index = await readIndex(stateDir);
2392
+ if (!index.scenes || !index.scenes[name])
2393
+ return fail('error.rules.notFound', `场景不存在:${name}`);
2394
+ // 未启动的场景不能上锁(用户裁定):锁定的意义是冻结**运行中**场景的配置。
2395
+ // 解锁随时允许 —— 否则退出模式后,被锁的场景就没人能解了。
2396
+ if (args.locked === true && (!index.mode || index.mode.scene !== name)) {
2397
+ return fail('error.rules.sceneNotActive', `场景「${name}」未启动:先启动再锁定`);
2398
+ }
2399
+ index.scenes[name] = { ...index.scenes[name], locked: args.locked === true };
2400
+ await writeIndex(stateDir, index);
2401
+ invalidateSnapshot();
2402
+ return { ok: true, scene: name, locked: args.locked === true };
2229
2403
  }
2230
2404
  /**
2231
2405
  * 删除场景:**仅空目录可删**(避免一次操作带走整组记忆)。
@@ -2245,35 +2419,59 @@ export function createRulesService(ctx, deps) {
2245
2419
  if (!index.scenes?.[name] && !(await pathExists(join(rulesRoot, name)))) {
2246
2420
  return fail('error.rules.notFound', `场景不存在:${name}`);
2247
2421
  }
2248
- let entries = [];
2249
- try {
2250
- entries = await readdir(join(rulesRoot, name));
2251
- }
2252
- catch {
2253
- entries = []; // 目录本来就不存在(只有记录)→ 仍允许删记录
2254
- }
2255
- if (entries.filter((n) => !n.startsWith('.')).length > 0) {
2256
- return fail('error.rules.sceneNotEmpty', `场景「${name}」里还有 ${entries.length} 项,请先删除其中的记忆`);
2257
- }
2258
2422
  // 当前模式场景不可删:快照只在引擎里可退(rules service 反向注入会成环),
2259
2423
  // 直接删除会让运行时启停永久停在档案态且无恢复路径 → 给出可逆出路(先退出模式)。
2260
2424
  if (index.mode?.scene === name) {
2261
2425
  return fail('error.rules.sceneInMode', `场景「${name}」正处在当前模式,请先退出模式再删除`);
2262
2426
  }
2263
- // 场景本体(记录 + 档案)**先移入回收站**,再从索引里摘掉——这样「删除场景」
2264
- // 是可恢复的。记忆目录必须是空的(上面已拦),所以没有正文需要搬。
2265
- const trashed = await moveToTrash('scenes', name, [], {
2427
+ // 删除场景 = **连它下面的全部记忆一起去掉**(用户裁定):不管有没有启用、是不是子目录、
2428
+ // 是不是 bundle 附件,统统收走。
2429
+ // 但一律**先移入回收站**(与场景记录、档案装在同一条条目里),所以「删错了」还能整条恢复:
2430
+ // 记忆文件按原来的相对路径放回,场景记录与档案也一起回来。
2431
+ const sceneDir = join(rulesRoot, name);
2432
+ const moves = [];
2433
+ const collect = async (abs, rel) => {
2434
+ let items = [];
2435
+ try {
2436
+ items = await readdir(abs, { withFileTypes: true });
2437
+ }
2438
+ catch {
2439
+ return; // 目录不存在(只有记录的场景)或读不了 → 当作没有文件
2440
+ }
2441
+ for (const item of items) {
2442
+ const childAbs = join(abs, item.name);
2443
+ const childRel = rel === '' ? item.name : `${rel}/${item.name}`;
2444
+ if (item.isDirectory())
2445
+ await collect(childAbs, childRel);
2446
+ else
2447
+ moves.push({ from: childAbs, dest: childRel });
2448
+ }
2449
+ };
2450
+ await collect(sceneDir, '');
2451
+ const trashed = await moveToTrash('scenes', name, moves, {
2266
2452
  record: (index.scenes && index.scenes[name]) || null,
2267
2453
  archive: (index.archives && index.archives[name]) || null,
2454
+ memories: moves.map((m) => m.dest),
2268
2455
  });
2269
2456
  if (trashed.ok === false) {
2270
2457
  return fail('error.rules.ioFailed', `移入回收站失败:${trashed.error}`);
2271
2458
  }
2272
2459
  try {
2273
- // fs.rm 删目录必须 recursive(即使已确认它是空的),否则报 EISDIR。
2274
- await rm(join(rulesRoot, name), { recursive: true, force: true });
2460
+ // 文件已搬空,剩下的只是空子目录;recursive + force 一并清掉。
2461
+ await rm(sceneDir, { recursive: true, force: true });
2275
2462
  }
2276
2463
  catch (e) {
2464
+ // 目录没清掉就把记忆放回去:宁可整个操作失败,也不要「文件在回收站、场景还留在列表里」。
2465
+ for (const move of moves) {
2466
+ try {
2467
+ await moveOutOfTrash('scenes', trashed.id, move.dest, move.from);
2468
+ }
2469
+ catch { /* 尽力而为 */ }
2470
+ }
2471
+ try {
2472
+ await purgeTrashEntry('scenes', trashed.id);
2473
+ }
2474
+ catch { /* 同上 */ }
2277
2475
  return fail('error.rules.ioFailed', `删除场景目录失败:${message(e)}`);
2278
2476
  }
2279
2477
  // 索引清理一次读-改-写:记录 + 启用集合悬空引用 + 该场景档案(否则 archives 留孤儿条目)。
@@ -2294,7 +2492,7 @@ export function createRulesService(ctx, deps) {
2294
2492
  await writeIndex(stateDir, index);
2295
2493
  invalidateSnapshot();
2296
2494
  invalidateProviders();
2297
- return { ok: true, name, trashId: trashed.id };
2495
+ return { ok: true, name, trashId: trashed.id, movedFiles: moves.length };
2298
2496
  }
2299
2497
  /** 场景回收站列表(只读):`<hub>/trash/scenes-trash/<id>/manifest.json`。 */
2300
2498
  async function sceneTrashList() {
@@ -2333,6 +2531,18 @@ export function createRulesService(ctx, deps) {
2333
2531
  catch (e) {
2334
2532
  return fail('error.rules.ioFailed', `重建场景目录失败:${message(e)}`);
2335
2533
  }
2534
+ // 删除场景时一起收进回收站的记忆文件:按原来的相对路径放回(目录已确认是空的,不会覆盖)。
2535
+ const files = Array.isArray(entry.files) ? entry.files : [];
2536
+ const restored = [];
2537
+ for (const rel of files) {
2538
+ try {
2539
+ await moveOutOfTrash('scenes', id, String(rel), join(dir, String(rel)));
2540
+ restored.push(String(rel));
2541
+ }
2542
+ catch (e) {
2543
+ return fail('error.rules.ioFailed', `恢复记忆文件失败(已放回 ${restored.length}/${files.length}):${message(e)}`);
2544
+ }
2545
+ }
2336
2546
  if (data.record && typeof data.record === 'object')
2337
2547
  index.scenes = { ...(index.scenes || {}), [name]: data.record };
2338
2548
  if (data.archive && typeof data.archive === 'object')
@@ -2341,7 +2551,7 @@ export function createRulesService(ctx, deps) {
2341
2551
  await purgeTrashEntry('scenes', id);
2342
2552
  invalidateSnapshot();
2343
2553
  invalidateProviders();
2344
- return { ok: true, name };
2554
+ return { ok: true, name, restoredFiles: restored.length };
2345
2555
  }
2346
2556
  /** 永久删除一条场景回收站条目。 */
2347
2557
  async function sceneTrashDelete(args) {
@@ -2409,9 +2619,17 @@ export function createRulesService(ctx, deps) {
2409
2619
  // ── 组装 ─────────────────────────────────────────────────────────────────
2410
2620
  const registerProviders = () => {
2411
2621
  try {
2412
- const registrar = createRuleProviderRegistrar(ctx, {
2413
- renderActiveScenes: () => sceneMemory().text,
2414
- });
2622
+ // 场景绑定的提示词**不再注入**(2026-09-15 用户裁定:「切换场景,对应的提示词直接把
2623
+ // AGENTS.md 修改」):启用/切换场景、改绑、编辑绑定的预设时,宿主把那份正文写进
2624
+ // `~/.dsh/AGENTS.md`(与「提示词」页的「应用」同一条路,覆盖前多代备份),关掉场景时
2625
+ // 恢复进场景之前的基线。真改文件之后再注入一遍,同一份正文会进上下文两次,而且用户手改
2626
+ // 基线之后还会被重新注入 —— 所以这里只保留场景记忆段。绑定关系的**只读投影**仍由 rules
2627
+ // 服务提供(页面「生效中」标记,以及"文件是否已经同步成它"的判断)。
2628
+ const registrar = createPromptSectionRegistrar(ctx, [{
2629
+ name: 'tool-management:scene-memory',
2630
+ order: SECTION_ORDER.sceneMemory,
2631
+ text: () => sceneMemory().text,
2632
+ }]);
2415
2633
  providerInvalidators.add(registrar.invalidate);
2416
2634
  return () => {
2417
2635
  providerInvalidators.delete(registrar.invalidate);
@@ -2436,6 +2654,7 @@ export function createRulesService(ctx, deps) {
2436
2654
  const writeOps = new Set([
2437
2655
  'rules-create', 'rules-update', 'rules-remove', 'rules-restore', 'rules-toggle', 'rules-import',
2438
2656
  'rules-set-index', 'rules-set-active', 'rules-create-scene', 'rules-update-scene', 'rules-remove-scene', 'rules-rebind-prompt',
2657
+ 'rules-scene-lock',
2439
2658
  'rules-attach', 'rules-detach', 'rules-trash-remove',
2440
2659
  // 场景回收站(与记忆回收站 rules-trash-* 分开:那套管记忆正文,这套管场景记录与档案)
2441
2660
  'scene-trash-restore', 'scene-trash-delete',
@@ -2459,6 +2678,7 @@ export function createRulesService(ctx, deps) {
2459
2678
  'rules-set-active': (args) => runWrite(() => rulesSetActive(args || {})),
2460
2679
  'rules-create-scene': (args) => runWrite(() => rulesCreateScene(args || {})),
2461
2680
  'rules-update-scene': (args) => runWrite(() => rulesUpdateScene(args || {})),
2681
+ 'rules-scene-lock': (args) => runWrite(() => rulesSceneLock(args || {})),
2462
2682
  'rules-remove-scene': (args) => runWrite(() => rulesRemoveScene(args || {})),
2463
2683
  'scene-trash-list': () => sceneTrashList(),
2464
2684
  'scene-trash-restore': (args) => runWrite(() => sceneTrashRestore(args || {})),
@@ -883,7 +883,10 @@ async function writeFileAtomically(path, content) {
883
883
  const temp = join(dirname(path), `.${basename(path)}.dssm-${randomUUID()}.tmp`);
884
884
  try {
885
885
  await fs.writeFile(temp, content, "utf8");
886
- await fs.rename(temp, path);
886
+ // Windows 上目标文件会被杀软/索引器短暂占住(EPERM/EACCES/EBUSY)——
887
+ // 场景模式进出时这里写的是技能来源/策略状态,rename 被撞 = 运行时已切、
888
+ // 状态没落盘。与 rules-index.json 同一处理:重试瞬时占用,全失败才抛。
889
+ await renameWithRetry(temp, path);
887
890
  }
888
891
  catch (error) {
889
892
  await fs.rm(temp, { force: true }).catch(() => undefined);
@@ -0,0 +1,89 @@
1
+ import { filterBySceneBinding } from './tools.js';
2
+ /**
3
+ * 描述截断长度 —— 照抄官方技能目录的默认值
4
+ * (`dsh-tool-skill` 的 `DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH = 500`)。
5
+ *
6
+ * 照抄的理由:截断风格与模型**已经见过的**技能目录一致,不用让它适应两套习惯;
7
+ * 而且这是官方旋钮的默认值,不是本插件拍脑袋定的数。日后 token 成本成为问题时,
8
+ * 官方对应的旋钮是 `catalogDescriptionMaxLength`。
9
+ */
10
+ export const DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH = 500;
11
+ /** 段里最多列几个人设;超出部分只报数量,让模型自己去调 subagent_list。 */
12
+ export const DEFAULT_CATALOG_MAX_ENTRIES = 40;
13
+ /** 无描述时的占位,与 `subagent_list` 工具的输出保持同一口径。 */
14
+ const NO_DESCRIPTION = '(无描述)';
15
+ /**
16
+ * 描述归一化 + 截断 —— 逐字对齐官方 `dsh-tool-skill` 的实现:
17
+ * 先把所有空白折叠成单空格,再按长度截断并补省略号。保证「一人设一行」。
18
+ */
19
+ export function catalogDescription(value, maxLength) {
20
+ const normalized = String(value ?? '').replaceAll(/\s+/g, ' ').trim();
21
+ if (normalized.length <= maxLength)
22
+ return normalized;
23
+ return `${normalized.slice(0, maxLength - 3)}...`;
24
+ }
25
+ /**
26
+ * 渲染人设目录段(纯函数,便于单独推理)。
27
+ *
28
+ * 返回 `''` 表示不注入 —— `renderPrompt` 会删除空段,所以不用人设的用户零 token 成本。
29
+ * 名字按字典序排序:即使底层目录枚举顺序变化,段文本也保持逐字节稳定(前缀缓存契约)。
30
+ */
31
+ export function renderSubagentCatalog(allowed, maxEntries = DEFAULT_CATALOG_MAX_ENTRIES, maxDescription = DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH) {
32
+ if (!allowed.length)
33
+ return '';
34
+ const sorted = [...allowed].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
35
+ const shown = sorted.slice(0, Math.max(0, maxEntries));
36
+ const lines = shown.map((p) => '- **' + p.name + '** — ' + (catalogDescription(p.description, maxDescription) || NO_DESCRIPTION));
37
+ const hidden = sorted.length - shown.length;
38
+ const out = [
39
+ '## 子智能体(人设)',
40
+ '',
41
+ '需要委派独立任务时,用 `subagent_run` 并指定下面的人设名。',
42
+ '',
43
+ ...lines,
44
+ ];
45
+ if (hidden > 0)
46
+ out.push('', `(另有 ${hidden} 个未列出,用 subagent_list 查看全部。)`);
47
+ return out.join('\n');
48
+ }
49
+ /**
50
+ * 创建 SWR 人设目录。
51
+ *
52
+ * ⚠️ 计算失败(读盘异常等)时**保留上一次的值**,不把段清空 —— 否则一次瞬时 IO 抖动
53
+ * 会让模型突然「忘记」有哪些人设。
54
+ */
55
+ export function createSubagentCatalog(deps, opts = {}) {
56
+ const maxEntries = opts.maxEntries ?? DEFAULT_CATALOG_MAX_ENTRIES;
57
+ const maxDescription = opts.maxDescription ?? DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH;
58
+ const ttlMs = opts.ttlMs ?? 1000;
59
+ const now = opts.now ?? (() => Date.now());
60
+ let value = '';
61
+ let loadedAt = Number.NEGATIVE_INFINITY;
62
+ let inflight = null;
63
+ const recompute = async () => {
64
+ try {
65
+ const { allowed } = await filterBySceneBinding(await deps.list(), await deps.sceneLists());
66
+ value = renderSubagentCatalog(allowed, maxEntries, maxDescription);
67
+ }
68
+ catch { /* 保留上一次的值;首次失败则维持 '' */ }
69
+ loadedAt = now();
70
+ };
71
+ const revalidate = () => {
72
+ if (inflight)
73
+ return inflight;
74
+ inflight = recompute().finally(() => { inflight = null; });
75
+ return inflight;
76
+ };
77
+ return {
78
+ text: () => {
79
+ if (now() - loadedAt > ttlMs)
80
+ void revalidate();
81
+ return value;
82
+ },
83
+ refresh: () => {
84
+ loadedAt = Number.NEGATIVE_INFINITY;
85
+ return revalidate();
86
+ },
87
+ warm: () => revalidate(),
88
+ };
89
+ }