dsh-powertools 0.0.0-stage → 0.2.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 (251) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/client.js +2179 -0
  4. package/cordis.patch.yml +3 -0
  5. package/icon.svg +9 -0
  6. package/index.js +79 -0
  7. package/lib/enhance.js +159 -0
  8. package/lib/errors.js +11 -0
  9. package/lib/mcp.js +124 -0
  10. package/lib/platform.js +70 -0
  11. package/lib/sessions.js +377 -0
  12. package/lib/skill-repositories.js +152 -0
  13. package/lib/skills.js +280 -0
  14. package/licenses/lucide.txt +43 -0
  15. package/licenses/magi-code.txt +203 -0
  16. package/locale/en.json +1 -0
  17. package/locale/zh.json +1 -0
  18. package/node_modules/yaml/LICENSE +13 -0
  19. package/node_modules/yaml/README.md +172 -0
  20. package/node_modules/yaml/bin.mjs +11 -0
  21. package/node_modules/yaml/browser/dist/compose/compose-collection.js +88 -0
  22. package/node_modules/yaml/browser/dist/compose/compose-doc.js +43 -0
  23. package/node_modules/yaml/browser/dist/compose/compose-node.js +109 -0
  24. package/node_modules/yaml/browser/dist/compose/compose-scalar.js +86 -0
  25. package/node_modules/yaml/browser/dist/compose/composer.js +219 -0
  26. package/node_modules/yaml/browser/dist/compose/resolve-block-map.js +115 -0
  27. package/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +198 -0
  28. package/node_modules/yaml/browser/dist/compose/resolve-block-seq.js +49 -0
  29. package/node_modules/yaml/browser/dist/compose/resolve-end.js +37 -0
  30. package/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +207 -0
  31. package/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +226 -0
  32. package/node_modules/yaml/browser/dist/compose/resolve-props.js +146 -0
  33. package/node_modules/yaml/browser/dist/compose/util-contains-newline.js +34 -0
  34. package/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +26 -0
  35. package/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +15 -0
  36. package/node_modules/yaml/browser/dist/compose/util-map-includes.js +13 -0
  37. package/node_modules/yaml/browser/dist/doc/Document.js +335 -0
  38. package/node_modules/yaml/browser/dist/doc/anchors.js +71 -0
  39. package/node_modules/yaml/browser/dist/doc/applyReviver.js +55 -0
  40. package/node_modules/yaml/browser/dist/doc/createNode.js +88 -0
  41. package/node_modules/yaml/browser/dist/doc/directives.js +176 -0
  42. package/node_modules/yaml/browser/dist/errors.js +57 -0
  43. package/node_modules/yaml/browser/dist/index.js +17 -0
  44. package/node_modules/yaml/browser/dist/log.js +11 -0
  45. package/node_modules/yaml/browser/dist/nodes/Alias.js +118 -0
  46. package/node_modules/yaml/browser/dist/nodes/Collection.js +147 -0
  47. package/node_modules/yaml/browser/dist/nodes/Node.js +38 -0
  48. package/node_modules/yaml/browser/dist/nodes/Pair.js +36 -0
  49. package/node_modules/yaml/browser/dist/nodes/Scalar.js +24 -0
  50. package/node_modules/yaml/browser/dist/nodes/YAMLMap.js +144 -0
  51. package/node_modules/yaml/browser/dist/nodes/YAMLSeq.js +113 -0
  52. package/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +63 -0
  53. package/node_modules/yaml/browser/dist/nodes/identity.js +36 -0
  54. package/node_modules/yaml/browser/dist/nodes/toJS.js +37 -0
  55. package/node_modules/yaml/browser/dist/parse/cst-scalar.js +214 -0
  56. package/node_modules/yaml/browser/dist/parse/cst-stringify.js +61 -0
  57. package/node_modules/yaml/browser/dist/parse/cst-visit.js +97 -0
  58. package/node_modules/yaml/browser/dist/parse/cst.js +98 -0
  59. package/node_modules/yaml/browser/dist/parse/lexer.js +721 -0
  60. package/node_modules/yaml/browser/dist/parse/line-counter.js +39 -0
  61. package/node_modules/yaml/browser/dist/parse/parser.js +975 -0
  62. package/node_modules/yaml/browser/dist/public-api.js +102 -0
  63. package/node_modules/yaml/browser/dist/schema/Schema.js +37 -0
  64. package/node_modules/yaml/browser/dist/schema/common/map.js +17 -0
  65. package/node_modules/yaml/browser/dist/schema/common/null.js +15 -0
  66. package/node_modules/yaml/browser/dist/schema/common/seq.js +17 -0
  67. package/node_modules/yaml/browser/dist/schema/common/string.js +14 -0
  68. package/node_modules/yaml/browser/dist/schema/core/bool.js +19 -0
  69. package/node_modules/yaml/browser/dist/schema/core/float.js +43 -0
  70. package/node_modules/yaml/browser/dist/schema/core/int.js +38 -0
  71. package/node_modules/yaml/browser/dist/schema/core/schema.js +23 -0
  72. package/node_modules/yaml/browser/dist/schema/json/schema.js +62 -0
  73. package/node_modules/yaml/browser/dist/schema/tags.js +96 -0
  74. package/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +58 -0
  75. package/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +26 -0
  76. package/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +46 -0
  77. package/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +71 -0
  78. package/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +67 -0
  79. package/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +74 -0
  80. package/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +78 -0
  81. package/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +39 -0
  82. package/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +93 -0
  83. package/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +101 -0
  84. package/node_modules/yaml/browser/dist/stringify/foldFlowLines.js +146 -0
  85. package/node_modules/yaml/browser/dist/stringify/stringify.js +129 -0
  86. package/node_modules/yaml/browser/dist/stringify/stringifyCollection.js +153 -0
  87. package/node_modules/yaml/browser/dist/stringify/stringifyComment.js +20 -0
  88. package/node_modules/yaml/browser/dist/stringify/stringifyDocument.js +85 -0
  89. package/node_modules/yaml/browser/dist/stringify/stringifyNumber.js +25 -0
  90. package/node_modules/yaml/browser/dist/stringify/stringifyPair.js +150 -0
  91. package/node_modules/yaml/browser/dist/stringify/stringifyString.js +336 -0
  92. package/node_modules/yaml/browser/dist/util.js +11 -0
  93. package/node_modules/yaml/browser/dist/visit.js +233 -0
  94. package/node_modules/yaml/browser/index.js +5 -0
  95. package/node_modules/yaml/browser/package.json +3 -0
  96. package/node_modules/yaml/dist/cli.d.ts +8 -0
  97. package/node_modules/yaml/dist/cli.mjs +201 -0
  98. package/node_modules/yaml/dist/compose/compose-collection.d.ts +11 -0
  99. package/node_modules/yaml/dist/compose/compose-collection.js +90 -0
  100. package/node_modules/yaml/dist/compose/compose-doc.d.ts +7 -0
  101. package/node_modules/yaml/dist/compose/compose-doc.js +45 -0
  102. package/node_modules/yaml/dist/compose/compose-node.d.ts +29 -0
  103. package/node_modules/yaml/dist/compose/compose-node.js +112 -0
  104. package/node_modules/yaml/dist/compose/compose-scalar.d.ts +5 -0
  105. package/node_modules/yaml/dist/compose/compose-scalar.js +88 -0
  106. package/node_modules/yaml/dist/compose/composer.d.ts +63 -0
  107. package/node_modules/yaml/dist/compose/composer.js +224 -0
  108. package/node_modules/yaml/dist/compose/resolve-block-map.d.ts +6 -0
  109. package/node_modules/yaml/dist/compose/resolve-block-map.js +117 -0
  110. package/node_modules/yaml/dist/compose/resolve-block-scalar.d.ts +11 -0
  111. package/node_modules/yaml/dist/compose/resolve-block-scalar.js +200 -0
  112. package/node_modules/yaml/dist/compose/resolve-block-seq.d.ts +6 -0
  113. package/node_modules/yaml/dist/compose/resolve-block-seq.js +51 -0
  114. package/node_modules/yaml/dist/compose/resolve-end.d.ts +6 -0
  115. package/node_modules/yaml/dist/compose/resolve-end.js +39 -0
  116. package/node_modules/yaml/dist/compose/resolve-flow-collection.d.ts +7 -0
  117. package/node_modules/yaml/dist/compose/resolve-flow-collection.js +209 -0
  118. package/node_modules/yaml/dist/compose/resolve-flow-scalar.d.ts +10 -0
  119. package/node_modules/yaml/dist/compose/resolve-flow-scalar.js +228 -0
  120. package/node_modules/yaml/dist/compose/resolve-props.d.ts +23 -0
  121. package/node_modules/yaml/dist/compose/resolve-props.js +148 -0
  122. package/node_modules/yaml/dist/compose/util-contains-newline.d.ts +2 -0
  123. package/node_modules/yaml/dist/compose/util-contains-newline.js +36 -0
  124. package/node_modules/yaml/dist/compose/util-empty-scalar-position.d.ts +2 -0
  125. package/node_modules/yaml/dist/compose/util-empty-scalar-position.js +28 -0
  126. package/node_modules/yaml/dist/compose/util-flow-indent-check.d.ts +3 -0
  127. package/node_modules/yaml/dist/compose/util-flow-indent-check.js +17 -0
  128. package/node_modules/yaml/dist/compose/util-map-includes.d.ts +4 -0
  129. package/node_modules/yaml/dist/compose/util-map-includes.js +15 -0
  130. package/node_modules/yaml/dist/doc/Document.d.ts +141 -0
  131. package/node_modules/yaml/dist/doc/Document.js +337 -0
  132. package/node_modules/yaml/dist/doc/anchors.d.ts +24 -0
  133. package/node_modules/yaml/dist/doc/anchors.js +76 -0
  134. package/node_modules/yaml/dist/doc/applyReviver.d.ts +9 -0
  135. package/node_modules/yaml/dist/doc/applyReviver.js +57 -0
  136. package/node_modules/yaml/dist/doc/createNode.d.ts +17 -0
  137. package/node_modules/yaml/dist/doc/createNode.js +90 -0
  138. package/node_modules/yaml/dist/doc/directives.d.ts +49 -0
  139. package/node_modules/yaml/dist/doc/directives.js +178 -0
  140. package/node_modules/yaml/dist/errors.d.ts +21 -0
  141. package/node_modules/yaml/dist/errors.js +62 -0
  142. package/node_modules/yaml/dist/index.d.ts +25 -0
  143. package/node_modules/yaml/dist/index.js +50 -0
  144. package/node_modules/yaml/dist/log.d.ts +3 -0
  145. package/node_modules/yaml/dist/log.js +19 -0
  146. package/node_modules/yaml/dist/nodes/Alias.d.ts +29 -0
  147. package/node_modules/yaml/dist/nodes/Alias.js +120 -0
  148. package/node_modules/yaml/dist/nodes/Collection.d.ts +73 -0
  149. package/node_modules/yaml/dist/nodes/Collection.js +151 -0
  150. package/node_modules/yaml/dist/nodes/Node.d.ts +53 -0
  151. package/node_modules/yaml/dist/nodes/Node.js +40 -0
  152. package/node_modules/yaml/dist/nodes/Pair.d.ts +22 -0
  153. package/node_modules/yaml/dist/nodes/Pair.js +39 -0
  154. package/node_modules/yaml/dist/nodes/Scalar.d.ts +47 -0
  155. package/node_modules/yaml/dist/nodes/Scalar.js +27 -0
  156. package/node_modules/yaml/dist/nodes/YAMLMap.d.ts +53 -0
  157. package/node_modules/yaml/dist/nodes/YAMLMap.js +147 -0
  158. package/node_modules/yaml/dist/nodes/YAMLSeq.d.ts +60 -0
  159. package/node_modules/yaml/dist/nodes/YAMLSeq.js +115 -0
  160. package/node_modules/yaml/dist/nodes/addPairToJSMap.d.ts +4 -0
  161. package/node_modules/yaml/dist/nodes/addPairToJSMap.js +65 -0
  162. package/node_modules/yaml/dist/nodes/identity.d.ts +23 -0
  163. package/node_modules/yaml/dist/nodes/identity.js +53 -0
  164. package/node_modules/yaml/dist/nodes/toJS.d.ts +29 -0
  165. package/node_modules/yaml/dist/nodes/toJS.js +39 -0
  166. package/node_modules/yaml/dist/options.d.ts +350 -0
  167. package/node_modules/yaml/dist/parse/cst-scalar.d.ts +64 -0
  168. package/node_modules/yaml/dist/parse/cst-scalar.js +218 -0
  169. package/node_modules/yaml/dist/parse/cst-stringify.d.ts +8 -0
  170. package/node_modules/yaml/dist/parse/cst-stringify.js +63 -0
  171. package/node_modules/yaml/dist/parse/cst-visit.d.ts +39 -0
  172. package/node_modules/yaml/dist/parse/cst-visit.js +99 -0
  173. package/node_modules/yaml/dist/parse/cst.d.ts +109 -0
  174. package/node_modules/yaml/dist/parse/cst.js +112 -0
  175. package/node_modules/yaml/dist/parse/lexer.d.ts +87 -0
  176. package/node_modules/yaml/dist/parse/lexer.js +723 -0
  177. package/node_modules/yaml/dist/parse/line-counter.d.ts +22 -0
  178. package/node_modules/yaml/dist/parse/line-counter.js +41 -0
  179. package/node_modules/yaml/dist/parse/parser.d.ts +84 -0
  180. package/node_modules/yaml/dist/parse/parser.js +980 -0
  181. package/node_modules/yaml/dist/public-api.d.ts +44 -0
  182. package/node_modules/yaml/dist/public-api.js +107 -0
  183. package/node_modules/yaml/dist/schema/Schema.d.ts +17 -0
  184. package/node_modules/yaml/dist/schema/Schema.js +39 -0
  185. package/node_modules/yaml/dist/schema/common/map.d.ts +2 -0
  186. package/node_modules/yaml/dist/schema/common/map.js +19 -0
  187. package/node_modules/yaml/dist/schema/common/null.d.ts +4 -0
  188. package/node_modules/yaml/dist/schema/common/null.js +17 -0
  189. package/node_modules/yaml/dist/schema/common/seq.d.ts +2 -0
  190. package/node_modules/yaml/dist/schema/common/seq.js +19 -0
  191. package/node_modules/yaml/dist/schema/common/string.d.ts +2 -0
  192. package/node_modules/yaml/dist/schema/common/string.js +16 -0
  193. package/node_modules/yaml/dist/schema/core/bool.d.ts +4 -0
  194. package/node_modules/yaml/dist/schema/core/bool.js +21 -0
  195. package/node_modules/yaml/dist/schema/core/float.d.ts +4 -0
  196. package/node_modules/yaml/dist/schema/core/float.js +47 -0
  197. package/node_modules/yaml/dist/schema/core/int.d.ts +4 -0
  198. package/node_modules/yaml/dist/schema/core/int.js +42 -0
  199. package/node_modules/yaml/dist/schema/core/schema.d.ts +1 -0
  200. package/node_modules/yaml/dist/schema/core/schema.js +25 -0
  201. package/node_modules/yaml/dist/schema/json/schema.d.ts +2 -0
  202. package/node_modules/yaml/dist/schema/json/schema.js +64 -0
  203. package/node_modules/yaml/dist/schema/json-schema.d.ts +69 -0
  204. package/node_modules/yaml/dist/schema/tags.d.ts +48 -0
  205. package/node_modules/yaml/dist/schema/tags.js +99 -0
  206. package/node_modules/yaml/dist/schema/types.d.ts +92 -0
  207. package/node_modules/yaml/dist/schema/yaml-1.1/binary.d.ts +2 -0
  208. package/node_modules/yaml/dist/schema/yaml-1.1/binary.js +70 -0
  209. package/node_modules/yaml/dist/schema/yaml-1.1/bool.d.ts +7 -0
  210. package/node_modules/yaml/dist/schema/yaml-1.1/bool.js +29 -0
  211. package/node_modules/yaml/dist/schema/yaml-1.1/float.d.ts +4 -0
  212. package/node_modules/yaml/dist/schema/yaml-1.1/float.js +50 -0
  213. package/node_modules/yaml/dist/schema/yaml-1.1/int.d.ts +5 -0
  214. package/node_modules/yaml/dist/schema/yaml-1.1/int.js +76 -0
  215. package/node_modules/yaml/dist/schema/yaml-1.1/merge.d.ts +9 -0
  216. package/node_modules/yaml/dist/schema/yaml-1.1/merge.js +71 -0
  217. package/node_modules/yaml/dist/schema/yaml-1.1/omap.d.ts +22 -0
  218. package/node_modules/yaml/dist/schema/yaml-1.1/omap.js +77 -0
  219. package/node_modules/yaml/dist/schema/yaml-1.1/pairs.d.ts +10 -0
  220. package/node_modules/yaml/dist/schema/yaml-1.1/pairs.js +82 -0
  221. package/node_modules/yaml/dist/schema/yaml-1.1/schema.d.ts +1 -0
  222. package/node_modules/yaml/dist/schema/yaml-1.1/schema.js +41 -0
  223. package/node_modules/yaml/dist/schema/yaml-1.1/set.d.ts +28 -0
  224. package/node_modules/yaml/dist/schema/yaml-1.1/set.js +96 -0
  225. package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.d.ts +6 -0
  226. package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +105 -0
  227. package/node_modules/yaml/dist/stringify/foldFlowLines.d.ts +34 -0
  228. package/node_modules/yaml/dist/stringify/foldFlowLines.js +151 -0
  229. package/node_modules/yaml/dist/stringify/stringify.d.ts +21 -0
  230. package/node_modules/yaml/dist/stringify/stringify.js +132 -0
  231. package/node_modules/yaml/dist/stringify/stringifyCollection.d.ts +17 -0
  232. package/node_modules/yaml/dist/stringify/stringifyCollection.js +155 -0
  233. package/node_modules/yaml/dist/stringify/stringifyComment.d.ts +10 -0
  234. package/node_modules/yaml/dist/stringify/stringifyComment.js +24 -0
  235. package/node_modules/yaml/dist/stringify/stringifyDocument.d.ts +4 -0
  236. package/node_modules/yaml/dist/stringify/stringifyDocument.js +87 -0
  237. package/node_modules/yaml/dist/stringify/stringifyNumber.d.ts +2 -0
  238. package/node_modules/yaml/dist/stringify/stringifyNumber.js +27 -0
  239. package/node_modules/yaml/dist/stringify/stringifyPair.d.ts +3 -0
  240. package/node_modules/yaml/dist/stringify/stringifyPair.js +152 -0
  241. package/node_modules/yaml/dist/stringify/stringifyString.d.ts +9 -0
  242. package/node_modules/yaml/dist/stringify/stringifyString.js +338 -0
  243. package/node_modules/yaml/dist/test-events.d.ts +4 -0
  244. package/node_modules/yaml/dist/test-events.js +134 -0
  245. package/node_modules/yaml/dist/util.d.ts +16 -0
  246. package/node_modules/yaml/dist/util.js +28 -0
  247. package/node_modules/yaml/dist/visit.d.ts +102 -0
  248. package/node_modules/yaml/dist/visit.js +236 -0
  249. package/node_modules/yaml/package.json +97 -0
  250. package/node_modules/yaml/util.js +2 -0
  251. package/package.json +73 -4
