@kafukatree/dsh-skill-manager 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (307) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-lucide.txt +43 -0
  3. package/README.md +44 -2
  4. package/agent-tool.mjs +118 -0
  5. package/client-bridge.mjs +307 -0
  6. package/client-entry.mjs +131 -0
  7. package/client.js +6769 -0
  8. package/control-icon.mjs +40 -0
  9. package/cordis.patch.yml +4 -0
  10. package/design/skill-manager.pen +798 -0
  11. package/design.css +320 -0
  12. package/design.mjs +629 -0
  13. package/dialogs.css +460 -0
  14. package/dialogs.mjs +1130 -0
  15. package/document-link.mjs +13 -0
  16. package/file-actions.mjs +62 -0
  17. package/file-view.mjs +384 -0
  18. package/header-scroll.css +90 -0
  19. package/header-scroll.mjs +121 -0
  20. package/host.mjs +460 -0
  21. package/icon.svg +6 -0
  22. package/import-archive.mjs +41 -0
  23. package/import-commit.mjs +247 -0
  24. package/import-family.mjs +213 -0
  25. package/import-files.mjs +186 -0
  26. package/import-github.mjs +168 -0
  27. package/import-limits.mjs +10 -0
  28. package/import-native.mjs +79 -0
  29. package/imports.mjs +209 -0
  30. package/inventory.mjs +62 -0
  31. package/library.mjs +1334 -0
  32. package/local-families.mjs +277 -0
  33. package/locale/en.json +16 -0
  34. package/locale/zh.json +16 -0
  35. package/management-view.mjs +158 -0
  36. package/mode-view.mjs +72 -0
  37. package/node_modules/pend/LICENSE +23 -0
  38. package/node_modules/pend/README.md +41 -0
  39. package/node_modules/pend/index.js +55 -0
  40. package/node_modules/pend/package.json +18 -0
  41. package/node_modules/pend/test.js +137 -0
  42. package/node_modules/yaml/LICENSE +13 -0
  43. package/node_modules/yaml/README.md +172 -0
  44. package/node_modules/yaml/bin.mjs +11 -0
  45. package/node_modules/yaml/browser/dist/compose/compose-collection.js +88 -0
  46. package/node_modules/yaml/browser/dist/compose/compose-doc.js +43 -0
  47. package/node_modules/yaml/browser/dist/compose/compose-node.js +109 -0
  48. package/node_modules/yaml/browser/dist/compose/compose-scalar.js +86 -0
  49. package/node_modules/yaml/browser/dist/compose/composer.js +219 -0
  50. package/node_modules/yaml/browser/dist/compose/resolve-block-map.js +115 -0
  51. package/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +198 -0
  52. package/node_modules/yaml/browser/dist/compose/resolve-block-seq.js +49 -0
  53. package/node_modules/yaml/browser/dist/compose/resolve-end.js +37 -0
  54. package/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +207 -0
  55. package/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +226 -0
  56. package/node_modules/yaml/browser/dist/compose/resolve-props.js +146 -0
  57. package/node_modules/yaml/browser/dist/compose/util-contains-newline.js +34 -0
  58. package/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +26 -0
  59. package/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +15 -0
  60. package/node_modules/yaml/browser/dist/compose/util-map-includes.js +13 -0
  61. package/node_modules/yaml/browser/dist/doc/Document.js +335 -0
  62. package/node_modules/yaml/browser/dist/doc/anchors.js +71 -0
  63. package/node_modules/yaml/browser/dist/doc/applyReviver.js +55 -0
  64. package/node_modules/yaml/browser/dist/doc/createNode.js +88 -0
  65. package/node_modules/yaml/browser/dist/doc/directives.js +176 -0
  66. package/node_modules/yaml/browser/dist/errors.js +57 -0
  67. package/node_modules/yaml/browser/dist/index.js +17 -0
  68. package/node_modules/yaml/browser/dist/log.js +11 -0
  69. package/node_modules/yaml/browser/dist/nodes/Alias.js +118 -0
  70. package/node_modules/yaml/browser/dist/nodes/Collection.js +147 -0
  71. package/node_modules/yaml/browser/dist/nodes/Node.js +38 -0
  72. package/node_modules/yaml/browser/dist/nodes/Pair.js +36 -0
  73. package/node_modules/yaml/browser/dist/nodes/Scalar.js +24 -0
  74. package/node_modules/yaml/browser/dist/nodes/YAMLMap.js +144 -0
  75. package/node_modules/yaml/browser/dist/nodes/YAMLSeq.js +113 -0
  76. package/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +63 -0
  77. package/node_modules/yaml/browser/dist/nodes/identity.js +36 -0
  78. package/node_modules/yaml/browser/dist/nodes/toJS.js +37 -0
  79. package/node_modules/yaml/browser/dist/parse/cst-scalar.js +214 -0
  80. package/node_modules/yaml/browser/dist/parse/cst-stringify.js +61 -0
  81. package/node_modules/yaml/browser/dist/parse/cst-visit.js +97 -0
  82. package/node_modules/yaml/browser/dist/parse/cst.js +98 -0
  83. package/node_modules/yaml/browser/dist/parse/lexer.js +721 -0
  84. package/node_modules/yaml/browser/dist/parse/line-counter.js +39 -0
  85. package/node_modules/yaml/browser/dist/parse/parser.js +975 -0
  86. package/node_modules/yaml/browser/dist/public-api.js +102 -0
  87. package/node_modules/yaml/browser/dist/schema/Schema.js +37 -0
  88. package/node_modules/yaml/browser/dist/schema/common/map.js +17 -0
  89. package/node_modules/yaml/browser/dist/schema/common/null.js +15 -0
  90. package/node_modules/yaml/browser/dist/schema/common/seq.js +17 -0
  91. package/node_modules/yaml/browser/dist/schema/common/string.js +14 -0
  92. package/node_modules/yaml/browser/dist/schema/core/bool.js +19 -0
  93. package/node_modules/yaml/browser/dist/schema/core/float.js +43 -0
  94. package/node_modules/yaml/browser/dist/schema/core/int.js +38 -0
  95. package/node_modules/yaml/browser/dist/schema/core/schema.js +23 -0
  96. package/node_modules/yaml/browser/dist/schema/json/schema.js +62 -0
  97. package/node_modules/yaml/browser/dist/schema/tags.js +96 -0
  98. package/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +58 -0
  99. package/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +26 -0
  100. package/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +46 -0
  101. package/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +71 -0
  102. package/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +67 -0
  103. package/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +74 -0
  104. package/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +78 -0
  105. package/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +39 -0
  106. package/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +93 -0
  107. package/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +101 -0
  108. package/node_modules/yaml/browser/dist/stringify/foldFlowLines.js +146 -0
  109. package/node_modules/yaml/browser/dist/stringify/stringify.js +129 -0
  110. package/node_modules/yaml/browser/dist/stringify/stringifyCollection.js +153 -0
  111. package/node_modules/yaml/browser/dist/stringify/stringifyComment.js +20 -0
  112. package/node_modules/yaml/browser/dist/stringify/stringifyDocument.js +85 -0
  113. package/node_modules/yaml/browser/dist/stringify/stringifyNumber.js +25 -0
  114. package/node_modules/yaml/browser/dist/stringify/stringifyPair.js +150 -0
  115. package/node_modules/yaml/browser/dist/stringify/stringifyString.js +336 -0
  116. package/node_modules/yaml/browser/dist/util.js +11 -0
  117. package/node_modules/yaml/browser/dist/visit.js +233 -0
  118. package/node_modules/yaml/browser/index.js +5 -0
  119. package/node_modules/yaml/browser/package.json +3 -0
  120. package/node_modules/yaml/dist/cli.d.ts +8 -0
  121. package/node_modules/yaml/dist/cli.mjs +201 -0
  122. package/node_modules/yaml/dist/compose/compose-collection.d.ts +11 -0
  123. package/node_modules/yaml/dist/compose/compose-collection.js +90 -0
  124. package/node_modules/yaml/dist/compose/compose-doc.d.ts +7 -0
  125. package/node_modules/yaml/dist/compose/compose-doc.js +45 -0
  126. package/node_modules/yaml/dist/compose/compose-node.d.ts +29 -0
  127. package/node_modules/yaml/dist/compose/compose-node.js +112 -0
  128. package/node_modules/yaml/dist/compose/compose-scalar.d.ts +5 -0
  129. package/node_modules/yaml/dist/compose/compose-scalar.js +88 -0
  130. package/node_modules/yaml/dist/compose/composer.d.ts +63 -0
  131. package/node_modules/yaml/dist/compose/composer.js +224 -0
  132. package/node_modules/yaml/dist/compose/resolve-block-map.d.ts +6 -0
  133. package/node_modules/yaml/dist/compose/resolve-block-map.js +117 -0
  134. package/node_modules/yaml/dist/compose/resolve-block-scalar.d.ts +11 -0
  135. package/node_modules/yaml/dist/compose/resolve-block-scalar.js +200 -0
  136. package/node_modules/yaml/dist/compose/resolve-block-seq.d.ts +6 -0
  137. package/node_modules/yaml/dist/compose/resolve-block-seq.js +51 -0
  138. package/node_modules/yaml/dist/compose/resolve-end.d.ts +6 -0
  139. package/node_modules/yaml/dist/compose/resolve-end.js +39 -0
  140. package/node_modules/yaml/dist/compose/resolve-flow-collection.d.ts +7 -0
  141. package/node_modules/yaml/dist/compose/resolve-flow-collection.js +209 -0
  142. package/node_modules/yaml/dist/compose/resolve-flow-scalar.d.ts +10 -0
  143. package/node_modules/yaml/dist/compose/resolve-flow-scalar.js +228 -0
  144. package/node_modules/yaml/dist/compose/resolve-props.d.ts +23 -0
  145. package/node_modules/yaml/dist/compose/resolve-props.js +148 -0
  146. package/node_modules/yaml/dist/compose/util-contains-newline.d.ts +2 -0
  147. package/node_modules/yaml/dist/compose/util-contains-newline.js +36 -0
  148. package/node_modules/yaml/dist/compose/util-empty-scalar-position.d.ts +2 -0
  149. package/node_modules/yaml/dist/compose/util-empty-scalar-position.js +28 -0
  150. package/node_modules/yaml/dist/compose/util-flow-indent-check.d.ts +3 -0
  151. package/node_modules/yaml/dist/compose/util-flow-indent-check.js +17 -0
  152. package/node_modules/yaml/dist/compose/util-map-includes.d.ts +4 -0
  153. package/node_modules/yaml/dist/compose/util-map-includes.js +15 -0
  154. package/node_modules/yaml/dist/doc/Document.d.ts +141 -0
  155. package/node_modules/yaml/dist/doc/Document.js +337 -0
  156. package/node_modules/yaml/dist/doc/anchors.d.ts +24 -0
  157. package/node_modules/yaml/dist/doc/anchors.js +76 -0
  158. package/node_modules/yaml/dist/doc/applyReviver.d.ts +9 -0
  159. package/node_modules/yaml/dist/doc/applyReviver.js +57 -0
  160. package/node_modules/yaml/dist/doc/createNode.d.ts +17 -0
  161. package/node_modules/yaml/dist/doc/createNode.js +90 -0
  162. package/node_modules/yaml/dist/doc/directives.d.ts +49 -0
  163. package/node_modules/yaml/dist/doc/directives.js +178 -0
  164. package/node_modules/yaml/dist/errors.d.ts +21 -0
  165. package/node_modules/yaml/dist/errors.js +62 -0
  166. package/node_modules/yaml/dist/index.d.ts +25 -0
  167. package/node_modules/yaml/dist/index.js +50 -0
  168. package/node_modules/yaml/dist/log.d.ts +3 -0
  169. package/node_modules/yaml/dist/log.js +19 -0
  170. package/node_modules/yaml/dist/nodes/Alias.d.ts +29 -0
  171. package/node_modules/yaml/dist/nodes/Alias.js +120 -0
  172. package/node_modules/yaml/dist/nodes/Collection.d.ts +73 -0
  173. package/node_modules/yaml/dist/nodes/Collection.js +151 -0
  174. package/node_modules/yaml/dist/nodes/Node.d.ts +53 -0
  175. package/node_modules/yaml/dist/nodes/Node.js +40 -0
  176. package/node_modules/yaml/dist/nodes/Pair.d.ts +22 -0
  177. package/node_modules/yaml/dist/nodes/Pair.js +39 -0
  178. package/node_modules/yaml/dist/nodes/Scalar.d.ts +47 -0
  179. package/node_modules/yaml/dist/nodes/Scalar.js +27 -0
  180. package/node_modules/yaml/dist/nodes/YAMLMap.d.ts +53 -0
  181. package/node_modules/yaml/dist/nodes/YAMLMap.js +147 -0
  182. package/node_modules/yaml/dist/nodes/YAMLSeq.d.ts +60 -0
  183. package/node_modules/yaml/dist/nodes/YAMLSeq.js +115 -0
  184. package/node_modules/yaml/dist/nodes/addPairToJSMap.d.ts +4 -0
  185. package/node_modules/yaml/dist/nodes/addPairToJSMap.js +65 -0
  186. package/node_modules/yaml/dist/nodes/identity.d.ts +23 -0
  187. package/node_modules/yaml/dist/nodes/identity.js +53 -0
  188. package/node_modules/yaml/dist/nodes/toJS.d.ts +29 -0
  189. package/node_modules/yaml/dist/nodes/toJS.js +39 -0
  190. package/node_modules/yaml/dist/options.d.ts +350 -0
  191. package/node_modules/yaml/dist/parse/cst-scalar.d.ts +64 -0
  192. package/node_modules/yaml/dist/parse/cst-scalar.js +218 -0
  193. package/node_modules/yaml/dist/parse/cst-stringify.d.ts +8 -0
  194. package/node_modules/yaml/dist/parse/cst-stringify.js +63 -0
  195. package/node_modules/yaml/dist/parse/cst-visit.d.ts +39 -0
  196. package/node_modules/yaml/dist/parse/cst-visit.js +99 -0
  197. package/node_modules/yaml/dist/parse/cst.d.ts +109 -0
  198. package/node_modules/yaml/dist/parse/cst.js +112 -0
  199. package/node_modules/yaml/dist/parse/lexer.d.ts +87 -0
  200. package/node_modules/yaml/dist/parse/lexer.js +723 -0
  201. package/node_modules/yaml/dist/parse/line-counter.d.ts +22 -0
  202. package/node_modules/yaml/dist/parse/line-counter.js +41 -0
  203. package/node_modules/yaml/dist/parse/parser.d.ts +84 -0
  204. package/node_modules/yaml/dist/parse/parser.js +980 -0
  205. package/node_modules/yaml/dist/public-api.d.ts +44 -0
  206. package/node_modules/yaml/dist/public-api.js +107 -0
  207. package/node_modules/yaml/dist/schema/Schema.d.ts +17 -0
  208. package/node_modules/yaml/dist/schema/Schema.js +39 -0
  209. package/node_modules/yaml/dist/schema/common/map.d.ts +2 -0
  210. package/node_modules/yaml/dist/schema/common/map.js +19 -0
  211. package/node_modules/yaml/dist/schema/common/null.d.ts +4 -0
  212. package/node_modules/yaml/dist/schema/common/null.js +17 -0
  213. package/node_modules/yaml/dist/schema/common/seq.d.ts +2 -0
  214. package/node_modules/yaml/dist/schema/common/seq.js +19 -0
  215. package/node_modules/yaml/dist/schema/common/string.d.ts +2 -0
  216. package/node_modules/yaml/dist/schema/common/string.js +16 -0
  217. package/node_modules/yaml/dist/schema/core/bool.d.ts +4 -0
  218. package/node_modules/yaml/dist/schema/core/bool.js +21 -0
  219. package/node_modules/yaml/dist/schema/core/float.d.ts +4 -0
  220. package/node_modules/yaml/dist/schema/core/float.js +47 -0
  221. package/node_modules/yaml/dist/schema/core/int.d.ts +4 -0
  222. package/node_modules/yaml/dist/schema/core/int.js +42 -0
  223. package/node_modules/yaml/dist/schema/core/schema.d.ts +1 -0
  224. package/node_modules/yaml/dist/schema/core/schema.js +25 -0
  225. package/node_modules/yaml/dist/schema/json/schema.d.ts +2 -0
  226. package/node_modules/yaml/dist/schema/json/schema.js +64 -0
  227. package/node_modules/yaml/dist/schema/json-schema.d.ts +69 -0
  228. package/node_modules/yaml/dist/schema/tags.d.ts +48 -0
  229. package/node_modules/yaml/dist/schema/tags.js +99 -0
  230. package/node_modules/yaml/dist/schema/types.d.ts +92 -0
  231. package/node_modules/yaml/dist/schema/yaml-1.1/binary.d.ts +2 -0
  232. package/node_modules/yaml/dist/schema/yaml-1.1/binary.js +70 -0
  233. package/node_modules/yaml/dist/schema/yaml-1.1/bool.d.ts +7 -0
  234. package/node_modules/yaml/dist/schema/yaml-1.1/bool.js +29 -0
  235. package/node_modules/yaml/dist/schema/yaml-1.1/float.d.ts +4 -0
  236. package/node_modules/yaml/dist/schema/yaml-1.1/float.js +50 -0
  237. package/node_modules/yaml/dist/schema/yaml-1.1/int.d.ts +5 -0
  238. package/node_modules/yaml/dist/schema/yaml-1.1/int.js +76 -0
  239. package/node_modules/yaml/dist/schema/yaml-1.1/merge.d.ts +9 -0
  240. package/node_modules/yaml/dist/schema/yaml-1.1/merge.js +71 -0
  241. package/node_modules/yaml/dist/schema/yaml-1.1/omap.d.ts +22 -0
  242. package/node_modules/yaml/dist/schema/yaml-1.1/omap.js +77 -0
  243. package/node_modules/yaml/dist/schema/yaml-1.1/pairs.d.ts +10 -0
  244. package/node_modules/yaml/dist/schema/yaml-1.1/pairs.js +82 -0
  245. package/node_modules/yaml/dist/schema/yaml-1.1/schema.d.ts +1 -0
  246. package/node_modules/yaml/dist/schema/yaml-1.1/schema.js +41 -0
  247. package/node_modules/yaml/dist/schema/yaml-1.1/set.d.ts +28 -0
  248. package/node_modules/yaml/dist/schema/yaml-1.1/set.js +96 -0
  249. package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.d.ts +6 -0
  250. package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +105 -0
  251. package/node_modules/yaml/dist/stringify/foldFlowLines.d.ts +34 -0
  252. package/node_modules/yaml/dist/stringify/foldFlowLines.js +151 -0
  253. package/node_modules/yaml/dist/stringify/stringify.d.ts +21 -0
  254. package/node_modules/yaml/dist/stringify/stringify.js +132 -0
  255. package/node_modules/yaml/dist/stringify/stringifyCollection.d.ts +17 -0
  256. package/node_modules/yaml/dist/stringify/stringifyCollection.js +155 -0
  257. package/node_modules/yaml/dist/stringify/stringifyComment.d.ts +10 -0
  258. package/node_modules/yaml/dist/stringify/stringifyComment.js +24 -0
  259. package/node_modules/yaml/dist/stringify/stringifyDocument.d.ts +4 -0
  260. package/node_modules/yaml/dist/stringify/stringifyDocument.js +87 -0
  261. package/node_modules/yaml/dist/stringify/stringifyNumber.d.ts +2 -0
  262. package/node_modules/yaml/dist/stringify/stringifyNumber.js +27 -0
  263. package/node_modules/yaml/dist/stringify/stringifyPair.d.ts +3 -0
  264. package/node_modules/yaml/dist/stringify/stringifyPair.js +152 -0
  265. package/node_modules/yaml/dist/stringify/stringifyString.d.ts +9 -0
  266. package/node_modules/yaml/dist/stringify/stringifyString.js +338 -0
  267. package/node_modules/yaml/dist/test-events.d.ts +4 -0
  268. package/node_modules/yaml/dist/test-events.js +134 -0
  269. package/node_modules/yaml/dist/util.d.ts +16 -0
  270. package/node_modules/yaml/dist/util.js +28 -0
  271. package/node_modules/yaml/dist/visit.d.ts +102 -0
  272. package/node_modules/yaml/dist/visit.js +236 -0
  273. package/node_modules/yaml/package.json +97 -0
  274. package/node_modules/yaml/util.js +2 -0
  275. package/node_modules/yauzl/LICENSE +21 -0
  276. package/node_modules/yauzl/README.md +1015 -0
  277. package/node_modules/yauzl/crc32.js +45 -0
  278. package/node_modules/yauzl/fd-slicer.js +188 -0
  279. package/node_modules/yauzl/index.js +1096 -0
  280. package/node_modules/yauzl/package.json +40 -0
  281. package/package-files.mjs +244 -0
  282. package/package-view.mjs +375 -0
  283. package/package.css +131 -0
  284. package/package.json +75 -4
  285. package/removal.mjs +313 -0
  286. package/scripts/build.mjs +19 -0
  287. package/scripts/export-design.py +587 -0
  288. package/scripts/run-tests.mjs +14 -0
  289. package/skill-state.mjs +136 -0
  290. package/skills/skill-creator/SKILL.md +48 -0
  291. package/styles.mjs +10 -0
  292. package/surfaces.css +593 -0
  293. package/test/agent-tool.test.mjs +153 -0
  294. package/test/client-bridge.test.mjs +240 -0
  295. package/test/distribution.test.mjs +17 -0
  296. package/test/host.test.mjs +598 -0
  297. package/test/imports.test.mjs +491 -0
  298. package/test/inventory.test.mjs +144 -0
  299. package/test/library.test.mjs +785 -0
  300. package/test/local-families.test.mjs +220 -0
  301. package/test/management-view.test.mjs +102 -0
  302. package/test/mode-view.test.mjs +26 -0
  303. package/test/package-files.test.mjs +221 -0
  304. package/toolbar.css +228 -0
  305. package/typography.css +173 -0
  306. package/ui.css +399 -0
  307. package/ui.mjs +1545 -0
