lantern-harness 0.1.45 → 0.2.3

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 (274) hide show
  1. package/CHANGELOG.md +242 -0
  2. package/README.md +25 -8
  3. package/builtin/case-backup-contract.mjs +27 -0
  4. package/builtin/case-workflow-contract.mjs +158 -0
  5. package/builtin/session/lh-fs.mjs +93 -4
  6. package/builtin/session/lh-nav-groups.mjs +36 -1
  7. package/builtin/session/mcp-client.mjs +7 -3
  8. package/builtin/session/session-runs.mjs +5 -1
  9. package/builtin/session/skill-validation.mjs +72 -0
  10. package/builtin/session/space-layout.mjs +8 -1
  11. package/builtin/session/space-skills.mjs +758 -0
  12. package/cli/data-root.mjs +21 -4
  13. package/cli/lantern.mjs +26 -1
  14. package/cli/mcp-server.mjs +3733 -0
  15. package/cli/server.mjs +10 -2
  16. package/config/app.defaults.json +4 -2
  17. package/dist/500.html +14 -6
  18. package/dist/_astro/Base.BQf1tZMl.css +1 -0
  19. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dm3O_y-S.js +2 -0
  20. package/dist/_astro/BusinessMapBoard.CYxHcku_.js +5 -0
  21. package/dist/_astro/CaseExecBoard.CK9aGPmH.js +1 -0
  22. package/dist/_astro/CaseExecutionBoard.C94pmIMQ.js +5 -0
  23. package/dist/_astro/CaseGenerateApp.D5xlk9At.js +10 -0
  24. package/dist/_astro/CasesLibrary.BHQC955x.js +21 -0
  25. package/dist/_astro/ChatApp.CIt15w_1.js +1 -0
  26. package/dist/_astro/ChatApp.d4a9R3YS.js +262 -0
  27. package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
  28. package/dist/_astro/DashboardBoard.qgc1s7pG.js +5 -0
  29. package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
  30. package/dist/_astro/DefectSubmitEntry.JI85N1-i.js +2 -0
  31. package/dist/_astro/DocsFileBrowser.z5JZ74cy.js +1 -0
  32. package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.Dg765uHW.js} +1 -1
  33. package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
  34. package/dist/_astro/KnowledgeLibrary.mkShtVun.js +1 -0
  35. package/dist/_astro/LifeKrTasksBoard.DpAwQffE.js +1 -0
  36. package/dist/_astro/LifeKrTodosBoard.BIjPiZ8H.js +1 -0
  37. package/dist/_astro/LifeObjectivesBoard.DYwLHPEG.js +1 -0
  38. package/dist/_astro/LifePlanTypeSelect.CYaziESp.js +1 -0
  39. package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.DIxoWBDA.js} +3 -3
  40. package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.DuFQsMEx.js} +2 -2
  41. package/dist/_astro/LifeStagesBoard.DtOri9EW.js +1 -0
  42. package/dist/_astro/LifeYearCycleSelect.ByJ9-PGg.js +1 -0
  43. package/dist/_astro/LifeYearPlansBoard.BQN07wcv.js +1 -0
  44. package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
  45. package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
  46. package/dist/_astro/NavLibraries.BO4ezcUc.js +1 -0
  47. package/dist/_astro/PluginsPage.B1VeDtLx.js +18 -0
  48. package/dist/_astro/PmBugsBoard.Ddl3kqqt.js +1 -0
  49. package/dist/_astro/PmIterationsBoard.BJN7disI.js +1 -0
  50. package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.D78gWhqk.js} +1 -1
  51. package/dist/_astro/PmProjectsBoard.Bf8VB3t6.js +1 -0
  52. package/dist/_astro/PmRequirementsBoard.CDyNHN2a.js +1 -0
  53. package/dist/_astro/PmRequirementsBoard.DarfGIrL.js +1 -0
  54. package/dist/_astro/PmShared.TOjBbtV8.js +1 -0
  55. package/dist/_astro/ReportsPage.BXGduuY3.js +1 -0
  56. package/dist/_astro/ReqAnalysisBoard.WLtIfBg8.js +39 -0
  57. package/dist/_astro/RequirementBreakdownLibrary.DMoeTeqX.js +2 -0
  58. package/dist/_astro/RequirementsLibrary.Iv7zOqWe.js +1 -0
  59. package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
  60. package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
  61. package/dist/_astro/SettingsDialog.BvDU9EU6.js +1 -0
  62. package/dist/_astro/SlideOverDrawer.CvyB-quk.js +1 -0
  63. package/dist/_astro/SpaceSwitcher.D9bBNQBZ.js +7 -0
  64. package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.DHj25OKN.js} +1 -1
  65. package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
  66. package/dist/_astro/TasksBoard.CXmGdylV.js +1 -0
  67. package/dist/_astro/TemplatesLibrary.DsL2q-wp.js +1 -0
  68. package/dist/_astro/TestReportsLibrary.BBC1TYgP.js +1 -0
  69. package/dist/_astro/TestStatsBoard.VXjP4hu6.js +1 -0
  70. package/dist/_astro/Toast.BydY-X7T.js +1 -0
  71. package/dist/_astro/TodosBoard.-yKgp06M.js +1 -0
  72. package/dist/_astro/UiAutoBoard.BD5ZyLHj.js +3 -0
  73. package/dist/_astro/UiAutoEnvPanel.DrHUOlmH.js +10 -0
  74. package/dist/_astro/UiAutoGenerationDialog.gypq1zP9.js +12 -0
  75. package/dist/_astro/UiAutoProjectsPage.Dhzr09E9.js +3 -0
  76. package/dist/_astro/app-config.BSO5r82v.js +1 -0
  77. package/dist/_astro/app-version.CkDFkv4s.js +1 -0
  78. package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.C4DJiRJs.js} +1 -1
  79. package/dist/_astro/business-map.BiJ85oxm.js +1 -0
  80. package/dist/_astro/business-map.DKwdW1VL.css +1 -0
  81. package/dist/_astro/case-fields.C03NY3zC.js +148 -0
  82. package/dist/_astro/case-gen-run.C4p8uyU3.js +26 -0
  83. package/dist/_astro/case-prompt.ByLTgz4r.js +2 -0
  84. package/dist/_astro/{case-review.TdDs1WFM.js → case-review.BodP2jKm.js} +2 -2
  85. package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.CC2eXegU.js} +2 -2
  86. package/dist/_astro/case-types.BjF1BivA.js +1 -0
  87. package/dist/_astro/case-workflow-contract.BBQ9bbKL.js +1 -0
  88. package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
  89. package/dist/_astro/defect-workbench.DBmohR-y.js +6 -0
  90. package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
  91. package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
  92. package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.CMMErx63.js} +1 -1
  93. package/dist/_astro/i18n.CEWjL5GX.js +7 -0
  94. package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
  95. package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
  96. package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BoyV6R2A.js} +1 -1
  97. package/dist/_astro/plugins.ChGmBEkF.js +1 -0
  98. package/dist/_astro/project-docs.BRgNjXhG.js +1 -0
  99. package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
  100. package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
  101. package/dist/_astro/req-analysis.BLvcktvQ.js +31 -0
  102. package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
  103. package/dist/_astro/{settings.38J2uD5M.js → settings.BojKNwUC.js} +2 -2
  104. package/dist/_astro/space-skills.CPucW8zt.js +1 -0
  105. package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.B28rzu8J.js} +1 -1
  106. package/dist/_astro/story-review.dEBWTeOW.js +7 -0
  107. package/dist/_astro/test-points.BuNgdNcU.js +8 -0
  108. package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
  109. package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
  110. package/dist/_astro/ui-auto.LUcREUMe.js +1 -0
  111. package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.CWc5cQ2q.js} +1 -1
  112. package/dist/business-map/index.html +988 -0
  113. package/dist/case-exec/index.html +15 -7
  114. package/dist/{prompts → case-execution}/index.html +17 -9
  115. package/dist/cases/api/index.html +988 -0
  116. package/dist/cases/automation/index.html +988 -0
  117. package/dist/cases/functional/index.html +988 -0
  118. package/dist/cases/generate/index.html +14 -6
  119. package/dist/cases/index.html +1 -1
  120. package/dist/cases/library/index.html +1 -980
  121. package/dist/cases/other/index.html +988 -0
  122. package/dist/cases/performance/index.html +988 -0
  123. package/dist/dashboard/index.html +15 -7
  124. package/dist/defect-rules/index.html +695 -0
  125. package/dist/defect-submit/index.html +695 -0
  126. package/dist/defect-submit/templates/index.html +695 -0
  127. package/dist/docs/changelog/index.html +289 -52
  128. package/dist/docs/install/index.html +50 -12
  129. package/dist/docs/manual/index.html +230 -82
  130. package/dist/knowledge/index.html +15 -7
  131. package/dist/life/kr-tasks/index.html +15 -7
  132. package/dist/life/kr-todos/index.html +15 -7
  133. package/dist/life/objectives/index.html +15 -7
  134. package/dist/life/reviews/index.html +15 -7
  135. package/dist/life/stages/index.html +15 -7
  136. package/dist/life/year-plans/index.html +15 -7
  137. package/dist/plugins/index.html +15 -7
  138. package/dist/pm/bugs/index.html +15 -7
  139. package/dist/pm/iterations/index.html +15 -7
  140. package/dist/pm/projects/detail/index.html +15 -7
  141. package/dist/pm/projects/index.html +15 -7
  142. package/dist/pm/requirements/index.html +15 -7
  143. package/dist/reports/index.html +15 -7
  144. package/dist/requirement-analysis/index.html +15 -7
  145. package/dist/requirement-breakdowns/index.html +988 -0
  146. package/dist/requirements/index.html +15 -7
  147. package/dist/tasks/index.html +15 -7
  148. package/dist/templates/index.html +15 -7
  149. package/dist/test-automation/index.html +15 -7
  150. package/dist/test-automation/projects/index.html +15 -7
  151. package/dist/test-reports/index.html +15 -7
  152. package/dist/test-stats/index.html +15 -7
  153. package/dist/todos/index.html +15 -7
  154. package/dist/workbench/index.html +14 -6
  155. package/docs/Codex-MCP/351/233/206/346/210/220.md +340 -0
  156. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
  157. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/206/345/210/253/351/207/215/346/236/204/346/226/271/346/241/210.md +88 -0
  158. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +28 -3
  159. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
  160. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +65 -17
  161. package/docs//346/217/222/344/273/266/344/273/223/345/272/223/344/270/216/346/212/200/350/203/275/346/225/264/345/220/210/346/226/271/346/241/210.md +187 -0
  162. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +219 -74
  163. package/lh-plugins/business-map/assistant.mjs +958 -0
  164. package/lh-plugins/business-map/auth-paths.mjs +61 -0
  165. package/lh-plugins/business-map/jobs.mjs +749 -0
  166. package/lh-plugins/business-map/login.mjs +295 -0
  167. package/lh-plugins/business-map/sources.mjs +1014 -0
  168. package/lh-plugins/case-automation/service.mjs +921 -0
  169. package/lh-plugins/case-automation/store.mjs +231 -0
  170. package/lh-plugins/case-automation/tables.mjs +115 -0
  171. package/lh-plugins/case-automation-prompt.mjs +57 -0
  172. package/lh-plugins/case-execution/assets.mjs +180 -0
  173. package/lh-plugins/case-execution/files.mjs +829 -0
  174. package/lh-plugins/case-execution/plans.mjs +318 -0
  175. package/lh-plugins/case-execution/service.mjs +1026 -0
  176. package/lh-plugins/case-execution-prompt.mjs +36 -0
  177. package/lh-plugins/lh-business-map.mjs +2431 -0
  178. package/lh-plugins/lh-case-automation.mjs +169 -0
  179. package/lh-plugins/lh-case-design.mjs +456 -0
  180. package/lh-plugins/lh-case-execution.mjs +356 -0
  181. package/lh-plugins/lh-case-review.mjs +29 -11
  182. package/lh-plugins/lh-config.mjs +13 -0
  183. package/lh-plugins/lh-defect-submit.mjs +989 -0
  184. package/lh-plugins/lh-project-docs.mjs +55 -140
  185. package/lh-plugins/lh-reports.mjs +29 -57
  186. package/lh-plugins/lh-req-analysis.mjs +32 -3
  187. package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
  188. package/lh-plugins/lh-uiauto.mjs +625 -24
  189. package/lh-plugins/plugin-prompts.mjs +20 -15
  190. package/lh-plugins/req-analysis-revision.mjs +24 -0
  191. package/lh-plugins/test-points-prompt.mjs +2 -3
  192. package/lh-plugins/uiauto-adapters/playwright.mjs +44 -4
  193. package/lh-plugins/uiauto-adapters/shared.mjs +4 -0
  194. package/lh-plugins/uiauto-auth-setup.mjs +218 -0
  195. package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
  196. package/lh-plugins/uiauto-explorer/emit-files.mjs +16 -2
  197. package/lh-plugins/uiauto-explorer/ir.mjs +3 -0
  198. package/lh-plugins/uiauto-explorer/merge.mjs +37 -1
  199. package/lh-plugins/uiauto-explorer/navigation-guard.mjs +255 -0
  200. package/lh-plugins/uiauto-explorer/runner.mjs +80 -5
  201. package/lh-plugins/uiauto-explorer/sessions.mjs +334 -18
  202. package/lh-plugins/uiauto-node.mjs +102 -11
  203. package/lh-plugins/uiauto-prompt.mjs +20 -15
  204. package/lh-plugins/uiauto-sso.mjs +407 -0
  205. package/package.json +5 -2
  206. package/skills/case-automation-bridge/SKILL.md +27 -0
  207. package/skills/case-execution/SKILL.md +41 -0
  208. package/skills/lantern-defect-submit/SKILL.md +15 -0
  209. package/skills/lantern-workflow/SKILL.md +95 -0
  210. package/skills/office/SKILL.md +26 -0
  211. package/dist/_astro/Base.Bkt1lrgu.css +0 -1
  212. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js +0 -2
  213. package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
  214. package/dist/_astro/CaseGenerateApp.Be3h5XPG.js +0 -10
  215. package/dist/_astro/CasesLibrary.Buys7Cy-.js +0 -21
  216. package/dist/_astro/ChatApp.D3BheKci.js +0 -227
  217. package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
  218. package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
  219. package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
  220. package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
  221. package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
  222. package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
  223. package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
  224. package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
  225. package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
  226. package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
  227. package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
  228. package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
  229. package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
  230. package/dist/_astro/PluginsPage.C1JnInH4.js +0 -17
  231. package/dist/_astro/PluginsPage.C3eEwy3K.js +0 -1
  232. package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
  233. package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
  234. package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
  235. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
  236. package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
  237. package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
  238. package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
  239. package/dist/_astro/PromptsLibrary.B_SUf47p.js +0 -1
  240. package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
  241. package/dist/_astro/ReqAnalysisBoard.CIZKnCQH.js +0 -39
  242. package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
  243. package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
  244. package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
  245. package/dist/_astro/SettingsDialog.DYdtCvLc.js +0 -1
  246. package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
  247. package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
  248. package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
  249. package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
  250. package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
  251. package/dist/_astro/Toast.BO2NFckG.js +0 -1
  252. package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
  253. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
  254. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
  255. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
  256. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
  257. package/dist/_astro/app-config.DkyjuL-S.js +0 -1
  258. package/dist/_astro/app-version.Cy-5oZO2.js +0 -1
  259. package/dist/_astro/case-fields.CmePqYfh.js +0 -148
  260. package/dist/_astro/case-gen-run.BklG1H8k.js +0 -22
  261. package/dist/_astro/case-types.DlFkbZJN.js +0 -1
  262. package/dist/_astro/dialog.DZHZCe_T.js +0 -1
  263. package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
  264. package/dist/_astro/i18n.D_aOCHSN.js +0 -7
  265. package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
  266. package/dist/_astro/plugins.BRvXWHLe.js +0 -1
  267. package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
  268. package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
  269. package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
  270. package/dist/_astro/req-analysis.B12_MGMQ.js +0 -31
  271. package/dist/_astro/story-review.D2W5tEOY.js +0 -14
  272. package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
  273. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
  274. package/dist/_astro/ui-auto.DMv940x4.js +0 -1
