@dotdance/dsh-skill-scope 0.3.1 → 0.4.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.
package/lib/index.js CHANGED
@@ -209,9 +209,7 @@ const WORKSPACE_KEY = "workspace";
209
209
  /** 旧格式的行键。读到它即视为「未迁移的黑名单」。 */
210
210
  const LEGACY_KEY = "default";
211
211
  const sortKeys = (map) => {
212
- const out = {};
213
- for (const name of Object.keys(map).sort()) out[name] = map[name];
214
- return out;
212
+ return Object.fromEntries(Object.keys(map).sort().map((name) => [name, map[name]]));
215
213
  };
216
214
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
217
215
  /**
@@ -225,7 +223,7 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
225
223
  * `MAX_NAMES` 上限仍然保留:只为防止文件被写成无界清单,正常用量远低于它。
226
224
  */
227
225
  function parseDomain(raw, label) {
228
- const map = {};
226
+ const map = Object.create(null);
229
227
  const warnings = [];
230
228
  if (raw === void 0) return {
231
229
  map,
@@ -259,7 +257,7 @@ function parseDomain(raw, label) {
259
257
  }
260
258
  /** 旧格式:`default.skills` 是黑名单数组,每一项的含义都是「关」。 */
261
259
  function parseLegacyDomain(raw, label) {
262
- const map = {};
260
+ const map = Object.create(null);
263
261
  const warnings = [];
264
262
  if (raw === void 0) return {
265
263
  map,
@@ -358,7 +356,7 @@ function filterAgainstGlobal(policy, global) {
358
356
  mcps: new Set(global.mcps)
359
357
  };
360
358
  const pick = (map, domain) => {
361
- const out = {};
359
+ const out = Object.create(null);
362
360
  for (const [name, value] of Object.entries(map)) if (value !== !denied[domain].has(name)) out[name] = value;
363
361
  return out;
364
362
  };
@@ -378,10 +376,10 @@ function filterAgainstGlobal(policy, global) {
378
376
  * (`store.ts` 的 `revision` 靠它做乐观锁)。
379
377
  */
380
378
  function serializeWorkspacePolicy(policy, previousText, global) {
381
- const base = {};
379
+ let base = {};
382
380
  if (previousText !== void 0 && previousText.trim() !== "") try {
383
381
  const parsed = JSON.parse(previousText);
384
- if (isPlainObject(parsed)) Object.assign(base, parsed);
382
+ if (isPlainObject(parsed)) base = { ...parsed };
385
383
  } catch {}
386
384
  delete base[LEGACY_KEY];
387
385
  const filtered = filterAgainstGlobal(policy, global);
@@ -601,8 +599,8 @@ var PolicyStore = class {
601
599
  async saveWorkspace(cwd, policy, expected) {
602
600
  const path = workspacePolicyPath(cwd);
603
601
  return await this.write(path, expected, async (current) => {
604
- const global = await this.loadGlobal();
605
- return serializeWorkspacePolicy(policy, current ?? void 0, global.policy);
602
+ const global = parseGlobalPolicy(await this.readTransactionText(globalPolicyPath()) ?? void 0).policy;
603
+ return serializeWorkspacePolicy(policy, current ?? void 0, global);
606
604
  });
607
605
  }
608
606
  /** 读全文;文件不存在返回 `null`。读侧无锁,见类注释。 */
@@ -615,6 +613,15 @@ var PolicyStore = class {
615
613
  return null;
616
614
  }
617
615
  }
616
+ /** 写事务只能把 ENOENT 当作不存在;探测失败不能成为覆盖旧文件的依据。 */
617
+ async readTransactionText(path) {
618
+ try {
619
+ return await this.fs.readFile(path);
620
+ } catch (error) {
621
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return null;
622
+ throw error;
623
+ }
624
+ }
618
625
  /**
619
626
  * 一次完整的写事务:入队列 → 进文件锁 → 读现状 → revision 守卫 → 序列化 → 原子写。
620
627
  * `serialize` 拿到锁内读到的旧全文(工作区层用它保住未知顶层键)。
@@ -628,7 +635,7 @@ var PolicyStore = class {
628
635
  try {
629
636
  await ensureParentDir(path);
630
637
  return await this.lock(path, async () => {
631
- const current = await this.readText(path);
638
+ const current = await this.readTransactionText(path);
632
639
  const currentRevision = current === null ? null : sha256Hex(current);
633
640
  if (guard) {
634
641
  if (expected === null || expected === void 0) {
@@ -726,7 +733,8 @@ const deniedOf = (global, domain) => domain === "skills" ? global.skills : globa
726
733
  * 建一个「某域名字 → 是否启用」的判定函数(设计 4.1)。
727
734
  *
728
735
  * 规则只有一条:**工作区有决定就用决定,没有就跟随全局**。
729
- * `false` 是有效值,所以只能写 `??`,不能用 `||`(`false || 默认` 会吞掉「明令关」)。
736
+ * 只有自有键才是决定,不能把 constructor 等继承属性当成状态。
737
+ * `false` 是有效值,所以回退用 `??`,不能用 `||`(`false || 默认` 会吞掉「明令关」)。
730
738
  *
731
739
  * 返回函数而不是单次判定:调用方(`hiddenNames`、工作区视图)都是按域遍历,
732
740
  * 每次调用都重建 Set 会让 512 项的清单退化成 O(n²)。全局名单里同一个名字
@@ -735,7 +743,7 @@ const deniedOf = (global, domain) => domain === "skills" ? global.skills : globa
735
743
  function openResolver(effective, domain) {
736
744
  const denied = new Set(deniedOf(effective.global, domain));
737
745
  const local = effective.workspace?.[domain];
738
- return (name) => local?.[name] ?? !denied.has(name);
746
+ return (name) => (local !== void 0 && Object.hasOwn(local, name) ? local[name] : void 0) ?? !denied.has(name);
739
747
  }
740
748
  /**
741
749
  * 计算一个会话**被关掉**的名字(设计 4.1)。
@@ -777,7 +785,8 @@ function hiddenNames(inventories, effective) {
777
785
  * 改为**最长前缀匹配**:这是设计 4.3 的要求。它的必要性在于 server 名允许下划线
778
786
  * (`MCP_NAME_RE` 的 `[A-Za-z0-9_-]`),所以 `mcp__` 之后「第一个 `__`」并不必然是
779
787
  * 边界——`server_na__me` 这种名字会让非贪婪正则切错。有已知集合时不需要猜:
780
- * 逐个比对哪个已知名真的是该工具名的前缀,取**最长**的那个。
788
+ * 从工具名末尾向前检查每个 `__` 边界,用已知集合查找候选名,首个命中就是最长前缀。
789
+ * 检查次数取决于工具名中的分隔符数量,不随已知服务器数量增加。
781
790
  *
782
791
  * 没有已知集合(或集合里没有命中项)时退化为非贪婪启发式,即设计 4.3 说的
783
792
  * 「只有遇到未知 server 时才退化」。退化是**有损**的,所以调用方应当把这种情形
@@ -785,13 +794,9 @@ function hiddenNames(inventories, effective) {
785
794
  */
786
795
  function serverNameOf(toolName, knownServers) {
787
796
  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;
797
+ if (knownServers !== void 0) for (let boundary = toolName.lastIndexOf("__"); boundary >= MCP_PREFIX.length; boundary = toolName.lastIndexOf("__", boundary - 1)) {
798
+ const server = toolName.slice(MCP_PREFIX.length, boundary);
799
+ if (knownServers.has(server)) return server;
795
800
  }
796
801
  const server = HEURISTIC_SERVER.exec(toolName)?.[1];
797
802
  if (server === void 0 || server.length > 32) return null;
@@ -815,8 +820,9 @@ const HEURISTIC_SERVER = new RegExp(`^${MCP_PREFIX}([A-Za-z0-9_-]{1,32}?)__(.+)$
815
820
  */
816
821
  function classifyMcp(input) {
817
822
  const toolNamesByServer = /* @__PURE__ */ new Map();
823
+ const knownServers = new Set(input.loaderServers);
818
824
  for (const toolName of [...input.scopeToolNames, ...input.ownToolNames ?? []]) {
819
- const serverName = serverNameOf(toolName);
825
+ const serverName = serverNameOf(toolName, knownServers);
820
826
  if (serverName === null) continue;
821
827
  const bucket = toolNamesByServer.get(serverName) ?? /* @__PURE__ */ new Set();
822
828
  bucket.add(toolName);
@@ -939,28 +945,48 @@ function isOfficialSkillPath(path) {
939
945
  return path.includes(OFFICIAL_SCOPE);
940
946
  }
941
947
  /**
942
- * 已确认的官方 provider:**官方包自己注册、不经磁盘 provider,因此没有 `path` 可判**。
948
+ * 已确认的官方 provider:**官方包自己注册、且既没有 `path`、资源根也不在作用域内**,
949
+ * 前两条按磁盘出处的信号都盖不住,只能按名字认。名单外的 provider 一律按第三方处理,
950
+ * 面板照常展示(判不出不加任何标记)。
943
951
  *
944
- * 目前只有 `dsh-office`(`@deepseek-ai/dsh-skill-office` 注册 7 条 `office-*`,实测
945
- * `provider='dsh-office'`、`source='bundled'`、`path` 缺失)。这是**白名单**:名单外的
946
- * provider 一律按第三方处理,面板照常展示。
952
+ * 三条(2026-10-30 实测 0.2.2-alpha.2):`dsh-office`(桌面版把 `office-skills/` 放在
953
+ * app 资源目录,资源根不含作用域名)、`dsh-official-plugins`、`dsh-personalized-pages`
954
+ * (后两者 candidate 只有 `locator: null`)。
947
955
  *
948
956
  * `runtime` **不在**名单内:`browser-skill`、`memory-recall` 这类宿主内置能力必须留在
949
957
  * 面板上,用户要能单独关掉它们(见 `tests/routes/handlers.spec.ts` 的「活清单项」用例)。
950
958
  */
951
- const OFFICIAL_PROVIDERS = /* @__PURE__ */ new Set(["dsh-office"]);
959
+ const OFFICIAL_PROVIDERS = /* @__PURE__ */ new Set([
960
+ "dsh-office",
961
+ "dsh-official-plugins",
962
+ "dsh-personalized-pages"
963
+ ]);
964
+ /**
965
+ * 这一行的**资源根**是否落在官方作用域内。
966
+ *
967
+ * 有些官方 provider 只给 `resourceBase`(资源目录)、不给 `path`:`dsh-badge` 就是
968
+ * (`dsh-skill-badge/lib/index.js:10-39`,资源根恒在包目录内)。宿主 `toSummary` 会把
969
+ * `resourceBase` 透出(`dsh-skill/lib/index.js:490-502`),所以不必改 host。
970
+ */
971
+ function isOfficialResourceBase(resourceBase) {
972
+ const path = resourceBase?.path;
973
+ if (path === void 0) return false;
974
+ return path.includes(OFFICIAL_SCOPE);
975
+ }
952
976
  /**
953
977
  * 这一行是否属于官方 `@deepseek-ai` skill(⇒ 面板不展示)。**清单过滤只调这一个。**
954
978
  *
955
979
  * 判定顺序(任一命中即官方):
956
- * 1. `path` 任意位置含 `@deepseek-ai`(既有规则,覆盖有磁盘出处的官方包);
957
- * 2. `provider` 在 `OFFICIAL_PROVIDERS` 白名单里(覆盖没有 `path` 的官方 provider)。
980
+ * 1. `path` 任意位置含 `@deepseek-ai`(覆盖有磁盘出处的官方包);
981
+ * 2. `resourceBase.path` 含 `@deepseek-ai`(覆盖只给资源根的官方 provider);
982
+ * 3. `provider` 在 `OFFICIAL_PROVIDERS` 白名单里(覆盖两条磁盘信号都没有的)。
958
983
  *
959
- * 两条都判不出时返回 `false`:**不能因为「判不出」就把它藏起来**,否则用户会失去
960
- * 自己技能/第三方插件技能的开关入口。
984
+ * 三条都判不出时返回 `false`:**不能因为「判不出」就把它藏起来**,否则用户会失去
985
+ * 自己技能/第三方插件技能的开关入口;判不出的行就按第三方展示,不加任何标记。
961
986
  */
962
987
  function isOfficialSkill(entry) {
963
988
  if (isOfficialSkillPath(entry.path)) return true;
989
+ if (isOfficialResourceBase(entry.resourceBase)) return true;
964
990
  return entry.provider !== void 0 && OFFICIAL_PROVIDERS.has(entry.provider);
965
991
  }
966
992
  //#endregion
@@ -1023,9 +1049,9 @@ async function readAgentSkills(skills, agent, cwd, options) {
1023
1049
  * 滤掉官方 `@deepseek-ai` skill。
1024
1050
  *
1025
1051
  * 两个读函数都走这一行,所以全局层与工作区层**口径必然一致**——不会出现
1026
- * 「全局视图藏了、工作区视图还在」这类分歧。判定与取舍见 `./official.ts`
1027
- * (路径含 `@deepseek-ai`,或 provider 在官方白名单里——后者覆盖没有 `path` 的
1028
- * `dsh-office` 那 7 条)。
1052
+ * 「全局视图藏了、工作区视图还在」这类分歧。判定与取舍见 `./official.ts`:
1053
+ * 路径或资源根含 `@deepseek-ai`,或 provider 在官方白名单里(覆盖既不给路径也不给
1054
+ * 资源根的 `dsh-office` / `dsh-official-plugins` / `dsh-personalized-pages`)。
1029
1055
  *
1030
1056
  * **显示开关与掩蔽集是两件事,别合并**:面板用 `showOfficialSkills` 决定「列不列」,
1031
1057
  * 而 `src/agent/hooks.ts` 的掩蔽集合**永远**用全量清单(`showOfficialSkills: true`)。
@@ -1226,34 +1252,16 @@ async function applyMcpRestriction(input) {
1226
1252
  }
1227
1253
  //#endregion
1228
1254
  //#region src/agent/skills.ts
1229
- /**
1230
- * 把一批 skill 关成「只对用户可见」(设计 5.2)。
1231
- *
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
- * 但每次调用仍先释放上一轮:同名不同定义的替换必须靠「先撤后注册」才生效。
1247
- */
1255
+ const shadowHandles = /* @__PURE__ */ new WeakMap();
1256
+ const pendingDisposers = /* @__PURE__ */ new WeakMap();
1257
+ /** Installs model-hidden copies while preserving user invocation and full skill content. */
1248
1258
  async function applySkillShadow(input) {
1249
1259
  return await input.serial(async () => {
1250
- input.previous?.();
1251
- const applied = [];
1252
- const disposers = [];
1260
+ const scope = input.scopeOf ?? input.agent;
1253
1261
  const definitions = [];
1254
1262
  for (const name of input.hidden) {
1255
1263
  const definition = await input.skills.get(name, {
1256
- scope: input.agent,
1264
+ scope,
1257
1265
  cwd: input.cwd
1258
1266
  });
1259
1267
  if (definition === void 0) {
@@ -1265,42 +1273,112 @@ async function applySkillShadow(input) {
1265
1273
  definition
1266
1274
  });
1267
1275
  }
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
1276
+ const scopePending = pendingOf(scope);
1277
+ if (scopePending !== void 0 && scopePending.length > 0) setPending(scope, releaseAll(scopePending, input.logger));
1278
+ const previousHandle = input.previous === void 0 ? void 0 : shadowHandles.get(input.previous);
1279
+ if (previousHandle !== void 0) previousHandle.disposers = releaseAll(previousHandle.disposers, input.logger);
1280
+ else input.previous?.();
1281
+ const unresolvedNames = new Set([...pendingOf(scope) ?? [], ...previousHandle?.disposers ?? []].map(({ name }) => name));
1282
+ const disposers = [];
1283
+ const applied = [];
1284
+ try {
1285
+ for (const item of definitions) {
1286
+ if (unresolvedNames.has(item.name)) {
1287
+ input.logger.warn(`dsh-skill-scope: 暂不注册 skill「${item.name}」:同名注册尚未释放`);
1288
+ continue;
1276
1289
  }
1277
- }, input.agent));
1278
- applied.push(name);
1290
+ disposers.push({
1291
+ name: item.name,
1292
+ dispose: registerShadow(input.scoped, item, scope)
1293
+ });
1294
+ applied.push(item.name);
1295
+ }
1296
+ } catch (error) {
1297
+ const failedDisposers = releaseAll(disposers, input.logger);
1298
+ if (previousHandle !== void 0) {
1299
+ previousHandle.disposers.push(...failedDisposers);
1300
+ for (const { name } of failedDisposers) unresolvedNames.add(name);
1301
+ for (const item of previousHandle.definitions) {
1302
+ if (unresolvedNames.has(item.name)) {
1303
+ input.logger.warn(`dsh-skill-scope: 暂不恢复 skill「${item.name}」:同名部分注册尚未释放`);
1304
+ continue;
1305
+ }
1306
+ try {
1307
+ previousHandle.disposers.push({
1308
+ name: item.name,
1309
+ dispose: registerShadow(input.scoped, item, scope)
1310
+ });
1311
+ } catch (restoreError) {
1312
+ input.logger.warn(`dsh-skill-scope: 恢复 skill「${item.name}」失败:${String(restoreError)}`);
1313
+ }
1314
+ }
1315
+ } else setPending(scope, [...pendingOf(scope) ?? [], ...failedDisposers]);
1316
+ throw error;
1279
1317
  }
1280
- if (input.verifyStillVisible === true) {
1318
+ if (previousHandle !== void 0 && previousHandle.disposers.length > 0) {
1319
+ setPending(scope, [...pendingOf(scope) ?? [], ...previousHandle.disposers]);
1320
+ previousHandle.disposers = [];
1321
+ }
1322
+ const handle = {
1323
+ definitions,
1324
+ disposers
1325
+ };
1326
+ const release = () => {
1327
+ const failed = releaseAll(handle.disposers, input.logger);
1328
+ handle.disposers = [];
1329
+ if (failed.length > 0) setPending(scope, [...pendingOf(scope) ?? [], ...failed]);
1330
+ };
1331
+ shadowHandles.set(release, handle);
1332
+ if (input.verifyStillVisible === true) try {
1281
1333
  const snapshot = await input.skills.snapshot({
1282
- scope: input.scopeOf ?? input.agent,
1334
+ scope,
1283
1335
  cwd: input.cwd
1284
1336
  });
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);
1337
+ const hidden = new Set(input.hidden);
1338
+ const exposed = snapshot.skills.filter((row) => hidden.has(row.name) && row.invocation?.["modelInvocable"] !== false).map((row) => row.name);
1287
1339
  if (exposed.length > 0) input.logger.warn(`dsh-skill-scope: 以下 skill 遮蔽未生效(疑似被同层先到先得顶掉,已保留其余 ${applied.length} 项):${exposed.join(", ")}`);
1340
+ } catch (error) {
1341
+ input.logger.warn(`dsh-skill-scope: skill shadow 复验失败:${String(error)}`);
1288
1342
  }
1289
1343
  return {
1290
- release: () => releaseAll(disposers),
1344
+ release,
1291
1345
  applied
1292
1346
  };
1293
1347
  });
1294
1348
  }
1295
- /** 读出定义里的 `invocation` 对象;形状不对时返回 `undefined`(按缺省语义处理)。 */
1349
+ function pendingOf(scope) {
1350
+ return scope !== null && (typeof scope === "object" || typeof scope === "function") ? pendingDisposers.get(scope) : void 0;
1351
+ }
1352
+ function setPending(scope, disposers) {
1353
+ if (scope === null || typeof scope !== "object" && typeof scope !== "function") return;
1354
+ if (disposers.length === 0) pendingDisposers.delete(scope);
1355
+ else pendingDisposers.set(scope, disposers);
1356
+ }
1357
+ function registerShadow(scoped, item, scope) {
1358
+ const invocation = readInvocation(item.definition);
1359
+ return scoped.register({
1360
+ ...item.definition,
1361
+ invocation: {
1362
+ ...invocation,
1363
+ modelInvocable: false,
1364
+ userInvocable: invocation?.["userInvocable"] !== false
1365
+ }
1366
+ }, scope);
1367
+ }
1296
1368
  function readInvocation(definition) {
1297
1369
  const raw = definition["invocation"];
1298
1370
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
1299
1371
  return raw;
1300
1372
  }
1301
- /** 逐个释放;重复调用无害(释放函数自身的幂等性由 `dsh-skill` 保证)。 */
1302
- function releaseAll(disposers) {
1303
- for (const dispose of disposers) dispose();
1373
+ function releaseAll(disposers, logger) {
1374
+ const failed = [];
1375
+ for (const disposer of disposers) try {
1376
+ disposer.dispose();
1377
+ } catch (error) {
1378
+ failed.push(disposer);
1379
+ logger.warn(`dsh-skill-scope: 释放 skill shadow 失败:${String(error)}`);
1380
+ }
1381
+ return failed;
1304
1382
  }
1305
1383
  //#endregion
1306
1384
  //#region src/agent/hooks.ts
@@ -1357,12 +1435,13 @@ async function evaluate(deps, agent) {
1357
1435
  */
1358
1436
  async function computeHidden(deps, agent, effective) {
1359
1437
  const cwd = cwdOf(agent);
1360
- const inventory = await readAgentSkills(deps.skills, agent, cwd ?? "", { showOfficialSkills: true });
1438
+ const scope = agent.raw ?? agent;
1439
+ const inventory = await readAgentSkills(deps.skills, scope, cwd ?? "", { showOfficialSkills: true });
1361
1440
  if (inventory.complete !== true) {
1362
1441
  deps.logger.warn(`dsh-skill-scope: skill 清单不完整(incomplete),本轮不改变收窄状态(agent=${agent.id})`);
1363
1442
  return null;
1364
1443
  }
1365
- const toolNames = deps.tools.schemas(agent).map((schema) => schema.name);
1444
+ const toolNames = [...deps.tools.view(scope).restrictableNames];
1366
1445
  const knownServers = new Set(await deps.loaderServers());
1367
1446
  return {
1368
1447
  hidden: hiddenNames({
@@ -1395,26 +1474,33 @@ function serverNameOrTool(toolName, knownServers) {
1395
1474
  * 两件事都经 `serial` 串行,避免同一 Agent 的两个触发源交叉注册;
1396
1475
  * shadow 的成功名单只在 `applied` 非空时替换 `skillDispose`(`null` 释放器表示「本轮没有任何遮蔽」)。
1397
1476
  */
1398
- async function applyRound(deps, state, hidden, toolNames, knownServers) {
1477
+ async function applyRound(deps, state, hidden, toolNames, knownServers, isActive = () => true) {
1399
1478
  const cwd = cwdOf(state.agent) ?? "";
1479
+ const scope = state.agent.raw ?? state.agent;
1400
1480
  const chain = serial();
1401
1481
  const skillKey = hidden.skills.join(",");
1402
1482
  if (skillKey !== state.skillKey) {
1403
- state.skillDispose = (await applySkillShadow({
1483
+ const result = await applySkillShadow({
1404
1484
  skills: deps.skills,
1405
- scoped: deps.scoped,
1485
+ scoped: { register: (definition, agent) => isActive() ? deps.scoped.register(definition, agent) : () => {} },
1406
1486
  cwd,
1407
1487
  agent: state.agent,
1408
1488
  hidden: hidden.skills,
1409
1489
  serial: chain,
1410
1490
  logger: deps.logger,
1411
1491
  verifyStillVisible: true,
1412
- scopeOf: state.agent.raw ?? state.agent,
1492
+ scopeOf: scope,
1413
1493
  ...state.skillDispose === null ? {} : { previous: state.skillDispose }
1414
- })).release;
1494
+ });
1495
+ if (!isActive()) {
1496
+ releaseOne(deps, "skill shadow", result.release);
1497
+ return;
1498
+ }
1499
+ state.skillDispose = result.release;
1415
1500
  state.skillKey = skillKey;
1416
1501
  }
1417
- const restrictable = deps.tools.view(state.agent).restrictableNames;
1502
+ if (!isActive()) return;
1503
+ const restrictable = deps.tools.view(scope).restrictableNames;
1418
1504
  const deny = denyFor(toolNames, restrictable, hidden.mcps, knownServers);
1419
1505
  const mcpKey = `${hidden.mcps.join(",")}|deny=${deny.join(",")}`;
1420
1506
  if (mcpKey !== state.mcpKey) {
@@ -1423,8 +1509,12 @@ async function applyRound(deps, state, hidden, toolNames, knownServers) {
1423
1509
  deny,
1424
1510
  key: mcpKey,
1425
1511
  previous: mcpRestrictionOf(state),
1426
- agent: state.agent
1512
+ agent: scope
1427
1513
  }));
1514
+ if (!isActive()) {
1515
+ releaseOne(deps, "mcp restriction", next?.release ?? null);
1516
+ return;
1517
+ }
1428
1518
  state.mcpKey = mcpKey;
1429
1519
  state.mcpDispose = next === null ? null : next.release;
1430
1520
  }
@@ -1488,26 +1578,62 @@ function installAgentHooks(ctx, deps) {
1488
1578
  chains.set(agentId, chain);
1489
1579
  return chain;
1490
1580
  };
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);
1581
+ let stopped = false;
1582
+ const applyStates = /* @__PURE__ */ new Map();
1583
+ const applyStateFor = (agentId) => {
1584
+ const existing = applyStates.get(agentId);
1585
+ if (existing !== void 0) return existing;
1586
+ const created = {
1587
+ applying: false,
1588
+ pending: false,
1589
+ disposed: false
1590
+ };
1591
+ applyStates.set(agentId, created);
1592
+ return created;
1593
+ };
1594
+ const drainAgent = async (state, schedule, source) => {
1595
+ if (schedule.disposed || schedule.applying || stopped) return;
1596
+ schedule.applying = true;
1597
+ const isActive = () => !stopped && !schedule.disposed;
1598
+ let retriedIncomplete = false;
1599
+ try {
1600
+ do {
1601
+ schedule.pending = false;
1602
+ try {
1603
+ await chainFor(state.agent.id)(async () => {
1604
+ const effective = await evaluate(deps, state.agent);
1605
+ if (!isActive()) return;
1606
+ const computed = await computeHidden(deps, state.agent, effective);
1607
+ if (!isActive()) return;
1608
+ if (computed === null) {
1609
+ if (!retriedIncomplete) {
1610
+ retriedIncomplete = true;
1611
+ schedule.pending = true;
1612
+ }
1613
+ return;
1614
+ }
1615
+ reground(state, effective);
1616
+ const previousSkillKey = state.skillKey;
1617
+ const previousMcpKey = state.mcpKey;
1618
+ await applyRound(deps, state, computed.hidden, computed.toolNames, computed.knownServers, isActive);
1619
+ if (previousSkillKey !== state.skillKey || previousMcpKey !== state.mcpKey) schedule.pending = true;
1620
+ });
1621
+ } catch (error) {
1622
+ ctx.logger.warn(`dsh-skill-scope: ${source} 落地失败(agent=${state.agent.id}):${String(error)}`);
1623
+ }
1624
+ } while (schedule.pending && isActive());
1625
+ } finally {
1626
+ schedule.applying = false;
1627
+ }
1628
+ };
1629
+ const requestAgentApply = (state, source) => {
1630
+ const applyState = applyStateFor(state.agent.id);
1631
+ if (stopped || applyState.disposed) return Promise.resolve();
1632
+ applyState.pending = true;
1633
+ return applyState.applying ? Promise.resolve() : drainAgent(state, applyState, source);
1509
1634
  };
1510
1635
  const onCreated = async (payload) => {
1636
+ if (stopped) return;
1511
1637
  const agent = asAgentLike(payload?.agent);
1512
1638
  if (agent === null) {
1513
1639
  ctx.logger.warn("dsh-skill-scope: agent/created 负载形状不符,跳过落地");
@@ -1518,98 +1644,28 @@ function installAgentHooks(ctx, deps) {
1518
1644
  return;
1519
1645
  }
1520
1646
  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
- }
1647
+ requestAgentApply(state, "agent/created");
1531
1648
  };
1532
1649
  const onDisposed = (value) => {
1533
1650
  const agent = asAgentLike(value);
1534
1651
  if (agent === null) return;
1652
+ const applyState = applyStates.get(agent.id);
1653
+ if (applyState !== void 0) {
1654
+ applyState.disposed = true;
1655
+ applyState.pending = false;
1656
+ }
1535
1657
  const state = deps.states.get(agent.id);
1536
1658
  if (state === void 0) return;
1537
1659
  releaseState(deps, state);
1538
1660
  deps.states.delete(agent.id);
1539
1661
  chains.delete(agent.id);
1662
+ applyStates.delete(agent.id);
1540
1663
  };
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
1664
  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
- }
1665
+ await Promise.all(deps.states.ids().flatMap((agentId) => {
1666
+ const state = deps.states.get(agentId);
1667
+ return state === void 0 ? [] : [requestAgentApply(state, "清单变化后重新")];
1668
+ }));
1613
1669
  };
1614
1670
  const offCreated = ctx.on("agent/created", onCreated);
1615
1671
  const offDisposed = ctx.on("agent/disposed", onDisposed);
@@ -1626,6 +1682,12 @@ function installAgentHooks(ctx, deps) {
1626
1682
  * 每个退订各自 try/catch:一个失败不影响其余,也不影响 `chains.clear()`。
1627
1683
  */
1628
1684
  const stopAll = () => {
1685
+ if (stopped) return;
1686
+ stopped = true;
1687
+ for (const schedule of applyStates.values()) {
1688
+ schedule.disposed = true;
1689
+ schedule.pending = false;
1690
+ }
1629
1691
  for (const off of [
1630
1692
  offCreated,
1631
1693
  offDisposed,
@@ -1639,8 +1701,10 @@ function installAgentHooks(ctx, deps) {
1639
1701
  for (const agentId of deps.states.ids()) {
1640
1702
  const state = deps.states.get(agentId);
1641
1703
  if (state !== void 0) releaseState(deps, state);
1704
+ deps.states.delete(agentId);
1642
1705
  }
1643
1706
  chains.clear();
1707
+ applyStates.clear();
1644
1708
  };
1645
1709
  ctx.effect(() => stopAll);
1646
1710
  return {
@@ -1726,7 +1790,8 @@ function releaseObservation(ctx, observation, sessionId) {
1726
1790
  * 把一个 `sessionId` 解析成传输层视图(设计 6.3)。
1727
1791
  *
1728
1792
  * 顺序固定为「先问宿主拿到 cwd 与 preset,再优先取 live Agent」:
1729
- * 1. `sessionQuery.observeSession(sessionId, { projectionMode: 'none' })` —— 只读快照,不要投影推送。
1793
+ * 1. `sessionQuery.observeSession(sessionId, { projectionMode: 'all' })` —— 读取 preset;
1794
+ * 投影观察失败时回退 `none`,保留 cwd,preset 为 null。
1730
1795
  * 2. `agents.get(sessionId)` —— 拿到就说明该会话是活跃的,它的清单才是实时清单。
1731
1796
  *
1732
1797
  * **observation 必须在 `finally` 里 `dispose()`**:宿主会为每次观察保留订阅,
@@ -1744,7 +1809,13 @@ async function resolveSession(ctx, sessionId) {
1744
1809
  if (observe !== null) {
1745
1810
  let observation;
1746
1811
  try {
1747
- observation = await observe.call(sessionQuery, sessionId, { projectionMode: "none" });
1812
+ try {
1813
+ observation = await observe.call(sessionQuery, sessionId, { projectionMode: "all" });
1814
+ } catch (error) {
1815
+ if (readString(asRecord(error), "code") === "SESSION_QUERY_SESSION_NOT_FOUND") throw error;
1816
+ ctx.logger.warn(`dsh-skill-scope: 读取会话投影失败,回退无投影观察(sessionId=${sessionId}):${String(error)}`);
1817
+ observation = await observe.call(sessionQuery, sessionId, { projectionMode: "none" });
1818
+ }
1748
1819
  } catch (error) {
1749
1820
  ctx.logger.warn(`dsh-skill-scope: 观察会话失败(sessionId=${sessionId}):${String(error)}`);
1750
1821
  observation = void 0;
@@ -2216,7 +2287,7 @@ function wrap(handler) {
2216
2287
  };
2217
2288
  }
2218
2289
  /**
2219
- * 注册四条精确路由,返回一个**同步** disposer 释放它们全部。
2290
+ * 注册四条精确路由,返回一个**幂等的异步** disposer 释放它们全部。
2220
2291
  *
2221
2292
  * 每条路径只声明 `POST`:宿主的匹配是 `route.methods.has(request.method)`,
2222
2293
  * 不匹配时根本不进我们的 `fetch`,而是落到共享通道兜底并返回 `404 not found`
@@ -2226,7 +2297,7 @@ function wrap(handler) {
2226
2297
  function registerRoutes(ctx, deps, fetchRegister) {
2227
2298
  if (fetchRegister === void 0 || fetchRegister === null) {
2228
2299
  ctx.logger.warn("dsh-skill-scope: 未提供 fetch 注册面,路由未注册");
2229
- return () => {};
2300
+ return async () => {};
2230
2301
  }
2231
2302
  const disposers = [];
2232
2303
  const specs = [
@@ -2248,29 +2319,31 @@ function registerRoutes(ctx, deps, fetchRegister) {
2248
2319
  }
2249
2320
  ];
2250
2321
  for (const { path, handler } of specs) try {
2251
- disposers.push(fetchRegister.register({
2322
+ disposers.push({
2252
2323
  path,
2253
- methods: ["POST"],
2254
- requestBody: "buffered",
2255
- fetch: wrap(async (body) => await handler(body, deps))
2256
- }));
2324
+ dispose: fetchRegister.register({
2325
+ path,
2326
+ methods: ["POST"],
2327
+ requestBody: "buffered",
2328
+ fetch: wrap(async (body) => await handler(body, deps))
2329
+ })
2330
+ });
2257
2331
  } catch (error) {
2258
2332
  ctx.logger.warn(`dsh-skill-scope: 注册路由失败(${path}):${String(error)}`);
2259
2333
  }
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
- };
2334
+ let cleanup = null;
2272
2335
  return () => {
2273
- for (const dispose of disposers) releaseOne(dispose);
2336
+ if (cleanup !== null) return cleanup;
2337
+ cleanup = (async () => {
2338
+ await Promise.all(disposers.map(async ({ path, dispose }) => {
2339
+ try {
2340
+ await dispose();
2341
+ } catch (error) {
2342
+ ctx.logger.warn(`dsh-skill-scope: 释放路由失败(${path}):${String(error)}`);
2343
+ }
2344
+ }));
2345
+ })();
2346
+ return cleanup;
2274
2347
  };
2275
2348
  }
2276
2349
  //#endregion
@@ -2440,7 +2513,7 @@ function assemble(ctx, deps = {}) {
2440
2513
  ctx,
2441
2514
  reapplyAfterSave
2442
2515
  };
2443
- let disposeRoutes = () => {};
2516
+ let disposeRoutes = async () => {};
2444
2517
  ctx.inject(["connection"], () => {
2445
2518
  const fetchRegister = readFetchRegister(ctx);
2446
2519
  if (fetchRegister === null) {