@kingsleyasher/dsh-knowledge-base 0.0.0-stage → 3.1.4

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 (516) hide show
  1. package/ARCHITECTURE.en.md +35 -0
  2. package/ARCHITECTURE.md +40 -0
  3. package/BETA4.md +31 -0
  4. package/BETA7.md +35 -0
  5. package/BETA8.md +39 -0
  6. package/BETA9.md +38 -0
  7. package/CONTRIBUTING.md +5 -0
  8. package/DEVELOPMENT.en.md +26 -0
  9. package/DEVELOPMENT.md +27 -0
  10. package/EXISTING-FRAMEWORK-OPTIMIZATION.md +101 -0
  11. package/LICENSE +21 -0
  12. package/MONOREPO.md +34 -0
  13. package/NPM-EDITION.md +9 -0
  14. package/PARSING-PREVIEW.md +84 -0
  15. package/PERFORMANCE.md +43 -0
  16. package/PRIVACY.md +7 -0
  17. package/PROJECT-RECORD.en.md +778 -0
  18. package/PROJECT-RECORD.md +789 -0
  19. package/README.md +109 -3
  20. package/README.zh-CN.md +117 -0
  21. package/RELEASE.en.md +559 -0
  22. package/RELEASE.md +570 -0
  23. package/RETRIEVAL.md +93 -0
  24. package/SECURITY.md +7 -0
  25. package/THIRD-PARTY-NOTICES.md +5 -0
  26. package/VERSIONING.en.md +51 -0
  27. package/VERSIONING.md +50 -0
  28. package/WORKBENCH.en.md +201 -0
  29. package/WORKBENCH.md +195 -0
  30. package/browser-extension/background.js +146 -0
  31. package/browser-extension/icons/knowledge-base-128.png +0 -0
  32. package/browser-extension/icons/knowledge-base-16.png +0 -0
  33. package/browser-extension/icons/knowledge-base-32.png +0 -0
  34. package/browser-extension/icons/knowledge-base-48.png +0 -0
  35. package/browser-extension/manifest.json +25 -0
  36. package/browser-extension/options.html +22 -0
  37. package/browser-extension/options.js +41 -0
  38. package/browser-extension/popup.html +17 -0
  39. package/browser-extension/popup.js +58 -0
  40. package/browser-extension/style.css +11 -0
  41. package/cordis.patch.yml +88 -0
  42. package/docs/LEGACY-246-BOOTSTRAP.md +21 -0
  43. package/docs/LIBRARY-FRAMEWORK-MIGRATION.md +45 -0
  44. package/docs/ORIGINAL-FILE-INDEX-ARCHITECTURE.md +43 -0
  45. package/docs/TODO-LIFECYCLE-VALIDATION.md +42 -0
  46. package/docs/UPDATE-RECOVERY.en.md +18 -0
  47. package/docs/UPDATE-RECOVERY.md +70 -0
  48. package/docs/WINDOWS-SIGNING.md +30 -0
  49. package/docs/client/ARCHITECTURE.en.md +17 -0
  50. package/docs/client/ARCHITECTURE.md +17 -0
  51. package/docs/client/CONTRIBUTING.md +5 -0
  52. package/docs/client/CROSS-VOLUME-TRASH.md +13 -0
  53. package/docs/client/DEVELOPMENT.en.md +33 -0
  54. package/docs/client/DEVELOPMENT.md +33 -0
  55. package/docs/client/EXISTING-FRAMEWORK-OPTIMIZATION.md +3 -0
  56. package/docs/client/PERFORMANCE.md +3 -0
  57. package/docs/client/PRIVACY.md +7 -0
  58. package/docs/client/PROJECT-RECORD.en.md +199 -0
  59. package/docs/client/PROJECT-RECORD.md +219 -0
  60. package/docs/client/README.md +55 -0
  61. package/docs/client/README.zh-CN.md +45 -0
  62. package/docs/client/RELEASE.en.md +148 -0
  63. package/docs/client/RELEASE.md +149 -0
  64. package/docs/client/RETRIEVAL.md +3 -0
  65. package/docs/client/SECURITY.md +7 -0
  66. package/docs/client/THIRD-PARTY-NOTICES.md +5 -0
  67. package/docs/client/VERSIONING.en.md +9 -0
  68. package/docs/client/VERSIONING.md +9 -0
  69. package/docs/client/WORKBENCH.en.md +24 -0
  70. package/docs/client/WORKBENCH.md +24 -0
  71. package/docs/client/skills/personal-knowledge-base/SKILL.md +38 -0
  72. package/docs/releases/client-1.0.1.md +32 -0
  73. package/docs/releases/client-1.0.2.md +32 -0
  74. package/docs/releases/client-1.0.3.md +31 -0
  75. package/docs/releases/client-1.1.1.md +28 -0
  76. package/docs/releases/client-1.1.2.md +16 -0
  77. package/docs/releases/client-1.1.4.md +7 -0
  78. package/docs/releases/client-2.0.0.en.md +13 -0
  79. package/docs/releases/client-2.0.0.md +13 -0
  80. package/docs/releases/client-2.0.1.en.md +10 -0
  81. package/docs/releases/client-2.0.1.md +10 -0
  82. package/docs/releases/client-2.0.3.en.md +8 -0
  83. package/docs/releases/client-2.0.3.md +8 -0
  84. package/docs/releases/plugin-2.4.1.md +24 -0
  85. package/docs/releases/plugin-2.4.10.md +22 -0
  86. package/docs/releases/plugin-2.4.11.md +14 -0
  87. package/docs/releases/plugin-2.4.12.md +14 -0
  88. package/docs/releases/plugin-2.4.13.md +27 -0
  89. package/docs/releases/plugin-2.4.14.md +18 -0
  90. package/docs/releases/plugin-2.4.2.md +31 -0
  91. package/docs/releases/plugin-2.4.3.md +25 -0
  92. package/docs/releases/plugin-2.4.4.md +31 -0
  93. package/docs/releases/plugin-2.4.5.md +23 -0
  94. package/docs/releases/plugin-2.4.6.md +23 -0
  95. package/docs/releases/plugin-2.4.7.md +14 -0
  96. package/docs/releases/plugin-2.4.8.md +14 -0
  97. package/docs/releases/plugin-2.4.9.md +18 -0
  98. package/docs/releases/plugin-2.5.10.md +11 -0
  99. package/docs/releases/plugin-2.5.13.en.md +11 -0
  100. package/docs/releases/plugin-2.5.13.md +11 -0
  101. package/docs/releases/plugin-2.5.3.md +28 -0
  102. package/docs/releases/plugin-2.5.4.md +14 -0
  103. package/docs/releases/plugin-2.5.5.md +16 -0
  104. package/docs/releases/plugin-2.5.6.md +3 -0
  105. package/docs/releases/plugin-2.5.7.md +7 -0
  106. package/docs/releases/plugin-2.5.8.md +7 -0
  107. package/docs/releases/plugin-2.5.9.md +7 -0
  108. package/docs/releases/plugin-3.0.0.en.md +13 -0
  109. package/docs/releases/plugin-3.0.0.md +13 -0
  110. package/docs/releases/plugin-3.0.1.en.md +10 -0
  111. package/docs/releases/plugin-3.0.1.md +10 -0
  112. package/docs/releases/plugin-3.1.3.en.md +11 -0
  113. package/docs/releases/plugin-3.1.3.md +11 -0
  114. package/docs/validation/windows-auto-update-2.4.13.md +31 -0
  115. package/docs/validation/windows-direct-246-to-2413.md +32 -0
  116. package/package.json +78 -6
  117. package/packages/kb-contracts/desktop.js +29 -0
  118. package/packages/kb-contracts/index.js +132 -0
  119. package/packages/kb-contracts/node.js +3 -0
  120. package/packages/kb-contracts/package.json +17 -0
  121. package/packages/kb-contracts/schema.js +42 -0
  122. package/packages/kb-contracts/tools.js +1 -0
  123. package/packages/kb-contracts/version-policy.js +45 -0
  124. package/packages/kb-core/index.js +9 -0
  125. package/packages/kb-core/package.json +15 -0
  126. package/packages/kb-core/src/capture-surface.js +22 -0
  127. package/packages/kb-core/src/documents.js +105 -0
  128. package/packages/kb-core/src/embedded.js +29 -0
  129. package/packages/kb-core/src/file-catalog.js +151 -0
  130. package/packages/kb-core/src/file-classification.js +60 -0
  131. package/packages/kb-core/src/flow-workspace.js +66 -0
  132. package/packages/kb-core/src/flows.js +1136 -0
  133. package/packages/kb-core/src/fsindex.js +293 -0
  134. package/packages/kb-core/src/import-service.js +486 -0
  135. package/packages/kb-core/src/importer.js +909 -0
  136. package/packages/kb-core/src/inbox-flow.js +2 -0
  137. package/packages/kb-core/src/index-architecture.js +48 -0
  138. package/packages/kb-core/src/index-maintenance.js +81 -0
  139. package/packages/kb-core/src/index-policy-service.js +191 -0
  140. package/packages/kb-core/src/index-policy.js +121 -0
  141. package/packages/kb-core/src/kbcore.js +2519 -0
  142. package/packages/kb-core/src/library-framework.js +186 -0
  143. package/packages/kb-core/src/library-state.js +68 -0
  144. package/packages/kb-core/src/managed-files.js +69 -0
  145. package/packages/kb-core/src/map.js +171 -0
  146. package/packages/kb-core/src/parse-credentials.js +49 -0
  147. package/packages/kb-core/src/parse-discovery.js +119 -0
  148. package/packages/kb-core/src/parse-job-storage.js +40 -0
  149. package/packages/kb-core/src/parse-native.js +87 -0
  150. package/packages/kb-core/src/parse-presets.js +46 -0
  151. package/packages/kb-core/src/parse-source-authority.js +72 -0
  152. package/packages/kb-core/src/parsing.js +2307 -0
  153. package/packages/kb-core/src/relation-name-lookup.js +43 -0
  154. package/packages/kb-core/src/retrieval-api.js +79 -0
  155. package/packages/kb-core/src/retrieval-cache.js +22 -0
  156. package/packages/kb-core/src/retrieval-chunks.js +128 -0
  157. package/packages/kb-core/src/retrieval-pool.js +102 -0
  158. package/packages/kb-core/src/retrieval-worker.js +190 -0
  159. package/packages/kb-core/src/retrieval.js +618 -0
  160. package/packages/kb-core/src/runtime-resources.js +73 -0
  161. package/packages/kb-core/src/service-ownership.js +18 -0
  162. package/packages/kb-core/src/source-references.js +61 -0
  163. package/packages/kb-core/src/storage-io.js +121 -0
  164. package/packages/kb-core/src/system-upgrades.js +104 -0
  165. package/packages/kb-core/src/workbench-backup.js +219 -0
  166. package/packages/kb-core/src/workbench-deliverables.js +73 -0
  167. package/packages/kb-core/src/workbench-files.js +25 -0
  168. package/packages/kb-core/src/workbench-inbox.js +57 -0
  169. package/packages/kb-core/src/workbench-links.js +236 -0
  170. package/packages/kb-core/src/workbench-question.js +131 -0
  171. package/packages/kb-core/src/workbench-relation-index.js +110 -0
  172. package/packages/kb-core/src/workbench-state.js +102 -0
  173. package/packages/kb-core/src/workbench-trash.js +213 -0
  174. package/packages/kb-core/src/workbench.js +936 -0
  175. package/packages/kb-service/auth.js +39 -0
  176. package/packages/kb-service/build.js +18 -0
  177. package/packages/kb-service/cli.js +26 -0
  178. package/packages/kb-service/client.js +64 -0
  179. package/packages/kb-service/clipper.js +15 -0
  180. package/packages/kb-service/compatibility.js +34 -0
  181. package/packages/kb-service/desktop-files.js +514 -0
  182. package/packages/kb-service/desktop-host-links.js +39 -0
  183. package/packages/kb-service/dsh-broker.js +64 -0
  184. package/packages/kb-service/dsh-host.js +168 -0
  185. package/packages/kb-service/dsh-stream-relay.js +32 -0
  186. package/packages/kb-service/engines.js +32 -0
  187. package/packages/kb-service/extension.js +8 -0
  188. package/packages/kb-service/first-library-handoff.js +28 -0
  189. package/packages/kb-service/handoff-api.js +22 -0
  190. package/packages/kb-service/host-adapter.js +151 -0
  191. package/packages/kb-service/host-assets.js +9 -0
  192. package/packages/kb-service/host-python.js +30 -0
  193. package/packages/kb-service/host-updates.js +11 -0
  194. package/packages/kb-service/inbox-host.js +47 -0
  195. package/packages/kb-service/inbox-jobs.js +54 -0
  196. package/packages/kb-service/index.js +3 -0
  197. package/packages/kb-service/io.js +24 -0
  198. package/packages/kb-service/launch-lock.js +27 -0
  199. package/packages/kb-service/launcher.js +18 -0
  200. package/packages/kb-service/legacy-handoff.js +27 -0
  201. package/packages/kb-service/legacy-ports.js +18 -0
  202. package/packages/kb-service/main.js +13 -0
  203. package/packages/kb-service/memory-channel.js +57 -0
  204. package/packages/kb-service/memory-sync.js +42 -0
  205. package/packages/kb-service/migration.js +131 -0
  206. package/packages/kb-service/native.py +216 -0
  207. package/packages/kb-service/operations.js +19 -0
  208. package/packages/kb-service/package.json +1 -0
  209. package/packages/kb-service/runtime.js +185 -0
  210. package/packages/kb-service/safe-update.js +104 -0
  211. package/packages/kb-service/service.js +494 -0
  212. package/packages/kb-service/tool-definitions.json +934 -0
  213. package/packages/kb-service/tool-router.js +45 -0
  214. package/packages/kb-service/vector-profiles.js +41 -0
  215. package/presets/01-knowledge-agent.patch.yml +347 -0
  216. package/runtime/python/LICENSE.txt +676 -0
  217. package/runtime/python/_asyncio.pyd +0 -0
  218. package/runtime/python/_bz2.pyd +0 -0
  219. package/runtime/python/_ctypes.pyd +0 -0
  220. package/runtime/python/_decimal.pyd +0 -0
  221. package/runtime/python/_elementtree.pyd +0 -0
  222. package/runtime/python/_hashlib.pyd +0 -0
  223. package/runtime/python/_lzma.pyd +0 -0
  224. package/runtime/python/_multiprocessing.pyd +0 -0
  225. package/runtime/python/_overlapped.pyd +0 -0
  226. package/runtime/python/_queue.pyd +0 -0
  227. package/runtime/python/_remote_debugging.pyd +0 -0
  228. package/runtime/python/_socket.pyd +0 -0
  229. package/runtime/python/_sqlite3.pyd +0 -0
  230. package/runtime/python/_ssl.pyd +0 -0
  231. package/runtime/python/_uuid.pyd +0 -0
  232. package/runtime/python/_wmi.pyd +0 -0
  233. package/runtime/python/_zoneinfo.pyd +0 -0
  234. package/runtime/python/_zstd.pyd +0 -0
  235. package/runtime/python/libcrypto-3.dll +0 -0
  236. package/runtime/python/libffi-8.dll +0 -0
  237. package/runtime/python/libssl-3.dll +0 -0
  238. package/runtime/python/libtommath.dll +0 -0
  239. package/runtime/python/pyexpat.pyd +0 -0
  240. package/runtime/python/python.cat +0 -0
  241. package/runtime/python/python.exe +0 -0
  242. package/runtime/python/python3.dll +0 -0
  243. package/runtime/python/python314._pth +5 -0
  244. package/runtime/python/python314.dll +0 -0
  245. package/runtime/python/python314.zip +0 -0
  246. package/runtime/python/pythonw.exe +0 -0
  247. package/runtime/python/select.pyd +0 -0
  248. package/runtime/python/sqlite3.dll +0 -0
  249. package/runtime/python/unicodedata.pyd +0 -0
  250. package/runtime/python/vcruntime140.dll +0 -0
  251. package/runtime/python/vcruntime140_1.dll +0 -0
  252. package/runtime/python/winsound.pyd +0 -0
  253. package/skills/personal-knowledge-base/SKILL.md +38 -0
  254. package/src/client/capture-icon-192.png +0 -0
  255. package/src/client/capture-icon-512.png +0 -0
  256. package/src/client/capture-icon.svg +12 -0
  257. package/src/client/capture-sw.js +10 -0
  258. package/src/client/capture.css +1 -0
  259. package/src/client/capture.html +1 -0
  260. package/src/client/capture.js +37 -0
  261. package/src/client/capture.webmanifest +1 -0
  262. package/src/client/inbox-organize-bridge.js +22 -0
  263. package/src/client/index.js +4980 -0
  264. package/src/client/knowledge-ui.css +255 -0
  265. package/src/client/pdfjs/LICENSE +177 -0
  266. package/src/client/pdfjs/cmaps/78-EUC-H.bcmap +0 -0
  267. package/src/client/pdfjs/cmaps/78-EUC-V.bcmap +0 -0
  268. package/src/client/pdfjs/cmaps/78-H.bcmap +0 -0
  269. package/src/client/pdfjs/cmaps/78-RKSJ-H.bcmap +0 -0
  270. package/src/client/pdfjs/cmaps/78-RKSJ-V.bcmap +0 -0
  271. package/src/client/pdfjs/cmaps/78-V.bcmap +0 -0
  272. package/src/client/pdfjs/cmaps/78ms-RKSJ-H.bcmap +0 -0
  273. package/src/client/pdfjs/cmaps/78ms-RKSJ-V.bcmap +0 -0
  274. package/src/client/pdfjs/cmaps/83pv-RKSJ-H.bcmap +0 -0
  275. package/src/client/pdfjs/cmaps/90ms-RKSJ-H.bcmap +0 -0
  276. package/src/client/pdfjs/cmaps/90ms-RKSJ-V.bcmap +0 -0
  277. package/src/client/pdfjs/cmaps/90msp-RKSJ-H.bcmap +0 -0
  278. package/src/client/pdfjs/cmaps/90msp-RKSJ-V.bcmap +0 -0
  279. package/src/client/pdfjs/cmaps/90pv-RKSJ-H.bcmap +0 -0
  280. package/src/client/pdfjs/cmaps/90pv-RKSJ-V.bcmap +0 -0
  281. package/src/client/pdfjs/cmaps/Add-H.bcmap +0 -0
  282. package/src/client/pdfjs/cmaps/Add-RKSJ-H.bcmap +0 -0
  283. package/src/client/pdfjs/cmaps/Add-RKSJ-V.bcmap +0 -0
  284. package/src/client/pdfjs/cmaps/Add-V.bcmap +0 -0
  285. package/src/client/pdfjs/cmaps/Adobe-CNS1-0.bcmap +0 -0
  286. package/src/client/pdfjs/cmaps/Adobe-CNS1-1.bcmap +0 -0
  287. package/src/client/pdfjs/cmaps/Adobe-CNS1-2.bcmap +0 -0
  288. package/src/client/pdfjs/cmaps/Adobe-CNS1-3.bcmap +0 -0
  289. package/src/client/pdfjs/cmaps/Adobe-CNS1-4.bcmap +0 -0
  290. package/src/client/pdfjs/cmaps/Adobe-CNS1-5.bcmap +0 -0
  291. package/src/client/pdfjs/cmaps/Adobe-CNS1-6.bcmap +0 -0
  292. package/src/client/pdfjs/cmaps/Adobe-CNS1-UCS2.bcmap +0 -0
  293. package/src/client/pdfjs/cmaps/Adobe-GB1-0.bcmap +0 -0
  294. package/src/client/pdfjs/cmaps/Adobe-GB1-1.bcmap +0 -0
  295. package/src/client/pdfjs/cmaps/Adobe-GB1-2.bcmap +0 -0
  296. package/src/client/pdfjs/cmaps/Adobe-GB1-3.bcmap +0 -0
  297. package/src/client/pdfjs/cmaps/Adobe-GB1-4.bcmap +0 -0
  298. package/src/client/pdfjs/cmaps/Adobe-GB1-5.bcmap +0 -0
  299. package/src/client/pdfjs/cmaps/Adobe-GB1-UCS2.bcmap +0 -0
  300. package/src/client/pdfjs/cmaps/Adobe-Japan1-0.bcmap +0 -0
  301. package/src/client/pdfjs/cmaps/Adobe-Japan1-1.bcmap +0 -0
  302. package/src/client/pdfjs/cmaps/Adobe-Japan1-2.bcmap +0 -0
  303. package/src/client/pdfjs/cmaps/Adobe-Japan1-3.bcmap +0 -0
  304. package/src/client/pdfjs/cmaps/Adobe-Japan1-4.bcmap +0 -0
  305. package/src/client/pdfjs/cmaps/Adobe-Japan1-5.bcmap +0 -0
  306. package/src/client/pdfjs/cmaps/Adobe-Japan1-6.bcmap +0 -0
  307. package/src/client/pdfjs/cmaps/Adobe-Japan1-UCS2.bcmap +0 -0
  308. package/src/client/pdfjs/cmaps/Adobe-Korea1-0.bcmap +0 -0
  309. package/src/client/pdfjs/cmaps/Adobe-Korea1-1.bcmap +0 -0
  310. package/src/client/pdfjs/cmaps/Adobe-Korea1-2.bcmap +0 -0
  311. package/src/client/pdfjs/cmaps/Adobe-Korea1-UCS2.bcmap +0 -0
  312. package/src/client/pdfjs/cmaps/B5-H.bcmap +0 -0
  313. package/src/client/pdfjs/cmaps/B5-V.bcmap +0 -0
  314. package/src/client/pdfjs/cmaps/B5pc-H.bcmap +0 -0
  315. package/src/client/pdfjs/cmaps/B5pc-V.bcmap +0 -0
  316. package/src/client/pdfjs/cmaps/CNS-EUC-H.bcmap +0 -0
  317. package/src/client/pdfjs/cmaps/CNS-EUC-V.bcmap +0 -0
  318. package/src/client/pdfjs/cmaps/CNS1-H.bcmap +0 -0
  319. package/src/client/pdfjs/cmaps/CNS1-V.bcmap +0 -0
  320. package/src/client/pdfjs/cmaps/CNS2-H.bcmap +0 -0
  321. package/src/client/pdfjs/cmaps/CNS2-V.bcmap +3 -0
  322. package/src/client/pdfjs/cmaps/ETHK-B5-H.bcmap +0 -0
  323. package/src/client/pdfjs/cmaps/ETHK-B5-V.bcmap +0 -0
  324. package/src/client/pdfjs/cmaps/ETen-B5-H.bcmap +0 -0
  325. package/src/client/pdfjs/cmaps/ETen-B5-V.bcmap +0 -0
  326. package/src/client/pdfjs/cmaps/ETenms-B5-H.bcmap +3 -0
  327. package/src/client/pdfjs/cmaps/ETenms-B5-V.bcmap +0 -0
  328. package/src/client/pdfjs/cmaps/EUC-H.bcmap +0 -0
  329. package/src/client/pdfjs/cmaps/EUC-V.bcmap +0 -0
  330. package/src/client/pdfjs/cmaps/Ext-H.bcmap +0 -0
  331. package/src/client/pdfjs/cmaps/Ext-RKSJ-H.bcmap +0 -0
  332. package/src/client/pdfjs/cmaps/Ext-RKSJ-V.bcmap +0 -0
  333. package/src/client/pdfjs/cmaps/Ext-V.bcmap +0 -0
  334. package/src/client/pdfjs/cmaps/GB-EUC-H.bcmap +0 -0
  335. package/src/client/pdfjs/cmaps/GB-EUC-V.bcmap +0 -0
  336. package/src/client/pdfjs/cmaps/GB-H.bcmap +4 -0
  337. package/src/client/pdfjs/cmaps/GB-V.bcmap +0 -0
  338. package/src/client/pdfjs/cmaps/GBK-EUC-H.bcmap +0 -0
  339. package/src/client/pdfjs/cmaps/GBK-EUC-V.bcmap +0 -0
  340. package/src/client/pdfjs/cmaps/GBK2K-H.bcmap +0 -0
  341. package/src/client/pdfjs/cmaps/GBK2K-V.bcmap +0 -0
  342. package/src/client/pdfjs/cmaps/GBKp-EUC-H.bcmap +0 -0
  343. package/src/client/pdfjs/cmaps/GBKp-EUC-V.bcmap +0 -0
  344. package/src/client/pdfjs/cmaps/GBT-EUC-H.bcmap +0 -0
  345. package/src/client/pdfjs/cmaps/GBT-EUC-V.bcmap +0 -0
  346. package/src/client/pdfjs/cmaps/GBT-H.bcmap +0 -0
  347. package/src/client/pdfjs/cmaps/GBT-V.bcmap +0 -0
  348. package/src/client/pdfjs/cmaps/GBTpc-EUC-H.bcmap +0 -0
  349. package/src/client/pdfjs/cmaps/GBTpc-EUC-V.bcmap +0 -0
  350. package/src/client/pdfjs/cmaps/GBpc-EUC-H.bcmap +0 -0
  351. package/src/client/pdfjs/cmaps/GBpc-EUC-V.bcmap +0 -0
  352. package/src/client/pdfjs/cmaps/H.bcmap +0 -0
  353. package/src/client/pdfjs/cmaps/HKdla-B5-H.bcmap +0 -0
  354. package/src/client/pdfjs/cmaps/HKdla-B5-V.bcmap +0 -0
  355. package/src/client/pdfjs/cmaps/HKdlb-B5-H.bcmap +0 -0
  356. package/src/client/pdfjs/cmaps/HKdlb-B5-V.bcmap +0 -0
  357. package/src/client/pdfjs/cmaps/HKgccs-B5-H.bcmap +0 -0
  358. package/src/client/pdfjs/cmaps/HKgccs-B5-V.bcmap +0 -0
  359. package/src/client/pdfjs/cmaps/HKm314-B5-H.bcmap +0 -0
  360. package/src/client/pdfjs/cmaps/HKm314-B5-V.bcmap +0 -0
  361. package/src/client/pdfjs/cmaps/HKm471-B5-H.bcmap +0 -0
  362. package/src/client/pdfjs/cmaps/HKm471-B5-V.bcmap +0 -0
  363. package/src/client/pdfjs/cmaps/HKscs-B5-H.bcmap +0 -0
  364. package/src/client/pdfjs/cmaps/HKscs-B5-V.bcmap +0 -0
  365. package/src/client/pdfjs/cmaps/Hankaku.bcmap +0 -0
  366. package/src/client/pdfjs/cmaps/Hiragana.bcmap +0 -0
  367. package/src/client/pdfjs/cmaps/KSC-EUC-H.bcmap +0 -0
  368. package/src/client/pdfjs/cmaps/KSC-EUC-V.bcmap +0 -0
  369. package/src/client/pdfjs/cmaps/KSC-H.bcmap +0 -0
  370. package/src/client/pdfjs/cmaps/KSC-Johab-H.bcmap +0 -0
  371. package/src/client/pdfjs/cmaps/KSC-Johab-V.bcmap +0 -0
  372. package/src/client/pdfjs/cmaps/KSC-V.bcmap +0 -0
  373. package/src/client/pdfjs/cmaps/KSCms-UHC-H.bcmap +0 -0
  374. package/src/client/pdfjs/cmaps/KSCms-UHC-HW-H.bcmap +0 -0
  375. package/src/client/pdfjs/cmaps/KSCms-UHC-HW-V.bcmap +0 -0
  376. package/src/client/pdfjs/cmaps/KSCms-UHC-V.bcmap +0 -0
  377. package/src/client/pdfjs/cmaps/KSCpc-EUC-H.bcmap +0 -0
  378. package/src/client/pdfjs/cmaps/KSCpc-EUC-V.bcmap +0 -0
  379. package/src/client/pdfjs/cmaps/Katakana.bcmap +0 -0
  380. package/src/client/pdfjs/cmaps/LICENSE +36 -0
  381. package/src/client/pdfjs/cmaps/NWP-H.bcmap +0 -0
  382. package/src/client/pdfjs/cmaps/NWP-V.bcmap +0 -0
  383. package/src/client/pdfjs/cmaps/RKSJ-H.bcmap +0 -0
  384. package/src/client/pdfjs/cmaps/RKSJ-V.bcmap +0 -0
  385. package/src/client/pdfjs/cmaps/Roman.bcmap +0 -0
  386. package/src/client/pdfjs/cmaps/UniCNS-UCS2-H.bcmap +0 -0
  387. package/src/client/pdfjs/cmaps/UniCNS-UCS2-V.bcmap +0 -0
  388. package/src/client/pdfjs/cmaps/UniCNS-UTF16-H.bcmap +0 -0
  389. package/src/client/pdfjs/cmaps/UniCNS-UTF16-V.bcmap +0 -0
  390. package/src/client/pdfjs/cmaps/UniCNS-UTF32-H.bcmap +0 -0
  391. package/src/client/pdfjs/cmaps/UniCNS-UTF32-V.bcmap +0 -0
  392. package/src/client/pdfjs/cmaps/UniCNS-UTF8-H.bcmap +0 -0
  393. package/src/client/pdfjs/cmaps/UniCNS-UTF8-V.bcmap +0 -0
  394. package/src/client/pdfjs/cmaps/UniGB-UCS2-H.bcmap +0 -0
  395. package/src/client/pdfjs/cmaps/UniGB-UCS2-V.bcmap +0 -0
  396. package/src/client/pdfjs/cmaps/UniGB-UTF16-H.bcmap +0 -0
  397. package/src/client/pdfjs/cmaps/UniGB-UTF16-V.bcmap +0 -0
  398. package/src/client/pdfjs/cmaps/UniGB-UTF32-H.bcmap +0 -0
  399. package/src/client/pdfjs/cmaps/UniGB-UTF32-V.bcmap +0 -0
  400. package/src/client/pdfjs/cmaps/UniGB-UTF8-H.bcmap +0 -0
  401. package/src/client/pdfjs/cmaps/UniGB-UTF8-V.bcmap +0 -0
  402. package/src/client/pdfjs/cmaps/UniJIS-UCS2-H.bcmap +0 -0
  403. package/src/client/pdfjs/cmaps/UniJIS-UCS2-HW-H.bcmap +0 -0
  404. package/src/client/pdfjs/cmaps/UniJIS-UCS2-HW-V.bcmap +0 -0
  405. package/src/client/pdfjs/cmaps/UniJIS-UCS2-V.bcmap +0 -0
  406. package/src/client/pdfjs/cmaps/UniJIS-UTF16-H.bcmap +0 -0
  407. package/src/client/pdfjs/cmaps/UniJIS-UTF16-V.bcmap +0 -0
  408. package/src/client/pdfjs/cmaps/UniJIS-UTF32-H.bcmap +0 -0
  409. package/src/client/pdfjs/cmaps/UniJIS-UTF32-V.bcmap +0 -0
  410. package/src/client/pdfjs/cmaps/UniJIS-UTF8-H.bcmap +0 -0
  411. package/src/client/pdfjs/cmaps/UniJIS-UTF8-V.bcmap +0 -0
  412. package/src/client/pdfjs/cmaps/UniJIS2004-UTF16-H.bcmap +0 -0
  413. package/src/client/pdfjs/cmaps/UniJIS2004-UTF16-V.bcmap +0 -0
  414. package/src/client/pdfjs/cmaps/UniJIS2004-UTF32-H.bcmap +0 -0
  415. package/src/client/pdfjs/cmaps/UniJIS2004-UTF32-V.bcmap +0 -0
  416. package/src/client/pdfjs/cmaps/UniJIS2004-UTF8-H.bcmap +0 -0
  417. package/src/client/pdfjs/cmaps/UniJIS2004-UTF8-V.bcmap +0 -0
  418. package/src/client/pdfjs/cmaps/UniJISPro-UCS2-HW-V.bcmap +0 -0
  419. package/src/client/pdfjs/cmaps/UniJISPro-UCS2-V.bcmap +0 -0
  420. package/src/client/pdfjs/cmaps/UniJISPro-UTF8-V.bcmap +0 -0
  421. package/src/client/pdfjs/cmaps/UniJISX0213-UTF32-H.bcmap +0 -0
  422. package/src/client/pdfjs/cmaps/UniJISX0213-UTF32-V.bcmap +0 -0
  423. package/src/client/pdfjs/cmaps/UniJISX02132004-UTF32-H.bcmap +0 -0
  424. package/src/client/pdfjs/cmaps/UniJISX02132004-UTF32-V.bcmap +0 -0
  425. package/src/client/pdfjs/cmaps/UniKS-UCS2-H.bcmap +0 -0
  426. package/src/client/pdfjs/cmaps/UniKS-UCS2-V.bcmap +0 -0
  427. package/src/client/pdfjs/cmaps/UniKS-UTF16-H.bcmap +0 -0
  428. package/src/client/pdfjs/cmaps/UniKS-UTF16-V.bcmap +0 -0
  429. package/src/client/pdfjs/cmaps/UniKS-UTF32-H.bcmap +0 -0
  430. package/src/client/pdfjs/cmaps/UniKS-UTF32-V.bcmap +0 -0
  431. package/src/client/pdfjs/cmaps/UniKS-UTF8-H.bcmap +0 -0
  432. package/src/client/pdfjs/cmaps/UniKS-UTF8-V.bcmap +0 -0
  433. package/src/client/pdfjs/cmaps/V.bcmap +0 -0
  434. package/src/client/pdfjs/cmaps/WP-Symbol.bcmap +0 -0
  435. package/src/client/pdfjs/pdf.mjs +26779 -0
  436. package/src/client/pdfjs/pdf.worker.mjs +63420 -0
  437. package/src/client/pdfjs/standard_fonts/FoxitDingbats.pfb +0 -0
  438. package/src/client/pdfjs/standard_fonts/FoxitFixed.pfb +0 -0
  439. package/src/client/pdfjs/standard_fonts/FoxitFixedBold.pfb +0 -0
  440. package/src/client/pdfjs/standard_fonts/FoxitFixedBoldItalic.pfb +0 -0
  441. package/src/client/pdfjs/standard_fonts/FoxitFixedItalic.pfb +0 -0
  442. package/src/client/pdfjs/standard_fonts/FoxitSerif.pfb +0 -0
  443. package/src/client/pdfjs/standard_fonts/FoxitSerifBold.pfb +0 -0
  444. package/src/client/pdfjs/standard_fonts/FoxitSerifBoldItalic.pfb +0 -0
  445. package/src/client/pdfjs/standard_fonts/FoxitSerifItalic.pfb +0 -0
  446. package/src/client/pdfjs/standard_fonts/FoxitSymbol.pfb +0 -0
  447. package/src/client/pdfjs/standard_fonts/LICENSE_FOXIT +27 -0
  448. package/src/client/pdfjs/standard_fonts/LICENSE_LIBERATION +102 -0
  449. package/src/client/pdfjs/standard_fonts/LiberationSans-Bold.ttf +0 -0
  450. package/src/client/pdfjs/standard_fonts/LiberationSans-BoldItalic.ttf +0 -0
  451. package/src/client/pdfjs/standard_fonts/LiberationSans-Italic.ttf +0 -0
  452. package/src/client/pdfjs/standard_fonts/LiberationSans-Regular.ttf +0 -0
  453. package/src/client/pdfjs/wasm/LICENSE_JBIG2 +196 -0
  454. package/src/client/pdfjs/wasm/LICENSE_OPENJPEG +39 -0
  455. package/src/client/pdfjs/wasm/LICENSE_PDFJS_JBIG2 +13 -0
  456. package/src/client/pdfjs/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
  457. package/src/client/pdfjs/wasm/LICENSE_PDFJS_QCMS +22 -0
  458. package/src/client/pdfjs/wasm/LICENSE_QCMS +21 -0
  459. package/src/client/pdfjs/wasm/jbig2.wasm +0 -0
  460. package/src/client/pdfjs/wasm/openjpeg.wasm +0 -0
  461. package/src/client/pdfjs/wasm/openjpeg_nowasm_fallback.js +17 -0
  462. package/src/client/pdfjs/wasm/qcms_bg.wasm +0 -0
  463. package/src/client/todo-lifecycle-ui.js +58 -0
  464. package/src/client/workbench-features.js +148 -0
  465. package/src/client/workbench-relations.js +86 -0
  466. package/src/client/workbench-theme.css +81 -0
  467. package/src/client/workbench-ui.js +1761 -0
  468. package/src/host/capture-surface.js +2 -0
  469. package/src/host/citation-guard.js +40 -0
  470. package/src/host/command-description.js +43 -0
  471. package/src/host/flow-workspace.js +62 -0
  472. package/src/host/flows.js +2 -0
  473. package/src/host/fsindex.js +2 -0
  474. package/src/host/gateway.js +916 -0
  475. package/src/host/import-service.js +2 -0
  476. package/src/host/importer.js +2 -0
  477. package/src/host/index-maintenance.js +2 -0
  478. package/src/host/index-policy-service.js +2 -0
  479. package/src/host/index-policy.js +2 -0
  480. package/src/host/index.js +2224 -0
  481. package/src/host/kbcore.js +2 -0
  482. package/src/host/managed-files.js +2 -0
  483. package/src/host/map.js +2 -0
  484. package/src/host/parse-credentials.js +2 -0
  485. package/src/host/parse-discovery.js +2 -0
  486. package/src/host/parse-native.js +2 -0
  487. package/src/host/parse-presets.js +2 -0
  488. package/src/host/parse-source-authority.js +2 -0
  489. package/src/host/parsing.js +7 -0
  490. package/src/host/relation-name-lookup.js +2 -0
  491. package/src/host/retrieval-api.js +2 -0
  492. package/src/host/retrieval-cache.js +2 -0
  493. package/src/host/retrieval-chunks.js +2 -0
  494. package/src/host/retrieval-pool.js +2 -0
  495. package/src/host/retrieval-worker.js +2 -0
  496. package/src/host/retrieval.js +2 -0
  497. package/src/host/runtime-resources.js +2 -0
  498. package/src/host/selftest.js +747 -0
  499. package/src/host/storage-io.js +2 -0
  500. package/src/host/system-upgrades.js +2 -0
  501. package/src/host/todo-lifecycle.js +66 -0
  502. package/src/host/updates.js +281 -0
  503. package/src/host/versioning.js +2 -0
  504. package/src/host/workbench-backup.js +2 -0
  505. package/src/host/workbench-deliverables.js +2 -0
  506. package/src/host/workbench-files.js +2 -0
  507. package/src/host/workbench-inbox.js +2 -0
  508. package/src/host/workbench-links.js +2 -0
  509. package/src/host/workbench-question.js +2 -0
  510. package/src/host/workbench-relation-index.js +2 -0
  511. package/src/host/workbench-state.js +2 -0
  512. package/src/host/workbench-trash.js +2 -0
  513. package/src/host/workbench.js +5 -0
  514. package/tools/kb-local-model.py +141 -0
  515. package/tools/kb-pdf-pages.py +78 -0
  516. package/tools/kb-transactional-update.py +284 -0