@@ -0,0 +1,958 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const SESSION_VERSION = 1;
6
+ const SCAN_VERSION = 2;
7
+ const MAX_MESSAGES = 100;
8
+ const MAX_EVENTS = 500;
9
+ const MODEL_TIMEOUT_MS = 90_000;
10
+ const MODEL_HEARTBEAT_MS = 5_000;
11
+ const ACTIVE = new Map();
12
+ const CLIENTS = new Map();
13
+
14
+ const str = (value, max = 4000) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
15
+ const now = () => new Date().toISOString();
16
+
17
+ export const assistantDir = (root) =>
18
+ path.join(root, '.lantern', 'local', 'business-map', 'assistant');
19
+
20
+ function safeId(value) {
21
+ const id = str(value, 80);
22
+ if (!/^[A-Za-z0-9_-]+$/.test(id))
23
+ throw Object.assign(new Error('系统编号无效'), { statusCode: 400 });
24
+ return id;
25
+ }
26
+
27
+ function sessionPath(root, systemId) {
28
+ return path.join(assistantDir(root), `${safeId(systemId)}.json`);
29
+ }
30
+
31
+ function checkpointPath(root, systemId) {
32
+ return path.join(assistantDir(root), `${safeId(systemId)}.checkpoint.json`);
33
+ }
34
+
35
+ function readJson(file, fallback) {
36
+ try {
37
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
38
+ } catch {
39
+ return fallback;
40
+ }
41
+ }
42
+
43
+ function writeJson(file, value) {
44
+ fs.mkdirSync(path.dirname(file), { recursive: true });
45
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
46
+ fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
47
+ fs.renameSync(temp, file);
48
+ }
49
+
50
+ function emptySession(system) {
51
+ const at = now();
52
+ return {
53
+ version: SESSION_VERSION,
54
+ systemId: system.id,
55
+ phase: 'directory',
56
+ status: 'idle',
57
+ runId: '',
58
+ seq: 0,
59
+ messages: [],
60
+ events: [],
61
+ progress: {
62
+ stage: 'idle',
63
+ label: '等待开始',
64
+ current: 0,
65
+ total: 0,
66
+ percent: 0,
67
+ indeterminate: false,
68
+ startedAt: '',
69
+ elapsedSeconds: 0,
70
+ },
71
+ proposal: null,
72
+ directoryApplied: false,
73
+ flowApplied: false,
74
+ createdAt: at,
75
+ updatedAt: at,
76
+ };
77
+ }
78
+
79
+ function normalizeSession(raw, system) {
80
+ const base = emptySession(system);
81
+ if (!raw || typeof raw !== 'object') return base;
82
+ return {
83
+ ...base,
84
+ ...raw,
85
+ systemId: system.id,
86
+ phase: raw.phase === 'flow' ? 'flow' : 'directory',
87
+ status: [
88
+ 'idle',
89
+ 'running',
90
+ 'awaiting_confirmation',
91
+ 'stopped',
92
+ 'error',
93
+ 'interrupted',
94
+ ].includes(raw.status)
95
+ ? raw.status
96
+ : 'idle',
97
+ seq: Math.max(0, Number(raw.seq) || 0),
98
+ messages: Array.isArray(raw.messages) ? raw.messages.slice(-MAX_MESSAGES) : [],
99
+ events: Array.isArray(raw.events) ? raw.events.slice(-MAX_EVENTS) : [],
100
+ progress:
101
+ raw.progress && typeof raw.progress === 'object'
102
+ ? {
103
+ stage: str(raw.progress.stage, 80) || 'idle',
104
+ label: str(raw.progress.label, 300) || '等待开始',
105
+ current: Math.max(0, Number(raw.progress.current) || 0),
106
+ total: Math.max(0, Number(raw.progress.total) || 0),
107
+ percent: Math.min(100, Math.max(0, Number(raw.progress.percent) || 0)),
108
+ indeterminate: raw.progress.indeterminate === true,
109
+ startedAt: str(raw.progress.startedAt, 40),
110
+ elapsedSeconds: Math.max(0, Number(raw.progress.elapsedSeconds) || 0),
111
+ }
112
+ : base.progress,
113
+ directoryApplied: raw.directoryApplied === true,
114
+ flowApplied: raw.flowApplied === true,
115
+ };
116
+ }
117
+
118
+ function publicSession(session) {
119
+ return {
120
+ ...session,
121
+ messages: session.messages || [],
122
+ events: session.events || [],
123
+ };
124
+ }
125
+
126
+ function appendMessage(session, message) {
127
+ session.messages.push({
128
+ id: crypto.randomUUID(),
129
+ at: now(),
130
+ ...message,
131
+ });
132
+ session.messages = session.messages.slice(-MAX_MESSAGES);
133
+ }
134
+
135
+ function appendEvent(session, event) {
136
+ session.seq += 1;
137
+ const item = {
138
+ id: crypto.randomUUID(),
139
+ seq: session.seq,
140
+ at: now(),
141
+ ...event,
142
+ };
143
+ session.events.push(item);
144
+ session.events = session.events.slice(-MAX_EVENTS);
145
+ session.updatedAt = now();
146
+ for (const res of CLIENTS.get(session.systemId) || []) {
147
+ if (res.destroyed || res.writableEnded) continue;
148
+ res.write(`data: ${JSON.stringify(item)}\n\n`);
149
+ }
150
+ return item;
151
+ }
152
+
153
+ function setProgress(session, stage, label, current, total, extra = {}) {
154
+ const safeTotal = Math.max(0, Number(total) || 0);
155
+ session.progress = {
156
+ stage,
157
+ label,
158
+ current: Math.max(0, Number(current) || 0),
159
+ total: safeTotal,
160
+ percent: safeTotal
161
+ ? Math.min(100, Math.round((Math.max(0, Number(current) || 0) / safeTotal) * 100))
162
+ : 0,
163
+ indeterminate: extra.indeterminate === true || safeTotal === 0,
164
+ startedAt: extra.startedAt || '',
165
+ elapsedSeconds: Math.max(0, Number(extra.elapsedSeconds) || 0),
166
+ };
167
+ appendEvent(session, {
168
+ type: 'progress',
169
+ title: label,
170
+ detail: safeTotal ? `${session.progress.current}/${safeTotal}` : '',
171
+ progress: session.progress,
172
+ });
173
+ }
174
+
175
+ async function modelWithTimeout(model, settings, messages, signal, timeoutMs) {
176
+ const controller = new AbortController();
177
+ let timedOut = false;
178
+ const abort = () => controller.abort(signal.reason);
179
+ if (signal.aborted) abort();
180
+ else signal.addEventListener('abort', abort, { once: true });
181
+ const timer = setTimeout(() => {
182
+ timedOut = true;
183
+ controller.abort();
184
+ }, timeoutMs);
185
+ try {
186
+ return await model(settings, messages, controller.signal);
187
+ } catch (error) {
188
+ if (timedOut) {
189
+ throw new Error(
190
+ `模型在 ${Math.max(1, Math.round(timeoutMs / 1000))} 秒内没有响应,任务已停止,可检查模型设置后重试`,
191
+ );
192
+ }
193
+ if (signal.aborted) throw signal.reason || error;
194
+ throw error;
195
+ } finally {
196
+ clearTimeout(timer);
197
+ signal.removeEventListener('abort', abort);
198
+ }
199
+ }
200
+
201
+ function compactEvidence(evidence, system) {
202
+ const pages = evidence
203
+ .filter((item) => item.type === 'page')
204
+ .slice(0, 120)
205
+ .map((item) => ({
206
+ sourceId: item.id,
207
+ title: item.title,
208
+ ref: item.ref,
209
+ content: String(item.content || '').slice(0, 1800),
210
+ }));
211
+ return {
212
+ system: {
213
+ id: system.id,
214
+ name: system.name,
215
+ description: system.description,
216
+ entryUrl: system.entryUrl,
217
+ },
218
+ pages,
219
+ };
220
+ }
221
+
222
+ async function callModel(settings, messages, signal) {
223
+ const url = new URL(settings.baseURL.replace(/\/+$/, '') + '/chat/completions');
224
+ const response = await fetch(url, {
225
+ method: 'POST',
226
+ headers: {
227
+ 'Content-Type': 'application/json',
228
+ Authorization: `Bearer ${settings.apiKey}`,
229
+ },
230
+ body: JSON.stringify({
231
+ model: settings.model,
232
+ messages,
233
+ temperature: 0.1,
234
+ response_format: { type: 'json_object' },
235
+ stream: false,
236
+ }),
237
+ signal,
238
+ });
239
+ if (!response.ok) {
240
+ const detail = (await response.text().catch(() => '')).slice(0, 300);
241
+ throw new Error(`模型请求失败(HTTP ${response.status})${detail ? `:${detail}` : ''}`);
242
+ }
243
+ const data = await response.json();
244
+ const content = data.choices?.[0]?.message?.content;
245
+ if (typeof content !== 'string') throw new Error('模型没有返回正文');
246
+ try {
247
+ return {
248
+ value: JSON.parse(content.replace(/^```(?:json)?\s*/, '').replace(/\s*```$/, '')),
249
+ usage: data.usage || {},
250
+ };
251
+ } catch {
252
+ throw new Error('模型结果不是有效 JSON,可在会话中重试');
253
+ }
254
+ }
255
+
256
+ const DIRECTORY_CONTRACT = `你是业务地图功能目录助手。只依据提供的真实菜单、页面目录和证据整理目录树,不得虚构功能。
257
+ 输出 JSON:
258
+ {
259
+ "message": "给用户看的中文说明,简明指出识别范围和待确认项",
260
+ "directories": [{"key":"d1","parentKey":"","name":"一级目录","menuPath":["一级目录"],"entryUrl":""}],
261
+ "functions": [{"name":"功能名","directoryKey":"d1","purpose":"一句话作用","entry":"页面入口","menuPath":["一级目录","功能名"],"evidence":[{"sourceId":"来源ID","quote":"逐字证据"}]}],
262
+ "warnings": ["无法读取或证据不足的说明"]
263
+ }
264
+ 规则:
265
+ - context.menuCatalog 是从系统左侧导航直接提取的菜单清单,是目录顺序的唯一依据。
266
+ - directories 必须按 menuOrder 顺序完整覆盖 menuCatalog;不得自创大分类、合并菜单或按语义重排。
267
+ - menuCatalog 中的每个一级菜单都必须对应一个目录;有子级的菜单必须保留父子路径。重复菜单用不同 key 保留,不得静默丢弃。
268
+ - 只有用户明确要求整理或合并目录时,才允许改变菜单清单的名称、层级或顺序。
269
+ - 菜单名不能直接当功能。功能必须有页面、文档或用户明确说明作为证据。
270
+ - 一个功能只属于一个目录;目录 key 必须唯一,parentKey 必须引用其他目录 key 或为空。
271
+ - 不删除已有目录和功能;本阶段只提交新增或更新草案。
272
+ - 证据 quote 必须逐字来自对应 sourceId 的 content,找不到证据就不要提交该功能。
273
+ - 最多 200 个目录、500 个功能。`;
274
+
275
+ const FLOW_CONTRACT = `你是业务流程图助手。你只能使用已经应用的功能目录和真实页面证据整理业务流程,不得修改目录或虚构功能。
276
+ 输出 JSON:
277
+ {
278
+ "message": "给用户看的中文说明",
279
+ "flows": [{
280
+ "name": "流程名称",
281
+ "result": "最终业务结果",
282
+ "steps": [{
283
+ "n":1,
284
+ "title":"步骤名",
285
+ "role":"执行角色",
286
+ "system":"参与系统",
287
+ "functionId":"功能ID",
288
+ "input":"输入",
289
+ "output":"输出",
290
+ "next":"2",
291
+ "branch":"",
292
+ "manual":false
293
+ }],
294
+ "evidence":[{"sourceId":"来源ID","quote":"逐字证据"}]
295
+ }],
296
+ "warnings":["待确认说明"]
297
+ }
298
+ 规则:
299
+ - 默认覆盖全部已确认功能;用户缩小范围时严格遵守用户范围。
300
+ - 每个系统步骤的 functionId 必须来自给定功能列表;纯人工步骤可留空并设置 manual=true。
301
+ - 按实际顺序编号;未知下一步或分支明确标记并写入 warnings。
302
+ - 证据 quote 必须逐字来自 sourceId 的 content;没有证据的流程不要提交。
303
+ - 不删除已有流程。最多 80 条流程、每条 100 步。`;
304
+
305
+ function normalizeEvidenceRefs(sources, raw) {
306
+ const sourceMap = new Map(sources.map((item) => [item.id, item]));
307
+ const refs = [];
308
+ for (const ref of Array.isArray(raw) ? raw.slice(0, 20) : []) {
309
+ const source = sourceMap.get(str(ref?.sourceId, 80));
310
+ const quote = str(ref?.quote, 2000);
311
+ if (!source || quote.length < 4 || !String(source.content || '').includes(quote)) continue;
312
+ refs.push({
313
+ id: source.id,
314
+ type: 'page',
315
+ title: source.title || source.ref || '页面证据',
316
+ ref: source.ref || '',
317
+ note: quote,
318
+ confidence: 'medium',
319
+ });
320
+ }
321
+ return refs;
322
+ }
323
+
324
+ function normalizeDirectoryProposal(raw, evidence) {
325
+ const directories = [];
326
+ const keyMap = new Map();
327
+ for (const [index, item] of (Array.isArray(raw?.directories) ? raw.directories : [])
328
+ .slice(0, 200)
329
+ .entries()) {
330
+ const name = str(item?.name, 200);
331
+ if (!name) continue;
332
+ let key = str(item?.key, 80) || `d${index + 1}`;
333
+ if (keyMap.has(key)) key = `d${index + 1}_${directories.length}`;
334
+ const directory = {
335
+ key,
336
+ parentKey: str(item?.parentKey, 80),
337
+ name,
338
+ menuPath: Array.isArray(item?.menuPath)
339
+ ? item.menuPath
340
+ .map((part) => str(part, 200))
341
+ .filter(Boolean)
342
+ .slice(0, 20)
343
+ : [name],
344
+ entryUrl: str(item?.entryUrl, 2000),
345
+ };
346
+ keyMap.set(key, directory);
347
+ directories.push(directory);
348
+ }
349
+ for (const directory of directories) {
350
+ if (directory.parentKey && !keyMap.has(directory.parentKey)) directory.parentKey = '';
351
+ }
352
+ const functions = (Array.isArray(raw?.functions) ? raw.functions : [])
353
+ .slice(0, 500)
354
+ .flatMap((item) => {
355
+ const name = str(item?.name, 200);
356
+ if (!name) return [];
357
+ const refs = normalizeEvidenceRefs(evidence, item?.evidence);
358
+ if (!refs.length) return [];
359
+ return [
360
+ {
361
+ name,
362
+ directoryKey: str(item?.directoryKey, 80),
363
+ purpose: str(item?.purpose, 2000),
364
+ entry: str(item?.entry, 1000),
365
+ menuPath: Array.isArray(item?.menuPath)
366
+ ? item.menuPath
367
+ .map((part) => str(part, 200))
368
+ .filter(Boolean)
369
+ .slice(0, 20)
370
+ : [],
371
+ evidence: refs,
372
+ },
373
+ ];
374
+ });
375
+ return {
376
+ kind: 'directory',
377
+ message:
378
+ str(raw?.message, 4000) ||
379
+ `已整理 ${directories.length} 个目录和 ${functions.length} 个功能。`,
380
+ directories,
381
+ functions,
382
+ warnings: (Array.isArray(raw?.warnings) ? raw.warnings : [])
383
+ .map((item) => str(item, 500))
384
+ .filter(Boolean)
385
+ .slice(0, 100),
386
+ };
387
+ }
388
+
389
+ function alignDirectoryProposalToMenu(proposal, menuCatalog) {
390
+ const menuItems = (Array.isArray(menuCatalog) ? menuCatalog : [])
391
+ .map((item, index) => ({
392
+ label: str(item?.label, 200),
393
+ path: (Array.isArray(item?.path) ? item.path : [item?.label])
394
+ .map((part) => str(part, 200))
395
+ .filter(Boolean),
396
+ order: Number.isFinite(Number(item?.order)) ? Number(item.order) : index,
397
+ }))
398
+ .filter((item) => item.label && item.path.length)
399
+ .sort((left, right) => left.order - right.order);
400
+ if (!menuItems.length) return proposal;
401
+
402
+ const normalize = (value) =>
403
+ String(value || '')
404
+ .replace(/\s+/g, '')
405
+ .toLowerCase();
406
+ const pathKey = (parts) => parts.map(normalize).join('/');
407
+ const directories = proposal.directories || [];
408
+ const byKey = new Map(directories.map((directory) => [directory.key, directory]));
409
+ const pathByKey = new Map();
410
+ const resolvePath = (directory, seen = new Set()) => {
411
+ if (!directory || seen.has(directory.key)) return [];
412
+ const cached = pathByKey.get(directory.key);
413
+ if (cached) return cached;
414
+ seen.add(directory.key);
415
+ const parent = directory.parentKey ? byKey.get(directory.parentKey) : null;
416
+ const current = [...resolvePath(parent, seen), directory.name];
417
+ pathByKey.set(directory.key, current);
418
+ return current;
419
+ };
420
+ const existingByPath = new Map();
421
+ for (const directory of directories) {
422
+ const key = pathKey(resolvePath(directory));
423
+ if (key && !existingByPath.has(key)) existingByPath.set(key, directory.key);
424
+ }
425
+
426
+ let sequence = 0;
427
+ let added = 0;
428
+ for (const item of menuItems) {
429
+ let parentKey = '';
430
+ const prefix = [];
431
+ for (const part of item.path) {
432
+ prefix.push(part);
433
+ const key = pathKey(prefix);
434
+ let directory = directories.find((entry) => entry.key === existingByPath.get(key));
435
+ if (!directory) {
436
+ let directoryKey = `menu_${sequence++}`;
437
+ while (byKey.has(directoryKey)) directoryKey = `menu_${sequence++}`;
438
+ directory = {
439
+ key: directoryKey,
440
+ parentKey,
441
+ name: part,
442
+ menuPath: [...prefix],
443
+ entryUrl: '',
444
+ };
445
+ directories.push(directory);
446
+ byKey.set(directory.key, directory);
447
+ pathByKey.set(directory.key, [...prefix]);
448
+ existingByPath.set(key, directory.key);
449
+ added += 1;
450
+ }
451
+ parentKey = directory.key;
452
+ }
453
+ }
454
+
455
+ const rankByPath = new Map();
456
+ for (const item of menuItems) {
457
+ const key = pathKey(item.path);
458
+ rankByPath.set(key, Math.min(rankByPath.get(key) ?? Infinity, item.order));
459
+ }
460
+ const originalIndex = new Map(directories.map((directory, index) => [directory.key, index]));
461
+ directories.sort((left, right) => {
462
+ const leftRank = rankByPath.get(pathKey(resolvePath(left))) ?? 100000;
463
+ const rightRank = rankByPath.get(pathKey(resolvePath(right))) ?? 100000;
464
+ return (
465
+ leftRank - rightRank ||
466
+ (originalIndex.get(left.key) || 0) - (originalIndex.get(right.key) || 0)
467
+ );
468
+ });
469
+ proposal.directories = directories;
470
+ if (added) {
471
+ proposal.warnings = [
472
+ ...(proposal.warnings || []),
473
+ `已按真实系统菜单补充 ${added} 个目录节点,确保菜单顺序和覆盖完整。`,
474
+ ];
475
+ }
476
+ return proposal;
477
+ }
478
+
479
+ function normalizeFlowProposal(raw, evidence, system) {
480
+ const functionNames = new Map(system.functions.map((item) => [item.name, item.id]));
481
+ const functionIds = new Set(system.functions.map((item) => item.id));
482
+ const flows = (Array.isArray(raw?.flows) ? raw.flows : []).slice(0, 80).flatMap((flow) => {
483
+ const name = str(flow?.name, 300);
484
+ if (!name) return [];
485
+ const steps = (Array.isArray(flow?.steps) ? flow.steps : [])
486
+ .slice(0, 100)
487
+ .flatMap((step, index) => {
488
+ const title = str(step?.title, 500);
489
+ if (!title) return [];
490
+ const functionId =
491
+ str(step?.functionId, 64) || functionNames.get(str(step?.functionName, 200)) || '';
492
+ return [
493
+ {
494
+ n: Math.max(1, Number(step?.n) || index + 1),
495
+ title,
496
+ role: str(step?.role, 200),
497
+ system: str(step?.system, 200) || system.name,
498
+ functionId: functionIds.has(functionId) ? functionId : '',
499
+ input: str(step?.input, 1200),
500
+ output: str(step?.output, 1200),
501
+ next: str(step?.next, 100),
502
+ branch: str(step?.branch, 1000),
503
+ branchBroken: Boolean(str(step?.branch, 1000)),
504
+ manual: step?.manual === true || !functionId,
505
+ },
506
+ ];
507
+ });
508
+ if (!steps.length) return [];
509
+ return [
510
+ {
511
+ name,
512
+ result: str(flow?.result, 1000),
513
+ steps,
514
+ evidence: normalizeEvidenceRefs(evidence, flow?.evidence),
515
+ },
516
+ ];
517
+ });
518
+ return {
519
+ kind: 'flow',
520
+ message: str(raw?.message, 4000) || `已整理 ${flows.length} 条业务流程。`,
521
+ flows,
522
+ warnings: (Array.isArray(raw?.warnings) ? raw.warnings : [])
523
+ .map((item) => str(item, 500))
524
+ .filter(Boolean)
525
+ .slice(0, 100),
526
+ };
527
+ }
528
+
529
+ export function createBusinessAssistantService({
530
+ pages,
531
+ applyDirectoryProposal,
532
+ applyFlowProposal,
533
+ model = callModel,
534
+ modelTimeoutMs = MODEL_TIMEOUT_MS,
535
+ modelHeartbeatMs = MODEL_HEARTBEAT_MS,
536
+ }) {
537
+ function load(root, system) {
538
+ const session = normalizeSession(readJson(sessionPath(root, system.id), null), system);
539
+ if (session.status === 'running' && !ACTIVE.has(`${root}\0${system.id}`)) {
540
+ session.status = 'interrupted';
541
+ session.runId = '';
542
+ appendEvent(session, {
543
+ type: 'status',
544
+ title: '上次会话因服务重启中断',
545
+ detail: '会话历史已保留,可以重新发送该阶段指令继续。',
546
+ status: 'interrupted',
547
+ });
548
+ writeJson(sessionPath(root, system.id), session);
549
+ }
550
+ return session;
551
+ }
552
+
553
+ function save(root, session) {
554
+ session.updatedAt = now();
555
+ writeJson(sessionPath(root, session.systemId), session);
556
+ }
557
+
558
+ function get(root, system) {
559
+ return publicSession(load(root, system));
560
+ }
561
+
562
+ async function executeTurn(root, systemId, settings, runId, phase, instruction, refresh) {
563
+ const key = `${root}\0${systemId}`;
564
+ const active = ACTIVE.get(key);
565
+ if (!active || active.runId !== runId) return;
566
+ const system = active.system;
567
+ const session = active.session;
568
+ const signal = active.controller.signal;
569
+ try {
570
+ appendEvent(session, {
571
+ type: 'status',
572
+ title: phase === 'directory' ? '开始识别功能目录' : '开始识别业务流程',
573
+ status: 'running',
574
+ });
575
+ const checkpoint = readJson(checkpointPath(root, systemId), {});
576
+ let catalog = checkpoint.catalog || [];
577
+ let navigation = checkpoint.navigation || [];
578
+ let evidence = checkpoint.evidence || [];
579
+ const needsScan =
580
+ refresh ||
581
+ checkpoint.scanVersion !== SCAN_VERSION ||
582
+ !catalog.length ||
583
+ !evidence.length ||
584
+ checkpoint.phase !== phase ||
585
+ checkpoint.entryUrl !== system.entryUrl;
586
+ if (needsScan) {
587
+ appendEvent(session, {
588
+ type: 'tool',
589
+ title: 'scan_navigation',
590
+ detail: '读取系统菜单和页面,仅执行只读请求',
591
+ status: 'running',
592
+ });
593
+ setProgress(session, 'scan', '正在读取系统菜单和页面', 0, 0);
594
+ const browser = await pages(
595
+ root,
596
+ system,
597
+ {
598
+ sources: { page: { enabled: true } },
599
+ scope: { mode: 'system', targets: [] },
600
+ entryUrl: system.entryUrl,
601
+ pageUrls: [],
602
+ sourceDir: system.sourceDir,
603
+ maxPages: Number(active.maxPages) || 120,
604
+ maxDepth: 6,
605
+ maxChars: 2000000,
606
+ },
607
+ {
608
+ signal,
609
+ onProgress: (_stage, label) => {
610
+ const current = session.events.filter(
611
+ (event) => event.type === 'page' && event.runId === runId,
612
+ ).length;
613
+ appendEvent(session, {
614
+ type: 'page',
615
+ runId,
616
+ title: '已读取页面',
617
+ detail: label,
618
+ });
619
+ setProgress(session, 'scan', '正在读取系统页面', current + 1, 0);
620
+ save(root, session);
621
+ },
622
+ },
623
+ );
624
+ catalog = browser.pages || [];
625
+ navigation = browser.navigation || [];
626
+ evidence = browser.evidence || [];
627
+ const checkpointNext = {
628
+ scanVersion: SCAN_VERSION,
629
+ phase,
630
+ entryUrl: system.entryUrl,
631
+ catalog,
632
+ navigation,
633
+ evidence,
634
+ issues: browser.issues || [],
635
+ updatedAt: now(),
636
+ };
637
+ writeJson(checkpointPath(root, systemId), checkpointNext);
638
+ for (const issue of browser.issues || [])
639
+ appendEvent(session, { type: 'warning', title: '采集说明', detail: issue });
640
+ if (!navigation.length) {
641
+ appendEvent(session, {
642
+ type: 'warning',
643
+ title: '未提取到结构化菜单',
644
+ detail: '页面中没有识别到稳定的侧边导航树,目录草案可能只覆盖当前可见页面。',
645
+ });
646
+ }
647
+ appendEvent(session, {
648
+ type: 'tool',
649
+ title: 'scan_navigation',
650
+ detail: `发现 ${catalog.length} 个页面、${navigation.length} 个菜单,读取 ${evidence.length} 份页面正文`,
651
+ status: 'done',
652
+ });
653
+ } else {
654
+ appendEvent(session, {
655
+ type: 'tool',
656
+ title: 'read_pages',
657
+ detail: `复用 ${catalog.length} 个页面目录、${navigation.length} 个菜单,不重复扫描`,
658
+ status: 'done',
659
+ });
660
+ }
661
+ if (!evidence.length) throw new Error('没有取得可分析页面,请检查登录态、入口或页面权限');
662
+
663
+ const modelStartedAt = Date.now();
664
+ const startedAt = new Date(modelStartedAt).toISOString();
665
+ setProgress(session, 'model', '模型正在生成识别草案', 0, 0, {
666
+ indeterminate: true,
667
+ startedAt,
668
+ });
669
+ appendEvent(session, {
670
+ type: 'tool',
671
+ title: phase === 'directory' ? 'submit_directory_proposal' : 'submit_flow_proposal',
672
+ detail: '模型正在生成可审核草案',
673
+ status: 'running',
674
+ });
675
+ save(root, session);
676
+ const context = {
677
+ instruction,
678
+ phase,
679
+ currentDirectories: system.directories,
680
+ currentFunctions: system.functions.map((item) => ({
681
+ id: item.id,
682
+ name: item.name,
683
+ directoryId: item.directoryId,
684
+ purpose: item.purpose,
685
+ })),
686
+ menuCatalog: navigation
687
+ .map((item, index) => ({
688
+ label: item.label,
689
+ path: item.path,
690
+ depth: item.depth,
691
+ order: Number.isFinite(Number(item.order)) ? Number(item.order) : index,
692
+ }))
693
+ .sort((left, right) => left.order - right.order),
694
+ pageCatalog: catalog.map((item) => ({
695
+ id: item.id,
696
+ title: item.title,
697
+ url: item.url,
698
+ status: item.status,
699
+ menuPath: item.menuPath,
700
+ menuOrder: item.menuOrder,
701
+ actionable: item.actionable,
702
+ contentLength: item.contentLength,
703
+ })),
704
+ previousProposal: session.proposal,
705
+ sources: compactEvidence(evidence, system),
706
+ };
707
+ const heartbeat = setInterval(() => {
708
+ const elapsedSeconds = Math.max(1, Math.round((Date.now() - modelStartedAt) / 1000));
709
+ setProgress(session, 'model', `模型正在生成识别草案(已等待 ${elapsedSeconds} 秒)`, 0, 0, {
710
+ indeterminate: true,
711
+ startedAt,
712
+ elapsedSeconds,
713
+ });
714
+ save(root, session);
715
+ }, modelHeartbeatMs);
716
+ let response;
717
+ try {
718
+ response = await modelWithTimeout(
719
+ model,
720
+ settings,
721
+ [
722
+ {
723
+ role: 'system',
724
+ content:
725
+ (phase === 'directory' ? DIRECTORY_CONTRACT : FLOW_CONTRACT) +
726
+ `\n当前业务系统:${system.name}\n入口:${system.entryUrl || '未配置'}`,
727
+ },
728
+ {
729
+ role: 'user',
730
+ content: JSON.stringify(context),
731
+ },
732
+ ],
733
+ signal,
734
+ modelTimeoutMs,
735
+ );
736
+ } finally {
737
+ clearInterval(heartbeat);
738
+ }
739
+ const elapsedSeconds = Math.max(1, Math.round((Date.now() - modelStartedAt) / 1000));
740
+ setProgress(session, 'model', '模型已返回,正在校验草案', 1, 1, {
741
+ indeterminate: false,
742
+ startedAt,
743
+ elapsedSeconds,
744
+ });
745
+ const proposal =
746
+ phase === 'directory'
747
+ ? alignDirectoryProposalToMenu(
748
+ normalizeDirectoryProposal(response.value, evidence),
749
+ navigation,
750
+ )
751
+ : normalizeFlowProposal(response.value, evidence, system);
752
+ session.proposal = proposal;
753
+ session.status = 'awaiting_confirmation';
754
+ session.runId = '';
755
+ appendMessage(session, {
756
+ role: 'assistant',
757
+ content: proposal.message,
758
+ proposalKind: proposal.kind,
759
+ });
760
+ appendEvent(session, {
761
+ type: 'proposal',
762
+ title: phase === 'directory' ? '功能目录草案已生成' : '业务流程草案已生成',
763
+ detail:
764
+ phase === 'directory'
765
+ ? `${proposal.directories.length} 个目录、${proposal.functions.length} 个功能`
766
+ : `${proposal.flows.length} 条流程`,
767
+ status: 'awaiting_confirmation',
768
+ });
769
+ appendEvent(session, {
770
+ type: 'tool',
771
+ title: phase === 'directory' ? 'submit_directory_proposal' : 'submit_flow_proposal',
772
+ detail: '草案已通过结构校验',
773
+ status: 'done',
774
+ });
775
+ setProgress(session, 'done', '草案等待确认', 1, 1);
776
+ save(root, session);
777
+ } catch (error) {
778
+ const aborted = signal.aborted;
779
+ session.status = aborted ? 'stopped' : 'error';
780
+ session.runId = '';
781
+ appendEvent(session, {
782
+ type: 'error',
783
+ title: aborted ? '识别已停止' : '识别失败',
784
+ detail: aborted ? '可重新发送该阶段指令。' : String(error?.message || error).slice(0, 800),
785
+ status: session.status,
786
+ });
787
+ save(root, session);
788
+ } finally {
789
+ ACTIVE.delete(key);
790
+ }
791
+ }
792
+
793
+ function start(root, system, raw, settings) {
794
+ const key = `${root}\0${system.id}`;
795
+ if (ACTIVE.has(key))
796
+ throw Object.assign(new Error('当前系统已有 AI 回合在运行'), { statusCode: 409 });
797
+ const phase = raw.phase === 'flow' ? 'flow' : 'directory';
798
+ const instruction = str(raw.message, 12000);
799
+ if (!instruction) throw Object.assign(new Error('请输入识别要求'), { statusCode: 400 });
800
+ if (!settings?.baseURL || !settings?.apiKey || !settings?.model)
801
+ throw Object.assign(new Error('请先在模型设置中配置可用模型'), { statusCode: 400 });
802
+ const session = load(root, system);
803
+ if (phase === 'flow' && !session.directoryApplied && !system.functions.length)
804
+ throw Object.assign(new Error('请先识别并应用功能目录,再识别业务流程'), { statusCode: 400 });
805
+ const runId = crypto.randomUUID();
806
+ const controller = new AbortController();
807
+ session.phase = phase;
808
+ session.status = 'running';
809
+ session.runId = runId;
810
+ session.proposal = null;
811
+ session.progress = { stage: 'queued', label: '准备识别', current: 0, total: 0, percent: 0 };
812
+ appendMessage(session, { role: 'user', content: instruction, phase });
813
+ appendEvent(session, {
814
+ type: 'status',
815
+ title: 'AI 回合已启动',
816
+ detail: phase === 'directory' ? '识别功能目录' : '识别业务流程',
817
+ status: 'running',
818
+ });
819
+ save(root, session);
820
+ ACTIVE.set(key, {
821
+ runId,
822
+ controller,
823
+ session,
824
+ system,
825
+ maxPages: raw.maxPages,
826
+ });
827
+ void executeTurn(
828
+ root,
829
+ system.id,
830
+ {
831
+ baseURL: settings.baseURL,
832
+ model: settings.model,
833
+ apiKey: settings.apiKey,
834
+ },
835
+ runId,
836
+ phase,
837
+ instruction,
838
+ raw.refresh === true,
839
+ );
840
+ return publicSession(session);
841
+ }
842
+
843
+ function stop(root, system) {
844
+ const active = ACTIVE.get(`${root}\0${system.id}`);
845
+ if (!active) return get(root, system);
846
+ active.controller.abort();
847
+ return publicSession(active.session);
848
+ }
849
+
850
+ async function apply(root, system, raw) {
851
+ const session = load(root, system);
852
+ if (session.status === 'running')
853
+ throw Object.assign(new Error('请等待当前 AI 回合结束'), { statusCode: 409 });
854
+ if (!session.proposal || session.status !== 'awaiting_confirmation')
855
+ throw Object.assign(new Error('当前没有可应用的 AI 草案'), { statusCode: 400 });
856
+ const kind = session.proposal.kind;
857
+ if (kind === 'flow' && !session.directoryApplied && !system.functions.length)
858
+ throw Object.assign(new Error('请先应用功能目录'), { statusCode: 400 });
859
+ const result =
860
+ kind === 'directory'
861
+ ? applyDirectoryProposal(root, system.id, session.proposal, raw.revision)
862
+ : applyFlowProposal(root, system.id, session.proposal, raw.revision);
863
+ session.status = 'idle';
864
+ session.proposal = null;
865
+ if (kind === 'directory') {
866
+ session.directoryApplied = true;
867
+ session.phase = 'flow';
868
+ } else {
869
+ session.flowApplied = true;
870
+ }
871
+ appendMessage(session, {
872
+ role: 'assistant',
873
+ content:
874
+ kind === 'directory'
875
+ ? `已应用 ${result.applied.directories} 个目录和 ${result.applied.functions} 个功能。可以继续识别业务流程。`
876
+ : `已应用 ${result.applied.flows} 条业务流程。`,
877
+ applied: true,
878
+ });
879
+ appendEvent(session, {
880
+ type: 'status',
881
+ title: kind === 'directory' ? '功能目录已应用' : '业务流程已应用',
882
+ detail:
883
+ kind === 'directory'
884
+ ? `${result.applied.directories} 个目录、${result.applied.functions} 个功能`
885
+ : `${result.applied.flows} 条流程`,
886
+ status: 'completed',
887
+ });
888
+ setProgress(session, 'idle', '等待下一步', 0, 0);
889
+ save(root, session);
890
+ return { session: publicSession(session), store: result.store };
891
+ }
892
+
893
+ function reset(root, system) {
894
+ if (ACTIVE.has(`${root}\0${system.id}`))
895
+ throw Object.assign(new Error('请先停止当前 AI 回合'), { statusCode: 409 });
896
+ const session = emptySession(system);
897
+ session.directoryApplied = system.functions.length > 0;
898
+ writeJson(sessionPath(root, system.id), session);
899
+ return publicSession(session);
900
+ }
901
+
902
+ function subscribe(root, system, after, res) {
903
+ const session = load(root, system);
904
+ res.statusCode = 200;
905
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
906
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
907
+ res.setHeader('Connection', 'keep-alive');
908
+ res.flushHeaders?.();
909
+ for (const event of session.events.filter((item) => item.seq > Math.max(0, after)))
910
+ res.write(`data: ${JSON.stringify(event)}\n\n`);
911
+ if (session.status !== 'running') {
912
+ res.write(
913
+ `data: ${JSON.stringify({
914
+ seq: session.seq,
915
+ type: 'status',
916
+ status: session.status,
917
+ title: '会话状态',
918
+ })}\n\n`,
919
+ );
920
+ res.end();
921
+ return;
922
+ }
923
+ let clients = CLIENTS.get(system.id);
924
+ if (!clients) {
925
+ clients = new Set();
926
+ CLIENTS.set(system.id, clients);
927
+ }
928
+ clients.add(res);
929
+ const heartbeat = setInterval(() => {
930
+ if (!res.destroyed) res.write(': keep-alive\n\n');
931
+ }, 15000);
932
+ const cleanup = () => {
933
+ clearInterval(heartbeat);
934
+ clients?.delete(res);
935
+ };
936
+ res.on('close', cleanup);
937
+ res.on('error', cleanup);
938
+ }
939
+
940
+ function remove(root, systemId) {
941
+ const active = ACTIVE.get(`${root}\0${systemId}`);
942
+ active?.controller.abort();
943
+ ACTIVE.delete(`${root}\0${systemId}`);
944
+ fs.rmSync(sessionPath(root, systemId), { force: true });
945
+ fs.rmSync(checkpointPath(root, systemId), { force: true });
946
+ }
947
+
948
+ function close() {
949
+ for (const active of ACTIVE.values()) active.controller.abort();
950
+ ACTIVE.clear();
951
+ for (const clients of CLIENTS.values()) {
952
+ for (const res of clients) res.end();
953
+ }
954
+ CLIENTS.clear();
955
+ }
956
+
957
+ return { get, start, stop, apply, reset, subscribe, remove, close };
958
+ }