@dotdance/dsh-skill-scope 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -12,18 +12,93 @@ import { dshHomePath } from "@deepseek-ai/dsh-home-paths";
12
12
  * **唯一会被求值器采纳的模式**,用它当缺省可以避免「存进去的 mode 与读回来
13
13
  * 归一后的 mode 不一致」这种需要额外解释的状态。
14
14
  */
15
- const EMPTY_POLICY = {
15
+ const EMPTY_POLICY = deepFreeze({
16
16
  mode: "blacklist",
17
17
  skills: [],
18
18
  mcps: [],
19
19
  showOfficialSkills: false
20
- };
20
+ });
21
+ /**
22
+ * 冻结缺省策略(含里面的数组)。
23
+ *
24
+ * 它是**被所有调用方共享**的常量:`tests/agent/hooks.spec.ts` 的 `makeHarness` 直接把它
25
+ * 当作 `global`,生产侧也可能把它当缺省层返回。一次原地 `push` 就会让缺省策略永久带上
26
+ * 别人的名字,而且跨用例、跨会话串味(单跑不复现、全量偶发)。冻结后这种写入会直接抛。
27
+ */
28
+ function deepFreeze(value) {
29
+ if (value === null || typeof value !== "object") return value;
30
+ for (const inner of Object.values(value)) deepFreeze(inner);
31
+ return Object.freeze(value);
32
+ }
21
33
  /** Skill 名形状(与 `dsh-skill` 的命名一致,见设计 3.1)。 */
22
34
  const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
23
35
  /** MCP server 名形状。由 `MCP_SERVER_NAME_MAX` 生成,长度约束不再手写第二遍。 */
24
36
  const MCP_NAME_RE = new RegExp(`^[A-Za-z0-9_-]{1,32}$`);
25
37
  const SORTED_UNIQUE = (names) => [...new Set(names)].sort();
26
38
  /**
39
+ * 逐元素挑出合法名字,并把被丢弃的元素**原样**带出来(`previewValue` 与去重交给调用方)。
40
+ *
41
+ * **不能退回「正则挂在 zod 数组元素上」的写法**:`z.array(z.string().regex(…)).catch([])`
42
+ * 的 `.catch` 是整数组级别的,一个坏名字让整份名单失效(见 lenientPolicySchema 的注释)。
43
+ * 这里改成逐个判,最坏只丢那一条,且丢弃项可被用户看见。
44
+ *
45
+ * `pattern` 必须**不带 `g` 标志**:`RegExp.prototype.test` 对带 `g` 的正则会推进
46
+ * `lastIndex`,同一个正则复用会漏判隔项(这里用的是模块级共享正则)。
47
+ */
48
+ function pickNames(raw, pattern) {
49
+ const names = [];
50
+ const dropped = [];
51
+ for (const item of raw) if (typeof item === "string" && pattern.test(item)) names.push(item);
52
+ else dropped.push(item);
53
+ return {
54
+ names,
55
+ dropped
56
+ };
57
+ }
58
+ /**
59
+ * 丢弃项去重后再渲染:按**原值**去重(`Set` 对原始值按值、对对象按引用),
60
+ * 先渲染再去重会把 `1` 与 `"1"` 这类不同原值合并成一条,条数与实际不符。
61
+ */
62
+ function previewDropped(items) {
63
+ return [...new Set(items)].map(previewValue);
64
+ }
65
+ /** 被丢弃条目的展示上限:单条超过这个长度就截断(用户输入长度不可控)。 */
66
+ const PREVIEW_MAX = 40;
67
+ /**
68
+ * 把被丢弃的元素写成一短段可读文本。**永不抛错**。
69
+ *
70
+ * `normalizePolicy` 的契约是「永不抛错」,而 `JSON.stringify` 遇到 `BigInt` 与循环引用
71
+ * 会抛 `TypeError`(实测 `{skills:[1n]}` → `TypeError: Do not know how to serialize a BigInt`),
72
+ * 所以这里必须兜住;字符串走 `JSON.stringify` 是为了让空串与前导空格在日志里可见
73
+ * (`""` / `" good"` 一眼可辨)。
74
+ */
75
+ function previewValue(item) {
76
+ if (typeof item === "number" && !Number.isFinite(item)) return String(item);
77
+ let text;
78
+ if (typeof item === "string") text = JSON.stringify(clamp(item));
79
+ else try {
80
+ text = JSON.stringify(item) ?? `[${typeof item}]`;
81
+ } catch {
82
+ text = `[${typeof item}]`;
83
+ }
84
+ return clamp(text);
85
+ }
86
+ /** 按**码点**(不是 UTF-16 码元)截断,超长加省略号。 */
87
+ function clamp(text) {
88
+ if (text.length <= PREVIEW_MAX) return text;
89
+ return `${Array.from(text).slice(0, PREVIEW_MAX).join("")}…`;
90
+ }
91
+ /**
92
+ * 该字段是否**整份**被 zod 丢掉——与「只丢了几个元素」区分开。
93
+ *
94
+ * 只剩「非数组(类型写错)」一种:数量超限**不再**由 zod 判(见 reconstruct 后的注释),
95
+ * 因为超限必须在元素过滤之后、按**过滤后的有效名字数**判,否则
96
+ * 「512 条合法 + 1 条 junk」会先因 513 条超限被整份 `.catch()` 掉。
97
+ */
98
+ function listVoided(raw) {
99
+ return raw !== void 0 && !Array.isArray(raw);
100
+ }
101
+ /**
27
102
  * 宽松的读取 schema:任何一项不合法都退回该层的缺省,由调用方补一条 warning。
28
103
  * `mode` 可选(缺失时取调用方给的层缺省);名单元素必须过正则、数量不得超限。
29
104
  *
@@ -36,8 +111,8 @@ const SORTED_UNIQUE = (names) => [...new Set(names)].sort();
36
111
  */
37
112
  const lenientPolicySchema = (fallbackMode) => z.object({
38
113
  mode: z.enum(["blacklist", "default"]).transform(() => "blacklist").catch(() => fallbackMode).default(() => fallbackMode),
39
- skills: z.array(z.string().regex(SKILL_NAME_RE)).max(512).catch([]).default([]),
40
- mcps: z.array(z.string().regex(MCP_NAME_RE)).max(512).catch([]).default([]),
114
+ skills: z.array(z.unknown()).catch([]).default([]),
115
+ mcps: z.array(z.unknown()).catch([]).default([]),
41
116
  showOfficialSkills: z.boolean().catch(false).default(false)
42
117
  });
