@kafukatree/dsh-skill-manager 0.0.0-stage → 0.3.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.
Files changed (307) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-lucide.txt +43 -0
  3. package/README.md +44 -2
  4. package/agent-tool.mjs +118 -0
  5. package/client-bridge.mjs +307 -0
  6. package/client-entry.mjs +131 -0
  7. package/client.js +6769 -0
  8. package/control-icon.mjs +40 -0
  9. package/cordis.patch.yml +4 -0
  10. package/design/skill-manager.pen +798 -0
  11. package/design.css +320 -0
  12. package/design.mjs +629 -0
  13. package/dialogs.css +460 -0
  14. package/dialogs.mjs +1130 -0
  15. package/document-link.mjs +13 -0
  16. package/file-actions.mjs +62 -0
  17. package/file-view.mjs +384 -0
  18. package/header-scroll.css +90 -0
  19. package/header-scroll.mjs +121 -0
  20. package/host.mjs +460 -0
  21. package/icon.svg +6 -0
  22. package/import-archive.mjs +41 -0
  23. package/import-commit.mjs +247 -0
  24. package/import-family.mjs +213 -0
  25. package/import-files.mjs +186 -0
  26. package/import-github.mjs +168 -0
  27. package/import-limits.mjs +10 -0
  28. package/import-native.mjs +79 -0
  29. package/imports.mjs +209 -0
  30. package/inventory.mjs +62 -0
  31. package/library.mjs +1334 -0
  32. package/local-families.mjs +277 -0
  33. package/locale/en.json +16 -0
  34. package/locale/zh.json +16 -0
  35. package/management-view.mjs +158 -0
  36. package/mode-view.mjs +72 -0
  37. package/node_modules/pend/LICENSE +23 -0
  38. package/node_modules/pend/README.md +41 -0
  39. package/node_modules/pend/index.js +55 -0
  40. package/node_modules/pend/package.json +18 -0
  41. package/node_modules/pend/test.js +137 -0
  42. package/node_modules/yaml/LICENSE +13 -0
  43. package/node_modules/yaml/README.md +172 -0
  44. package/node_modules/yaml/bin.mjs +11 -0
  45. package/node_modules/yaml/browser/dist/compose/compose-collection.js +88 -0
  46. package/node_modules/yaml/browser/dist/compose/compose-doc.js +43 -0
  47. package/node_modules/yaml/browser/dist/compose/compose-node.js +109 -0
  48. package/node_modules/yaml/browser/dist/compose/compose-scalar.js +86 -0
  49. package/node_modules/yaml/browser/dist/compose/composer.js +219 -0
  50. package/node_modules/yaml/browser/dist/compose/resolve-block-map.js +115 -0
  51. package/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +198 -0
  52. package/node_modules/yaml/browser/dist/compose/resolve-block-seq.js +49 -0
  53. package/node_modules/yaml/browser/dist/compose/resolve-end.js +37 -0
  54. package/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +207 -0
  55. package/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +226 -0
  56. package/node_modules/yaml/browser/dist/compose/resolve-props.js +146 -0
  57. package/node_modules/yaml/browser/dist/compose/util-contains-newline.js +34 -0
  58. package/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +26 -0
  59. package/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +15 -0
  60. package/node_modules/yaml/browser/dist/compose/util-map-includes.js +13 -0
  61. package/node_modules/yaml/browser/dist/doc/Document.js +335 -0
  62. package/node_modules/yaml/browser/dist/doc/anchors.js +71 -0
  63. package/node_modules/yaml/browser/dist/doc/applyReviver.js +55 -0
  64. package/node_modules/yaml/browser/dist/doc/createNode.js +88 -0
  65. package/node_modules/yaml/browser/dist/doc/directives.js +176 -0
  66. package/node_modules/yaml/browser/dist/errors.js +57 -0
  67. package/node_modules/yaml/browser/dist/index.js +17 -0
  68. package/node_modules/yaml/browser/dist/log.js +11 -0
  69. package/node_modules/yaml/browser/dist/nodes/Alias.js +118 -0
  70. package/node_modules/yaml/browser/dist/nodes/Collection.js +147 -0
  71. package/node_modules/yaml/browser/dist/nodes/Node.js +38 -0
  72. package/node_modules/yaml/browser/dist/nodes/Pair.js +36 -0
  73. package/node_modules/yaml/browser/dist/nodes/Scalar.js +24 -0
  74. package/node_modules/yaml/browser/dist/nodes/YAMLMap.js +144 -0
  75. package/node_modules/yaml/browser/dist/nodes/YAMLSeq.js +113 -0
  76. package/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +63 -0
  77. package/node_modules/yaml/browser/dist/nodes/identity.js +36 -0
  78. package/node_modules/yaml/browser/dist/nodes/toJS.js +37 -0
  79. package/node_modules/yaml/browser/dist/parse/cst-scalar.js +214 -0
  80. package/node_modules/yaml/browser/dist/parse/cst-stringify.js +61 -0
  81. package/node_modules/yaml/browser/dist/parse/cst-visit.js +97 -0
  82. package/node_modules/yaml/browser/dist/parse/cst.js +98 -0
  83. package/node_modules/yaml/browser/dist/parse/lexer.js +721 -0
  84. package/node_modules/yaml/browser/dist/parse/line-counter.js +39 -0
  85. package/node_modules/yaml/browser/dist/parse/parser.js +975 -0
  86. package/node_modules/yaml/browser/dist/public-api.js +102 -0
  87. package/node_modules/yaml/browser/dist/schema/Schema.js +37 -0
  88. package/node_modules/yaml/browser/dist/schema/common/map.js +17 -0
  89. package/node_modules/yaml/browser/dist/schema/common/null.js +15 -0
  90. package/node_modules/yaml/browser/dist/schema/common/seq.js +17 -0
  91. package/node_modules/yaml/browser/dist/schema/common/string.js +14 -0
  92. package/node_modules/yaml/browser/dist/schema/core/bool.js +19 -0
  93. package/node_modules/yaml/browser/dist/schema/core/float.js +43 -0
  94. package/node_modules/yaml/browser/dist/schema/core/int.js +38 -0
  95. package/node_modules/yaml/browser/dist/schema/core/schema.js +23 -0
  96. package/node_modules/yaml/browser/dist/schema/json/schema.js +62 -0
  97. package/node_modules/yaml/browser/dist/schema/tags.js +96 -0
  98. package/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +58 -0
  99. package/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +26 -0
  100. package/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +46 -0
  101. package/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +71 -0
  102. package/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +67 -0
  103. package/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +74 -0
  104. package/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +78 -0
  105. package/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +39 -0
  106. package/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +93 -0
  107. package/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +101 -0
  108. package/node_modules/yaml/browser/dist/stringify/foldFlowLines.js +146 -0
  109. package/node_modules/yaml/browser/dist/stringify/stringify.js +129 -0
  110. package/node_modules/yaml/browser/dist/stringify/stringifyCollection.js +153 -0
  111. package/node_modules/yaml/browser/dist/stringify/stringifyComment.js +20 -0
  112. package/node_modules/yaml/browser/dist/stringify/stringifyDocument.js +85 -0
  113. package/node_modules/yaml/browser/dist/stringify/stringifyNumber.js +25 -0
  114. package/node_modules/yaml/browser/dist/stringify/stringifyPair.js +150 -0
  115. package/node_modules/yaml/browser/dist/stringify/stringifyString.js +336 -0
  116. package/node_modules/yaml/browser/dist/util.js +11 -0
  117. package/node_modules/yaml/browser/dist/visit.js +233 -0
  118. package/node_modules/yaml/browser/index.js +5 -0
  119. package/node_modules/yaml/browser/package.json +3 -0
  120. package/node_modules/yaml/dist/cli.d.ts +8 -0
  121. package/node_modules/yaml/dist/cli.mjs +201 -0
  122. package/node_modules/yaml/dist/compose/compose-collection.d.ts +11 -0
  123. package/node_modules/yaml/dist/compose/compose-collection.js +90 -0
  124. package/node_modules/yaml/dist/compose/compose-doc.d.ts +7 -0
  125. package/node_modules/yaml/dist/compose/compose-doc.js +45 -0
  126. package/node_modules/yaml/dist/compose/compose-node.d.ts +29 -0
  127. package/node_modules/yaml/dist/compose/compose-node.js +112 -0
  128. package/node_modules/yaml/dist/compose/compose-scalar.d.ts +5 -0
  129. package/node_modules/yaml/dist/compose/compose-scalar.js +88 -0
  130. package/node_modules/yaml/dist/compose/composer.d.ts +63 -0
  131. package/node_modules/yaml/dist/compose/composer.js +224 -0
  132. package/node_modules/yaml/dist/compose/resolve-block-map.d.ts +6 -0
  133. package/node_modules/yaml/dist/compose/resolve-block-map.js +117 -0
  134. package/node_modules/yaml/dist/compose/resolve-block-scalar.d.ts +11 -0
  135. package/node_modules/yaml/dist/compose/resolve-block-scalar.js +200 -0
  136. package/node_modules/yaml/dist/compose/resolve-block-seq.d.ts +6 -0
  137. package/node_modules/yaml/dist/compose/resolve-block-seq.js +51 -0
  138. package/node_modules/yaml/dist/compose/resolve-end.d.ts +6 -0
  139. package/node_modules/yaml/dist/compose/resolve-end.js +39 -0
  140. package/node_modules/yaml/dist/compose/resolve-flow-collection.d.ts +7 -0
  141. package/node_modules/yaml/dist/compose/resolve-flow-collection.js +209 -0
  142. package/node_modules/yaml/dist/compose/resolve-flow-scalar.d.ts +10 -0
  143. package/node_modules/yaml/dist/compose/resolve-flow-scalar.js +228 -0
  144. package/node_modules/yaml/dist/compose/resolve-props.d.ts +23 -0
  145. package/node_modules/yaml/dist/compose/resolve-props.js +148 -0
  146. package/node_modules/yaml/dist/compose/util-contains-newline.d.ts +2 -0
  147. package/node_modules/yaml/dist/compose/util-contains-newline.js +36 -0
  148. package/node_modules/yaml/dist/compose/util-empty-scalar-position.d.ts +2 -0
  149. package/node_modules/yaml/dist/compose/util-empty-scalar-position.js +28 -0
  150. package/node_modules/yaml/dist/compose/util-flow-indent-check.d.ts +3 -0
  151. package/node_modules/yaml/dist/compose/util-flow-indent-check.js +17 -0
  152. package/node_modules/yaml/dist/compose/util-map-includes.d.ts +4 -0
  153. package/node_modules/yaml/dist/compose/util-map-includes.js +15 -0
  154. package/node_modules/yaml/dist/doc/Document.d.ts +141 -0
  155. package/node_modules/yaml/dist/doc/Document.js +337 -0
  156. package/node_modules/yaml/dist/doc/anchors.d.ts +24 -0
  157. package/node_modules/yaml/dist/doc/anchors.js +76 -0
  158. package/node_modules/yaml/dist/doc/applyReviver.d.ts +9 -0
  159. package/node_modules/yaml/dist/doc/applyReviver.js +57 -0
  160. package/node_modules/yaml/dist/doc/createNode.d.ts +17 -0
  161. package/node_modules/yaml/dist/doc/createNode.js +90 -0
  162. package/node_modules/yaml/dist/doc/directives.d.ts +49 -0
  163. package/node_modules/yaml/dist/doc/directives.js +178 -0
  164. package/node_modules/yaml/dist/errors.d.ts +21 -0
  165. package/node_modules/yaml/dist/errors.js +62 -0
  166. package/node_modules/yaml/dist/index.d.ts +25 -0
  167. package/node_modules/yaml/dist/index.js +50 -0
  168. package/node_modules/yaml/dist/log.d.ts +3 -0
  169. package/node_modules/yaml/dist/log.js +19 -0
  170. package/node_modules/yaml/dist/nodes/Alias.d.ts +29 -0
  171. package/node_modules/yaml/dist/nodes/Alias.js +120 -0
  172. package/node_modules/yaml/dist/nodes/Collection.d.ts +73 -0
  173. package/node_modules/yaml/dist/nodes/Collection.js +151 -0
  174. package/node_modules/yaml/dist/nodes/Node.d.ts +53 -0
  175. package/node_modules/yaml/dist/nodes/Node.js +40 -0
  176. package/node_modules/yaml/dist/nodes/Pair.d.ts +22 -0
  177. package/node_modules/yaml/dist/nodes/Pair.js +39 -0
  178. package/node_modules/yaml/dist/nodes/Scalar.d.ts +47 -0
  179. package/node_modules/yaml/dist/nodes/Scalar.js +27 -0
  180. package/node_modules/yaml/dist/nodes/YAMLMap.d.ts +53 -0
  181. package/node_modules/yaml/dist/nodes/YAMLMap.js +147 -0
  182. package/node_modules/yaml/dist/nodes/YAMLSeq.d.ts +60 -0
  183. package/node_modules/yaml/dist/nodes/YAMLSeq.js +115 -0
  184. package/node_modules/yaml/dist/nodes/addPairToJSMap.d.ts +4 -0
  185. package/node_modules/yaml/dist/nodes/addPairToJSMap.js +65 -0
  186. package/node_modules/yaml/dist/nodes/identity.d.ts +23 -0
  187. package/node_modules/yaml/dist/nodes/identity.js +53 -0
  188. package/node_modules/yaml/dist/nodes/toJS.d.ts +29 -0
  189. package/node_modules/yaml/dist/nodes/toJS.js +39 -0
  190. package/node_modules/yaml/dist/options.d.ts +350 -0
  191. package/node_modules/yaml/dist/parse/cst-scalar.d.ts +64 -0
  192. package/node_modules/yaml/dist/parse/cst-scalar.js +218 -0
  193. package/node_modules/yaml/dist/parse/cst-stringify.d.ts +8 -0
  194. package/node_modules/yaml/dist/parse/cst-stringify.js +63 -0
  195. package/node_modules/yaml/dist/parse/cst-visit.d.ts +39 -0
  196. package/node_modules/yaml/dist/parse/cst-visit.js +99 -0
  197. package/node_modules/yaml/dist/parse/cst.d.ts +109 -0
  198. package/node_modules/yaml/dist/parse/cst.js +112 -0
  199. package/node_modules/yaml/dist/parse/lexer.d.ts +87 -0
  200. package/node_modules/yaml/dist/parse/lexer.js +723 -0
  201. package/node_modules/yaml/dist/parse/line-counter.d.ts +22 -0
  202. package/node_modules/yaml/dist/parse/line-counter.js +41 -0
  203. package/node_modules/yaml/dist/parse/parser.d.ts +84 -0
  204. package/node_modules/yaml/dist/parse/parser.js +980 -0
  205. package/node_modules/yaml/dist/public-api.d.ts +44 -0
  206. package/node_modules/yaml/dist/public-api.js +107 -0
  207. package/node_modules/yaml/dist/schema/Schema.d.ts +17 -0
  208. package/node_modules/yaml/dist/schema/Schema.js +39 -0
  209. package/node_modules/yaml/dist/schema/common/map.d.ts +2 -0
  210. package/node_modules/yaml/dist/schema/common/map.js +19 -0
  211. package/node_modules/yaml/dist/schema/common/null.d.ts +4 -0
  212. package/node_modules/yaml/dist/schema/common/null.js +17 -0
  213. package/node_modules/yaml/dist/schema/common/seq.d.ts +2 -0
  214. package/node_modules/yaml/dist/schema/common/seq.js +19 -0
  215. package/node_modules/yaml/dist/schema/common/string.d.ts +2 -0
  216. package/node_modules/yaml/dist/schema/common/string.js +16 -0
  217. package/node_modules/yaml/dist/schema/core/bool.d.ts +4 -0
  218. package/node_modules/yaml/dist/schema/core/bool.js +21 -0
  219. package/node_modules/yaml/dist/schema/core/float.d.ts +4 -0
  220. package/node_modules/yaml/dist/schema/core/float.js +47 -0
  221. package/node_modules/yaml/dist/schema/core/int.d.ts +4 -0
  222. package/node_modules/yaml/dist/schema/core/int.js +42 -0
  223. package/node_modules/yaml/dist/schema/core/schema.d.ts +1 -0
  224. package/node_modules/yaml/dist/schema/core/schema.js +25 -0
  225. package/node_modules/yaml/dist/schema/json/schema.d.ts +2 -0
  226. package/node_modules/yaml/dist/schema/json/schema.js +64 -0
  227. package/node_modules/yaml/dist/schema/json-schema.d.ts +69 -0
  228. package/node_modules/yaml/dist/schema/tags.d.ts +48 -0
  229. package/node_modules/yaml/dist/schema/tags.js +99 -0
  230. package/node_modules/yaml/dist/schema/types.d.ts +92 -0
  231. package/node_modules/yaml/dist/schema/yaml-1.1/binary.d.ts +2 -0
  232. package/node_modules/yaml/dist/schema/yaml-1.1/binary.js +70 -0
  233. package/node_modules/yaml/dist/schema/yaml-1.1/bool.d.ts +7 -0
  234. package/node_modules/yaml/dist/schema/yaml-1.1/bool.js +29 -0
  235. package/node_modules/yaml/dist/schema/yaml-1.1/float.d.ts +4 -0
  236. package/node_modules/yaml/dist/schema/yaml-1.1/float.js +50 -0
  237. package/node_modules/yaml/dist/schema/yaml-1.1/int.d.ts +5 -0
  238. package/node_modules/yaml/dist/schema/yaml-1.1/int.js +76 -0
  239. package/node_modules/yaml/dist/schema/yaml-1.1/merge.d.ts +9 -0
  240. package/node_modules/yaml/dist/schema/yaml-1.1/merge.js +71 -0
  241. package/node_modules/yaml/dist/schema/yaml-1.1/omap.d.ts +22 -0
  242. package/node_modules/yaml/dist/schema/yaml-1.1/omap.js +77 -0
  243. package/node_modules/yaml/dist/schema/yaml-1.1/pairs.d.ts +10 -0
  244. package/node_modules/yaml/dist/schema/yaml-1.1/pairs.js +82 -0
  245. package/node_modules/yaml/dist/schema/yaml-1.1/schema.d.ts +1 -0
  246. package/node_modules/yaml/dist/schema/yaml-1.1/schema.js +41 -0
  247. package/node_modules/yaml/dist/schema/yaml-1.1/set.d.ts +28 -0
  248. package/node_modules/yaml/dist/schema/yaml-1.1/set.js +96 -0
  249. package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.d.ts +6 -0
  250. package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +105 -0
  251. package/node_modules/yaml/dist/stringify/foldFlowLines.d.ts +34 -0
  252. package/node_modules/yaml/dist/stringify/foldFlowLines.js +151 -0
  253. package/node_modules/yaml/dist/stringify/stringify.d.ts +21 -0
  254. package/node_modules/yaml/dist/stringify/stringify.js +132 -0
  255. package/node_modules/yaml/dist/stringify/stringifyCollection.d.ts +17 -0
  256. package/node_modules/yaml/dist/stringify/stringifyCollection.js +155 -0
  257. package/node_modules/yaml/dist/stringify/stringifyComment.d.ts +10 -0
  258. package/node_modules/yaml/dist/stringify/stringifyComment.js +24 -0
  259. package/node_modules/yaml/dist/stringify/stringifyDocument.d.ts +4 -0
  260. package/node_modules/yaml/dist/stringify/stringifyDocument.js +87 -0
  261. package/node_modules/yaml/dist/stringify/stringifyNumber.d.ts +2 -0
  262. package/node_modules/yaml/dist/stringify/stringifyNumber.js +27 -0
  263. package/node_modules/yaml/dist/stringify/stringifyPair.d.ts +3 -0
  264. package/node_modules/yaml/dist/stringify/stringifyPair.js +152 -0
  265. package/node_modules/yaml/dist/stringify/stringifyString.d.ts +9 -0
  266. package/node_modules/yaml/dist/stringify/stringifyString.js +338 -0
  267. package/node_modules/yaml/dist/test-events.d.ts +4 -0
  268. package/node_modules/yaml/dist/test-events.js +134 -0
  269. package/node_modules/yaml/dist/util.d.ts +16 -0
  270. package/node_modules/yaml/dist/util.js +28 -0
  271. package/node_modules/yaml/dist/visit.d.ts +102 -0
  272. package/node_modules/yaml/dist/visit.js +236 -0
  273. package/node_modules/yaml/package.json +97 -0
  274. package/node_modules/yaml/util.js +2 -0
  275. package/node_modules/yauzl/LICENSE +21 -0
  276. package/node_modules/yauzl/README.md +1015 -0
  277. package/node_modules/yauzl/crc32.js +45 -0
  278. package/node_modules/yauzl/fd-slicer.js +188 -0
  279. package/node_modules/yauzl/index.js +1096 -0
  280. package/node_modules/yauzl/package.json +40 -0
  281. package/package-files.mjs +244 -0
  282. package/package-view.mjs +375 -0
  283. package/package.css +131 -0
  284. package/package.json +75 -4
  285. package/removal.mjs +313 -0
  286. package/scripts/build.mjs +19 -0
  287. package/scripts/export-design.py +587 -0
  288. package/scripts/run-tests.mjs +14 -0
  289. package/skill-state.mjs +136 -0
  290. package/skills/skill-creator/SKILL.md +48 -0
  291. package/styles.mjs +10 -0
  292. package/surfaces.css +593 -0
  293. package/test/agent-tool.test.mjs +153 -0
  294. package/test/client-bridge.test.mjs +240 -0
  295. package/test/distribution.test.mjs +17 -0
  296. package/test/host.test.mjs +598 -0
  297. package/test/imports.test.mjs +491 -0
  298. package/test/inventory.test.mjs +144 -0
  299. package/test/library.test.mjs +785 -0
  300. package/test/local-families.test.mjs +220 -0
  301. package/test/management-view.test.mjs +102 -0
  302. package/test/mode-view.test.mjs +26 -0
  303. package/test/package-files.test.mjs +221 -0
  304. package/toolbar.css +228 -0
  305. package/typography.css +173 -0
  306. package/ui.css +399 -0
  307. package/ui.mjs +1545 -0
