dsh-powertools 0.0.0-stage → 0.2.2

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 (254) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -2
  3. package/client.js +3213 -0
  4. package/cordis.patch.yml +3 -0
  5. package/icon.svg +9 -0
  6. package/index.js +90 -0
  7. package/lib/credentials.js +173 -0
  8. package/lib/enhance.js +159 -0
  9. package/lib/errors.js +11 -0
  10. package/lib/instructions.js +298 -0
  11. package/lib/mcp.js +124 -0
  12. package/lib/platform.js +70 -0
  13. package/lib/sessions.js +516 -0
  14. package/lib/skill-repositories.js +152 -0
  15. package/lib/skills.js +280 -0
  16. package/lib/tasks.js +244 -0
  17. package/licenses/lucide.txt +43 -0
  18. package/licenses/magi-code.txt +203 -0
  19. package/locale/en.json +1 -0
  20. package/locale/zh.json +1 -0
  21. package/node_modules/yaml/LICENSE +13 -0
  22. package/node_modules/yaml/README.md +172 -0
  23. package/node_modules/yaml/bin.mjs +11 -0
  24. package/node_modules/yaml/browser/dist/compose/compose-collection.js +88 -0
  25. package/node_modules/yaml/browser/dist/compose/compose-doc.js +43 -0
  26. package/node_modules/yaml/browser/dist/compose/compose-node.js +109 -0
  27. package/node_modules/yaml/browser/dist/compose/compose-scalar.js +86 -0
  28. package/node_modules/yaml/browser/dist/compose/composer.js +219 -0
  29. package/node_modules/yaml/browser/dist/compose/resolve-block-map.js +115 -0
  30. package/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +198 -0
  31. package/node_modules/yaml/browser/dist/compose/resolve-block-seq.js +49 -0
  32. package/node_modules/yaml/browser/dist/compose/resolve-end.js +37 -0
  33. package/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +207 -0
  34. package/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +226 -0
  35. package/node_modules/yaml/browser/dist/compose/resolve-props.js +146 -0
  36. package/node_modules/yaml/browser/dist/compose/util-contains-newline.js +34 -0
  37. package/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +26 -0
  38. package/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +15 -0
  39. package/node_modules/yaml/browser/dist/compose/util-map-includes.js +13 -0
  40. package/node_modules/yaml/browser/dist/doc/Document.js +335 -0
  41. package/node_modules/yaml/browser/dist/doc/anchors.js +71 -0
  42. package/node_modules/yaml/browser/dist/doc/applyReviver.js +55 -0
  43. package/node_modules/yaml/browser/dist/doc/createNode.js +88 -0
  44. package/node_modules/yaml/browser/dist/doc/directives.js +176 -0
  45. package/node_modules/yaml/browser/dist/errors.js +57 -0
  46. package/node_modules/yaml/browser/dist/index.js +17 -0
  47. package/node_modules/yaml/browser/dist/log.js +11 -0
  48. package/node_modules/yaml/browser/dist/nodes/Alias.js +118 -0
  49. package/node_modules/yaml/browser/dist/nodes/Collection.js +147 -0
  50. package/node_modules/yaml/browser/dist/nodes/Node.js +38 -0
  51. package/node_modules/yaml/browser/dist/nodes/Pair.js +36 -0
  52. package/node_modules/yaml/browser/dist/nodes/Scalar.js +24 -0
  53. package/node_modules/yaml/browser/dist/nodes/YAMLMap.js +144 -0
  54. package/node_modules/yaml/browser/dist/nodes/YAMLSeq.js +113 -0
  55. package/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +63 -0
  56. package/node_modules/yaml/browser/dist/nodes/identity.js +36 -0
  57. package/node_modules/yaml/browser/dist/nodes/toJS.js +37 -0
  58. package/node_modules/yaml/browser/dist/parse/cst-scalar.js +214 -0
  59. package/node_modules/yaml/browser/dist/parse/cst-stringify.js +61 -0
  60. package/node_modules/yaml/browser/dist/parse/cst-visit.js +97 -0
  61. package/node_modules/yaml/browser/dist/parse/cst.js +98 -0
  62. package/node_modules/yaml/browser/dist/parse/lexer.js +721 -0
  63. package/node_modules/yaml/browser/dist/parse/line-counter.js +39 -0
  64. package/node_modules/yaml/browser/dist/parse/parser.js +975 -0
  65. package/node_modules/yaml/browser/dist/public-api.js +102 -0
  66. package/node_modules/yaml/browser/dist/schema/Schema.js +37 -0
  67. package/node_modules/yaml/browser/dist/schema/common/map.js +17 -0
  68. package/node_modules/yaml/browser/dist/schema/common/null.js +15 -0
  69. package/node_modules/yaml/browser/dist/schema/common/seq.js +17 -0
  70. package/node_modules/yaml/browser/dist/schema/common/string.js +14 -0
  71. package/node_modules/yaml/browser/dist/schema/core/bool.js +19 -0
  72. package/node_modules/yaml/browser/dist/schema/core/float.js +43 -0
  73. package/node_modules/yaml/browser/dist/schema/core/int.js +38 -0
  74. package/node_modules/yaml/browser/dist/schema/core/schema.js +23 -0
  75. package/node_modules/yaml/browser/dist/schema/json/schema.js +62 -0
  76. package/node_modules/yaml/browser/dist/schema/tags.js +96 -0
  77. package/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +58 -0
  78. package/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +26 -0
  79. package/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +46 -0
  80. package/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +71 -0
  81. package/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +67 -0
  82. package/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +74 -0
  83. package/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +78 -0
  84. package/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +39 -0
  85. package/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +93 -0
  86. package/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +101 -0
  87. package/node_modules/yaml/browser/dist/stringify/foldFlowLines.js +146 -0
  88. package/node_modules/yaml/browser/dist/stringify/stringify.js +129 -0
  89. package/node_modules/yaml/browser/dist/stringify/stringifyCollection.js +153 -0
  90. package/node_modules/yaml/browser/dist/stringify/stringifyComment.js +20 -0
  91. package/node_modules/yaml/browser/dist/stringify/stringifyDocument.js +85 -0
  92. package/node_modules/yaml/browser/dist/stringify/stringifyNumber.js +25 -0
  93. package/node_modules/yaml/browser/dist/stringify/stringifyPair.js +150 -0
  94. package/node_modules/yaml/browser/dist/stringify/stringifyString.js +336 -0
  95. package/node_modules/yaml/browser/dist/util.js +11 -0
  96. package/node_modules/yaml/browser/dist/visit.js +233 -0
  97. package/node_modules/yaml/browser/index.js +5 -0
  98. package/node_modules/yaml/browser/package.json +3 -0
  99. package/node_modules/yaml/dist/cli.d.ts +8 -0
  100. package/node_modules/yaml/dist/cli.mjs +201 -0
  101. package/node_modules/yaml/dist/compose/compose-collection.d.ts +11 -0
  102. package/node_modules/yaml/dist/compose/compose-collection.js +90 -0
  103. package/node_modules/yaml/dist/compose/compose-doc.d.ts +7 -0
  104. package/node_modules/yaml/dist/compose/compose-doc.js +45 -0
  105. package/node_modules/yaml/dist/compose/compose-node.d.ts +29 -0
  106. package/node_modules/yaml/dist/compose/compose-node.js +112 -0
  107. package/node_modules/yaml/dist/compose/compose-scalar.d.ts +5 -0
  108. package/node_modules/yaml/dist/compose/compose-scalar.js +88 -0
  109. package/node_modules/yaml/dist/compose/composer.d.ts +63 -0
  110. package/node_modules/yaml/dist/compose/composer.js +224 -0
  111. package/node_modules/yaml/dist/compose/resolve-block-map.d.ts +6 -0
  112. package/node_modules/yaml/dist/compose/resolve-block-map.js +117 -0
  113. package/node_modules/yaml/dist/compose/resolve-block-scalar.d.ts +11 -0
  114. package/node_modules/yaml/dist/compose/resolve-block-scalar.js +200 -0
  115. package/node_modules/yaml/dist/compose/resolve-block-seq.d.ts +6 -0
  116. package/node_modules/yaml/dist/compose/resolve-block-seq.js +51 -0
  117. package/node_modules/yaml/dist/compose/resolve-end.d.ts +6 -0
  118. package/node_modules/yaml/dist/compose/resolve-end.js +39 -0
  119. package/node_modules/yaml/dist/compose/resolve-flow-collection.d.ts +7 -0
  120. package/node_modules/yaml/dist/compose/resolve-flow-collection.js +209 -0
  121. package/node_modules/yaml/dist/compose/resolve-flow-scalar.d.ts +10 -0
  122. package/node_modules/yaml/dist/compose/resolve-flow-scalar.js +228 -0
  123. package/node_modules/yaml/dist/compose/resolve-props.d.ts +23 -0
  124. package/node_modules/yaml/dist/compose/resolve-props.js +148 -0
  125. package/node_modules/yaml/dist/compose/util-contains-newline.d.ts +2 -0
  126. package/node_modules/yaml/dist/compose/util-contains-newline.js +36 -0
  127. package/node_modules/yaml/dist/compose/util-empty-scalar-position.d.ts +2 -0
  128. package/node_modules/yaml/dist/compose/util-empty-scalar-position.js +28 -0
  129. package/node_modules/yaml/dist/compose/util-flow-indent-check.d.ts +3 -0
  130. package/node_modules/yaml/dist/compose/util-flow-indent-check.js +17 -0
  131. package/node_modules/yaml/dist/compose/util-map-includes.d.ts +4 -0
  132. package/node_modules/yaml/dist/compose/util-map-includes.js +15 -0
  133. package/node_modules/yaml/dist/doc/Document.d.ts +141 -0
  134. package/node_modules/yaml/dist/doc/Document.js +337 -0
  135. package/node_modules/yaml/dist/doc/anchors.d.ts +24 -0
  136. package/node_modules/yaml/dist/doc/anchors.js +76 -0
  137. package/node_modules/yaml/dist/doc/applyReviver.d.ts +9 -0
  138. package/node_modules/yaml/dist/doc/applyReviver.js +57 -0
  139. package/node_modules/yaml/dist/doc/createNode.d.ts +17 -0
  140. package/node_modules/yaml/dist/doc/createNode.js +90 -0
  141. package/node_modules/yaml/dist/doc/directives.d.ts +49 -0
  142. package/node_modules/yaml/dist/doc/directives.js +178 -0
  143. package/node_modules/yaml/dist/errors.d.ts +21 -0
  144. package/node_modules/yaml/dist/errors.js +62 -0
  145. package/node_modules/yaml/dist/index.d.ts +25 -0
  146. package/node_modules/yaml/dist/index.js +50 -0
  147. package/node_modules/yaml/dist/log.d.ts +3 -0
  148. package/node_modules/yaml/dist/log.js +19 -0
  149. package/node_modules/yaml/dist/nodes/Alias.d.ts +29 -0
  150. package/node_modules/yaml/dist/nodes/Alias.js +120 -0
  151. package/node_modules/yaml/dist/nodes/Collection.d.ts +73 -0
  152. package/node_modules/yaml/dist/nodes/Collection.js +151 -0
  153. package/node_modules/yaml/dist/nodes/Node.d.ts +53 -0
  154. package/node_modules/yaml/dist/nodes/Node.js +40 -0
  155. package/node_modules/yaml/dist/nodes/Pair.d.ts +22 -0
  156. package/node_modules/yaml/dist/nodes/Pair.js +39 -0
  157. package/node_modules/yaml/dist/nodes/Scalar.d.ts +47 -0
  158. package/node_modules/yaml/dist/nodes/Scalar.js +27 -0
  159. package/node_modules/yaml/dist/nodes/YAMLMap.d.ts +53 -0
  160. package/node_modules/yaml/dist/nodes/YAMLMap.js +147 -0
  161. package/node_modules/yaml/dist/nodes/YAMLSeq.d.ts +60 -0
  162. package/node_modules/yaml/dist/nodes/YAMLSeq.js +115 -0
  163. package/node_modules/yaml/dist/nodes/addPairToJSMap.d.ts +4 -0
  164. package/node_modules/yaml/dist/nodes/addPairToJSMap.js +65 -0
  165. package/node_modules/yaml/dist/nodes/identity.d.ts +23 -0
  166. package/node_modules/yaml/dist/nodes/identity.js +53 -0
  167. package/node_modules/yaml/dist/nodes/toJS.d.ts +29 -0
  168. package/node_modules/yaml/dist/nodes/toJS.js +39 -0
  169. package/node_modules/yaml/dist/options.d.ts +350 -0
  170. package/node_modules/yaml/dist/parse/cst-scalar.d.ts +64 -0
  171. package/node_modules/yaml/dist/parse/cst-scalar.js +218 -0
  172. package/node_modules/yaml/dist/parse/cst-stringify.d.ts +8 -0
  173. package/node_modules/yaml/dist/parse/cst-stringify.js +63 -0
  174. package/node_modules/yaml/dist/parse/cst-visit.d.ts +39 -0
  175. package/node_modules/yaml/dist/parse/cst-visit.js +99 -0
  176. package/node_modules/yaml/dist/parse/cst.d.ts +109 -0
  177. package/node_modules/yaml/dist/parse/cst.js +112 -0
  178. package/node_modules/yaml/dist/parse/lexer.d.ts +87 -0
  179. package/node_modules/yaml/dist/parse/lexer.js +723 -0
  180. package/node_modules/yaml/dist/parse/line-counter.d.ts +22 -0
  181. package/node_modules/yaml/dist/parse/line-counter.js +41 -0
  182. package/node_modules/yaml/dist/parse/parser.d.ts +84 -0
  183. package/node_modules/yaml/dist/parse/parser.js +980 -0
  184. package/node_modules/yaml/dist/public-api.d.ts +44 -0
  185. package/node_modules/yaml/dist/public-api.js +107 -0
  186. package/node_modules/yaml/dist/schema/Schema.d.ts +17 -0
  187. package/node_modules/yaml/dist/schema/Schema.js +39 -0
  188. package/node_modules/yaml/dist/schema/common/map.d.ts +2 -0
  189. package/node_modules/yaml/dist/schema/common/map.js +19 -0
  190. package/node_modules/yaml/dist/schema/common/null.d.ts +4 -0
  191. package/node_modules/yaml/dist/schema/common/null.js +17 -0
  192. package/node_modules/yaml/dist/schema/common/seq.d.ts +2 -0
  193. package/node_modules/yaml/dist/schema/common/seq.js +19 -0
  194. package/node_modules/yaml/dist/schema/common/string.d.ts +2 -0
  195. package/node_modules/yaml/dist/schema/common/string.js +16 -0
  196. package/node_modules/yaml/dist/schema/core/bool.d.ts +4 -0
  197. package/node_modules/yaml/dist/schema/core/bool.js +21 -0
  198. package/node_modules/yaml/dist/schema/core/float.d.ts +4 -0
  199. package/node_modules/yaml/dist/schema/core/float.js +47 -0
  200. package/node_modules/yaml/dist/schema/core/int.d.ts +4 -0
  201. package/node_modules/yaml/dist/schema/core/int.js +42 -0
  202. package/node_modules/yaml/dist/schema/core/schema.d.ts +1 -0
  203. package/node_modules/yaml/dist/schema/core/schema.js +25 -0
  204. package/node_modules/yaml/dist/schema/json/schema.d.ts +2 -0
  205. package/node_modules/yaml/dist/schema/json/schema.js +64 -0
  206. package/node_modules/yaml/dist/schema/json-schema.d.ts +69 -0
  207. package/node_modules/yaml/dist/schema/tags.d.ts +48 -0
  208. package/node_modules/yaml/dist/schema/tags.js +99 -0
  209. package/node_modules/yaml/dist/schema/types.d.ts +92 -0
  210. package/node_modules/yaml/dist/schema/yaml-1.1/binary.d.ts +2 -0
  211. package/node_modules/yaml/dist/schema/yaml-1.1/binary.js +70 -0
  212. package/node_modules/yaml/dist/schema/yaml-1.1/bool.d.ts +7 -0
  213. package/node_modules/yaml/dist/schema/yaml-1.1/bool.js +29 -0
  214. package/node_modules/yaml/dist/schema/yaml-1.1/float.d.ts +4 -0
  215. package/node_modules/yaml/dist/schema/yaml-1.1/float.js +50 -0
  216. package/node_modules/yaml/dist/schema/yaml-1.1/int.d.ts +5 -0
  217. package/node_modules/yaml/dist/schema/yaml-1.1/int.js +76 -0
  218. package/node_modules/yaml/dist/schema/yaml-1.1/merge.d.ts +9 -0
  219. package/node_modules/yaml/dist/schema/yaml-1.1/merge.js +71 -0
  220. package/node_modules/yaml/dist/schema/yaml-1.1/omap.d.ts +22 -0
  221. package/node_modules/yaml/dist/schema/yaml-1.1/omap.js +77 -0
  222. package/node_modules/yaml/dist/schema/yaml-1.1/pairs.d.ts +10 -0
  223. package/node_modules/yaml/dist/schema/yaml-1.1/pairs.js +82 -0
  224. package/node_modules/yaml/dist/schema/yaml-1.1/schema.d.ts +1 -0
  225. package/node_modules/yaml/dist/schema/yaml-1.1/schema.js +41 -0
  226. package/node_modules/yaml/dist/schema/yaml-1.1/set.d.ts +28 -0
  227. package/node_modules/yaml/dist/schema/yaml-1.1/set.js +96 -0
  228. package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.d.ts +6 -0
  229. package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +105 -0
  230. package/node_modules/yaml/dist/stringify/foldFlowLines.d.ts +34 -0
  231. package/node_modules/yaml/dist/stringify/foldFlowLines.js +151 -0
  232. package/node_modules/yaml/dist/stringify/stringify.d.ts +21 -0
  233. package/node_modules/yaml/dist/stringify/stringify.js +132 -0
  234. package/node_modules/yaml/dist/stringify/stringifyCollection.d.ts +17 -0
  235. package/node_modules/yaml/dist/stringify/stringifyCollection.js +155 -0
  236. package/node_modules/yaml/dist/stringify/stringifyComment.d.ts +10 -0
  237. package/node_modules/yaml/dist/stringify/stringifyComment.js +24 -0
  238. package/node_modules/yaml/dist/stringify/stringifyDocument.d.ts +4 -0
  239. package/node_modules/yaml/dist/stringify/stringifyDocument.js +87 -0
  240. package/node_modules/yaml/dist/stringify/stringifyNumber.d.ts +2 -0
  241. package/node_modules/yaml/dist/stringify/stringifyNumber.js +27 -0
  242. package/node_modules/yaml/dist/stringify/stringifyPair.d.ts +3 -0
  243. package/node_modules/yaml/dist/stringify/stringifyPair.js +152 -0
  244. package/node_modules/yaml/dist/stringify/stringifyString.d.ts +9 -0
  245. package/node_modules/yaml/dist/stringify/stringifyString.js +338 -0
  246. package/node_modules/yaml/dist/test-events.d.ts +4 -0
  247. package/node_modules/yaml/dist/test-events.js +134 -0
  248. package/node_modules/yaml/dist/util.d.ts +16 -0
  249. package/node_modules/yaml/dist/util.js +28 -0
  250. package/node_modules/yaml/dist/visit.d.ts +102 -0
  251. package/node_modules/yaml/dist/visit.js +236 -0
  252. package/node_modules/yaml/package.json +97 -0
  253. package/node_modules/yaml/util.js +2 -0
  254. package/package.json +74 -4