43
118
  /**
@@ -51,22 +126,39 @@ function normalizePolicy(raw, fallbackMode) {
51
126
  warning: `策略内容不合法,已回退为空策略:${parsed.error.message}`
52
127
  };
53
128
  const source = raw;
129
+ const skillsScan = pickNames(parsed.data.skills, SKILL_NAME_RE);
130
+ const mcpsScan = pickNames(parsed.data.mcps, MCP_NAME_RE);
131
+ const droppedSkills = previewDropped(skillsScan.dropped);
132
+ const droppedMcps = previewDropped(mcpsScan.dropped);
133
+ const skills = SORTED_UNIQUE(skillsScan.names);
134
+ const mcps = SORTED_UNIQUE(mcpsScan.names);
135
+ const skillsOverflow = skills.length > 512;
136
+ const mcpsOverflow = mcps.length > 512;
54
137
  const policy = {
55
138
  mode: parsed.data.mode,
56
- skills: SORTED_UNIQUE(parsed.data.skills),
57
- mcps: SORTED_UNIQUE(parsed.data.mcps),
139
+ skills: skillsOverflow ? [] : skills,
140
+ mcps: mcpsOverflow ? [] : mcps,
58
141
  showOfficialSkills: parsed.data.showOfficialSkills
59
142
  };
60
143
  const drifted = [];
61
- if (source?.skills !== void 0 && !sameSet(source.skills, policy.skills)) drifted.push("skills");
62
- if (source?.mcps !== void 0 && !sameSet(source.mcps, policy.mcps)) drifted.push("mcps");
144
+ if (listVoided(source?.skills)) drifted.push("skills");
145
+ if (listVoided(source?.mcps)) drifted.push("mcps");
63
146
  if (source?.showOfficialSkills !== void 0 && source.showOfficialSkills !== policy.showOfficialSkills) drifted.push("showOfficialSkills");
64
147
  const migratedMode = source?.mode !== void 0 && source.mode !== policy.mode;
65
- if (drifted.length > 0) {
148
+ const dropSegment = (label, names) => names.length === 0 ? "" : `${label}:${names.slice(0, 5).join(", ")}${names.length > 5 ? ` 等 ${names.length} 项` : ""}`;
149
+ const droppedTotal = droppedSkills.length + droppedMcps.length;
150
+ const dropParts = [dropSegment("不合法 skill", droppedSkills), dropSegment("不合法 mcp", droppedMcps)].filter((part) => part !== "");
151
+ const droppedText = dropParts.length === 0 ? "" : `(${dropParts.join(";")})`;
152
+ const clauses = [];
153
+ if (drifted.length > 0) clauses.push(`已忽略字段:${drifted.join(", ")}`);
154
+ if (droppedTotal > 0) clauses.push("已丢弃不合法的名字");
155
+ if (skillsOverflow) clauses.push(`skills 有效名字 ${skills.length} 条超过上限 512,已整份忽略`);
156
+ if (mcpsOverflow) clauses.push(`mcps 有效名字 ${mcps.length} 条超过上限 512,已整份忽略`);
157
+ if (clauses.length > 0) {
66
158
  const migrated = migratedMode ? `;mode 由「${String(source?.mode)}」归一到「${policy.mode}」(白名单已废弃,名单语义统一为黑名单)` : "";
67
159
  return {
68
160
  policy,
69
- warning: `策略中有内容不合法,已忽略字段:${drifted.join(", ")}${migrated}`
161
+ warning: `策略中有内容不合法,${clauses.join(";")}${droppedText}${migrated}`
70
162
  };
71
163
  }
72
164
  if (migratedMode) return {
@@ -75,12 +167,6 @@ function normalizePolicy(raw, fallbackMode) {
75
167
  };
76
168
  return { policy };
77
169
  }
78
- function sameSet(raw, normalized) {
79
- if (!Array.isArray(raw)) return false;
80
- const asStrings = raw.filter((item) => typeof item === "string");
81
- if (asStrings.length !== raw.length) return false;
82
- return asStrings.length === normalized.length && SORTED_UNIQUE(asStrings).join("\n") === normalized.join("\n");
83
- }
84
170
  /**
85
171
  * `JSON.parse` 一次,失败时折叠成 `{ ok: false, warning }`。
86
172
  *
@@ -209,9 +295,7 @@ const WORKSPACE_KEY = "workspace";
209
295
  /** 旧格式的行键。读到它即视为「未迁移的黑名单」。 */
210
296
  const LEGACY_KEY = "default";
211
297
  const sortKeys = (map) => {
212
- const out = {};
213
- for (const name of Object.keys(map).sort()) out[name] = map[name];
214
- return out;
298
+ return Object.fromEntries(Object.keys(map).sort().map((name) => [name, map[name]]));
215
299
  };
216
300
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
217
301
  /**
@@ -225,7 +309,7 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
225
309
  * `MAX_NAMES` 上限仍然保留:只为防止文件被写成无界清单,正常用量远低于它。
226
310
  */
