@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,168 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { checkPath, checkSize, describePackage, ignoredResource, ImportFiles, limits, parseSkillMetadata, problem } from './import-files.mjs'
3
+
4
+ const shaPattern = /^[a-f0-9]{40}$/
5
+ const encodePath = parts => parts.map(encodeURIComponent).join('/')
6
+
7
+ export function githubSource(value) {
8
+ const invalid = () => problem('INVALID_URL', '请输入公开的 GitHub 仓库或技能子目录链接。')
9
+ if (typeof value !== 'string' || !value.trim() || value.length > 2048 || /[\\\x00-\x1f]/.test(value)) throw invalid()
10
+ let text = value.trim()
11
+ if (/^[\w.-]+\/[\w.-]+$/.test(text)) text = `https://github.com/${text}`
12
+ if (text.startsWith('github.com/')) text = `https://${text}`
13
+ let url, parts
14
+ try {
15
+ url = new URL(text)
16
+ parts = url.pathname.replace(/^\//, '').replace(/\/$/, '').split('/').map(decodeURIComponent)
17
+ } catch { throw invalid() }
18
+ if (url.origin !== 'https://github.com' || url.username || url.password || !/^[a-z\d][a-z\d-]{0,38}$/i.test(parts[0])) throw invalid()
19
+ const owner = parts[0], repo = parts[1]?.replace(/\.git$/, '')
20
+ if (!repo || !/^[\w.-]{1,100}$/.test(repo) || repo === '.' || repo === '..') throw invalid()
21
+ const tail = parts.slice(3).flatMap(part => part.split('/'))
22
+ if ((parts.length > 2 && (parts[2] !== 'tree' || !tail.length)) || tail.length > limits.depth) throw invalid()
23
+ if (tail.length) checkPath(tail.join('/'))
24
+ const repository = `${owner}/${repo}`
25
+ const key = `https://github.com/${repository}${tail.length ? `/tree/${encodePath(tail)}` : ''}`
26
+ return { key, repository, tail }
27
+ }
28
+
29
+ async function responseBytes(fetch, url, accept, maximum, signal) {
30
+ const timeout = AbortSignal.timeout(20000)
31
+ let response
32
+ try {
33
+ response = await fetch(url, { redirect: 'error', credentials: 'omit', headers: { Accept: accept }, signal: signal ? AbortSignal.any([signal, timeout]) : timeout })
34
+ if (!response.ok) {
35
+ await response.body?.cancel()
36
+ const message = [403, 429].includes(response.status) ? 'GitHub 暂时限制了请求,请稍后重试。' : `GitHub 返回 HTTP ${response.status},请检查仓库、版本和路径。`
37
+ throw problem('GITHUB_HTTP', message, { status: response.status })
38
+ }
39
+ const length = response.headers.get('content-length')
40
+ if (length !== null && Number(length) > maximum) {
41
+ await response.body?.cancel()
42
+ throw problem('SIZE_LIMIT', 'GitHub 返回的数据超过导入限制,请选择具体的技能子目录。')
43
+ }
44
+ const chunks = []
45
+ let size = 0
46
+ for await (const chunk of response.body) {
47
+ size += chunk.length
48
+ checkSize(size, maximum)
49
+ chunks.push(chunk)
50
+ }
51
+ return Buffer.concat(chunks, size)
52
+ } catch (error) {
53
+ signal?.throwIfAborted()
54
+ if (error.code === 'GITHUB_HTTP' || error.code === 'SIZE_LIMIT') throw error
55
+ throw problem('GITHUB_UNAVAILABLE', '无法读取 GitHub 公开仓库,请检查连接后重试。', { cause: error })
56
+ }
57
+ }
58
+
59
+ async function together(items, action) {
60
+ let next = 0, failure
61
+ const results = new Array(items.length)
62
+ async function run() {
63
+ while (!failure && next < items.length) {
64
+ const index = next++
65
+ try { results[index] = await action(items[index]) } catch (error) { failure = error }
66
+ }
67
+ }
68
+ await Promise.all(Array.from({ length: Math.min(5, items.length) }, run))
69
+ if (failure) throw failure
70
+ return results
71
+ }
72
+
73
+ function regular(blob) {
74
+ return blob.type === 'blob' && ['100644', '100755'].includes(blob.mode) && shaPattern.test(blob.sha)
75
+ }
76
+
77
+ async function rawBlob(fetch, source, revision, blob, signal) {
78
+ if (!regular(blob)) throw problem('UNSAFE_PATH', `GitHub 技能中包含链接或子模块:${blob.path}`)
79
+ checkSize(blob.size, limits.file)
80
+ const bytes = await responseBytes(fetch, `https://raw.githubusercontent.com/${source.repository}/${revision}/${encodePath(blob.path.split('/'))}`, 'application/octet-stream', blob.size, signal)
81
+ const hash = createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex')
82
+ if (bytes.length !== blob.size || hash !== blob.sha) throw problem('SOURCE_CHANGED', 'GitHub 文件与所选提交不一致,请重新查看仓库。')
83
+ return bytes
84
+ }
85
+
86
+ export async function githubCandidates(source, fetch, signal) {
87
+ const api = `https://api.github.com/repos/${source.repository}`
88
+ async function json(endpoint, size) {
89
+ const bytes = await responseBytes(fetch, `${api}${endpoint}`, 'application/vnd.github+json', size, signal)
90
+ try { return JSON.parse(bytes) } catch { throw problem('GITHUB_UNAVAILABLE', 'GitHub 返回的仓库信息无效。') }
91
+ }
92
+ const repo = await json('', 256 * 1024)
93
+ if (repo.private !== false || !repo.default_branch) throw problem('INVALID_URL', '请选择可匿名读取的公开 GitHub 仓库。')
94
+ const segments = source.tail.length ? source.tail : [repo.default_branch]
95
+ let revision, prefix, ref
96
+ // Try the longest ref first. A slash in a branch/tag name is not necessarily
97
+ // the boundary between the ref and the selected repository directory.
98
+ for (let count = segments.length; count > 0; count--) {
99
+ ref = segments.slice(0, count).join('/')
100
+ try {
101
+ revision = (await responseBytes(fetch, `${api}/commits/${encodeURIComponent(ref)}`, 'application/vnd.github.sha', 256, signal)).toString().trim()
102
+ } catch (error) {
103
+ if (count > 1 && [404, 422].includes(error.status)) continue
104
+ throw error
105
+ }
106
+ if (!shaPattern.test(revision)) throw problem('GITHUB_UNAVAILABLE', 'GitHub 返回的提交版本无效。')
107
+ prefix = source.tail.slice(count).join('/')
108
+ break
109
+ }
110
+ // Walk to the selected subtree first. A large repository can truncate a
111
+ // recursive root listing even when an individual skill is small.
112
+ let treeSha = revision
113
+ for (const component of prefix ? prefix.split('/') : []) {
114
+ const directory = await json(`/git/trees/${treeSha}`, 8 * 1024 ** 2)
115
+ const next = directory.tree?.find(entry => entry.path === component && entry.type === 'tree' && entry.mode === '040000')
116
+ if (!next || !shaPattern.test(next.sha)) throw problem('GITHUB_PATH', '该版本中没有这个技能目录。')
117
+ treeSha = next.sha
118
+ }
119
+ const tree = await json(`/git/trees/${treeSha}?recursive=1`, 8 * 1024 ** 2)
120
+ if (!Array.isArray(tree.tree) || tree.truncated || tree.tree.length > 40000) throw problem('SIZE_LIMIT', '仓库文件列表过大,请粘贴具体的技能子目录链接。')
121
+ const entries = tree.tree.map(entry => ({ ...entry, path: prefix ? `${prefix}/${entry.path}` : entry.path }))
122
+ const manifests = entries.filter(entry => typeof entry.path === 'string' && (entry.path === 'SKILL.md' || entry.path.endsWith('/SKILL.md')) && !ignoredResource(entry.path))
123
+ if (manifests.length > 256) throw problem('SIZE_LIMIT', '此目录的技能超过 256 项,请选择更具体的子目录。')
124
+ let metadataBytes = 0
125
+ for (const blob of manifests) if (regular(blob)) {
126
+ if (!Number.isSafeInteger(blob.size) || blob.size < 0) throw problem('GITHUB_UNAVAILABLE', 'GitHub 返回的文件大小无效。')
127
+ if (blob.size > limits.file) continue
128
+ metadataBytes += blob.size
129
+ checkSize(metadataBytes, limits.bundle)
130
+ }
131
+ const warnings = []
132
+ const choices = await together(manifests, async blob => {
133
+ const folder = blob.path.split('/').slice(0, -1).join('/')
134
+ try {
135
+ checkPath(blob.path)
136
+ const bytes = await rawBlob(fetch, source, revision, blob, signal)
137
+ const info = parseSkillMetadata(bytes.toString('utf8'))
138
+ return { ...info, path: folder || '.', format: 'folder', folder, revision, ref, entries, manifest: blob, bytes }
139
+ } catch (error) {
140
+ if (!['INVALID_SKILL', 'UNSAFE_PATH', 'SIZE_LIMIT'].includes(error.code)) throw error
141
+ warnings.push(`${blob.path}:${error.message}`)
142
+ return null
143
+ }
144
+ })
145
+ return { choices: choices.filter(Boolean), sourceLabel: 'GitHub', sourcePath: source.repository, warnings }
146
+ }
147
+
148
+ export async function githubPreview(source, item, fetch, signal) {
149
+ const { folder, revision } = item
150
+ const prefix = folder ? `${folder}/` : ''
151
+ const files = new ImportFiles(), downloads = []
152
+ for (const blob of item.entries) {
153
+ if (!blob.path.startsWith(prefix) || blob.path === folder) continue
154
+ const relative = blob.path.slice(prefix.length)
155
+ if (ignoredResource(relative)) continue
156
+ if (blob.type === 'tree' && blob.mode === '040000') {
157
+ files.reserve(relative, true)
158
+ } else {
159
+ if (!regular(blob)) throw problem('UNSAFE_PATH', `技能中包含链接或子模块:${relative}`)
160
+ const record = files.reserve(relative, false, blob.size, blob.mode === '100755')
161
+ if (blob.path === item.manifest.path) record.bytes = item.bytes
162
+ else downloads.push({ record, blob })
163
+ }
164
+ }
165
+ await together(downloads, async ({ record, blob }) => { record.bytes = await rawBlob(fetch, source, revision, blob, signal) })
166
+ const snapshot = describePackage([...files.nodes.values()], 'folder', `GitHub · ${item.name}`, `${source.repository}${folder ? ` · ${folder}` : ''}`)
167
+ return { ...snapshot, revision, ref: item.ref }
168
+ }
@@ -0,0 +1,10 @@
1
+ // The browser stages the same sizes the Host accepts from disk or an archive.
2
+ export const limits = Object.freeze({
3
+ entries: 1024,
4
+ file: 16 * 1024 ** 2,
5
+ bundle: 64 * 1024 ** 2,
6
+ archive: 32 * 1024 ** 2,
7
+ header: 256 * 1024,
8
+ depth: 32,
9
+ rootEntries: 4096,
10
+ })
@@ -0,0 +1,79 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { rename } from 'node:fs/promises'
3
+ import { createRequire } from 'node:module'
4
+ import path from 'node:path'
5
+ import { promisify } from 'node:util'
6
+ import { problem } from './import-files.mjs'
7
+
8
+ const requireHost = createRequire(import.meta.url)
9
+ const execute = promisify(execFile)
10
+ const unavailable = () => problem('ATOMIC_REPLACE_UNAVAILABLE', '当前系统或目标磁盘不支持原子发布此工具包。请更换保存位置后重试,原工具包已保留。')
11
+
12
+ // Load only from the running application's own installation. Never resolve a
13
+ // native library relative to the selected package, target or working directory.
14
+ function hostRename() {
15
+ const install = process.env.DSH_INSTALL_DIR
16
+ const modules = []
17
+ if (install && path.isAbsolute(install)) {
18
+ modules.push(path.join(install, 'node_modules'))
19
+ if (path.basename(install) === 'dsh' && path.basename(path.dirname(install)) === '@deepseek-ai') modules.push(path.dirname(path.dirname(install)))
20
+ }
21
+ if (process.resourcesPath && path.isAbsolute(process.resourcesPath)) modules.unshift(path.join(process.resourcesPath, 'app.asar', 'dsh', 'node_modules'))
22
+ const platform = `${process.platform}-${process.arch}`
23
+ for (const root of modules) {
24
+ const libraries = [path.join(root, 'koffi')]
25
+ if (root.includes(`${path.sep}app.asar${path.sep}`)) {
26
+ const unpacked = root.replace(`${path.sep}app.asar${path.sep}`, `${path.sep}app.asar.unpacked${path.sep}`)
27
+ libraries.push(path.join(unpacked, '@koromix', `koffi-${platform}`, `${process.platform}_${process.arch}`, 'koffi.node'))
28
+ }
29
+ for (const library of libraries) {
30
+ try {
31
+ const ffi = requireHost(library)
32
+ const libc = ffi.load(null)
33
+ const rename = process.platform === 'darwin'
34
+ ? libc.func('int renamex_np(const char *src, const char *dst, unsigned int flags)')
35
+ : libc.func('int renameat2(int oldfd, const char *src, int newfd, const char *dst, unsigned int flags)')
36
+ return (src, dst, swap) => {
37
+ const result = process.platform === 'darwin' ? rename(src, dst, swap ? 2 : 4) : rename(-100, src, -100, dst, swap ? 2 : 1)
38
+ return result === 0 ? 0 : ffi.errno()
39
+ }
40
+ } catch { /* The CLI distribution may omit the desktop's native FFI. */ }
41
+ }
42
+ }
43
+ return null
44
+ }
45
+
46
+ // CLI-only fallback: one fixed libc call via the system's isolated Python.
47
+ // Paths are separate argv values and the environment has no loader overrides.
48
+ const python = [
49
+ 'import ctypes, os, sys',
50
+ 'lib = ctypes.CDLL(None, use_errno=True)',
51
+ 'src, dst = map(os.fsencode, sys.argv[1:3])',
52
+ 'swap = sys.argv[3] == "swap"',
53
+ 'if sys.platform == "darwin":',
54
+ ' result = lib.renamex_np(src, dst, 2 if swap else 4)',
55
+ 'else:',
56
+ ' result = lib.renameat2(-100, src, -100, dst, 2 if swap else 1)',
57
+ 'if result != 0: sys.exit(ctypes.get_errno())',
58
+ ].join('\n')
59
+
60
+ let native
61
+ export async function publishFamily(source, destination, swap) {
62
+ if (process.platform === 'win32' && !swap) return rename(source, destination)
63
+ if (!['darwin', 'linux'].includes(process.platform)) throw unavailable()
64
+ if (native === undefined) native = hostRename()
65
+ let errno
66
+ if (native) errno = native(source, destination, swap)
67
+ else {
68
+ try {
69
+ await execute('/usr/bin/python3', ['-I', '-S', '-c', python, source, destination, swap ? 'swap' : 'new'], {
70
+ cwd: '/', env: { LC_ALL: 'C', PATH: '/usr/bin:/bin' }, maxBuffer: 4096,
71
+ })
72
+ return
73
+ } catch (error) { errno = error.code }
74
+ }
75
+ if (!errno) return
76
+ if ([17, 39, 66].includes(errno)) throw problem('TARGET_OCCUPIED', `工具包位置已变化:${destination}`)
77
+ if (errno === 2) throw problem('TARGET_CHANGED', '工具包目标已变化,请重新预览。')
78
+ throw unavailable()
79
+ }
package/imports.mjs ADDED
@@ -0,0 +1,209 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { lstat, opendir, realpath } from 'node:fs/promises'
3
+ import { homedir } from 'node:os'
4
+ import path from 'node:path'
5
+ import { readArchive } from './import-archive.mjs'
6
+ import { commitPackage } from './import-commit.mjs'
7
+ import { deriveFamily, describeLocalPackage, FAMILY_MARKER } from './import-family.mjs'
8
+ import { checkSize, describePackage, limits, parseSkillMetadata, problem, readFolder, readRegular, statOrNull } from './import-files.mjs'
9
+ import { githubCandidates, githubPreview, githubSource } from './import-github.mjs'
10
+
11
+ const sources = { claude: ['Claude Code', '.claude'], codex: ['Codex', '.agents'], gemini: ['Gemini CLI', '.gemini'] }
12
+ const lifetime = 15 * 60 * 1000
13
+
14
+ async function sourceFor(request, home) {
15
+ if (request.type === 'github') return githubSource(request.url)
16
+ if (request.type !== 'tool' || !Object.hasOwn(sources, request.tool) || !['user', 'project'].includes(request.scope)) {
17
+ throw problem('INVALID_SOURCE', '请选择工具和目录范围。')
18
+ }
19
+ let base = home
20
+ if (request.scope === 'project') {
21
+ if (typeof request.cwd !== 'string' || !path.isAbsolute(request.cwd)) throw problem('INVALID_SOURCE', '请在当前项目的会话中选择项目范围。')
22
+ const cwd = await realpath(request.cwd)
23
+ if (!(await lstat(cwd)).isDirectory()) throw problem('INVALID_SOURCE', '工作区目录不可用。')
24
+ base = cwd
25
+ for (let candidate = cwd; ; candidate = path.dirname(candidate)) {
26
+ if (await statOrNull(path.join(candidate, '.git'))) { base = candidate; break }
27
+ if (path.dirname(candidate) === candidate) break
28
+ }
29
+ }
30
+ const [label, config] = sources[request.tool]
31
+ const root = path.join(base, config, 'skills')
32
+ return { key: JSON.stringify([request.tool, request.scope, root]), label, root }
33
+ }
34
+
35
+ async function toolCandidates(source, signal) {
36
+ const result = { choices: [], warnings: [], sourceLabel: source.label, sourcePath: source.root }
37
+ let directory
38
+ try { directory = await opendir(source.root) } catch (error) {
39
+ if (error.code === 'ENOENT') return result
40
+ throw error
41
+ }
42
+ let seen = 0
43
+ for await (const item of directory) {
44
+ checkSize(++seen, limits.rootEntries)
45
+ signal.throwIfAborted()
46
+ if (item.name.startsWith('.') || (!item.isDirectory() && !item.isSymbolicLink() && !/\.md$/i.test(item.name))) continue
47
+ const display = path.join(source.root, item.name)
48
+ try {
49
+ const actual = await realpath(display), stat = await lstat(actual)
50
+ const folder = stat.isDirectory()
51
+ if (!folder && (!stat.isFile() || !/\.md$/i.test(item.name))) continue
52
+ const instructionPath = folder ? path.join(actual, 'SKILL.md') : actual
53
+ const entry = await statOrNull(instructionPath)
54
+ if (folder && (!entry || await statOrNull(path.join(actual, FAMILY_MARKER)))) {
55
+ const records = await readFolder(actual, { metadataOnly: true, signal })
56
+ const family = deriveFamily(records, { sourceName: item.name })
57
+ if (family) {
58
+ const members = family.members.map(({ name, entry }) => [name, entry])
59
+ result.choices.push({ kind: 'family', name: family.name, description: family.description, idOnDisk: family.id, members,
60
+ memberCount: members.length, path: display, actual, instructionPath: path.join(actual, family.entry), format: 'folder' })
61
+ continue
62
+ }
63
+ }
64
+ if (!entry) continue
65
+ if (!entry.isFile()) throw problem('UNSAFE_PATH', '说明文件须为普通文件。')
66
+ const info = parseSkillMetadata((await readRegular(instructionPath, limits.header, true)).bytes.toString('utf8'))
67
+ result.choices.push({ ...info, path: display, actual, instructionPath, format: folder ? 'folder' : 'markdown' })
68
+ } catch (error) {
69
+ result.warnings.push(`${item.name}:${error.message}`)
70
+ }
71
+ }
72
+ result.choices.sort((a, b) => a.name.localeCompare(b.name) || a.path.localeCompare(b.path))
73
+ return result
74
+ }
75
+
76
+ async function fromDisk(display, sourceLabel, expected, signal) {
77
+ const actual = await realpath(display)
78
+ if (expected && actual !== expected.actual) throw problem('SOURCE_CHANGED', '工具中的技能位置已变化,请重新查看。')
79
+ const info = await lstat(actual)
80
+ let records, format
81
+ if (info.isDirectory()) {
82
+ format = 'folder'
83
+ records = await readFolder(actual, { signal })
84
+ } else if (info.isFile() && /\.md$/i.test(display)) {
85
+ format = 'markdown'
86
+ records = [{ ...(await readRegular(actual, limits.file)), directory: false }]
87
+ } else if (info.isFile() && /\.(zip|skill)$/i.test(display) && !expected) {
88
+ format = 'archive'
89
+ records = await readArchive((await readRegular(actual, limits.archive)).bytes, signal)
90
+ } else {
91
+ throw problem('INVALID_SOURCE', '请选择 Markdown 文件、技能文件夹或 .zip / .skill 压缩包。')
92
+ }
93
+ signal.throwIfAborted()
94
+ const snapshot = expected && expected.kind !== 'family' ? describePackage(records, format, sourceLabel, display) : describeLocalPackage(records, format, sourceLabel, display)
95
+ if (expected && (snapshot.name !== expected.name || format !== expected.format)) throw problem('SOURCE_CHANGED', '候选技能已经变化,请重新查看。')
96
+ if (expected?.kind === 'family' && (snapshot.family?.id !== expected.idOnDisk || JSON.stringify(snapshot.members.map(({ name, entry }) => [name, entry])) !== JSON.stringify(expected.members))) throw problem('SOURCE_CHANGED', '工具包成员或归属已经变化,请重新查看。')
97
+ return snapshot
98
+ }
99
+
100
+ function prune(cache) {
101
+ const now = Date.now()
102
+ for (const [key, item] of cache) if (!item.busy && item.expires <= now) cache.delete(key)
103
+ }
104
+
105
+ function remember(cache, key, value, maxCount, maxBytes) {
106
+ prune(cache)
107
+ let bytes = value.size
108
+ for (const item of cache.values()) bytes += item.size
109
+ for (const [oldKey, old] of cache) {
110
+ if (cache.size < maxCount && bytes <= maxBytes) break
111
+ if (old.busy) continue
112
+ cache.delete(oldKey)
113
+ bytes -= old.size
114
+ }
115
+ if (bytes > maxBytes || cache.size >= maxCount) throw problem('IMPORT_BUSY', '仍有技能正在导入,请稍后再预览。')
116
+ cache.set(key, { ...value, expires: Date.now() + lifetime })
117
+ }
118
+
119
+ export function createImports({ home = homedir(), fetch = globalThis.fetch } = {}) {
120
+ const scans = new Map(), previews = new Map(), lifecycle = new AbortController()
121
+ const signalFor = signal => signal ? AbortSignal.any([signal, lifecycle.signal]) : lifecycle.signal
122
+
123
+ async function candidates(request) {
124
+ const signal = signalFor(request.signal)
125
+ signal.throwIfAborted()
126
+ const source = await sourceFor(request, home)
127
+ const found = request.type === 'github' ? await githubCandidates(source, fetch, signal) : await toolCandidates(source, signal)
128
+ signal.throwIfAborted()
129
+ const group = randomUUID()
130
+ const items = found.choices.map(({ name, description, path, format, instructionPath, kind, memberCount }, index) => ({
131
+ id: `${group}.${index}`, name, description, path, format, ...(instructionPath && { instructionPath }),
132
+ ...(kind === 'family' && { kind, memberCount }),
133
+ }))
134
+ // One tree is shared by every candidate in this scan.
135
+ const size = (found.choices[0]?.entries?.length || 0) * 256 + found.choices.reduce((sum, item) => sum + (item.bytes?.length || 0), 0)
136
+ remember(scans, group, { key: source.key, choices: found.choices, size }, 16, 96 * 1024 ** 2)
137
+ return { items, sourcePath: found.sourcePath, sourceLabel: found.sourceLabel, warnings: found.warnings }
138
+ }
139
+
140
+ async function preview(request) {
141
+ const signal = signalFor(request.signal)
142
+ signal.throwIfAborted()
143
+ let snapshot
144
+ if (request.type === 'local') {
145
+ if (typeof request.path !== 'string' || !request.path || request.path.includes('\0')) throw problem('INVALID_SOURCE', '请选择需要导入的文件或文件夹。')
146
+ let local = request.path
147
+ if (local.startsWith('~/')) local = path.join(home, local.slice(2))
148
+ if (!path.isAbsolute(local)) {
149
+ if (typeof request.cwd !== 'string' || !path.isAbsolute(request.cwd)) throw problem('INVALID_SOURCE', '本地来源需要绝对路径或当前项目目录。')
150
+ local = path.resolve(request.cwd, local)
151
+ }
152
+ snapshot = await fromDisk(local, path.basename(local), null, signal)
153
+ } else {
154
+ const source = await sourceFor(request, home)
155
+ let id = request.id
156
+ if (!id) {
157
+ const { items } = await candidates(request)
158
+ const options = request.path ? items.filter(item => item.path === request.path) : items
159
+ if (options.length !== 1) throw problem('CHOOSE_SKILL', '请先选择一项可用技能。')
160
+ id = options[0].id
161
+ }
162
+ prune(scans)
163
+ const match = typeof id === 'string' && /^([a-f\d-]{36})\.(0|[1-9]\d*)$/.exec(id)
164
+ const scan = match && scans.get(match[1])
165
+ const item = scan?.key === source.key && scan.choices[Number(match[2])]
166
+ if (!item) throw problem('CANDIDATE_EXPIRED', '候选已失效或来源已变化,请重新查看技能。')
167
+ snapshot = request.type === 'github' ? await githubPreview(source, item, fetch, signal) : await fromDisk(item.path, `${source.label} · ${item.name}`, item, signal)
168
+ }
169
+ signal.throwIfAborted()
170
+ const token = randomUUID()
171
+ const { records, ...view } = snapshot
172
+ const size = records.reduce((sum, file) => sum + (file.bytes?.length || 0), 0)
173
+ remember(previews, token, { snapshot, size, busy: false }, 128, 128 * 1024 ** 2)
174
+ return structuredClone({ ...view, token })
175
+ }
176
+
177
+ async function commit({ token, directory, conflict, enabled } = {}) {
178
+ prune(previews)
179
+ const state = previews.get(token)
180
+ if (!state) throw problem('PREVIEW_EXPIRED', '本次预览已失效,请重新预览后导入。')
181
+ if (state.busy) throw problem('IMPORT_BUSY', '该项导入正在进行,请稍后重试。')
182
+ if (conflict !== undefined && !['replace', 'cancel'].includes(conflict)) throw problem('INVALID_CONFLICT', '请选择有效的冲突处理方式。')
183
+ if (conflict === 'cancel') {
184
+ previews.delete(token)
185
+ return { cancelled: true }
186
+ }
187
+ if (state.receipt) {
188
+ if (state.receipt.directoryId !== directory?.id || state.root !== directory?.path) throw problem('PREVIEW_EXPIRED', '此预览已保存到其他目录,请重新预览。')
189
+ if (state.receipt.family && enabled !== undefined && enabled !== state.receipt.enabled) throw problem('ALREADY_SAVED', '本次工具包已按原选项保存。')
190
+ return structuredClone(state.receipt)
191
+ }
192
+ if (enabled !== undefined && typeof enabled !== 'boolean') throw problem('INVALID_INPUT', '启用状态须为布尔值。')
193
+ state.busy = true
194
+ try {
195
+ const receipt = await commitPackage(state.snapshot, state, directory, conflict === 'replace', enabled)
196
+ state.receipt = receipt
197
+ state.root = directory.path
198
+ state.snapshot = undefined
199
+ state.size = 0
200
+ return structuredClone(receipt)
201
+ } finally {
202
+ state.busy = false
203
+ state.expires = Date.now() + lifetime
204
+ }
205
+ }
206
+
207
+ function dispose() { lifecycle.abort(); scans.clear(); previews.clear() }
208
+ return { candidates, preview, commit, dispose }
209
+ }
package/inventory.mjs ADDED
@@ -0,0 +1,62 @@
1
+ import { matchesSkillState } from './skill-state.mjs'
2
+
3
+ const byName = new Intl.Collator('zh-CN', { numeric: true, sensitivity: 'base' })
4
+ const normalized = value => String(value || '').normalize('NFKC').toLocaleLowerCase()
5
+
6
+ export function builtinPreview(cards, searching) {
7
+ if (searching || cards.length <= 6) return cards
8
+ return cards.slice(0, 6)
9
+ }
10
+
11
+ function timestamp(value) {
12
+ const time = typeof value === 'number' ? value : Date.parse(value)
13
+ return Number.isFinite(time) ? time : -Infinity
14
+ }
15
+
16
+ // Membership comes from the Host's resolved package, including when only one
17
+ // member of that package matches the current search or state filter.
18
+ export function indexInventory(items) {
19
+ const packages = new Map()
20
+ for (const item of items) {
21
+ const pkg = item.package
22
+ if (!pkg?.id) continue
23
+ if (!packages.has(pkg.id)) packages.set(pkg.id, { pkg, members: [] })
24
+ packages.get(pkg.id).members.push(item)
25
+ }
26
+ return packages
27
+ }
28
+
29
+ export function inventoryResults(items, packages, { query = '', filter = 'all', sort = 'updated' } = {}) {
30
+ const keyword = normalized(query.trim())
31
+ const cards = []
32
+ const packageCards = new Map()
33
+ let skillCount = 0
34
+ for (const item of items) {
35
+ if (!matchesSkillState(item, filter)) continue
36
+ const bundle = packages.get(item.package?.id)
37
+ const pkg = bundle?.pkg
38
+ const matchesPackage = !!pkg && keyword !== '' && normalized(`${pkg.label}\n${pkg.name}\n${pkg.description || ''}`).includes(keyword)
39
+ if (keyword && !matchesPackage && !normalized(`${item.name}\n${item.description || ''}`).includes(keyword)) continue
40
+ skillCount++
41
+ if (!bundle) { cards.push(item); continue }
42
+ let card = packageCards.get(pkg.id)
43
+ if (!card) {
44
+ card = { kind: 'package', id: pkg.id, name: pkg.label || pkg.name, category: pkg.category || item.category,
45
+ source: item.source, pkg, members: bundle.members, total: bundle.members.length, matched: 0,
46
+ initialQuery: matchesPackage ? '' : query.trim(), initialFilter: filter, updatedAt: -Infinity }
47
+ packageCards.set(pkg.id, card)
48
+ cards.push(card)
49
+ }
50
+ card.matched++
51
+ card.updatedAt = Math.max(card.updatedAt, timestamp(item.updatedAt))
52
+ }
53
+ cards.sort((a, b) => {
54
+ if (sort === 'updated') {
55
+ const difference = timestamp(b.updatedAt) - timestamp(a.updatedAt)
56
+ if (difference) return difference
57
+ }
58
+ const comparison = byName.compare(a.name, b.name)
59
+ return sort === 'za' ? -comparison : comparison
60
+ })
61
+ return { cards, skillCount, packageCount: packageCards.size }
62
+ }