@@ -0,0 +1,516 @@
1
+ import { lstat, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { RequestError, requireValue } from './errors.js'
4
+ import { confinedPath, inside, moveLocal, statOrMissing } from './platform.js'
5
+
6
+ const allowedArtifactFile = /^(?:session(?:\.v\d+)?\.jsonl(?:\.zstd?)?|session\.lock|[\w.-]+\.jsonl(?:\.zstd?)?)$/i
7
+
8
+ function buildLineage(items) {
9
+ const byId = new Map(items.map(item => [item.id, item]))
10
+ const subagentChildren = new Map()
11
+ for (const item of items) {
12
+ if (item.isSubagent && item.parentSessionId && byId.has(item.parentSessionId)) {
13
+ const list = subagentChildren.get(item.parentSessionId) ?? []
14
+ list.push(item.id)
15
+ subagentChildren.set(item.parentSessionId, list)
16
+ }
17
+ }
18
+ function collectDescendants(rootId) {
19
+ const result = []
20
+ const visited = new Set([rootId])
21
+ const queue = [rootId]
22
+ while (queue.length > 0) {
23
+ const current = queue.shift()
24
+ for (const childId of subagentChildren.get(current) ?? []) {
25
+ if (visited.has(childId)) continue
26
+ visited.add(childId)
27
+ result.push(childId)
28
+ queue.push(childId)
29
+ }
30
+ }
31
+ return result
32
+ }
33
+ function rootAncestor(item) {
34
+ const visited = new Set([item.id])
35
+ let cursor = item
36
+ while (cursor.isSubagent && cursor.parentSessionId && byId.has(cursor.parentSessionId)) {
37
+ if (visited.has(cursor.parentSessionId)) break
38
+ visited.add(cursor.parentSessionId)
39
+ cursor = byId.get(cursor.parentSessionId)
40
+ }
41
+ return cursor.id
42
+ }
43
+ return { byId, subagentChildren, collectDescendants, rootAncestor }
44
+ }
45
+
46
+ async function validateJsonlSessionDirectory(location, workspacePaths) {
47
+ if (!location || location.kind !== 'jsonl' || typeof location.path !== 'string' || !path.isAbsolute(location.path)) {
48
+ return { ok: false, reason: '当前会话尚未落盘或后端不支持单会话目录回收(如 SQLite 存储)。' }
49
+ }
50
+ const file = path.resolve(location.path)
51
+ const dir = path.dirname(file)
52
+ if (!dir || dir === path.dirname(dir)) {
53
+ return { ok: false, reason: '会话文件位置异常,已拒绝删除。' }
54
+ }
55
+ for (const wsPath of workspacePaths) {
56
+ if (!wsPath) continue
57
+ const resolvedWs = path.resolve(wsPath)
58
+ if (dir === resolvedWs || inside(dir, resolvedWs) || inside(resolvedWs, dir)) {
59
+ return { ok: false, reason: '会话位置与工作区目录重叠,已拒绝删除以保护工作区文件。' }
60
+ }
61
+ }
62
+ const dirInfo = await statOrMissing(dir)
63
+ const fileInfo = await statOrMissing(file)
64
+ if (!dirInfo?.isDirectory() || dirInfo.isSymbolicLink() || !fileInfo?.isFile() || fileInfo.isSymbolicLink()) {
65
+ return { ok: false, reason: '会话目录或文件不存在,或是符号链接,已拒绝删除。' }
66
+ }
67
+ if (!await confinedPath(dir, file)) {
68
+ return { ok: false, reason: '会话文件路径超出所属目录范围,已拒绝删除。' }
69
+ }
70
+ const entries = await readdir(dir, { withFileTypes: true })
71
+ for (const entry of entries) {
72
+ if (!entry.isFile() || !allowedArtifactFile.test(entry.name)) {
73
+ return { ok: false, reason: `会话目录包含非预期文件(${entry.name}),已拒绝删除以防止误删数据。` }
74
+ }
75
+ }
76
+ return { ok: true, dir, file }
77
+ }
78
+
79
+ export async function collectAllSessions(ctx, signal) {
80
+ const persistence = ctx.sessionPersistence
81
+ const persisted = await persistence.list({ signal })
82
+ const liveSessions = typeof ctx.sessions?.list === 'function' ? ctx.sessions.list() : []
83
+ const workspaces = typeof ctx.workspaceRegistry?.list === 'function' ? ctx.workspaceRegistry.list() : []
84
+ const archivedSet = new Set(ctx.workspaceRegistry?.archivedSessionIds ?? [])
85
+ const pinnedList = Array.isArray(ctx.workspaceRegistry?.pinnedSessionIds) ? ctx.workspaceRegistry.pinnedSessionIds : []
86
+ const pinnedOrder = new Map(pinnedList.map((id, index) => [id, index]))
87
+
88
+ const wsBySession = new Map()
89
+ for (const ws of workspaces) {
90
+ for (const id of ws.sessionIds ?? []) {
91
+ const list = wsBySession.get(id) ?? []
92
+ list.push({ workspaceId: ws.workspaceId, title: ws.title, path: ws.path })
93
+ wsBySession.set(id, list)
94
+ }
95
+ }
96
+
97
+ const byId = new Map()
98
+ for (const snap of persisted) {
99
+ const header = snap.header
100
+ if (!header?.id) continue
101
+ byId.set(header.id, {
102
+ id: header.id,
103
+ createdAt: header.createdAt ?? 0,
104
+ cwd: header.cwd ?? '',
105
+ parentSessionId: header.parentSession ?? null,
106
+ isSubagent: header.origin === 'subagent',
107
+ isFork: Boolean(header.parentSession && header.origin !== 'subagent'),
108
+ delegationDepth: header.delegationDepth ?? null,
109
+ agentPreset: header.agentPreset ?? null,
110
+ persisted: true,
111
+ resident: false,
112
+ running: false,
113
+ archived: archivedSet.has(header.id),
114
+ pinned: pinnedOrder.has(header.id),
115
+ pinnedRank: pinnedOrder.get(header.id) ?? -1,
116
+ sizeBytes: snap.sizeBytes ?? null,
117
+ eventCount: snap.eventCount ?? null,
118
+ location: snap.location ?? null,
119
+ formatStatus: snap.formatStatus ?? null,
120
+ workspaces: wsBySession.get(header.id) ?? [],
121
+ })
122
+ }
123
+
124
+ for (const session of liveSessions) {
125
+ const header = session?.header
126
+ if (!header?.id) continue
127
+ const agent = ctx.agents?.get?.(header.id)
128
+ const existing = byId.get(header.id)
129
+ const running = agent?.status === 'running'
130
+ byId.set(header.id, {
131
+ id: header.id,
132
+ createdAt: header.createdAt ?? existing?.createdAt ?? 0,
133
+ cwd: header.cwd ?? existing?.cwd ?? '',
134
+ parentSessionId: header.parentSession ?? existing?.parentSessionId ?? null,
135
+ isSubagent: header.origin === 'subagent' || Boolean(existing?.isSubagent),
136
+ isFork: Boolean((header.parentSession ?? existing?.parentSessionId) && header.origin !== 'subagent'),
137
+ delegationDepth: header.delegationDepth ?? existing?.delegationDepth ?? null,
138
+ agentPreset: header.agentPreset ?? existing?.agentPreset ?? null,
139
+ persisted: Boolean(existing?.persisted),
140
+ resident: true,
141
+ running,
142
+ archived: archivedSet.has(header.id),
143
+ pinned: pinnedOrder.has(header.id),
144
+ pinnedRank: pinnedOrder.get(header.id) ?? -1,
145
+ sizeBytes: existing?.sizeBytes ?? null,
146
+ eventCount: existing?.eventCount ?? null,
147
+ location: existing?.location ?? null,
148
+ formatStatus: existing?.formatStatus ?? 'current',
149
+ workspaces: wsBySession.get(header.id) ?? existing?.workspaces ?? [],
150
+ })
151
+ }
152
+
153
+ const items = [...byId.values()]
154
+ const { subagentChildren, collectDescendants, rootAncestor } = buildLineage(items)
155
+
156
+ return items.map(item => {
157
+ const descendantIds = collectDescendants(item.id)
158
+ const directSubagentIds = subagentChildren.get(item.id) ?? []
159
+ const rootId = rootAncestor(item)
160
+ const orphanSubagent = item.isSubagent && (!item.parentSessionId || !byId.has(item.parentSessionId))
161
+ const cascadeIds = [item.id, ...descendantIds]
162
+ let deleteReason = ''
163
+ let deleteBlocker
164
+
165
+ for (const targetId of cascadeIds) {
166
+ const target = byId.get(targetId)
167
+ if (!target) continue
168
+ if (target.running) {
169
+ deleteBlocker = target.id === item.id ? 'running' : 'childRunning'
170
+ deleteReason = target.id === item.id ? '会话正在运行中,请先停止后再删除。' : '关联子 Agent 正在运行中,请先停止后再删除。'
171
+ break
172
+ }
173
+ if (target.resident) {
174
+ deleteBlocker = target.id === item.id ? 'resident' : 'childResident'
175
+ deleteReason = target.id === item.id
176
+ ? '会话正由当前 DSH 进程打开持有,请关闭或重启 DSH 释放句柄后再删除。'
177
+ : '关联子 Agent 正由当前 DSH 进程持有,请等待结束或重启 DSH 后再删除。'
178
+ break
179
+ }
180
+ if (target.location?.kind !== 'jsonl' || !target.location?.path) {
181
+ deleteBlocker = 'storage'
182
+ deleteReason = '当前会话或关联子 Agent 未落盘为 JSONL 单会话目录(如 SQLite 后端),暂不支持安全删除。'
183
+ break
184
+ }
185
+ }
186
+
187
+ return {
188
+ id: item.id,
189
+ createdAt: item.createdAt,
190
+ cwd: item.cwd,
191
+ parentSessionId: item.parentSessionId,
192
+ rootSessionId: rootId,
193
+ isSubagent: item.isSubagent,
194
+ isFork: item.isFork,
195
+ orphanSubagent,
196
+ delegationDepth: item.delegationDepth,
197
+ agentPreset: item.agentPreset,
198
+ persisted: item.persisted,
199
+ resident: item.resident,
200
+ running: item.running,
201
+ archived: item.archived,
202
+ pinned: item.pinned,
203
+ pinnedRank: item.pinnedRank,
204
+ sizeBytes: item.sizeBytes,
205
+ eventCount: item.eventCount,
206
+ backendKind: item.location?.kind ?? (item.persisted ? 'unknown' : 'pending'),
207
+ workspaces: item.workspaces.map(({ workspaceId, title }) => ({ workspaceId, title })),
208
+ directSubagentIds,
209
+ descendantSubagentIds: descendantIds,
210
+ deletable: !deleteBlocker,
211
+ deleteBlocker,
212
+ deleteReason: deleteReason || undefined,
213
+ _location: item.location,
214
+ }
215
+ })
216
+ }
217
+
218
+ export function sessionOperations(ctx) {
219
+ let tail = Promise.resolve()
220
+
221
+ async function list(signal) {
222
+ const rows = await collectAllSessions(ctx, signal)
223
+ return {
224
+ sessions: rows.map(({ _location, ...publicRow }) => publicRow),
225
+ }
226
+ }
227
+
228
+ async function executeDelete(requestedIds, singleRootId, signal) {
229
+ const all = await collectAllSessions(ctx, signal)
230
+ const byId = new Map(all.map(row => [row.id, row]))
231
+ const roots = []
232
+ for (const sessionId of requestedIds) {
233
+ const root = byId.get(sessionId)
234
+ requireValue(root, requestedIds.length === 1 ? '目标会话不存在或已被移除,请刷新列表。' : `目标会话(${sessionId})不存在或已被移除,请刷新列表。`, 404)
235
+ roots.push(root)
236
+ }
237
+
238
+ const targetIdSet = new Set()
239
+ for (const root of roots) {
240
+ targetIdSet.add(root.id)
241
+ for (const subId of root.descendantSubagentIds) {
242
+ if (byId.has(subId)) targetIdSet.add(subId)
243
+ }
244
+ }
245
+ const targets = [...targetIdSet].map(id => byId.get(id)).filter(Boolean)
246
+ const requestedSet = new Set(requestedIds)
247
+ const workspaces = typeof ctx.workspaceRegistry?.list === 'function' ? ctx.workspaceRegistry.list() : []
248
+ const workspacePaths = workspaces.map(ws => ws.path).filter(Boolean)
249
+
250
+ // Phase 1: Validate every target & acquire write ownership atomically (sorted to prevent lock ordering issues).
251
+ const sortedTargets = [...targets].sort((a, b) => a.id.localeCompare(b.id))
252
+ const handles = []
253
+ const validated = []
254
+ try {
255
+ for (const target of sortedTargets) {
256
+ signal.throwIfAborted()
257
+ const isDirect = requestedSet.has(target.id)
258
+ if (target.running || ctx.agents?.get?.(target.id)?.status === 'running') {
259
+ throw new RequestError(isDirect && singleRootId
260
+ ? '会话正在运行中,请先停止后再删除。'
261
+ : `${isDirect ? '会话' : '关联子 Agent'}(${target.id})正在运行中,请先停止后再删除。`, 409)
262
+ }
263
+ if (target.resident || ctx.sessions?.get?.(target.id) || ctx.agents?.get?.(target.id)) {
264
+ throw new RequestError(isDirect && singleRootId
265
+ ? '会话正由当前 DSH 进程打开持有,请切换或重启 DSH 释放写句柄后再删除。'
266
+ : `${isDirect ? '会话' : '关联子 Agent'}(${target.id})正由当前 DSH 进程持有,请等待释放或重启 DSH 后再删除。`, 409)
267
+ }
268
+ const check = await validateJsonlSessionDirectory(target._location, workspacePaths)
269
+ if (!check.ok) throw new RequestError(check.reason, 409)
270
+ let handle
271
+ try {
272
+ handle = await ctx.sessionPersistence.open(target.id, 'write', { signal })
273
+ } catch (error) {
274
+ if (error?.name === 'SessionAlreadyOwnedError') {
275
+ throw new RequestError(`会话 ${target.id} 正在被其他进程或句柄写入,已拒绝删除。`, 409)
276
+ }
277
+ if (error?.name === 'SessionPersistenceNotFoundError') {
278
+ throw new RequestError(`会话 ${target.id} 已不存在,请刷新列表。`, 404)
279
+ }
280
+ throw error
281
+ }
282
+ handles.push(handle)
283
+ validated.push({ target, dir: check.dir, file: check.file })
284
+ }
285
+ } finally {
286
+ // Release all write leases before moving directories (required on Windows and clean on macOS).
287
+ for (const handle of handles.reverse()) {
288
+ await handle.close().catch(() => {})
289
+ }
290
+ }
291
+
292
+ signal.throwIfAborted()
293
+
294
+ // Phase 2: Move all session directories into a single recoverable batch folder (rollback on partial error).
295
+ const profileDir = ctx.profileContext?.dir
296
+ requireValue(typeof profileDir === 'string' && path.isAbsolute(profileDir), '无法定位 Profile 可恢复目录。', 503)
297
+ const recoveryRoot = path.join(profileDir, 'powertools-session-recovery')
298
+ await mkdir(recoveryRoot, { recursive: true, mode: 0o700 })
299
+ const batchDir = await mkdtemp(path.join(recoveryRoot, 'deleted-'))
300
+ const padWidth = Math.max(2, String(validated.length).length)
301
+ const moved = []
302
+ try {
303
+ for (let index = 0; index < validated.length; index++) {
304
+ const entry = validated[index]
305
+ const folderName = `${String(index + 1).padStart(padWidth, '0')}-${path.basename(entry.dir)}`
306
+ const destination = path.join(batchDir, folderName)
307
+ await moveLocal(entry.dir, destination)
308
+ moved.push({
309
+ id: entry.target.id,
310
+ isSubagent: entry.target.isSubagent,
311
+ parentSessionId: entry.target.parentSessionId,
312
+ sourceDir: entry.dir,
313
+ recoveredDir: destination,
314
+ })
315
+ }
316
+ const manifestPayload = {
317
+ deletedAt: Date.now(),
318
+ ...(singleRootId ? { rootSessionId: singleRootId } : {}),
319
+ rootSessionIds: requestedIds,
320
+ items: moved,
321
+ }
322
+ await writeFile(
323
+ path.join(batchDir, 'manifest.json'),
324
+ JSON.stringify(manifestPayload, null, 2) + '\n',
325
+ { mode: 0o600 },
326
+ )
327
+ } catch (error) {
328
+ for (const item of moved.reverse()) {
329
+ await moveLocal(item.recoveredDir, item.sourceDir).catch(() => {})
330
+ }
331
+ await rm(batchDir, { recursive: true, force: true }).catch(() => {})
332
+ throw error
333
+ }
334
+
335
+ // Phase 3: Best-effort cleanup of archive/pin registry entries so deleted IDs don't linger.
336
+ for (const item of moved) {
337
+ if (typeof ctx.workspaceRegistry?.unarchiveSession === 'function') {
338
+ await ctx.workspaceRegistry.unarchiveSession(item.id).catch(() => {})
339
+ }
340
+ if (typeof ctx.workspaceRegistry?.unpinSession === 'function') {
341
+ await ctx.workspaceRegistry.unpinSession(item.id).catch(() => {})
342
+ }
343
+ }
344
+
345
+ return {
346
+ deletedIds: moved.map(item => item.id),
347
+ requestedCount: requestedIds.length,
348
+ subagentCount: singleRootId
349
+ ? moved.filter(item => item.id !== singleRootId).length
350
+ : moved.filter(item => item.isSubagent).length,
351
+ cascadedCount: moved.filter(item => !requestedSet.has(item.id)).length,
352
+ recovery: batchDir,
353
+ }
354
+ }
355
+
356
+ async function remove(body, signal) {
357
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
358
+ requireValue(sessionId, '请指定要删除的会话 ID。')
359
+ requireValue(body.confirm === sessionId, '请确认要删除的目标会话。', 409)
360
+ return executeDelete([sessionId], sessionId, signal)
361
+ }
362
+
363
+ async function batchRemove(body, signal) {
364
+ requireValue(Array.isArray(body.sessionIds) && body.sessionIds.length > 0, '请至少选择一条要删除的会话。')
365
+ requireValue(body.sessionIds.length <= 500, '单次批量删除最多支持 500 条会话,请分批处理。')
366
+ requireValue(body.confirm === true, '请确认批量删除的目标会话。', 409)
367
+ const uniqueIds = [...new Set(body.sessionIds.map(id => typeof id === 'string' ? id.trim() : '').filter(Boolean))]
368
+ requireValue(uniqueIds.length === body.sessionIds.length, '批量删除列表中包含无效或重复的会话 ID。')
369
+ return executeDelete(uniqueIds, null, signal)
370
+ }
371
+
372
+ function extractEventPlainText(event) {
373
+ if (!event || typeof event !== 'object') return ''
374
+ if (event.type === 'user/message') {
375
+ const kind = event.data?.source?.kind
376
+ if (kind && kind !== 'user') return ''
377
+ const content = event.data?.content
378
+ if (!Array.isArray(content)) return ''
379
+ return content.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text).join('\n').trim()
380
+ }
381
+ if (event.type === 'assistant/message') {
382
+ const content = event.data?.message?.content
383
+ if (!Array.isArray(content)) return ''
384
+ return content.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text).join('\n').trim()
385
+ }
386
+ return ''
387
+ }
388
+
389
+ function buildSnippet(text, needleLower) {
390
+ const collapsed = text.replace(/\s+/g, ' ').trim()
391
+ const index = collapsed.toLowerCase().indexOf(needleLower)
392
+ if (index < 0) return ''
393
+ const start = Math.max(0, index - 40)
394
+ const end = Math.min(collapsed.length, index + needleLower.length + 100)
395
+ return `${start > 0 ? '…' : ''}${collapsed.slice(start, end)}${end < collapsed.length ? '…' : ''}`
396
+ }
397
+
398
+ async function scanSessionsFallback(sessionQuery, query, limit, signal) {
399
+ const all = await collectAllSessions(ctx, signal)
400
+ const ordered = [...all].sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0)).slice(0, 200)
401
+ const needleLower = query.toLowerCase()
402
+ const hits = []
403
+ let index = 0
404
+ const concurrency = 4
405
+
406
+ async function worker() {
407
+ while (index < ordered.length && hits.length < limit) {
408
+ signal?.throwIfAborted()
409
+ const row = ordered[index++]
410
+ if (!row) break
411
+ let snapshot
412
+ try {
413
+ snapshot = await sessionQuery.readSession(row.id)
414
+ } catch {
415
+ continue
416
+ }
417
+ const events = Array.isArray(snapshot?.events) ? snapshot.events : []
418
+ for (let i = events.length - 1; i >= 0; i--) {
419
+ const event = events[i]
420
+ const text = extractEventPlainText(event)
421
+ if (!text) continue
422
+ const snippet = buildSnippet(text, needleLower)
423
+ if (snippet) {
424
+ hits.push({
425
+ sessionId: row.id,
426
+ seq: event.seq ?? null,
427
+ type: event.type ?? '',
428
+ time: event.time ?? row.createdAt ?? 0,
429
+ snippet,
430
+ })
431
+ break
432
+ }
433
+ }
434
+ }
435
+ }
436
+
437
+ await Promise.all(Array.from({ length: Math.min(concurrency, ordered.length) }, () => worker()))
438
+ hits.sort((a, b) => (b.time ?? 0) - (a.time ?? 0))
439
+ return { query, hits: hits.slice(0, limit), hasMore: hits.length > limit }
440
+ }
441
+
442
+ async function search(body, signal) {
443
+ const query = typeof body.query === 'string' ? body.query.trim() : ''
444
+ requireValue(query && query.length <= 256, '请输入 256 字以内的搜索关键词。')
445
+ const sessionQuery = typeof ctx.get === 'function' ? ctx.get('sessionQuery') : ctx.sessionQuery
446
+ requireValue(
447
+ typeof sessionQuery?.searchSessions === 'function' || typeof sessionQuery?.readSession === 'function',
448
+ '当前 DSH 配置未启用会话正文检索服务。',
449
+ 503,
450
+ )
451
+ const rawLimit = Number(body.limit)
452
+ const limit = Number.isInteger(rawLimit) && rawLimit >= 1 && rawLimit <= 100 ? rawLimit : 50
453
+ if (typeof sessionQuery.searchSessions === 'function') {
454
+ try {
455
+ const page = await sessionQuery.searchSessions({ query, limit }, { signal })
456
+ const cleanSnippet = raw => typeof raw === 'string'
457
+ ? raw.replaceAll('\uFDD0', '').replaceAll('\uFDD1', '').replace(/\s+/g, ' ').trim()
458
+ : ''
459
+ const hits = (page?.items ?? []).map(hit => ({
460
+ sessionId: hit.header?.id ?? hit.bestMatch?.sessionId,
461
+ seq: hit.bestMatch?.seq ?? null,
462
+ type: hit.bestMatch?.type ?? '',
463
+ time: hit.bestMatch?.time ?? 0,
464
+ snippet: cleanSnippet(hit.bestMatch?.snippet),
465
+ })).filter(hit => hit.sessionId)
466
+ return { query, hits, hasMore: Boolean(page?.nextCursor) }
467
+ } catch (error) {
468
+ if (error?.code !== 'SESSION_QUERY_SEARCH_DISABLED' || typeof sessionQuery.readSession !== 'function') {
469
+ if (error instanceof RequestError) throw error
470
+ throw new RequestError('会话正文搜索未完成,请稍后重试。', 502)
471
+ }
472
+ }
473
+ }
474
+ return scanSessionsFallback(sessionQuery, query, limit, signal)
475
+ }
476
+
477
+ async function setPinned(body, pinned) {
478
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
479
+ requireValue(sessionId, '请指定要操作的会话 ID。')
480
+ const fn = pinned ? ctx.workspaceRegistry?.pinSession : ctx.workspaceRegistry?.unpinSession
481
+ requireValue(typeof fn === 'function', '当前 DSH 版本不支持会话置顶。', 501)
482
+ try {
483
+ await fn.call(ctx.workspaceRegistry, sessionId)
484
+ } catch (error) {
485
+ if (error?.name === 'WorkspaceArchivedSessionPinError') {
486
+ throw new RequestError('已归档的会话不能置顶,请先恢复会话。', 409)
487
+ }
488
+ if (error?.name === 'WorkspaceUnknownSessionError') {
489
+ throw new RequestError('目标会话不存在或已被移除,请刷新列表。', 404)
490
+ }
491
+ throw error
492
+ }
493
+ return { sessionId, pinned }
494
+ }
495
+
496
+ return (body, signal) => {
497
+ if (body.action === 'list') return list(signal)
498
+ if (body.action === 'search') return search(body, signal)
499
+ if (body.action === 'pin' || body.action === 'unpin') {
500
+ const pending = tail.then(() => setPinned(body, body.action === 'pin'))
501
+ tail = pending.catch(() => {})
502
+ return pending
503
+ }
504
+ if (body.action === 'delete') {
505
+ const pending = tail.then(() => remove(body, signal))
506
+ tail = pending.catch(() => {})
507
+ return pending
508
+ }
509
+ if (body.action === 'batch-delete') {
510
+ const pending = tail.then(() => batchRemove(body, signal))
511
+ tail = pending.catch(() => {})
512
+ return pending
513
+ }
514
+ throw new RequestError('会话操作无效。')
515
+ }
516
+ }
@@ -0,0 +1,152 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
4
+ import { devNull } from 'node:os'
5
+ import path from 'node:path'
6
+ import { promisify } from 'node:util'
7
+ import { RequestError, requireValue } from './errors.js'
8
+ import { confinedPath, statOrMissing } from './platform.js'
9
+
10
+ const git = promisify(execFile)
11
+ const hash = value => createHash('sha256').update(value).digest('hex').slice(0, 24)
12
+
13
+ export function githubRepository(input) {
14
+ let url
15
+ try { url = new URL(input) } catch { throw new RequestError('请输入 GitHub 仓库的 HTTPS 地址。') }
16
+ const origin = url.origin === 'https://github.com' && !url.username && !url.password && !url.search && !url.hash
17
+ const name = url.pathname.match(/^\/([a-z0-9-]+)\/([a-z0-9_.-]+)\/?$/i)?.slice(1).join('/').replace(/\.git$/i, '')
18
+ requireValue(origin && name && !name.endsWith('/') && !name.endsWith('/.'), '请输入 GitHub 仓库首页地址,例如 https://github.com/owner/repo。')
19
+ return { id: hash(name.toLowerCase()), name, url: `https://github.com/${name}` }
20
+ }
21
+
22
+ async function cloneRepository(url, checkout, signal) {
23
+ const options = {
24
+ signal, timeout: 45_000, maxBuffer: 512 * 1024, windowsHide: true,
25
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: devNull,
26
+ GIT_ALLOW_PROTOCOL: 'https', GIT_LFS_SKIP_SMUDGE: '1' },
27
+ }
28
+ try {
29
+ await git('git', ['clone', '--quiet', '--depth=1', '--no-tags', '--no-recurse-submodules', '--', url, checkout], options)
30
+ const { stdout } = await git('git', ['-C', checkout, 'rev-parse', 'HEAD'], options)
31
+ requireValue(/^[a-f\d]{40,64}$/.test(stdout.trim()), '无法读取仓库提交版本。')
32
+ return stdout.trim()
33
+ } catch (error) {
34
+ signal.throwIfAborted()
35
+ if (error.code === 'ENOENT') throw new RequestError('请先安装 Git,再刷新 Skill 仓库。', 409)
36
+ if (error instanceof RequestError) throw error
37
+ throw new RequestError('无法下载仓库。请检查 GitHub 地址、网络和仓库访问权限。', 502)
38
+ }
39
+ }
40
+
41
+ export function skillRepositories(profileDir, readSkill, parseSkill, clone = cloneRepository) {
42
+ const root = path.join(profileDir, 'powertools-skill-repositories')
43
+ const catalog = path.join(root, 'repositories.json')
44
+ const snapshotPath = name => {
45
+ requireValue(typeof name === 'string' && /^checkout-[a-z0-9]+$/i.test(name), '仓库缓存记录无效。', 409)
46
+ return path.join(root, name)
47
+ }
48
+
49
+ async function registry() {
50
+ try {
51
+ const entries = JSON.parse(await readFile(catalog, 'utf8'))
52
+ requireValue(Array.isArray(entries) && entries.every(entry => entry?.snapshot && Array.isArray(entry.skills)), '仓库配置无效。')
53
+ for (const entry of entries) snapshotPath(entry.snapshot)
54
+ return entries
55
+ }
56
+ catch (error) {
57
+ if (error.code === 'ENOENT') return []
58
+ throw new RequestError('Skill 仓库配置无法读取。', 502)
59
+ }
60
+ }
61
+
62
+ async function save(entries) {
63
+ const temporary = path.join(root, `.${randomUUID()}.tmp`)
64
+ try {
65
+ await writeFile(temporary, JSON.stringify(entries, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
66
+ await rename(temporary, catalog)
67
+ } finally { await rm(temporary, { force: true }) }
68
+ }
69
+
70
+ async function scan(checkout, signal) {
71
+ const skills = []
72
+ let visited = 0
73
+ const directories = [checkout]
74
+ while (directories.length) {
75
+ signal.throwIfAborted()
76
+ const folder = directories.pop()
77
+ if (++visited > 12_000 || skills.length >= 250) throw new RequestError('仓库过大,请添加范围更小的 Skill 仓库。', 422)
78
+ const marker = await statOrMissing(path.join(folder, 'SKILL.md'))
79
+ if (marker?.isFile() && marker.size <= 512 * 1024) {
80
+ try {
81
+ const { text } = await readSkill(path.join(folder, 'SKILL.md'))
82
+ const { data } = parseSkill(text)
83
+ const relative = path.relative(checkout, folder).split(path.sep).join('/')
84
+ skills.push({ id: hash(relative), relative, name: data.name, description: data.description })
85
+ continue
86
+ } catch (error) {
87
+ if (!(error instanceof RequestError)) throw error
88
+ }
89
+ }
90
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
91
+ if (entry.isDirectory() && !entry.name.startsWith('.')) directories.push(path.join(folder, entry.name))
92
+ }
93
+ }
94
+ return skills.sort((a, b) => a.name.localeCompare(b.name) || a.relative.localeCompare(b.relative))
95
+ }
96
+
97
+ function publicRepository({ snapshot, skills, ...info }) {
98
+ return { ...info, skills: skills.map(({ relative, ...skill }) => skill) }
99
+ }
100
+
101
+ async function sync(entries, repository, previous, signal) {
102
+ await mkdir(root, { recursive: true, mode: 0o700 })
103
+ const snapshot = await mkdtemp(path.join(root, 'checkout-'))
104
+ try {
105
+ const commit = await clone(`${repository.url}.git`, path.join(snapshot, 'source'), signal)
106
+ const skills = await scan(path.join(snapshot, 'source'), signal)
107
+ signal.throwIfAborted()
108
+ const next = { ...repository, commit, checkedAt: Date.now(), snapshot: path.basename(snapshot), skills }
109
+ const updated = previous ? entries.map(entry => entry.id === repository.id ? next : entry) : [...entries, next]
110
+ await save(updated)
111
+ if (previous) await rm(snapshotPath(previous.snapshot), { recursive: true, force: true }).catch(() => {})
112
+ return { repository: publicRepository(next) }
113
+ } catch (error) {
114
+ await rm(snapshot, { recursive: true, force: true }).catch(() => {})
115
+ throw error
116
+ }
117
+ }
118
+
119
+ return async (body, signal) => {
120
+ const entries = await registry()
121
+ if (body.action === 'repository-list') return { repositories: entries.map(publicRepository) }
122
+ if (body.action === 'repository-add') {
123
+ const repository = githubRepository(body.url)
124
+ requireValue(!entries.some(entry => entry.id === repository.id), '此仓库已经添加。', 409)
125
+ return sync(entries, repository, null, signal)
126
+ }
127
+ const entry = entries.find(candidate => candidate.id === body.repositoryId)
128
+ requireValue(entry, '仓库已移除,请刷新列表。', 404)
129
+ if (body.action === 'repository-refresh') {
130
+ return sync(entries, githubRepository(entry.url), entry, signal)
131
+ }
132
+ if (body.action === 'repository-remove') {
133
+ requireValue(body.confirm === entry.id, '请确认要移除的仓库。')
134
+ await save(entries.filter(candidate => candidate.id !== entry.id))
135
+ await rm(snapshotPath(entry.snapshot), { recursive: true, force: true }).catch(() => {})
136
+ return {}
137
+ }
138
+ requireValue(entry.commit === body.commit, '仓库已刷新,请重新打开 Skill。', 409)
139
+ const skill = entry.skills.find(item => item.id === body.skillId)
140
+ requireValue(skill, '仓库中没有找到该 Skill。', 404)
141
+ const checkout = path.join(snapshotPath(entry.snapshot), 'source')
142
+ requireValue(await confinedPath(root, checkout), '无法验证仓库缓存目录。', 409)
143
+ const directory = path.resolve(checkout, skill.relative)
144
+ requireValue(directory === checkout || await confinedPath(checkout, directory), '无法打开仓库中的 Skill 目录。', 409)
145
+ if (body.action === 'repository-preview') {
146
+ const { text } = await readSkill(path.join(directory, 'SKILL.md'))
147
+ return { markdown: text }
148
+ }
149
+ requireValue(body.action === 'repository-install', '仓库操作无效。')
150
+ return { directory }
151
+ }
152
+ }