@@ -0,0 +1,377 @@
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
+
86
+ const wsBySession = new Map()
87
+ for (const ws of workspaces) {
88
+ for (const id of ws.sessionIds ?? []) {
89
+ const list = wsBySession.get(id) ?? []
90
+ list.push({ workspaceId: ws.workspaceId, title: ws.title, path: ws.path })
91
+ wsBySession.set(id, list)
92
+ }
93
+ }
94
+
95
+ const byId = new Map()
96
+ for (const snap of persisted) {
97
+ const header = snap.header
98
+ if (!header?.id) continue
99
+ byId.set(header.id, {
100
+ id: header.id,
101
+ createdAt: header.createdAt ?? 0,
102
+ cwd: header.cwd ?? '',
103
+ parentSessionId: header.parentSession ?? null,
104
+ isSubagent: header.origin === 'subagent',
105
+ isFork: Boolean(header.parentSession && header.origin !== 'subagent'),
106
+ delegationDepth: header.delegationDepth ?? null,
107
+ agentPreset: header.agentPreset ?? null,
108
+ persisted: true,
109
+ resident: false,
110
+ running: false,
111
+ archived: archivedSet.has(header.id),
112
+ sizeBytes: snap.sizeBytes ?? null,
113
+ eventCount: snap.eventCount ?? null,
114
+ location: snap.location ?? null,
115
+ formatStatus: snap.formatStatus ?? null,
116
+ workspaces: wsBySession.get(header.id) ?? [],
117
+ })
118
+ }
119
+
120
+ for (const session of liveSessions) {
121
+ const header = session?.header
122
+ if (!header?.id) continue
123
+ const agent = ctx.agents?.get?.(header.id)
124
+ const existing = byId.get(header.id)
125
+ const running = agent?.status === 'running'
126
+ byId.set(header.id, {
127
+ id: header.id,
128
+ createdAt: header.createdAt ?? existing?.createdAt ?? 0,
129
+ cwd: header.cwd ?? existing?.cwd ?? '',
130
+ parentSessionId: header.parentSession ?? existing?.parentSessionId ?? null,
131
+ isSubagent: header.origin === 'subagent' || Boolean(existing?.isSubagent),
132
+ isFork: Boolean((header.parentSession ?? existing?.parentSessionId) && header.origin !== 'subagent'),
133
+ delegationDepth: header.delegationDepth ?? existing?.delegationDepth ?? null,
134
+ agentPreset: header.agentPreset ?? existing?.agentPreset ?? null,
135
+ persisted: Boolean(existing?.persisted),
136
+ resident: true,
137
+ running,
138
+ archived: archivedSet.has(header.id),
139
+ sizeBytes: existing?.sizeBytes ?? null,
140
+ eventCount: existing?.eventCount ?? null,
141
+ location: existing?.location ?? null,
142
+ formatStatus: existing?.formatStatus ?? 'current',
143
+ workspaces: wsBySession.get(header.id) ?? existing?.workspaces ?? [],
144
+ })
145
+ }
146
+
147
+ const items = [...byId.values()]
148
+ const { subagentChildren, collectDescendants, rootAncestor } = buildLineage(items)
149
+
150
+ return items.map(item => {
151
+ const descendantIds = collectDescendants(item.id)
152
+ const directSubagentIds = subagentChildren.get(item.id) ?? []
153
+ const rootId = rootAncestor(item)
154
+ const orphanSubagent = item.isSubagent && (!item.parentSessionId || !byId.has(item.parentSessionId))
155
+ const cascadeIds = [item.id, ...descendantIds]
156
+ let deletable = true
157
+ let deleteReason = ''
158
+
159
+ for (const targetId of cascadeIds) {
160
+ const target = byId.get(targetId)
161
+ if (!target) continue
162
+ if (target.running) {
163
+ deletable = false
164
+ deleteReason = target.id === item.id ? '会话正在运行中,请先停止后再删除。' : '关联子 Agent 正在运行中,请先停止后再删除。'
165
+ break
166
+ }
167
+ if (target.resident) {
168
+ deletable = false
169
+ deleteReason = target.id === item.id
170
+ ? '会话正由当前 DSH 进程打开持有,请关闭或重启 DSH 释放句柄后再删除。'
171
+ : '关联子 Agent 正由当前 DSH 进程持有,请等待结束或重启 DSH 后再删除。'
172
+ break
173
+ }
174
+ if (target.location?.kind !== 'jsonl' || !target.location?.path) {
175
+ deletable = false
176
+ deleteReason = '当前会话或关联子 Agent 未落盘为 JSONL 单会话目录(如 SQLite 后端),暂不支持安全删除。'
177
+ break
178
+ }
179
+ }
180
+
181
+ return {
182
+ id: item.id,
183
+ createdAt: item.createdAt,
184
+ cwd: item.cwd,
185
+ parentSessionId: item.parentSessionId,
186
+ rootSessionId: rootId,
187
+ isSubagent: item.isSubagent,
188
+ isFork: item.isFork,
189
+ orphanSubagent,
190
+ delegationDepth: item.delegationDepth,
191
+ agentPreset: item.agentPreset,
192
+ persisted: item.persisted,
193
+ resident: item.resident,
194
+ running: item.running,
195
+ archived: item.archived,
196
+ sizeBytes: item.sizeBytes,
197
+ eventCount: item.eventCount,
198
+ backendKind: item.location?.kind ?? (item.persisted ? 'unknown' : 'pending'),
199
+ workspaces: item.workspaces.map(({ workspaceId, title }) => ({ workspaceId, title })),
200
+ directSubagentIds,
201
+ descendantSubagentIds: descendantIds,
202
+ deletable,
203
+ deleteReason: deleteReason || undefined,
204
+ _location: item.location,
205
+ }
206
+ })
207
+ }
208
+
209
+ export function sessionOperations(ctx) {
210
+ let tail = Promise.resolve()
211
+
212
+ async function list(signal) {
213
+ const rows = await collectAllSessions(ctx, signal)
214
+ return {
215
+ sessions: rows.map(({ _location, ...publicRow }) => publicRow),
216
+ }
217
+ }
218
+
219
+ async function executeDelete(requestedIds, singleRootId, signal) {
220
+ const all = await collectAllSessions(ctx, signal)
221
+ const byId = new Map(all.map(row => [row.id, row]))
222
+ const roots = []
223
+ for (const sessionId of requestedIds) {
224
+ const root = byId.get(sessionId)
225
+ requireValue(root, requestedIds.length === 1 ? '目标会话不存在或已被移除,请刷新列表。' : `目标会话(${sessionId})不存在或已被移除,请刷新列表。`, 404)
226
+ roots.push(root)
227
+ }
228
+
229
+ const targetIdSet = new Set()
230
+ for (const root of roots) {
231
+ targetIdSet.add(root.id)
232
+ for (const subId of root.descendantSubagentIds) {
233
+ if (byId.has(subId)) targetIdSet.add(subId)
234
+ }
235
+ }
236
+ const targets = [...targetIdSet].map(id => byId.get(id)).filter(Boolean)
237
+ const requestedSet = new Set(requestedIds)
238
+ const workspaces = typeof ctx.workspaceRegistry?.list === 'function' ? ctx.workspaceRegistry.list() : []
239
+ const workspacePaths = workspaces.map(ws => ws.path).filter(Boolean)
240
+
241
+ // Phase 1: Validate every target & acquire write ownership atomically (sorted to prevent lock ordering issues).
242
+ const sortedTargets = [...targets].sort((a, b) => a.id.localeCompare(b.id))
243
+ const handles = []
244
+ const validated = []
245
+ try {
246
+ for (const target of sortedTargets) {
247
+ signal.throwIfAborted()
248
+ const isDirect = requestedSet.has(target.id)
249
+ if (target.running || ctx.agents?.get?.(target.id)?.status === 'running') {
250
+ throw new RequestError(isDirect && singleRootId
251
+ ? '会话正在运行中,请先停止后再删除。'
252
+ : `${isDirect ? '会话' : '关联子 Agent'}(${target.id})正在运行中,请先停止后再删除。`, 409)
253
+ }
254
+ if (target.resident || ctx.sessions?.get?.(target.id) || ctx.agents?.get?.(target.id)) {
255
+ throw new RequestError(isDirect && singleRootId
256
+ ? '会话正由当前 DSH 进程打开持有,请切换或重启 DSH 释放写句柄后再删除。'
257
+ : `${isDirect ? '会话' : '关联子 Agent'}(${target.id})正由当前 DSH 进程持有,请等待释放或重启 DSH 后再删除。`, 409)
258
+ }
259
+ const check = await validateJsonlSessionDirectory(target._location, workspacePaths)
260
+ if (!check.ok) throw new RequestError(check.reason, 409)
261
+ let handle
262
+ try {
263
+ handle = await ctx.sessionPersistence.open(target.id, 'write', { signal })
264
+ } catch (error) {
265
+ if (error?.name === 'SessionAlreadyOwnedError') {
266
+ throw new RequestError(`会话 ${target.id} 正在被其他进程或句柄写入,已拒绝删除。`, 409)
267
+ }
268
+ if (error?.name === 'SessionPersistenceNotFoundError') {
269
+ throw new RequestError(`会话 ${target.id} 已不存在,请刷新列表。`, 404)
270
+ }
271
+ throw error
272
+ }
273
+ handles.push(handle)
274
+ validated.push({ target, dir: check.dir, file: check.file })
275
+ }
276
+ } finally {
277
+ // Release all write leases before moving directories (required on Windows and clean on macOS).
278
+ for (const handle of handles.reverse()) {
279
+ await handle.close().catch(() => {})
280
+ }
281
+ }
282
+
283
+ signal.throwIfAborted()
284
+
285
+ // Phase 2: Move all session directories into a single recoverable batch folder (rollback on partial error).
286
+ const profileDir = ctx.profileContext?.dir
287
+ requireValue(typeof profileDir === 'string' && path.isAbsolute(profileDir), '无法定位 Profile 可恢复目录。', 503)
288
+ const recoveryRoot = path.join(profileDir, 'powertools-session-recovery')
289
+ await mkdir(recoveryRoot, { recursive: true, mode: 0o700 })
290
+ const batchDir = await mkdtemp(path.join(recoveryRoot, 'deleted-'))
291
+ const padWidth = Math.max(2, String(validated.length).length)
292
+ const moved = []
293
+ try {
294
+ for (let index = 0; index < validated.length; index++) {
295
+ const entry = validated[index]
296
+ const folderName = `${String(index + 1).padStart(padWidth, '0')}-${path.basename(entry.dir)}`
297
+ const destination = path.join(batchDir, folderName)
298
+ await moveLocal(entry.dir, destination)
299
+ moved.push({
300
+ id: entry.target.id,
301
+ isSubagent: entry.target.isSubagent,
302
+ parentSessionId: entry.target.parentSessionId,
303
+ sourceDir: entry.dir,
304
+ recoveredDir: destination,
305
+ })
306
+ }
307
+ const manifestPayload = {
308
+ deletedAt: Date.now(),
309
+ ...(singleRootId ? { rootSessionId: singleRootId } : {}),
310
+ rootSessionIds: requestedIds,
311
+ items: moved,
312
+ }
313
+ await writeFile(
314
+ path.join(batchDir, 'manifest.json'),
315
+ JSON.stringify(manifestPayload, null, 2) + '\n',
316
+ { mode: 0o600 },
317
+ )
318
+ } catch (error) {
319
+ for (const item of moved.reverse()) {
320
+ await moveLocal(item.recoveredDir, item.sourceDir).catch(() => {})
321
+ }
322
+ await rm(batchDir, { recursive: true, force: true }).catch(() => {})
323
+ throw error
324
+ }
325
+
326
+ // Phase 3: Best-effort cleanup of archive/pin registry entries so deleted IDs don't linger.
327
+ for (const item of moved) {
328
+ if (typeof ctx.workspaceRegistry?.unarchiveSession === 'function') {
329
+ await ctx.workspaceRegistry.unarchiveSession(item.id).catch(() => {})
330
+ }
331
+ if (typeof ctx.workspaceRegistry?.unpinSession === 'function') {
332
+ await ctx.workspaceRegistry.unpinSession(item.id).catch(() => {})
333
+ }
334
+ }
335
+
336
+ return {
337
+ deletedIds: moved.map(item => item.id),
338
+ requestedCount: requestedIds.length,
339
+ subagentCount: singleRootId
340
+ ? moved.filter(item => item.id !== singleRootId).length
341
+ : moved.filter(item => item.isSubagent).length,
342
+ cascadedCount: moved.filter(item => !requestedSet.has(item.id)).length,
343
+ recovery: batchDir,
344
+ }
345
+ }
346
+
347
+ async function remove(body, signal) {
348
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
349
+ requireValue(sessionId, '请指定要删除的会话 ID。')
350
+ requireValue(body.confirm === sessionId, '请确认要删除的目标会话。', 409)
351
+ return executeDelete([sessionId], sessionId, signal)
352
+ }
353
+
354
+ async function batchRemove(body, signal) {
355
+ requireValue(Array.isArray(body.sessionIds) && body.sessionIds.length > 0, '请至少选择一条要删除的会话。')
356
+ requireValue(body.sessionIds.length <= 500, '单次批量删除最多支持 500 条会话,请分批处理。')
357
+ requireValue(body.confirm === true, '请确认批量删除的目标会话。', 409)
358
+ const uniqueIds = [...new Set(body.sessionIds.map(id => typeof id === 'string' ? id.trim() : '').filter(Boolean))]
359
+ requireValue(uniqueIds.length === body.sessionIds.length, '批量删除列表中包含无效或重复的会话 ID。')
360
+ return executeDelete(uniqueIds, null, signal)
361
+ }
362
+
363
+ return (body, signal) => {
364
+ if (body.action === 'list') return list(signal)
365
+ if (body.action === 'delete') {
366
+ const pending = tail.then(() => remove(body, signal))
367
+ tail = pending.catch(() => {})
368
+ return pending
369
+ }
370
+ if (body.action === 'batch-delete') {
371
+ const pending = tail.then(() => batchRemove(body, signal))
372
+ tail = pending.catch(() => {})
373
+ return pending
374
+ }
375
+ throw new RequestError('会话操作无效。')
376
+ }
377
+ }
@@ -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
+ }