dsh-plugin-tool-management 0.21.1 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +42 -6
  3. package/README_EN.md +40 -6
  4. package/docs/images/1-EN.png +0 -0
  5. package/docs/images/1.png +0 -0
  6. package/docs/images/2-EN.png +0 -0
  7. package/docs/images/2.png +0 -0
  8. package/docs/images/3-EN.png +0 -0
  9. package/docs/images/3.png +0 -0
  10. package/docs/images/4-EN.png +0 -0
  11. package/docs/images/4.png +0 -0
  12. package/docs/images/5-EN.png +0 -0
  13. package/docs/images/5.png +0 -0
  14. package/docs/images/6-EN.png +0 -0
  15. package/docs/images/6.png +0 -0
  16. package/docs/images/7-EN.png +0 -0
  17. package/docs/images/7.png +0 -0
  18. package/docs/images/8-EN.png +0 -0
  19. package/docs/images/8.png +0 -0
  20. package/docs/update.md +37 -36
  21. package/lib/boot/reconcile.js +157 -0
  22. package/lib/client.js +6658 -3146
  23. package/lib/compat/patch-dialect.js +14 -1
  24. package/lib/compat/probe.js +25 -21
  25. package/lib/context-inject-frame.js +27 -36
  26. package/lib/context-inject-select.js +59 -4
  27. package/lib/context-inject-surface.js +49 -3
  28. package/lib/context-inject.js +144 -21
  29. package/lib/diagnostics.js +77 -0
  30. package/lib/http-api.js +39 -23
  31. package/lib/http-fence.js +40 -5
  32. package/lib/imports/unzip.js +48 -0
  33. package/lib/imports/upload.js +8 -36
  34. package/lib/index.js +2906 -166
  35. package/lib/mcp/disabled-tools.js +96 -0
  36. package/lib/mcp/manager.js +559 -128
  37. package/lib/mcp/restart-marker.js +110 -0
  38. package/lib/mcp/state-section.js +132 -43
  39. package/lib/mcp/tool-visibility.js +348 -56
  40. package/lib/memories/archive-engine.js +39 -14
  41. package/lib/memories/discovery.js +30 -10
  42. package/lib/memories/index-io.js +217 -18
  43. package/lib/memories/projection.js +20 -3
  44. package/lib/memories/prompt-layer.js +37 -0
  45. package/lib/memories/search.js +86 -0
  46. package/lib/memories/service.js +327 -91
  47. package/lib/memories/snapshot.js +49 -10
  48. package/lib/op-registry.js +46 -4
  49. package/lib/ops/candidates.js +11 -3
  50. package/lib/ops/compat.js +46 -4
  51. package/lib/ops/memory.js +78 -9
  52. package/lib/ops/prompts.js +49 -5
  53. package/lib/ops/quick-prompts.js +24 -2
  54. package/lib/ops/scene-records.js +7 -0
  55. package/lib/ops/scene-sync.js +23 -4
  56. package/lib/ops/scope.js +1093 -0
  57. package/lib/ops/sessions.js +5 -2
  58. package/lib/ops/snapshot.js +55 -20
  59. package/lib/ops/state-doctor.js +39 -4
  60. package/lib/paths.js +50 -3
  61. package/lib/prompts/preset-id.js +4 -0
  62. package/lib/prompts/project-instructions.js +162 -0
  63. package/lib/prompts/quick-service.js +5 -4
  64. package/lib/prompts/service.js +20 -9
  65. package/lib/request-gate.js +6 -4
  66. package/lib/scene-linkage.js +12 -0
  67. package/lib/scene-prompt-sync.js +1 -1
  68. package/lib/scenes/candidates.js +8 -1
  69. package/lib/scope/intent-store.js +105 -0
  70. package/lib/scope/intent.js +376 -0
  71. package/lib/scope/resolve.js +190 -0
  72. package/lib/scope/scope-overrides.js +894 -0
  73. package/lib/scope/store.js +262 -0
  74. package/lib/scope/workspace-key.js +64 -0
  75. package/lib/sessions/history.js +3 -2
  76. package/lib/settings-sidecars.js +50 -24
  77. package/lib/skills/catalog.js +206 -33
  78. package/lib/skills/core.js +1 -1
  79. package/lib/skills/frontmatter.js +121 -0
  80. package/lib/skills/service.js +145 -20
  81. package/lib/stale-write.js +74 -0
  82. package/lib/subagents/catalog.js +47 -13
  83. package/lib/subagents/persona-parse.js +26 -5
  84. package/lib/subagents/persona-write.js +11 -7
  85. package/lib/subagents/service.js +3 -2
  86. package/lib/subagents/tools.js +78 -8
  87. package/lib/token-config.js +25 -5
  88. package/lib/tool-table-switch.js +141 -49
  89. package/lib/tools/deps.js +151 -5
  90. package/lib/tools/mcp.js +189 -39
  91. package/lib/tools/memory.js +103 -18
  92. package/lib/tools/prompt.js +61 -9
  93. package/lib/tools/remove.js +46 -21
  94. package/lib/tools/scene.js +120 -26
  95. package/lib/tools/skills.js +191 -30
  96. package/lib/tools/subagent.js +52 -20
  97. package/lib/tools/table.js +48 -11
  98. package/lib/trash-retention.js +3 -2
  99. package/lib/update-check.js +218 -0
  100. package/package.json +16 -14