@@ -0,0 +1,514 @@
1
+
2
+ import path from 'node:path';
3
+ import {readFile,readdir,lstat,stat,realpath,mkdir,open,unlink,link,rename,rmdir,access,cp} from 'node:fs/promises';
4
+ import {constants} from 'node:fs';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {TextDecoder} from 'node:util';
7
+ import {safePath,relativePath,inside,locked} from '../kb-core/src/workbench-state.js';
8
+ import {fileRole} from '../kb-core/src/workbench-files.js';
9
+ import {DEFAULT_PRIVATE_DIRS} from '../kb-core/src/fsindex.js';
10
+ import {readIndexPolicy,policyExcluded,createPolicyMatcher,indexPolicySignature,savePolicy,policyFile} from '../kb-core/src/index-policy.js';
11
+ import {readCatalog,CATALOG_PATH} from '../kb-core/src/file-catalog.js';
12
+ import {createEmbeddedKernel} from '../kb-core/index.js';
13
+ import {atomic,readJson,hash,error} from './io.js';
14
+
15
+ const MAX_TEXT=512*1024,MAX_FILE=64*1024*1024,MAX_BACKUP=128*1024*1024;
16
+ const MAX_OFFICE=16*1024*1024,OFFICE=/\.(docx|xlsx)$/i,TEXT=/\.(md|mdx|markdown|txt|csv|json|ya?ml|[cm]?js|tsx?|jsx|py|css|s[ac]ss|html?|xml|log|c|cc|cpp|h|hpp|cs|java|rs|go|sh|ps1|toml|ini|sql|vue|svelte)$/i;
17
+ const decoder=new TextDecoder('utf-8',{fatal:true});
18
+ const mimeOf=p=>OFFICE.test(p)?(/\.docx$/i.test(p)?'application/vnd.openxmlformats-officedocument.wordprocessingml.document':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'):TEXT.test(p)?(/\.md$/i.test(p)?'text/markdown':'text/plain'):({pdf:'application/pdf',png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',svg:'image/svg+xml',webp:'image/webp',wav:'audio/wav',mp3:'audio/mpeg',mp4:'video/mp4',webm:'video/webm'})[p.split('.').at(-1).toLowerCase()]??'application/octet-stream';
19
+ const version=s=>'fs:'+hash([String(s.dev),String(s.ino),String(s.size),String(s.mtimeNs),String(s.ctimeNs)]);
20
+ const uuid=/^[a-f0-9-]{32,64}$/;
21
+ const osName=n=>{if(typeof n!=='string'||!n||/[<>:"|?*\x00-\x1f\\/]/.test(n)||/[. ]$/.test(n)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(n))throw error('BAD_REQUEST','文件名无效');return n.normalize('NFC');};
22
+ export async function createDesktopFiles({root,privateDir,desktopRoot,core,withLock,getPrivateDirs=()=>DEFAULT_PRIVATE_DIRS,getCatalog=()=>null,showPrivate=()=>false,candidateOnly=true}){
23
+ const sandbox=await realpath(desktopRoot),base=await realpath(root);
24
+ if(!inside(sandbox,base)||base===sandbox)throw error('FORBIDDEN','候选客户端只能访问隔离的虚构库');
25
+ const marker=await readJson(path.join(base,'.desktop-preview.json'),null);
26
+ if(candidateOnly&&(marker?.synthetic!==true||marker?.schemaVersion!==1))throw error('FORBIDDEN','缺少虚构库标记');
27
+ const storage=path.join(privateDir,'desktop');
28
+ await mkdir(storage,{recursive:true});
29
+ const plans=new Map(),resources=new Map(),stages=new Map();
30
+ let catalogSnapshot,catalogRows=new Map();
31
+ const records=()=>{const c=getCatalog();if(c!==catalogSnapshot){catalogSnapshot=c;catalogRows=new Map((c?.files??[]).map(f=>[f.path,f]));}return catalogRows;};
32
+ const localTrash=await safePath(base,'.kbmeta/desktop-trash',{missing:true});
33
+ async function trashDir(id,{create=false}={}){
34
+ if(!uuid.test(id??''))throw error('BAD_REQUEST','回收项目标识无效');
35
+ const local=await safePath(base,'.kbmeta/desktop-trash/'+id,{missing:true});
36
+ if(create){await mkdir(local,{recursive:true});return safePath(base,'.kbmeta/desktop-trash/'+id);}
37
+ if(await lstat(local).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))return local;
38
+ return safePath(privateDir,'desktop/trash/'+id,{missing:true});
39
+ }
40
+
41
+ const privatePath=p=>getPrivateDirs().some(v=>{const a=p.toLowerCase(),b=v.replaceAll('\\','/').toLowerCase();return a===b||a.startsWith(b+'/');});
42
+ let matcherCache={signature:null,matcher:null};
43
+ function policyMatcher(){
44
+ const signature=indexPolicySignature(base);
45
+ if(matcherCache.signature!==signature)matcherCache={signature,matcher:createPolicyMatcher(readIndexPolicy(base))};
46
+ return matcherCache.matcher;
47
+ }
48
+ async function checked(p,{missing=false,write=false}={}){
49
+ p=relativePath(p);
50
+ if(p.split('/').some(s=>s.startsWith('.')||['node_modules','索引层'].includes(s))||privatePath(p))throw error('FORBIDDEN','资料路径不在当前浏览授权范围内');
51
+ if(!showPrivate()&&records().get(p)?.private)throw error('FORBIDDEN','资料路径不在当前浏览授权范围内');
52
+ if(write&&(fileRole(p)!=='document'||/^(_模板|_手册)\//.test(p)))throw error('READ_ONLY','系统资料受保护');
53
+ return safePath(base,p,{missing});
54
+ }
55
+ async function info(p,matcher,absoluteOverride){
56
+ const absolute=absoluteOverride??await checked(p),s=await lstat(absolute,{bigint:true});
57
+ if(s.isSymbolicLink())throw error('LINK_DENIED','不允许通过目录链接访问资料');
58
+ if(!s.isFile()&&!s.isDirectory())throw error('READ_ONLY','仅支持普通文件和目录');
59
+ if(absoluteOverride&&!showPrivate()&&records().get(p)?.private)throw error('FORBIDDEN','资料路径不在当前浏览授权范围内');
60
+ let writable=Boolean(s.mode&0o222n);
61
+ // Windows reports the read-only attribute through the mode bits; the extra
62
+ // access() probes only repeat that check for every entry in a directory.
63
+ if(process.platform!=='win32')try{await access(absolute,constants.W_OK);await access(path.dirname(absolute),constants.W_OK);}catch{writable=false;}
64
+ const system=fileRole(p)!=='document'||/^(_模板|_手册)(\/|$)/.test(p);
65
+ const accessInfo={canBrowse:true,canEdit:s.isFile()&&(OFFICE.test(p)?s.size<=BigInt(MAX_OFFICE):TEXT.test(p)&&s.size<=BigInt(MAX_TEXT))&&writable&&!system,
66
+ canRename:writable&&!system,canMove:writable&&!system,canTrash:writable&&!system,canSendToModel:false,
67
+ indexExcluded:matcher?matcher.excluded(p):policyMatcher().excluded(p),reasons:system?['系统资料受保护']:!writable?['文件或目录只读']:s.size>BigInt(OFFICE.test(p)?MAX_OFFICE:MAX_TEXT)?['文件超过完整编辑上限']:[]};
68
+ const record=records().get(p),original=record?.status==='available'?record:null;
69
+ return {id:p,path:p,name:path.posix.basename(p),type:s.isDirectory()?'directory':'file',mime:s.isFile()?mimeOf(p):undefined,size:Number(s.size),modifiedAt:Number(s.mtimeMs),revision:version(s),access:accessInfo,protected:system,hasChildren:s.isDirectory(),...(original?{category:original.category,kind:original.kind,original:true}:{})};
70
+ }
71
+ const listCache=new Map(),LIST_CACHE_MS=15000,LIST_CACHE_MAX=64;
72
+ const dirSignature=async folder=>{const s=await lstat(folder,{bigint:true});return [String(s.dev),String(s.ino),String(s.mtimeNs),String(s.ctimeNs)].join(':')};
73
+ async function list(parent='',offset=0,limit=500,sort='name-asc'){
74
+ const folder=parent?await checked(parent):base,signature=await dirSignature(folder);
75
+ const cacheKey=parent+'|'+sort,catalog=getCatalog(),hint=[signature,indexPolicySignature(base),catalog?`${catalog.revision??0}:${catalog.policyRevision??0}`:'-',showPrivate()?'1':'0',getPrivateDirs().join('|')].join('#');
76
+ const cached=listCache.get(cacheKey);
77
+ if(cached?.hint===hint&&Date.now()-cached.at<LIST_CACHE_MS){
78
+ cached.at=Date.now();listCache.delete(cacheKey);listCache.set(cacheKey,cached);
79
+ return {items:cached.items.slice(offset,offset+limit),nextOffset:offset+limit<cached.items.length?offset+limit:undefined,total:cached.items.length};
80
+ }
81
+ const matcher=policyMatcher(),rows=[];
82
+ for(const e of await readdir(folder,{withFileTypes:true})){
83
+ const p=parent?parent+'/'+e.name:e.name;
84
+ if(e.name.startsWith('.')||e.isSymbolicLink()||privatePath(p)||['node_modules','索引层'].includes(e.name))continue;
85
+ try{rows.push(await info(p,matcher,path.join(folder,e.name)));}catch(e){if(!['FORBIDDEN','LINK_DENIED','EACCES','ENOENT'].includes(e.code))throw e;}
86
+ }
87
+ const nameOrder=(a,b)=>a.name.localeCompare(b.name,'zh-CN',{numeric:true});
88
+ rows.sort((a,b)=>(a.type===b.type?0:a.type==='directory'?-1:1)||(sort==='modified-desc'?b.modifiedAt-a.modifiedAt:sort==='modified-asc'?a.modifiedAt-b.modifiedAt:sort==='name-desc'?-nameOrder(a,b):nameOrder(a,b))||nameOrder(a,b));
89
+ if(rows.length<=3000){if(listCache.size>=LIST_CACHE_MAX)listCache.delete(listCache.keys().next().value);listCache.set(cacheKey,{hint,at:Date.now(),items:rows});}
90
+ return {items:rows.slice(offset,offset+limit),nextOffset:offset+limit<rows.length?offset+limit:undefined,total:rows.length};
91
+ }
92
+ async function walk(parent='',out=[],depth=0){
93
+ if(depth>20||out.length>5000)throw error('BAD_REQUEST','目录超过候选版枚举预算');
94
+ const page=await list(parent);
95
+ if(page.nextOffset!==undefined)throw error('BAD_REQUEST','单目录超过500项,缩小范围后操作');
96
+ for(const f of page.items){if(f.type==='directory')await walk(f.path,out,depth+1);else out.push(f);}
97
+ return out;
98
+ }
99
+ async function stable(p,max=MAX_FILE){
100
+ const absolute=await checked(p),before=await stat(absolute,{bigint:true});
101
+ if(!before.isFile()||before.size>BigInt(max))throw error('READ_ONLY','文件超过此次操作预算');
102
+ const data=await readFile(absolute),after=await stat(absolute,{bigint:true});
103
+ if(version(before)!==version(after)||data.length>max)throw error('CONFLICT','文件在读取时发生变化');
104
+ return {data,revision:version(after),absolute};
105
+ }
106
+ async function preview(p,caller){
107
+ const f=await info(p);if(f.type!=='file')return {file:f,kind:'unsupported'};
108
+ if(OFFICE.test(p)){
109
+ if(f.size>MAX_OFFICE)return {file:{...f,access:{...f.access,canEdit:false}},kind:'unsupported',readOnlyReason:'Office 文件超过候选版16MiB编辑预算'};
110
+ const original=await stable(p,MAX_OFFICE),key=hash([caller,p,original.revision]),folder=path.join(storage,'edit-originals');await mkdir(folder,{recursive:true});
111
+ if(!await readJson(path.join(folder,key+'.json'),null)){
112
+ let total=0;for(const name of await readdir(folder))if(name.endsWith('.bin'))total+=(await stat(path.join(folder,name))).size;
113
+ if(total+original.data.length>256*1024*1024)throw error('READ_ONLY','编辑原件缓存已达256MiB预算,请先处理已有草稿');
114
+ await atomic(path.join(folder,key+'.bin'),original.data);await atomic(path.join(folder,key+'.json'),{caller,path:p,file:{...f,size:original.data.length,revision:original.revision},sha256:hash(original.data)});
115
+ }
116
+ return editOriginal(p,key,caller);
117
+ }
118
+ const kind=f.mime==='application/pdf'?'pdf':f.mime?.startsWith('image/')?'image':f.mime?.startsWith('audio/')?'audio':f.mime?.startsWith('video/')?'video':f.mime==='text/markdown'?'markdown':f.mime==='text/plain'?'text':'unsupported';
119
+ if(['markdown','text'].includes(kind)){
120
+ if(f.size>MAX_TEXT)return {file:{...f,access:{...f.access,canEdit:false}},kind:'unsupported',readOnlyReason:'文件过大,未截断为可编辑文本'};
121
+ let data,bom;try{const raw=(await stable(p,MAX_TEXT)).data;data=decoder.decode(raw);bom=raw.subarray(0,3).equals(Buffer.from([239,187,191]));}catch(e){if(e.code)throw e;return {file:{...f,access:{...f.access,canEdit:false}},kind:'unsupported',readOnlyReason:'编码不是无损UTF-8'};}
122
+ return {file:f,kind:/\.csv$/i.test(p)?'csv':kind,text:data,bom,complete:true};
123
+ }
124
+ if(kind==='unsupported'||f.size>256*1024*1024)return {file:f,kind:'unsupported',readOnlyReason:'此格式使用默认应用查看'};
125
+ const handle=randomUUID();resources.set(handle,{path:p,revision:f.revision,caller,expires:Date.now()+15*60000});
126
+ return {file:f,kind,resourceHandle:handle};
127
+ }
128
+ async function editOriginal(p,key,caller){
129
+ await info(p);if(!/^[a-f0-9]{64}$/.test(key))throw error('BAD_REQUEST');const folder=path.join(storage,'edit-originals'),m=await readJson(path.join(folder,key+'.json'),null);
130
+ if(!m||m.path!==p||m.caller!==caller)throw error('FORBIDDEN','编辑原件不属于当前文件与授权');
131
+ const file=path.join(folder,key+'.bin');if(hash(await readFile(file))!==m.sha256)throw error('RECOVERY_REQUIRED','编辑原件校验失败');
132
+ const handle=randomUUID();resources.set(handle,{path:p,revision:m.file.revision,caller,snapshot:file,expires:Date.now()+15*60000});return {file:m.file,kind:/\.docx$/i.test(p)?'docx':'xlsx',originalKey:key,resourceHandle:handle};
133
+ }
134
+ async function trashObject(id,relative=''){
135
+ if(!uuid.test(id??''))throw error('BAD_REQUEST','回收项目标识无效');
136
+ const dir=await trashDir(id),item=await readJson(await safePath(dir,'manifest.json'),null);
137
+ if(item?.state!=='trashed')throw error('NOT_FOUND','回收项目已恢复或删除');
138
+ if(relative)relative=relativePath(relative);
139
+ if(relative&&item.type!=='directory')throw error('BAD_REQUEST');
140
+ const entry=relative?item.entries?.find(e=>e.path===relative):item;
141
+ if(!entry)throw error('NOT_FOUND','回收项目内没有该资料');
142
+ const absolute=await safePath(dir,(item.type==='directory'?'original-folder':'original')+(relative?'/'+relative:'')),s=await lstat(absolute,{bigint:true});
143
+ if((entry.type==='directory')!==s.isDirectory()||!s.isFile()&&!s.isDirectory())throw error('RECOVERY_REQUIRED','回收原件类型不一致');
144
+ const p=item.path+(relative?'/'+relative:''),file={id:p,path:p,name:path.posix.basename(p),type:s.isDirectory()?'directory':'file',mime:s.isFile()?mimeOf(p):undefined,size:Number(s.size),modifiedAt:Number(s.mtimeMs),revision:version(s),access:{canEdit:false,canRename:false,canMove:false,canTrash:false,indexExcluded:!!entry.excluded,reasons:['回收站原件只读']}};
145
+ return {dir,item,entry,absolute,file,relative};
146
+ }
147
+ async function trashPreview(id,relative,caller){
148
+ const o=await trashObject(id,relative),{file,item}=o,baseReply={file,trashId:id,trashPath:o.relative};
149
+ if(file.type==='directory')return {...baseReply,kind:'unsupported',items:item.entries.filter(e=>path.posix.dirname(e.path)===(o.relative||'.')).map(e=>({path:e.path,name:path.posix.basename(e.path),type:e.type,size:e.size??0}))};
150
+ if(file.size>MAX_FILE)return {...baseReply,kind:'unsupported',readOnlyReason:'文件超过预览预算'};
151
+ const data=await readFile(o.absolute);if(hash(data)!==o.entry.sha256)throw error('RECOVERY_REQUIRED','回收原件校验失败');
152
+ const kind=OFFICE.test(file.path)?(/\.docx$/i.test(file.path)?'docx':'xlsx'):file.mime==='application/pdf'?'pdf':file.mime?.startsWith('image/')?'image':file.mime?.startsWith('audio/')?'audio':file.mime?.startsWith('video/')?'video':TEXT.test(file.path)?(/\.(md|mdx|markdown)$/i.test(file.path)?'markdown':/\.csv$/i.test(file.path)?'csv':'text'):'unsupported';
153
+ if(['markdown','text','csv'].includes(kind)){if(file.size>MAX_TEXT)return {...baseReply,kind:'unsupported',readOnlyReason:'文本超过完整预览上限'};try{return {...baseReply,kind,text:decoder.decode(data)};}catch{return {...baseReply,kind:'unsupported',readOnlyReason:'编码不是 UTF-8'};}}
154
+ if(kind==='unsupported'||OFFICE.test(file.path)&&file.size>MAX_OFFICE)return {...baseReply,kind:'unsupported',readOnlyReason:'此格式暂不支持内置预览'};
155
+ const handle=randomUUID();resources.set(handle,{caller,trashId:id,trashPath:o.relative,revision:file.revision,expires:Date.now()+15*60000});return {...baseReply,kind,resourceHandle:handle};
156
+ }
157
+ async function media(a,caller){
158
+ const r=resources.get(a.handle);
159
+ if(!r||r.caller!==caller||r.expires<Date.now())throw error('UNAUTHORIZED','媒体读取授权已失效');
160
+ const archived=r.trashId?await trashObject(r.trashId,r.trashPath):null,current=archived?.file??await info(r.path),f=r.snapshot?{...current,size:(await stat(r.snapshot)).size}:current;if(!r.snapshot&&f.revision!==r.revision)throw error('CONFLICT','原件已更新,请重新打开');
161
+ if(a.offset>f.size)throw error('BAD_REQUEST','媒体读取范围无效');
162
+ const h=await open(r.snapshot??archived?.absolute??await checked(r.path),'r'),buf=Buffer.alloc(Math.min(a.length,f.size-a.offset));
163
+ try{const {bytesRead}=await h.read(buf,0,buf.length,a.offset);if(!r.snapshot&&(archived?(await trashObject(r.trashId,r.trashPath)).file:await info(r.path)).revision!==r.revision)throw error('CONFLICT');return {data:buf.subarray(0,bytesRead).toString('base64'),size:f.size,mime:f.mime};}finally{await h.close();}
164
+ }
165
+ async function replaceFile(a,caller,operationId){
166
+ const s=stages.get(a.stageId);if(!s||s.caller!==caller||!s.final)throw error('FORBIDDEN');
167
+ return withLock(async()=>{
168
+ const f=await info(a.path);if(!f.access.canEdit||/\.md$/i.test(a.path))throw error('READ_ONLY','此文件不支持该保存方式');
169
+ const before=await stable(a.path,OFFICE.test(a.path)?MAX_OFFICE:MAX_TEXT);if(before.revision!==a.expectedRevision)throw error('CONFLICT','文件已在另一入口修改,草稿未覆盖原件');
170
+ const data=await readFile(s.file);if(data.length>(OFFICE.test(a.path)?MAX_OFFICE:MAX_TEXT)||hash(data)!==s.hash)throw error('BAD_REQUEST');
171
+ if(!OFFICE.test(a.path))try{decoder.decode(data);}catch{throw error('BAD_REQUEST','文本须为完整UTF-8');}
172
+ const proof=path.join(storage,'operations',operationId);await mkdir(proof,{recursive:true});await atomic(path.join(proof,'original.bin'),before.data);await atomic(path.join(proof,'intent.json'),{path:a.path,before:hash(before.data),after:hash(data)});
173
+ if((await info(a.path)).revision!==a.expectedRevision)throw error('CONFLICT');await atomic(before.absolute,data);const result={committed:true,path:a.path,revision:(await info(a.path)).revision};await atomic(path.join(proof,'committed.json'),result);return result;
174
+ });
175
+ }
176
+ async function retainExclusion(source,destination,force=false){
177
+ await locked(policyFile(base),async()=>{
178
+ const p=readIndexPolicy(base);
179
+ if(!force&&!policyExcluded(p,source))return;
180
+ const id=randomUUID();
181
+ p.groups[id]={id,state:'excluded',excluded:true,pending:false,files:[{current:destination,normal:destination,aliases:[source]}],savedLinks:[]};
182
+ await savePolicy(base,p);
183
+ });
184
+ }
185
+ async function moveInventory(parent,out=[],depth=0){
186
+ if(depth>20)throw error('BAD_REQUEST','目录层级超过此次操作预算');
187
+ for(const e of await readdir(await checked(parent),{withFileTypes:true})){
188
+ const p=parent+'/'+e.name;
189
+ if(e.name.startsWith('.')||e.isSymbolicLink()||privatePath(p)||['node_modules','索引层'].includes(e.name))throw error('READ_ONLY','目录内有未授权、内部或链接资料,请单独移动可见文件');
190
+ const f=await info(p);if(f.protected)throw error('READ_ONLY','目录内有受保护资料');out.push(f);
191
+ if(out.length>5000)throw error('BAD_REQUEST','目录超过候选版移动预算');
192
+ if(f.type==='directory')await moveInventory(p,out,depth+1);
193
+ }return out;
194
+ }
195
+ async function referencePlan(source,destination){
196
+ const rewrites=[],unresolved=[];
197
+ const mapped=p=>p===source?destination:p.startsWith(source+'/')?destination+p.slice(source.length):p;
198
+ for(const file of await walk()){
199
+ if(!/\.md$/i.test(file.path)||file.size>MAX_TEXT)continue;
200
+ const before=await stable(file.path,MAX_TEXT);let text;try{text=decoder.decode(before.data);}catch{continue;}
201
+ const destinationPath=mapped(file.path);
202
+ let next=text.replace(/\[\[([^\]|#]+)(#[^\]|]+)?(\|[^\]]+)?\]\]/g,(whole,target,anchor='',label='')=>{
203
+ const explicit=target.endsWith('.md')?target:target+'.md',changed=mapped(explicit);
204
+ if(changed!==explicit)return '[['+(target.endsWith('.md')?changed:changed.replace(/\.md$/i,''))+anchor+label+']]';
205
+ if(!target.includes('/')&&target===path.posix.basename(source).replace(/\.md$/i,''))unresolved.push(file.path);
206
+ return whole;
207
+ });
208
+ next=next.replace(/\]\(([^)]+)\)/g,(whole,target)=>{
209
+ if(target.startsWith('#')||/^[a-z]+:/i.test(target))return whole;
210
+ let decoded;try{decoded=decodeURIComponent(target.split('#')[0]);}catch{return whole;}
211
+ const resolved=path.posix.normalize(path.posix.join(path.posix.dirname(file.path),decoded));
212
+ const targetPath=mapped(resolved);
213
+ if(targetPath===resolved&&destinationPath===file.path)return whole;
214
+ const rel=path.posix.relative(path.posix.dirname(destinationPath),targetPath);
215
+ return ']('+encodeURI(rel)+(target.includes('#')?'#'+target.split('#').slice(1).join('#'):'')+')';
216
+ });
217
+ if(next!==text){if(file.protected){unresolved.push(file.path);continue;}rewrites.push({path:file.path,destinationPath,revision:before.revision,before:before.data.toString('base64'),after:Buffer.concat([before.data.subarray(0,3).equals(Buffer.from([239,187,191]))?Buffer.from([239,187,191]):Buffer.alloc(0),Buffer.from(next)]).toString('base64')});}
218
+ }
219
+ return {rewrites,unresolved:[...new Set(unresolved)]};
220
+ }
221
+ async function plan(a,caller){
222
+ const {operation}=a,id=randomUUID(),p={id,caller,expires:Date.now()+5*60000,operation,source:a.path??'',destination:a.destination??'',revision:a.revision,rewrites:[],unresolved:[]};
223
+ if(['create','mkdir'].includes(operation)){
224
+ p.destination=relativePath(a.destination);osName(path.posix.basename(p.destination));await checked(p.destination,{missing:true,write:true});
225
+ if(await lstat(path.join(base,p.destination)).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))throw error('CONFLICT','目标已存在');
226
+ await stat(path.dirname(path.join(base,p.destination)));
227
+ }else if(['move','trash'].includes(operation)){
228
+ p.source=relativePath(a.path);const f=await info(p.source);
229
+ if(!f.access.canMove||!f.access.canTrash)throw error('READ_ONLY',f.access.reasons.join(';'));
230
+ if(f.revision!==a.revision)throw error('CONFLICT','原件已更新,请重新预览');
231
+ p.revision=f.revision;p.isDirectory=f.type==='directory';
232
+ if(p.isDirectory&&operation==='trash'){p.descendants=await moveInventory(p.source);if(p.descendants.some(f=>!f.access.canTrash))throw error('READ_ONLY','目录内有只读或受保护资料');}
233
+ if(operation==='move'){
234
+ p.destination=relativePath(a.destination);osName(path.posix.basename(p.destination));await checked(p.destination,{missing:true,write:true});
235
+ if(p.destination===p.source||p.destination.startsWith(p.source+'/'))throw error('BAD_REQUEST','目标目录不能位于源目录内');
236
+ if(await lstat(path.join(base,p.destination)).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))throw error('CONFLICT','目标已存在,不覆盖同名资料');
237
+ await stat(path.dirname(path.join(base,p.destination)));
238
+ if(p.isDirectory)p.descendants=await moveInventory(p.source);
239
+ Object.assign(p,await referencePlan(p.source,p.destination));
240
+ }
241
+ }else if(['restore','purge'].includes(operation)){
242
+ if(!uuid.test(a.path??''))throw error('BAD_REQUEST');
243
+ p.item=await readJson(path.join(await trashDir(a.path),'manifest.json'),null);
244
+ if(!p.item||p.item.state!=='trashed')throw error('NOT_FOUND');
245
+ p.trashId=a.path;
246
+ if(operation==='restore'){p.destination=relativePath(a.destination||p.item.path);await checked(p.destination,{missing:true,write:true});if(await lstat(path.join(base,p.destination)).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))throw error('CONFLICT','恢复目标已存在,请选择新名称');}
247
+ }else throw error('BAD_REQUEST','不支持该计划');
248
+ plans.set(id,p);
249
+ return {id,operation,expiresAt:p.expires,source:p.source,destination:p.destination,linkUpdates:p.rewrites.length,unresolvedLinks:p.unresolved,canCommit:true};
250
+ }
251
+ async function publishNew(file,data){
252
+ const h=await open(file,'wx');try{await h.writeFile(data);await h.sync();}finally{await h.close();}
253
+ }
254
+ async function validateTrashedDirectory(dir,item,relative='original-folder'){
255
+ const folder=await safePath(dir,relative),found=[];
256
+ async function visit(relative='',depth=0){
257
+ if(depth>20||found.length>5000)throw error('RECOVERY_REQUIRED','回收目录超过校验预算');
258
+ const current=relative?await safePath(folder,relative):folder;
259
+ for(const e of await readdir(current,{withFileTypes:true})){
260
+ if(e.isSymbolicLink())throw error('RECOVERY_REQUIRED','回收目录含链接');
261
+ const p=relative?relative+'/'+e.name:e.name,expected=item.entries.find(v=>v.path===p);if(!expected||expected.type!==(e.isDirectory()?'directory':'file'))throw error('RECOVERY_REQUIRED','回收目录内容已改变');
262
+ found.push(p);if(e.isDirectory())await visit(p,depth+1);else if(hash(await readFile(await safePath(folder,p)))!==expected.sha256)throw error('RECOVERY_REQUIRED','回收原件校验失败');
263
+ }
264
+ }
265
+ await visit();if(found.length!==item.entries.length)throw error('RECOVERY_REQUIRED','回收目录内容不完整');return folder;
266
+ }
267
+ async function finishDirectoryTrash(operationId,item){
268
+ const dir=await trashDir(operationId);await validateTrashedDirectory(dir,item);
269
+ await atomic(path.join(dir,'manifest.json'),{...item,state:'trashed'});
270
+ const result={committed:true,path:item.path,operation:'trash',unresolvedLinks:[],requestState:'committed'};
271
+ await atomic(path.join(storage,'operations',operationId,'committed.json'),result);return result;
272
+ }
273
+ async function commit(a,caller,operationId){
274
+ const p=plans.get(a.planId);if(!p||p.caller!==caller||p.expires<Date.now())throw error('CONFLICT','操作计划已失效,请重新预览');
275
+ const proofDir=path.join(storage,'operations',operationId);await mkdir(proofDir,{recursive:true});
276
+ return withLock(async()=>{
277
+ await atomic(path.join(proofDir,'intent.json'),p);
278
+ if(p.operation==='create'||p.operation==='mkdir'){
279
+ const dst=await checked(p.destination,{missing:true,write:true});
280
+ if(p.operation==='mkdir')await mkdir(dst);
281
+ else {if(typeof a.text!=='string'||Buffer.byteLength(a.text)>MAX_TEXT||a.text.startsWith('\ufeff'))throw error('BAD_REQUEST');await publishNew(dst,Buffer.from(a.text));}
282
+ }else if(p.operation==='move'){
283
+ const src=await checked(p.source,{write:true}),dst=await checked(p.destination,{missing:true,write:true});
284
+ if((await info(p.source)).revision!==p.revision)throw error('CONFLICT','原件已改变');
285
+ for(const f of p.descendants??[])if((await info(f.path)).revision!==f.revision)throw error('CONFLICT','目录内资料已改变');
286
+ for(const r of p.rewrites)if((await info(r.path)).revision!==r.revision)throw error('CONFLICT','引用文件已改变');
287
+ await retainExclusion(p.source,p.destination);
288
+ for(const f of p.descendants??[])if(f.access.indexExcluded)await retainExclusion(f.path,p.destination+f.path.slice(p.source.length));
289
+ const done=[];
290
+ try{
291
+ if(p.isDirectory)await rename(src,dst);else{await link(src,dst);await unlink(src);}
292
+ done.push({kind:'move'});
293
+ for(const r of p.rewrites){
294
+ await atomic(path.join(proofDir,hash(r.path)+'.original'),Buffer.from(r.before,'base64'));
295
+ const file=await checked(r.destinationPath,{write:true});if(hash((await stable(r.destinationPath)).data)!==hash(Buffer.from(r.before,'base64')))throw error('CONFLICT');
296
+ await atomic(file,Buffer.from(r.after,'base64'));done.push(r);
297
+ }
298
+ }catch(e){
299
+ // Restore only bytes still matching our published rewrite; preserve external edits.
300
+ for(const r of done.filter(x=>x.path).reverse()){
301
+ const now=await readFile(path.join(base,r.destinationPath));
302
+ if(hash(now)===hash(Buffer.from(r.after,'base64')))await atomic(path.join(base,r.destinationPath),Buffer.from(r.before,'base64'));
303
+ }
304
+ if(done.some(x=>x.kind==='move')&&!await lstat(src).catch(()=>null))await rename(dst,src).catch(()=>{});
305
+ throw e;
306
+ }
307
+ }else if(p.operation==='trash'){
308
+ const src=await checked(p.source,{write:true});if((await info(p.source)).revision!==p.revision)throw error('CONFLICT');
309
+ const dir=await trashDir(operationId,{create:true});
310
+ if(p.isDirectory){
311
+ const now=await moveInventory(p.source);if(hash(now.map(f=>[f.path,f.revision]))!==hash(p.descendants.map(f=>[f.path,f.revision])))throw error('CONFLICT','目录内资料已改变');
312
+ const entries=[];let size=0;
313
+ for(const f of now){const data=f.type==='file'?await stable(f.path):null;size+=data?.data.length??0;if(size>MAX_BACKUP)throw error('BAD_REQUEST','目录超过128MiB回收预算');entries.push({path:f.path.slice(p.source.length+1),type:f.type,size:f.size,excluded:f.access.indexExcluded,...(data?{sha256:hash(data.data)}:{})});}
314
+ const latest=await moveInventory(p.source);if((await info(p.source)).revision!==p.revision||hash(latest.map(f=>[f.path,f.revision]))!==hash(now.map(f=>[f.path,f.revision])))throw error('CONFLICT','目录内资料已改变');
315
+ const item={id:operationId,path:p.source,type:'directory',entries,size,state:'prepared',deletedAt:Date.now(),excluded:policyExcluded(readIndexPolicy(base),p.source)};
316
+ await atomic(path.join(dir,'manifest.json'),item);await rename(src,path.join(dir,'original-folder'));await finishDirectoryTrash(operationId,item);
317
+ }else{
318
+ const data=(await stable(p.source)).data;await publishNew(path.join(dir,'original'),data);
319
+ const item={id:operationId,path:p.source,type:'file',size:data.length,state:'prepared',sha256:hash(data),deletedAt:Date.now(),excluded:policyExcluded(readIndexPolicy(base),p.source)};
320
+ await atomic(path.join(dir,'manifest.json'),item);if((await info(p.source)).revision!==p.revision)throw error('CONFLICT');
321
+ await unlink(src);await atomic(path.join(dir,'manifest.json'),{...item,state:'trashed'});
322
+ }
323
+ }else if(p.operation==='restore'){
324
+ const {dir,item}=await trashObject(p.trashId);if(hash(item)!==hash(p.item))throw error('CONFLICT','回收项目已改变');
325
+ const dst=await checked(p.destination,{missing:true,write:true});if(await lstat(dst).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))throw error('CONFLICT','恢复目标已存在,请选择新名称');
326
+ if(item.excluded)await retainExclusion(item.path,p.destination,true);
327
+ if(item.type==='directory'){
328
+ const original=await validateTrashedDirectory(dir,item);
329
+ for(const e of item.entries)if(e.excluded)await retainExclusion(item.path+'/'+e.path,p.destination+'/'+e.path,true);
330
+ try{await rename(original,dst);}catch(e){
331
+ if(e.code!=='EXDEV')throw e;
332
+ // Legacy archives can live on another volume. Copy into a private stage
333
+ // beside the library, verify every entry, then publish on that volume.
334
+ // Retain the legacy original, as for restored single-file archives.
335
+ const staging=await trashDir(operationId,{create:true}),name='restore-copy';
336
+ await cp(original,path.join(staging,name),{recursive:true,force:false,errorOnExist:true,preserveTimestamps:true});
337
+ await validateTrashedDirectory(staging,item,name);
338
+ if(await lstat(dst).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))throw error('CONFLICT','恢复目标已存在');
339
+ await rename(path.join(staging,name),dst);
340
+ }
341
+ }else{const data=await readFile(await safePath(dir,'original'));if(hash(data)!==item.sha256)throw error('RECOVERY_REQUIRED','回收原件校验失败');await publishNew(dst,data);}
342
+ await atomic(path.join(dir,'manifest.json'),{...item,state:'restored',restoredTo:p.destination});
343
+ }else if(p.operation==='purge'){
344
+ const {dir,item,absolute}=await trashObject(p.trashId);if(hash(item)!==hash(p.item))throw error('CONFLICT','回收项目已改变');
345
+ if(item.type==='directory')await deleteTree(dir,absolute);else await unlink(absolute);
346
+ await atomic(path.join(dir,'manifest.json'),{...item,state:'purged'});
347
+ }else if(p.operation==='import'){
348
+ const stage=stages.get(p.stageId);if(!stage||stage.caller!==caller||!stage.final)throw error('UNAUTHORIZED');
349
+ const data=await readFile(stage.file);if(hash(data)!==stage.hash)throw error('CONFLICT');
350
+ await publishNew(await checked(p.destination,{missing:true,write:true}),data);
351
+ }
352
+ const result={committed:true,path:p.destination||p.source,operation:p.operation,unresolvedLinks:p.unresolved,requestState:'committed'};
353
+ await atomic(path.join(proofDir,'committed.json'),result);plans.delete(p.id);return result;
354
+ });
355
+ }
356
+ async function manifests(kind){
357
+ const rows=[],seen=new Set(),dirs=kind==='trash'?[localTrash,path.join(storage,kind)]:[path.join(storage,kind)];
358
+ for(const dir of dirs)for(const item of await readdir(dir).catch(e=>e.code==='ENOENT'?[]:Promise.reject(e))){
359
+ if(!uuid.test(item)||seen.has(item))continue;seen.add(item);
360
+ if((await lstat(path.join(dir,item))).isSymbolicLink())continue;
361
+ const entry=kind==='trash'?await trashDir(item):await safePath(privateDir,'desktop/'+kind+'/'+item);
362
+ let m=await readJson(await safePath(entry,'manifest.json',{missing:true}),null);
363
+ if(kind==='trash'&&m?.state==='prepared'&&m.type==='directory'&&await lstat(path.join(entry,'original-folder')).catch(()=>null)){await finishDirectoryTrash(item,m);m={...m,state:'trashed'};}
364
+ if(m)rows.push(kind==='backups'?{...m,id:item,digest:hash(m)}:m);
365
+ }
366
+ return rows.sort((a,b)=>(b.createdAt??b.deletedAt??0)-(a.createdAt??a.deletedAt??0));
367
+ }
368
+ async function backupPath(id,{missing=false}={}){
369
+ if(!uuid.test(id??''))throw error('BAD_REQUEST','备份标识无效');
370
+ return safePath(privateDir,'desktop/backups/'+id,{missing});
371
+ }
372
+ async function deleteTree(parent,target){
373
+ // Verify every directory before descending. Links are unlinked, never followed.
374
+ const canonicalParent=await realpath(parent),s=await lstat(target);
375
+ if(!inside(canonicalParent,target)||target===canonicalParent)throw error('FORBIDDEN','删除路径超出备份目录');
376
+ if(s.isSymbolicLink()||!s.isDirectory()){await unlink(target);return;}
377
+ const canonicalTarget=await realpath(target);
378
+ if(!inside(canonicalParent,canonicalTarget)||canonicalTarget===canonicalParent)throw error('FORBIDDEN','删除路径超出备份目录');
379
+ for(const name of await readdir(target))await deleteTree(canonicalParent,path.join(target,name));
380
+ await rmdir(target);
381
+ }
382
+ async function finishBackupDelete(operationId,intent){
383
+ const parent=await safePath(privateDir,'desktop/backups'),tomb=await safePath(parent,'.deleting-'+operationId,{missing:true});
384
+ let receipt=await readJson(path.join(storage,'operations',operationId,'committed.json'),null);
385
+ const staged=await lstat(tomb).catch(e=>e.code==='ENOENT'?null:Promise.reject(e));
386
+ if(!receipt){
387
+ if(!staged)return null;
388
+ const manifest=await readJson(await safePath(tomb,'manifest.json'),null);
389
+ if(hash(manifest)!==intent.expectedDigest)throw error('RECOVERY_REQUIRED','待删除备份校验失败');
390
+ receipt={committed:true,deleted:true,backupId:intent.backupId,cleanupPending:true};
391
+ await atomic(path.join(storage,'operations',operationId,'committed.json'),receipt);
392
+ }
393
+ if(receipt.cleanupPending){
394
+ try{if(staged)await deleteTree(parent,tomb);receipt={...receipt,cleanupPending:false};await atomic(path.join(storage,'operations',operationId,'committed.json'),receipt);}
395
+ catch{ /* Logical removal is durable; startup recovery retries private-file cleanup. */ }
396
+ }
397
+ return receipt;
398
+ }
399
+ async function backupDelete(a,operationId){
400
+ const source=await backupPath(a.backupId,{missing:true});
401
+ if(!await lstat(source).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))throw error('CONFLICT','备份已不存在,请刷新列表');
402
+ const manifest=await readJson(await safePath(source,'manifest.json'),null);
403
+ if(hash(manifest)!==a.expectedDigest)throw error('CONFLICT','备份已发生变化,请刷新后重新确认');
404
+ const parent=await safePath(privateDir,'desktop/backups'),tomb=await safePath(parent,'.deleting-'+operationId,{missing:true});
405
+ const intent={operation:'backupDelete',backupId:a.backupId,expectedDigest:a.expectedDigest};
406
+ await atomic(path.join(storage,'operations',operationId,'intent.json'),intent);
407
+ await rename(source,tomb);
408
+ for(const [id,p] of plans)if(p.backupId===a.backupId)plans.delete(id);
409
+ return finishBackupDelete(operationId,intent);
410
+ }
411
+ async function backup(operationId){
412
+ const dir=path.join(storage,'backups',operationId);await mkdir(path.join(dir,'files'),{recursive:true});
413
+ const files=await walk();let total=0;const manifest=[];
414
+ for(const f of files){const b=await stable(f.path);total+=b.data.length;if(total>MAX_BACKUP)throw error('BAD_REQUEST','备份超过候选版128MB预算');
415
+ await mkdir(path.dirname(path.join(dir,'files',f.path)),{recursive:true});await publishNew(path.join(dir,'files',f.path),b.data);manifest.push({path:f.path,sha256:hash(b.data),size:b.data.length});}
416
+ const shared=await readJson(path.join(base,'.kbmeta/shared-state.json'),null),policy=readIndexPolicy(base);
417
+ const included=new Set(files.map(f=>f.path)),catalog=await readCatalog(base);
418
+ const safeShared=shared?{...shared,links:(shared.links??[]).filter(e=>included.has(e.from)&&included.has(e.to)),captures:(shared.captures??[]).filter(e=>included.has(e.path)),annotations:(shared.annotations??[]).filter(e=>included.has(e.path)),reading:Object.fromEntries(Object.entries(shared.reading??{}).filter(([p])=>included.has(p))),reviews:Object.fromEntries(Object.entries(shared.reviews??{}).filter(([p])=>included.has(p))),tasks:[],trashOperations:{}}:null;
419
+ const sharedPolicy=await readJson(path.join(base,'.kbmeta/shared-policy.json'),null);
420
+ const state={shared:safeShared,policy,sharedPolicy:sharedPolicy?{...sharedPolicy,preferences:{...sharedPolicy.preferences,showPrivate:false}}:null,catalog:catalog?{...catalog,files:catalog.files.filter(f=>included.has(f.path)),references:catalog.references.filter(f=>included.has(f.path))}:null};
421
+ await atomic(path.join(dir,'state.json'),state);
422
+ const result={id:operationId,createdAt:Date.now(),files:manifest,size:total,stateHash:hash(state),verified:true,scope:'authorized-public-files-and-shared-state'};
423
+ await atomic(path.join(dir,'manifest.json'),result);const receipt={id:operationId,files:manifest.length,size:total,createdAt:result.createdAt,verified:true};await atomic(path.join(storage,'operations',operationId,'committed.json'),receipt);return receipt;
424
+ }
425
+ async function restorePreview(backupId,caller){
426
+ const dir=await backupPath(backupId,{missing:true});
427
+ if(!await lstat(dir).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))throw error('NOT_FOUND');
428
+ const manifest=await readJson(await safePath(dir,'manifest.json',{missing:true}),null);if(!manifest?.verified)throw error('NOT_FOUND');
429
+ const id=randomUUID();plans.set(id,{id,caller,backupId,manifest,expires:Date.now()+300000,operation:'backupRestore'});
430
+ return {id,files:manifest.files.length,size:manifest.size,mode:'new-copy',canCommit:true};
431
+ }
432
+ async function restoreCopy(planId,caller,operationId){
433
+ const p=plans.get(planId);if(!p||p.caller!==caller||p.operation!=='backupRestore'||p.expires<Date.now())throw error('CONFLICT');
434
+ const state=await readJson(await safePath(storage,'backups/'+p.backupId+'/state.json'));
435
+ if(p.manifest.stateHash&&hash(state)!==p.manifest.stateHash)throw error('RECOVERY_REQUIRED','备份状态校验失败');
436
+ const parent=await safePath(sandbox,'libraries',{missing:true});await mkdir(parent,{recursive:true});
437
+ const dst=await safePath(sandbox,'libraries/恢复副本-'+operationId,{missing:true});await mkdir(dst,{recursive:false});
438
+ const kernel=createEmbeddedKernel({stateDir:path.join(storage,'restore-init',operationId)});
439
+ try{const result=await kernel.openCore().bind(dst,{confirmInit:true,originalIndex:!!state.catalog});if(!result.ok)throw error('BINDING_CHANGED');}finally{kernel.dispose();}
440
+ await atomic(path.join(dst,'.desktop-preview.json'),{schemaVersion:1,synthetic:true,restoredAt:Date.now()});
441
+ for(const f of p.manifest.files){
442
+ const data=await readFile(path.join(storage,'backups',p.backupId,'files',f.path));if(hash(data)!==f.sha256)throw error('RECOVERY_REQUIRED','备份文件校验失败');
443
+ const target=await safePath(dst,f.path,{missing:true});await mkdir(path.dirname(target),{recursive:true});await atomic(target,data);
444
+ }
445
+ const meta=await readJson(path.join(dst,'.kbmeta/kb.json'));
446
+ if(state.catalog){state.catalog={...state.catalog,kbId:meta.kbId};await atomic(path.join(dst,CATALOG_PATH),state.catalog);}
447
+ if(state.shared)state.shared={...state.shared,kbId:meta.kbId};
448
+ await atomic(path.join(dst,'.desktop-restore-state.json'),state);
449
+ const result={committed:true,copyRoot:dst,files:p.manifest.files.length,restoreStatePending:true};await atomic(path.join(storage,'operations',operationId,'committed.json'),result);plans.delete(planId);return result;
450
+ }
451
+ async function restoreState(){
452
+ const pending=path.join(base,'.desktop-restore-state.json'),state=await readJson(pending,null);if(!state)return {committed:true,alreadyApplied:true};
453
+ return withLock(async()=>{if(state.shared?.schemaVersion===1||state.shared?.format===1)await atomic(path.join(base,'.kbmeta/shared-state.json'),state.shared);if(state.sharedPolicy?.schemaVersion===1)await atomic(path.join(base,'.kbmeta/shared-policy.json'),state.sharedPolicy);if(state.policy?.format===1)await atomic(path.join(base,'.kbmeta/index-policy.json'),state.policy);await unlink(pending);return {committed:true};});
454
+ }
455
+ // Retry only cleanup of already staged deletions, including after a crash between
456
+ // the atomic rename and receipt publication. Never infer deletion from absence.
457
+ for(const name of await readdir(path.join(storage,'backups')).catch(e=>e.code==='ENOENT'?[]:Promise.reject(e))){
458
+ const match=/^\.deleting-([a-f0-9]{64})$/.exec(name);if(!match)continue;
459
+ const intent=await readJson(path.join(storage,'operations',match[1],'intent.json'),null);
460
+ if(intent?.operation==='backupDelete')await finishBackupDelete(match[1],intent);
461
+ }
462
+ return {
463
+ async sourceFromStage(id,caller){const s=stages.get(id);if(!s||s.caller!==caller||!s.final)throw error('FORBIDDEN');const data=await readFile(s.file);if(hash(data)!==s.hash)throw error('CONFLICT','暂存原件已变化');return {data,name:s.name,bytes:data.length,external:true};},
464
+ async recoverReceipt(operationId){const intent=await readJson(path.join(storage,'operations',operationId,'intent.json'),null);if(intent?.operation==='backupDelete')return finishBackupDelete(operationId,intent);const receipt=await readJson(path.join(storage,'operations',operationId,'committed.json'),null);if(receipt)return receipt;if(intent?.operation==='trash'){
465
+ const dir=await trashDir(operationId),item=await readJson(path.join(dir,'manifest.json'),null);
466
+ if(item?.type==='directory'&&item.state==='prepared'){
467
+ if(await lstat(path.join(dir,'original-folder')).catch(e=>e.code==='ENOENT'?null:Promise.reject(e)))return finishDirectoryTrash(operationId,item);
468
+ try{const current=await info(intent.source),entries=await moveInventory(intent.source);if(current.revision===intent.revision&&hash(entries.map(f=>[f.path,f.revision]))===hash(intent.descendants.map(f=>[f.path,f.revision])))return {failed:true,error:{code:'CONFLICT',message:'上次回收未移动原目录,操作已确认失败。请重新预览后提交。'}};}catch{}
469
+ }
470
+ }return null;},
471
+ async call(method,a,caller,operationId){
472
+ if(method==='desktop.list')return list(a.parent??'',a.offset??0,a.limit??500);
473
+ if(method==='desktop.listSorted')return list(a.parent??'',a.offset??0,a.limit??500,a.sort??'name-asc');
474
+ if(method==='desktop.stat')return info(a.path);
475
+ if(method==='desktop.preview')return preview(a.path,caller);
476
+ if(method==='desktop.trashPreview')return trashPreview(a.id,a.path??'',caller);
477
+ if(method==='desktop.editOriginal')return editOriginal(a.path,a.originalKey,caller);
478
+ if(method==='desktop.fileReplace')return replaceFile(a,caller,operationId);
479
+ if(method==='desktop.media')return media(a,caller);
480
+ if(method==='desktop.plan')return plan(a,caller);
481
+ if(method==='desktop.commit')return commit(a,caller,operationId);
482
+ if(method==='desktop.trash')return {items:(await manifests('trash')).filter(m=>m.state==='trashed')};
483
+ if(method==='desktop.backups')return {items:(await manifests('backups')).map(({files,...m})=>({...m,fileCount:Array.isArray(files)?files.length:0}))};
484
+ if(method==='desktop.backupCreate')return backup(operationId);
485
+ if(method==='desktop.backupDelete')return backupDelete(a,operationId);
486
+ if(method==='desktop.restorePreview')return restorePreview(a.backupId,caller);
487
+ if(method==='desktop.restoreCommit')return restoreCopy(a.planId,caller,operationId);
488
+ if(method==='desktop.restoreState')return restoreState();
489
+ if(method==='desktop.tasks')return {items:[]};
490
+ if(method==='desktop.search'){
491
+ const all=await walk(),q=a.query.toLowerCase(),items=[];
492
+ for(const f of all){
493
+ if(a.mode==='name'&&(f.path.toLowerCase().includes(q)))items.push({...f,snippet:f.path});
494
+ if(a.mode==='fulltext'&&!f.access.indexExcluded&&/\.(md|txt)$/i.test(f.path)&&f.size<MAX_TEXT){const b=await stable(f.path,MAX_TEXT);let text;try{text=decoder.decode(b.data);}catch{continue;}const i=text.toLowerCase().indexOf(q);if(i>=0)items.push({...f,snippet:text.slice(Math.max(0,i-36),i+120)});}
495
+ if(items.length>=100)break;
496
+ }return {items};
497
+ }
498
+ if(method==='desktop.importStage'||method==='desktop.editStage'){
499
+ osName(a.name);let s=a.stageId?stages.get(a.stageId):null;
500
+ if(a.stageId&&(!s||s.caller!==caller))throw error('UNAUTHORIZED');
501
+ if(!s){const id=randomUUID(),file=path.join(storage,'imports',id);await mkdir(path.dirname(file),{recursive:true});await publishNew(file,Buffer.alloc(0));s={id,file,caller,size:0,name:a.name,final:false};stages.set(id,s);}
502
+ if(s.final||s.name!==a.name)throw error('CONFLICT');
503
+ const data=Buffer.from(a.data,'base64');s.size+=data.length;if(s.size>MAX_FILE)throw error('BAD_REQUEST','导入超过64MB预算');
504
+ const h=await open(s.file,'a');try{await h.writeFile(data);}finally{await h.close();}s.final=a.final;if(s.final)s.hash=hash(await readFile(s.file));return {stageId:s.id,size:s.size,final:s.final};
505
+ }
506
+ if(method==='desktop.importPlan'){
507
+ const s=stages.get(a.stageId);if(!s||s.caller!==caller||!s.final)throw error('UNAUTHORIZED');
508
+ const p=await plan({operation:'create',destination:a.destination},caller),stored=plans.get(p.id);stored.operation='import';stored.stageId=s.id;return {...p,operation:'import'};
509
+ }
510
+ throw error('CAPABILITY_UNSUPPORTED');
511
+ }
512
+ };
513
+ }
514
+
@@ -0,0 +1,39 @@
1
+ import path from 'node:path';import os from 'node:os';import {readdir,realpath} from 'node:fs/promises';
2
+ import {readJson} from './io.js';import {libraryIdentity} from './service.js';
3
+ // Only time-limited selections published by a desktop main process are followed.
4
+ export async function desktopHostSelections(home=path.join(os.homedir(),'.dsh/knowledge-desktop-links'),now=Date.now()){
5
+ const rows=[];
6
+ for(const name of await readdir(home).catch(e=>e.code==='ENOENT'?[]:Promise.reject(e))){
7
+ if(!/^[a-f0-9-]{36}\.json$/i.test(name))continue;
8
+ try{const lease=await readJson(path.join(home,name),null);if(!lease||lease.expiresAt<now||lease.expiresAt>now+30000)continue;
9
+ const root=await realpath(lease.root),data=await realpath(lease.dataDir),identity=await libraryIdentity(root);if(identity.instanceId!==lease.instanceId||identity.kbId!==lease.kbId)continue;
10
+ const grants=await readJson(path.join(data,'real-library-grants.json'),[]),grant=grants.find(g=>g.instanceId===identity.instanceId&&g.kbId===identity.kbId&&path.resolve(g.root).toLowerCase()===root.toLowerCase()&&g.serviceHome===lease.serviceHome);
11
+ const rel=path.relative(path.join(data,'libraries'),root),sample=lease.synthetic===true&&rel&&!rel.startsWith('..')&&!path.isAbsolute(rel)&&(await readJson(path.join(root,'.desktop-preview.json'),null))?.synthetic===true;
12
+ if(!grant&&!sample)continue;rows.push({...identity,serviceHome:lease.serviceHome});
13
+ }catch{/* A stale or mismatched request never grants a new library. */}
14
+ }
15
+ return [...new Map(rows.map(r=>[r.instanceId,r])).values()];
16
+ }
17
+ export function startDesktopHostLinks({ctx,python,connectRuntime,startBridge,workspaceFor,primaryRoot,ownerFor,recordSession,home,onLibraryEvent=()=>{},onError=()=>{}}){
18
+ const links=new Map(),knownWorkspaces=new Map();let disposed=false,busy=false;
19
+ async function refresh(){if(disposed||busy)return;busy=true;try{
20
+ const rows=(await desktopHostSelections(home)).filter(r=>path.resolve(r.root).toLowerCase()!==path.resolve(primaryRoot).toLowerCase()),wanted=new Set(rows.map(r=>r.instanceId));
21
+ for(const [id,link]of links)if(!wanted.has(id)){
22
+ links.delete(id);
23
+ onLibraryEvent({event:'connection.changed',data:{state:'offline'}});
24
+ link.bridge.dispose();await link.runtime.close();
25
+ }
26
+ for(const row of rows){if(links.has(row.instanceId)||disposed)continue;let runtime;try{runtime=await connectRuntime({library:row.root,home:row.serviceHome,python,onEvent:onLibraryEvent,kind:'dsh-adapter',allowFreshSynthetic:false,required:['host.bridge']});const workspace=await workspaceFor(row.root);if(disposed){await runtime.close();continue;}knownWorkspaces.set(path.resolve(workspace.workspacePath).toLowerCase(),row.instanceId);const bridge=startBridge({client:runtime.client,ctx,workspace,ensureWorkspace:()=>workspaceFor(row.root),libraryRoot:row.root,ownsSession:ownerFor?(id=>ownerFor(id)===row.instanceId):undefined,onSessionCreated:recordSession?(id=>recordSession(row.instanceId,id)):undefined,label:'DSH · '+path.basename(row.root),onError});links.set(row.instanceId,{runtime,bridge});onLibraryEvent({event:'connection.changed',data:{state:'ready'}});}catch(e){await runtime?.close();onError(e);}}
27
+ }finally{busy=false;}}
28
+ const timer=setInterval(()=>void refresh().catch(onError),1000);timer.unref?.();void refresh().catch(onError);
29
+ return {
30
+ clientForLibrary(instanceId){return links.get(instanceId)?.runtime.client??null;},
31
+ clientForAgent(agent){if(!agent||ctx.get('agents')?.get(agent.id)!==agent)return undefined;if(ownerFor){const owner=ownerFor(agent.id);return owner?links.get(owner)?.runtime.client??null:undefined;}const cwd=agent.session?.header?.cwd;if(!cwd)return undefined;const id=knownWorkspaces.get(path.resolve(cwd).toLowerCase());return id?links.get(id)?.runtime.client??null:undefined;},
32
+ async dispose(){
33
+ disposed=true;clearInterval(timer);
34
+ const detached=[...links.values()];links.clear();
35
+ if(detached.length)onLibraryEvent({event:'connection.changed',data:{state:'offline'}});
36
+ for(const link of detached){link.bridge.dispose();await link.runtime.close();}
37
+ }
38
+ };
39
+ }