227
311
  function parseDomain(raw, label) {
228
- const map = {};
312
+ const map = Object.create(null);
229
313
  const warnings = [];
230
314
  if (raw === void 0) return {
231
315
  map,
@@ -259,7 +343,7 @@ function parseDomain(raw, label) {
259
343
  }
260
344
  /** 旧格式:`default.skills` 是黑名单数组,每一项的含义都是「关」。 */
261
345
  function parseLegacyDomain(raw, label) {
262
- const map = {};
346
+ const map = Object.create(null);
263
347
  const warnings = [];
264
348
  if (raw === void 0) return {
265
349
  map,
@@ -358,7 +442,7 @@ function filterAgainstGlobal(policy, global) {
358
442
  mcps: new Set(global.mcps)
359
443
  };
360
444
  const pick = (map, domain) => {
361
- const out = {};
445
+ const out = Object.create(null);
362
446
  for (const [name, value] of Object.entries(map)) if (value !== !denied[domain].has(name)) out[name] = value;
363
447
  return out;
364
448
  };
@@ -378,10 +462,10 @@ function filterAgainstGlobal(policy, global) {
378
462
  * (`store.ts` 的 `revision` 靠它做乐观锁)。
379
463
  */
380
464
  function serializeWorkspacePolicy(policy, previousText, global) {
381
- const base = {};
465
+ let base = {};
382
466
  if (previousText !== void 0 && previousText.trim() !== "") try {
383
467
  const parsed = JSON.parse(previousText);
384
- if (isPlainObject(parsed)) Object.assign(base, parsed);
468
+ if (isPlainObject(parsed)) base = { ...parsed };
385
469
  } catch {}
386
470
  delete base[LEGACY_KEY];
387
471
  const filtered = filterAgainstGlobal(policy, global);
@@ -526,6 +610,8 @@ var PolicyStore = class {
526
610
  fs;
527
611
  lock;
528
612
  logger;
613
+ /** 上一次已上报的全局警告指纹(`revision + warning`),见 `reportGlobalWarning`。 */
614
+ reportedGlobalWarning = "";
529
615
  /** 按路径串行化的队列尾。每个写入者的 promise 接在上一个之后。 */
530
616
  queues = /* @__PURE__ */ new Map();
531
617
  constructor(deps) {
@@ -541,14 +627,32 @@ var PolicyStore = class {
541
627
  revision: null,
542
628
  exists: false
543
629
  };
630
+ const revision = sha256Hex(text);
544
631
  const { policy, warning } = parseGlobalPolicy(text);
632
+ if (warning !== void 0) this.reportGlobalWarning(path, revision, warning);
545
633
  return {
546
634
  policy,
547
- revision: sha256Hex(text),
635
+ revision,
548
636
  exists: true,
549
637
  ...warning === void 0 ? {} : { warning }
550
638
  };
551
639
  }
640
+ /**
641
+ * 把全局文件的解析警告**就地**记一条日志。
642
+ *
643
+ * 为什么不在调用方记:`loadGlobal` 有三个消费方——面板的 `readGlobalValue`、
644
+ * 工作区视图的 `buildWorkspaceView`、以及真正的执行路径 `agent/hooks` 的 `evaluate`。
645
+ * 只在路由层记的话,「用户从不打开面板」时坏策略**一行日志都没有**(skill 悄悄失效、
646
+ * 用户无从查起);分别记则每次 `agent/created` 都刷一条。
647
+ * 在唯一的数据源处记、并按 `revision + warning` 去重,三种情形一并解决:
648
+ * 内容不变只记一次,文件一改立刻再记一次。
649
+ */
650
+ reportGlobalWarning(path, revision, warning) {
651
+ const stamp = `${revision}\n${warning}`;
652
+ if (stamp === this.reportedGlobalWarning) return;
653
+ this.reportedGlobalWarning = stamp;
654
+ this.logger.warn(`dsh-skill-scope: 全局策略文件(${path}):${warning}`);
655
+ }
552
656
  async saveGlobal(policy, expected) {
553
657
  const path = globalPolicyPath();
554
658
  return await this.write(path, expected, () => serializeGlobalPolicy(policy));
@@ -601,8 +705,8 @@ var PolicyStore = class {
601
705
  async saveWorkspace(cwd, policy, expected) {
602
706
  const path = workspacePolicyPath(cwd);
603
707
  return await this.write(path, expected, async (current) => {
604
- const global = await this.loadGlobal();
605
- return serializeWorkspacePolicy(policy, current ?? void 0, global.policy);
708
+ const global = parseGlobalPolicy(await this.readTransactionText(globalPolicyPath()) ?? void 0).policy;
709
+ return serializeWorkspacePolicy(policy, current ?? void 0, global);
606
710
  });
607
711
  }
608
712
  /** 读全文;文件不存在返回 `null`。读侧无锁,见类注释。 */
@@ -615,6 +719,15 @@ var PolicyStore = class {
615
719
  return null;
616
720
  }
617
721
  }
722
+ /** 写事务只能把 ENOENT 当作不存在;探测失败不能成为覆盖旧文件的依据。 */
723
+ async readTransactionText(path) {
724
+ try {
725
+ return await this.fs.readFile(path);
726
+ } catch (error) {
727
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return null;
728
+ throw error;
729
+ }
730
+ }
618
731
  /**
619
732
  * 一次完整的写事务:入队列 → 进文件锁 → 读现状 → revision 守卫 → 序列化 → 原子写。
620
733
  * `serialize` 拿到锁内读到的旧全文(工作区层用它保住未知顶层键)。
@@ -628,7 +741,7 @@ var PolicyStore = class {
628
741
  try {
629
742
  await ensureParentDir(path);
630
743
  return await this.lock(path, async () => {
631
- const current = await this.readText(path);
744
+ const current = await this.readTransactionText(path);
632
745
  const currentRevision = current === null ? null : sha256Hex(current);
633
746
  if (guard) {
634
747
  if (expected === null || expected === void 0) {
@@ -726,7 +839,8 @@ const deniedOf = (global, domain) => domain === "skills" ? global.skills : globa
726
839
  * 建一个「某域名字 → 是否启用」的判定函数(设计 4.1)。
727
840
  *
728
841
  * 规则只有一条:**工作区有决定就用决定,没有就跟随全局**。
729
- * `false` 是有效值,所以只能写 `??`,不能用 `||`(`false || 默认` 会吞掉「明令关」)。
842
+ * 只有自有键才是决定,不能把 constructor 等继承属性当成状态。
843
+ * `false` 是有效值,所以回退用 `??`,不能用 `||`(`false || 默认` 会吞掉「明令关」)。
730
844
  *
731
845
  * 返回函数而不是单次判定:调用方(`hiddenNames`、工作区视图)都是按域遍历,
732
846
  * 每次调用都重建 Set 会让 512 项的清单退化成 O(n²)。全局名单里同一个名字
@@ -735,7 +849,7 @@ const deniedOf = (global, domain) => domain === "skills" ? global.skills : globa
735
849
  function openResolver(effective, domain) {
736
850
  const denied = new Set(deniedOf(effective.global, domain));
737
851
  const local = effective.workspace?.[domain];
738
- return (name) => local?.[name] ?? !denied.has(name);
852
+ return (name) => (local !== void 0 && Object.hasOwn(local, name) ? local[name] : void 0) ?? !denied.has(name);
739
853
  }
740
854
  /**
741
855
  * 计算一个会话**被关掉**的名字(设计 4.1)。
@@ -777,7 +891,8 @@ function hiddenNames(inventories, effective) {
777
891
  * 改为**最长前缀匹配**:这是设计 4.3 的要求。它的必要性在于 server 名允许下划线
778
892
  * (`MCP_NAME_RE` 的 `[A-Za-z0-9_-]`),所以 `mcp__` 之后「第一个 `__`」并不必然是
779
893
  * 边界——`server_na__me` 这种名字会让非贪婪正则切错。有已知集合时不需要猜:
780
- * 逐个比对哪个已知名真的是该工具名的前缀,取**最长**的那个。
894
+ * 从工具名末尾向前检查每个 `__` 边界,用已知集合查找候选名,首个命中就是最长前缀。
895
+ * 检查次数取决于工具名中的分隔符数量,不随已知服务器数量增加。
781
896
  *
782
897
  * 没有已知集合(或集合里没有命中项)时退化为非贪婪启发式,即设计 4.3 说的
783
898
  * 「只有遇到未知 server 时才退化」。退化是**有损**的,所以调用方应当把这种情形
@@ -785,13 +900,9 @@ function hiddenNames(inventories, effective) {
785
900
  */
786
901
  function serverNameOf(toolName, knownServers) {
787
902
  if (!toolName.startsWith(MCP_PREFIX)) return null;
788
- if (knownServers !== void 0) {
789
- let best = null;
790
- for (const server of knownServers) {
791
- if (!toolName.startsWith(`${MCP_PREFIX}${server}__`)) continue;
792
- if (best === null || server.length > best.length) best = server;
793
- }
794
- if (best !== null) return best;
903
+ if (knownServers !== void 0) for (let boundary = toolName.lastIndexOf("__"); boundary >= MCP_PREFIX.length; boundary = toolName.lastIndexOf("__", boundary - 1)) {
904
+ const server = toolName.slice(MCP_PREFIX.length, boundary);
905
+ if (knownServers.has(server)) return server;
795
906
  }
796
907
  const server = HEURISTIC_SERVER.exec(toolName)?.[1];
797
908
  if (server === void 0 || server.length > 32) return null;
@@ -815,8 +926,9 @@ const HEURISTIC_SERVER = new RegExp(`^${MCP_PREFIX}([A-Za-z0-9_-]{1,32}?)__(.+)$
815
926
  */
816
927
  function classifyMcp(input) {
817
928
  const toolNamesByServer = /* @__PURE__ */ new Map();
929
+ const knownServers = new Set(input.loaderServers);
818
930
  for (const toolName of [...input.scopeToolNames, ...input.ownToolNames ?? []]) {
819
- const serverName = serverNameOf(toolName);
931
+ const serverName = serverNameOf(toolName, knownServers);
820
932
  if (serverName === null) continue;
821
933
  const bucket = toolNamesByServer.get(serverName) ?? /* @__PURE__ */ new Set();
822
934
  bucket.add(toolName);
@@ -939,28 +1051,48 @@ function isOfficialSkillPath(path) {
939
1051
  return path.includes(OFFICIAL_SCOPE);
940
1052
  }
941
1053
  /**
942
- * 已确认的官方 provider:**官方包自己注册、不经磁盘 provider,因此没有 `path` 可判**。
1054
+ * 已确认的官方 provider:**官方包自己注册、且既没有 `path`、资源根也不在作用域内**,
1055
+ * 前两条按磁盘出处的信号都盖不住,只能按名字认。名单外的 provider 一律按第三方处理,
1056
+ * 面板照常展示(判不出不加任何标记)。
943
1057
  *
944
- * 目前只有 `dsh-office`(`@deepseek-ai/dsh-skill-office` 注册 7 条 `office-*`,实测
945
- * `provider='dsh-office'`、`source='bundled'`、`path` 缺失)。这是**白名单**:名单外的
946
- * provider 一律按第三方处理,面板照常展示。
1058
+ * 三条(2026-10-30 实测 0.2.2-alpha.2):`dsh-office`(桌面版把 `office-skills/` 放在
1059
+ * app 资源目录,资源根不含作用域名)、`dsh-official-plugins`、`dsh-personalized-pages`
1060
+ * (后两者 candidate 只有 `locator: null`)。
947
1061
  *
948
1062
  * `runtime` **不在**名单内:`browser-skill`、`memory-recall` 这类宿主内置能力必须留在
949
1063
  * 面板上,用户要能单独关掉它们(见 `tests/routes/handlers.spec.ts` 的「活清单项」用例)。
950
1064
  */
951
- const OFFICIAL_PROVIDERS = /* @__PURE__ */ new Set(["dsh-office"]);
1065
+ const OFFICIAL_PROVIDERS = /* @__PURE__ */ new Set([
1066
+ "dsh-office",
1067
+ "dsh-official-plugins",
1068
+ "dsh-personalized-pages"
1069
+ ]);
1070
+ /**
1071
+ * 这一行的**资源根**是否落在官方作用域内。
1072
+ *
1073
+ * 有些官方 provider 只给 `resourceBase`(资源目录)、不给 `path`:`dsh-badge` 就是
1074
+ * (`dsh-skill-badge/lib/index.js:10-39`,资源根恒在包目录内)。宿主 `toSummary` 会把
1075
+ * `resourceBase` 透出(`dsh-skill/lib/index.js:490-502`),所以不必改 host。
1076
+ */
1077
+ function isOfficialResourceBase(resourceBase) {
1078
+ const path = resourceBase?.path;
1079
+ if (path === void 0) return false;
1080
+ return path.includes(OFFICIAL_SCOPE);
1081
+ }
952
1082
  /**
953
1083
  * 这一行是否属于官方 `@deepseek-ai` skill(⇒ 面板不展示)。**清单过滤只调这一个。**
954
1084
  *
955
1085
  * 判定顺序(任一命中即官方):
956
- * 1. `path` 任意位置含 `@deepseek-ai`(既有规则,覆盖有磁盘出处的官方包);
957
- * 2. `provider` 在 `OFFICIAL_PROVIDERS` 白名单里(覆盖没有 `path` 的官方 provider)。
1086
+ * 1. `path` 任意位置含 `@deepseek-ai`(覆盖有磁盘出处的官方包);
1087
+ * 2. `resourceBase.path` 含 `@deepseek-ai`(覆盖只给资源根的官方 provider);
1088
+ * 3. `provider` 在 `OFFICIAL_PROVIDERS` 白名单里(覆盖两条磁盘信号都没有的)。
958
1089
  *
959
- * 两条都判不出时返回 `false`:**不能因为「判不出」就把它藏起来**,否则用户会失去
960
- * 自己技能/第三方插件技能的开关入口。
1090
+ * 三条都判不出时返回 `false`:**不能因为「判不出」就把它藏起来**,否则用户会失去
1091
+ * 自己技能/第三方插件技能的开关入口;判不出的行就按第三方展示,不加任何标记。
961
1092
  */
962
1093
  function isOfficialSkill(entry) {
963
1094
  if (isOfficialSkillPath(entry.path)) return true;
1095
+ if (isOfficialResourceBase(entry.resourceBase)) return true;
964
1096
  return entry.provider !== void 0 && OFFICIAL_PROVIDERS.has(entry.provider);
965
1097
  }
966
1098
  //#endregion
@@ -1023,9 +1155,9 @@ async function readAgentSkills(skills, agent, cwd, options) {
1023
1155
  * 滤掉官方 `@deepseek-ai` skill。
1024
1156
  *
1025
1157
  * 两个读函数都走这一行,所以全局层与工作区层**口径必然一致**——不会出现
1026
- * 「全局视图藏了、工作区视图还在」这类分歧。判定与取舍见 `./official.ts`
1027
- * (路径含 `@deepseek-ai`,或 provider 在官方白名单里——后者覆盖没有 `path` 的
1028
- * `dsh-office` 那 7 条)。
1158
+ * 「全局视图藏了、工作区视图还在」这类分歧。判定与取舍见 `./official.ts`:
1159
+ * 路径或资源根含 `@deepseek-ai`,或 provider 在官方白名单里(覆盖既不给路径也不给
1160
+ * 资源根的 `dsh-office` / `dsh-official-plugins` / `dsh-personalized-pages`)。
1029
1161
  *
1030
1162
  * **显示开关与掩蔽集是两件事,别合并**:面板用 `showOfficialSkills` 决定「列不列」,
1031
1163
  * 而 `src/agent/hooks.ts` 的掩蔽集合**永远**用全量清单(`showOfficialSkills: true`)。
@@ -1216,44 +1348,46 @@ function denyFor(toolNames, restrictableNames, hiddenServers, knownServers) {
1216
1348
  */
1217
1349
  async function applyMcpRestriction(input) {
1218
1350
  if (input.previous !== null && input.previous.key === input.key) return input.previous;
1219
- input.previous?.release();
1220
- if (input.deny.length === 0) return null;
1351
+ if (input.deny.length === 0) {
1352
+ releasePrevious(input);
1353
+ return null;
1354
+ }
1221
1355
  const release = input.tools.restrict({ deny: [...input.deny] }, input.agent);
1356
+ releasePrevious(input);
1222
1357
  return {
1223
1358
  key: input.key,
1224
1359
  release
1225
1360
  };
1226
1361
  }
1227
- //#endregion
1228
- //#region src/agent/skills.ts
1229
1362
  /**
1230
- * 把一批 skill 关成「只对用户可见」(设计 5.2)。
1363
+ * 释放旧句柄,**失败只上报、不抛**。
1231
1364
  *
1232
- * 产品决定:**关闭 = 只对模型不可见,用户手动 `/name` 调用一律保留**。
1233
- * 所以注册的是原定义的完整副本,只把 `invocation.modelInvocable` 置 false,
1234
- * 并把 `userInvocable` 兜成 `true`——绝不能顺手删掉 `content`、`path` 等字段,
1235
- * 否则用户的 `/name` 会拿到一个空壳。
1236
- *
1237
- * 顺序(全部在 `serial` 内,避免与同 Agent 的其他装配步骤交错):
1238
- * 1. 先释放上一轮 → 2. 逐个取定义 → 3. 注册 → 4. 可选复验。
1239
- *
1240
- * 取不到定义只记 warning 并跳过,不抛错:清单里出现的名字未必还留在注册表里
1241
- * (provider 掉线、文件被删),这不是代码缺陷,不该让整轮装配失败。
1242
- * 复验发现漏网同样只记 warning:详见下方复验段的注释(抛错会导致**全部遮蔽失效**)。
1243
- *
1244
- * 调用方只在「目标隐藏集变化」时调用本函数——同层重名注册在 `dsh-skill` 里
1245
- * 是 warning + no-op disposer,每个回合无条件重注册只会刷告警。
1246
- * 但每次调用仍先释放上一轮:同名不同定义的替换必须靠「先撤后注册」才生效。
1365
+ * `release()` 会同步 emit `tools/change`(`ScopedLayers` 的 undo 里调 `onChange()`),
1366
+ * 若某个监听器在 emit 时抛错,异常会从 `release()` 里冒出来。裸调用的话:新层已挂上、
1367
+ * 旧层已撤、`applyMcpRestriction` 却抛错 ⇒ `applyRound` 不更新 `state.mcpKey` 与
1368
+ * `mcpDispose`,状态仍指着**已死**的旧句柄 —— 这正是「先注册后释放」要消灭的那个状态,
1369
+ * 从释放这一侧重新进来。仓内 `releaseOne`(`src/agent/hooks.ts`)用的是同一口径。
1247
1370
  */
1371
+ function releasePrevious(input) {
1372
+ if (input.previous === null) return;
1373
+ try {
1374
+ input.previous.release();
1375
+ } catch (error) {
1376
+ input.onReleaseError?.(error);
1377
+ }
1378
+ }
1379
+ //#endregion
1380
+ //#region src/agent/skills.ts
1381
+ const shadowHandles = /* @__PURE__ */ new WeakMap();
1382
+ const pendingDisposers = /* @__PURE__ */ new WeakMap();
1383
+ /** Installs model-hidden copies while preserving user invocation and full skill content. */
1248
1384
  async function applySkillShadow(input) {
1249
1385
  return await input.serial(async () => {
1250
- input.previous?.();
1251
- const applied = [];
1252
- const disposers = [];
1386
+ const scope = input.scopeOf ?? input.agent;
1253
1387
  const definitions = [];
1254
1388
  for (const name of input.hidden) {
1255
1389
  const definition = await input.skills.get(name, {
1256
- scope: input.agent,
1390
+ scope,
1257
1391
  cwd: input.cwd
1258
1392
  });
1259
1393
  if (definition === void 0) {
@@ -1265,42 +1399,112 @@ async function applySkillShadow(input) {
1265
1399
  definition
1266
1400
  });
1267
1401
  }
1268
- for (const { name, definition } of definitions) {
1269
- const invocation = readInvocation(definition);
1270
- disposers.push(input.scoped.register({
1271
- ...definition,
1272
- invocation: {
1273
- ...invocation,
1274
- modelInvocable: false,
1275
- userInvocable: invocation?.["userInvocable"] !== false
1402
+ const scopePending = pendingOf(scope);
1403
+ if (scopePending !== void 0 && scopePending.length > 0) setPending(scope, releaseAll(scopePending, input.logger));
1404
+ const previousHandle = input.previous === void 0 ? void 0 : shadowHandles.get(input.previous);
1405
+ if (previousHandle !== void 0) previousHandle.disposers = releaseAll(previousHandle.disposers, input.logger);
1406
+ else input.previous?.();
1407
+ const unresolvedNames = new Set([...pendingOf(scope) ?? [], ...previousHandle?.disposers ?? []].map(({ name }) => name));
1408
+ const disposers = [];
1409
+ const applied = [];
1410
+ try {
1411
+ for (const item of definitions) {
1412
+ if (unresolvedNames.has(item.name)) {
1413
+ input.logger.warn(`dsh-skill-scope: 暂不注册 skill「${item.name}」:同名注册尚未释放`);
1414
+ continue;
1415
+ }
1416
+ disposers.push({
1417
+ name: item.name,
1418
+ dispose: registerShadow(input.scoped, item, scope)
1419
+ });
1420
+ applied.push(item.name);
1421
+ }
1422
+ } catch (error) {
1423
+ const failedDisposers = releaseAll(disposers, input.logger);
1424
+ if (previousHandle !== void 0) {
1425
+ previousHandle.disposers.push(...failedDisposers);
1426
+ for (const { name } of failedDisposers) unresolvedNames.add(name);
1427
+ for (const item of previousHandle.definitions) {
1428
+ if (unresolvedNames.has(item.name)) {
1429
+ input.logger.warn(`dsh-skill-scope: 暂不恢复 skill「${item.name}」:同名部分注册尚未释放`);
1430
+ continue;
1431
+ }
1432
+ try {
1433
+ previousHandle.disposers.push({
1434
+ name: item.name,
1435
+ dispose: registerShadow(input.scoped, item, scope)
1436
+ });
1437
+ } catch (restoreError) {
1438
+ input.logger.warn(`dsh-skill-scope: 恢复 skill「${item.name}」失败:${String(restoreError)}`);
1439
+ }
1276
1440
  }
1277
- }, input.agent));
1278
- applied.push(name);
1441
+ } else setPending(scope, [...pendingOf(scope) ?? [], ...failedDisposers]);
1442
+ throw error;
1279
1443
  }
1280
- if (input.verifyStillVisible === true) {
1444
+ if (previousHandle !== void 0 && previousHandle.disposers.length > 0) {
1445
+ setPending(scope, [...pendingOf(scope) ?? [], ...previousHandle.disposers]);
1446
+ previousHandle.disposers = [];
1447
+ }
1448
+ const handle = {
1449
+ definitions,
1450
+ disposers
1451
+ };
1452
+ const release = () => {
1453
+ const failed = releaseAll(handle.disposers, input.logger);
1454
+ handle.disposers = [];
1455
+ if (failed.length > 0) setPending(scope, [...pendingOf(scope) ?? [], ...failed]);
1456
+ };
1457
+ shadowHandles.set(release, handle);
1458
+ if (input.verifyStillVisible === true) try {
1281
1459
  const snapshot = await input.skills.snapshot({
1282
- scope: input.scopeOf ?? input.agent,
1460
+ scope,
1283
1461
  cwd: input.cwd
1284
1462
  });
1285
- const hiddenSet = new Set(input.hidden);
1286
- const exposed = snapshot.skills.filter((row) => hiddenSet.has(row.name) && row.invocation?.["modelInvocable"] !== false).map((row) => row.name);
1463
+ const hidden = new Set(input.hidden);
1464
+ const exposed = snapshot.skills.filter((row) => hidden.has(row.name) && row.invocation?.["modelInvocable"] !== false).map((row) => row.name);
1287
1465
  if (exposed.length > 0) input.logger.warn(`dsh-skill-scope: 以下 skill 遮蔽未生效(疑似被同层先到先得顶掉,已保留其余 ${applied.length} 项):${exposed.join(", ")}`);
1466
+ } catch (error) {
1467
+ input.logger.warn(`dsh-skill-scope: skill shadow 复验失败:${String(error)}`);
1288
1468
  }
1289
1469
  return {
1290
- release: () => releaseAll(disposers),
1470
+ release,
1291
1471
  applied
1292
1472
  };
1293
1473
  });
1294
1474
  }
1295
- /** 读出定义里的 `invocation` 对象;形状不对时返回 `undefined`(按缺省语义处理)。 */
1475
+ function pendingOf(scope) {
1476
+ return scope !== null && (typeof scope === "object" || typeof scope === "function") ? pendingDisposers.get(scope) : void 0;
1477
+ }
1478
+ function setPending(scope, disposers) {
1479
+ if (scope === null || typeof scope !== "object" && typeof scope !== "function") return;
1480
+ if (disposers.length === 0) pendingDisposers.delete(scope);
1481
+ else pendingDisposers.set(scope, disposers);
1482
+ }
1483
+ function registerShadow(scoped, item, scope) {
1484
+ const invocation = readInvocation(item.definition);
1485
+ return scoped.register({
1486
+ ...item.definition,
1487
+ invocation: {
1488
+ ...invocation,
1489
+ modelInvocable: false,
1490
+ userInvocable: invocation?.["userInvocable"] !== false
1491
+ }
1492
+ }, scope);
1493
+ }
1296
1494
  function readInvocation(definition) {
1297
1495
  const raw = definition["invocation"];
1298
1496
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
1299
1497
  return raw;
1300
1498
  }
1301
- /** 逐个释放;重复调用无害(释放函数自身的幂等性由 `dsh-skill` 保证)。 */
1302
- function releaseAll(disposers) {
1303
- for (const dispose of disposers) dispose();
1499
+ function releaseAll(disposers, logger) {
1500
+ const failed = [];
1501
+ for (const disposer of disposers) try {
1502
+ disposer.dispose();
1503
+ } catch (error) {
1504
+ failed.push(disposer);
1505
+ logger.warn(`dsh-skill-scope: 释放 skill shadow 失败:${String(error)}`);
1506
+ }
1507
+ return failed;
1304
1508
  }
1305
1509
  //#endregion
1306
1510
  //#region src/agent/hooks.ts
@@ -1357,12 +1561,13 @@ async function evaluate(deps, agent) {
1357
1561
  */
1358
1562
  async function computeHidden(deps, agent, effective) {
1359
1563
  const cwd = cwdOf(agent);
1360
- const inventory = await readAgentSkills(deps.skills, agent, cwd ?? "", { showOfficialSkills: true });
1564
+ const scope = agent.raw ?? agent;
1565
+ const inventory = await readAgentSkills(deps.skills, scope, cwd ?? "", { showOfficialSkills: true });
1361
1566
  if (inventory.complete !== true) {
1362
1567
  deps.logger.warn(`dsh-skill-scope: skill 清单不完整(incomplete),本轮不改变收窄状态(agent=${agent.id})`);
1363
1568
  return null;
1364
1569
  }
1365
- const toolNames = deps.tools.schemas(agent).map((schema) => schema.name);
1570
+ const toolNames = [...deps.tools.view(scope).restrictableNames];
1366
1571
  const knownServers = new Set(await deps.loaderServers());
1367
1572
  return {
1368
1573
  hidden: hiddenNames({
@@ -1395,26 +1600,35 @@ function serverNameOrTool(toolName, knownServers) {
1395
1600
  * 两件事都经 `serial` 串行,避免同一 Agent 的两个触发源交叉注册;
1396
1601
  * shadow 的成功名单只在 `applied` 非空时替换 `skillDispose`(`null` 释放器表示「本轮没有任何遮蔽」)。
1397
1602
  */
1398
- async function applyRound(deps, state, hidden, toolNames, knownServers) {
1603
+ async function applyRound(deps, state, hidden, toolNames, knownServers, isActive = () => true) {
1399
1604
  const cwd = cwdOf(state.agent) ?? "";
1605
+ const scope = state.agent.raw ?? state.agent;
1400
1606
  const chain = serial();
1401
1607
  const skillKey = hidden.skills.join(",");
1402
1608
  if (skillKey !== state.skillKey) {
1403
- state.skillDispose = (await applySkillShadow({
1609
+ const result = await applySkillShadow({
1404
1610
  skills: deps.skills,
1405
- scoped: deps.scoped,
1611
+ scoped: { register: (definition, agent) => isActive() ? deps.scoped.register(definition, agent) : () => {} },
1406
1612
  cwd,
1407
1613
  agent: state.agent,
1408
1614
  hidden: hidden.skills,
1409
1615
  serial: chain,
1410
1616
  logger: deps.logger,
1411
1617
  verifyStillVisible: true,
1412
- scopeOf: state.agent.raw ?? state.agent,
1618
+ scopeOf: scope,
1413
1619
  ...state.skillDispose === null ? {} : { previous: state.skillDispose }
1414
- })).release;
1620
+ });
1621
+ if (!isActive()) {
1622
+ releaseOne(deps, "skill shadow", result.release);
1623
+ state.skillKey = "";
1624
+ state.skillDispose = null;
1625
+ return;
1626
+ }
1627
+ state.skillDispose = result.release;
1415
1628
  state.skillKey = skillKey;
1416
1629
  }
1417
- const restrictable = deps.tools.view(state.agent).restrictableNames;
1630
+ if (!isActive()) return;
1631
+ const restrictable = deps.tools.view(scope).restrictableNames;
1418
1632
  const deny = denyFor(toolNames, restrictable, hidden.mcps, knownServers);
1419
1633
  const mcpKey = `${hidden.mcps.join(",")}|deny=${deny.join(",")}`;
1420
1634
  if (mcpKey !== state.mcpKey) {
@@ -1423,8 +1637,17 @@ async function applyRound(deps, state, hidden, toolNames, knownServers) {
1423
1637
  deny,
1424
1638
  key: mcpKey,
1425
1639
  previous: mcpRestrictionOf(state),
1426
- agent: state.agent
1640
+ agent: scope,
1641
+ onReleaseError: (error) => {
1642
+ deps.logger.warn(`dsh-skill-scope: 撤销 mcp restriction 失败:${String(error)}`);
1643
+ }
1427
1644
  }));
1645
+ if (!isActive()) {
1646
+ releaseOne(deps, "mcp restriction", next?.release ?? null);
1647
+ state.mcpKey = "";
1648
+ state.mcpDispose = null;
1649
+ return;
1650
+ }
1428
1651
  state.mcpKey = mcpKey;
1429
1652
  state.mcpDispose = next === null ? null : next.release;
1430
1653
  }
@@ -1488,26 +1711,80 @@ function installAgentHooks(ctx, deps) {
1488
1711
  chains.set(agentId, chain);
1489
1712
  return chain;
1490
1713
  };
1491
- /**
1492
- * 本插件自己正在落地时置位;用来掐断**自反馈环**(见 `onChange` 的长注释)。
1493
- *
1494
- * 用计数而不是布尔:`regroundAndApply` 可能被嵌套触发(落地期间又收到一个
1495
- * 真正的外部 `skills/change`),计数能让最外层退出时才复位。
1496
- *
1497
- * **必须声明在 `onCreated` 之前**:`onCreated` 与 `onChange` 都要读写它,
1498
- * 而 `let` 在声明前是暂时性死区(TDZ),声明放后面会在首次 `agent/created`
1499
- * 抛 `Cannot access 'applying' before initialization`。
1500
- */
1501
- let applying = 0;
1502
- /** 一次完整的「重读策略 → 重算隐藏集 → 重新落地」,被两个触发源共用。 */
1503
- const regroundAndApply = async (state) => {
1504
- const effective = await evaluate(deps, state.agent);
1505
- reground(state, effective);
1506
- const computed = await computeHidden(deps, state.agent, effective);
1507
- if (computed === null) return;
1508
- await applyRound(deps, state, computed.hidden, computed.toolNames, computed.knownServers);
1714
+ let stopped = false;
1715
+ const applyStates = /* @__PURE__ */ new Map();
1716
+ const applyStateFor = (agentId) => {
1717
+ const existing = applyStates.get(agentId);
1718
+ if (existing !== void 0) return existing;
1719
+ const created = {
1720
+ applying: false,
1721
+ pending: false,
1722
+ disposed: false,
1723
+ inFlight: null
1724
+ };
1725
+ applyStates.set(agentId, created);
1726
+ return created;
1727
+ };
1728
+ const drainAgent = async (state, schedule, source) => {
1729
+ if (schedule.disposed || schedule.applying || stopped) return;
1730
+ schedule.applying = true;
1731
+ const isActive = () => !stopped && !schedule.disposed;
1732
+ let retriedIncomplete = false;
1733
+ try {
1734
+ do {
1735
+ schedule.pending = false;
1736
+ try {
1737
+ await chainFor(state.agent.id)(async () => {
1738
+ const effective = await evaluate(deps, state.agent);
1739
+ if (!isActive()) return;
1740
+ const computed = await computeHidden(deps, state.agent, effective);
1741
+ if (!isActive()) return;
1742
+ if (computed === null) {
1743
+ if (!retriedIncomplete) {
1744
+ retriedIncomplete = true;
1745
+ schedule.pending = true;
1746
+ }
1747
+ return;
1748
+ }
1749
+ reground(state, effective);
1750
+ const previousSkillKey = state.skillKey;
1751
+ const previousMcpKey = state.mcpKey;
1752
+ await applyRound(deps, state, computed.hidden, computed.toolNames, computed.knownServers, isActive);
1753
+ if (previousSkillKey !== state.skillKey || previousMcpKey !== state.mcpKey) schedule.pending = true;
1754
+ });
1755
+ } catch (error) {
1756
+ ctx.logger.warn(`dsh-skill-scope: ${source} 落地失败(agent=${state.agent.id}):${String(error)}`);
1757
+ }
1758
+ } while (schedule.pending && isActive());
1759
+ } finally {
1760
+ schedule.applying = false;
1761
+ }
1762
+ };
1763
+ const requestAgentApply = (state, source) => {
1764
+ const applyState = applyStateFor(state.agent.id);
1765
+ if (stopped || applyState.disposed) return Promise.resolve();
1766
+ applyState.pending = true;
1767
+ const running = applyState.inFlight;
1768
+ if (running !== null) return running;
1769
+ let settle = () => {};
1770
+ const flight = new Promise((resolve) => {
1771
+ settle = resolve;
1772
+ });
1773
+ applyState.inFlight = flight;
1774
+ (async () => {
1775
+ try {
1776
+ do
1777
+ await drainAgent(state, applyState, source);
1778
+ while (applyState.pending && !stopped && !applyState.disposed);
1779
+ } finally {
1780
+ applyState.inFlight = null;
1781
+ settle();
1782
+ }
1783
+ })();
1784
+ return flight;
1509
1785
  };
1510
1786
  const onCreated = async (payload) => {
1787
+ if (stopped) return;
1511
1788
  const agent = asAgentLike(payload?.agent);
1512
1789
  if (agent === null) {
1513
1790
  ctx.logger.warn("dsh-skill-scope: agent/created 负载形状不符,跳过落地");
@@ -1518,98 +1795,28 @@ function installAgentHooks(ctx, deps) {
1518
1795
  return;
1519
1796
  }
1520
1797
  const state = deps.states.ensure(agent);
1521
- applying += 1;
1522
- try {
1523
- await chainFor(agent.id)(async () => {
1524
- await regroundAndApply(state);
1525
- });
1526
- } catch (error) {
1527
- ctx.logger.warn(`dsh-skill-scope: agent/created 落地失败,本会话按空策略运行:${String(error)}`);
1528
- } finally {
1529
- applying -= 1;
1530
- }
1798
+ await requestAgentApply(state, "agent/created");
1531
1799
  };
1532
1800
  const onDisposed = (value) => {
1533
- const agent = asAgentLike(value);
1801
+ const agent = asAgentLike((typeof value === "object" && value !== null ? value : null)?.agent ?? value);
1534
1802
  if (agent === null) return;
1803
+ const applyState = applyStates.get(agent.id);
1804
+ if (applyState !== void 0) {
1805
+ applyState.disposed = true;
1806
+ applyState.pending = false;
1807
+ }
1535
1808
  const state = deps.states.get(agent.id);
1536
1809
  if (state === void 0) return;
1537
1810
  releaseState(deps, state);
1538
1811
  deps.states.delete(agent.id);
1539
1812
  chains.delete(agent.id);
1813
+ applyStates.delete(agent.id);
1540
1814
  };
1541
- /**
1542
- * 清单变化:对该会话重新求值并差分重算;只处理已有状态的 Agent。
1543
- *
1544
- * ## 为什么必须掐断自反馈环
1545
- *
1546
- * 本插件**监听** `skills/change`,同时它的遮蔽落地又**发出** `skills/change`:
1547
- *
1548
- * ```
1549
- * onChange → regroundAndApply → applyRound → applySkillShadow
1550
- * → scoped.register() src/agent/skills.ts:88
1551
- * → dsh-skill/lib/index.js:209 this.layers.effect(this.ctx, …, { label: "skills.register()" })
1552
- * → dsh-scope/lib/index.js:189 effect(ctx, action, options)
1553
- * → :191 const notify = options.notify ?? true ← dsh-skill 没传,默认开
1554
- * → :216 if (notify) this.onChange()
1555
- * → SkillRegistry 构造时传入的失效回调 dsh-skill/lib/index.js:123
1556
- * → invalidateCache() → notifyChange() → 派发 "skills/change"
1557
- * → 回到本监听器
1558
- * ```
1559
- *
1560
- * 实测(probe1 / 3092,一次会话创建):`onChange` 触发 **243** 次、
1561
- * `shadow` 注册 127 次、`onCreated` 耗时 **3576 ms**。其中 `applyRound` 只有
1562
- * **1** 次 `keyChanged=true`,其余 138 次都因 key 未变而空转——说明这一串爆发
1563
- * 全是环造成的,不是真的有清单变化。
1564
- *
1565
- * ## 环造成的两个用户可见症状
1566
- *
1567
- * 1. **新建会话卡顿**:`agent/created` 是 serial 派发,回调里跑完 127 次注册
1568
- * (每次注册同步触发一次 `skills/change` 并重入)要 3.5 秒以上。
1569
- * 2. **第一条消息的 skill 目录整个消失**:`collect()`(`dsh-skill/lib/index.js:266-296`)
1570
- * 先记 `const revision = this.revision`,`await collectFresh()` 之后再比对;
1571
- * 不一致就重试,`MAX_COLLECT_ATTEMPTS = 2`(同文件 `:19`)用尽仍不一致时
1572
- * 返回 `cacheable: false` ⇒ `snapshot.complete = false`。而宿主
1573
- * `dsh-tool-skill/lib/index.js:944` 对不完整快照的处理是
1574
- * `if (!snapshot.complete) return decision;` —— **整块目录不注入**(全有或全无)。
1575
- * 注册风暴期间 revision 被本插件自己反复 +1,于是第一条消息恰好落在窗口内时,
1576
- * 模型拿到的就是「一个 skill 都没有」。
1577
- *
1578
- * 可控复现(8 秒窗口内每 5ms 快照一次):
1579
- * 两轮分别得到 `incomplete=39/648` 与 `incomplete=76/80`。
1580
- *
1581
- * ## 修法
1582
- *
1583
- * 只做**重入守卫**,不改任何策略语义:本插件自己触发的落地不重入。
1584
- * *不*去改 `dsh-skill` 的 `register()` 传 `notify: false`——那是上游包的硬编码
1585
- * (`register` 只传 `{ label }`,没暴露 `notify`),不该由本插件越界修改。
1586
- *
1587
- * 守卫必须覆盖**整个** `regroundAndApply`:`applySkillShadow` 内部逐条
1588
- * `register`,环是在**每条注册**上闭合的,只在函数首尾开关挡不住中间的注册。
1589
- *
1590
- * 注意不能因此丢事件:真正的外部 `skills/change`(provider 上下线、文件增删)
1591
- * 若在落地期间到达,会被这一层丢弃。这是**有意的取舍**——落地本身结尾会重读
1592
- * 清单并差分(`applyRound` 按 key 比较),所以落地结束时状态已是最新;
1593
- * 而放行它只会再触发一轮同环。
1594
- */
1595
1815
  const onChange = async () => {
1596
- if (applying > 0) return;
1597
- applying += 1;
1598
- try {
1599
- for (const agentId of deps.states.ids()) {
1600
- const state = deps.states.get(agentId);
1601
- if (state === void 0) continue;
1602
- try {
1603
- await chainFor(agentId)(async () => {
1604
- await regroundAndApply(state);
1605
- });
1606
- } catch (error) {
1607
- ctx.logger.warn(`dsh-skill-scope: 清单变化后重新落地失败(agent=${agentId}):${String(error)}`);
1608
- }
1609
- }
1610
- } finally {
1611
- applying -= 1;
1612
- }
1816
+ await Promise.all(deps.states.ids().flatMap((agentId) => {
1817
+ const state = deps.states.get(agentId);
1818
+ return state === void 0 ? [] : [requestAgentApply(state, "清单变化后重新")];
1819
+ }));
1613
1820
  };
1614
1821
  const offCreated = ctx.on("agent/created", onCreated);
1615
1822
  const offDisposed = ctx.on("agent/disposed", onDisposed);
@@ -1626,6 +1833,12 @@ function installAgentHooks(ctx, deps) {
1626
1833
  * 每个退订各自 try/catch:一个失败不影响其余,也不影响 `chains.clear()`。
1627
1834
  */
1628
1835
  const stopAll = () => {
1836
+ if (stopped) return;
1837
+ stopped = true;
1838
+ for (const schedule of applyStates.values()) {
1839
+ schedule.disposed = true;
1840
+ schedule.pending = false;
1841
+ }
1629
1842
  for (const off of [
1630
1843
  offCreated,
1631
1844
  offDisposed,
@@ -1639,8 +1852,10 @@ function installAgentHooks(ctx, deps) {
1639
1852
  for (const agentId of deps.states.ids()) {
1640
1853
  const state = deps.states.get(agentId);
1641
1854
  if (state !== void 0) releaseState(deps, state);
1855
+ deps.states.delete(agentId);
1642
1856
  }
1643
1857
  chains.clear();
1858
+ applyStates.clear();
1644
1859
  };
1645
1860
  ctx.effect(() => stopAll);
1646
1861
  return {
@@ -1726,7 +1941,8 @@ function releaseObservation(ctx, observation, sessionId) {
1726
1941
  * 把一个 `sessionId` 解析成传输层视图(设计 6.3)。
1727
1942
  *
1728
1943
  * 顺序固定为「先问宿主拿到 cwd 与 preset,再优先取 live Agent」:
1729
- * 1. `sessionQuery.observeSession(sessionId, { projectionMode: 'none' })` —— 只读快照,不要投影推送。
1944
+ * 1. `sessionQuery.observeSession(sessionId, { projectionMode: 'all' })` —— 读取 preset;
1945
+ * 投影观察失败时回退 `none`,保留 cwd,preset 为 null。
1730
1946
  * 2. `agents.get(sessionId)` —— 拿到就说明该会话是活跃的,它的清单才是实时清单。
1731
1947
  *
1732
1948
  * **observation 必须在 `finally` 里 `dispose()`**:宿主会为每次观察保留订阅,
@@ -1744,7 +1960,13 @@ async function resolveSession(ctx, sessionId) {
1744
1960
  if (observe !== null) {
1745
1961
  let observation;
1746
1962
  try {
1747
- observation = await observe.call(sessionQuery, sessionId, { projectionMode: "none" });
1963
+ try {
1964
+ observation = await observe.call(sessionQuery, sessionId, { projectionMode: "all" });
1965
+ } catch (error) {
1966
+ if (readString(asRecord(error), "code") === "SESSION_QUERY_SESSION_NOT_FOUND") throw error;
1967
+ ctx.logger.warn(`dsh-skill-scope: 读取会话投影失败,回退无投影观察(sessionId=${sessionId}):${String(error)}`);
1968
+ observation = await observe.call(sessionQuery, sessionId, { projectionMode: "none" });
1969
+ }
1748
1970
  } catch (error) {
1749
1971
  ctx.logger.warn(`dsh-skill-scope: 观察会话失败(sessionId=${sessionId}):${String(error)}`);
1750
1972
  observation = void 0;
@@ -2216,7 +2438,7 @@ function wrap(handler) {
2216
2438
  };
2217
2439
  }
2218
2440
  /**
2219
- * 注册四条精确路由,返回一个**同步** disposer 释放它们全部。
2441
+ * 注册四条精确路由,返回一个**幂等的异步** disposer 释放它们全部。
2220
2442
  *
2221
2443
  * 每条路径只声明 `POST`:宿主的匹配是 `route.methods.has(request.method)`,
2222
2444
  * 不匹配时根本不进我们的 `fetch`,而是落到共享通道兜底并返回 `404 not found`
@@ -2226,7 +2448,7 @@ function wrap(handler) {
2226
2448
  function registerRoutes(ctx, deps, fetchRegister) {
2227
2449
  if (fetchRegister === void 0 || fetchRegister === null) {
2228
2450
  ctx.logger.warn("dsh-skill-scope: 未提供 fetch 注册面,路由未注册");
2229
- return () => {};
2451
+ return async () => {};
2230
2452
  }
2231
2453
  const disposers = [];
2232
2454
  const specs = [
@@ -2248,29 +2470,31 @@ function registerRoutes(ctx, deps, fetchRegister) {
2248
2470
  }
2249
2471
  ];
2250
2472
  for (const { path, handler } of specs) try {
2251
- disposers.push(fetchRegister.register({
2473
+ disposers.push({
2252
2474
  path,
2253
- methods: ["POST"],
2254
- requestBody: "buffered",
2255
- fetch: wrap(async (body) => await handler(body, deps))
2256
- }));
2475
+ dispose: fetchRegister.register({
2476
+ path,
2477
+ methods: ["POST"],
2478
+ requestBody: "buffered",
2479
+ fetch: wrap(async (body) => await handler(body, deps))
2480
+ })
2481
+ });
2257
2482
  } catch (error) {
2258
2483
  ctx.logger.warn(`dsh-skill-scope: 注册路由失败(${path}):${String(error)}`);
2259
2484
  }
2260
- /** 释放一条路由;失败只 warn(成功路径与抛错路径的文案相同,故合成一处)。 */
2261
- const releaseOne = (dispose) => {
2262
- const fail = (error) => {
2263
- ctx.logger.warn(`dsh-skill-scope: 释放路由失败:${String(error)}`);
2264
- };
2265
- try {
2266
- const result = dispose();
2267
- if (result !== null && typeof result === "object" && "catch" in result) result.catch(fail);
2268
- } catch (error) {
2269
- fail(error);
2270
- }
2271
- };
2485
+ let cleanup = null;
2272
2486
  return () => {
2273
- for (const dispose of disposers) releaseOne(dispose);
2487
+ if (cleanup !== null) return cleanup;
2488
+ cleanup = (async () => {
2489
+ await Promise.all(disposers.map(async ({ path, dispose }) => {
2490
+ try {
2491
+ await dispose();
2492
+ } catch (error) {
2493
+ ctx.logger.warn(`dsh-skill-scope: 释放路由失败(${path}):${String(error)}`);
2494
+ }
2495
+ }));
2496
+ })();
2497
+ return cleanup;
2274
2498
  };
2275
2499
  }
2276
2500
  //#endregion
@@ -2440,20 +2664,28 @@ function assemble(ctx, deps = {}) {
2440
2664
  ctx,
2441
2665
  reapplyAfterSave
2442
2666
  };
2443
- let disposeRoutes = () => {};
2667
+ let disposeRoutes = async () => {};
2444
2668
  ctx.inject(["connection"], () => {
2445
2669
  const fetchRegister = readFetchRegister(ctx);
2446
2670
  if (fetchRegister === null) {
2447
2671
  ctx.logger.warn(`dsh-skill-scope: connection 服务在册但没有 fetch.register,路由未注册(策略仍生效)`);
2448
- return;
2672
+ return () => {};
2449
2673
  }
2450
- disposeRoutes = registerRoutes(ctx, routeDeps, fetchRegister);
2674
+ const release = registerRoutes(ctx, routeDeps, fetchRegister);
2675
+ let released = false;
2676
+ const dispose = async () => {
2677
+ if (released) return;
2678
+ released = true;
2679
+ await release();
2680
+ };
2681
+ disposeRoutes = dispose;
2682
+ return dispose;
2451
2683
  });
2452
2684
  return {
2453
2685
  store,
2454
2686
  states,
2455
2687
  disposeHooks: disposeHooks.stopAll,
2456
- disposeRoutes,
2688
+ disposeRoutes: () => disposeRoutes(),
2457
2689
  reapplyAfterSave
2458
2690
  };
2459
2691
  }