@@ -5,6 +5,7 @@
5
5
  // 沿用上游机制:全局层接管 + 每个活动 agent scope 内二次注册。
6
6
  import { appendFile, rename, rm, stat } from 'node:fs/promises';
7
7
  import { isInsideRootResolved } from '../paths.js';
8
+ import { workspaceCwdOfScopeKey } from '../scope/workspace-key.js';
8
9
  import { state, setSkillEnabled, setPreferredSkill, markSkillsDisabled, setSourceEnabled, setSourceRemoved, deleteSkill, restoreTrash, importSkill, importUploadedSkill, browseDirectories, createSkill, updateSkill, skillDetail, userRoots, projectRoots, readManagerState, customRootsFromState, addCustomRoot, removeCustomRoot, forgetSource, logPath, } from './core.js';
9
10
  import { watchDirectories } from './dir-watch.js';
10
11
  import { registerAgentSkillProviders, externalSkillProvider } from './provider-registration.js';
@@ -32,6 +33,37 @@ function makeLog() {
32
33
  await queue;
33
34
  };
34
35
  }
36
+ /**
37
+ * 某个会话的 cwd(`null` = 在自己的活动会话清单里找不到这个会话)。
38
+ *
39
+ * 与 `activeSessionCwds` 同一条取法(`sessions.list()` → `header.cwd`),只是按 id 过滤。
40
+ * 用 `list()` 而不是 `sessions.get(id)`:前者是宿主公开的活会话清单,后者在冷会话上返回
41
+ * undefined。**找不到 ≠ 没有 cwd**:调用方据此退回全局口径(全部活动会话),
42
+ * 而不是把项目技能整个清空 —— 一次清单读取时序问题不该让某一轮少掉一整类技能。
43
+ */
44
+ export function sessionCwdOf(ctx, sessionId) {
45
+ // 工作区模式(0.21.2):面板 / 斜杠菜单传过来的可能是 `ws:<cwd>` 作用域键。
46
+ // 它本身就是项目技能根(键里带归一化后的完整路径),不必再去会话清单里找。
47
+ const workspaceCwd = workspaceCwdOfScopeKey(sessionId);
48
+ if (workspaceCwd !== undefined)
49
+ return [workspaceCwd];
50
+ try {
51
+ const sessions = (typeof ctx.get === 'function' ? ctx.get('sessions') : undefined) || ctx.sessions;
52
+ const list = sessions && typeof sessions.list === 'function' ? sessions.list() : [];
53
+ for (const session of Array.isArray(list) ? list : []) {
54
+ const id = session && (session.id ?? (session.header && session.header.id));
55
+ if (String(id ?? '') !== sessionId)
56
+ continue;
57
+ const cwd = session && session.header && session.header.cwd;
58
+ // 找到了这个会话:有 cwd 就只取它;没有 cwd = 这个对话不在任何项目里。
59
+ return typeof cwd === 'string' && cwd.trim() !== '' ? [cwd.trim()] : [];
60
+ }
61
+ return null;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
35
67
  /** 活动 Session 的宿主 cwd;项目 Skill 只从这些已知 workspace 推导。 */
36
68
  export function activeSessionCwds(ctx) {
37
69
  try {
@@ -105,7 +137,26 @@ export function createSkillsService(ctx) {
105
137
  const log = pluginLog();
106
138
  const roots = userRoots();
107
139
  const rootByKey = Object.fromEntries(roots.map((root) => [root.key, root]));
108
- const projectOptions = () => ({ projectCwds: activeSessionCwds(ctx) });
140
+ /** op 入参里的 `sessionId`(空串 / 非字符串 → undefined = 全局口径)。 */
141
+ const sessionIdOfArgs = (args) => {
142
+ const raw = args && typeof args.sessionId === 'string' ? args.sessionId.trim() : '';
143
+ return raw === '' ? undefined : raw;
144
+ };
145
+ /**
146
+ * 项目技能根的 cwd 集合(0.21.2)。
147
+ *
148
+ * 不给 `sessionId` 时是**全部活动会话的 cwd 并集**(0.21.2 及以前的行为,界面没有"当前会话"
149
+ * 概念时用它);给了就只取那一个会话的 cwd —— 这是让项目技能按会话隔离的关键:
150
+ * A 对话在 `proj-a`、B 在 `proj-b` 时,并集会让两边都看到两个项目的技能,而"这个对话在哪个
151
+ * 项目里"本来就有唯一答案(会话自己的 `header.cwd`)。
152
+ */
153
+ const projectOptions = (sessionId) => {
154
+ if (sessionId === undefined)
155
+ return { projectCwds: activeSessionCwds(ctx) };
156
+ const own = sessionCwdOf(ctx, sessionId);
157
+ // 清单里找不到这个会话(时序 / 冷会话)→ 退回全局口径,不把项目技能清空。
158
+ return { projectCwds: own === null ? activeSessionCwds(ctx) : own };
159
+ };
109
160
  const requestRoot = async (key) => {
110
161
  if (rootByKey[key])
111
162
  return rootByKey[key];
@@ -160,16 +211,69 @@ export function createSkillsService(ctx) {
160
211
  // 全部 SKILL.md 正文;UI 默认每 5s 轮询一次。加 1s TTL 缓存吸收密集轮询,
161
212
  // 任何写操作成功后立即失效(afterWrite),保证写后读到的总是新状态。
162
213
  const STATE_TTL_MS = 1000;
163
- let stateCache = null;
164
- const readState = async () => {
165
- if (stateCache && Date.now() - stateCache.at < STATE_TTL_MS)
166
- return stateCache.value;
167
- const value = await state(projectOptions());
168
- stateCache = { at: Date.now(), value };
169
- return value;
214
+ // ⚠️ 按**项目根集合**分桶(0.21.2):`projectOptions(sessionId)` 只取该会话的 cwd,两个会话能
215
+ // 算出两份不同的技能清单。单槽缓存下 A 读完 B 直接用 —— 症状是「B 的对话里列出了 A 项目的技能」。
216
+ // 键不能是 sessionId:同一工作区里的多个对话、以及全局口径,算出来的是**同一份**扫描结果,
217
+ // 按会话分桶会让 `skillCatalog.refresh()` 为每个会话各扫一遍磁盘(写操作因此从毫秒拖到秒级)。
218
+ // 上限 16 条 LRU(与记忆段同一手法)。
219
+ const STATE_CACHE_MAX = 16;
220
+ const stateCache = new Map();
221
+ /** cwd 集合 → 缓存键(去重、排序:同一组项目根只有一个桶)。 */
222
+ const stateKeyOf = (cwds) => {
223
+ const seen = new Set();
224
+ for (const cwd of cwds) {
225
+ const trimmed = String(cwd || '').trim();
226
+ if (trimmed !== '')
227
+ seen.add(trimmed);
228
+ }
229
+ return [...seen].sort().join('\u0000');
230
+ };
231
+ /**
232
+ * 同一次扫描的并发合流 + 写后作废(0.21.2)。
233
+ *
234
+ * `scope-get`、斜杠菜单、对账、目录刷新会在同一拍里各问一次「技能清单」——不合流的话
235
+ * 一次场景切换会并发跑好几份全量扫描,既有磁盘开销又抢事件循环;而写操作之后在飞的那份
236
+ * 是**写之前**的,不能复用。`generation` 同时解决两件事:同代的在飞共享,换代后的旧结果不落缓存。
237
+ */
238
+ let stateGeneration = 0;
239
+ const stateInflight = new Map();
240
+ const readState = async (sessionId) => {
241
+ const options = projectOptions(sessionId);
242
+ const key = stateKeyOf(options.projectCwds);
243
+ const hit = stateCache.get(key);
244
+ if (hit !== undefined && Date.now() - hit.at < STATE_TTL_MS)
245
+ return hit.value;
246
+ const running = stateInflight.get(key);
247
+ if (running !== undefined && running.gen === stateGeneration)
248
+ return running.promise;
249
+ const gen = stateGeneration;
250
+ let promise;
251
+ promise = state(options).then((value) => {
252
+ // 扫描期间有过写操作 → 这份结果可能是写之前的,丢掉(下一次读会重扫)。
253
+ if (gen === stateGeneration) {
254
+ stateCache.delete(key);
255
+ stateCache.set(key, { at: Date.now(), value });
256
+ while (stateCache.size > STATE_CACHE_MAX) {
257
+ const oldest = stateCache.keys().next();
258
+ if (oldest.done === true)
259
+ break;
260
+ stateCache.delete(oldest.value);
261
+ }
262
+ }
263
+ return value;
264
+ }).finally(() => {
265
+ const current = stateInflight.get(key);
266
+ if (current !== undefined && current.promise === promise)
267
+ stateInflight.delete(key);
268
+ });
269
+ stateInflight.set(key, { gen, promise });
270
+ return promise;
170
271
  };
171
272
  const afterWrite = () => {
172
- stateCache = null;
273
+ // 写操作影响的是磁盘事实 → 全清;同时换代,让写之前发出的扫描结果不再被当成新鲜数据。
274
+ stateGeneration += 1;
275
+ stateCache.clear();
276
+ stateInflight.clear();
173
277
  notifyChatCatalog(ctx, invalidateSkills);
174
278
  };
175
279
  let mutationQueue = Promise.resolve();
@@ -180,16 +284,32 @@ export function createSkillsService(ctx) {
180
284
  };
181
285
  const registerProviders = () => {
182
286
  const disposers = [];
287
+ // 卸载竞态(0.21.2):自定义目录那份 watcher 是**异步**挂上的(要先读状态文件)。
288
+ // 如果插件在 `readManagerState()` 落地之前就被卸载,`dispose()` 已经跑完,随后那句
289
+ // `disposers.push(...)` 就永远没人收 —— 结果是一个 Worker 线程加一组 fs.watch 句柄
290
+ // 留在进程里(Worker 已 unref 不会挡住退出,但每次重载都多一份,热重载环境里会累积)。
291
+ // 所以记一个"已卸载"标记:晚到的 disposer 当场自己跑掉。
292
+ let disposed = false;
293
+ const add = (dispose) => {
294
+ if (disposed) {
295
+ try {
296
+ dispose();
297
+ }
298
+ catch { /* ignore */ }
299
+ return;
300
+ }
301
+ disposers.push(dispose);
302
+ };
183
303
  try {
184
304
  const dispose = ctx.skills.registerProvider((control) => externalSkillProvider(control, providerInvalidators));
185
305
  if (typeof dispose === 'function')
186
- disposers.push(dispose);
306
+ add(dispose);
187
307
  }
188
308
  catch (e) {
189
309
  console.error('[dsh-plugin-tool-management] global skills provider registration failed:', message(e));
190
310
  }
191
311
  try {
192
- disposers.push(registerAgentSkillProviders(ctx, providerInvalidators));
312
+ add(registerAgentSkillProviders(ctx, providerInvalidators));
193
313
  }
194
314
  catch (e) {
195
315
  console.error('[dsh-plugin-tool-management] agent-scoped provider setup failed:', message(e));
@@ -200,7 +320,7 @@ export function createSkillsService(ctx) {
200
320
  .filter((root) => root.key !== 'official')
201
321
  .map((root) => String((root && root.path) || ''))
202
322
  .filter(Boolean);
203
- disposers.push(watchDirectories(watchPaths, invalidateSkills));
323
+ add(watchDirectories(watchPaths, invalidateSkills));
204
324
  // 自定义目录在状态文件里,注册时读取一次并一并监听(后添加的目录由
205
325
  // provider 首次 list 天然覆盖,等插件重载后才有 watcher)。
206
326
  readManagerState()
@@ -209,19 +329,23 @@ export function createSkillsService(ctx) {
209
329
  .map((root) => String((root && root.path) || ''))
210
330
  .filter(Boolean);
211
331
  if (customPaths.length)
212
- disposers.push(watchDirectories(customPaths, invalidateSkills));
332
+ add(watchDirectories(customPaths, invalidateSkills));
213
333
  })
214
334
  .catch(() => { });
215
335
  }
216
336
  catch (e) {
217
337
  console.error('[dsh-plugin-tool-management] skill watcher setup failed:', message(e));
218
338
  }
219
- return () => { for (const dispose of disposers) {
220
- try {
221
- dispose();
339
+ return () => {
340
+ disposed = true;
341
+ for (const dispose of disposers) {
342
+ try {
343
+ dispose();
344
+ }
345
+ catch { /* ignore */ }
222
346
  }
223
- catch { /* ignore */ }
224
- } };
347
+ disposers.length = 0;
348
+ };
225
349
  };
226
350
  /** 成功 → {ok:true, data};core 业务失败 → 原样透传 {ok:false,...};成功后可选触发 afterWrite。 */
227
351
  const wrap = (fn, after) => async (args) => {
@@ -283,11 +407,12 @@ export function createSkillsService(ctx) {
283
407
  }
284
408
  const ops = {
285
409
  // 读操作(state 走短 TTL 缓存,见上方 readState)
286
- 'skill-state': wrap(() => readState()),
410
+ // 会话层(0.21.2):给了 `sessionId` 就只按该会话的 cwd 推导项目技能根。
411
+ 'skill-state': wrap((args) => readState(sessionIdOfArgs(args))),
287
412
  'skill-detail': wrap(async (args) => {
288
413
  const key = String(args.root || 'dsh');
289
414
  // requestRoot 未命中时回传原始 key,让 core 的 error.root.unknown 带上来源名(而非 undefined)。
290
- return skillDetail((await requestRoot(key)) || key, String(args.name || ''), projectOptions());
415
+ return skillDetail((await requestRoot(key)) || key, String(args.name || ''), projectOptions(sessionIdOfArgs(args)));
291
416
  }),
292
417
  'skill-browse': wrap((args) => browseDirectories(args && args.path)),
293
418
  // 启停(写 manager 状态,不改源文件)
@@ -0,0 +1,74 @@
1
+ // 并发编辑的「内容指纹」判据(0.21.2 Phase 4)。
2
+ //
3
+ // 问题:两个窗口同时打开同一份记忆 / 提示词 / 补丁,后保存的那一份会把前一份的改动整份覆盖。
4
+ // 文件锁只能防同进程的两条路径,防不住外部编辑器 —— 所以判据必须是**内容**:读的时候给一份
5
+ // 指纹,写的时候核对指纹还在不在。
6
+ //
7
+ // 为什么不用 mtime:拷贝、同步盘回写、`touch` 都会改 mtime 而不改内容;反过来,某些工具
8
+ // 会保留 mtime 而改内容。内容 hash 没有这两种误判。
9
+ //
10
+ // `expectedStamp` 是**可选**参数:不带 = 回到旧行为(不校验)。这样旧客户端、脚本、
11
+ // 模型工具都不受影响,只有界面在编辑弹窗里主动带。
12
+ import { createHash } from 'node:crypto';
13
+ import { readFile } from 'node:fs/promises';
14
+ export const STALE_WRITE_CODE = 'stale-write';
15
+ /** 内容指纹:sha256 前 16 位。`null` / `undefined` 表示"文件不存在"。 */
16
+ export function stampOfText(text) {
17
+ if (text === null || text === undefined)
18
+ return null;
19
+ return createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 16);
20
+ }
21
+ /** 文件指纹:不存在返回 `null`;其它读失败抛错(调用方按失败处理,不静默放行)。 */
22
+ export async function stampOf(abs) {
23
+ try {
24
+ return stampOfText(await readFile(abs, 'utf8'));
25
+ }
26
+ catch (e) {
27
+ if (e?.code === 'ENOENT')
28
+ return null;
29
+ throw e;
30
+ }
31
+ }
32
+ /** 规范化客户端传来的 `expectedStamp`:非字符串 / 空串 = 没带。 */
33
+ export function normalizeStamp(expected) {
34
+ if (typeof expected !== 'string')
35
+ return null;
36
+ const s = expected.trim();
37
+ return s === '' ? null : s;
38
+ }
39
+ export function staleWriteResult(current) {
40
+ return {
41
+ ok: false,
42
+ code: STALE_WRITE_CODE,
43
+ error: '文件已在别处被修改,本次保存没有写入。请重新加载后再改,或选择覆盖保存。',
44
+ current: { stamp: current },
45
+ };
46
+ }
47
+ /**
48
+ * 比对指纹:一致 / 没带 = `null`(继续写);不一致 = 冲突回执。
49
+ * 调用方直接 `return conflict` 即可,回执形状与其余 op 的失败一致。
50
+ */
51
+ export function stampConflict(current, expected) {
52
+ const want = normalizeStamp(expected);
53
+ if (want === null)
54
+ return null;
55
+ return want === current ? null : staleWriteResult(current);
56
+ }
57
+ export class StaleWriteError extends Error {
58
+ code = STALE_WRITE_CODE;
59
+ current;
60
+ constructor(current) {
61
+ super('文件已在别处被修改,本次保存没有写入。');
62
+ this.name = 'StaleWriteError';
63
+ this.current = current;
64
+ }
65
+ }
66
+ /** 抛错版:给没有结构化回执通道的写路径用。 */
67
+ export async function assertStamp(abs, expected) {
68
+ const want = normalizeStamp(expected);
69
+ if (want === null)
70
+ return;
71
+ const current = await stampOf(abs);
72
+ if (current !== want)
73
+ throw new StaleWriteError(current);
74
+ }
@@ -77,22 +77,49 @@ export function createSubagentCatalog(deps, opts = {}) {
77
77
  const maxDescription = opts.maxDescription ?? DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH;
78
78
  const ttlMs = opts.ttlMs ?? 1000;
79
79
  const now = opts.now ?? (() => Date.now());
80
- let allowed = [];
80
+ let docs = [];
81
+ let globalSceneLists = [];
82
+ /** 全局口径的可见集合(正在用的场景绑定 ∩ 全局启停)—— 每次重算从 docs 推一次。 */
83
+ let globalAllowed = new Set();
81
84
  let loadedAt = Number.NEGATIVE_INFINITY;
82
85
  let inflight = null;
83
- // 渲染结果按**深度 + 尾句前提**缓存:过滤只依赖深度这一个整数(实际出现的深度就 0/1/2 三档),
84
- // 而尾句点不点名 `subagent_manager_list` 取决于**这个 agent 手里有没有它**(2026-10-14
85
- // 审查 P1-8:此前只按深度缓存,于是尾句用的是第一个来问的 agent 的答案)。
86
- // 两维都是小枚举,于是"每个 step 同步渲染"退化成一次查表。重算成功时清空。
86
+ // 渲染结果按**深度 + 尾句前提 + 会话层指纹**缓存:过滤只依赖这三样。
87
87
  const rendered = new Map();
88
88
  const recompute = async () => {
89
89
  try {
90
- allowed = (await filterBySceneBinding(await deps.list(), await deps.sceneLists())).allowed;
90
+ docs = await deps.list();
91
+ globalSceneLists = await deps.sceneLists();
92
+ globalAllowed = new Set(filterBySceneBinding(docs, globalSceneLists).allowed
93
+ .filter((p) => p.enabled !== false)
94
+ .map((p) => p.name));
91
95
  rendered.clear();
92
96
  }
93
97
  catch { /* 保留上一次的值;首次失败则维持 [] */ }
94
98
  loadedAt = now();
95
99
  };
100
+ /**
101
+ * 某个 agent 该列的人设:四层并值(`flagFor`)优先;这一层没话说就落到全局口径。
102
+ *
103
+ * 会话层**能救回**场景绑定的排除项("进入场景之后还想开什么就开什么")—— 所以这里不再
104
+ * 先按场景过滤再按覆盖过滤,而是逐条问一句"本会话怎么判",只有判不出来时才用全局集合。
105
+ */
106
+ const listedFor = (agent, depth) => {
107
+ let flag;
108
+ try {
109
+ flag = deps.flagFor ? deps.flagFor(agent) : undefined;
110
+ }
111
+ catch {
112
+ flag = undefined;
113
+ }
114
+ return docs.filter((p) => {
115
+ if (!catalogInjectedAt(p, depth))
116
+ return false;
117
+ const f = flag ? flag(p.name) : undefined;
118
+ if (typeof f === 'boolean')
119
+ return f;
120
+ return globalAllowed.has(p.name);
121
+ });
122
+ };
96
123
  const revalidate = () => {
97
124
  if (inflight)
98
125
  return inflight;
@@ -105,15 +132,22 @@ export function createSubagentCatalog(deps, opts = {}) {
105
132
  void revalidate();
106
133
  const depth = subagentDepthOf(agent);
107
134
  const visible = deps.listToolVisible ? deps.listToolVisible(agent) : true;
108
- const key = depth + '|' + (visible ? '1' : '0');
109
- const cached = rendered.get(key);
110
- if (cached !== undefined)
111
- return cached;
112
- const out = renderSubagentCatalog(allowed.filter((p) => catalogInjectedAt(p, depth)), maxEntries, maxDescription, visible);
113
- rendered.set(key, out);
135
+ const hasLayer = deps.flagFor !== undefined && deps.flagFor(agent) !== undefined;
136
+ // 有会话层但装配层没给指纹(老装配 / 测试)时不走渲染缓存:宁可多算一次。
137
+ const cacheable = !hasLayer || deps.layerKeyFor !== undefined;
138
+ const layerKey = deps.layerKeyFor ? deps.layerKeyFor(agent) : '';
139
+ const key = layerKey + '\u0000' + depth + '|' + (visible ? '1' : '0');
140
+ if (cacheable) {
141
+ const cached = rendered.get(key);
142
+ if (cached !== undefined)
143
+ return cached;
144
+ }
145
+ const out = renderSubagentCatalog(listedFor(agent, depth), maxEntries, maxDescription, visible);
146
+ if (cacheable)
147
+ rendered.set(key, out);
114
148
  return out;
115
149
  },
116
- catalogVisibleAt: (depth) => allowed.some((p) => catalogInjectedAt(p, depth)),
150
+ catalogVisibleAt: (depth, agent) => listedFor(agent, depth).length > 0,
117
151
  refresh: () => {
118
152
  loadedAt = Number.NEGATIVE_INFINITY;
119
153
  return revalidate();
@@ -1,3 +1,9 @@
1
+ // 人设文件的读侧与渲染:解析 frontmatter、规整名字、把中性骨架拼成某个语言的提示词,
2
+ // 以及工具结果/空结果的文案收口。
3
+ //
4
+ // 从 subagents/service.ts 整段搬来,一行未改。这一层不认识宿主也不写文件:进来一段文本,
5
+ // 出去一个 PersonaDoc;创建与更新走的解析口径与扫描时同一份,两处不能各写一套。
6
+ import { decodeYamlScalar } from '../skills/frontmatter.js';
1
7
  /** 逗号/顿号分隔的名字清单(空串 → undefined)。 */
2
8
  export function listOf(value) {
3
9
  const text = String(value ?? '').trim();
@@ -72,19 +78,34 @@ export function parsePersona(raw, fallbackName) {
72
78
  let body = raw;
73
79
  let toolsByPreset;
74
80
  if (m) {
81
+ // 新写入用 `output:` + YAML 序列;旧文件是重复的 `output: 一行`。两种都读。
82
+ let inOutputSequence = false;
75
83
  for (const line of m[1].split(/\r?\n/)) {
84
+ if (inOutputSequence) {
85
+ const item = /^\s*-\s?(.*)$/.exec(line);
86
+ if (item) {
87
+ const value = decodeYamlScalar(item[1]).trim();
88
+ if (value !== '')
89
+ outputLines.push(value);
90
+ continue;
91
+ }
92
+ if (line.trim() === '')
93
+ continue;
94
+ inOutputSequence = false;
95
+ }
76
96
  const kv = /^([A-Za-z_-]+)\s*:\s*(.*)$/.exec(line.trim());
77
97
  if (!kv)
78
98
  continue;
79
99
  const key = kv[1].toLowerCase();
80
- // `output:` 是**可重复**的键(一条要求一行,按顺序收集)。frontmatter 是逐行解析的,
81
- // 多行契约塞不进一个值里;写成重复键比引入块标量语法简单,也一眼看得懂。
82
100
  if (key === 'output') {
83
- if (kv[2].trim() !== '')
84
- outputLines.push(kv[2].trim());
101
+ const value = decodeYamlScalar(kv[2]).trim();
102
+ if (value === '')
103
+ inOutputSequence = true;
104
+ else
105
+ outputLines.push(value);
85
106
  continue;
86
107
  }
87
- data[key] = kv[2].trim();
108
+ data[key] = decodeYamlScalar(kv[2]).trim();
88
109
  }
89
110
  toolsByPreset = parsePresetToolRules(m[1]);
90
111
  body = raw.slice(m[0].length);
@@ -3,6 +3,7 @@
3
3
  // 从 subagents/service.ts 整段搬来,一行未改。只写用户填过的键这条纪律留在函数自己的
4
4
  // 注释里;名字谓词仍收敛到 ../paths.ts,这里不另写一份。
5
5
  import { isValidSegment } from '../paths.js';
6
+ import { yamlScalar } from '../skills/frontmatter.js';
6
7
  import { DEFAULT_PERSONA_CATALOG_DEPTH, normalizeReasoningEffort, truthyFlag } from './persona-parse.js';
7
8
  /** 人设名长度上限(字符)。 */
8
9
  export const PERSONA_NAME_MAX = 64;
@@ -44,25 +45,28 @@ export function serializePersona(args) {
44
45
  // 说明"它和默认一样",也保证老的人设文件回写后逐字节不变。入参兼容布尔与字符串两种形态
45
46
  // (界面传布尔,手写/导入的 frontmatter 走解析侧已归一成布尔)。
46
47
  const continuable = args?.continuable === true || truthyFlag(String(args?.continuable ?? ''));
47
- // `output` 可传字符串(按行拆)或数组(界面直接给数组):一条要求写成一行重复键。
48
+ // `output` 可传字符串(按行拆)或数组(界面直接给数组):一条要求写成序列的一项。
48
49
  const outputLines = (Array.isArray(args?.output) ? args.output.map((v) => String(v)) : String(args?.output ?? '').split(/\r?\n/))
49
50
  .map((line) => line.trim())
50
51
  .filter((line) => line !== '');
51
52
  const lines = ['---'];
52
53
  if (description)
53
- lines.push('description: ' + description);
54
+ lines.push('description: ' + yamlScalar(description));
54
55
  if (provider)
55
- lines.push('provider: ' + provider);
56
+ lines.push('provider: ' + yamlScalar(provider));
56
57
  if (model)
57
- lines.push('model: ' + model);
58
+ lines.push('model: ' + yamlScalar(model));
58
59
  if (reasoningEffort)
59
- lines.push('reasoningEffort: ' + reasoningEffort);
60
+ lines.push('reasoningEffort: ' + yamlScalar(reasoningEffort));
60
61
  if (hasCatalogDepth)
61
62
  lines.push('catalogDepth: ' + String(catalogDepth));
62
63
  if (continuable)
63
64
  lines.push('continuable: true');
64
- for (const line of outputLines)
65
- lines.push('output: ' + line);
65
+ if (outputLines.length) {
66
+ lines.push('output:');
67
+ for (const line of outputLines)
68
+ lines.push(' - ' + yamlScalar(line));
69
+ }
66
70
  if (tools.length)
67
71
  lines.push('tools: ' + tools.join(', '));
68
72
  if (toolsDeny.length)
@@ -9,6 +9,7 @@ import { createRunProvider } from "./run-provider.js";
9
9
  import { createRequire } from 'node:module';
10
10
  import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
11
11
  import { join } from 'node:path';
12
+ import { writeFileAtomically } from '../memories/index-io.js';
12
13
  import { resolveDshHome } from '../skills/core.js';
13
14
  import { listTrashEntries, moveOutOfTrash, moveToTrash, purgeTrashEntry, readTrashEntry } from '../hub.js';
14
15
  import { expandUploads, planPersonaImport } from '../imports/upload.js';
@@ -142,7 +143,7 @@ export function createSubagentService(ctx, opts) {
142
143
  }
143
144
  async function writeEnabled(list) {
144
145
  await mkdir(stateDir, { recursive: true });
145
- await writeFile(stateFile, JSON.stringify({ version: 1, enabled: list }, null, 2), 'utf8');
146
+ await writeFileAtomically(stateFile, JSON.stringify({ version: 1, enabled: list }, null, 2));
146
147
  enabledCache = list;
147
148
  // 写入后重取指纹,让下一次 readEnabled 直接命中缓存(否则会白读一次)。
148
149
  enabledStamp = await fileStamp(stateFile);
@@ -299,7 +300,7 @@ export function createSubagentService(ctx, opts) {
299
300
  catch (e) {
300
301
  return { ok: false, error: `创建人设目录失败: ${dir}(${message(e)})` };
301
302
  }
302
- await writeFile(target, serializePersona(args), 'utf8');
303
+ await writeFileAtomically(target, serializePersona(args));
303
304
  // v0.8.5:新建默认不启动——显式集合下新名天然停用;文件缺失时先物化全集并排除新名。
304
305
  cache = null;
305
306
  return withEnabledNote({ ok: true, name }, () => materializeEnabledExcluding([name]));