package/ui.mjs ADDED
@@ -0,0 +1,1545 @@
1
+ import { designFragment, designMenus, designText, icon as penIcon, skillAppearance } from './design.mjs'
2
+ import { controlIcon as icon } from './control-icon.mjs'
3
+ import { openFlow, openRecoveryDialog, openRemovalDialog } from './dialogs.mjs'
4
+ import { builtinPreview, indexInventory, inventoryResults } from './inventory.mjs'
5
+ import { createPackageView } from './package-view.mjs'
6
+ import { createFileView } from './file-view.mjs'
7
+ import { AGENT_FILTERS, skillState } from './skill-state.mjs'
8
+ import { createScopeFilters } from './mode-view.mjs'
9
+ import { attachHeaderScroll } from './header-scroll.mjs'
10
+
11
+ const text = designText
12
+ const sourceNames = new Map(Object.entries({
13
+ 'project-dsh': '项目 DSH 目录',
14
+ 'project-agents': '项目共享目录',
15
+ 'user-dsh': 'DSH 个人目录',
16
+ 'user-agents': '个人共享目录',
17
+ custom: '自定义目录', personal: 'DSH 个人目录', project: '项目目录', shared: '共享目录',
18
+ bundled: '随包提供', preset: 'Agent 预设', runtime: '运行时提供',
19
+ }))
20
+ const categoryNames = new Map([
21
+ ['builtin', '内置技能'], ['experimental', '实验性技能'], ['user', '用户技能'], ['provided', '插件与预设技能'],
22
+ ])
23
+ const emptyModes = []
24
+ let mountCount = 0
25
+
26
+ function sourceName(source) {
27
+ return sourceNames.get(source) || source || '未标注来源'
28
+ }
29
+
30
+ function canToggle(item) {
31
+ return item.canToggle ?? (item.managed !== false)
32
+ }
33
+
34
+ function categoryOf(item) {
35
+ if (categoryNames.has(item.category)) return item.category
36
+ if (['project-dsh', 'project-agents', 'user-dsh', 'user-agents'].includes(item.source)) return 'user'
37
+ if (item.source === 'custom' && item.directoryId) return 'user'
38
+ return 'provided'
39
+ }
40
+
41
+ function errorText(error) {
42
+ if (typeof error === 'string') return error
43
+ return error?.message || '请求未完成,请重试。'
44
+ }
45
+
46
+ function hasSnapshot(value) {
47
+ return Array.isArray(value?.items) && Array.isArray(value.directories)
48
+ }
49
+
50
+ function containingPath(item) {
51
+ return item.directoryPath || item.path?.replace(/[/\\][^/\\]+$/, '') || ''
52
+ }
53
+
54
+ export function mountManager(container, api, renderMarkdown, management) {
55
+ const doc = container.ownerDocument
56
+ const win = doc.defaultView
57
+ const prefix = `dsh-skill-manager-${++mountCount}`
58
+ const scope = new AbortController()
59
+ const rows = new Map()
60
+ const packageRows = new Map()
61
+ const pendingToggles = new Set()
62
+ const notices = new Map()
63
+ let snapshot = { items: [], directories: [] }
64
+ let itemsById = new Map()
65
+ let packagesById = new Map()
66
+ let directoriesById = new Map()
67
+ const duplicateNames = new Set()
68
+ let hasLoaded = false
69
+ let scanning = false
70
+ let reading = false
71
+ let readError = ''
72
+ let route = 'list'
73
+ let query = management?.preferences.query ?? ''
74
+ let filter = management?.preferences.filter ?? 'all'
75
+ let sort = management?.preferences.sort ?? 'updated'
76
+ let activeMenu = null
77
+ let directoryDialog = null
78
+ let removalDialog = null
79
+ let flow = null
80
+ let openingCreator = false
81
+ let detailId = null
82
+ let detail = null
83
+ let detailError = ''
84
+ let detailVersion = 0
85
+ let detailTab = 'overview'
86
+ let fileSelection = null
87
+ let resourceReset = false
88
+ let overviewScroll = 0
89
+ let instructionScroll = 0
90
+ let openChoices = null
91
+ let pendingOpen = null
92
+ let skillDocument = null
93
+ let listScroll = 0
94
+ let openPackageId = null
95
+ let packageQuery = ''
96
+ let packageFilter = 'all'
97
+ let packageReset = false
98
+ let packageFocus = false
99
+ let moreScroll = 0
100
+ let moreFocus = null
101
+ let inMore = false
102
+ let returnKey = ''
103
+ let disposed = false
104
+ let queue = Promise.resolve()
105
+
106
+ function el(tag, className, content) {
107
+ const node = doc.createElement(tag)
108
+ if (className) node.className = className
109
+ if (content != null) node.textContent = content
110
+ return node
111
+ }
112
+
113
+ function button(label, className, action, glyph, glyphSize = 16) {
114
+ const node = el('button', className)
115
+ node.type = 'button'
116
+ if (glyph) node.append(icon(glyph, glyphSize))
117
+ if (label) node.append(el('span', '', label))
118
+ if (action) node.addEventListener('click', action)
119
+ return node
120
+ }
121
+
122
+ function labelButton(node, label) {
123
+ node.setAttribute('aria-label', label)
124
+ node.title = label
125
+ return node
126
+ }
127
+
128
+ function remember(node, key) {
129
+ node.dataset.smFocus = key
130
+ return node
131
+ }
132
+
133
+ function focusKey(key, fallback) {
134
+ const target = Array.from(page.querySelectorAll('[data-sm-focus]')).find(node =>
135
+ node.dataset.smFocus === key && !node.disabled && node.getClientRects().length)
136
+ const next = target || fallback
137
+ next?.focus({ preventScroll: true })
138
+ }
139
+
140
+ function navigationFocus() {
141
+ if (route === 'list') return tabButtons.get(filter)
142
+ if (route === 'builtin') return moreBack
143
+ return route === 'package' ? packagePane.querySelector('button') : subPane.querySelector('[data-sm-focus="back"]')
144
+ }
145
+
146
+ const root = el('div', 'sm-design sm-manager')
147
+ const scroller = el('div', 'sm-ui-scroll')
148
+ const page = el('div', 'sm-ui-page')
149
+ const listPane = el('section', 'sm-ui-library')
150
+ const subPane = el('section', 'sm-ui-subpage')
151
+ const detailSummary = el('div')
152
+ const detailTabs = el('div', 'sm-ui-tab-row sm-pkg-tabs sm-ui-detail-tabs')
153
+ const overviewPane = el('section')
154
+ const overviewFacts = el('div')
155
+ const detailFilesPane = el('section')
156
+ overviewPane.append(overviewFacts)
157
+ subPane.append(detailSummary, detailTabs, overviewPane, detailFilesPane)
158
+ const packagePane = el('section', 'sm-ui-subpage sm-ui-package-page')
159
+ const toastStack = el('div', 'sm-ui-toasts')
160
+ subPane.hidden = true
161
+ packagePane.hidden = true
162
+ page.append(listPane, subPane, packagePane)
163
+ scroller.append(page)
164
+ root.append(scroller, toastStack)
165
+ container.append(root)
166
+ const packageView = createPackageView(packagePane, api, {
167
+ renderMarkdown, menuTrigger, openMenu,
168
+ back: () => navigate(inMore ? 'builtin' : 'list'),
169
+ openSkill: id => showDetail(id),
170
+ removePackage: pkg => startRemoval('package', pkg.id, `remove-package-${pkg.id}`),
171
+ setEnabled: (id, enabled) => ordered(async () => {
172
+ const pkg = packagesById.get(id)?.pkg
173
+ if (!pkg?.canToggle) throw new Error('此技能包的启用状态由其来源管理。')
174
+ if (pkg.enabled === enabled) return
175
+ await reconcile(await api.setPackageEnabled(id, enabled))
176
+ if (!disposed) notify(`已${enabled ? '启用' : '停用'}技能包 ${pkg.label || pkg.name}`, { key: `package-${id}` })
177
+ }),
178
+ })
179
+ const detailFiles = createFileView(detailFilesPane, {
180
+ entries: (path, offset) => api.skillEntries(detailId, path, offset),
181
+ file: path => api.skillFile(detailId, path),
182
+ }, { renderMarkdown })
183
+
184
+ function dismissNotice(key) {
185
+ const notice = notices.get(key)
186
+ if (!notice) return
187
+ const hadFocus = notice.node.contains(doc.activeElement)
188
+ win.clearTimeout(notice.timer)
189
+ notice.node.remove()
190
+ notices.delete(key)
191
+ if (hadFocus && !disposed) {
192
+ let destination = notice.returnFocus
193
+ if (notice.itemId) destination = route === 'detail' && detailId === notice.itemId ? 'detail-switch' : `switch-${notice.itemId}`
194
+ focusKey(destination, navigationFocus())
195
+ }
196
+ }
197
+
198
+ function notify(message, { key = Symbol(), error = false, undo, itemId, focusUndo = false } = {}) {
199
+ if (disposed || !message) return
200
+ dismissNotice(key)
201
+ if (notices.size >= 3) dismissNotice(notices.keys().next().value)
202
+ const node = el('div', `sm-ui-toast${error ? ' sm-ui-toast-error' : ''}`)
203
+ node.setAttribute('role', error ? 'alert' : 'status')
204
+ const glyph = el('span', 'sm-ui-notice-glyph')
205
+ glyph.append(icon(error ? 'circle-alert' : 'circle-check', 17))
206
+ node.append(glyph, el('span', 'sm-ui-notice-text', message))
207
+ let undoButton
208
+ if (undo) {
209
+ undoButton = button(text('skv-358', '撤销'), 'sm-ui-text-action', () => {
210
+ dismissNotice(key)
211
+ undo()
212
+ })
213
+ if (focusUndo) undoButton.dataset.action = 'undo-removal'
214
+ node.append(undoButton)
215
+ } else if (error) {
216
+ node.append(labelButton(button('', 'sm-ui-toast-close', () => dismissNotice(key), 'x'), '关闭提示'))
217
+ }
218
+ const notice = { node, timer: 0, itemId, returnFocus: doc.activeElement?.dataset.smFocus }
219
+ const pause = () => win.clearTimeout(notice.timer)
220
+ const resume = () => {
221
+ pause()
222
+ if (!node.matches(':hover, :focus-within')) {
223
+ notice.timer = win.setTimeout(() => dismissNotice(key), undo || error ? 9000 : 5000)
224
+ }
225
+ }
226
+ node.addEventListener('pointerenter', pause)
227
+ node.addEventListener('pointerleave', resume)
228
+ node.addEventListener('focusin', pause)
229
+ node.addEventListener('focusout', () => queueMicrotask(() => { if (node.isConnected) resume() }))
230
+ notices.set(key, notice)
231
+ toastStack.append(node)
232
+ if (focusUndo) undoButton?.focus({ preventScroll: true })
233
+ resume()
234
+ }
235
+
236
+ function closeMenu(restoreFocus = false) {
237
+ if (pendingOpen) {
238
+ pendingOpen.abort()
239
+ pendingOpen = null
240
+ openWith.removeAttribute('aria-busy')
241
+ openWith.title = openWith.getAttribute('aria-label')
242
+ }
243
+ if (!activeMenu) return
244
+ const { node, anchor, events, observer } = activeMenu
245
+ activeMenu = null
246
+ events.abort()
247
+ observer?.disconnect()
248
+ node.remove()
249
+ anchor.setAttribute('aria-expanded', 'false')
250
+ anchor.removeAttribute('aria-controls')
251
+ if (restoreFocus && anchor.isConnected) anchor.focus({ preventScroll: true })
252
+ }
253
+
254
+ function positionMenu() {
255
+ if (!activeMenu) return
256
+ const { node, anchor } = activeMenu
257
+ const bounds = root.getBoundingClientRect()
258
+ const rect = anchor.getBoundingClientRect()
259
+ if (!anchor.isConnected || !rect.width || rect.bottom <= bounds.top || rect.top >= bounds.bottom) {
260
+ const keyboardInside = node.contains(doc.activeElement)
261
+ closeMenu()
262
+ if (keyboardInside) focusKey(anchor.dataset.smFocus, tabButtons.get(filter))
263
+ return
264
+ }
265
+ const margin = 12
266
+ const gap = 4
267
+ const below = bounds.bottom - rect.bottom - gap - margin
268
+ const above = rect.top - bounds.top - gap - margin
269
+ const scopeMenu = node.classList.contains('sm-ui-menu-scope')
270
+ const availableHeight = scopeMenu ? Math.max(above, below) : bounds.height - margin * 2
271
+ node.style.maxHeight = `${Math.max(0, availableHeight)}px`
272
+ const height = node.offsetHeight
273
+ let top = rect.bottom - bounds.top + gap
274
+ if (below < height) top = above >= height ? rect.top - bounds.top - gap - height : margin
275
+ const preferredLeft = (scopeMenu ? rect.left : rect.right - node.offsetWidth) - bounds.left
276
+ const left = Math.max(margin, Math.min(preferredLeft, bounds.width - node.offsetWidth - margin))
277
+ node.style.left = `${left}px`
278
+ node.style.top = `${top}px`
279
+ }
280
+
281
+ function openMenu(anchor, kind, entries, select, first = 'first') {
282
+ if (activeMenu?.anchor === anchor) { closeMenu(true); return }
283
+ closeMenu()
284
+ const node = el('div', `sm-ui-menu sm-ui-menu-${kind}`)
285
+ const events = new AbortController()
286
+ const enabled = []
287
+ node.id = `${prefix}-menu`
288
+ node.dataset.menuMaterial = 'translucent'
289
+ node.setAttribute('role', 'menu')
290
+ node.setAttribute('aria-label', anchor.getAttribute('aria-label') || anchor.textContent)
291
+ function menuItem(entry) {
292
+ if (entry.separatorBefore) {
293
+ const separator = el('div', 'sm-ui-menu-divider')
294
+ separator.setAttribute('role', 'separator')
295
+ node.append(separator)
296
+ }
297
+ const choice = button('', 'sm-ui-menu-item', () => { closeMenu(true); select(entry.action) })
298
+ choice.dataset.action = entry.action
299
+ choice.tabIndex = -1
300
+ if (kind === 'scope') choice.title = entry.label
301
+ const checked = kind === 'sort' ? sort === entry.action : entry.checked
302
+ choice.setAttribute('role', typeof checked === 'boolean' ? 'menuitemradio' : 'menuitem')
303
+ if (entry.icon && kind !== 'sort') choice.append(icon(entry.icon, 14))
304
+ const lines = el('span', 'sm-ui-menu-copy')
305
+ lines.append(el('span', 'sm-ui-menu-label', entry.label))
306
+ if (entry.description) lines.append(el('span', 'sm-ui-menu-description', entry.description))
307
+ choice.append(lines)
308
+ if (typeof checked === 'boolean') {
309
+ choice.setAttribute('aria-checked', String(checked))
310
+ if (checked) choice.append(icon('check', 14))
311
+ }
312
+ if (entry.disabled) {
313
+ choice.disabled = true
314
+ choice.title = entry.reason || '当前不可用'
315
+ } else enabled.push(choice)
316
+ node.append(choice)
317
+ }
318
+ entries.forEach(menuItem)
319
+ root.append(node)
320
+ anchor.setAttribute('aria-expanded', 'true')
321
+ anchor.setAttribute('aria-controls', node.id)
322
+ const observer = win.ResizeObserver ? new win.ResizeObserver(positionMenu) : null
323
+ activeMenu = { node, anchor, events, observer }
324
+ observer?.observe(root)
325
+ observer?.observe(anchor)
326
+ positionMenu()
327
+ if (!activeMenu) return
328
+ const selected = node.querySelector('[aria-checked="true"]:enabled')
329
+ const initial = first === 'last' ? enabled.at(-1) : (selected || enabled[0])
330
+ if (initial) {
331
+ initial.setAttribute('data-dsh-automatic-focus', '')
332
+ const clearAutomaticFocus = () => initial.removeAttribute('data-dsh-automatic-focus')
333
+ initial.addEventListener('blur', clearAutomaticFocus, { once: true, signal: events.signal })
334
+ initial.addEventListener('keydown', clearAutomaticFocus, { once: true, signal: events.signal })
335
+ initial.focus({ preventScroll: true })
336
+ if (first === 'last' || selected) initial.scrollIntoView({ block: 'nearest', container: 'nearest' })
337
+ }
338
+ const outside = event => {
339
+ if (!node.contains(event.target) && !anchor.contains(event.target)) closeMenu()
340
+ }
341
+ doc.addEventListener('pointerdown', outside, { capture: true, signal: events.signal })
342
+ doc.addEventListener('focusin', outside, { signal: events.signal })
343
+ scroller.addEventListener('scroll', positionMenu, { passive: true, signal: events.signal })
344
+ win.addEventListener('resize', positionMenu, { signal: events.signal })
345
+ let searchPrefix = ''
346
+ let lastTyped = 0
347
+ node.addEventListener('keydown', event => {
348
+ const index = enabled.indexOf(doc.activeElement)
349
+ let next
350
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); return }
351
+ if (event.key === 'Tab') { closeMenu(true); return }
352
+ if (event.key === 'ArrowDown') next = (index + 1) % enabled.length
353
+ if (event.key === 'ArrowUp') next = (index - 1 + enabled.length) % enabled.length
354
+ if (event.key === 'Home') next = 0
355
+ if (event.key === 'End') next = enabled.length - 1
356
+ if (kind === 'scope' && event.key.length === 1 && event.key !== ' ' && !event.isComposing &&
357
+ !event.ctrlKey && !event.metaKey && !event.altKey) {
358
+ const letter = event.key.toLocaleLowerCase()
359
+ searchPrefix = event.timeStamp - lastTyped < 650 && searchPrefix !== letter ? searchPrefix + letter : letter
360
+ lastTyped = event.timeStamp
361
+ const start = Math.max(0, searchPrefix.length === 1 ? index + 1 : index)
362
+ const match = [...enabled.slice(start), ...enabled.slice(0, start)].find(item => item.title.toLocaleLowerCase().startsWith(searchPrefix))
363
+ if (match) next = enabled.indexOf(match)
364
+ }
365
+ if (next !== undefined) { event.preventDefault(); enabled[next]?.focus() }
366
+ })
367
+ }
368
+
369
+ function menuTrigger(node, label, open) {
370
+ labelButton(node, label)
371
+ node.setAttribute('aria-haspopup', 'menu')
372
+ node.setAttribute('aria-expanded', 'false')
373
+ node.addEventListener('click', () => open('first'))
374
+ node.addEventListener('keydown', event => {
375
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return
376
+ event.preventDefault()
377
+ open(event.key === 'ArrowUp' ? 'last' : 'first')
378
+ })
379
+ }
380
+
381
+ // Host mutations supply whole snapshots. Queue reads and writes together so a slow
382
+ // scan or an older mutation cannot replace the result of a later user action.
383
+ function ordered(task) {
384
+ const result = queue.then(() => { if (!disposed) return task() })
385
+ queue = result.catch(() => {})
386
+ return result
387
+ }
388
+
389
+ function adopt(value) {
390
+ if (disposed) return
391
+ if (!hasSnapshot(value)) throw new Error('技能管理器未收到有效的技能列表。')
392
+ snapshot = value
393
+ if (management && Array.isArray(value.modes)) management.preferences.modes = value.modes
394
+ itemsById = new Map(value.items.map(item => [item.id, item]))
395
+ packagesById = indexInventory(value.items)
396
+ directoriesById = new Map(value.directories.map(dir => [dir.id, dir]))
397
+ duplicateNames.clear()
398
+ const seen = new Set()
399
+ for (const item of value.items) {
400
+ if (seen.has(item.name)) duplicateNames.add(item.name)
401
+ seen.add(item.name)
402
+ }
403
+ hasLoaded = true
404
+ readError = ''
405
+ for (const id of rows.keys()) if (!itemsById.has(id)) rows.delete(id)
406
+ for (const id of packageRows.keys()) if (!packagesById.has(id)) packageRows.delete(id)
407
+ renderCurrent()
408
+ }
409
+
410
+ async function reconcile(value) {
411
+ if (disposed) return
412
+ adopt(hasSnapshot(value) ? value : await api.list())
413
+ }
414
+
415
+ async function removalWrite(write) {
416
+ try {
417
+ return await ordered(async () => {
418
+ const result = await write()
419
+ try { await reconcile(result.snapshot) } catch (error) { reportReadError(result.warning || error) }
420
+ return result.receipt
421
+ })
422
+ } catch (error) {
423
+ if (!disposed && ['CONNECTION_FAILED', 'RECOVERY_REQUIRED', 'SNAPSHOT_FAILED', 'TARGET_CHANGED', 'REMOVAL_NOT_ALLOWED'].includes(error?.code)) void load()
424
+ throw error
425
+ }
426
+ }
427
+
428
+ function startRemoval(kind, id, trigger) {
429
+ if (disposed || removalDialog || !api.prepareRemoval) return
430
+ const item = kind === 'package' ? packagesById.get(id)?.pkg : itemsById.get(id)
431
+ if (!item?.canRemove) return
432
+ closeMenu(true)
433
+ removalDialog = openRemovalDialog(root, {
434
+ kind, id,
435
+ prepare: () => ordered(() => api.prepareRemoval(kind, id)),
436
+ commit: token => removalWrite(() => api.commitRemoval(token)),
437
+ onRemoved: receipt => {
438
+ if (kind === 'skill' && route === 'detail' && detailId === id) navigate('list')
439
+ else if (kind === 'package' && route === 'package' && openPackageId === id) navigate(inMore ? 'builtin' : 'list')
440
+ if (route === 'list') focusKey(trigger, search)
441
+ notify(`已删除 ${receipt.name}`, { key: `removal-${receipt.id}`, focusUndo: true,
442
+ undo: receipt.canRestore ? () => void undoRemoval(receipt) : undefined })
443
+ if (readError && route !== 'list') notify(readError, { key: 'refresh', error: true })
444
+ },
445
+ onClose: restoreFocus => {
446
+ removalDialog = null
447
+ if (restoreFocus && !disposed) focusKey(trigger, navigationFocus())
448
+ },
449
+ })
450
+ }
451
+
452
+ async function undoRemoval(receipt) {
453
+ try {
454
+ const restored = await removalWrite(() => api.restoreRemoval(receipt.id))
455
+ if (!disposed) notify(`已恢复 ${restored.name}`, { key: 'recovery' })
456
+ } catch (error) {
457
+ notify(`${errorText(error)} 可在“已删除”中查看恢复状态。`, { key: 'recovery', error: true })
458
+ }
459
+ }
460
+
461
+ function showRecovery() {
462
+ if (disposed || removalDialog || !api.listRemovals) return
463
+ closeMenu(true)
464
+ removalDialog = openRecoveryDialog(root, {
465
+ list: () => ordered(() => api.listRemovals()),
466
+ restore: id => removalWrite(() => api.restoreRemoval(id)),
467
+ onRestored: id => dismissNotice(`removal-${id}`),
468
+ onClose: restoreFocus => {
469
+ removalDialog = null
470
+ if (restoreFocus && !disposed) focusKey('removed-skills', navigationFocus())
471
+ },
472
+ })
473
+ }
474
+
475
+ function reportReadError(error) {
476
+ if (disposed) return
477
+ readError = errorText(error)
478
+ renderCurrent()
479
+ }
480
+
481
+ async function load(scan = false) {
482
+ if ((scan && scanning) || (!scan && reading)) return
483
+ if (scan) scanning = true
484
+ else reading = true
485
+ renderCurrent()
486
+ try {
487
+ await ordered(async () => {
488
+ await reconcile(scan ? await api.refresh() : await api.list())
489
+ if (scan) {
490
+ const message = snapshot.complete === false
491
+ ? `已读取 ${snapshot.items.length} 个技能,部分目录仍需重试`
492
+ : `刷新完成,找到 ${snapshot.items.length} 个技能`
493
+ notify(message, { key: 'refresh' })
494
+ }
495
+ })
496
+ } catch (error) { reportReadError(error) }
497
+ finally {
498
+ if (scan) scanning = false
499
+ else reading = false
500
+ if (!disposed) renderCurrent()
501
+ }
502
+ }
503
+
504
+ async function imported(message) {
505
+ if (disposed) return
506
+ try { await ordered(async () => adopt(await api.list())) }
507
+ catch (error) { reportReadError(error) }
508
+ notify(message, { key: 'import' })
509
+ }
510
+
511
+ async function openCreatorDraft() {
512
+ if (openingCreator || disposed) return
513
+ openingCreator = true
514
+ dismissNotice('create-draft')
515
+ try { await api.openCreatorDraft() }
516
+ catch (error) {
517
+ if (error?.name !== 'AbortError') notify(`未能打开技能创建会话。${errorText(error)}`, { key: 'create-draft', error: true })
518
+ }
519
+ finally { openingCreator = false }
520
+ }
521
+
522
+ function startFlow(kind) {
523
+ closeMenu(true)
524
+ flow?.cleanup()
525
+ if (kind === 'agent') { void openCreatorDraft(); return }
526
+ try { flow = openFlow(root, api, { kind }, imported) }
527
+ catch (error) { notify(errorText(error), { error: true }) }
528
+ }
529
+
530
+ async function toggle(id, enabled, undoing = false) {
531
+ const original = itemsById.get(id)
532
+ if (!original || !canToggle(original) || pendingToggles.has(id)) return
533
+ const key = `toggle-${id}`
534
+ if (original.enabled === enabled) { dismissNotice(key); return }
535
+ pendingToggles.add(id)
536
+ renderCurrent()
537
+ try {
538
+ await ordered(async () => {
539
+ const current = itemsById.get(id)
540
+ if (!current || !canToggle(current)) throw new Error('技能已变更,请刷新后重试。')
541
+ if (current.enabled === enabled) { dismissNotice(key); return }
542
+ const result = await api.setEnabled(id, enabled)
543
+ await reconcile(result)
544
+ const updated = itemsById.get(id)
545
+ if (!updated || updated.enabled !== enabled) throw new Error('技能状态已变更,请刷新后核对。')
546
+ notify(`${undoing ? '已撤销操作,' : ''}${updated.name} 的 Agent 自动调用设置已${enabled ? '开启' : '关闭'}`, {
547
+ key, itemId: id, undo: undoing ? undefined : () => toggle(id, !enabled, true),
548
+ })
549
+ })
550
+ } catch (error) { notify(errorText(error), { key, error: true, itemId: id }) }
551
+ finally {
552
+ pendingToggles.delete(id)
553
+ if (!disposed) renderCurrent()
554
+ }
555
+ }
556
+
557
+ const header = designFragment('header')
558
+ header.setAttribute('data-window-drag', '')
559
+ const part = (parent, name) => parent.querySelector(`[data-part="${name}"]`)
560
+ const scopeCaption = part(header, 'description')
561
+ scopeCaption.textContent = '管理技能来源和 Agent 自动调用设置。各模式的调用方式见技能详情。'
562
+ const directoryButton = remember(part(header, 'directories'), 'directories')
563
+ const refreshButton = remember(part(header, 'refresh'), 'refresh')
564
+ const addButton = remember(part(header, 'add'), 'add')
565
+ const addMenuButton = remember(part(header, 'add-menu'), 'add-menu')
566
+ const refreshLabel = part(header, 'refresh-label')
567
+ const idleRefreshLabel = refreshLabel.textContent
568
+ const addLabel = part(header, 'add-label').textContent
569
+ labelButton(directoryButton, part(header, 'directories-label').textContent)
570
+ labelButton(refreshButton, idleRefreshLabel)
571
+ labelButton(addButton, addLabel)
572
+ const split = part(header, 'split')
573
+ split.setAttribute('role', 'group')
574
+ split.setAttribute('aria-label', addLabel)
575
+ for (const slot of header.querySelectorAll('[data-pen-icon]')) {
576
+ slot.replaceChildren(icon(slot.dataset.penIcon, Number(slot.dataset.size)))
577
+ }
578
+ directoryButton.addEventListener('click', () => navigate('directories', 'directories'))
579
+ refreshButton.addEventListener('click', () => load(true))
580
+ addButton.addEventListener('click', () => startFlow('local'))
581
+ menuTrigger(addMenuButton, '选择添加技能的方式', first => openMenu(addMenuButton, 'add', designMenus.add, startFlow, first))
582
+
583
+ const tabs = el('div', 'sm-ui-tabs')
584
+ tabs.setAttribute('role', 'tablist')
585
+ tabs.setAttribute('aria-label', 'Agent 调用状态')
586
+ const tabRow = el('div', 'sm-ui-tab-row')
587
+ tabRow.append(tabs)
588
+ header.append(tabRow)
589
+ function setFilter(next, focus = false) {
590
+ filter = next
591
+ renderList()
592
+ if (focus) tabButtons.get(next).focus()
593
+ }
594
+ const tabButtons = new Map(AGENT_FILTERS.map(({ value, label }, i) => {
595
+ const tab = button(label, 'sm-ui-tab', () => setFilter(value))
596
+ tab.id = `${prefix}-tab-${value}`
597
+ tab.setAttribute('role', 'tab')
598
+ tab.setAttribute('aria-controls', `${prefix}-results`)
599
+ tab.addEventListener('keydown', event => {
600
+ const count = AGENT_FILTERS.length
601
+ const next = { ArrowLeft: (i - 1 + count) % count, ArrowRight: (i + 1) % count, Home: 0, End: count - 1 }[event.key]
602
+ if (next !== undefined) { event.preventDefault(); event.stopPropagation(); setFilter(AGENT_FILTERS[next].value, true) }
603
+ })
604
+ tabs.append(tab)
605
+ return [value, tab]
606
+ }))
607
+ const searchBox = el('div', 'sm-ui-search')
608
+ const search = remember(el('input', 'sm-ui-search-input'), 'search')
609
+ search.type = 'search'
610
+ search.placeholder = '搜索技能包、技能名称或描述'
611
+ search.setAttribute('aria-label', search.placeholder)
612
+ search.setAttribute('aria-controls', `${prefix}-results`)
613
+ search.autocomplete = 'off'
614
+ search.spellcheck = false
615
+ search.value = query
616
+ search.addEventListener('input', () => { query = search.value; renderList() })
617
+ const clearSearch = () => { search.value = ''; query = ''; renderList(); search.focus() }
618
+ const clearButton = labelButton(button('', 'sm-ui-icon-button', clearSearch, 'x'), '清除搜索')
619
+ searchBox.append(icon('search', 17), search, clearButton)
620
+ searchBox.addEventListener('click', event => { if (!clearButton.contains(event.target)) search.focus() })
621
+
622
+ const results = el('div', 'sm-ui-results')
623
+ results.id = `${prefix}-results`
624
+ results.setAttribute('role', 'tabpanel')
625
+ const summary = el('div', 'sm-ui-summary')
626
+ const listTitle = el('h2', 'sm-ui-list-title')
627
+ const count = el('span', 'sm-ui-count')
628
+ const progress = el('span', 'sm-ui-scan-status')
629
+ progress.setAttribute('role', 'status')
630
+ const sortButton = remember(button('', 'sm-ui-sort'), 'sort')
631
+ menuTrigger(sortButton, '排序方式', first => openMenu(sortButton, 'sort', designMenus.sort, value => {
632
+ sort = value
633
+ renderList()
634
+ }, first))
635
+ const sortLabel = el('span')
636
+ sortButton.append(sortLabel, icon('chevron-down', 13))
637
+ const recoveryButton = remember(button('已删除', 'sm-ui-text-action sm-ui-recovery', showRecovery), 'removed-skills')
638
+ recoveryButton.setAttribute('aria-haspopup', 'dialog')
639
+ recoveryButton.hidden = typeof api.listRemovals !== 'function'
640
+ summary.append(listTitle, count, progress, sortButton, recoveryButton)
641
+ const listStatus = el('div', 'sm-ui-list-status')
642
+ const list = el('div', 'sm-ui-library-groups')
643
+ const groups = new Map()
644
+ for (const [category, name] of categoryNames) {
645
+ const section = el('section', 'sm-ui-skill-group')
646
+ const head = el('div', 'sm-ui-group-head')
647
+ const title = el('h3', 'sm-ui-group-title', name)
648
+ const quantity = el('span', 'sm-ui-count')
649
+ const entries = el('div', 'sm-ui-rows')
650
+ title.id = `${prefix}-group-${category}`
651
+ section.setAttribute('aria-labelledby', title.id)
652
+ section.dataset.category = category
653
+ section.hidden = true
654
+ entries.setAttribute('role', 'list')
655
+ entries.setAttribute('aria-labelledby', title.id)
656
+ head.append(title, quantity)
657
+ let more
658
+ if (category === 'builtin') {
659
+ more = remember(button('更多', 'sm-ui-group-more', () => navigate('builtin', 'more-builtin')), 'more-builtin')
660
+ more.setAttribute('aria-label', '查看更多内置技能')
661
+ more.append(icon('chevron-right', 14))
662
+ more.hidden = true
663
+ head.append(more)
664
+ }
665
+ section.append(head, entries)
666
+ list.append(section)
667
+ groups.set(category, { section, quantity, entries, more })
668
+ }
669
+ const empty = el('div', 'sm-ui-empty')
670
+ results.append(summary, listStatus, list, empty)
671
+ const scopeFilters = management && createScopeFilters(doc, {
672
+ ...management,
673
+ menuTrigger, openMenu,
674
+ onChange(next) {
675
+ // Keep the next inventory read behind writes from the outgoing view.
676
+ void ordered(() => management.onChange(next))
677
+ },
678
+ })
679
+ listPane.append(header)
680
+ if (scopeFilters) listPane.append(scopeFilters.node)
681
+ listPane.append(searchBox, results)
682
+ const morePane = el('section', 'sm-ui-subpage sm-ui-more-page')
683
+ const moreHeader = el('header', 'sm-ui-more-head')
684
+ moreHeader.setAttribute('data-window-drag', '')
685
+ const moreBack = remember(button('', 'sm-ui-group-back', () => navigate('list'), 'arrow-left'), 'more-back')
686
+ labelButton(moreBack, '返回技能列表')
687
+ moreHeader.append(moreBack)
688
+ const moreHeading = addHeading(moreHeader, '内置技能')
689
+ const moreRows = el('div', 'sm-ui-rows')
690
+ moreRows.setAttribute('role', 'list')
691
+ moreRows.setAttribute('aria-label', '全部内置技能')
692
+ const moreEmpty = el('p', 'sm-ui-subtitle', '此视图没有内置技能。')
693
+ morePane.append(moreHeader, moreRows, moreEmpty)
694
+ morePane.hidden = true
695
+ page.append(morePane)
696
+
697
+ function applySwitch(control, item, name = item.name) {
698
+ const busy = pendingToggles.has(item.id)
699
+ control.setAttribute('role', 'switch')
700
+ control.setAttribute('aria-checked', String(!!item.enabled))
701
+ control.setAttribute('aria-label', `设置 ${name} 的 Agent 自动调用`)
702
+ control.disabled = !canToggle(item)
703
+ // Keep keyboard focus on an in-flight switch while suppressing repeated writes.
704
+ control.setAttribute('aria-disabled', String(control.disabled || busy))
705
+ control.setAttribute('aria-busy', String(busy))
706
+ control.title = control.disabled ? item.toggleReason || '调用方式由来源管理' : `${item.name} · ${skillState(item, snapshot.mode).detail}`
707
+ }
708
+
709
+ function originLabel(item) {
710
+ if (item.package?.label) return item.package.label
711
+ if (item.category === 'builtin' && item.source === 'custom') return 'DSH 预设'
712
+ return directoriesById.get(item.directoryId)?.label || (item.source === 'bundled' && item.provider) || sourceName(item.source || item.provider)
713
+ }
714
+
715
+ function removalOrigin(item) {
716
+ if (categoryOf(item) === 'builtin') return '由 DSH 随应用提供,调用设置由 Agent 预设或提供方管理。'
717
+ if (item.source === 'preset') return '请在 Agent 预设中管理此来源。'
718
+ if (item.source === 'bundled') return '请在提供方的插件设置中管理。'
719
+ if (categoryOf(item) === 'provided' || categoryOf(item) === 'experimental') return '请在提供方的插件设置或 Agent 预设中管理。'
720
+ return '请在来源目录中管理文件。'
721
+ }
722
+
723
+ function skillRow(item) {
724
+ let view = rows.get(item.id)
725
+ if (!view) {
726
+ const row = designFragment('row')
727
+ const open = remember(part(row, 'open'), `open-${item.id}`)
728
+ const more = remember(part(row, 'more'), `more-${item.id}`)
729
+ const control = remember(part(row, 'switch'), `switch-${item.id}`)
730
+ const fixed = el('span', 'sm-ui-state-label sm-ui-fixed-state')
731
+ row.classList.add('sm-ui-skill-row')
732
+ fixed.id = `${prefix}-state-${item.id}`
733
+ open.setAttribute('aria-describedby', fixed.id)
734
+ row.insertBefore(fixed, control)
735
+ const moreIcon = more.querySelector('[data-pen-icon]')
736
+ moreIcon.replaceChildren(icon(moreIcon.dataset.penIcon, 16))
737
+ row.setAttribute('role', 'listitem')
738
+ open.addEventListener('click', () => showDetail(item.id, open.dataset.smFocus))
739
+ control.addEventListener('click', () => {
740
+ const current = itemsById.get(item.id)
741
+ if (current) void toggle(item.id, !current.enabled)
742
+ })
743
+ menuTrigger(more, `更多操作 · ${item.name}`, first => {
744
+ const current = itemsById.get(item.id)
745
+ if (!current) return
746
+ const entries = [designMenus.row.find(entry => entry.action === 'detail')]
747
+ if (current.path && api.skillFile) entries.push({ action: 'entry', label: '在 DSH 中查看文件', icon: 'file-text' })
748
+ if (current.canRemove && api.prepareRemoval) entries.push({ action: 'remove', label: '删除技能…', separatorBefore: true })
749
+ openMenu(more, 'row', entries, action => {
750
+ if (action === 'remove') startRemoval('skill', current.id, more.dataset.smFocus)
751
+ else showDetail(item.id, more.dataset.smFocus, action)
752
+ }, first)
753
+ })
754
+ view = { row, open, more, control, fixed, title: part(row, 'title'), description: part(row, 'description'), glyph: part(row, 'glyph'), tile: part(row, 'tile') }
755
+ rows.set(item.id, view)
756
+ }
757
+ const origin = duplicateNames.has(item.name) ? originLabel(item) : ''
758
+ const qualifier = origin && (item.effective ? `${origin} · 优先` : origin)
759
+ const accessibleName = qualifier ? `${item.name} · ${qualifier}${item.path ? ` · ${item.path}` : ''}` : item.name
760
+ if (view.name !== item.name) {
761
+ const appearance = skillAppearance(item.name)
762
+ view.name = item.name
763
+ view.tile.style.color = appearance.color
764
+ view.glyph.replaceChildren(penIcon(appearance.icon, 25))
765
+ }
766
+ if (view.accessibleName !== accessibleName) {
767
+ view.accessibleName = accessibleName
768
+ view.title.textContent = item.name
769
+ if (qualifier) view.title.append(el('span', 'sm-ui-row-source', qualifier))
770
+ view.open.setAttribute('aria-label', `查看 ${accessibleName} 的详情`)
771
+ labelButton(view.more, `更多操作 · ${accessibleName}`)
772
+ }
773
+ const description = item.description || ''
774
+ if (view.description.textContent !== description) view.description.textContent = description
775
+ view.open.title = qualifier ? [accessibleName, description].filter(Boolean).join('\n') : description || item.name
776
+ // An overridden file still has an editable preference in its own detail view.
777
+ const toggleable = canToggle(item) && item.effective !== false
778
+ const state = skillState(item, snapshot.mode)
779
+ view.control.hidden = !toggleable
780
+ view.fixed.textContent = state.labels.join(' · ')
781
+ view.fixed.title = state.detail
782
+ if (toggleable) applySwitch(view.control, item, accessibleName)
783
+ return view.row
784
+ }
785
+
786
+ function packageRow(card) {
787
+ let view = packageRows.get(card.id)
788
+ if (!view) {
789
+ const row = designFragment('row')
790
+ row.classList.add('sm-ui-package-card')
791
+ row.setAttribute('role', 'listitem')
792
+ part(row, 'switch').remove()
793
+ part(row, 'more').remove()
794
+ const open = remember(part(row, 'open'), `package-${card.id}`)
795
+ const title = part(row, 'title')
796
+ const titleText = el('span')
797
+ title.replaceChildren(titleText, el('span', 'sm-ui-package-kind', '技能包'))
798
+ part(row, 'glyph').replaceChildren(icon('layers', 28))
799
+ const number = el('span', 'sm-ui-state-label')
800
+ const trail = el('span', 'sm-ui-package-trail')
801
+ trail.append(number, icon('chevron-right', 14))
802
+ trail.setAttribute('aria-hidden', 'true')
803
+ open.append(trail)
804
+ view = { row, open, titleText, number, description: part(row, 'description'), card }
805
+ open.addEventListener('click', () => {
806
+ openPackageId = view.card.id
807
+ packageQuery = view.card.initialQuery
808
+ packageFilter = view.card.initialFilter
809
+ packageReset = true
810
+ navigate('package', open.dataset.smFocus)
811
+ })
812
+ packageRows.set(card.id, view)
813
+ }
814
+ view.card = card
815
+ view.titleText.textContent = card.name
816
+ view.description.textContent = card.pkg.description || card.pkg.name
817
+ const total = `${card.total} 个技能`
818
+ view.number.textContent = card.matched < card.total ? `${card.matched} / ${total}` : total
819
+ const countLabel = card.matched < card.total ? `匹配 ${card.matched} 个,共 ${total}` : total
820
+ const state = skillState(card, snapshot.mode)
821
+ view.open.setAttribute('aria-label', `打开技能包 ${card.name},${countLabel},${state.label}`)
822
+ view.open.title = `${card.name} · ${state.label}。${state.detail}`
823
+ return view.row
824
+ }
825
+
826
+ function updateRows(items) {
827
+ const focused = list.contains(doc.activeElement) ? doc.activeElement : null
828
+ const buckets = Map.groupBy(items, categoryOf)
829
+ for (const [category, { section, quantity, entries, more }] of groups) {
830
+ const groupItems = buckets.get(category) || []
831
+ const shown = more ? builtinPreview(groupItems, !!query.trim()) : groupItems
832
+ section.hidden = !groupItems.length
833
+ quantity.textContent = String(groupItems.length)
834
+ quantity.setAttribute('aria-label', `${groupItems.length} 项`)
835
+ if (more) more.hidden = shown.length === groupItems.length
836
+ updateEntries(entries, shown)
837
+ }
838
+ if (focused && route === 'list' && !focused.getClientRects().length) tabButtons.get(filter).focus({ preventScroll: true })
839
+ else if (focused?.isConnected && doc.activeElement === doc.body) focused.focus({ preventScroll: true })
840
+ if (activeMenu) positionMenu()
841
+ }
842
+
843
+ function updateEntries(entries, items) {
844
+ let next = entries.firstElementChild
845
+ for (const item of items) {
846
+ const row = item.kind === 'package' ? packageRow(item) : skillRow(item)
847
+ if (row !== next) entries.insertBefore(row, next)
848
+ next = row.nextElementSibling
849
+ }
850
+ while (next) {
851
+ const following = next.nextElementSibling
852
+ next.remove()
853
+ next = following
854
+ }
855
+ }
856
+
857
+ function renderMore() {
858
+ const builtin = snapshot.items.filter(item => categoryOf(item) === 'builtin')
859
+ const { cards } = inventoryResults(builtin, packagesById, { sort })
860
+ updateEntries(moreRows, cards)
861
+ moreEmpty.hidden = cards.length > 0
862
+ morePane.setAttribute('aria-busy', String(reading || scanning))
863
+ if (activeMenu) positionMenu()
864
+ }
865
+
866
+ function renderEmpty(keyword) {
867
+ let heading, hint, action
868
+ if (keyword) {
869
+ heading = `没有找到与“${query.trim()}”匹配的技能`
870
+ hint = filter === 'all' ? text('skv-226', '试试其他关键词,或清除搜索查看全部技能。') : '试试其他关键词,或清除搜索查看当前筛选下的技能。'
871
+ action = button('清除搜索', 'sm-ui-button', clearSearch)
872
+ } else if (filter !== 'all' && snapshot.items.length) {
873
+ heading = `没有${tabButtons.get(filter).textContent}的技能`
874
+ hint = '切换筛选条件查看其他技能。'
875
+ action = button('查看全部', 'sm-ui-button', () => setFilter('all', true))
876
+ } else {
877
+ heading = text('skv-248', '还没有本地技能')
878
+ hint = text('skv-249', '导入已有技能,或让 Agent 帮你创建第一个技能。')
879
+ action = button(text('sm-r5-2', '添加技能'), 'sm-ui-button sm-ui-primary')
880
+ menuTrigger(action, '添加技能', first => openMenu(action, 'add', designMenus.add, startFlow, first))
881
+ }
882
+ remember(action, 'empty-action')
883
+ const art = designFragment(keyword ? 'emptySearch' : 'emptyLibrary')
884
+ empty.replaceChildren(art, el('h3', '', heading), el('p', '', hint), action)
885
+ }
886
+
887
+ function renderStatus(host) {
888
+ const expanded = !!host.querySelector('details[open]')
889
+ host.replaceChildren()
890
+ if (readError) {
891
+ const line = el('div', 'sm-ui-warning')
892
+ line.setAttribute('role', 'alert')
893
+ const retry = remember(button('重试', 'sm-ui-text-action', () => load(true)), 'retry-list')
894
+ line.append(el('span', '', `读取技能列表失败。${readError}`), retry)
895
+ host.append(line)
896
+ } else if (snapshot.complete === false || snapshot.warnings?.length) {
897
+ const warning = el('details', 'sm-ui-warning sm-ui-warnings')
898
+ warning.open = expanded
899
+ warning.append(remember(el('summary', '', '部分目录或技能未能完整读取'), 'warnings'))
900
+ const messages = snapshot.warnings?.length ? snapshot.warnings : ['可刷新技能列表后重试。']
901
+ for (const message of messages) warning.append(el('p', '', message))
902
+ host.append(warning)
903
+ }
904
+ host.hidden = !host.childElementCount
905
+ }
906
+
907
+ function renderList() {
908
+ const keyword = query.trim()
909
+ if (management) {
910
+ Object.assign(management.preferences, { query, filter, sort })
911
+ scopeFilters.setModes(management.preferences.modes ?? emptyModes)
912
+ }
913
+ listPane.setAttribute('aria-busy', String(!hasLoaded && reading))
914
+ for (const [value, tab] of tabButtons) {
915
+ tab.setAttribute('aria-selected', String(filter === value))
916
+ tab.tabIndex = value === filter ? 0 : -1
917
+ }
918
+ const { cards: items, skillCount, packageCount } = inventoryResults(snapshot.items, packagesById, { query, filter, sort })
919
+ const sortName = designMenus.sort.find(entry => entry.action === sort)?.label || '最近更新'
920
+ sortLabel.textContent = sortName
921
+ labelButton(sortButton, `排序方式 · ${sortName}`)
922
+ sortButton.hidden = items.length === 0
923
+ results.setAttribute('aria-labelledby', tabButtons.get(filter).id)
924
+ list.setAttribute('aria-busy', String(scanning || reading))
925
+ listTitle.textContent = keyword ? text('skv-199', '搜索结果') : '技能列表'
926
+ listTitle.classList.toggle('sm-ui-sr-only', !keyword)
927
+ count.textContent = hasLoaded ? (packageCount ? `${items.length} 项 · ${skillCount} 个技能` : `共 ${skillCount} 个技能`) : '—'
928
+ count.setAttribute('aria-label', hasLoaded ? count.textContent : '尚未读取技能数量')
929
+ clearButton.hidden = !query
930
+ const scanLabel = scanning || (!hasLoaded && reading) ? text('sm-r5-63', '正在扫描技能目录…') : ''
931
+ if (progress.textContent !== scanLabel) progress.textContent = scanLabel
932
+ if ((refreshButton.dataset.scanning === 'true') !== scanning) {
933
+ refreshButton.dataset.scanning = String(scanning)
934
+ refreshLabel.textContent = scanning ? text('sm-r5-60', '刷新中') : idleRefreshLabel
935
+ labelButton(refreshButton, refreshLabel.textContent)
936
+ }
937
+ refreshButton.setAttribute('aria-disabled', String(scanning))
938
+ refreshButton.setAttribute('aria-busy', String(scanning))
939
+ renderStatus(listStatus)
940
+ updateRows(items)
941
+ empty.hidden = items.length > 0 || !hasLoaded || !!readError || (snapshot.complete === false && !snapshot.items.length)
942
+ if (empty.hidden) empty.removeAttribute('data-state')
943
+ else {
944
+ const emptyState = JSON.stringify([query, filter, snapshot.items.length])
945
+ if (empty.dataset.state !== emptyState) {
946
+ empty.dataset.state = emptyState
947
+ renderEmpty(keyword)
948
+ }
949
+ }
950
+ }
951
+
952
+ function navigate(next, key) {
953
+ closeMenu()
954
+ const from = route
955
+ if (route === 'list' && next !== 'list') { listScroll = scroller.scrollTop; returnKey = key }
956
+ if (from === 'builtin' && next !== 'list') { moreScroll = scroller.scrollTop; moreFocus = key }
957
+ if (from === 'package' && next !== 'package') packageView.hide()
958
+ if (from === 'detail' && next !== 'detail') { detailFiles.hide(); clearSkillDocument() }
959
+ if (next === 'builtin') inMore = true
960
+ else if (next === 'list' || from === 'list') inMore = false
961
+ if (next === 'list' || next === 'builtin' || (from === 'list' && next !== 'package')) openPackageId = null
962
+ packageFocus = next === 'package'
963
+ route = next
964
+ page.dataset.view = next
965
+ listPane.hidden = next !== 'list'
966
+ subPane.hidden = next !== 'detail' && next !== 'directories'
967
+ packagePane.hidden = next !== 'package'
968
+ morePane.hidden = next !== 'builtin'
969
+ renderCurrent()
970
+ if (next === 'package') return
971
+ if (next === 'list') {
972
+ scroller.scrollTop = listScroll
973
+ focusKey(returnKey, search)
974
+ } else if (next === 'builtin') {
975
+ scroller.scrollTop = from === 'list' ? 0 : moreScroll
976
+ if (from === 'list') moreHeading.focus({ preventScroll: true })
977
+ else focusKey(moreFocus, moreHeading)
978
+ } else {
979
+ scroller.scrollTop = 0
980
+ subPane.querySelector('h1')?.focus({ preventScroll: true })
981
+ }
982
+ }
983
+
984
+ function backButton() {
985
+ const parent = route === 'detail' && packagesById.get(openPackageId)
986
+ if (parent) return remember(button(`返回 ${parent.pkg.label || parent.pkg.name}`, 'sm-ui-back', () => navigate('package'), 'arrow-left'), 'back')
987
+ if (inMore) return remember(button('返回内置技能', 'sm-ui-back', () => navigate('builtin'), 'arrow-left'), 'back')
988
+ return remember(button(text('skv-301', '返回技能列表'), 'sm-ui-back', () => navigate('list'), 'arrow-left'), 'back')
989
+ }
990
+
991
+ function addHeading(parent, title) {
992
+ const heading = remember(el('h1', 'sm-ui-heading', title), 'page-heading')
993
+ heading.tabIndex = -1
994
+ parent.append(heading)
995
+ return heading
996
+ }
997
+
998
+ async function showDetail(id, key, intent = 'detail') {
999
+ const version = ++detailVersion
1000
+ detailFiles.hide()
1001
+ clearSkillDocument()
1002
+ detailId = id
1003
+ detail = null
1004
+ detailError = ''
1005
+ detailTab = intent === 'entry' ? 'files' : 'overview'
1006
+ fileSelection = intent === 'entry' ? { entry: true, focus: true } : null
1007
+ resourceReset = true
1008
+ openChoices = null
1009
+ overviewScroll = 0
1010
+ instructionScroll = 0
1011
+ navigate('detail', key)
1012
+ try {
1013
+ const value = await api.detail(id)
1014
+ if (disposed || route !== 'detail' || detailVersion !== version) return
1015
+ if (!value) throw new Error('未找到此技能。')
1016
+ detail = value
1017
+ if (value.files) openChoices = prepareOpenChoices(value)
1018
+ } catch (error) {
1019
+ if (disposed || route !== 'detail' || detailVersion !== version) return
1020
+ detailError = errorText(error)
1021
+ }
1022
+ renderCurrent()
1023
+ }
1024
+
1025
+ function locationRow(label, value) {
1026
+ const row = el('div', 'sm-ui-location-row')
1027
+ row.append(el('dt', '', label), el('dd', '', value))
1028
+ return row
1029
+ }
1030
+
1031
+ const contentTabs = el('div', 'sm-ui-tabs')
1032
+ contentTabs.setAttribute('role', 'tablist')
1033
+ contentTabs.setAttribute('aria-label', '技能内容')
1034
+ detailTabs.append(contentTabs)
1035
+ const detailTabButtons = new Map()
1036
+ for (const [key, label, panel] of [['overview', '概览', overviewPane], ['files', '文件', detailFilesPane]]) {
1037
+ const tab = remember(button(label, 'sm-ui-tab', () => chooseDetailTab(key)), `detail-tab-${key}`)
1038
+ tab.id = `${prefix}-detail-${key}`
1039
+ tab.setAttribute('role', 'tab')
1040
+ panel.id = `${tab.id}-panel`
1041
+ tab.setAttribute('aria-controls', panel.id)
1042
+ panel.setAttribute('role', 'tabpanel')
1043
+ panel.setAttribute('aria-labelledby', tab.id)
1044
+ contentTabs.append(tab)
1045
+ detailTabButtons.set(key, tab)
1046
+ }
1047
+ contentTabs.addEventListener('keydown', event => {
1048
+ let key
1049
+ if (event.key === 'Home') key = 'overview'
1050
+ else if (event.key === 'End') key = 'files'
1051
+ else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') key = detailTab === 'overview' ? 'files' : 'overview'
1052
+ else return
1053
+ event.preventDefault()
1054
+ event.stopPropagation()
1055
+ chooseDetailTab(key)
1056
+ detailTabButtons.get(key).focus({ preventScroll: true })
1057
+ })
1058
+
1059
+ function chooseDetailTab(key, selection = null) {
1060
+ if (!detail || route !== 'detail' || (key === 'files' && !detail.files)) return
1061
+ if (key === detailTab && !selection) return
1062
+ if (key !== detailTab) {
1063
+ if (detailTab === 'overview') { overviewScroll = scroller.scrollTop; clearSkillDocument() }
1064
+ else detailFiles.hide()
1065
+ }
1066
+ fileSelection = selection
1067
+ detailTab = key
1068
+ paintDetailContent()
1069
+ if (key === 'overview') scroller.scrollTop = overviewScroll
1070
+ }
1071
+
1072
+ function paintDetailContent() {
1073
+ const files = detail.files
1074
+ const hasFiles = !!files && typeof api.skillFile === 'function'
1075
+ if (!hasFiles) detailTab = 'overview'
1076
+ detailTabs.hidden = !hasFiles
1077
+ for (const [key, tab] of detailTabButtons) {
1078
+ const selected = key === detailTab
1079
+ tab.setAttribute('aria-selected', String(selected))
1080
+ tab.tabIndex = selected ? 0 : -1
1081
+ }
1082
+ overviewPane.hidden = detailTab !== 'overview'
1083
+ detailFilesPane.hidden = detailTab !== 'files'
1084
+ if (detailTab === 'overview') {
1085
+ showInstructions(detail)
1086
+ return
1087
+ }
1088
+ const selection = fileSelection
1089
+ fileSelection = null
1090
+ detailFiles.show({ id: detailId, root: files.root, browse: files.canBrowse,
1091
+ file: selection?.path || (selection?.entry || !files.canBrowse ? files.entryPath : undefined),
1092
+ reset: resourceReset || selection?.root, focus: selection?.focus })
1093
+ resourceReset = false
1094
+ if (selection?.focus) scrollToFocusedFile()
1095
+ }
1096
+
1097
+ function scrollToFocusedFile() {
1098
+ const crumb = detailFilesPane.querySelector('[aria-current="page"]')
1099
+ if (crumb && doc.activeElement === crumb) crumb.scrollIntoView({ block: 'nearest' })
1100
+ }
1101
+
1102
+ const openControl = el('div', 'sm-ui-open-split')
1103
+ openControl.setAttribute('role', 'group')
1104
+ openControl.setAttribute('aria-label', '打开技能文件')
1105
+ const viewEntry = remember(button('在 DSH 中查看', 'sm-ui-button', () => chooseDetailTab('files', { entry: true, focus: true }), 'file-text', 14), 'open-file')
1106
+ const openWith = remember(button('', 'sm-ui-button', undefined, 'chevron-down', 12), 'open-with')
1107
+ menuTrigger(openWith, '选择打开方式', showOpenMenu)
1108
+ openControl.append(viewEntry, openWith)
1109
+
1110
+ function prepareOpenChoices(item) {
1111
+ const entries = [{ action: 'preview', label: 'DSH 内置预览', icon: 'file-text' }]
1112
+ if (item.files.canBrowse) entries.push({ action: 'browse', label: '浏览技能目录', icon: 'folder-open' })
1113
+ const choices = { entries, loading: null, failed: false }
1114
+ if (item.files.archived || !api.openOptions || !api.openItem) return choices
1115
+ choices.loading = Promise.resolve().then(() => api.openOptions(item.id)).then(result => {
1116
+ result.applications.forEach((app, index) => entries.push({ action: `app:${app.id}`, icon: 'arrow-up-right',
1117
+ label: `${app.name}${app.isDefault ? '(系统默认)' : ''}`, separatorBefore: index === 0 }))
1118
+ if (result.canReveal) entries.push({ action: 'reveal', label: '显示文件位置', icon: 'folder-open', separatorBefore: true })
1119
+ }).catch(error => {
1120
+ choices.failed = true
1121
+ entries.push({ action: 'unavailable', label: '无法读取本机应用', description: errorText(error), disabled: true, separatorBefore: true })
1122
+ }).finally(() => { choices.loading = null })
1123
+ return choices
1124
+ }
1125
+
1126
+ async function showOpenMenu(first) {
1127
+ if (!detail?.files || route !== 'detail') return
1128
+ if (pendingOpen || activeMenu?.anchor === openWith) { closeMenu(true); return }
1129
+ const item = detail
1130
+ const choices = openChoices ??= prepareOpenChoices(item)
1131
+ if (choices.loading) {
1132
+ closeMenu()
1133
+ const events = new AbortController()
1134
+ pendingOpen = events
1135
+ openWith.setAttribute('aria-busy', 'true')
1136
+ openWith.title = '正在读取本机打开方式…'
1137
+ const outside = event => { if (!openWith.contains(event.target)) closeMenu() }
1138
+ doc.addEventListener('pointerdown', outside, { capture: true, signal: events.signal })
1139
+ doc.addEventListener('focusin', outside, { signal: events.signal })
1140
+ doc.addEventListener('keydown', event => {
1141
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true) }
1142
+ else if (event.key === 'Tab') closeMenu()
1143
+ }, { capture: true, signal: events.signal })
1144
+ await choices.loading
1145
+ if (events.signal.aborted) return
1146
+ closeMenu()
1147
+ if (disposed || detail !== item || route !== 'detail' || !openWith.isConnected) return
1148
+ }
1149
+ if (choices.failed) openChoices = null
1150
+ openMenu(openWith, 'open', choices.entries, action => {
1151
+ if (action === 'preview') chooseDetailTab('files', { entry: true, focus: true })
1152
+ else if (action === 'browse') chooseDetailTab('files', { root: true, focus: true })
1153
+ else launchFileAction(item, action)
1154
+ }, first)
1155
+ }
1156
+
1157
+ async function launchFileAction(item, action) {
1158
+ const reveal = action === 'reveal'
1159
+ if (!reveal && !action.startsWith('app:')) return
1160
+ try { await api.openItem(item.id, reveal ? 'directory' : 'file', reveal ? undefined : action.slice(4)) }
1161
+ catch (error) {
1162
+ if (route === 'detail' && detail === item) {
1163
+ openChoices = null
1164
+ notify(errorText(error), { key: `open-${item.id}`, error: true })
1165
+ }
1166
+ }
1167
+ }
1168
+
1169
+ function clearSkillDocument() {
1170
+ if (!skillDocument) return
1171
+ if (skillDocument.region) instructionScroll = skillDocument.region.scrollTop
1172
+ skillDocument.dispose?.()
1173
+ skillDocument.section.remove()
1174
+ skillDocument = null
1175
+ }
1176
+
1177
+ function showInstructions(item) {
1178
+ if (skillDocument?.source === detail) return
1179
+ clearSkillDocument()
1180
+ const section = el('section', 'sm-ui-detail-section sm-ui-instructions')
1181
+ const title = text('skv-324', '使用说明')
1182
+ section.append(el('h2', '', title))
1183
+ overviewPane.append(section)
1184
+ const view = skillDocument = { source: detail, section }
1185
+ if (typeof detail.content === 'string' && detail.content.trim()) {
1186
+ const target = el('div', 'sm-document-scroll')
1187
+ section.append(target)
1188
+ const files = detail.files
1189
+ const topBeforeMount = scroller.scrollTop
1190
+ view.dispose = renderMarkdown(target, detail.content, {
1191
+ label: `${item.name} ${title}`, filePath: files?.entryPath,
1192
+ onOpenFile: files?.canBrowse ? path => {
1193
+ if (skillDocument === view) chooseDetailTab('files', { path, focus: true })
1194
+ } : undefined,
1195
+ onReady: region => {
1196
+ if (skillDocument !== view) return
1197
+ view.region = region
1198
+ region.scrollTop = instructionScroll
1199
+ if (overviewScroll && scroller.scrollTop === topBeforeMount) scroller.scrollTop = overviewScroll
1200
+ },
1201
+ })
1202
+ } else section.append(el('p', 'sm-ui-subtitle', '该来源未提供说明正文。'))
1203
+ }
1204
+
1205
+ function renderDetail() {
1206
+ if (detailSummary.parentNode !== subPane) subPane.replaceChildren(detailSummary, detailTabs, overviewPane, detailFilesPane)
1207
+ const current = itemsById.get(detailId)
1208
+ if (!detail || detailError || (!current && hasLoaded)) {
1209
+ detailFiles.hide()
1210
+ clearSkillDocument()
1211
+ detailTabs.hidden = overviewPane.hidden = detailFilesPane.hidden = true
1212
+ }
1213
+ if (!current && hasLoaded) {
1214
+ detailSummary.replaceChildren(backButton())
1215
+ addHeading(detailSummary, '技能详情')
1216
+ detailSummary.append(el('p', 'sm-ui-subtitle', '技能列表中已找不到这项技能。'))
1217
+ return
1218
+ }
1219
+ const item = { ...detail, ...current }
1220
+ const title = item.name || '技能详情'
1221
+ const top = el('div', 'sm-ui-detail-head')
1222
+ const tile = el('span', 'sm-ui-detail-tile')
1223
+ const appearance = skillAppearance(title)
1224
+ tile.style.color = appearance.color
1225
+ tile.append(penIcon(appearance.icon, 30))
1226
+ const copy = el('div', 'sm-ui-detail-copy')
1227
+ addHeading(copy, title)
1228
+ if (item.description) copy.append(el('p', 'sm-ui-subtitle', item.description))
1229
+ top.append(tile, copy)
1230
+ if (detail?.files && api.skillFile) top.append(openControl)
1231
+ detailSummary.replaceChildren(backButton(), top)
1232
+ if (detailError) {
1233
+ const error = el('div', 'sm-ui-warning')
1234
+ error.setAttribute('role', 'alert')
1235
+ error.append(el('span', '', detailError), button('重试', 'sm-ui-text-action', () => showDetail(detailId, returnKey)))
1236
+ detailSummary.append(error)
1237
+ return
1238
+ }
1239
+ if (!detail) {
1240
+ const loading = el('p', 'sm-ui-subtitle', '正在读取技能说明…')
1241
+ loading.setAttribute('role', 'status')
1242
+ detailSummary.append(loading)
1243
+ return
1244
+ }
1245
+ const status = el('section', 'sm-ui-detail-status')
1246
+ const label = el('div', 'sm-ui-status-copy')
1247
+ const toggleable = canToggle(item)
1248
+ const state = skillState(item, snapshot.mode)
1249
+ label.append(el('h2', '', '调用方式'), el('p', 'sm-ui-subtitle', state.detail))
1250
+ if (!toggleable && item.toggleReason && (state.model || state.user)) label.append(el('p', 'sm-ui-subtitle', item.toggleReason))
1251
+ const switchLabel = 'Agent 自动调用设置'
1252
+ status.append(label, el('span', 'sm-ui-state-label', toggleable ? switchLabel : state.label))
1253
+ if (toggleable) {
1254
+ const control = remember(button('', 'sm-ui-detail-switch', () => toggle(item.id, !item.enabled)), 'detail-switch')
1255
+ control.append(el('span'))
1256
+ applySwitch(control, item)
1257
+ status.append(control)
1258
+ }
1259
+ const location = el('section', 'sm-ui-detail-section')
1260
+ location.append(el('h2', '', text('skv-316', '文件位置')))
1261
+ const fields = el('dl', 'sm-ui-location')
1262
+ const source = originLabel(item)
1263
+ if (detail.files || item.path) {
1264
+ fields.append(locationRow(detail.files?.canBrowse ? '技能根目录' : '所在目录', detail.files?.root || containingPath(item)),
1265
+ locationRow('说明文件', detail.files?.entryPath || item.path.split(/[/\\]/).pop()))
1266
+ if (detail.files?.archived) fields.append(locationRow('存储方式', 'DSH 应用归档,可在“文件”中浏览。'))
1267
+ } else if (!item.resourceBase) fields.append(locationRow('说明形式', '由提供方直接提供正文'))
1268
+ const category = categoryNames.get(categoryOf(item))
1269
+ const origin = locationRow('来源', category === source ? source : `${category} · ${source}`)
1270
+ origin.classList.add('sm-ui-origin')
1271
+ fields.append(origin)
1272
+ if (item.shadowedBy) {
1273
+ const winner = itemsById.get(item.shadowedBy)
1274
+ fields.append(locationRow('同名技能', winner ? `优先使用${originLabel(winner)}中的 ${winner.name}` : '另一个来源的同名技能优先使用'))
1275
+ }
1276
+ location.append(fields)
1277
+ const canRemove = item.canRemove && api.prepareRemoval
1278
+ const removal = canRemove
1279
+ ? remember(button('删除技能…', 'sm-ui-button sm-ui-destructive', () => startRemoval('skill', item.id, 'remove-skill')), 'remove-skill')
1280
+ : el('p', 'sm-ui-subtitle', item.package ? '请从所属技能包管理此技能。'
1281
+ : [categoryOf(item) === 'user' ? item.removeReason : '', removalOrigin(item)].filter(Boolean).join(' '))
1282
+ removal.classList.add('sm-ui-removal-action')
1283
+ if (canRemove) removal.setAttribute('aria-haspopup', 'dialog')
1284
+ location.append(removal)
1285
+ overviewFacts.replaceChildren(status, location)
1286
+ paintDetailContent()
1287
+ }
1288
+
1289
+ function renderDirectories() {
1290
+ const head = el('div', 'sm-ui-dir-head')
1291
+ const copy = el('div')
1292
+ addHeading(copy, text('sm-r5-605', '技能目录'))
1293
+ copy.append(el('p', 'sm-ui-subtitle', text('sm-r5-606', '添加自定义目录后,DSH 会扫描其中的技能。')))
1294
+ const add = remember(button(text('sm-r5-608', '添加目录'), 'sm-ui-button sm-ui-primary', () => openDirectoryDialog(), 'plus'), 'add-directory')
1295
+ head.append(copy, add)
1296
+ const status = el('div')
1297
+ renderStatus(status)
1298
+ const configured = snapshot.directories.filter(dir => dir.kind === 'personal' || dir.kind === 'custom')
1299
+ const discovered = snapshot.directories.filter(dir => dir.kind !== 'personal' && dir.kind !== 'custom')
1300
+ const destinations = el('section', 'sm-ui-destinations')
1301
+ destinations.append(el('h2', '', text('sm-r5-611', '导入存放目录')))
1302
+ const table = el('table', 'sm-ui-dir-table')
1303
+ table.setAttribute('aria-label', text('sm-r5-611', '导入存放目录'))
1304
+ const tableHead = table.createTHead().insertRow()
1305
+ for (const [id, label] of [['sm-r5-599', '目录名称'], ['sm-r5-600', '路径'], ['sm-r5-601', '来源'], ['sm-r5-602', '操作']]) {
1306
+ const th = el('th', '', text(id, label))
1307
+ th.scope = 'col'
1308
+ tableHead.append(th)
1309
+ }
1310
+ const body = table.createTBody()
1311
+ for (const dir of configured) {
1312
+ const row = body.insertRow()
1313
+ const name = row.insertCell()
1314
+ const nameGroup = el('div', 'sm-ui-dir-name')
1315
+ const tile = el('span', 'sm-ui-dir-tile')
1316
+ tile.append(icon('folder', 18))
1317
+ nameGroup.append(tile, el('strong', '', dir.label))
1318
+ if (dir.kind === 'personal' && dir.writable) nameGroup.append(el('span', 'sm-ui-badge', '默认导入'))
1319
+ name.append(nameGroup)
1320
+ const path = row.insertCell()
1321
+ path.className = 'sm-ui-dir-path'
1322
+ path.textContent = dir.displayPath || dir.path
1323
+ path.title = dir.path
1324
+ const source = row.insertCell()
1325
+ source.className = 'sm-ui-dir-source'
1326
+ source.textContent = dir.kind === 'personal' ? 'DSH' : '自定义'
1327
+ if (!dir.writable) source.append(el('span', 'sm-ui-readonly-note', '只读'))
1328
+ const actions = row.insertCell()
1329
+ if (dir.kind === 'custom' && dir.removable !== false) {
1330
+ const remove = remember(button('移除', 'sm-ui-dir-remove', () => openDirectoryDialog(dir)), `remove-${dir.id}`)
1331
+ remove.setAttribute('aria-label', `移除目录 ${dir.label}`)
1332
+ actions.append(remove)
1333
+ }
1334
+ }
1335
+ destinations.append(table)
1336
+ if (!configured.length && !readError && snapshot.complete !== false) {
1337
+ destinations.append(el('p', 'sm-ui-subtitle', hasLoaded ? '当前没有已配置的存放目录。' : '正在读取目录…'))
1338
+ }
1339
+
1340
+ const auto = el('section', 'sm-ui-auto-dirs')
1341
+ const autoHead = el('div', 'sm-ui-auto-head')
1342
+ autoHead.append(el('h2', '', text('sm-r5-639', '自动发现的目录')))
1343
+ if (discovered.length && discovered.every(dir => !dir.writable)) {
1344
+ const badge = el('span', 'sm-ui-readonly')
1345
+ badge.append(icon('lock-keyhole', 14), el('span', '', text('sm-r5-642', '只读')))
1346
+ autoHead.append(badge)
1347
+ }
1348
+ auto.append(autoHead, el('p', 'sm-ui-subtitle', text('sm-r5-640', '项目路径相对于当前项目的根目录。')))
1349
+ const tiles = el('dl', 'sm-ui-discovered-grid')
1350
+ for (const dir of discovered) {
1351
+ const tile = el('div', 'sm-ui-discovered')
1352
+ tile.append(el('dt', '', dir.label || sourceName(dir.kind)), el('dd', '', dir.displayPath || dir.path))
1353
+ tile.title = dir.path
1354
+ tiles.append(tile)
1355
+ }
1356
+ if (discovered.length) auto.append(tiles)
1357
+ else if (!readError && snapshot.complete !== false) {
1358
+ auto.append(el('p', 'sm-ui-no-dirs', hasLoaded ? '当前没有自动发现的目录。' : '正在读取目录…'))
1359
+ }
1360
+ subPane.replaceChildren(backButton(), head, status, destinations, auto)
1361
+ }
1362
+
1363
+ function openDirectoryDialog(dir = null) {
1364
+ if (directoryDialog || disposed) return
1365
+ const triggerKey = dir ? `remove-${dir.id}` : 'add-directory'
1366
+ const dialog = el('dialog', `sm-ui-dialog${dir ? ' sm-ui-remove-dialog' : ''}`)
1367
+ const titleId = `${prefix}-dialog-title`
1368
+ dialog.setAttribute('aria-modal', 'true')
1369
+ dialog.setAttribute('aria-labelledby', titleId)
1370
+ const form = el('form', 'sm-ui-dialog-form')
1371
+ const head = el('header', 'sm-ui-dialog-head')
1372
+ const title = el('h2', '', dir ? text('sm-r5-694', '移除目录?') : text('sm-r5-674', '添加目录'))
1373
+ title.id = titleId
1374
+ let saving = false
1375
+ let picking = false
1376
+ const live = () => !disposed && directoryDialog?.node === dialog
1377
+ function close(restore = true) {
1378
+ if (dialog.open) dialog.close()
1379
+ dialog.remove()
1380
+ if (directoryDialog?.node === dialog) directoryDialog = null
1381
+ if (restore && !disposed) focusKey(triggerKey, subPane.querySelector('[data-sm-focus="add-directory"]'))
1382
+ }
1383
+ const dismiss = () => { if (!saving) close() }
1384
+ const x = labelButton(button('', 'sm-ui-dialog-close', dismiss, 'x'), '关闭')
1385
+ head.append(title, x)
1386
+ const content = el('div', 'sm-ui-dialog-content')
1387
+ const path = el('input', 'sm-ui-input sm-ui-path-input')
1388
+ const name = el('input', 'sm-ui-input')
1389
+ const error = el('p', 'sm-ui-form-error')
1390
+ error.setAttribute('role', 'alert')
1391
+ error.hidden = true
1392
+ const showError = message => { error.hidden = !message; error.textContent = message }
1393
+ const browse = button(text('sm-r5-664', '选择文件夹'), 'sm-ui-button sm-ui-browse', async () => {
1394
+ if (saving || picking) return
1395
+ picking = true
1396
+ updateControls()
1397
+ try {
1398
+ const selected = await api.pick('directory')
1399
+ if (!live()) return
1400
+ const value = typeof selected === 'string' ? selected : selected?.path
1401
+ if (value) { path.value = value; showError(''); path.focus() }
1402
+ } catch (reason) { if (live()) showError(errorText(reason)) }
1403
+ finally { picking = false; if (live()) updateControls() }
1404
+ }, 'folder-open')
1405
+ const labelFor = (field, suffix, caption) => {
1406
+ field.id = `${prefix}-dir-${suffix}`
1407
+ const label = el('label', 'sm-ui-field-label', caption)
1408
+ label.htmlFor = field.id
1409
+ return label
1410
+ }
1411
+ if (dir) {
1412
+ const card = el('div', 'sm-ui-remove-target')
1413
+ const lines = el('div')
1414
+ lines.append(el('strong', '', dir.label), el('span', '', dir.displayPath || dir.path))
1415
+ card.append(icon('folder', 20), lines)
1416
+ content.append(card, el('p', 'sm-ui-remove-copy', text('sm-r5-688', 'DSH 将停止扫描此目录。已有技能文件会保留在原处。')))
1417
+ } else {
1418
+ head.append(el('p', 'sm-ui-subtitle', text('sm-r5-675', '选择文件夹,或直接输入目录路径。')))
1419
+ path.type = name.type = 'text'
1420
+ path.required = true
1421
+ path.autocomplete = name.autocomplete = 'off'
1422
+ path.spellcheck = false
1423
+ const pathLine = el('div', 'sm-ui-path-line')
1424
+ pathLine.append(path, browse)
1425
+ content.append(labelFor(path, 'path', text('sm-r5-660', '目录路径')), pathLine, labelFor(name, 'name', text('sm-r5-666', '名称(可选)')), name)
1426
+ path.addEventListener('input', () => { showError(''); updateControls() })
1427
+ }
1428
+ content.append(error)
1429
+ const footer = el('footer', 'sm-ui-dialog-footer')
1430
+ const cancel = button(text('sm-r5-670', '取消'), 'sm-ui-button', dismiss)
1431
+ const submitLabel = dir ? text('sm-r5-692', '移除目录') : text('sm-r5-672', '添加目录')
1432
+ const submit = button(submitLabel, 'sm-ui-button sm-ui-primary')
1433
+ submit.type = 'submit'
1434
+ function updateControls() {
1435
+ x.disabled = cancel.disabled = path.disabled = name.disabled = saving
1436
+ browse.disabled = saving || picking || !api.pick
1437
+ submit.disabled = saving || picking || (!dir && !path.value.trim())
1438
+ submit.textContent = saving ? (dir ? '正在移除…' : '正在添加…') : submitLabel
1439
+ form.setAttribute('aria-busy', String(saving || picking))
1440
+ }
1441
+ form.addEventListener('submit', async event => {
1442
+ event.preventDefault()
1443
+ if (submit.disabled || !live()) return
1444
+ saving = true
1445
+ updateControls()
1446
+ showError('')
1447
+ const enteredPath = path.value.trim()
1448
+ const enteredName = name.value.trim()
1449
+ try {
1450
+ await ordered(async () => {
1451
+ const result = dir ? await api.removeDirectory(dir.id) : await api.addDirectory(enteredPath, enteredName || undefined)
1452
+ // A committed directory edit must not be submitted again if reloading fails.
1453
+ try { await reconcile(result) } catch (reason) { reportReadError(reason) }
1454
+ if (!live()) return
1455
+ close()
1456
+ const label = dir?.label || enteredName || result?.directories?.find(entry => entry.path === enteredPath)?.label || enteredPath
1457
+ notify(dir ? `已移除${label}` : `已添加${label},可在导入时选择`, { key: 'directories' })
1458
+ })
1459
+ } catch (reason) {
1460
+ if (!live()) return
1461
+ saving = false
1462
+ updateControls()
1463
+ showError(errorText(reason))
1464
+ const retryFocus = dir ? cancel : path
1465
+ retryFocus.focus()
1466
+ }
1467
+ })
1468
+ dialog.addEventListener('cancel', event => { event.preventDefault(); dismiss() })
1469
+ dialog.addEventListener('click', event => {
1470
+ if (event.target !== dialog) return
1471
+ const rect = dialog.getBoundingClientRect()
1472
+ if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dismiss()
1473
+ })
1474
+ footer.append(cancel, submit)
1475
+ form.append(head, content, footer)
1476
+ dialog.append(form)
1477
+ root.append(dialog)
1478
+ directoryDialog = { node: dialog, close }
1479
+ updateControls()
1480
+ dialog.showModal()
1481
+ const initialFocus = dir ? cancel : path
1482
+ initialFocus.focus()
1483
+ }
1484
+
1485
+ function renderCurrent() {
1486
+ if (disposed) return
1487
+ const previous = page.contains(doc.activeElement) ? doc.activeElement : null
1488
+ const key = previous?.dataset.smFocus
1489
+ if (route === 'list') renderList()
1490
+ else if (route === 'builtin') renderMore()
1491
+ else if (route === 'detail') renderDetail()
1492
+ else if (route === 'package') {
1493
+ const bundle = packagesById.get(openPackageId)
1494
+ if (bundle) {
1495
+ packageView.show(bundle.pkg, bundle.members, packageQuery, { reset: packageReset, filter: packageFilter, mode: snapshot.mode, focus: packageFocus,
1496
+ backLabel: inMore ? '返回内置技能' : '返回技能列表', removalOrigin: removalOrigin(bundle.members[0]) })
1497
+ packageReset = false
1498
+ packageFocus = false
1499
+ } else {
1500
+ packageView.hide()
1501
+ packagePane.replaceChildren(backButton(), el('p', 'sm-ui-subtitle', '此技能包已移除。'))
1502
+ }
1503
+ }
1504
+ else renderDirectories()
1505
+ if (key && !previous.isConnected && doc.activeElement === doc.body) {
1506
+ focusKey(key, navigationFocus())
1507
+ }
1508
+ }
1509
+
1510
+ root.addEventListener('keydown', event => {
1511
+ if (route !== 'list' || event.isComposing || activeMenu || root.querySelector('dialog[open]')) return
1512
+ const target = event.target
1513
+ if (event.key === 'Escape' && target === search && query) {
1514
+ event.preventDefault()
1515
+ event.stopPropagation()
1516
+ clearSearch()
1517
+ } else if (((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'f') ||
1518
+ (event.key === '/' && !event.ctrlKey && !event.metaKey && !event.altKey && !target.closest('input, textarea, select, [contenteditable="true"]'))) {
1519
+ event.preventDefault()
1520
+ search.focus()
1521
+ search.select()
1522
+ }
1523
+ }, { signal: scope.signal })
1524
+ page.dataset.view = 'list'
1525
+ attachHeaderScroll(scroller, header, scope.signal)
1526
+ void load()
1527
+ if (management?.focus) focusKey(management.focus, search)
1528
+
1529
+ return function dispose() {
1530
+ if (disposed) return
1531
+ disposed = true
1532
+ scope.abort()
1533
+ closeMenu()
1534
+ clearSkillDocument()
1535
+ detailFiles.dispose()
1536
+ flow?.cleanup()
1537
+ removalDialog?.cleanup()
1538
+ packageView.dispose()
1539
+ directoryDialog?.close(false)
1540
+ for (const key of notices.keys()) dismissNotice(key)
1541
+ rows.clear()
1542
+ packageRows.clear()
1543
+ root.remove()
1544
+ }
1545
+ }