@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
@@ -0,0 +1,247 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { link, lstat, mkdir, opendir, realpath, rename, rm, rmdir, writeFile } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { deriveFamily, FAMILY_MARKER, prepareFamily } from './import-family.mjs'
5
+ import { publishFamily } from './import-native.mjs'
6
+ import { checkSize, limits, parseSkillMetadata, problem, readFolder, readRegular, statOrNull } from './import-files.mjs'
7
+
8
+ const inFlight = new Map()
9
+ const occupied = message => problem('TARGET_OCCUPIED', message)
10
+
11
+ async function targetRoot(directory) {
12
+ if (!directory || typeof directory.id !== 'string' || !directory.id || typeof directory.path !== 'string' || !path.isAbsolute(directory.path) || directory.writable === false) {
13
+ throw problem('INVALID_TARGET', '请选择已登记且可写的技能目录。')
14
+ }
15
+ let stat = await statOrNull(directory.path)
16
+ if (!stat && directory.kind === 'personal' && directory.writable === true) {
17
+ await mkdir(directory.path, { recursive: true })
18
+ stat = await lstat(directory.path)
19
+ }
20
+ if (!stat?.isDirectory()) throw problem('INVALID_TARGET', '目标目录已变化,请刷新技能目录。')
21
+ return { root: await realpath(directory.path), dev: stat.dev, ino: stat.ino }
22
+ }
23
+
24
+ async function verifyRoot(directory, anchor) {
25
+ const stat = await statOrNull(directory.path)
26
+ if (!stat?.isDirectory() || stat.dev !== anchor.dev || stat.ino !== anchor.ino || await realpath(directory.path) !== anchor.root) {
27
+ throw problem('INVALID_TARGET', '存放目录已变化,请重新选择。')
28
+ }
29
+ }
30
+
31
+ async function instructionAt(target) {
32
+ try {
33
+ const actual = await realpath(target)
34
+ const stat = await lstat(actual)
35
+ if (stat.isDirectory()) {
36
+ const entry = path.join(actual, 'SKILL.md')
37
+ return { entry: await realpath(entry), directory: true }
38
+ }
39
+ if (stat.isFile() && target.endsWith('.md')) return { entry: actual, directory: false }
40
+ } catch (error) {
41
+ if (!['ENOENT', 'ENOTDIR', 'ELOOP'].includes(error.code)) throw error
42
+ }
43
+ return null
44
+ }
45
+
46
+ async function fingerprint(target, directory, records) {
47
+ const info = await lstat(target)
48
+ const digest = createHash('sha256').update(`${info.dev}/${info.ino}\0`)
49
+ if (directory) {
50
+ const contents = records ?? await readFolder(target, { previous: true })
51
+ for (const record of contents.toSorted((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)) {
52
+ digest.update(JSON.stringify([record.path, record.directory, record.executable, record.bytes?.length])).update('\0')
53
+ if (record.bytes) digest.update(record.bytes)
54
+ }
55
+ } else {
56
+ const { bytes, executable } = await readRegular(target, limits.file)
57
+ digest.update(executable ? 'x' : '-').update(bytes)
58
+ }
59
+ return digest.digest('hex')
60
+ }
61
+
62
+ async function existingSkill(root, desired, name) {
63
+ const matches = []
64
+ let count = 0
65
+ for await (const item of await opendir(root)) {
66
+ checkSize(++count, limits.rootEntries)
67
+ const target = path.join(root, item.name)
68
+ if (!item.isDirectory() && !item.isSymbolicLink() && !item.name.endsWith('.md')) continue
69
+ const located = await instructionAt(target)
70
+ if (!located) continue
71
+ const instruction = await statOrNull(located.entry)
72
+ if (!instruction?.isFile()) continue
73
+ let metadata
74
+ try { metadata = parseSkillMetadata((await readRegular(located.entry, limits.header, true)).bytes.toString('utf8')) } catch (error) {
75
+ if (error.code === 'INVALID_SKILL' || error.code === 'ENOENT') continue
76
+ throw error
77
+ }
78
+ if (metadata.name !== name) continue
79
+ if (item.isSymbolicLink() || (located.directory && located.entry !== path.join(target, 'SKILL.md'))) {
80
+ throw occupied(`同名技能使用了符号链接,请在目录中手动处理:${target}`)
81
+ }
82
+ if (located.directory && await statOrNull(path.join(target, FAMILY_MARKER))) throw occupied(`同名技能属于已保存的工具包:${target}`)
83
+ matches.push({ path: target, ...located })
84
+ }
85
+ const selected = matches[0]
86
+ if (matches.length > 1) throw occupied(`此目录中有多个名为 ${name} 的技能,请先处理重复项。`)
87
+ if (await statOrNull(desired) && selected?.path !== desired) throw occupied(`目标路径已被其他文件或目录占用:${desired}`)
88
+ if (!selected) return null
89
+ try {
90
+ if (selected.directory) {
91
+ const records = await readFolder(selected.path, { previous: true })
92
+ if (deriveFamily(records, { sourceName: path.basename(selected.path) })) throw occupied('同名技能属于多成员工具包。')
93
+ return { ...selected, signature: await fingerprint(selected.path, true, records) }
94
+ }
95
+ return { ...selected, signature: await fingerprint(selected.path, false) }
96
+ } catch (error) {
97
+ throw occupied(`无法安全替换现有技能 ${selected.path}。${error.message}`)
98
+ }
99
+ }
100
+
101
+ async function existingFamily(target, snapshot) {
102
+ const stat = await statOrNull(target)
103
+ if (!stat) return null
104
+ if (!stat.isDirectory() || await realpath(target) !== target) throw occupied(`工具包保存位置已被占用:${target}`)
105
+ try {
106
+ const records = await readFolder(target, { previous: true })
107
+ const family = deriveFamily(records, { sourceName: path.basename(target) })
108
+ const managed = records.some(record => record.path === FAMILY_MARKER)
109
+ const sharedMember = family?.members.some(old => snapshot.members.some(next => old.name === next.name))
110
+ if (!family || family.id !== snapshot.family.id || (!managed && !sharedMember)) throw occupied('目录中已有其他内容。')
111
+ return { path: target, entry: target, directory: true, family, signature: await fingerprint(target, true, records) }
112
+ } catch (error) {
113
+ throw occupied(`无法安全替换现有目录 ${target}。${error.message}`)
114
+ }
115
+ }
116
+
117
+ function requireConfirmation(state, existing, directory, anchor, replace, targetPath) {
118
+ if (!existing) {
119
+ state.confirmation = null
120
+ if (replace) throw problem('TARGET_CHANGED', '原有技能已移除,请重新确认导入位置。')
121
+ return
122
+ }
123
+ const signature = JSON.stringify([directory.id, anchor.root, anchor.dev, anchor.ino, existing.path, existing.signature])
124
+ if (!replace || state.confirmation !== signature) {
125
+ state.confirmation = signature
126
+ const subject = existing.family ? `工具包(${existing.family.members.length} 个成员)` : '技能'
127
+ const message = existing.entry === targetPath ? `目标目录已有同名${subject},替换将更新 ${existing.entry}。` : `同名${subject}位于 ${existing.entry}。替换后将保存到 ${targetPath}。`
128
+ throw problem('CONFLICT', message, { existingPath: existing.entry, targetPath })
129
+ }
130
+ }
131
+
132
+ async function stagePackage(payload, snapshot) {
133
+ if (snapshot.format === 'markdown') {
134
+ await writeFile(payload, snapshot.records[0].bytes, { flag: 'wx', mode: 0o644 })
135
+ return
136
+ }
137
+ await mkdir(payload, { mode: 0o755 })
138
+ for (const record of snapshot.records) {
139
+ const target = path.join(payload, record.path)
140
+ if (record.directory) await mkdir(target, { mode: 0o755 })
141
+ else await writeFile(target, record.bytes, { flag: 'wx', mode: record.executable ? 0o755 : 0o644 })
142
+ }
143
+ }
144
+
145
+ // link(2) fails on every existing file. On POSIX, reserve an empty directory
146
+ // exclusively first, since rename(2) by itself would replace someone else's
147
+ // empty directory. Windows refuses to rename a directory over any other entry.
148
+ async function publish(source, destination, directory) {
149
+ if (!directory) { await link(source, destination); return }
150
+ if (process.platform === 'win32') { await rename(source, destination); return }
151
+ await mkdir(destination, { mode: 0o700 })
152
+ const placeholder = await lstat(destination)
153
+ try { await rename(source, destination) } catch (error) {
154
+ const stat = await statOrNull(destination)
155
+ if (stat?.dev === placeholder.dev && stat.ino === placeholder.ino) await rmdir(destination).catch(() => {})
156
+ throw error
157
+ }
158
+ }
159
+
160
+ async function transaction(snapshot, state, directory, anchor, replace, work, enabled) {
161
+ const { root } = anchor
162
+ const targetPath = path.join(root, snapshot.targetRelativePath)
163
+ const flat = snapshot.format === 'markdown'
164
+ const isFamily = snapshot.kind === 'family'
165
+ const destination = flat || isFamily ? targetPath : path.dirname(targetPath)
166
+ const inspectTarget = () => isFamily ? existingFamily(destination, snapshot) : existingSkill(root, destination, snapshot.name)
167
+ const payload = path.join(work, 'payload'), backup = path.join(work, 'previous')
168
+ let moved
169
+ try {
170
+ await verifyRoot(directory, anchor)
171
+ let existing = await inspectTarget()
172
+ requireConfirmation(state, existing, directory, anchor, replace, targetPath)
173
+ const saved = isFamily ? prepareFamily(snapshot, existing?.family, enabled) : snapshot
174
+ await stagePackage(payload, saved)
175
+ await verifyRoot(directory, anchor)
176
+ existing = await inspectTarget()
177
+ requireConfirmation(state, existing, directory, anchor, replace, targetPath)
178
+ const receipt = { name: snapshot.name, path: targetPath, directoryId: directory.id, format: snapshot.format, sourceLabel: snapshot.sourceLabel, sourcePath: snapshot.sourcePath, replaced: Boolean(existing) }
179
+ if (isFamily) {
180
+ await publishFamily(payload, destination, Boolean(existing))
181
+ if (existing) {
182
+ try {
183
+ if (await fingerprint(payload, true) !== existing.signature) throw problem('TARGET_CHANGED', '原有工具包已变化,请重新确认替换。')
184
+ } catch (error) {
185
+ try { await publishFamily(payload, destination, true) } catch {
186
+ throw problem('RECOVERY_REQUIRED', `原工具包保留在 ${payload},请恢复后重试。`, { backupPath: payload, cause: error })
187
+ }
188
+ throw error
189
+ }
190
+ }
191
+ const members = saved.members.map(member => ({ ...member, path: path.join(destination, member.entry) }))
192
+ return { ...receipt, kind: 'family', enabled: saved.family.enabled, familyRoot: destination, path: path.join(destination, saved.entry), family: { ...saved.family, members }, members }
193
+ }
194
+ if (existing) {
195
+ await rename(existing.path, backup)
196
+ moved = existing
197
+ if (await fingerprint(backup, existing.directory) !== existing.signature) throw problem('TARGET_CHANGED', '原有技能已变化,请重新确认替换。')
198
+ }
199
+ await publish(payload, destination, !flat)
200
+ return receipt
201
+ } catch (error) {
202
+ if (moved) {
203
+ try { await publish(backup, moved.path, moved.directory) } catch {
204
+ throw problem('RECOVERY_REQUIRED', `原路径被占用,原技能保留在 ${backup}。`, { backupPath: backup, cause: error })
205
+ }
206
+ }
207
+ if (['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw occupied(`目标路径已变化,请重新检查:${destination}`)
208
+ throw error
209
+ }
210
+ }
211
+
212
+ async function locked(work, operation) {
213
+ try { await mkdir(work, { mode: 0o700 }) } catch (error) {
214
+ if (error.code === 'EEXIST') throw problem('IMPORT_BUSY', `此技能已有写入事务。请稍后重试;中断事务保存在 ${work}。`)
215
+ throw error
216
+ }
217
+ const marker = await lstat(work)
218
+ let result, failure
219
+ try { result = await operation(work) } catch (error) { failure = error }
220
+ // Only remove our transaction, never a path swapped in by another writer.
221
+ const current = await statOrNull(work)
222
+ if (failure?.code !== 'RECOVERY_REQUIRED' && current?.dev === marker.dev && current.ino === marker.ino) {
223
+ try { await rm(work, { recursive: true }) } catch (error) {
224
+ if (result && typeof result === 'object') result.warning = `技能已写入,事务目录待清理:${work}`
225
+ else if (!failure) throw error
226
+ }
227
+ }
228
+ if (failure) throw failure
229
+ return result
230
+ }
231
+
232
+ /** Serialize import and invocation-policy edits for one name across Host instances. */
233
+ export async function withSkillWriteLock(root, name, operation) {
234
+ const canonical = await realpath(root)
235
+ const key = `${canonical}\0${name}`
236
+ const digest = createHash('sha256').update(name).digest('hex').slice(0, 24)
237
+ const work = path.join(canonical, `.dsh-skill-import-${digest}`)
238
+ const previous = inFlight.get(key) || Promise.resolve()
239
+ const pending = previous.catch(() => {}).then(() => locked(work, operation))
240
+ inFlight.set(key, pending)
241
+ try { return await pending } finally { if (inFlight.get(key) === pending) inFlight.delete(key) }
242
+ }
243
+
244
+ export async function commitPackage(snapshot, state, directory, replace, enabled) {
245
+ const anchor = await targetRoot(directory)
246
+ return withSkillWriteLock(anchor.root, snapshot.family?.id ?? snapshot.name, work => transaction(snapshot, state, directory, anchor, replace, work, enabled))
247
+ }
@@ -0,0 +1,213 @@
1
+ import { createHash } from 'node:crypto'
2
+ import path from 'node:path'
3
+ import { isDeepStrictEqual } from 'node:util'
4
+ import { isMap, parseDocument } from 'yaml'
5
+ import { checkPath, describePackage, limits, parseSkillMetadata, problem } from './import-files.mjs'
6
+
7
+ export const FAMILY_MARKER = '.dsh-skill-family.json'
8
+ const namePattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
9
+ const attachments = new Set(['assets', 'docs', 'documentation', 'example', 'examples', 'fixture', 'fixtures', 'node_modules', 'reference', 'references', 'sample', 'samples', 'scripts', 'template', 'templates', 'test', 'tests'])
10
+ const containers = new Set(['skills', '.agents', '.claude', '.codex', '.gemini'])
11
+ const invalid = message => problem('INVALID_FAMILY', message)
12
+
13
+ function label(value, max = 240) {
14
+ return typeof value === 'string' && value.trim() && value.length <= max && !/[\x00-\x1f\x7f]/.test(value) ? value.trim() : ''
15
+ }
16
+
17
+ function checkMembers(members) {
18
+ if (!Array.isArray(members) || members.length < 2 || members.length > limits.entries) throw invalid('工具包需要至少两个独立的技能成员。')
19
+ const names = new Set(), paths = new Set()
20
+ for (const member of members) {
21
+ if (!member || typeof member.name !== 'string' || !namePattern.test(member.name) || typeof member.entry !== 'string') throw invalid('工具包成员的名称或入口无效。')
22
+ checkPath(member.entry)
23
+ if (!member.entry.endsWith('/SKILL.md') && member.entry !== 'SKILL.md') throw invalid('工具包成员须提供 SKILL.md 入口。')
24
+ const key = member.entry.normalize('NFC').toLowerCase()
25
+ if (names.has(member.name) || paths.has(key)) throw invalid(`工具包中存在重复的技能名称或入口:${member.name}`)
26
+ names.add(member.name); paths.add(key)
27
+ }
28
+ }
29
+
30
+ /** Parse a persisted membership list. Paths are always relative to the family directory. */
31
+ export function parseFamilyMarker(text) {
32
+ let data
33
+ try { data = JSON.parse(text) } catch { throw invalid(`无法解析工具包归属文件 ${FAMILY_MARKER}。`) }
34
+ if (!data || data.version !== 1 || typeof data.id !== 'string' || !namePattern.test(data.id) || data.id.length > 128 ||
35
+ !label(data.name) || !label(data.description, 8192) || typeof data.entry !== 'string' || typeof data.enabled !== 'boolean' ||
36
+ !['folder', 'archive'].includes(data.source?.format) || !label(data.source?.label, 255) || /[\\/]/.test(data.source.label)) {
37
+ throw invalid(`工具包归属文件 ${FAMILY_MARKER} 的版本或字段无效。`)
38
+ }
39
+ checkPath(data.id)
40
+ checkPath(data.entry)
41
+ if (!/\.md$/i.test(data.entry)) throw invalid('工具包的介绍入口须为 Markdown 文件。')
42
+ checkMembers(data.members)
43
+ return data
44
+ }
45
+
46
+ function memberRecords(files, rootSkill) {
47
+ const selected = []
48
+ // A package can contain examples and even complete ancillary tools elsewhere
49
+ // (for example automations/*/skills). A declared conventional root owns the
50
+ // callable members, while the rest still travels in the package.
51
+ const explicitRoot = /^(?:skills|\.(?:claude|agents|codex|gemini)\/skills)\/[^/]+\/SKILL\.md$/
52
+ const hasSkillRoot = files.some(item => !item.directory && explicitRoot.test(item.path))
53
+ for (const record of files) {
54
+ const parts = record.path.split('/')
55
+ if (record.directory || parts.at(-1) !== 'SKILL.md') continue
56
+ const folders = parts.slice(0, -1)
57
+ if ((rootSkill || hasSkillRoot) && folders.length && !explicitRoot.test(record.path)) continue
58
+ if (!explicitRoot.test(record.path) && folders.some(folder => attachments.has(folder.toLowerCase()) || (folder.startsWith('.') && !containers.has(folder)))) continue
59
+ selected.push(record)
60
+ }
61
+ selected.sort((a, b) => a.path.split('/').length - b.path.split('/').length || (a.path < b.path ? -1 : 1))
62
+ const roots = [], members = []
63
+ for (const item of selected) {
64
+ if (roots.some(root => item.path.startsWith(root))) continue
65
+ // A root SKILL.md can explicitly ship child skills under skills/. Inside
66
+ // every other established skill, nested SKILL.md files are its resources.
67
+ if (item.path !== 'SKILL.md') roots.push(item.path.slice(0, -'SKILL.md'.length))
68
+ members.push(item)
69
+ }
70
+ return members
71
+ }
72
+
73
+ function readText(record, max = 128 * 1024) {
74
+ return Buffer.isBuffer(record?.bytes) ? record.bytes.toString('utf8', 0, max) : ''
75
+ }
76
+
77
+ function summaryText(text) {
78
+ const lines = text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '').split(/\r?\n/)
79
+ const title = lines.find(line => /^#\s+\S/.test(line))?.replace(/^#\s+/, '').trim()
80
+ const afterTitle = title ? lines.slice(lines.findIndex(line => /^#\s+\S/.test(line)) + 1) : lines
81
+ const paragraph = afterTitle.find(line => /^[\p{L}\p{N}]/u.test(line.trim()))
82
+ return { title: label(title), description: label(paragraph?.trim().slice(0, 600), 600) }
83
+ }
84
+
85
+ function familyId(value) {
86
+ const slug = value.normalize('NFKD').toLowerCase().replace(/\p{M}+/gu, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 128).replace(/-$/, '')
87
+ if (slug && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(slug)) return slug
88
+ return `family-${createHash('sha256').update(value.normalize('NFC')).digest('hex').slice(0, 12)}`
89
+ }
90
+
91
+ /** Inspect a local package without executing its scripts or following manifests outside the root. */
92
+ export function deriveFamily(records, { sourceName = 'skills' } = {}) {
93
+ const listing = new Map(records.map(record => [record.path, record]))
94
+ const reserved = records.filter(record => record.path.normalize('NFC').toLowerCase() === FAMILY_MARKER)
95
+ if (reserved.length && (reserved.length !== 1 || reserved[0].path !== FAMILY_MARKER || reserved[0].directory)) throw invalid(`工具包中已占用归属文件名 ${FAMILY_MARKER}。`)
96
+ const marker = reserved.length ? parseFamilyMarker(readText(reserved[0], limits.file)) : null
97
+ const logical = memberRecords(records, listing.has('SKILL.md'))
98
+ if (!marker && logical.length < 2) return null
99
+ // An explicit persisted marker can identify a member under a documentation
100
+ // folder. Still require every independently discovered member to be listed.
101
+ if (marker && logical.some(record => !marker.members.some(member => member.entry === record.path))) throw invalid('归属文件遗漏了工具包中的技能,请核对成员清单。')
102
+ const entries = marker?.members.map(member => member.entry) ?? logical.map(record => record.path)
103
+ const members = entries.map((entry, index) => {
104
+ const record = listing.get(entry)
105
+ if (!record || record.directory || !Buffer.isBuffer(record.bytes)) throw invalid(`工具包中缺少成员说明:${entry}`)
106
+ const info = parseSkillMetadata(record.bytes.toString('utf8'), { invocation: true })
107
+ if (marker && info.name !== marker.members[index].name) throw invalid(`归属文件中的成员名称与 YAML 不一致:${entry}`)
108
+ return { ...info, entry }
109
+ })
110
+ checkMembers(members)
111
+ const readme = records.find(record => !record.directory && /^readme\.md$/i.test(record.path))
112
+ const summary = summaryText(readText(readme))
113
+ let manifest
114
+ try { manifest = JSON.parse(readText(listing.get('package.json'))) } catch { /* An npm manifest is optional in a skill collection. */ }
115
+ const origin = label(path.basename(sourceName).replace(/\.(skill|zip)$/i, '')) || 'skills'
116
+ const entry = marker?.entry ?? readme?.path ?? members[0].entry
117
+ if (!listing.has(entry) || listing.get(entry).directory) throw invalid(`工具包介绍文件已不存在:${entry}`)
118
+ return {
119
+ id: marker?.id ?? familyId(label(manifest?.name) || (summary.title && !/^(skills?|toolkit|readme|overview|工具包|技能)$/i.test(summary.title) ? summary.title : origin)),
120
+ name: marker?.name ?? (label(manifest?.displayName) || summary.title || label(manifest?.name) || origin),
121
+ description: marker?.description ?? (label(manifest?.description, 8192) || summary.description || `${members.length} 个技能:${members.map(member => member.name).join('、').slice(0, 400)}`),
122
+ entry, enabled: marker?.enabled ?? true, members,
123
+ }
124
+ }
125
+
126
+ export function markerBytes(snapshot, enabled = snapshot.family.enabled) {
127
+ const { family } = snapshot
128
+ const current = snapshot.records.find(record => record.path === FAMILY_MARKER)
129
+ if (current) {
130
+ const data = parseFamilyMarker(readText(current, limits.file))
131
+ if (data.enabled === enabled) return current.bytes
132
+ return Buffer.from(`${JSON.stringify({ ...data, enabled }, null, 2)}\n`)
133
+ }
134
+ const data = { version: 1, id: family.id, name: family.name, description: family.description, entry: family.entry, enabled,
135
+ members: family.members.map(({ name, entry }) => ({ name, entry })),
136
+ source: { format: snapshot.format, label: path.basename(snapshot.sourcePath) } }
137
+ parseFamilyMarker(JSON.stringify(data))
138
+ return Buffer.from(`${JSON.stringify(data, null, 2)}\n`)
139
+ }
140
+
141
+ export function describeLocalPackage(records, format, sourceLabel, sourcePath) {
142
+ if (format === 'markdown') return describePackage(records, format, sourceLabel, sourcePath)
143
+ let sourceName = path.basename(sourcePath).replace(/\.(zip|skill)$/i, '')
144
+ const roots = records.filter(record => !record.path.includes('/'))
145
+ if (roots.length === 1 && roots[0].directory) {
146
+ const wrapper = roots[0].path
147
+ const child = name => records.some(item => item.path === `${wrapper}/${name}`)
148
+ const wrapsPackage = child('SKILL.md') || child(FAMILY_MARKER)
149
+ // Preserve structural directories such as skills/. An extracted outer
150
+ // folder often wraps the actual project exactly as a downloaded ZIP does.
151
+ const hasWrapper = format === 'archive' || wrapper === sourceName || child('package.json') || child('skills') || records.some(item => item.path.toLowerCase() === `${wrapper.toLowerCase()}/readme.md`)
152
+ if (wrapsPackage || (!containers.has(wrapper.toLowerCase()) && hasWrapper)) {
153
+ const prefix = `${wrapper}/`
154
+ records = records.filter(record => record.path.startsWith(prefix)).map(record => ({ ...record, path: record.path.slice(prefix.length) }))
155
+ sourceName = wrapper
156
+ }
157
+ }
158
+ const family = deriveFamily(records, { sourceName })
159
+ if (!family) return describePackage(records, format, sourceLabel, sourcePath)
160
+ const files = records.filter(record => !record.directory && record.path !== FAMILY_MARKER).map(record => record.path).sort()
161
+ const snapshot = { records, kind: 'family', family, name: family.name, description: family.description, members: family.members,
162
+ format, sourceLabel, sourcePath, entry: family.entry, targetRelativePath: family.id, files }
163
+ const marker = markerBytes(snapshot)
164
+ if (!records.some(item => item.path === FAMILY_MARKER) && (records.length + 1 > limits.entries || records.reduce((sum, item) => sum + (item.bytes?.length || 0), marker.length) > limits.bundle)) throw problem('SIZE_LIMIT', '工具包大小超过导入限制。')
165
+ return snapshot
166
+ }
167
+
168
+ // Tighten only the two invocation flags for a replaced member. This happens
169
+ // when the installed member had a restriction that its incoming YAML lacks.
170
+ // Keep the incoming body verbatim and verify every unrelated YAML value.
171
+ function restrictedBytes(bytes, name, updates) {
172
+ let raw
173
+ try { raw = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes) } catch { throw invalid(`成员 ${name} 的说明不是有效的 UTF-8,无法安全保留原调用权限。`) }
174
+ const opening = /^---\r?\n/.exec(raw)
175
+ const closing = /^---\r?$/gm
176
+ closing.lastIndex = opening[0].length
177
+ const end = closing.exec(raw)
178
+ const header = raw.slice(opening[0].length, end.index)
179
+ const doc = parseDocument(header)
180
+ if (doc.errors.length || !isMap(doc.contents)) throw invalid(`无法保留成员 ${name} 的调用权限。`)
181
+ const expected = { ...doc.toJS(), ...updates }
182
+ for (const [field, value] of Object.entries(updates)) doc.set(field, value)
183
+ let changed = doc.toString({ lineWidth: 0 })
184
+ if (!isDeepStrictEqual(parseDocument(changed).toJS(), expected)) throw invalid(`成员 ${name} 的调用字段使用了共享 YAML 引用,无法单独保留原权限。`)
185
+ if (opening[0].endsWith('\r\n')) changed = changed.replace(/\r?\n/g, '\r\n')
186
+ const suffixOffset = Buffer.byteLength(raw.slice(0, end.index))
187
+ return Buffer.concat([Buffer.from(opening[0] + changed), bytes.subarray(suffixOffset)])
188
+ }
189
+
190
+ export function prepareFamily(snapshot, existingFamily, enabled) {
191
+ const oldMembers = new Map(existingFamily?.members.map(member => [member.name, member]))
192
+ const restrictions = new Map()
193
+ const members = snapshot.members.map(member => {
194
+ const old = oldMembers.get(member.name)
195
+ if (!old) return member
196
+ const invocation = { ...member.invocation }, updates = {}
197
+ if (!old.invocation.modelInvocable && invocation.modelInvocable) { invocation.modelInvocable = false; updates['disable-model-invocation'] = true }
198
+ if (!old.invocation.userInvocable && invocation.userInvocable) { invocation.userInvocable = false; updates['user-invocable'] = false }
199
+ if (!Object.keys(updates).length) return member
200
+ restrictions.set(member.entry, { name: member.name, updates })
201
+ return { ...member, invocation }
202
+ })
203
+ const family = { ...snapshot.family, members, enabled: enabled ?? existingFamily?.enabled ?? snapshot.family.enabled }
204
+ const records = snapshot.records.map(record => {
205
+ const tightened = restrictions.get(record.path)
206
+ return tightened ? { ...record, bytes: restrictedBytes(record.bytes, tightened.name, tightened.updates) } : record
207
+ })
208
+ const result = { ...snapshot, members, family, records }
209
+ const bytes = markerBytes(result, family.enabled)
210
+ result.records = records.filter(record => record.path !== FAMILY_MARKER).concat({ path: FAMILY_MARKER, directory: false, executable: false, bytes })
211
+ if (result.records.reduce((sum, item) => sum + (item.bytes?.length || 0), 0) > limits.bundle || result.records.some(item => item.bytes?.length > limits.file)) throw problem('SIZE_LIMIT', '工具包超过导入限制。')
212
+ return result
213
+ }
@@ -0,0 +1,186 @@
1
+ import { constants } from 'node:fs'
2
+ import { lstat, open, opendir, realpath } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { parse as parseYaml } from 'yaml'
5
+ import { limits } from './import-limits.mjs'
6
+
7
+ export { limits }
8
+
9
+ export function problem(code, message, details = {}) {
10
+ return Object.assign(new Error(message), { code, ...details })
11
+ }
12
+
13
+ export function parseSkillMetadata(text, { invocation = false } = {}) {
14
+ const invalid = message => problem('INVALID_SKILL', message)
15
+ const opening = /^---\r?\n/.exec(text)
16
+ if (!opening) throw invalid('技能说明须以 YAML 文件头开始。')
17
+ const closing = /^---\r?$/gm
18
+ closing.lastIndex = opening[0].length
19
+ const end = closing.exec(text.slice(0, limits.header))
20
+ if (!end || Buffer.byteLength(text.slice(0, end.index + end[0].length)) > limits.header) throw invalid('YAML 文件头缺少结束分隔行,或超过 256 KiB。')
21
+ let fields
22
+ try {
23
+ fields = parseYaml(text.slice(opening[0].length, end.index), { logLevel: 'error' })
24
+ } catch (cause) {
25
+ throw invalid(`YAML 文件头无效。${cause.message.split('\n')[0]}`)
26
+ }
27
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields)) throw invalid('YAML 文件头须为一组字段。')
28
+ if (typeof fields.name !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(fields.name)) {
29
+ throw invalid('name 须由小写字母、数字与单个连字符组成。')
30
+ }
31
+ if (typeof fields.description !== 'string' || !fields.description.trim()) throw invalid('请在 YAML 文件头中填写 description。')
32
+ for (const [old, key] of [['disableModelInvocation', 'disable-model-invocation'], ['modelInvocable', 'disable-model-invocation'], ['userInvocable', 'user-invocable']]) {
33
+ if (Object.hasOwn(fields, old)) throw invalid(`DSH 不支持 ${old} 字段,请使用 ${key}。`)
34
+ }
35
+ for (const key of ['disable-model-invocation', 'user-invocable']) {
36
+ const value = fields[key]
37
+ if (Object.hasOwn(fields, key) && !(['string', 'boolean', 'number'].includes(typeof value) && /^(true|false|yes|no|on|off|0|1)$/i.test(String(value)))) {
38
+ throw invalid(`${key} 须为布尔值。`)
39
+ }
40
+ }
41
+ const result = { name: fields.name, description: fields.description }
42
+ if (invocation) {
43
+ const on = value => /^(true|yes|on|1)$/i.test(String(value))
44
+ result.invocation = {
45
+ modelInvocable: !on(fields['disable-model-invocation']),
46
+ userInvocable: !Object.hasOwn(fields, 'user-invocable') || on(fields['user-invocable']),
47
+ }
48
+ }
49
+ return result
50
+ }
51
+
52
+ export function checkPath(relative) {
53
+ const parts = relative.split('/')
54
+ if (parts.length > limits.depth || Buffer.byteLength(relative) > 2048 || parts.some(part =>
55
+ !part || part === '.' || part === '..' || Buffer.byteLength(part) > 255 ||
56
+ /[<>:"|?*\\\x00-\x1f\x7f]|[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) {
57
+ throw problem('UNSAFE_PATH', `技能中的路径无效:${relative.slice(0, 140)}`)
58
+ }
59
+ }
60
+
61
+ export function ignoredResource(relative) {
62
+ return relative.split('/').some(part => ['.git', '.ds_store', '__macosx'].includes(part.toLowerCase()) || part.startsWith('._'))
63
+ }
64
+
65
+ export function checkSize(size, limit) {
66
+ if (!Number.isSafeInteger(size) || size < 0 || size > limit) throw problem('SIZE_LIMIT', '技能文件的数量或大小超过导入限制。')
67
+ }
68
+
69
+ export async function statOrNull(target) {
70
+ try {
71
+ return await lstat(target)
72
+ } catch (error) {
73
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return null
74
+ throw error
75
+ }
76
+ }
77
+
78
+ // Sources are opened by canonical path. Check the open handle as well as its
79
+ // path so a replaced file, parent link or special file cannot change a preview.
80
+ export async function readRegular(file, maxBytes, prefixOnly = false) {
81
+ const flags = constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | (constants.O_NONBLOCK || 0)
82
+ const handle = await open(file, flags)
83
+ try {
84
+ const info = await handle.stat()
85
+ if (!info.isFile() || await realpath(file) !== file) throw problem('UNSAFE_PATH', `请使用普通文件:${file}`)
86
+ const current = await lstat(file)
87
+ if (info.dev !== current.dev || info.ino !== current.ino) throw problem('SOURCE_CHANGED', '文件已变化,请重新预览。')
88
+ if (!prefixOnly) checkSize(info.size, maxBytes)
89
+ const size = Math.min(info.size, maxBytes)
90
+ const bytes = Buffer.alloc(size)
91
+ let offset = 0
92
+ while (offset < size) {
93
+ const { bytesRead } = await handle.read(bytes, offset, size - offset, offset)
94
+ if (!bytesRead) throw problem('SOURCE_CHANGED', '文件已变化,请重新预览。')
95
+ offset += bytesRead
96
+ }
97
+ const after = await handle.stat()
98
+ if (after.size !== info.size || after.ctimeMs !== info.ctimeMs) throw problem('SOURCE_CHANGED', '文件已变化,请重新预览。')
99
+ return { bytes, executable: Boolean(info.mode & 0o111) }
100
+ } finally {
101
+ await handle.close()
102
+ }
103
+ }
104
+
105
+ // Register paths before allocating file buffers or inflating entries. Includes
106
+ // implicit parent directories and detects collisions on case-insensitive disks.
107
+ export class ImportFiles {
108
+ nodes = new Map()
109
+ #spellings = new Map()
110
+ total = 0
111
+
112
+ reserve(relative, directory, size = 0, executable = false) {
113
+ checkPath(relative)
114
+ checkSize(size, limits.file)
115
+ checkSize(this.total + size, limits.bundle)
116
+ const parts = relative.split('/')
117
+ let prefix = ''
118
+ for (const [index, part] of parts.entries()) {
119
+ prefix = prefix ? `${prefix}/${part}` : part
120
+ const last = index === parts.length - 1
121
+ const isDirectory = !last || directory
122
+ const key = prefix.normalize('NFC').toLowerCase()
123
+ const old = this.nodes.get(prefix)
124
+ if ((this.#spellings.has(key) && this.#spellings.get(key) !== prefix) || (old && (old.directory !== isDirectory || (last && old.explicit)))) {
125
+ throw problem('UNSAFE_PATH', `技能中存在重叠的文件路径:${prefix}`)
126
+ }
127
+ if (!old) {
128
+ checkSize(this.nodes.size + 1, limits.entries)
129
+ this.#spellings.set(key, prefix)
130
+ this.nodes.set(prefix, { path: prefix, directory: isDirectory, explicit: last, executable: last && executable })
131
+ } else if (last) {
132
+ old.explicit = true
133
+ }
134
+ }
135
+ this.total += size
136
+ return this.nodes.get(relative)
137
+ }
138
+ }
139
+
140
+ export async function readFolder(root, { previous = false, metadataOnly = false, signal } = {}) {
141
+ const files = new ImportFiles()
142
+ async function visit(relative) {
143
+ const directory = path.join(root, relative)
144
+ if (await realpath(directory) !== directory) throw problem('UNSAFE_PATH', `技能中包含符号链接:${relative}`)
145
+ for await (const item of await opendir(directory)) {
146
+ signal?.throwIfAborted()
147
+ const name = relative ? `${relative}/${item.name}` : item.name
148
+ if (ignoredResource(name) && !previous) continue
149
+ if (previous && item.name.toLowerCase() === '.git') throw problem('TARGET_OCCUPIED', '现有技能含有 Git 工作目录。')
150
+ const absolute = path.join(root, name)
151
+ const info = await lstat(absolute)
152
+ if (info.isDirectory()) {
153
+ files.reserve(name, true)
154
+ await visit(name)
155
+ } else if (info.isFile()) {
156
+ const record = files.reserve(name, false, info.size)
157
+ if (metadataOnly) {
158
+ if (name === '.dsh-skill-family.json') record.bytes = (await readRegular(absolute, limits.file)).bytes
159
+ else if (item.name === 'SKILL.md' || /^(readme\.md|package\.json)$/i.test(name)) record.bytes = (await readRegular(absolute, limits.header, true)).bytes
160
+ continue
161
+ }
162
+ const file = await readRegular(absolute, info.size)
163
+ if (file.bytes.length !== info.size) throw problem('SOURCE_CHANGED', '技能目录已变化,请重新预览。')
164
+ record.bytes = file.bytes
165
+ record.executable = file.executable
166
+ } else {
167
+ throw problem('UNSAFE_PATH', `技能中包含链接或特殊文件:${name}`)
168
+ }
169
+ }
170
+ }
171
+ await visit('')
172
+ return [...files.nodes.values()]
173
+ }
174
+
175
+ export function describePackage(records, format, sourceLabel, sourcePath) {
176
+ const flat = format === 'markdown'
177
+ const manifest = flat ? records[0] : records.find(record => record.path === 'SKILL.md' && !record.directory)
178
+ if (!manifest?.bytes) throw problem('INVALID_SKILL', '技能文件夹顶层缺少 SKILL.md。')
179
+ const { name, description } = parseSkillMetadata(manifest.bytes.toString('utf8'))
180
+ const entry = flat ? `${name}.md` : 'SKILL.md'
181
+ const targetRelativePath = flat ? entry : `${name}/${entry}`
182
+ checkPath(targetRelativePath)
183
+ if (flat) manifest.path = entry
184
+ const files = records.filter(record => !record.directory).map(record => record.path).sort()
185
+ return { records, name, description, entry, files, format, sourceLabel, sourcePath, targetRelativePath }
186
+ }