package/library.mjs ADDED
@@ -0,0 +1,1334 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { constants, existsSync, realpathSync } from 'node:fs'
3
+ import { access, link, lstat, open, realpath, rename, stat, unlink } from 'node:fs/promises'
4
+ import { createRequire } from 'node:module'
5
+ import { homedir } from 'node:os'
6
+ import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { isDeepStrictEqual } from 'node:util'
9
+ import { withSkillWriteLock } from './import-commit.mjs'
10
+ import { problem } from './import-files.mjs'
11
+ import { FAMILY_MARKER, parseFamilyMarker } from './import-family.mjs'
12
+ import { listFamilies, getFamily } from './local-families.mjs'
13
+ import { inspectRemoval, listRemovedSkills, removeSkill, restoreSkill } from './removal.mjs'
14
+ import { findManagementPreset, isManagementSelection, mergeManagementViews, withManagementScope } from './management-view.mjs'
15
+
16
+ // The Desktop host doesn't export the shell tools' DSH_INSTALL_DIR. A CLI
17
+ // host can run from npm or a checkout. In both cases prefer the host's exact
18
+ // modules: dsh-scope's keys and Cordis plugin callbacks are instance-specific.
19
+ const localRequire = createRequire(import.meta.url)
20
+ const anchors = [
21
+ process.env.DSH_INSTALL_DIR && join(process.env.DSH_INSTALL_DIR, 'package.json'),
22
+ process.resourcesPath && join(process.resourcesPath, 'app.asar', 'dsh', 'package.json'),
23
+ ...Object.keys(localRequire.cache).filter(path => /[/\\]@deepseek-ai[/\\]dsh(?:-skill(?:-filesystem)?|-agent-preset-registry)?[/\\]/.test(path)),
24
+ process.argv[1],
25
+ ].filter(path => path && isAbsolute(path) && existsSync(path))
26
+ const hostResolvers = [...new Set(anchors.map(path => realpathSync(path)))].map(path => createRequire(path))
27
+
28
+ function hostModulePath(name) {
29
+ for (const from of [...hostResolvers, localRequire]) {
30
+ try { return from.resolve(name) } catch (error) {
31
+ if (error.code !== 'MODULE_NOT_FOUND' && error.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw error
32
+ }
33
+ }
34
+ }
35
+
36
+ export function hostRequire(name) {
37
+ const path = hostModulePath(name)
38
+ if (path) return localRequire(path)
39
+ throw new Error(`无法从运行中的 DeepSeek Harness 安装目录加载 ${name}。`)
40
+ }
41
+
42
+ const filesystem = hostRequire('@deepseek-ai/dsh-skill-filesystem')
43
+ const { FileSystemSkillProvider } = filesystem
44
+ const { scopeChainOf, scopeOf } = hostRequire('@deepseek-ai/dsh-scope')
45
+ const { canonicalizeWatchPath, expandHomePath, resolveAgentsHome, resolveDshHome } = hostRequire('@deepseek-ai/dsh-home-paths')
46
+ const z = hostRequire('@deepseek-ai/schemastery')
47
+ const yaml = hostRequire('yaml')
48
+
49
+ export const Config = z.object({
50
+ customDirectories: z.array(z.object({ path: z.string().min(1), label: z.string() })).default([]).volatile(),
51
+ })
52
+
53
+ const CUSTOM_PROVIDER = 'dsh-skill-manager-directories'
54
+ const CREATOR_PROVIDER = 'dsh-skill-manager'
55
+ const ACTIVE = 2 // Cordis FiberState.ACTIVE (a TypeScript const enum).
56
+ const FLAG = 'disable-model-invocation'
57
+ const noop = () => {}
58
+ const USER_SOURCES = new Set(['user-dsh', 'user-agents', 'project-dsh', 'project-agents'])
59
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
60
+ const coldPreset = Symbol('cold session preset')
61
+
62
+ export function coldSkillView(preset) { return { [coldPreset]: preset } }
63
+
64
+ export function registerCreatorSkill(ctx) {
65
+ ctx.skills.registerProvider(control => new FileSystemSkillProvider(ctx, control, {
66
+ providerName: CREATOR_PROVIDER, includeDefaultRoots: false, watch: false,
67
+ bundledSkillDir: fileURLToPath(new URL('./skills/', import.meta.url)),
68
+ }))
69
+ }
70
+
71
+ function shippedRoot(name, directory) {
72
+ const manifest = hostModulePath(`${name}/package.json`)
73
+ return manifest && join(dirname(realpathSync(manifest)), directory)
74
+ }
75
+
76
+ // Standard and Creator mount the first root as `custom`. Packaged providers
77
+ // (including third-party plugins) all use `bundled`, so that label alone is
78
+ // insufficient to identify Office or the official experimental badge bundle.
79
+ const presetSkills = shippedRoot('@deepseek-ai/dsh-agent-preset', 'skills')
80
+ const officeAssets = shippedRoot('@deepseek-ai/dsh-skill-office', 'assets')
81
+ const badgeBundle = '@deepseek-ai/dsh-experimental-badge-skill-bundle'
82
+ const officialCatalog = hostModulePath('@deepseek-ai/dsh-official-bundles')
83
+ const badgeAssets = officialCatalog && localRequire(officialCatalog).EXPERIMENTAL_BUNDLES?.has(badgeBundle)
84
+ && shippedRoot('@deepseek-ai/dsh-skill-badge', 'assets')
85
+ const cardRegistrations = [
86
+ ['@deepseek-ai/dsh-plugin-recommendations', 'dsh-official-plugins', 'official-plugins'],
87
+ ['@deepseek-ai/dsh-creation-recommendations', 'dsh-personalized-pages', 'personalized-pages'],
88
+ ]
89
+
90
+ function id(prefix, ...values) {
91
+ const digest = createHash('sha256').update(JSON.stringify(values)).digest('base64url')
92
+ return `${prefix}-${digest}`
93
+ }
94
+
95
+ function skillId(skill) {
96
+ const base = skill.resourceBase
97
+ return id('skill', skill.name, skill.provider, skill.source, skill.path, base?.kind,
98
+ base?.path ?? base?.url ?? base?.description)
99
+ }
100
+
101
+ function dirId(source, path) {
102
+ return id(`dir-${source}`, path)
103
+ }
104
+
105
+ function configured(config) {
106
+ const field = config?.customDirectories
107
+ return (typeof field?.get === 'function' ? field.get() : field) ?? []
108
+ }
109
+
110
+ function missing(error) {
111
+ return error?.code === 'ENOENT' || error?.code === 'ENOTDIR'
112
+ }
113
+
114
+ function relativeChild(parent, path) {
115
+ const part = relative(parent, path)
116
+ if (!part || part === '..' || part.startsWith(`..${sep}`) || isAbsolute(part)) return undefined
117
+ return part
118
+ }
119
+
120
+ function displayPath(path) {
121
+ const home = homedir()
122
+ if (path === home) return '~'
123
+ const part = relativeChild(home, path)
124
+ return part === undefined ? path : `~/${part.split(sep).join('/')}`
125
+ }
126
+
127
+ function activeFibers(ctx, pluginName) {
128
+ // Third-party entry loaders can evaluate a second copy of a module. Its
129
+ // exact Loader entry name identifies that copy as well.
130
+ return [...ctx.registry.values()].flatMap(runtime => [...runtime.fibers]).filter(fiber =>
131
+ fiber.state === ACTIVE && (fiber.entry?.options?.name === `@deepseek-ai/dsh-${pluginName}`
132
+ || (pluginName === filesystem.name ? fiber.runtime.callback === filesystem.apply : fiber.runtime.name === pluginName)))
133
+ }
134
+
135
+ // One companion per native filesystem layer. An unscoped provider alone
136
+ // would lose to a scoped personal skill regardless of the native custom rank.
137
+ function mountDirectories(ctx, config) {
138
+ const mounts = new Map()
139
+ const closing = new Set()
140
+ let disposed = false
141
+
142
+ function retire(provider) {
143
+ if (!provider) return
144
+ const ended = provider.dispose()
145
+ closing.add(ended)
146
+ void ended.then(() => closing.delete(ended), error => {
147
+ closing.delete(ended)
148
+ ctx.logger.warn(String(error))
149
+ })
150
+ }
151
+
152
+ function mount(fiber) {
153
+ const familyContexts = new WeakMap()
154
+ const state = { fiber, fibers: [fiber], paths: [], provider: null, controller: null, control: null, families: new Map(),
155
+ familyContext: candidate => familyContexts.get(candidate.locator) ?? fiber.ctx }
156
+ async function familyList(options) {
157
+ const combined = { candidates: [], complete: true }
158
+ const rootsSeen = new Set()
159
+ for (const source of state.fibers) {
160
+ const candidates = await familyRoots(source, source === fiber ? state.paths : [], options.cwd)
161
+ const roots = candidates.filter(root => {
162
+ const key = JSON.stringify([root.source, root.path])
163
+ if (rootsSeen.has(key)) return false
164
+ rootsSeen.add(key)
165
+ return true
166
+ })
167
+ const found = await listFamilies(source.ctx, roots, options, filesystem)
168
+ if (!found.complete) combined.complete = false
169
+ for (const skill of found.candidates) {
170
+ familyContexts.set(skill.locator, source.ctx)
171
+ combined.candidates.push(skill)
172
+ }
173
+ }
174
+ return combined
175
+ }
176
+ state.familyList = familyList
177
+ const release = fiber.ctx.skills.registerProvider(control => {
178
+ state.control = control
179
+ control.signal.addEventListener('abort', () => {
180
+ state.controller?.abort()
181
+ retire(state.provider)
182
+ }, { once: true })
183
+ return {
184
+ name: CUSTOM_PROVIDER,
185
+ async list(options) {
186
+ const [direct, families] = await Promise.all([state.provider?.list(options) ?? [], familyList(options)])
187
+ const plain = observation(direct)
188
+ const nested = new Set(families.candidates.map(skill => skill.locator.path))
189
+ // A collection with its own root SKILL.md also has a plain candidate
190
+ // in the native provider. Its family policy must apply to both views.
191
+ for (const skill of families.candidates) {
192
+ const part = relativeChild(skill.family.sourceRoot, skill.locator.path)
193
+ if (part && part.split(sep).length <= 2) skill.rank -= 0.25
194
+ }
195
+ state.families.delete(options.cwd)
196
+ state.families.set(options.cwd, families)
197
+ if (state.families.size > 32) state.families.delete(state.families.keys().next().value)
198
+ return { candidates: [...plain.candidates.filter(skill => !nested.has(skill.locator.path)), ...families.candidates],
199
+ complete: plain.complete && families.complete }
200
+ },
201
+ async get(candidate, options) {
202
+ if (candidate.family) return getFamily(state.familyContext(candidate), candidate, options, filesystem)
203
+ return state.provider?.get(candidate, options)
204
+ },
205
+ }
206
+ })
207
+ return Object.assign(state, { release })
208
+ }
209
+
210
+ function reconcile() {
211
+ if (disposed) return
212
+ const byScope = new Map(), all = new Map()
213
+ for (const fiber of activeFibers(ctx, filesystem.name)) {
214
+ const key = scopeOf(fiber.ctx)
215
+ if (!all.has(key)) all.set(key, [])
216
+ all.get(key).push(fiber)
217
+ const first = byScope.get(key)
218
+ const hasDefaults = fiber.effectiveConfig?.includeDefaultRoots !== false
219
+ if (!first || (first.effectiveConfig?.includeDefaultRoots === false && hasDefaults)) byScope.set(key, fiber)
220
+ }
221
+ for (const [key, state] of mounts) {
222
+ if (byScope.get(key) === state.fiber) continue
223
+ state.release()
224
+ mounts.delete(key)
225
+ }
226
+ const configuredPaths = configured(config).map(dir => dir.path)
227
+ for (const [key, fiber] of byScope) {
228
+ // An isolated native provider has no manager-owned directories. Its
229
+ // control still lets a refresh invalidate the native provider's cache.
230
+ const paths = fiber.effectiveConfig?.includeDefaultRoots === false ? [] : configuredPaths
231
+ let state = mounts.get(key)
232
+ if (!state) {
233
+ state = mount(fiber)
234
+ mounts.set(key, state)
235
+ }
236
+ state.fibers = all.get(key)
237
+ if (isDeepStrictEqual(state.paths, paths)) continue
238
+ const controller = new AbortController()
239
+ const provider = paths.length ? new FileSystemSkillProvider(fiber.ctx, {
240
+ signal: controller.signal, invalidate: state.control.invalidate,
241
+ }, { ...fiber.effectiveConfig, bundledSkillDir: undefined, includeDefaultRoots: false,
242
+ providerName: CUSTOM_PROVIDER, customSkillDirs: paths }) : null
243
+ const previous = state.provider
244
+ state.controller?.abort()
245
+ Object.assign(state, { provider, paths, controller })
246
+ retire(previous)
247
+ state.control.invalidate()
248
+ }
249
+ }
250
+
251
+ ctx.on('internal/status', fiber => {
252
+ if (fiber.runtime?.callback === filesystem.apply || fiber.entry?.options?.name === '@deepseek-ai/dsh-skill-filesystem') reconcile()
253
+ }, { global: true })
254
+ ctx.on('loader/volatile-update', reconcile)
255
+ ctx.on('fs/observed', (target, _observation, actor) => {
256
+ if (actor?.name !== 'write' && actor?.name !== 'edit') return
257
+ for (const { provider, families, control } of mounts.values()) {
258
+ provider?.observeHostMutation(target.displayPath)
259
+ if ([...families.values()].some(list => list.candidates.some(skill => within(skill.family.root, target.displayPath)))) control.invalidate()
260
+ }
261
+ })
262
+ ctx.effect(() => async () => {
263
+ disposed = true
264
+ for (const state of mounts.values()) state.release()
265
+ mounts.clear()
266
+ await Promise.allSettled([...closing])
267
+ }, 'skill manager custom directories')
268
+ reconcile()
269
+ return {
270
+ reconcile,
271
+ invalidate(scope) {
272
+ // In 0.2.3 a single registered provider control invalidates the entire
273
+ // registry cache. Access only a control visible to this viewing scope.
274
+ for (const key of [...scopeChainOf(scope), undefined]) {
275
+ const state = mounts.get(key)
276
+ if (state) { state.control.invalidate(); break }
277
+ }
278
+ },
279
+ get(key) { return mounts.get(key) },
280
+ }
281
+ }
282
+
283
+ async function projectRoot(cwd, ctx) {
284
+ const fs = ctx.get('fs')
285
+ for (let path = cwd; ; path = dirname(path)) {
286
+ try {
287
+ const marker = join(path, '.git')
288
+ if (fs ? await fs.stat(await fs.resolve(marker)) : await stat(marker)) return path
289
+ } catch { /* DSH skips inaccessible .git candidates. */ }
290
+ if (dirname(path) === path) return cwd
291
+ }
292
+ }
293
+
294
+ async function familyRoots(fiber, managed, cwd) {
295
+ const config = fiber.effectiveConfig ?? {}
296
+ const roots = (config.customSkillDirs ?? []).map(path => ({ path, source: 'custom', rank: 300 }))
297
+ if (config.includeDefaultRoots !== false) {
298
+ roots.push(...managed.map(path => ({ path, source: 'custom', rank: 300, includeDirect: true })),
299
+ { path: join(resolveDshHome(config.dshHome), 'skills'), source: 'user-dsh', rank: 400 },
300
+ { path: join(resolveAgentsHome(config.agentsHome), 'skills'), source: 'user-agents', rank: 500 })
301
+ if (cwd) {
302
+ const project = await projectRoot(resolve(cwd), fiber.ctx)
303
+ roots.unshift({ path: join(project, '.dsh/skills'), source: 'project-dsh', rank: 100 },
304
+ { path: join(project, '.agents/skills'), source: 'project-agents', rank: 200 })
305
+ }
306
+ }
307
+ const bundled = config.bundledSkillDir ?? (config.includeDefaultRoots !== false ? process.env.DSH_BUNDLED_SKILL_DIR : undefined)
308
+ if (bundled) roots.push({ path: bundled, source: 'bundled', rank: 600 })
309
+ return roots
310
+ }
311
+
312
+ async function writableDirectory(path, allowMissing) {
313
+ for (let current = path; ; current = dirname(current)) {
314
+ try {
315
+ const info = await lstat(current)
316
+ if (!info.isDirectory()) return false
317
+ await access(current, constants.W_OK | constants.X_OK)
318
+ return true
319
+ } catch (error) {
320
+ if (!allowMissing || !missing(error) || dirname(current) === current) return false
321
+ }
322
+ }
323
+ }
324
+
325
+ async function directory(kind, source, label, path, pretty) {
326
+ const canonical = await canonicalizeWatchPath(path).catch(() => resolve(path))
327
+ const info = await stat(path).catch(() => null)
328
+ const exists = info?.isDirectory() === true
329
+ const writable = (kind === 'personal' || kind === 'custom') && await writableDirectory(path, kind === 'personal')
330
+ return {
331
+ id: dirId(source, canonical), kind, source, label, path, displayPath: pretty ?? displayPath(path),
332
+ exists, writable, removable: kind === 'custom',
333
+ }
334
+ }
335
+
336
+ async function directoriesFor(cwd, fibers, extra) {
337
+ const result = new Map()
338
+ const reserved = new Set()
339
+ for (const fiber of fibers) {
340
+ const config = fiber.effectiveConfig ?? {}
341
+ for (const path of config.customSkillDirs ?? []) reserved.add(resolve(path))
342
+ const bundled = config.bundledSkillDir ?? (config.includeDefaultRoots !== false ? process.env.DSH_BUNDLED_SKILL_DIR : undefined)
343
+ if (bundled) reserved.add(resolve(bundled))
344
+ if (config.includeDefaultRoots === false) continue
345
+ const root = await projectRoot(cwd, fiber.ctx)
346
+ const rows = await Promise.all([
347
+ directory('personal', 'user-dsh', 'DSH 个人目录', join(resolveDshHome(config.dshHome), 'skills')),
348
+ directory('project', 'project-dsh', '项目 DSH 目录', join(root, '.dsh/skills'), '.dsh/skills'),
349
+ directory('project', 'project-agents', '项目共享目录', join(root, '.agents/skills'), '.agents/skills'),
350
+ directory('shared', 'user-agents', '个人共享目录', join(resolveAgentsHome(config.agentsHome), 'skills')),
351
+ ])
352
+ for (const row of rows) result.set(row.id, row)
353
+ }
354
+ const hasDefaults = [...result.values()].some(row => row.kind === 'personal')
355
+ for (const { path, label } of extra) {
356
+ const row = await directory('custom', 'custom', label || basename(path), path)
357
+ // Configuration can still be removed when this preset has no filesystem.
358
+ if (!hasDefaults) row.writable = false
359
+ result.set(row.id, row)
360
+ }
361
+ return { directories: [...result.values()], reserved }
362
+ }
363
+
364
+ // Check the discovered locator too. DSH can follow bundle and file symlinks
365
+ // for reads. Only edit an ordinary entry still belonging to this local root.
366
+ async function editableFile(dir, locator, reportedPath, family) {
367
+ if (!dir || !locator || !reportedPath) return null
368
+ const part = relativeChild(dir.path, locator)
369
+ if (!part) return null
370
+ const pieces = part.split(sep)
371
+ if (!family && !(pieces.length === 1 && pieces[0].endsWith('.md') || pieces.length === 2 && pieces[1] === 'SKILL.md')) return null
372
+ try {
373
+ const [root, path, info] = await Promise.all([realpath(dir.path), realpath(locator), lstat(dir.path)])
374
+ if (!info.isDirectory() || path !== join(root, part) || path !== await realpath(reportedPath)) return null
375
+ if (family && (family.sourceRoot !== root || !within(root, family.root) || !within(family.root, family.memberRoot)
376
+ || path !== join(family.memberRoot, 'SKILL.md'))) return null
377
+ if (!(await lstat(path)).isFile()) return null
378
+ await Promise.all([access(root, constants.W_OK | constants.X_OK), access(path, constants.W_OK),
379
+ access(dirname(path), constants.W_OK | constants.X_OK)])
380
+ const familyLock = family?.markerId ?? family?.markerTemplate?.id
381
+ return { root, path, ...(familyLock && { lockRoot: dirname(family.root), lockName: familyLock }) }
382
+ } catch { return null }
383
+ }
384
+
385
+ function matchesDirectory(candidate, dir) {
386
+ if (dir.source !== candidate.source || (dir.kind === 'custom' && candidate.provider !== CUSTOM_PROVIDER)) return false
387
+ if (candidate.family) return dir.id === dirId(candidate.source, candidate.family.sourceRoot)
388
+ const part = relativeChild(dir.path, candidate.locator.path)?.split(sep)
389
+ return part?.length === 1 || (part?.length === 2 && part[1] === 'SKILL.md')
390
+ }
391
+
392
+ function observation(output) {
393
+ return Array.isArray(output) ? { candidates: output, complete: true } : output
394
+ }
395
+
396
+ function reader(ctx, config) {
397
+ return new FileSystemSkillProvider(ctx, { signal: new AbortController().signal, invalidate: noop }, { ...config, watch: false })
398
+ }
399
+
400
+ function visibleFibers(ctx, name, scope) {
401
+ const chain = [...scopeChainOf(scope), undefined]
402
+ return activeFibers(ctx, name).filter(fiber => chain.includes(scopeOf(fiber.ctx)))
403
+ .sort((a, b) => chain.indexOf(scopeOf(a.ctx)) - chain.indexOf(scopeOf(b.ctx)))
404
+ }
405
+
406
+ function excludedSkills(ctx, scope) {
407
+ return new Set(visibleFibers(ctx, 'tool-skill', scope)[0]?.effectiveConfig?.excludedSkills ?? [])
408
+ }
409
+
410
+ function canCreateFile(ctx, scope) {
411
+ const tools = ctx.get('tools')
412
+ try {
413
+ if (tools.get('write', scope) || tools.get('apply_patch', scope)) return true
414
+ if (!tools.get('run_code', scope)) return false
415
+ // Program-only roots expose one direct entry. Check the native filesystem
416
+ // contribution in that scope for the write or create-file patch binding.
417
+ return visibleFibers(ctx, 'tool-fs', scope).some(({ effectiveConfig: fs }) =>
418
+ fs.write !== false || (fs.applyPatch ?? fs.edit) !== false)
419
+ } catch (error) {
420
+ if (error.code === 'TOOL_REGISTRY_UNAVAILABLE') return false
421
+ throw error
422
+ }
423
+ }
424
+
425
+ async function creatorPreset(ctx, cwd, selection) {
426
+ const preset = await findManagementPreset(selection, 'standard', async (scope, signal) => {
427
+ const dispatcher = visibleFibers(ctx, 'tool-skill', scope)[0]
428
+ if (!dispatcher || dispatcher.effectiveConfig?.excludedSkills?.includes('skill-creator') || !canCreateFile(ctx, scope)) return false
429
+ // Match the same winning definition the native slash dispatcher will load.
430
+ const definition = await ctx.skills.get('skill-creator', { cwd, scope, signal })
431
+ return definition?.invocation.userInvocable === true
432
+ })
433
+ if (preset) return preset
434
+ throw problem('CREATOR_UNAVAILABLE', '当前工作区没有可用的技能创建模式。请在管理器中检查 /skill-creator 的调用方式和模式设置。')
435
+ }
436
+
437
+ function lacksMinimalInvocation(mode, dispatcher, tools, scope) {
438
+ // Minimal may retain skill providers for reading while omitting the native
439
+ // dispatcher. Confirm both entry points are absent in the effective scope.
440
+ // Other compositions may have their own skill integration.
441
+ if (mode.id !== 'minimal' || dispatcher || typeof tools?.get !== 'function') return false
442
+ try { return !tools.get('skill', scope) }
443
+ catch { return false } // The selected tool registry may be unloaded or ambiguous.
444
+ }
445
+
446
+ function within(root, path) {
447
+ return Boolean(root && path && (resolve(root) === resolve(path) || relativeChild(root, path)))
448
+ }
449
+
450
+ function sourceCategory(skill, local, dir, cards) {
451
+ if (USER_SOURCES.has(skill.source)) return 'user'
452
+ if (local && (skill.source === 'bundled' || within(presetSkills, local.candidate.locator.path))) return 'builtin'
453
+ const resources = skill.resourceBase?.kind === 'directory' ? skill.resourceBase.path : null
454
+ if (skill.source === 'bundled') {
455
+ if (skill.provider === 'dsh-badge' && within(badgeAssets, resources)) return 'experimental'
456
+ if (skill.provider === 'dsh-office' && within(officeAssets, resources)) return 'builtin'
457
+ if (!skill.path && !skill.resourceBase && cards.has(skill)) return 'builtin'
458
+ }
459
+ return dir?.kind === 'custom' ? 'user' : 'provided'
460
+ }
461
+
462
+ function toggleReason(source, enabled, excluded, editable, effective) {
463
+ if (excluded) return '当前模式限制了这项技能的调用。Agent 调用和用户斜杠调用均不可用。'
464
+ if (source === 'builtin') {
465
+ if (!effective) return '这项技能随 DSH 提供。所查模式优先使用另一项同名技能。'
466
+ return enabled ? '这项技能随 DSH 提供,由当前预设启用 Agent 自动调用。' : '这项技能随 DSH 提供,当前配置已关闭 Agent 自动调用。'
467
+ }
468
+ if (editable) return null
469
+ if (source === 'user') return '技能管理器对此技能文件只有读取权限。'
470
+ return '这项技能的调用设置由提供它的插件或预设管理。'
471
+ }
472
+
473
+ function bundledCardCandidates(ctx, registry, entries) {
474
+ const cards = new Set()
475
+ for (const [module, provider, name] of cardRegistrations) {
476
+ const registered = entries.get(name)
477
+ if (!registered || registered.provider.name !== provider || registered.candidate.provider !== provider) continue
478
+ const file = hostModulePath(module)
479
+ const apply = file && localRequire(file).apply
480
+ for (const runtime of ctx.registry.values()) {
481
+ for (const fiber of runtime.fibers) {
482
+ if (fiber.state !== ACTIVE || !(runtime.callback === apply || fiber.entry?.options?.name === module)) continue
483
+ // The provider must win from the official plugin's own registry layer.
484
+ // A session plugin may legitimately use the same provider/skill names.
485
+ const scope = scopeOf(fiber.ctx)
486
+ const layer = scope === undefined ? registry.layers?.global : registry.layers?.peek(scope)
487
+ if (layer === registered.layer) cards.add(registered.candidate)
488
+ }
489
+ }
490
+ }
491
+ return cards
492
+ }
493
+
494
+ async function discoverSkills(ctx, registry, cwd, scope) {
495
+ // In DSH 0.2.3, snapshot() projects this same scoped collection to summaries
496
+ // and deliberately removes candidate metadata. Reuse its discovery cache so
497
+ // listing a package never loads each member's body via a provider's get().
498
+ if (typeof registry.collect === 'function') {
499
+ const result = await registry.collect({ cwd, scope })
500
+ if (result?.entries instanceof Map && typeof result.cacheable === 'boolean') {
501
+ return { skills: Array.from(result.entries.values(), entry => entry.candidate), complete: result.cacheable,
502
+ cards: bundledCardCandidates(ctx, registry, result.entries) }
503
+ }
504
+ }
505
+ return { ...await registry.snapshot({ cwd, scope }), cards: new Set() }
506
+ }
507
+
508
+ // The registry returns the winning bare name. A package command can still
509
+ // resolve its own member when a personal skill wins that name in this scope.
510
+ async function pstackMembers(ctx, registry, cwd, scope) {
511
+ const command = ctx.get('commands')?.find?.(scope, 'pstack')
512
+ if (command?.definitionId !== 'dsh-pstack.pstack') return null
513
+ for (const key of scopeChainOf(scope)) {
514
+ const provider = registry.layers?.peek(key)?.providers.get('pstack')?.provider
515
+ if (!provider) continue
516
+ const found = observation(await provider.list({ cwd, scope }))
517
+ const members = found.candidates.filter(skill => skill.provider === 'pstack' &&
518
+ skill.metadata?.package === '@kafukatree/dsh-pstack' && skill.metadata.pstackUserInvocable === true)
519
+ return { members, provider, complete: found.complete }
520
+ }
521
+ return null
522
+ }
523
+
524
+ async function publishedSkillFile(skill) {
525
+ if (typeof skill.path === 'string' && isAbsolute(skill.path)) {
526
+ return { path: skill.path, info: await stat(skill.path).catch(() => null) }
527
+ }
528
+ const { resourceBase, locator } = skill
529
+ // A locator is provider-owned and may be opaque. Accept it as a file only
530
+ // when it names a conventional entry directly inside the declared directory.
531
+ if (skill.path != null || resourceBase?.kind !== 'directory' || typeof resourceBase.path !== 'string' ||
532
+ !isAbsolute(resourceBase.path) || typeof locator !== 'string' || !isAbsolute(locator)) return null
533
+ const root = normalize(resourceBase.path)
534
+ const path = normalize(locator)
535
+ if (dirname(path) !== root || dirname(root) === root || !/^skill\.md$/i.test(basename(path))) return null
536
+ try {
537
+ if (await realpath(path) !== path) return null
538
+ const info = await lstat(path)
539
+ return info.isFile() ? { path, info } : null
540
+ } catch (error) {
541
+ if (missing(error) || ['EACCES', 'EPERM', 'ELOOP'].includes(error.code)) return null
542
+ throw error
543
+ }
544
+ }
545
+
546
+ function declaredPackage(skill) {
547
+ const name = skill.metadata?.package
548
+ return typeof name === 'string' && name.length <= 214 && PACKAGE_NAME.test(name) ? name : null
549
+ }
550
+
551
+ // Package metadata is data, never a module to execute or a path supplied by a
552
+ // skill. Restrict reads to small, regular, non-linked files inside the root.
553
+ async function packageJson(path) {
554
+ try {
555
+ if (await realpath(path) !== path) return null
556
+ const file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0))
557
+ try {
558
+ const info = await file.stat()
559
+ if (!info.isFile() || !info.size || info.size > 256 * 1024) return null
560
+ const buffer = Buffer.alloc(info.size)
561
+ let offset = 0
562
+ while (offset < buffer.length) {
563
+ const { bytesRead } = await file.read(buffer, offset, buffer.length - offset, offset)
564
+ if (!bytesRead) return null
565
+ offset += bytesRead
566
+ }
567
+ return JSON.parse(buffer.toString('utf8'))
568
+ } finally { await file.close() }
569
+ } catch { return null }
570
+ }
571
+
572
+ function installedRoot(path) {
573
+ for (let root = path; dirname(root) !== root; root = dirname(root)) {
574
+ const parent = dirname(root)
575
+ if (basename(parent) === 'node_modules' || (basename(parent).startsWith('@') && basename(dirname(parent)) === 'node_modules')) return root
576
+ }
577
+ return null
578
+ }
579
+
580
+ async function editableMarker(dir, family, cwd) {
581
+ if (!dir || !(family?.markerId || family?.markerTemplate)) return null
582
+ const root = family.root, marker = join(root, FAMILY_MARKER)
583
+ try {
584
+ const configuredRoot = await realpath(dir.path)
585
+ if (!within(configuredRoot, root) || await realpath(root) !== root || !(await lstat(root)).isDirectory()) return null
586
+ await access(root, constants.W_OK | constants.X_OK)
587
+ if (family.markerId) {
588
+ if (await realpath(marker) !== marker || !(await lstat(marker)).isFile()) return null
589
+ await access(marker, constants.W_OK)
590
+ } else {
591
+ // Only a verified family can obtain its first marker. A configured
592
+ // generic skill index, home or a workspace itself is never a package.
593
+ if (root === configuredRoot && (dir.kind !== 'custom' || ['skills', '.dsh', '.agents'].includes(basename(root).toLowerCase())
594
+ || root === homedir() || within(root, cwd))) return null
595
+ if (await lstat(marker).catch(error => { if (!missing(error)) throw error })) return null
596
+ }
597
+ return { path: marker, root, lockRoot: dirname(root), lockName: family.markerId ?? family.markerTemplate.id }
598
+ } catch { return null }
599
+ }
600
+
601
+ function memo(map, key, read) {
602
+ if (!map.has(key)) map.set(key, read(key))
603
+ return map.get(key)
604
+ }
605
+
606
+ const maxReferenceFileBytes = 64 * 1024
607
+ const inlineSiblingSkillPath = /(?:`(\.\.\/[a-z0-9][a-z0-9-]*\/SKILL\.md)`|\]\((\.\.\/[a-z0-9][a-z0-9-]*\/SKILL\.md)\))/g
608
+
609
+ async function documentedSiblingPaths(path, cache) {
610
+ try {
611
+ if (await realpath(path) !== path) return []
612
+ const file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0))
613
+ try {
614
+ const info = await file.stat({ bigint: true })
615
+ if (!info.isFile() || info.size > maxReferenceFileBytes) return []
616
+ const version = `${info.dev}/${info.ino}/${info.size}/${info.mtimeNs}/${info.ctimeNs}`
617
+ const previous = cache.get(path)
618
+ if (previous?.version === version) return previous.paths
619
+ const bytes = Buffer.alloc(Number(info.size))
620
+ const { bytesRead } = await file.read(bytes, 0, bytes.length, 0)
621
+ if (bytesRead !== bytes.length || (await file.stat({ bigint: true })).ctimeNs !== info.ctimeNs) return []
622
+ const text = bytes.toString('utf8')
623
+ const opening = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(text)
624
+ if (!opening) return []
625
+ const body = text.slice(opening[0].length)
626
+ const paths = [...new Set(Array.from(body.matchAll(inlineSiblingSkillPath), match => resolve(dirname(path), match[1] ?? match[2])))]
627
+ cache.delete(path)
628
+ cache.set(path, { version, paths })
629
+ if (cache.size > 128) cache.delete(cache.keys().next().value)
630
+ return paths
631
+ } finally { await file.close() }
632
+ } catch { return [] }
633
+ }
634
+
635
+ async function attachPackageReferences(group, cache, canonical) {
636
+ // These are documentation references between known members. DSH's skill
637
+ // tool does not traverse them or grant another invocation channel.
638
+ const sources = []
639
+ const targets = new Map()
640
+ for (const { item } of group.entries) {
641
+ if (item.excluded || !item.effective || !item.path || !relativeChild(group.root, item.path) || await canonical(item.path) !== item.path) continue
642
+ if (item.invocation?.modelInvocable) sources.push(item)
643
+ else targets.set(item.path, item)
644
+ }
645
+ if (!targets.size) return
646
+ await Promise.all(sources.slice(0, 16).map(async source => {
647
+ for (const path of await documentedSiblingPaths(source.path, cache)) {
648
+ const target = targets.get(path)
649
+ if (target) (target.referencedBy ??= []).push(source.name)
650
+ }
651
+ }))
652
+ for (const item of targets.values()) item.referencedBy?.sort()
653
+ }
654
+
655
+ async function attachPackages(entries, cwd, referenceCache) {
656
+ const manifests = new Map(), paths = new Map(), groups = new Map(), directoryMembers = new Map()
657
+ const canonical = path => memo(paths, path, value => realpath(value).catch(() => null))
658
+ for (const entry of entries) {
659
+ if (!entry.dir) continue
660
+ const members = directoryMembers.get(entry.dir.id) ?? []
661
+ members.push(declaredPackage(entry.skill))
662
+ directoryMembers.set(entry.dir.id, members)
663
+ }
664
+ await Promise.all(entries.map(async entry => {
665
+ const { skill, item, dir, local } = entry
666
+ const family = local?.candidate.family
667
+ if (family) {
668
+ const { root, name, label, description } = family
669
+ const key = id('package', root, name)
670
+ const group = groups.get(key) ?? { id: key, name, root, family, dir, label, description, entries: [], members: new Set(), declared: true }
671
+ group.entries.push(entry)
672
+ groups.set(key, group)
673
+ return
674
+ }
675
+ const declared = declaredPackage(skill)
676
+ // A home or project skills directory is an index of independent skills.
677
+ // Do not look for a surrounding workspace package on an unmarked entry.
678
+ if (local && !declared && USER_SOURCES.has(skill.source)) return
679
+ const resources = skill.resourceBase?.kind === 'directory' ? skill.resourceBase.path : null
680
+ if (!resources || !isAbsolute(resources)) return
681
+ const base = await canonical(resources)
682
+ const member = item.path ? await canonical(item.path) : base
683
+ if (!base || !within(base, member)) return
684
+ const localRoot = dir ? await canonical(dir.path) : null
685
+ if (dir && !within(localRoot, member)) return
686
+ const collection = item.path && basename(member) !== 'SKILL.md' ? dirname(member) : dirname(base)
687
+ const installed = installedRoot(member)
688
+ const roots = installed ? [installed] : [collection]
689
+ if (!installed && ['skills', 'assets'].includes(basename(collection))) roots.push(dirname(collection))
690
+
691
+ let name, root, manifest
692
+ for (const candidate of roots) {
693
+ if (candidate === homedir() || dirname(candidate) === candidate || !relativeChild(candidate, member)) continue
694
+ if (localRoot && !within(localRoot, candidate)) continue
695
+ if (dir && dir.kind !== 'custom' && within(candidate, localRoot)) continue
696
+ if (!installed && !local && !declared && !['skills', 'assets'].includes(basename(collection))) continue
697
+ const data = await memo(manifests, candidate, path => packageJson(join(path, 'package.json')))
698
+ if (!data) continue
699
+ if (typeof data.name !== 'string' || !PACKAGE_NAME.test(data.name) || (declared && declared !== data.name)) return
700
+ name = data.name; root = candidate; manifest = data
701
+ break
702
+ }
703
+ // A dedicated custom root can declare a collection in each member's own
704
+ // frontmatter, without an npm manifest. Never widen it to an ancestor.
705
+ if (!root && declared && dir?.kind === 'custom' && collection === localRoot && !within(collection, cwd)
706
+ && collection !== homedir() && directoryMembers.get(dir.id).every(name => name === declared)) {
707
+ name = declared; root = collection
708
+ }
709
+ if (!root) return
710
+ const key = id('package', root, name)
711
+ const group = groups.get(key) ?? { id: key, name, root, manifest, entries: [], members: new Set(), declared: false }
712
+ group.entries.push(entry)
713
+ group.members.add(member)
714
+ if (manifest && declared) group.declared = true
715
+ groups.set(key, group)
716
+ }))
717
+ await Promise.all([...groups.values()].map(async group => {
718
+ if (!group.declared && group.members.size < 2) return
719
+ const { id, name, root, manifest } = group
720
+ let meta
721
+ if (manifest) {
722
+ for (const language of ['zh-CN', 'zh', 'en']) {
723
+ meta = (await packageJson(join(root, 'locale', `${language}.json`)))?.meta
724
+ if (typeof meta?.title === 'string' && meta.title.trim()) break
725
+ }
726
+ }
727
+ const label = [group.label, meta?.title, manifest?.displayName, name].find(value => typeof value === 'string' && value.trim())
728
+ const description = [group.description, meta?.description, manifest?.description].find(value => typeof value === 'string' && value.trim()) ?? ''
729
+ const canToggle = Boolean(await editableMarker(group.dir, group.family, cwd))
730
+ const pkg = { id, name, label, description, root, enabled: group.family && (group.family.markerId || canToggle) ? group.family.enabled : null, canToggle }
731
+ const categories = new Set(group.entries.map(({ item }) => item.category))
732
+ const category = ['experimental', 'builtin', 'provided', 'user'].find(value => categories.has(value))
733
+ for (const { item } of group.entries) { item.package = pkg; item.category = category }
734
+ if (pkg.enabled !== false) await attachPackageReferences(group, referenceCache, canonical)
735
+ }))
736
+ }
737
+
738
+ function removalSource(dir) {
739
+ return dir?.kind === 'custom' || USER_SOURCES.has(dir?.source)
740
+ }
741
+
742
+ function providedRemovalRoots(ctx, reserved) {
743
+ const roots = new Set(reserved)
744
+ for (const fiber of activeFibers(ctx, filesystem.name)) {
745
+ const config = fiber.effectiveConfig ?? {}
746
+ for (const path of config.customSkillDirs ?? []) roots.add(resolve(path))
747
+ const bundled = config.bundledSkillDir ?? (config.includeDefaultRoots !== false ? process.env.DSH_BUNDLED_SKILL_DIR : undefined)
748
+ if (bundled) roots.add(resolve(bundled))
749
+ }
750
+ return roots
751
+ }
752
+
753
+ async function removalBoundary(directories, reserved, cwd, canonical) {
754
+ const protectedRoots = await Promise.all([...directories.map(dir => dir.path), cwd, homedir()].map(canonical))
755
+ const providerRoots = await Promise.all([...reserved].map(canonical))
756
+ return path => !protectedRoots.some(root => within(path, root)) && !providerRoots.some(root => within(path, root) || within(root, path))
757
+ }
758
+
759
+ async function attachRemoval(entries, directories, reserved, cwd) {
760
+ const groups = new Map(), canonicalPaths = new Map()
761
+ const canonical = path => memo(canonicalPaths, path, value => canonicalizeWatchPath(value).catch(() => resolve(value)))
762
+ const withinBoundary = await removalBoundary(directories, reserved, cwd, canonical)
763
+ for (const entry of entries) {
764
+ const pkg = entry.item.package
765
+ if (pkg) {
766
+ if (!groups.has(pkg.id)) groups.set(pkg.id, [])
767
+ groups.get(pkg.id).push(entry)
768
+ }
769
+ }
770
+ const occupants = new Map()
771
+ await Promise.all(entries.map(async ({ item }) => {
772
+ if (!item.path) return
773
+ for (let path = await canonical(item.path); dirname(path) !== path; path = dirname(path)) {
774
+ if (!occupants.has(path)) occupants.set(path, [])
775
+ occupants.get(path).push(item)
776
+ }
777
+ }))
778
+ function hostPath(local, path) {
779
+ const fs = local?.ctx.get('fs')
780
+ return !fs || fs.processPathFromHostPath?.(path) === path
781
+ }
782
+ async function annotate(item, target, genericReason) {
783
+ let reason = genericReason
784
+ if (target) {
785
+ const actual = await canonical(target.path)
786
+ const source = await canonical(target.dir.path)
787
+ if (dirname(actual) !== source || !withinBoundary(actual) ||
788
+ occupants.get(actual)?.some(row => target.kind === 'package' ? row.package?.id !== item.id : row.id !== item.id)) {
789
+ reason = '此位置与共享目录、其他技能或提供方管理的来源重叠。'
790
+ } else {
791
+ try { await inspectRemoval(target); reason = null }
792
+ catch (error) { reason = error.code === 'REMOVAL_NOT_ALLOWED' ? error.message : genericReason }
793
+ }
794
+ }
795
+ item.canRemove = reason === null
796
+ item.removeReason = reason
797
+ return item.canRemove ? target : null
798
+ }
799
+ await Promise.all(entries.map(async entry => {
800
+ const { item, dir, local } = entry
801
+ let target
802
+ if (!item.package && !local?.candidate.family && removalSource(dir) && local && item.category === 'user' && item.path && !declaredPackage(entry.skill)) {
803
+ const relative = relativeChild(dir.path, local.candidate.locator.path)?.split(sep)
804
+ const file = relative?.length === 1 && relative[0].endsWith('.md') && relative[0] !== 'SKILL.md'
805
+ if (file || (relative?.length === 2 && relative[1] === 'SKILL.md')) {
806
+ const path = join(dir.path, relative[0])
807
+ if (hostPath(local, path) && await canonical(local.candidate.locator.path) === await canonical(item.path)) {
808
+ target = { dir, id: item.id, kind: 'skill', name: item.name, scope: file ? 'file' : 'directory', path,
809
+ entry: relative.join(sep), lockName: item.name }
810
+ }
811
+ }
812
+ }
813
+ entry.removal = await annotate(item, target, item.package || local?.candidate.family ? '这是工具包的一部分。请从所属工具包管理。' :
814
+ '仅可移除当前用户拥有且路径可验证的独立技能。')
815
+ }))
816
+ const packageRemovals = new Map()
817
+ await Promise.all([...groups.values()].map(async group => {
818
+ const { item, dir, local } = group[0]
819
+ const pkg = item.package, family = local?.candidate.family
820
+ let target
821
+ if (pkg && family?.markerId && removalSource(dir) && item.category === 'user' && hostPath(local, family.root) &&
822
+ group.every(member => member.dir?.id === dir.id && member.local?.candidate.family?.root === family.root)) {
823
+ target = { dir, id: pkg.id, kind: 'package', name: pkg.label, scope: 'directory', path: join(dir.path, basename(family.root)),
824
+ lockName: family.markerId, members: group.map(({ item }) => ({ name: item.name, path: item.path })) }
825
+ if (await canonical(target.path) !== family.root) target = null
826
+ }
827
+ const allowed = await annotate(pkg, target, '仅可移除由技能管理器确认导入归属的完整工具包。')
828
+ if (allowed) packageRemovals.set(pkg.id, allowed)
829
+ }))
830
+ return packageRemovals
831
+ }
832
+
833
+ async function scan(ctx, mounts, config, cwd, scope, referenceCache, mode, registry, tools) {
834
+ mounts.reconcile()
835
+ const fibers = visibleFibers(ctx, filesystem.name, scope)
836
+ const [snapshot, roots] = await Promise.all([
837
+ discoverSkills(ctx, registry, cwd, scope), directoriesFor(cwd, fibers, configured(config)),
838
+ ])
839
+ const { directories } = roots
840
+ const dispatcher = visibleFibers(ctx, 'tool-skill', scope)[0]
841
+ const excluded = new Set(dispatcher?.effectiveConfig?.excludedSkills ?? [])
842
+ const invocationUnavailable = lacksMinimalInvocation(mode, dispatcher, tools, scope)
843
+ const winners = new Map(snapshot.skills.map(skill => [skill.name, skillId(skill)]))
844
+ const entries = new Map(snapshot.skills.map(skill => [skillId(skill), { skill }]))
845
+ let complete = snapshot.complete
846
+ const warnings = []
847
+ const grouped = await pstackMembers(ctx, registry, cwd, scope)
848
+ if (grouped) {
849
+ if (!grouped.complete) complete = false
850
+ for (const skill of grouped.members) {
851
+ const key = skillId(skill)
852
+ entries.set(key, { skill, groupedProvider: grouped.provider })
853
+ }
854
+ }
855
+ const scannedScopes = new Set()
856
+ const nested = new Set()
857
+ function addLocal(ctx, config, found, mount) {
858
+ if (!found.complete) complete = false
859
+ for (const skill of found.candidates) {
860
+ const key = skillId(skill)
861
+ if (entries.get(key)?.local && !skill.family) continue
862
+ const local = { ctx: mount?.familyContext(skill) ?? ctx, config, candidate: skill }
863
+ const dir = directories.filter(dir => matchesDirectory(skill, dir)).sort((a, b) => b.path.length - a.path.length)[0]
864
+ entries.set(key, { skill, local, dir })
865
+ if (skill.family) nested.add(JSON.stringify([skill.source, skill.name, skill.path]))
866
+ }
867
+ }
868
+ async function collectLocal(ctx, config) {
869
+ const provider = reader(ctx, config)
870
+ try { addLocal(ctx, config, observation(await provider.list({ cwd }))) } finally { await provider.dispose() }
871
+ }
872
+ for (const fiber of fibers) {
873
+ await collectLocal(fiber.ctx, fiber.effectiveConfig ?? {})
874
+ const key = scopeOf(fiber.ctx)
875
+ const mount = mounts.get(key)
876
+ if (mount && !scannedScopes.has(key)) {
877
+ scannedScopes.add(key)
878
+ if (mount.provider) await collectLocal(mount.fiber.ctx, { providerName: CUSTOM_PROVIDER, includeDefaultRoots: false, customSkillDirs: mount.paths })
879
+ const found = mount.families.get(cwd) ?? await mount.familyList({ cwd })
880
+ addLocal(mount.fiber.ctx, null, found, mount)
881
+ }
882
+ }
883
+ for (const [key, { skill, local }] of entries) {
884
+ if (local && !skill.family && winners.get(skill.name) !== key && nested.has(JSON.stringify([skill.source, skill.name, skill.path]))) entries.delete(key)
885
+ }
886
+ if (!complete) warnings.push('部分技能目录暂时无法完整读取,请刷新重试。')
887
+ for (const dir of directories) {
888
+ if (dir.kind === 'custom' && !dir.exists) warnings.push(`自定义目录暂时无法访问:${dir.path}`)
889
+ }
890
+ const items = await Promise.all([...entries].map(async ([key, entry]) => {
891
+ const { skill, local, dir } = entry
892
+ const { path, info } = await publishedSkillFile(skill) ?? { path: null, info: null }
893
+ const editable = await editableFile(dir, local?.candidate.locator.path, path, local?.candidate.family)
894
+ const effective = winners.get(skill.name) === key
895
+ const excludedHere = excluded.has(skill.name)
896
+ const enabled = skill.invocation?.modelInvocable === true && !excludedHere && !invocationUnavailable
897
+ const source = sourceCategory(skill, local, dir, snapshot.cards)
898
+ let reason = toggleReason(source, enabled, excludedHere, editable, effective)
899
+ if (!excludedHere && local?.candidate.family?.enabled === false) reason = '所属工具包已停用。启用工具包后可使用成员原有的调用设置。'
900
+ if (invocationUnavailable) reason = '当前模式未提供技能调用功能。仍可浏览技能说明。'
901
+ entry.item = {
902
+ id: key, name: skill.name, description: skill.description, whenToUse: skill.whenToUse ?? null,
903
+ category: skill.metadata?.experimental === true ? 'experimental' : source, package: null,
904
+ provider: skill.provider, source: skill.source, path,
905
+ directoryPath: skill.resourceBase?.kind === 'directory' ? skill.resourceBase.path : path ? dirname(path) : null,
906
+ sourceDirectoryPath: dir?.path ?? null,
907
+ resourceBase: skill.resourceBase ?? null, directoryId: dir?.id ?? null, updatedAt: info?.mtimeMs ?? null,
908
+ invocation: skill.invocation, enabled, canToggle: reason === null, toggleReason: reason,
909
+ ...(entry.groupedProvider && !excludedHere && { manualCommand: `/pstack ${skill.name}` }),
910
+ ...(invocationUnavailable ? { invocationAvailable: false } : {}),
911
+ effective, excluded: excludedHere, shadowedBy: effective ? null : winners.get(skill.name) ?? null,
912
+ }
913
+ return entry.item
914
+ }))
915
+ await attachPackages([...entries.values()], cwd, referenceCache)
916
+ const reserved = providedRemovalRoots(ctx, roots.reserved)
917
+ const packageRemovals = await attachRemoval([...entries.values()], directories, reserved, cwd)
918
+ items.sort((a, b) => a.name.localeCompare(b.name) || Number(b.effective) - Number(a.effective) || a.id.localeCompare(b.id))
919
+ return { entries, packageRemovals, output: { items, directories, cwd, complete, warnings, mode } }
920
+ }
921
+
922
+ function flagValue(value) {
923
+ if (value === undefined) return false
924
+ const text = typeof value === 'string' ? value.toLowerCase() : value
925
+ if (text === true || text === 1) return true
926
+ if (text === false || text === 0) return false
927
+ if (['true', 'yes', 'on', '1'].includes(text)) return true
928
+ if (['false', 'no', 'off', '0'].includes(text)) return false
929
+ throw new Error('技能调用字段已经改变,请检查 YAML 后刷新。')
930
+ }
931
+
932
+ // Replace only the value's YAML token. Preserve the body, comments, line
933
+ // endings, other frontmatter and any user-invocable setting byte-for-byte.
934
+ function withInvocation(raw, expectedName, enabled) {
935
+ const opening = /^---\r?\n/.exec(raw)
936
+ const closing = /^---\r?$/gm
937
+ if (!opening) throw new Error('技能文件缺少 YAML 元信息。')
938
+ closing.lastIndex = opening[0].length
939
+ const end = closing.exec(raw)
940
+ if (!end) throw new Error('技能文件的 YAML 元信息不完整。')
941
+ const prefix = opening[0]
942
+ const header = raw.slice(prefix.length, end.index)
943
+ const doc = yaml.parseDocument(header)
944
+ if (doc.errors.length || !yaml.isMap(doc.contents)) throw new Error('无法解析技能文件的 YAML 元信息。')
945
+ const data = doc.toJS()
946
+ if (data.name !== expectedName) throw new Error('技能名称已经改变,请刷新后再试。')
947
+ if (flagValue(data[FLAG]) === !enabled) return raw
948
+ const value = String(!enabled)
949
+ const pair = doc.contents.items.find(pair => pair.key?.value === FLAG)
950
+ let next
951
+ if (pair) {
952
+ const node = pair.value
953
+ if (!(yaml.isScalar(node) || yaml.isAlias(node)) || !node.range) throw new Error('无法独立编辑技能的调用字段。')
954
+ const [from, to] = node.range
955
+ const token = header.slice(from, to)
956
+ let updated = value
957
+ if (node.type === 'QUOTE_DOUBLE') updated = `"${value}"`
958
+ if (node.type === 'QUOTE_SINGLE') updated = `'${value}'`
959
+ if (node.type === 'BLOCK_FOLDED' || node.type === 'BLOCK_LITERAL') {
960
+ updated = token.replace(/(\n[ \t]*)(true|false|yes|no|on|off|1|0)(?=[ \t\r\n]*$)/i, `$1${value}`)
961
+ }
962
+ next = header.slice(0, from) + updated + header.slice(to)
963
+ } else {
964
+ const start = doc.contents.range[0]
965
+ const indent = header.slice(header.lastIndexOf('\n', start - 1) + 1, start)
966
+ if (doc.contents.flow) next = header.slice(0, start + 1) + `${FLAG}: ${value}, ` + header.slice(start + 1)
967
+ else if (/^ *$/.test(indent)) next = header.slice(0, start) + `${FLAG}: ${value}` + prefix.slice(3) + indent + header.slice(start)
968
+ else throw new Error('无法安全插入技能的调用字段。')
969
+ }
970
+ const checked = yaml.parse(next)
971
+ const before = { ...data }
972
+ const after = { ...checked }
973
+ delete before[FLAG]
974
+ delete after[FLAG]
975
+ if (checked[FLAG] === undefined || flagValue(checked[FLAG]) !== !enabled || !isDeepStrictEqual(before, after)) {
976
+ throw new Error('调用字段与其他 YAML 字段共用值,无法单独修改。')
977
+ }
978
+ return prefix + next + raw.slice(end.index)
979
+ }
980
+
981
+ async function updateSettingFile(locate, lockName, change) {
982
+ const first = await locate()
983
+ if (!first) throw new Error('技能文件已经移动或不可写,请刷新后再试。')
984
+ await withSkillWriteLock(first.lockRoot ?? first.root, first.lockName ?? lockName, async () => {
985
+ const target = await locate()
986
+ if (!target || target.path !== first.path || target.root !== first.root) throw new Error('技能目录已经改变,请刷新后再试。')
987
+ const file = await open(target.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0))
988
+ let original, info
989
+ try {
990
+ info = await file.stat({ bigint: true })
991
+ if (!info.isFile()) throw new Error('技能文件已经改变,请刷新后再试。')
992
+ original = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(await file.readFile())
993
+ } finally { await file.close() }
994
+ const next = change(original)
995
+ if (next === original) return
996
+ const temp = join(dirname(target.path), `.dsh-skill-${randomUUID()}.tmp`)
997
+ const mode = Number(info.mode & 0o7777n)
998
+ const staged = await open(temp, 'wx', 0o600)
999
+ try {
1000
+ try { await staged.writeFile(next); await staged.chmod(mode) } finally { await staged.close() }
1001
+ const [current, destination] = await Promise.all([lstat(target.path, { bigint: true }), locate()])
1002
+ if (destination?.path !== target.path || current.dev !== info.dev || current.ino !== info.ino || current.ctimeNs !== info.ctimeNs) {
1003
+ throw new Error('技能文件在编辑期间发生改变,请刷新后再试。')
1004
+ }
1005
+ await rename(temp, target.path)
1006
+ } finally { await unlink(temp).catch(error => { if (!missing(error)) throw error }) }
1007
+ })
1008
+ }
1009
+
1010
+ async function changeInvocation(entry, enabled) {
1011
+ if (typeof enabled !== 'boolean') throw new Error('启用状态必须是布尔值。')
1012
+ if (!entry.item.canToggle) throw new Error(entry.item.toggleReason)
1013
+ const { dir, local, item } = entry
1014
+ const locate = () => editableFile(dir, local.candidate.locator.path, item.path, local.candidate.family)
1015
+ await updateSettingFile(locate, item.name, original => withInvocation(original, item.name, enabled))
1016
+ }
1017
+
1018
+ // Publish a complete first marker without ever replacing an existing path.
1019
+ // Recheck the directory identity and membership under the same import lock.
1020
+ async function createPackageMarker(entry, cwd, refresh) {
1021
+ const { family } = entry.local.candidate
1022
+ const location = await editableMarker(entry.dir, family, cwd)
1023
+ if (!location) throw new Error('工具包根目录已改变或不可写,请刷新后再试。')
1024
+ await withSkillWriteLock(location.lockRoot, location.lockName, async () => {
1025
+ const info = await lstat(location.root, { bigint: true })
1026
+ const fresh = await refresh()
1027
+ const verified = fresh?.local?.candidate.family
1028
+ if (!verified || !isDeepStrictEqual(verified.markerTemplate, family.markerTemplate) || !await editableMarker(fresh.dir, verified, cwd)) {
1029
+ throw new Error('工具包的成员或目录已经改变,请刷新后再试。')
1030
+ }
1031
+ const text = `${JSON.stringify({ ...verified.markerTemplate, enabled: false }, null, 2)}\n`
1032
+ parseFamilyMarker(text)
1033
+ const temp = join(location.root, `.dsh-skill-${randomUUID()}.tmp`)
1034
+ const file = await open(temp, 'wx', 0o600)
1035
+ try {
1036
+ try { await file.writeFile(text) } finally { await file.close() }
1037
+ const current = await lstat(location.root, { bigint: true })
1038
+ if (info.dev !== current.dev || info.ino !== current.ino || await realpath(location.root) !== location.root) {
1039
+ throw new Error('工具包的目录已经改变,请刷新后再试。')
1040
+ }
1041
+ await link(temp, location.path)
1042
+ } finally { await unlink(temp).catch(error => { if (!missing(error)) throw error }) }
1043
+ })
1044
+ }
1045
+
1046
+ function warnOverrides(items, output) {
1047
+ const winners = new Map(output.items.map(item => [item.id, item]))
1048
+ for (const item of items) {
1049
+ if (!item.shadowedBy) continue
1050
+ const winner = winners.get(item.shadowedBy)
1051
+ output.warnings.push(`技能 ${item.name} 已导入。技能目录优先使用同名技能 ${winner?.path || winner?.provider || ''}。`)
1052
+ }
1053
+ }
1054
+
1055
+ export function createLibrary(ctx, config = ctx.fiber.effectiveConfig) {
1056
+ const mounts = mountDirectories(ctx, config)
1057
+ const referenceCache = new Map()
1058
+ async function withView(cwd, agent, action) {
1059
+ if (typeof cwd !== 'string' || !isAbsolute(cwd)) throw new Error('无法确定当前工作目录。')
1060
+ if (isManagementSelection(agent)) {
1061
+ return withManagementScope(agent, management => action(resolve(cwd), undefined, management.mode,
1062
+ { registry: ctx.skills, tools: ctx.get('tools'), management }))
1063
+ }
1064
+ const presets = ctx.get('agentPresets')
1065
+ const cold = agent && coldPreset in agent
1066
+ const live = cold ? undefined : agent
1067
+ const mode = { id: null, source: agent ? 'session' : 'default' }
1068
+ let lease
1069
+ if (live?.ctx) mode.id = presets?.composedPreset?.(live.ctx) ?? null
1070
+ if (cold) mode.id = agent[coldPreset]
1071
+ if (!agent && presets?.resolve) {
1072
+ try {
1073
+ const preset = await presets.resolve()
1074
+ mode.id = preset.id
1075
+ if (typeof preset.name === 'string' && preset.name.trim()) mode.name = preset.name
1076
+ } catch (error) {
1077
+ if (!['agent-preset/no-default', 'agent-preset/not-found', 'agent-preset/invalid'].includes(error.code)) throw error
1078
+ }
1079
+ }
1080
+ if (mode.id && !mode.name && !['standard', 'cordis', 'minimal'].includes(mode.id) && presets?.readDocument) {
1081
+ try {
1082
+ const { name } = await presets.readDocument(mode.id)
1083
+ if (typeof name === 'string' && name.trim()) mode.name = name
1084
+ } catch (error) { if (error.code !== 'agent-preset/not-found') throw error }
1085
+ }
1086
+ if (!live && (mode.id !== null || (!agent && presets && !presets.resolve))) {
1087
+ if (!presets) throw problem('SESSION_MODE_UNAVAILABLE', '主机无法读取所选会话的模式。')
1088
+ try { lease = await presets.acquireScope(mode.id ?? undefined) }
1089
+ catch (error) {
1090
+ if (['agent-preset/not-found', 'agent-preset/invalid', 'agent-preset/no-default'].includes(error.code)) {
1091
+ throw problem('SESSION_MODE_UNAVAILABLE', '无法加载当前模式的技能目录,请刷新后重试。')
1092
+ }
1093
+ throw error
1094
+ }
1095
+ }
1096
+ try {
1097
+ const registry = (live?.ctx && presets?.serviceFor?.(live, 'skills')) || ctx.skills
1098
+ const tools = (live?.ctx && presets?.serviceFor?.(live, 'tools')) || ctx.get('tools')
1099
+ return await action(resolve(cwd), live ?? lease?.key, mode, { registry, tools })
1100
+ }
1101
+ finally { await lease?.[Symbol.asyncDispose]() }
1102
+ }
1103
+ function filesystemFibers(scope, { management }) {
1104
+ if (!management) return visibleFibers(ctx, filesystem.name, scope)
1105
+ return [...new Set(management.scopes.flatMap(({ scope }) => visibleFibers(ctx, filesystem.name, scope)))]
1106
+ }
1107
+ function invalidate(scope, { management }) {
1108
+ if (!management) return mounts.invalidate(scope)
1109
+ for (const scoped of management.scopes) mounts.invalidate(scoped.scope)
1110
+ }
1111
+ async function view(cwd, scope, mode, { registry, tools, management }) {
1112
+ if (!management) return scan(ctx, mounts, config, cwd, scope, referenceCache, mode, registry, tools)
1113
+ const views = []
1114
+ for (const scoped of management.scopes) {
1115
+ management.signal?.throwIfAborted()
1116
+ views.push({ ...await scan(ctx, mounts, config, cwd, scoped.scope, referenceCache, scoped.mode, registry, tools), ...scoped })
1117
+ }
1118
+ management.signal?.throwIfAborted()
1119
+ const result = mergeManagementViews(views, management)
1120
+ if (views.length > 1) {
1121
+ // Validate the union for nested directories and definitions that only another mode exposes.
1122
+ result.packageRemovals = await attachRemoval([...result.entries.values()], result.output.directories,
1123
+ providedRemovalRoots(ctx, []), cwd)
1124
+ }
1125
+ return result
1126
+ }
1127
+ async function catalog(cwd, scope, mode, services) { return (await view(cwd, scope, mode, services)).output }
1128
+ async function removalTarget(cwd, scope, mode, services, kind, key, signal) {
1129
+ signal?.throwIfAborted()
1130
+ invalidate(scope, services)
1131
+ const current = await view(cwd, scope, mode, services)
1132
+ const entry = current.entries.get(key)
1133
+ const packageRow = kind === 'package' && current.output.items.find(item => item.package?.id === key)?.package
1134
+ const target = kind === 'package' ? current.packageRemovals.get(key) : entry?.removal
1135
+ if (!target) throw problem('REMOVAL_NOT_ALLOWED', (kind === 'package' ? packageRow : entry?.item)?.removeReason ?? '当前技能库中找不到可移除的目标。')
1136
+ return inspectRemoval(target, { deep: true, signal })
1137
+ }
1138
+ async function removalResult(cwd, scope, mode, services, receipt) {
1139
+ try {
1140
+ invalidate(scope, services)
1141
+ return { receipt, snapshot: await catalog(cwd, scope, mode, services) }
1142
+ } catch { return { receipt, snapshot: null, warning: '文件操作已完成,技能列表暂时无法更新。请刷新技能列表和恢复记录。' } }
1143
+ }
1144
+ async function recoverySources(cwd, scope, services) {
1145
+ const { directories, reserved } = await directoriesFor(cwd, filesystemFibers(scope, services), configured(config))
1146
+ const withinBoundary = await removalBoundary(directories, providedRemovalRoots(ctx, reserved), cwd,
1147
+ path => canonicalizeWatchPath(path).catch(() => resolve(path)))
1148
+ return { directories: directories.filter(dir => removalSource(dir) && dir.exists && (dir.kind !== 'custom' || dir.writable)), withinBoundary }
1149
+ }
1150
+ function lookup(current, key) {
1151
+ const entry = current.entries.get(key)
1152
+ if (!entry) throw new Error('技能已移动或移除,请刷新列表。')
1153
+ return entry
1154
+ }
1155
+ async function saveDirectories(change) {
1156
+ const editor = ctx.get('configEditor')
1157
+ const entry = ctx.fiber.entry
1158
+ if (!editor || !entry) throw new Error('当前配置环境无法保存自定义目录。')
1159
+ await editor.edit(entry, current => {
1160
+ const dirs = current.customDirectories ?? []
1161
+ if (!Array.isArray(dirs)) throw new Error('自定义目录使用配置表达式,请先在插件设置中修改。')
1162
+ return { ...current, customDirectories: change(dirs) }
1163
+ })
1164
+ mounts.reconcile()
1165
+ }
1166
+ return {
1167
+ list(cwd, agent) { return withView(cwd, agent, catalog) },
1168
+ creatorPreset(cwd, selection) { return creatorPreset(ctx, cwd, selection) },
1169
+ refresh(cwd, agent) {
1170
+ return withView(cwd, agent, (cwd, scope, mode, services) => { invalidate(scope, services); return catalog(cwd, scope, mode, services) })
1171
+ },
1172
+ async modelCatalog(cwd, agent, { refresh = false, signal } = {}) {
1173
+ if (!agent || typeof cwd !== 'string' || !isAbsolute(cwd)) throw new Error('无法确定会话技能的作用域。')
1174
+ signal?.throwIfAborted()
1175
+ if (refresh) mounts.invalidate(agent)
1176
+ const { skills, complete } = await ctx.skills.snapshot({ cwd, scope: agent, signal })
1177
+ const excluded = excludedSkills(ctx, agent)
1178
+ return { complete, skills: skills.filter(skill => skill.invocation?.modelInvocable === true && !excluded.has(skill.name))
1179
+ .map(({ name, description }) => ({ name, description })) }
1180
+ },
1181
+ targets(cwd, agent) {
1182
+ return withView(cwd, agent, async (cwd, scope, _mode, services) => {
1183
+ const fibers = filesystemFibers(scope, services)
1184
+ return (await directoriesFor(cwd, fibers, configured(config))).directories.filter(dir => dir.writable)
1185
+ })
1186
+ },
1187
+ detail(cwd, key, agent) {
1188
+ return withView(cwd, agent, async (cwd, scope, mode, services) => {
1189
+ const current = await view(cwd, scope, mode, services)
1190
+ const { item, local, groupedProvider, skill: candidate, origin = { item, scope } } = lookup(current, key)
1191
+ let skill
1192
+ if (origin.item.effective) skill = await services.registry.get(item.name, { cwd, scope: origin.scope })
1193
+ else if (local?.candidate.family) skill = await getFamily(local.ctx, local.candidate, { cwd }, filesystem)
1194
+ else if (local) {
1195
+ const provider = reader(local.ctx, local.config)
1196
+ try { skill = await provider.get(local.candidate, { cwd }) } finally { await provider.dispose() }
1197
+ } else if (groupedProvider) skill = await groupedProvider.get(candidate, { cwd, scope: origin.scope })
1198
+ if (!skill || skillId(skill) !== key) throw new Error('技能内容已经改变,请刷新列表。')
1199
+ return { ...item, mode, ...(services.management && { modes: current.output.modes }),
1200
+ content: skill.content, metadata: skill.metadata ?? {}, whenToUse: skill.whenToUse ?? null }
1201
+ })
1202
+ },
1203
+ prepareRemoval(cwd, kind, key, agent, signal) {
1204
+ return withView(cwd, agent, (cwd, scope, mode, services) => removalTarget(cwd, scope, mode, services, kind, key, signal))
1205
+ },
1206
+ commitRemoval(cwd, plan, agent, signal) {
1207
+ return withView(cwd, agent, async (cwd, scope, mode, services) => {
1208
+ const receipt = await removeSkill(plan, () => removalTarget(cwd, scope, mode, services, plan.kind, plan.id, signal).catch(error => {
1209
+ if (error.code === 'REMOVAL_NOT_ALLOWED') throw problem('TARGET_CHANGED', '原技能已改变,请刷新后重新确认。')
1210
+ throw error
1211
+ }), signal)
1212
+ return removalResult(cwd, scope, mode, services, receipt)
1213
+ })
1214
+ },
1215
+ listRemovals(cwd, agent, signal) {
1216
+ return withView(cwd, agent, async (cwd, scope, _mode, services) => listRemovedSkills(await recoverySources(cwd, scope, services), signal))
1217
+ },
1218
+ restoreRemoval(cwd, id, agent, signal) {
1219
+ return withView(cwd, agent, async (cwd, scope, mode, services) => {
1220
+ const receipt = await restoreSkill(() => recoverySources(cwd, scope, services), id, signal)
1221
+ return removalResult(cwd, scope, mode, services, receipt)
1222
+ })
1223
+ },
1224
+ setEnabled(cwd, key, enabled, agent) {
1225
+ return withView(cwd, agent, async (cwd, scope, mode, services) => {
1226
+ await changeInvocation(lookup(await view(cwd, scope, mode, services), key), enabled)
1227
+ invalidate(scope, services)
1228
+ return catalog(cwd, scope, mode, services)
1229
+ })
1230
+ },
1231
+ setPackageEnabled(cwd, key, enabled, agent) {
1232
+ if (typeof enabled !== 'boolean') throw new Error('启用状态必须是布尔值。')
1233
+ return withView(cwd, agent, async (cwd, scope, mode, services) => {
1234
+ const current = await view(cwd, scope, mode, services)
1235
+ const entry = [...current.entries.values()].find(entry => {
1236
+ const pkg = (entry.origin?.item ?? entry.item).package
1237
+ return pkg?.id === key && pkg.canToggle
1238
+ })
1239
+ if (!entry) throw new Error('找不到可更改启用状态的本地工具包。')
1240
+ const family = entry.local.candidate.family
1241
+ const members = current.output.items.filter(item => item.package?.id === key)
1242
+ if (!family.markerId) {
1243
+ if (enabled) return current.output
1244
+ await createPackageMarker(entry, cwd, async () => {
1245
+ invalidate(scope, services)
1246
+ return (await view(cwd, scope, mode, services)).entries.get(entry.item.id)
1247
+ })
1248
+ invalidate(scope, services)
1249
+ return catalog(cwd, scope, mode, services)
1250
+ }
1251
+ const locate = () => editableMarker(entry.dir, family, cwd)
1252
+ await updateSettingFile(locate, family.markerId, original => {
1253
+ const data = parseFamilyMarker(original)
1254
+ if (data.id !== family.markerId || data.members.length !== members.length || !data.members.every(member =>
1255
+ members.some(item => item.name === member.name && item.path === join(family.root, member.entry)))) {
1256
+ throw new Error('工具包信息已经改变,请刷新后再试。')
1257
+ }
1258
+ return data.enabled === enabled ? original : `${JSON.stringify({ ...data, enabled }, null, 2)}\n`
1259
+ })
1260
+ invalidate(scope, services)
1261
+ return catalog(cwd, scope, mode, services)
1262
+ })
1263
+ },
1264
+ addDirectory(cwd, input, label, agent) {
1265
+ if (label && typeof label === 'object' && agent === undefined) { agent = label; label = undefined }
1266
+ return withView(cwd, agent, async (cwd, scope, mode, services) => {
1267
+ if (typeof input !== 'string' || !input.trim() || !isAbsolute(expandHomePath(input.trim()))) throw new Error('请输入有效的绝对目录路径。')
1268
+ if (label !== undefined && typeof label !== 'string') throw new Error('目录名称必须是文本。')
1269
+ const path = await realpath(expandHomePath(input.trim())).catch(() => { throw new Error('目录不存在或无法访问。') })
1270
+ if (!(await stat(path)).isDirectory()) throw new Error('请选择文件夹。')
1271
+ await access(path, constants.R_OK | constants.X_OK)
1272
+ const { reserved, directories } = await directoriesFor(cwd, filesystemFibers(scope, services), configured(config))
1273
+ const protectedRoots = [...reserved, ...directories.filter(dir => !dir.removable).map(dir => dir.path)]
1274
+ const canonical = await Promise.all(protectedRoots.map(path => canonicalizeWatchPath(path).catch(() => path)))
1275
+ if (canonical.includes(path)) throw new Error('DSH 已经在扫描此目录。')
1276
+ const row = { path, label: label?.trim() || basename(path) || path }
1277
+ await saveDirectories(dirs => dirs.some(dir => dir.path === path) ? dirs : [...dirs, row])
1278
+ return catalog(cwd, scope, mode, services)
1279
+ })
1280
+ },
1281
+ removeDirectory(cwd, key, agent) {
1282
+ return withView(cwd, agent, async (cwd, scope, mode, services) => {
1283
+ const { directories } = await directoriesFor(cwd, filesystemFibers(scope, services), configured(config))
1284
+ const dir = directories.find(dir => dir.id === key)
1285
+ if (!dir) {
1286
+ if (typeof key === 'string' && key.startsWith('dir-custom-')) return catalog(cwd, scope, mode, services)
1287
+ throw new Error('找不到这个自定义目录。')
1288
+ }
1289
+ if (!dir.removable) throw new Error('仅可移除自定义目录。')
1290
+ await saveDirectories(dirs => dirs.filter(row => row.path !== dir.path))
1291
+ return catalog(cwd, scope, mode, services)
1292
+ })
1293
+ },
1294
+ imported(cwd, receipt, enabled, agent) {
1295
+ return withView(cwd, agent, async (cwd, scope, mode, services) => {
1296
+ if (!receipt || typeof receipt.path !== 'string' || !isAbsolute(receipt.path)) throw new Error('导入结果缺少有效的技能文件路径。')
1297
+ invalidate(scope, services)
1298
+ const current = await view(cwd, scope, mode, services)
1299
+ if (receipt.family) {
1300
+ if (!isAbsolute(receipt.familyRoot ?? '') || !Array.isArray(receipt.members) || !receipt.members.length) throw new Error('导入结果缺少工具包及成员的有效路径。')
1301
+ const root = await realpath(receipt.familyRoot)
1302
+ const key = id('package', root, receipt.family.id)
1303
+ const visible = current.output.items.filter(item => item.package?.id === key && item.directoryId === receipt.directoryId)
1304
+ const importedItems = await Promise.all(receipt.members.map(async member => {
1305
+ const path = typeof member.path === 'string' && isAbsolute(member.path) && await realpath(member.path)
1306
+ const matched = visible.find(item => item.path === path && item.name === member.name)
1307
+ if (!matched || !relativeChild(root, path)) throw new Error(`工具包已写入,但当前预设尚未发现成员 ${member.name}。请刷新后重试。`)
1308
+ return matched
1309
+ }))
1310
+ if (new Set(importedItems).size !== visible.length || importedItems.length !== visible.length) throw new Error('工具包的成员清单已经改变,请刷新后再试。')
1311
+ warnOverrides(importedItems, current.output)
1312
+ return { ...current.output, importedItems, importedItem: importedItems[0], importedPackage: importedItems[0].package }
1313
+ }
1314
+ const path = await realpath(receipt.path)
1315
+ const candidates = [...current.entries.values()].filter(({ item }) => item.name === receipt.name && item.directoryId === receipt.directoryId && item.path)
1316
+ let entry
1317
+ for (const candidate of candidates) {
1318
+ if (await realpath(candidate.item.path).catch(() => null) === path) { entry = candidate; break }
1319
+ }
1320
+ if (!entry) throw new Error(`技能已写入 ${receipt.path},但当前预设尚未发现它。请检查目录后刷新。`)
1321
+ let output = current.output
1322
+ if (enabled !== undefined && enabled !== entry.item.invocation?.modelInvocable) {
1323
+ await changeInvocation(entry, enabled)
1324
+ invalidate(scope, services)
1325
+ output = await catalog(cwd, scope, mode, services)
1326
+ }
1327
+ const item = output.items.find(item => item.id === entry.item.id)
1328
+ if (!item) throw new Error('技能已写入,但文件在更新期间发生变化,请刷新后重试。')
1329
+ warnOverrides([item], output)
1330
+ return { ...output, importedItem: item }
1331
+ })
1332
+ },
1333
+ }
1334
+ }