@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,1136 @@
1
+ // 自定义流程:定义持久化 + 触发语解析 + 运行执行器 + 受控落库。
2
+ //
3
+ // 设计约束(来自产品需求,逐条对应):
4
+ // 1. 定义随**库身份(kbId)**保存:`<stateDir>/flows/<kbId>/flows.json`。
5
+ // 未绑定知识库 → 拒绝读写并给明确错误(不落"无主的流程")。
6
+ // 2. revision 防覆盖:更新必须带 expectedRevision;不符 → conflict 且**不改盘**。
7
+ // 写前备份(与 kbcore 的原子写/备份风格一致:tmp + rename 重试 + 逐次 .bak)。
8
+ // 3. 软删除 = archived:true —— 从可触发列表移除,但定义与运行记录都保留,可恢复。
9
+ // 4. 运行记录与定义分开:`<stateDir>/flows/<kbId>/runs/<runId>.json`。
10
+ // 记录里固定 kbId / flowRevision / params / runId —— 库切换后不会串读(路径按 kbId 分)。
11
+ // 5. 执行 = 通过 gateway 的委派内核逐步交给知识库子代理(**不新建 Agent 运行时**)。
12
+ // 每一步一次委派 → 真进度、真取消、真失败原因;无副作用步骤才允许重试。
13
+ // 6. 成功才落库,且落库走**现有 core 的 createEntry**(隐私/路径/revision 保护全继承);
14
+ // 失败或取消绝不写成成功,也绝不把"流程说明"当成已执行结果。
15
+ //
16
+ // 本文件不 import 任何 @deepseek-ai/* 包,只用 node 内置 + 注入进来的 core/delegate。
17
+
18
+ import crypto from 'node:crypto'
19
+ import { mkdir, readFile, writeFile, rename, readdir, unlink, copyFile } from 'node:fs/promises'
20
+ import path from 'node:path'
21
+ import { INBOX_FLOW } from './inbox-flow.js'
22
+
23
+ export const FLOWS_SCHEMA_VERSION = 1
24
+ function withBuiltinFlows(flows) {
25
+ const saved = flows.find(f => f.id === INBOX_FLOW.id)
26
+ const flow = normalizeFlow({ id: INBOX_FLOW.id, name: INBOX_FLOW.name,
27
+ triggers: ['整理并归档收件箱'], description: '内置流程:新开知识库 agent 会话,以 High 推理强度整理收件箱。',
28
+ steps: [{ title: '整理并归档收件箱内的文件', instruction: INBOX_FLOW.prompt }],
29
+ outputRules: { land: false }, enabled: true, execution: saved?.execution || {},
30
+ revision: Number.isSafeInteger(saved?.revision) && saved.revision > 0 ? saved.revision : 1 })
31
+ return [{ ...flow, builtin: true }, ...flows.filter(f => f.id !== flow.id)]
32
+ }
33
+ export const FLOW_KINDS = ['知识', '项目', '人物', '素材', '画像']
34
+ export const MAX_STEPS = 12
35
+ export const MAX_RUNS_KEPT = 120
36
+ const BAK_KEEP = 5
37
+ // Multiple engine instances in one host must not race read/modify/write or
38
+ // admit the same run while its initial record is still being written.
39
+ const stateQueues = new Map()
40
+ async function serialized(key, fn) {
41
+ const previous = stateQueues.get(key) ?? Promise.resolve()
42
+ const current = previous.catch(() => {}).then(fn)
43
+ stateQueues.set(key, current)
44
+ try { return await current } finally { if (stateQueues.get(key) === current) stateQueues.delete(key) }
45
+ }
46
+
47
+ const nowIso = () => new Date().toISOString()
48
+ const str = (v) => (typeof v === 'string' ? v.trim() : '')
49
+ const arr = (v) => (Array.isArray(v) ? v : [])
50
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
51
+
52
+ function newId(prefix) {
53
+ return prefix + '-' + crypto.randomBytes(5).toString('hex')
54
+ }
55
+
56
+ /** kbId 直接进路径前必须收窄(防路径逃逸) */
57
+ function safeKbKey(kbId) {
58
+ const raw = str(kbId)
59
+ if (/^[A-Za-z0-9._-]{1,64}$/.test(raw) && raw !== '.' && raw !== '..') return raw
60
+ return 'h-' + crypto.createHash('sha1').update(raw).digest('hex').slice(0, 16)
61
+ }
62
+
63
+ export function flowPathsOf(stateDir, kbId) {
64
+ const base = path.join(path.resolve(stateDir), 'flows', safeKbKey(kbId))
65
+ return {
66
+ base: base,
67
+ file: path.join(base, 'flows.json'),
68
+ runsDir: path.join(base, 'runs'),
69
+ backupsDir: path.join(base, 'backups'),
70
+ }
71
+ }
72
+
73
+ /** 与 kbcore 一致的原子写:先写 tmp,再 rename;Windows 上短暂的 EPERM/EBUSY 退避重试。 */
74
+ async function atomicWrite(file, text) {
75
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomBytes(4).toString('hex')}`
76
+ await mkdir(path.dirname(file), { recursive: true })
77
+ await writeFile(tmp, text, 'utf8')
78
+ let lastError = null
79
+ for (let i = 0; i < 6; i += 1) {
80
+ try {
81
+ await rename(tmp, file)
82
+ return
83
+ } catch (error) {
84
+ lastError = error
85
+ const code = String((error && error.code) ?? '')
86
+ if (!['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY'].includes(code)) throw error
87
+ await new Promise((r) => setTimeout(r, 20 * 2 ** i))
88
+ }
89
+ }
90
+ throw lastError
91
+ }
92
+
93
+ async function readJson(file) {
94
+ try {
95
+ const raw = await readFile(file, 'utf8')
96
+ try {
97
+ return { state: 'ok', value: JSON.parse(raw), raw: raw }
98
+ } catch (error) {
99
+ return { state: 'corrupt', error: String((error && error.message) ?? error) }
100
+ }
101
+ } catch (error) {
102
+ if (error && error.code === 'ENOENT') return { state: 'missing' }
103
+ return { state: 'unreadable', error: String((error && (error.code || error.message)) ?? error) }
104
+ }
105
+ }
106
+
107
+ // ── 校验 / 规范化 ────────────────────────────────────────────────────────────
108
+ /**
109
+ * 校验一份流程定义。返回**错误清单**(空数组 = 通过)。
110
+ * 之所以是纯函数:桩测要用同一个函数做双向自证(好样本零误报、坏样本逐项命中)。
111
+ */
112
+ export function validateFlow(flow) {
113
+ const errors = []
114
+ if (!isPlainObject(flow)) return ['定义必须是对象']
115
+ if (str(flow.name) === '') errors.push('name 必填')
116
+ if (str(flow.name).length > 80) errors.push('name 过长(≤80)')
117
+ const triggers = arr(flow.triggers).map(str).filter((t) => t !== '')
118
+ if (triggers.length === 0) errors.push('triggers 至少要有一条触发语')
119
+ if (triggers.some((t) => t.length > 40)) errors.push('单条触发语过长(≤40)')
120
+ const steps = arr(flow.steps)
121
+ if (steps.length === 0) errors.push('steps 至少要有一项')
122
+ if (steps.length > MAX_STEPS) errors.push(`steps 最多 ${MAX_STEPS} 项`)
123
+ steps.forEach((s, i) => {
124
+ if (!isPlainObject(s)) {
125
+ errors.push(`steps[${i}] 必须是对象`)
126
+ return
127
+ }
128
+ if (str(s.title) === '') errors.push(`steps[${i}].title 必填`)
129
+ if (str(s.instruction) === '') errors.push(`steps[${i}].instruction 必填`)
130
+ if (s.capability !== undefined && s.capability !== null && typeof s.capability !== 'string') errors.push(`steps[${i}].capability 必须是字符串`)
131
+ })
132
+ for (const [i, p] of arr(flow.params).entries()) {
133
+ if (!isPlainObject(p)) {
134
+ errors.push(`params[${i}] 必须是对象`)
135
+ continue
136
+ }
137
+ if (!/^[A-Za-z0-9_\u4e00-\u9fa5-]{1,32}$/.test(str(p.name))) errors.push(`params[${i}].name 非法(字母/数字/下划线/汉字,≤32)`)
138
+ }
139
+ const names = arr(flow.params).filter(isPlainObject).map((p) => str(p.name)).filter((n) => n !== '')
140
+ if (new Set(names).size !== names.length) errors.push('params 名字重复')
141
+ if (flow.capabilities !== undefined && flow.capabilities !== null && !Array.isArray(flow.capabilities)) errors.push('capabilities 必须是数组')
142
+ if (flow.execution !== undefined && flow.execution !== null) {
143
+ const route = flow.execution
144
+ if (!isPlainObject(route)) errors.push('execution 必须是对象')
145
+ else {
146
+ for (const key of ['provider', 'model', 'reasoningEffort']) {
147
+ if (route[key] !== undefined && (typeof route[key] !== 'string' || route[key].length > 256)) errors.push(`execution.${key} 必须是 ≤256 字的字符串`)
148
+ }
149
+ if (Boolean(str(route.provider)) !== Boolean(str(route.model))) errors.push('执行模型必须同时指定 provider 和 model')
150
+ if (str(route.reasoningEffort) && !str(route.model)) errors.push('选择推理强度前请先选择执行模型')
151
+ }
152
+ }
153
+ const rules = flow.outputRules === undefined || flow.outputRules === null ? {} : flow.outputRules
154
+ if (!isPlainObject(rules)) errors.push('outputRules 必须是对象')
155
+ else {
156
+ if (rules.kind !== undefined && rules.kind !== null && FLOW_KINDS.indexOf(String(rules.kind)) < 0) errors.push('outputRules.kind 不在允许值内:' + FLOW_KINDS.join(' / '))
157
+ if (rules.tags !== undefined && rules.tags !== null && !Array.isArray(rules.tags)) errors.push('outputRules.tags 必须是数组')
158
+ if (rules.dir !== undefined && rules.dir !== null && rules.dir !== '') {
159
+ const d = String(rules.dir).replace(/\\/g, '/')
160
+ if (d.startsWith('/') || /^[A-Za-z]:/.test(d) || d.split('/').some((s) => s === '..')) errors.push('outputRules.dir 必须是库内相对路径(不得绝对路径/不得 ..)')
161
+ }
162
+ if (rules.status !== undefined && rules.status !== null && (typeof rules.status !== 'string' || String(rules.status).length > 20)) errors.push('outputRules.status 必须是 ≤20 字的字符串')
163
+ if (rules.windowDays !== undefined && rules.windowDays !== null) {
164
+ const n = Number(rules.windowDays)
165
+ if (!Number.isInteger(n) || n < 1 || n > 365) errors.push('outputRules.windowDays 必须是 1..365 的整数')
166
+ }
167
+ }
168
+ return errors
169
+ }
170
+
171
+ /** 规范化成磁盘形状(补默认值、去空白、生成 step id)。校验不过的不写盘。 */
172
+ export function normalizeFlow(input, ctxIn = {}) {
173
+ const now = ctxIn.now ?? nowIso()
174
+ const rulesIn = isPlainObject(input.outputRules) ? input.outputRules : {}
175
+ const steps = arr(input.steps).map((s, i) => {
176
+ const step = {
177
+ id: str(s.id) || 's' + String(i + 1),
178
+ title: str(s.title),
179
+ instruction: str(s.instruction),
180
+ }
181
+ if (str(s.capability) !== '') step.capability = str(s.capability)
182
+ return step
183
+ })
184
+ const params = arr(input.params).map((p) => {
185
+ const one = { name: str(p.name), default: p.default === undefined || p.default === null ? '' : String(p.default) }
186
+ one.required = p.required === true
187
+ return one
188
+ })
189
+ return {
190
+ id: str(input.id) || newId('flow'),
191
+ schemaVersion: FLOWS_SCHEMA_VERSION,
192
+ revision: Number.isSafeInteger(input.revision) && input.revision > 0 ? input.revision : 1,
193
+ name: str(input.name),
194
+ triggers: Array.from(new Set(arr(input.triggers).map(str).filter((t) => t !== ''))),
195
+ description: str(input.description),
196
+ execution: Object.fromEntries(['provider', 'model', 'reasoningEffort'].filter(key => str(input.execution?.[key])).map(key => [key, str(input.execution[key])])),
197
+ params: params,
198
+ steps: steps,
199
+ capabilities: Array.from(new Set(arr(input.capabilities).map(str).filter((c) => c !== ''))),
200
+ outputRules: {
201
+ land: rulesIn.land === true,
202
+ kind: FLOW_KINDS.indexOf(String(rulesIn.kind)) >= 0 ? String(rulesIn.kind) : '知识',
203
+ tags: Array.from(new Set(arr(rulesIn.tags).map(str).filter((t) => t !== ''))),
204
+ dir: str(rulesIn.dir).replace(/\\/g, '/'),
205
+ tz: str(rulesIn.tz) || 'Asia/Shanghai',
206
+ // 落库报告的 frontmatter status:终态语义(缺省「生效」,不写「进行中」这种过程态)
207
+ status: str(rulesIn.status) || '生效',
208
+ windowDays: Number.isFinite(Number(rulesIn.windowDays)) ? Math.trunc(Number(rulesIn.windowDays)) : 7,
209
+ },
210
+ enabled: input.enabled !== false,
211
+ archived: input.archived === true,
212
+ createdAt: str(input.createdAt) || now,
213
+ updatedAt: now,
214
+ }
215
+ }
216
+
217
+ /** 参数默认值解析:给定值 → 默认值;required 且最终为空 → 报缺参(不替用户猜)。 */
218
+ export function resolveParams(flow, given) {
219
+ const g = isPlainObject(given) ? given : {}
220
+ const values = Object.create(null)
221
+ const missing = []
222
+ for (const p of arr(flow.params)) {
223
+ const raw = Object.hasOwn(g, p.name) ? g[p.name] : undefined
224
+ const value = raw === undefined || raw === null || String(raw) === '' ? (p.default ?? '') : String(raw)
225
+ if (p.required === true && String(value ?? '').trim() === '') missing.push(p.name)
226
+ values[p.name] = String(value)
227
+ }
228
+ // 未声明的参数原样保留(调用方可能带临时值),但不参与 required 判定
229
+ for (const key of Object.keys(g)) if (!Object.hasOwn(values, key)) values[key] = String(g[key])
230
+ return { ok: missing.length === 0, values: values, missing: missing }
231
+ }
232
+
233
+ // ── 触发语解析(纯函数,桩测直接调) ─────────────────────────────────────────
234
+ const NEGATION = ['不要', '不用', '不需要', '别', '先别', '取消', '停止', '不用再', '别去', '不做', '不搞', '不必']
235
+ const HYPOTHETICAL = ['如果', '假如', '要是', '万一', '假设']
236
+ const DOC_MENTION = ['提到', '文档里', '文档中', '说明里', '说明中', '写着', '指的是', '引号', '所谓']
237
+
238
+ /**
239
+ * 在一段话里找命中哪些**已启用且未归档**的流程。
240
+ * 返回:
241
+ * status = hit(唯一流程)/ ambiguous(多个流程都命中)/ miss(无命中)
242
+ * matched:命中的 {flowId, name, trigger} —— ambiguous 时调用方列出候选让用户选
243
+ * guarded / guardReasons:句子里出现否定、假设、文档提及 → 提示"这更像提及而不是命令",
244
+ * 执行器默认因此**不自动开跑**(需求原文:不得把普通句子、否定句或文档中的触发词自动视作启动命令)。
245
+ */
246
+ export function matchTriggers(flows, textIn) {
247
+ const text = str(textIn)
248
+ const matched = []
249
+ if (text === '') return { status: 'miss', matched: [], guarded: false, guardReasons: [], coverage: { flows: arr(flows).length } }
250
+ const live = arr(flows).filter((f) => f && f.enabled !== false && f.archived !== true)
251
+ for (const flow of live) {
252
+ for (const trigger of arr(flow.triggers)) {
253
+ if (str(trigger) === '') continue
254
+ const at = text.indexOf(trigger)
255
+ if (at < 0) continue
256
+ matched.push({ flowId: flow.id, name: flow.name, trigger: trigger, at: at })
257
+ break
258
+ }
259
+ }
260
+ const reasons = []
261
+ const window = (entry) => text.slice(Math.max(0, entry.at - 10), entry.at)
262
+ let guarded = false
263
+ for (const entry of matched) {
264
+ const before = window(entry)
265
+ const neg = NEGATION.find((w) => before.indexOf(w) >= 0)
266
+ if (neg !== undefined) {
267
+ guarded = true
268
+ reasons.push(`「${entry.trigger}」前面有否定词「${neg}」:这看起来不是在叫我执行`)
269
+ }
270
+ const hyp = HYPOTHETICAL.find((w) => before.indexOf(w) >= 0)
271
+ if (hyp !== undefined) {
272
+ guarded = true
273
+ reasons.push(`「${entry.trigger}」出现在「${hyp}…」的假设句里`)
274
+ }
275
+ const doc = DOC_MENTION.find((w) => text.indexOf(w) >= 0)
276
+ if (doc !== undefined) {
277
+ guarded = true
278
+ reasons.push(`这段话里有对「${entry.trigger}」的提及式措辞(${doc}),可能只是提到而不是要求执行`)
279
+ }
280
+ }
281
+ const flowIds = Array.from(new Set(matched.map((m) => m.flowId)))
282
+ const status = matched.length === 0 ? 'miss' : flowIds.length === 1 ? 'hit' : 'ambiguous'
283
+ return { status: status, matched: matched, guarded: guarded, guardReasons: Array.from(new Set(reasons)), coverage: { flows: live.length } }
284
+ }
285
+
286
+ // ── 执行器 ───────────────────────────────────────────────────────────────────
287
+ function fmtInTz(iso, tz) {
288
+ try {
289
+ return new Intl.DateTimeFormat('sv-SE', { timeZone: tz, dateStyle: 'short', timeStyle: 'medium' }).format(new Date(iso))
290
+ } catch {
291
+ return iso
292
+ }
293
+ }
294
+
295
+ function isSideEffectStep(step) {
296
+ const cap = str(step === undefined || step === null ? '' : step.capability).toLowerCase()
297
+ // Unknown capabilities can have side effects. Only explicitly read-only
298
+ // steps qualify for automatic retry; a label is not a permission boundary.
299
+ return !['read', 'search', 'fetch', 'read-only'].includes(cap)
300
+ }
301
+
302
+ function buildStepTask(flow, run, step, index, prior) {
303
+ const lines = []
304
+ lines.push(`【流程】${flow.name}(定义版本 v${flow.revision},运行 ${run.runId})`)
305
+ if (flow.description !== '') lines.push(`【用途】${flow.description}`)
306
+ lines.push('【本次参数】')
307
+ const keys = Object.keys(run.params ?? {})
308
+ if (keys.length === 0) lines.push('(无)')
309
+ else for (const k of keys) lines.push(`- ${k} = ${run.params[k]}`)
310
+ lines.push(`【时间窗】${run.window.startAt} → ${run.window.endAt}(时区 ${run.window.tz};默认取最近 ${run.window.windowDays} 天)`)
311
+ lines.push(`【第 ${index + 1}/${flow.steps.length} 步】${step.title}`)
312
+ lines.push(step.instruction)
313
+ if (prior.length > 0) {
314
+ lines.push('【前序步骤已产出的内容(节选,作为本步输入)】')
315
+ for (const p of prior) {
316
+ const body = String(p.answer ?? '').trim()
317
+ lines.push(`--- ${p.index + 1}. ${p.title} ---`)
318
+ lines.push(body.length > 1200 ? body.slice(0, 1200) + '…(已截断)' : body)
319
+ }
320
+ }
321
+ lines.push('')
322
+ lines.push('【本次作业纪律】')
323
+ lines.push('1. 只做上面这一步;不要替后面的步骤先做,也不要省略。')
324
+ lines.push('2. 这一段的产出会被留在运行记录里,后续步骤会读它 —— 写清楚、可引用,不要寒暄。')
325
+ lines.push('3. 需要主人当场确认的事(删除、覆盖原件、外发),不要执行;直接写「需用户确认」+ 原因。')
326
+ lines.push('4. 不要调用其它子代理,也不要再调用知识库请求工具。')
327
+ return lines.join('\n')
328
+ }
329
+
330
+ function buildReport(flow, run) {
331
+ const lines = []
332
+ lines.push(`# ${flow.name} · 运行报告`)
333
+ lines.push('')
334
+ lines.push(`- 运行:\`${run.runId}\`(流程 ${flow.id} v${run.flowRevision})`)
335
+ lines.push(`- 知识库:${run.kbId}`)
336
+ lines.push(`- 参数:${Object.keys(run.params ?? {}).length === 0 ? '(无)' : Object.keys(run.params).map((k) => `${k}=${run.params[k]}`).join(',')}`)
337
+ lines.push(`- 时间窗:${run.window.startAt} → ${run.window.endAt}(${run.window.tz})`)
338
+ lines.push(`- 开始 / 结束:${run.startedAt} / ${run.finishedAt ?? '-'}`)
339
+ lines.push('')
340
+ lines.push('## 步骤')
341
+ run.steps.forEach((s, i) => {
342
+ lines.push(`${i + 1}. ${s.title} — ${s.status}${s.attempts > 1 ? `(重试 ${s.attempts - 1} 次)` : ''}`)
343
+ })
344
+ lines.push('')
345
+ lines.push('## 产出')
346
+ run.steps.forEach((s, i) => {
347
+ lines.push(`### ${i + 1}. ${s.title}`)
348
+ lines.push(String(s.answer ?? '').trim() === '' ? '(本步没有产出文本)' : String(s.answer).trim())
349
+ lines.push('')
350
+ })
351
+ lines.push('---')
352
+ lines.push(`> 本报告由自定义流程执行器生成(流程输出规则:落库=${flow.outputRules.land ? '是' : '否'},类型=${flow.outputRules.kind})。运行记录见 \`${run.runId}\`。`)
353
+ return lines.join('\n')
354
+ }
355
+
356
+ /**
357
+ * 创建流程引擎。
358
+ *
359
+ * opts = {
360
+ * stateDir, // <profile>/kb-state
361
+ * core, // kbcore 实例(要 status() 与 createEntry())
362
+ * delegate, // async ({targetId, task, kind, context, parentAgent, signal}) => {answer, subagentId, target, preset}
363
+ * log, // (level, message) => void
364
+ * targetId, // 委派目标 id(默认 knowledge)
365
+ * }
366
+ */
367
+ export function createFlowEngine(opts) {
368
+ const stateDir = path.resolve(opts.stateDir)
369
+ const core = opts.core
370
+ const delegate = opts.delegate
371
+ const log = typeof opts.log === 'function' ? opts.log : () => {}
372
+ const targetId = str(opts.targetId) || 'knowledge'
373
+ // 第二轮:解析步骤(capability = parse / parse.ocr / parse.asr)走与工具、设置页同一个解析服务。
374
+ // 没注入就是"未启用"——不静默退回委派,也不假装跑过。
375
+ const parseStep = typeof opts.parseStep === 'function' ? opts.parseStep : null
376
+ const active = new Map() // flowId -> { runId, controller, startedAt }
377
+ const activeByRun = new Map() // runId -> same entry
378
+
379
+ const fail = (reason, error, extra) => Object.assign({ ok: false, reason: reason, error: error }, extra ?? {})
380
+
381
+ const UNBOUND_TEXT = '未绑定知识库:流程按库身份(kbId)保存,先绑定再管理流程'
382
+ const UNINIT_TEXT = '知识库尚未初始化(没有 kbId):先运行 kb_init 补齐,再管理流程'
383
+
384
+ /** 按未绑定 / 未初始化分别给明确错误(不把两种"没有库"混成一句) */
385
+ const kbFail = (b) => fail(b.reason, b.reason === 'kb-uninitialized' ? UNINIT_TEXT : UNBOUND_TEXT)
386
+
387
+ async function boundKb() {
388
+ const st = await core.status()
389
+ if (!st || st.bound !== true || !st.kbPath) return { ok: false, reason: 'unbound', status: st }
390
+ // 有路径但还没有 kbId(未 init)→ 拒绝:否则两个"未初始化"的库会落到同一个 key 上互串
391
+ if (!st.kbId) return { ok: false, reason: 'kb-uninitialized', status: st }
392
+ return { ok: true, kbId: st.kbId, kbPath: st.kbPath, status: st }
393
+ }
394
+
395
+ async function readStore(kbId) {
396
+ const p = flowPathsOf(stateDir, kbId)
397
+ const disk = await readJson(p.file)
398
+ if (disk.state === 'ok' && isPlainObject(disk.value)) {
399
+ const value = disk.value
400
+ return {
401
+ ok: true,
402
+ store: {
403
+ schemaVersion: FLOWS_SCHEMA_VERSION,
404
+ kbId: kbId,
405
+ updatedAt: str(value.updatedAt),
406
+ flows: withBuiltinFlows(arr(value.flows).filter(isPlainObject)),
407
+ },
408
+ paths: p,
409
+ state: 'ok',
410
+ }
411
+ }
412
+ if (disk.state === 'corrupt') return { ok: false, reason: 'flows-corrupt', error: 'flows.json 损坏,未改动:' + (disk.error ?? ''), paths: p }
413
+ if (disk.state === 'unreadable') return { ok: false, reason: 'flows-unreadable', error: 'flows.json 不可读:' + (disk.error ?? ''), paths: p }
414
+ return { ok: true, store: { schemaVersion: FLOWS_SCHEMA_VERSION, kbId: kbId, updatedAt: '', flows: withBuiltinFlows([]) }, paths: p, state: 'missing' }
415
+ }
416
+
417
+ async function writeStore(kbId, store, paths) {
418
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
419
+ try {
420
+ const prev = await readFile(paths.file, 'utf8')
421
+ await mkdir(paths.backupsDir, { recursive: true })
422
+ await writeFile(path.join(paths.backupsDir, `flows.json.${stamp}.bak`), prev, 'utf8')
423
+ const olds = (await readdir(paths.backupsDir)).filter((n) => n.endsWith('.bak')).sort()
424
+ for (const name of olds.slice(0, Math.max(0, olds.length - BAK_KEEP))) {
425
+ await unlink(path.join(paths.backupsDir, name)).catch(() => {})
426
+ }
427
+ } catch (error) {
428
+ if (!(error && error.code === 'ENOENT')) log('warn', '流程写前备份失败(继续写):' + String((error && error.message) ?? error))
429
+ }
430
+ const payload = {
431
+ schemaVersion: FLOWS_SCHEMA_VERSION,
432
+ kbId: kbId,
433
+ updatedAt: nowIso(),
434
+ flows: arr(store.flows).map(f => f.id === INBOX_FLOW.id
435
+ ? { id: f.id, execution: f.execution || {}, revision: f.revision } : f),
436
+ }
437
+ await atomicWrite(paths.file, JSON.stringify(payload, null, 2))
438
+ return payload
439
+ }
440
+
441
+ // ── 运行记录读写 ──
442
+ async function writeRun(kbId, record) {
443
+ const p = flowPathsOf(stateDir, kbId)
444
+ await atomicWrite(path.join(p.runsDir, record.runId + '.json'), JSON.stringify(record, null, 2))
445
+ }
446
+
447
+ async function readRun(kbId, runId) {
448
+ if (!/^[A-Za-z0-9._-]{1,80}$/.test(str(runId))) return null
449
+ const p = flowPathsOf(stateDir, kbId)
450
+ const disk = await readJson(path.join(p.runsDir, str(runId) + '.json'))
451
+ return disk.state === 'ok' && isPlainObject(disk.value) ? disk.value : null
452
+ }
453
+
454
+ async function listRuns(kbId, flowId, limit) {
455
+ const p = flowPathsOf(stateDir, kbId)
456
+ let names = []
457
+ try {
458
+ names = (await readdir(p.runsDir)).filter((n) => n.endsWith('.json'))
459
+ } catch {
460
+ return []
461
+ }
462
+ const rows = []
463
+ for (const name of names) {
464
+ const disk = await readJson(path.join(p.runsDir, name))
465
+ if (disk.state !== 'ok' || !isPlainObject(disk.value)) continue
466
+ if (flowId !== undefined && flowId !== null && flowId !== '' && disk.value.flowId !== flowId) continue
467
+ rows.push(summaryOfRun(disk.value))
468
+ }
469
+ rows.sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt)))
470
+ return rows.slice(0, Math.max(1, Math.min(Number(limit) > 0 ? Number(limit) : 20, MAX_RUNS_KEPT)))
471
+ }
472
+
473
+ function summaryOfRun(run) {
474
+ return {
475
+ runId: run.runId,
476
+ flowId: run.flowId,
477
+ flowName: run.flowName,
478
+ flowRevision: run.flowRevision,
479
+ kbId: run.kbId,
480
+ status: run.status,
481
+ startedAt: run.startedAt,
482
+ finishedAt: run.finishedAt ?? null,
483
+ reason: run.reason ?? null,
484
+ error: run.error ?? null,
485
+ landedEntryId: run.landedEntryId ?? null,
486
+ stepDone: arr(run.steps).filter((s) => s.status === 'done').length,
487
+ stepTotal: arr(run.steps).length,
488
+ cached: false,
489
+ }
490
+ }
491
+
492
+ async function pruneRuns(kbId) {
493
+ const p = flowPathsOf(stateDir, kbId)
494
+ let names = []
495
+ try {
496
+ names = (await readdir(p.runsDir)).filter((n) => n.endsWith('.json'))
497
+ } catch {
498
+ return { removed: 0 }
499
+ }
500
+ if (names.length <= MAX_RUNS_KEPT) return { removed: 0 }
501
+ const rows = []
502
+ for (const name of names) {
503
+ const disk = await readJson(path.join(p.runsDir, name))
504
+ rows.push({ name: name, at: disk.state === 'ok' ? String(disk.value.startedAt ?? '') : '' })
505
+ }
506
+ rows.sort((a, b) => a.at.localeCompare(b.at))
507
+ let removed = 0
508
+ for (const row of rows.slice(0, rows.length - MAX_RUNS_KEPT)) {
509
+ await unlink(path.join(p.runsDir, row.name)).catch(() => {})
510
+ removed += 1
511
+ }
512
+ return { removed: removed }
513
+ }
514
+
515
+ // ── 对外:定义 CRUD ──
516
+ async function list(input) {
517
+ const b = await boundKb()
518
+ if (!b.ok) return kbFail(b)
519
+ const r = await readStore(b.kbId)
520
+ if (!r.ok) return fail(r.reason, r.error)
521
+ const includeArchived = input !== undefined && input !== null && input.includeArchived === true
522
+ const runsByFlow = new Map()
523
+ const runs = await listRuns(b.kbId, '', MAX_RUNS_KEPT)
524
+ for (const run of runs) if (!runsByFlow.has(run.flowId)) runsByFlow.set(run.flowId, run)
525
+ const flows = r.store.flows
526
+ .filter((f) => includeArchived || f.archived !== true)
527
+ .map((f) => ({
528
+ id: f.id,
529
+ builtin: f.builtin === true,
530
+ name: f.name,
531
+ triggers: arr(f.triggers),
532
+ description: f.description,
533
+ enabled: f.enabled !== false,
534
+ archived: f.archived === true,
535
+ revision: f.revision,
536
+ execution: f.execution || {},
537
+ stepCount: arr(f.steps).length,
538
+ updatedAt: f.updatedAt,
539
+ lastRun: runsByFlow.get(f.id) ?? null,
540
+ }))
541
+ return {
542
+ ok: true,
543
+ kbId: b.kbId,
544
+ kbPath: b.kbPath,
545
+ schemaVersion: FLOWS_SCHEMA_VERSION,
546
+ count: flows.length,
547
+ includeArchived: includeArchived,
548
+ flows: flows,
549
+ activeRuns: Array.from(active.keys()),
550
+ }
551
+ }
552
+
553
+ async function get(id) {
554
+ const b = await boundKb()
555
+ if (!b.ok) return kbFail(b)
556
+ const r = await readStore(b.kbId)
557
+ if (!r.ok) return fail(r.reason, r.error)
558
+ const flow = r.store.flows.find((f) => f.id === str(id))
559
+ if (!flow) return fail('not-found', '没有这个流程:' + str(id), { kbId: b.kbId })
560
+ return { ok: true, kbId: b.kbId, flow: flow }
561
+ }
562
+
563
+ // 页面运行只准备一条完整提示词;执行和实时事件交给普通知识库会话。
564
+ // 不调用 start/run,不创建后台运行记录,也不启动委派或落库。
565
+ async function prepareConversation(input = {}) {
566
+ const b = await boundKb()
567
+ if (!b.ok) return kbFail(b)
568
+ if (input.kbId !== b.kbId) return fail('kb-changed', '绑定的知识库已变化,请刷新流程页面后再运行')
569
+ const found = await get(input.id)
570
+ if (!found.ok) return found
571
+ if (found.kbId !== b.kbId) return fail('kb-changed', '绑定的知识库已变化,请刷新后重试')
572
+ const flow = found.flow
573
+ if (flow.archived === true) return fail('archived', '该流程已归档:恢复后才能运行')
574
+ if (flow.enabled === false) return fail('disabled', '该流程已停用:启用后才能运行')
575
+ if (flow.revision !== input.expectedRevision) return fail('flow-changed', '流程定义已变化,请刷新页面后再运行')
576
+ const configured = input.execution === undefined ? (flow.execution || {}) : input.execution
577
+ const execution = flow.builtin ? (configured?.provider && configured?.model ? { provider: configured.provider, model: configured.model, reasoningEffort: 'high' } : {}) : configured
578
+ const executionErrors = validateFlow({ ...flow, execution })
579
+ if (executionErrors.length) return fail('invalid-flow', executionErrors.join(';'))
580
+ const running = active.get(flow.id)
581
+ if (running) return fail('flow-busy', '该流程仍有后台任务运行,请等待结束或先取消(' + running.runId + ')')
582
+ const resolved = resolveParams(flow, input.params)
583
+ if (!resolved.ok) return fail('missing-param', '缺少必填参数:' + resolved.missing.join('、'))
584
+ const route = Object.fromEntries(['provider', 'model', 'reasoningEffort'].filter(key => str(execution?.[key])).map(key => [key, str(execution[key])]))
585
+ // The knowledge Agent and plugin own the operating rules. This button only
586
+ // supplies the user's task, without the generic custom-flow prompt wrapper.
587
+ if (flow.builtin) return { ok: true, kbId: b.kbId, kbPath: b.kbPath, cwd: b.kbPath, flowId: flow.id, flowRevision: flow.revision, execution: route, requiredReasoningEffort: 'high', prompt: flow.steps[0].instruction }
588
+ const rules = flow.outputRules
589
+ const windowDays = Number(rules.windowDays) || 7
590
+ const tz = rules.tz || 'Asia/Shanghai'
591
+ const end = Date.now()
592
+ const lines = [
593
+ `请在本会话中直接执行知识库流程「${flow.name}」(${flow.id},定义版本 v${flow.revision})。`,
594
+ `知识库身份:${b.kbId}`,
595
+ `用途:${flow.description || '按以下步骤完成任务'}`,
596
+ '先用 kb_status 核对当前绑定的 kbId;与上述身份不一致时停止并说明原因。',
597
+ '执行前核对已有产出和未结束的同名任务,避免重复写入或重复外发。',
598
+ '按顺序在本会话中执行以下全部步骤。开始每一步时说明步骤序号和当前动作,完成后展示实际结果;工具调用和输出留在本会话中。',
599
+ '不要调用 kb_flow 的 run,也不要把整个流程再次交给后台流程引擎或子代理。遇到错误、缺少参数或需确认的操作时,在本会话说明并等待处理;不得假报成功或自动重试有副作用的动作。',
600
+ '【本次参数】',
601
+ JSON.stringify(resolved.values, null, 2),
602
+ `【默认时间窗】${fmtInTz(new Date(end - windowDays * 86400_000).toISOString(), tz)} → ${fmtInTz(new Date(end).toISOString(), tz)}(${tz},最近 ${windowDays} 天;步骤中另有明确时间要求时按该要求执行)`,
603
+ '【依次执行】',
604
+ ]
605
+ flow.steps.forEach((step, index) => {
606
+ lines.push(`第 ${index + 1}/${flow.steps.length} 步:${step.title}`)
607
+ if (step.capability) lines.push(`步骤能力:${step.capability}`)
608
+ lines.push(step.instruction, '')
609
+ })
610
+ lines.push('【输出规则】', JSON.stringify(rules, null, 2))
611
+ lines.push(flow.builtin ? '请按步骤实际创建或更新归档知识条目,保留来源和原件;整理汇总保留在本会话,不额外创建一份汇总条目。'
612
+ : rules.land === true
613
+ ? '只有全部步骤成功后,才按上述输出规则通过知识库条目工具写入最终成果;失败、取消或等待确认时不写成功报告。完成后给出条目位置和实际产出。'
614
+ : '最终成果保留在本会话,不额外创建知识库条目。')
615
+ return { ok: true, kbId: b.kbId, kbPath: b.kbPath, cwd: b.kbPath, flowId: flow.id, flowRevision: flow.revision, execution: route, requiredReasoningEffort: flow.builtin ? 'high' : undefined, prompt: lines.join('\n') }
616
+ }
617
+
618
+ /**
619
+ * 新建或更新。更新必须带 expectedRevision(数字)。
620
+ * conflict 时**不写盘**,并返回当前 revision 与差异摘要。
621
+ */
622
+ async function setExecution(input = {}) {
623
+ const b = await boundKb()
624
+ if (!b.ok) return kbFail(b)
625
+ if (input.kbId !== b.kbId) return fail('kb-changed', '绑定的知识库已变化,请刷新后再保存配置')
626
+ const r = await readStore(b.kbId)
627
+ if (!r.ok) return fail(r.reason, r.error)
628
+ const flow = r.store.flows.find(f => f.id === str(input.id))
629
+ if (!flow) return fail('not-found', '没有这个流程')
630
+ if (flow.revision !== input.expectedRevision) return fail('conflict', '流程已变化,请刷新后重新设置', { conflict: true, currentRevision: flow.revision })
631
+ if (!isPlainObject(input.execution)) return fail('invalid-flow', '执行配置必须是对象')
632
+ const errors = validateFlow({ ...flow, execution: input.execution })
633
+ if (errors.length) return fail('invalid-flow', errors.join(';'))
634
+ const execution = Object.fromEntries(['provider', 'model', 'reasoningEffort'].filter(key => str(input.execution[key])).map(key => [key, str(input.execution[key])]))
635
+ if (flow.builtin && execution.model) execution.reasoningEffort = 'high'
636
+ const next = { ...flow, execution, revision: flow.revision + 1, updatedAt: nowIso() }
637
+ await writeStore(b.kbId, { flows: r.store.flows.map(f => f.id === next.id ? next : f) }, r.paths)
638
+ return { ok: true, kbId: b.kbId, flow: next, revision: next.revision }
639
+ }
640
+
641
+ async function save(input) {
642
+ const b = await boundKb()
643
+ if (!b.ok) return kbFail(b)
644
+ const r = await readStore(b.kbId)
645
+ if (!r.ok) return fail(r.reason, r.error)
646
+ const payload = isPlainObject(input) && isPlainObject(input.flow) ? input.flow : isPlainObject(input) ? input : null
647
+ if (payload === null) return fail('bad-flow', 'save 需要 flow 对象')
648
+ const errors = validateFlow(payload)
649
+ if (errors.length > 0) return fail('invalid-flow', '流程定义不合法:' + errors.join(';'), { errors: errors })
650
+ const wantId = str(payload.id)
651
+ if (wantId === 'builtin-inbox-organize') return fail('builtin-flow', '内置整理流程不可修改或删除')
652
+ const exist = wantId === '' ? null : r.store.flows.find((f) => f.id === wantId) ?? null
653
+ const expected = input !== null && input !== undefined && input.expectedRevision !== undefined && input.expectedRevision !== null
654
+ ? Number(input.expectedRevision)
655
+ : (payload.expectedRevision !== undefined && payload.expectedRevision !== null ? Number(payload.expectedRevision) : null)
656
+
657
+ if (exist !== null) {
658
+ if (!Number.isFinite(expected)) return fail('revision-required', '更新流程必须带 expectedRevision(先 list/get 取当前 revision)', { currentRevision: exist.revision })
659
+ if (Number(exist.revision) !== Number(expected)) {
660
+ return fail('conflict', `版本不符(期望 ${expected},当前 ${exist.revision}):为避免覆盖别人刚改的定义,本次未写盘`, {
661
+ currentRevision: exist.revision,
662
+ conflict: true,
663
+ current: { id: exist.id, name: exist.name, revision: exist.revision, updatedAt: exist.updatedAt },
664
+ })
665
+ }
666
+ } else if (wantId !== '' && (input.createIfMissing !== true)) {
667
+ return fail('not-found', '没有这个流程:' + wantId + '(新建请省略 id)')
668
+ }
669
+
670
+ const merged = Object.assign({}, exist || {}, payload, {
671
+ outputRules: Object.assign({}, exist ? exist.outputRules : {}, payload.outputRules || {}),
672
+ id: exist !== null ? exist.id : wantId,
673
+ revision: exist !== null ? Number(exist.revision) + 1 : 1,
674
+ createdAt: exist !== null ? exist.createdAt : undefined,
675
+ // Archive/restore has a separate endpoint; an edit must not restore a flow.
676
+ archived: exist !== null ? exist.archived === true : payload.archived === true,
677
+ })
678
+ const flow = normalizeFlow(merged)
679
+ if (flow.archived) flow.enabled = false
680
+ if (exist && Object.hasOwn(exist, 'enabledBeforeArchive')) flow.enabledBeforeArchive = exist.enabledBeforeArchive
681
+ const next = exist !== null
682
+ ? r.store.flows.map((f) => (f.id === flow.id ? flow : f))
683
+ : r.store.flows.concat([flow])
684
+ await writeStore(b.kbId, { flows: next }, r.paths)
685
+ log('info', `流程${exist !== null ? '更新' : '新建'} ${flow.id}「${flow.name}」→ v${flow.revision}`)
686
+ return { ok: true, kbId: b.kbId, flow: flow, created: exist === null, revision: flow.revision }
687
+ }
688
+
689
+ async function setEnabled(id, enabled) {
690
+ if (str(id) === 'builtin-inbox-organize') return fail('builtin-flow', '内置整理流程保持可用')
691
+ const b = await boundKb()
692
+ if (!b.ok) return kbFail(b)
693
+ const r = await readStore(b.kbId)
694
+ if (!r.ok) return fail(r.reason, r.error)
695
+ const flow = r.store.flows.find((f) => f.id === str(id))
696
+ if (!flow) return fail('not-found', '没有这个流程:' + str(id))
697
+ if (flow.archived === true) return fail('archived', '该流程已归档:请先恢复,再启用或停用')
698
+ const next = Object.assign({}, flow, { enabled: enabled === true, revision: Number(flow.revision) + 1, updatedAt: nowIso() })
699
+ await writeStore(b.kbId, { flows: r.store.flows.map((f) => (f.id === next.id ? next : f)) }, r.paths)
700
+ return { ok: true, kbId: b.kbId, id: next.id, enabled: next.enabled, revision: next.revision }
701
+ }
702
+
703
+ /** 软删除:archived=true。定义与运行记录都留着,可恢复;从可触发列表移除。 */
704
+ async function archive(id, restored) {
705
+ if (str(id) === 'builtin-inbox-organize') return fail('builtin-flow', '内置整理流程不可删除')
706
+ const b = await boundKb()
707
+ if (!b.ok) return kbFail(b)
708
+ const r = await readStore(b.kbId)
709
+ if (!r.ok) return fail(r.reason, r.error)
710
+ const flow = r.store.flows.find((f) => f.id === str(id))
711
+ if (!flow) return fail('not-found', '没有这个流程:' + str(id))
712
+ // 归档时把"原本是否启用"记下来,恢复时原样还回去(否则恢复后仍是停用,等于恢复了个不可用的流程)
713
+ const enabledBefore = flow.archived === true ? (flow.enabledBeforeArchive !== false) : (flow.enabled !== false)
714
+ const next = Object.assign({}, flow, {
715
+ archived: restored === true ? false : true,
716
+ enabled: restored === true ? enabledBefore : false,
717
+ enabledBeforeArchive: enabledBefore,
718
+ revision: Number(flow.revision) + 1,
719
+ updatedAt: nowIso(),
720
+ })
721
+ await writeStore(b.kbId, { flows: r.store.flows.map((f) => (f.id === next.id ? next : f)) }, r.paths)
722
+ return { ok: true, kbId: b.kbId, id: next.id, archived: next.archived, restored: restored === true, revision: next.revision }
723
+ }
724
+
725
+ async function resolve(text) {
726
+ const b = await boundKb()
727
+ if (!b.ok) return kbFail(b)
728
+ const r = await readStore(b.kbId)
729
+ if (!r.ok) return fail(r.reason, r.error)
730
+ const res = matchTriggers(r.store.flows, text)
731
+ return Object.assign({ ok: true, kbId: b.kbId }, res)
732
+ }
733
+
734
+ // ── 对外:运行 ──
735
+ function makeRun(flow, runId, kbId, params, window) {
736
+ return {
737
+ schemaVersion: FLOWS_SCHEMA_VERSION,
738
+ runId: runId,
739
+ flowId: flow.id,
740
+ flowName: flow.name,
741
+ flowRevision: Number(flow.revision),
742
+ kbId: kbId,
743
+ target: targetId,
744
+ params: params,
745
+ window: window,
746
+ status: 'running',
747
+ startedAt: nowIso(),
748
+ finishedAt: null,
749
+ steps: arr(flow.steps).map((s) => ({
750
+ id: s.id,
751
+ title: s.title,
752
+ capability: s.capability ?? null,
753
+ retryable: !isSideEffectStep(s),
754
+ status: 'pending',
755
+ attempts: 0,
756
+ startedAt: null,
757
+ finishedAt: null,
758
+ answer: '',
759
+ error: null,
760
+ subagentId: null,
761
+ })),
762
+ retryableSteps: arr(flow.steps).filter((s) => !isSideEffectStep(s)).map((s) => s.id),
763
+ sideEffectSteps: arr(flow.steps).filter((s) => isSideEffectStep(s)).map((s) => s.id),
764
+ landedEntryId: null,
765
+ landedRevision: null,
766
+ reason: null,
767
+ error: null,
768
+ cancelRequestedAt: null,
769
+ }
770
+ }
771
+
772
+ async function runOnce(flow, runId, b, paramsIn, parentAgent, signal, entry) {
773
+ const resolved = resolveParams(flow, paramsIn)
774
+ if (!resolved.ok) {
775
+ const rec = {
776
+ schemaVersion: FLOWS_SCHEMA_VERSION,
777
+ runId: runId,
778
+ flowId: flow.id,
779
+ flowName: flow.name,
780
+ flowRevision: Number(flow.revision),
781
+ kbId: b.kbId,
782
+ target: targetId,
783
+ params: resolved.values,
784
+ window: null,
785
+ status: 'failed',
786
+ startedAt: nowIso(),
787
+ finishedAt: nowIso(),
788
+ steps: [],
789
+ retryableSteps: [],
790
+ sideEffectSteps: [],
791
+ landedEntryId: null,
792
+ reason: 'missing-param',
793
+ error: '缺少必填参数:' + resolved.missing.join('、'),
794
+ cancelRequestedAt: null,
795
+ }
796
+ await writeRun(b.kbId, rec)
797
+ entry.persisted()
798
+ return rec
799
+ }
800
+ const windowDays = Number(flow.outputRules.windowDays) || 7
801
+ const tz = flow.outputRules.tz || 'Asia/Shanghai'
802
+ const startedAt = nowIso()
803
+ const window = {
804
+ startAt: fmtInTz(new Date(Date.now() - windowDays * 86400_000).toISOString(), tz),
805
+ endAt: fmtInTz(new Date().toISOString(), tz),
806
+ tz: tz,
807
+ windowDays: windowDays,
808
+ }
809
+ const rec = makeRun(flow, runId, b.kbId, resolved.values, window)
810
+ rec.startedAt = startedAt
811
+ entry.startedAt = startedAt
812
+ const recordCancellation = () => { rec.cancelRequestedAt ??= nowIso() }
813
+ entry.controller.signal.addEventListener('abort', recordCancellation, { once: true })
814
+ if (entry.controller.signal.aborted) recordCancellation()
815
+ const onAbort = () => entry.controller.abort()
816
+ if (signal !== undefined && signal !== null) {
817
+ if (signal.aborted) entry.controller.abort()
818
+ else signal.addEventListener('abort', onAbort, { once: true })
819
+ }
820
+ active.set(flow.id, entry)
821
+ activeByRun.set(runId, entry)
822
+ const prior = []
823
+ let canceled = false
824
+ let failure = null
825
+ try {
826
+ await writeRun(b.kbId, rec)
827
+ entry.persisted()
828
+ for (let i = 0; i < flow.steps.length; i += 1) {
829
+ const step = flow.steps[i]
830
+ const slot = rec.steps[i]
831
+ if (entry.controller.signal.aborted) {
832
+ canceled = true
833
+ slot.status = 'skipped'
834
+ break
835
+ }
836
+ slot.status = 'running'
837
+ slot.startedAt = nowIso()
838
+ await writeRun(b.kbId, rec)
839
+ const task = buildStepTask(flow, rec, step, i, prior)
840
+ let attempt = 0
841
+ const maxAttempts = slot.retryable ? 2 : 1
842
+ let lastError = null
843
+ while (attempt < maxAttempts) {
844
+ attempt += 1
845
+ slot.attempts = attempt
846
+ try {
847
+ const currentBinding = await boundKb()
848
+ if (!currentBinding.ok || currentBinding.kbId !== b.kbId || path.resolve(currentBinding.kbPath) !== path.resolve(b.kbPath)) {
849
+ throw Object.assign(new Error('流程运行中知识库绑定已改变,停止执行'), { code: 'FLOW_BINDING_CHANGED' })
850
+ }
851
+ const capNow = String(step.capability ?? '').trim().toLowerCase()
852
+ if (capNow === 'parse' || capNow === 'parse.ocr' || capNow === 'parse.asr') {
853
+ if (parseStep === null) {
854
+ throw Object.assign(new Error('解析能力未启用:本插件没有接入解析服务(先安装含解析服务的版本)'), { code: 'PARSE_NOT_ENABLED' })
855
+ }
856
+ const parsed = await parseStep({
857
+ kind: capNow === 'parse.asr' ? 'asr' : capNow === 'parse.ocr' ? 'ocr' : null,
858
+ flow: flow,
859
+ run: rec,
860
+ step: step,
861
+ index: i,
862
+ params: resolved.values,
863
+ signal: entry.controller.signal,
864
+ })
865
+ if (!parsed || parsed.ok !== true) {
866
+ throw new Error('解析步骤失败:' + String((parsed && (parsed.detail || parsed.reason)) || '未给出原因'))
867
+ }
868
+ slot.answer = str(parsed.answer)
869
+ slot.parseJobId = parsed.jobId ?? null
870
+ slot.parseStatus = parsed.status ?? null
871
+ slot.subagentId = null
872
+ slot.status = 'done'
873
+ slot.error = null
874
+ lastError = null
875
+ break
876
+ }
877
+ const delegated = await delegate({
878
+ targetId: targetId,
879
+ task: task,
880
+ kind: isSideEffectStep(step) ? 'write' : 'read',
881
+ context: `流程「${flow.name}」第 ${i + 1}/${flow.steps.length} 步。运行 ${runId},定义版本 v${flow.revision}。`,
882
+ parentAgent: parentAgent ?? null,
883
+ execution: flow.execution || {},
884
+ signal: entry.controller.signal,
885
+ label: 'kb_flow',
886
+ })
887
+ entry.controller.signal.throwIfAborted()
888
+ if (delegated?.ok === false || (delegated?.status && delegated.status !== 'completed' && delegated.status !== 'done')) {
889
+ throw new Error('委派返回失败状态,未接受为步骤产出')
890
+ }
891
+ const answer = str(delegated && delegated.answer)
892
+ if (answer === '') throw new Error('子代理没有产出文本(可能整轮失败,见 outbox 台账)')
893
+ slot.answer = answer
894
+ slot.subagentId = delegated && delegated.subagentId ? String(delegated.subagentId) : null
895
+ slot.status = 'done'
896
+ slot.error = null
897
+ lastError = null
898
+ break
899
+ } catch (error) {
900
+ lastError = String((error && error.message) ?? error)
901
+ if (entry.controller.signal.aborted || error?.code === 'FLOW_BINDING_CHANGED') break
902
+ if (attempt >= maxAttempts) break
903
+ slot.error = lastError
904
+ log('warn', `流程 ${flow.id} 第 ${i + 1} 步失败,准备重试(该步无副作用):${lastError}`)
905
+ }
906
+ }
907
+ slot.finishedAt = nowIso()
908
+ if (slot.status !== 'done') {
909
+ if (entry.controller.signal.aborted) {
910
+ canceled = true
911
+ slot.status = 'skipped'
912
+ } else {
913
+ slot.status = 'failed'
914
+ slot.error = lastError
915
+ failure = { step: i + 1, error: lastError }
916
+ failure.sideEffect = !slot.retryable
917
+ }
918
+ await writeRun(b.kbId, rec)
919
+ break
920
+ }
921
+ prior.push({ index: i, title: step.title, answer: slot.answer })
922
+ await writeRun(b.kbId, rec)
923
+ }
924
+
925
+ if (entry.controller.signal.aborted) canceled = true
926
+ if (canceled) {
927
+ rec.status = 'canceled'
928
+ rec.reason = 'canceled'
929
+ rec.error = '用户取消:未完成步骤已停止,未落库'
930
+ } else if (failure !== null) {
931
+ rec.status = 'failed'
932
+ rec.reason = failure.sideEffect ? 'step-failed-side-effect' : 'step-failed'
933
+ rec.error = `第 ${failure.step} 步失败:${failure.error}${failure.sideEffect ? '(该步有副作用,未自动重试)' : ''}`
934
+ } else {
935
+ // 全部步骤成功 → 按 outputRules 走**现有 core** 落库(不绕过隐私/路径/revision 保护)
936
+ if (flow.outputRules.land === true) {
937
+ const currentBinding = await boundKb()
938
+ if (!currentBinding.ok || currentBinding.kbId !== b.kbId || path.resolve(currentBinding.kbPath) !== path.resolve(b.kbPath)) {
939
+ throw new Error('落库前知识库绑定已改变,报告未写入其他库')
940
+ }
941
+ entry.controller.signal.throwIfAborted()
942
+ entry.committing = true
943
+ // 报告标题的日期按**定义里的时区**取(本地 03:29 时 UTC 还是前一天,实测会差一天)
944
+ const dayLocal = fmtInTz(nowIso(), flow.outputRules.tz || 'Asia/Shanghai').slice(0, 10)
945
+ if (rec.finishedAt === null || rec.finishedAt === '') rec.finishedAt = nowIso()
946
+ const landed = await core.createEntry({
947
+ kind: flow.outputRules.kind,
948
+ title: `${flow.name} 运行报告 ${dayLocal}`,
949
+ content: buildReport(flow, rec),
950
+ tags: arr(flow.outputRules.tags),
951
+ tz: flow.outputRules.tz || 'Asia/Shanghai',
952
+ status: flow.outputRules.status || '生效',
953
+ requestId: 'flow-run-' + runId,
954
+ expectedBinding: { kbId: b.kbId, kbPath: b.kbPath, revision: b.status?.config?.revision ?? null },
955
+ signal: entry.controller.signal,
956
+ })
957
+ if (landed && landed.ok === true) {
958
+ rec.status = 'landed'
959
+ rec.landedEntryId = landed.entryId ?? null
960
+ rec.landedRevision = landed.revision ?? null
961
+ rec.landedPath = landed.path ?? null
962
+ rec.landedPartial = landed.partial === true || landed.indexSynced === false
963
+ } else {
964
+ rec.status = 'failed'
965
+ rec.reason = 'land-failed'
966
+ rec.error = '步骤都跑完了,但落库失败(不算成功):' + String((landed && (landed.detail || landed.reason)) ?? '未知原因')
967
+ }
968
+ } else {
969
+ rec.status = 'done'
970
+ rec.reason = 'not-landed-by-rule'
971
+ }
972
+ }
973
+ } catch (error) {
974
+ rec.status = entry.controller.signal.aborted ? 'canceled' : 'failed'
975
+ rec.reason = rec.status === 'canceled' ? 'canceled' : 'runner-error'
976
+ rec.error = String((error && error.message) ?? error)
977
+ } finally {
978
+ entry.persisted()
979
+ signal?.removeEventListener('abort', onAbort)
980
+ entry.controller.signal.removeEventListener('abort', recordCancellation)
981
+ rec.finishedAt = nowIso()
982
+ active.delete(flow.id)
983
+ activeByRun.delete(runId)
984
+ await writeRun(b.kbId, rec)
985
+ await pruneRuns(b.kbId).catch(() => null)
986
+ log('info', `流程运行 ${runId}(${flow.name} v${flow.revision})结束:${rec.status}`)
987
+ }
988
+ return rec
989
+ }
990
+
991
+ /**
992
+ * 启动一次运行。返回**立即**(后台跑),便于界面轮询进度与取消。
993
+ * · 同一 runId 再次调用 → 直接返回既有记录(deduplicated:true),不会重复执行
994
+ * · 同一流程已有运行未结束 → 拒绝第二个并说明(不排队、不静默覆盖)
995
+ */
996
+ async function start(input) {
997
+ return serialized(stateDir, () => startLocked(input))
998
+ }
999
+
1000
+ async function startLocked(input) {
1001
+ const req = isPlainObject(input) ? input : {}
1002
+ const b = await boundKb()
1003
+ if (!b.ok) return kbFail(b)
1004
+ if (typeof delegate !== 'function') return fail('no-delegate', '委派能力不可用(gateway 未就绪)')
1005
+ const r = await readStore(b.kbId)
1006
+ if (!r.ok) return fail(r.reason, r.error)
1007
+
1008
+ let flow = null
1009
+ if (str(req.id) !== '') flow = r.store.flows.find((f) => f.id === str(req.id)) ?? null
1010
+ if (flow === null && str(req.text) !== '') {
1011
+ const res = matchTriggers(r.store.flows, req.text)
1012
+ if (res.status === 'ambiguous') {
1013
+ return fail('ambiguous', '这句话同时命中多个流程,请选一个再运行', { candidates: res.matched })
1014
+ }
1015
+ if (res.status === 'miss') return fail('no-match', '没有启用中的流程匹配这句话')
1016
+ if (res.guarded === true) return fail('guarded-mention', '这更像"提到"而不是"要求执行":' + res.guardReasons.join(';'), { candidates: res.matched })
1017
+ flow = r.store.flows.find((f) => f.id === res.matched[0].flowId) ?? null
1018
+ }
1019
+ if (flow === null) return fail('not-found', '找不到要运行的流程(给 id 或能命中触发语的一句话)')
1020
+ if (flow.builtin) return fail('conversation-required', '内置整理流程请从收件箱或流程页面新开知识库会话运行(High)')
1021
+ if (flow.archived === true) return fail('archived', '该流程已归档(删除是软删除):恢复后才能运行')
1022
+ if (flow.enabled === false) return fail('disabled', '该流程已停用:启用后才能运行')
1023
+
1024
+ const runId = /^[A-Za-z0-9._-]{1,80}$/.test(str(req.runId))
1025
+ ? str(req.runId)
1026
+ : 'run-' + new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14) + '-' + crypto.randomBytes(3).toString('hex')
1027
+
1028
+ const existing = await readRun(b.kbId, runId)
1029
+ if (existing !== null) {
1030
+ const expectedParams = resolveParams(flow, req.params).values
1031
+ const canonical = value => JSON.stringify(Object.keys(value ?? {}).sort().map(key => [key, String(value[key])]))
1032
+ if (existing.flowId !== flow.id || (req.params !== undefined && canonical(existing.params) !== canonical(expectedParams))) {
1033
+ return fail('run-payload-mismatch', '同一 runId 的流程或参数与已有请求不同,未重复执行')
1034
+ }
1035
+ return { ok: true, deduplicated: true, kbId: b.kbId, runId: runId, run: existing, note: '同一 runId 已有记录:直接返回它,不重复执行(防双击/重试重复)' }
1036
+ }
1037
+ const runningEntry = active.get(flow.id)
1038
+ if (runningEntry !== undefined) {
1039
+ return fail('flow-busy', '该流程已有一个运行未结束(runId=' + runningEntry.runId + '):同一流程不允许并发,请等它结束或先取消', { runningRunId: runningEntry.runId })
1040
+ }
1041
+
1042
+ const resolved = resolveParams(flow, req.params)
1043
+ if (!resolved.ok) return fail('missing-param', '缺少必填参数:' + resolved.missing.join('、'))
1044
+ let persisted
1045
+ const initialRecordWritten = new Promise(resolve => { persisted = resolve })
1046
+ const entry = { runId, controller: new AbortController(), startedAt: nowIso(), persisted, committing: false }
1047
+ active.set(flow.id, entry)
1048
+ activeByRun.set(runId, entry)
1049
+ const promise = runOnce(flow, runId, b, req.params, req.parentAgent ?? null, req.signal ?? null, entry)
1050
+ promise.then(persisted, persisted)
1051
+ promise.catch((error) => log('error', '流程运行异常:' + String((error && error.stack) ?? error)))
1052
+ await initialRecordWritten
1053
+ // 先把"运行中"的记录交给调用方(runOnce 内部会立即写盘一次)
1054
+ const pending = {
1055
+ runId: runId,
1056
+ flowId: flow.id,
1057
+ flowName: flow.name,
1058
+ flowRevision: flow.revision,
1059
+ kbId: b.kbId,
1060
+ status: 'running',
1061
+ startedAt: nowIso(),
1062
+ steps: arr(flow.steps).map((s, i) => ({ id: s.id, title: s.title, status: i === 0 ? 'running' : 'pending' })),
1063
+ promise: promise,
1064
+ }
1065
+ return { ok: true, deduplicated: false, kbId: b.kbId, runId: runId, run: pending }
1066
+ }
1067
+
1068
+ /** 等待式运行(工具调用用;界面用 start + 轮询)。 */
1069
+ async function run(input) {
1070
+ const started = await start(input)
1071
+ if (started.ok !== true) return started
1072
+ if (started.deduplicated === true) return { ok: true, deduplicated: true, runId: started.runId, run: started.run }
1073
+ // 注意:Promise 的 typeof 是 'object',必须判 then,不能判 function(首版就栽在这)
1074
+ const pendingPromise = started.run !== undefined && started.run !== null && started.run.promise !== undefined && typeof started.run.promise.then === 'function'
1075
+ ? started.run.promise
1076
+ : null
1077
+ if (pendingPromise === null) return started
1078
+ const final = await pendingPromise
1079
+ return { ok: final.status === 'done' || final.status === 'landed', runId: final.runId, run: final, status: final.status, reason: final.reason, error: final.error }
1080
+ }
1081
+
1082
+ async function runs(input) {
1083
+ const req = isPlainObject(input) ? input : {}
1084
+ const b = await boundKb()
1085
+ if (!b.ok) return kbFail(b)
1086
+ if (str(req.runId) !== '') {
1087
+ const one = await readRun(b.kbId, req.runId)
1088
+ if (one === null) return fail('not-found', '没有这个运行记录:' + str(req.runId))
1089
+ return { ok: true, kbId: b.kbId, run: one }
1090
+ }
1091
+ const rows = await listRuns(b.kbId, str(req.flowId), Number(req.limit) || 20)
1092
+ return { ok: true, kbId: b.kbId, count: rows.length, runs: rows }
1093
+ }
1094
+
1095
+ /** 取消:真的 abort(不是隐藏 UI),并把记录标成 canceled —— 之后绝不会变成成功。 */
1096
+ async function cancel(runId) {
1097
+ const b = await boundKb()
1098
+ if (!b.ok) return kbFail(b)
1099
+ const id = str(runId)
1100
+ const entry = activeByRun.get(id)
1101
+ if (entry !== undefined) {
1102
+ if (entry.committing) return fail('commit-in-progress', '报告已进入原子落库阶段,不能承诺撤销;请等待最终结果')
1103
+ entry.controller.abort()
1104
+ return { ok: true, kbId: b.kbId, runId: id, canceling: true, note: '已发出取消:正在跑的这一步会被中断,之后的步骤不再开始' }
1105
+ }
1106
+ const rec = await readRun(b.kbId, id)
1107
+ if (rec === null) return fail('not-found', '没有这个运行记录:' + id)
1108
+ if (['done', 'landed', 'failed', 'canceled'].includes(rec.status)) {
1109
+ return fail('not-running', `该运行已结束(status=${rec.status}):没有可取消的东西`, { run: summaryOfRun(rec) })
1110
+ }
1111
+ rec.status = 'canceled'
1112
+ rec.cancelRequestedAt ??= nowIso()
1113
+ rec.reason = 'canceled-implicit'
1114
+ rec.error = '进程内没有这次的执行上下文(可能插件已重启):已标记为取消,不会继续'
1115
+ rec.finishedAt = nowIso()
1116
+ await writeRun(b.kbId, rec)
1117
+ return { ok: true, kbId: b.kbId, runId: id, canceling: false, run: summaryOfRun(rec) }
1118
+ }
1119
+
1120
+ return {
1121
+ list: list,
1122
+ get: get,
1123
+ prepareConversation,
1124
+ save: input => serialized(stateDir, () => save(input)),
1125
+ setExecution: input => serialized(stateDir, () => setExecution(input)),
1126
+ setEnabled: (id, enabled) => serialized(stateDir, () => setEnabled(id, enabled)),
1127
+ archive: (id, restored) => serialized(stateDir, () => archive(id, restored)),
1128
+ resolve: resolve,
1129
+ start: start,
1130
+ run: run,
1131
+ runs: runs,
1132
+ cancel: cancel,
1133
+ activeRuns: () => Array.from(active.entries()).map(([flowId, entry]) => ({ flowId: flowId, runId: entry.runId, startedAt: entry.startedAt })),
1134
+ _internal: { boundKb: boundKb, readStore: readStore, matchTriggers: matchTriggers },
1135
+ }
1136
+ }