dsh-memu-memory 1.4.2 → 1.4.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 (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,453 +1,506 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
- import { downloadsDir, warn } from './paths.js'
4
- import { record } from './activity-log.js'
5
- import { listLibraries, loadPrivateIndex, loadGlobalIndex, saveGlobalIndex, updatePrivateIndex } from './state.js'
6
- import { commit as memuCommit, listFiles as memuListFiles, forget as memuForget } from './memu.js'
7
- import { getEmbeddingCatalog, prefixesRequireRole, resolveEmbeddingSources } from './embedding-catalog.js'
8
- import { createEmbeddingDownloadManager } from './embedding-download.js'
9
- import { createVectorMigrator } from './vector-migration.js'
10
- import { profileFromCatalog, setRequestedProfile, vectorStatus, assertProfileVerified } from './vector-profile.js'
11
- import { embeddingWorkerManager } from './local-embedding-manager.js'
12
- import { modelIdForRole } from './local-embedding-protocol.js'
13
- import { managedEmbeddingRuntime } from './embedding-runtime.js'
14
-
15
- const root = path.join(downloadsDir(), 'embeddings')
16
- // 受管 runtime 与模型制品分开放:模型在 downloads/embeddings/<id>,运行时在
17
- // downloads/embeddings/runtime/<key>。切换/回滚模型永远不碰运行时目录。
18
- const runtimeRoot = path.join(root, 'runtime')
19
- let downloader
20
- let migrator
21
- let installer
22
- let runtimeJob = null
23
-
24
- function getDownloader() {
25
- return downloader ||= createEmbeddingDownloadManager({ root })
26
- }
27
-
28
- // warn 走 paths.js 的 sink(index.js 装成 ctx.logger.warn):安装失败必须留可观测信号
29
- // (§1 规则 10),但它绝不能把召回一起拖垮——召回仍然 fail-open 到词法。
30
- function getInstaller() {
31
- return installer ||= managedEmbeddingRuntime({ root: runtimeRoot, logger: { warn: message => warn(message) } })
32
- }
33
-
34
- function envRuntimeDir() {
35
- const value = String(process.env.DSH_MEMU_EMBED_RUNTIME_DIR || '').trim()
36
- return value ? path.resolve(value) : null
37
- }
38
-
39
- /** 目录里真的有一套可 require 的运行时吗(不是「env 设了就算」)。 */
40
- export function hasEmbeddingRuntimePackages(dir) {
41
- if (typeof dir !== 'string' || !dir.trim()) return false
42
- try {
43
- return fs.statSync(path.join(path.resolve(dir.trim()), 'node_modules', 'onnxruntime-node', 'package.json')).isFile()
44
- } catch {
45
- return false
46
- }
47
- }
48
-
49
- /**
50
- * 运行时状态 = 受管安装事实 + 用户 env 覆盖事实,两者都如实报告。
51
- * env 指到一个没有运行时的目录时不会被当成 ready,而是回落到受管目录并留 warn。
52
- */
53
- export function localVectorRuntimeStatus(options = {}) {
54
- const env = envRuntimeDir()
55
- const envUsable = env != null && hasEmbeddingRuntimePackages(env)
56
- let status
57
- try {
58
- status = getInstaller().getStatus({ deep: options.deep === true, modelId: options.modelId || null })
59
- } catch (error) {
60
- status = { status: 'unsupported', ready: false, path: null, platform: null, key: null, error: { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_UNVERIFIED'), message: String(error?.message || error) } }
61
- }
62
- if (envUsable) return { ...status, status: 'configured', ready: true, source: 'env', path: env, managedStatus: status.status, error: null }
63
- return { ...status, source: status.status === 'installed' ? 'managed' : null, ...(env ? { envIgnored: true } : {}) }
64
- }
65
-
66
- // The installer owns the live job; pause/stop must survive the moment after the
67
- // abort (when that job is already gone) so the UI can still show the partial bytes
68
- // and let the user switch source before resuming.
69
- export function runtimeStateView() {
70
- const base = localVectorRuntimeStatus()
71
- if (!runtimeJob) return base
72
- const progress = runtimeJob.progress || base.progress || null
73
- if (runtimeJob.status === 'downloading') {
74
- return {
75
- ...base,
76
- status: 'downloading',
77
- ready: false,
78
- path: null,
79
- downloadSource: runtimeJob.source || base.downloadSource || null,
80
- progress: progress ? { ...progress, speedBps: Number(progress.speedBps) || 0 } : null,
81
- }
82
- }
83
- return {
84
- ...base,
85
- status: runtimeJob.status,
86
- ready: false,
87
- path: null,
88
- downloadSource: runtimeJob.source || null,
89
- progress: progress ? { ...progress, speedBps: 0 } : null,
90
- error: runtimeJob.error || null,
91
- }
92
- }
93
-
94
- /**
95
- * 受管安装:只有 confirmed === true 才会联网下载 catalog 里 pin 住的制品。
96
- * action=pause/stop 只中断当前下载并保留 .part;再次 start 会从稳定缓存续传。
97
- */
98
- export async function installLocalVectorRuntime(options = {}) {
99
- const action = String(options.action || 'start')
100
- const installer = getInstaller()
101
- if (action === 'pause' || action === 'stop') {
102
- if (runtimeJob && runtimeJob.status === 'downloading') {
103
- runtimeJob.stopRequested = action === 'stop'
104
- runtimeJob.status = action === 'stop' ? 'stopped' : 'paused'
105
- runtimeJob.progress = runtimeJob.progress ? { ...runtimeJob.progress, speedBps: 0 } : runtimeJob.progress
106
- try { runtimeJob.controller.abort() } catch {}
107
- }
108
- return { runtime: runtimeStateView(), action }
109
- }
110
- if (runtimeJob?.status === 'downloading') {
111
- throw Object.assign(new Error('a managed runtime install is already running'), { code: 'LOCAL_VECTOR_RUNTIME_BUSY' })
112
- }
113
- if (runtimeJob?.run) {
114
- try { await runtimeJob.run } catch {}
115
- }
116
- runtimeJob = null
117
- const controller = new AbortController()
118
- const onExternalAbort = () => controller.abort()
119
- options.signal?.addEventListener?.('abort', onExternalAbort, { once: true })
120
- const job = { status: 'downloading', source: options.source || null, progress: null, controller, stopRequested: false, run: null, error: null }
121
- runtimeJob = job
122
- const run = installer.ensure({
123
- modelId: options.modelId || null,
124
- confirmed: options.confirmed === true,
125
- reuseOnly: options.reuseOnly === true,
126
- source: options.source || null,
127
- signal: controller.signal,
128
- onProgress: (progress) => {
129
- if (runtimeJob === job) job.progress = { ...progress }
130
- try { options.onProgress?.(progress) } catch {}
131
- },
132
- })
133
- job.run = run
134
- try {
135
- const result = await run
136
- job.status = 'installed'
137
- return { runtime: result, state: getLocalVectorState() }
138
- } catch (error) {
139
- if (controller.signal.aborted || error?.code === 'LOCAL_VECTOR_RUNTIME_ABORTED' || error?.name === 'AbortError') {
140
- job.status = job.stopRequested ? 'stopped' : 'paused'
141
- job.progress = job.progress ? { ...job.progress, speedBps: 0 } : job.progress
142
- return { runtime: runtimeStateView(), paused: job.status === 'paused', stopped: job.status === 'stopped' }
143
- }
144
- job.status = 'failed'
145
- job.error = { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_INSTALL_FAILED'), message: String(error?.message || error) }
146
- throw error
147
- } finally {
148
- options.signal?.removeEventListener?.('abort', onExternalAbort)
149
- if (runtimeJob === job && job.status !== 'paused' && job.status !== 'stopped') runtimeJob = null
150
- }
151
- }
152
-
153
- /** 生效的运行时目录:用户显式 env > 已核实的受管目录 > profile 里记录的旧值。 */
154
- function runtimeDirFor(profile) {
155
- const env = envRuntimeDir()
156
- if (env && hasEmbeddingRuntimePackages(env)) return env
157
- if (env) warn('DSH_MEMU_EMBED_RUNTIME_DIR does not contain the managed runtime packages; using the managed runtime instead')
158
- const recorded = typeof profile?.runtimeDir === 'string' && profile.runtimeDir.trim() ? profile.runtimeDir.trim() : ''
159
- if (recorded && hasEmbeddingRuntimePackages(recorded)) return path.resolve(recorded)
160
- const status = getInstaller().getStatus({ modelId: profile?.catalogId || null })
161
- return status.status === 'installed' ? status.path : null
162
- }
163
-
164
- function profileFor(catalogId) {
165
- const id = String(catalogId)
166
- return profileFromCatalog(id, { modelDir: path.join(root, id), runtimeDir: runtimeDirFor({ catalogId: id }) })
167
- }
168
-
169
- function installationFor(id, sharedRuntime = null) {
170
- const status = getDownloader().getStatus(id, { deep: true })
171
- // 所有可用模型 pin 的是同一个受管 runtime;每个模型各走一遍运行时目录树(几百个文件)
172
- // 会让每次 getState 多花几百毫秒。上层已经算过一次就复用。
173
- const runtime = sharedRuntime || localVectorRuntimeStatus({ modelId: id })
174
- const degraded = status.state === 'installed' && status.verified === false
175
- return {
176
- status: degraded ? 'degraded' : status.state,
177
- installed: status.installed === true && !degraded,
178
- verified: status.verified ?? null,
179
- modelDir: status.installed && !degraded ? path.join(root, id) : null,
180
- runtimeDir: runtime.ready ? runtime.path : null,
181
- fingerprintMatches: status.fingerprintMatches ?? null,
182
- error: degraded ? { code: 'EMBEDDING_INSTALL_TAMPERED', message: 'installed embedding files failed deep verification' } : (status.error || null),
183
- progress: status.progress || null,
184
- }
185
- }
186
-
187
- /**
188
- * MemU `commit` 只认 `{ recall_files, resource, user }` 信封(写入与策划路径都走这个形状)。
189
- * 迁移器原先直接把 `{ name, description, ...entry }` 裸对象传进去:MemU 返回成功却一行
190
- * 都没写,随后回读不到 → 每条都 `VECTOR_READBACK_FAILED`,整次重建作废。
191
- */
192
- export function migrationCommitPayload(item) {
193
- const entry = item?.entry || {}
194
- const text = String(entry.content ?? item?.text ?? '')
195
- const title = String(entry.title ?? item?.text ?? item?.id ?? '')
196
- return {
197
- recall_files: [{ name: String(item?.id ?? ''), track: 'memory', description: title.slice(0, 180), content: text }],
198
- resource: [],
199
- user: {},
200
- }
201
- }
202
-
203
- function migratorFor() {
204
- return migrator ||= createVectorMigrator({
205
- listLibraries: () => listLibraries().map(item => item.id),
206
- loadIndex: libraryId => libraryId == null ? loadGlobalIndex() : loadPrivateIndex(libraryId),
207
- commit: ({ db, item, profile }) => {
208
- assertProfileVerified(profile)
209
- return memuCommit({
210
- db,
211
- vectorProfile: profile,
212
- route: 'managed-local',
213
- payload: migrationCommitPayload(item),
214
- })
215
- },
216
- forget: ({ db, itemId }) => memuForget({ db, name: itemId, route: 'managed-local' }),
217
- listFiles: ({ db, profile }) => {
218
- assertProfileVerified(profile)
219
- return memuListFiles({ db, vectorProfile: profile, route: 'managed-local' })
220
- },
221
- clearVectorPending: ({ libraryId, ids }) => {
222
- const wanted = new Set((Array.isArray(ids) ? ids : []).map(String).filter(Boolean))
223
- if (!wanted.size) return
224
- const clear = (index) => {
225
- let touched = 0
226
- for (const id of wanted) {
227
- const entry = index.entries?.[id]
228
- if (entry && entry.vectorPending) { delete entry.vectorPending; touched += 1 }
229
- }
230
- return touched
231
- }
232
- // The global layer is its own index file; a private library has one each. Nothing
233
- // crosses between them, so the scope decides which write path to take.
234
- if (libraryId == null) {
235
- const index = loadGlobalIndex()
236
- if (clear(index)) saveGlobalIndex(index)
237
- return
238
- }
239
- updatePrivateIndex(libraryId, (index) => { clear(index) })
240
- },
241
- })
242
- }
243
-
244
- export function getLocalVectorState() {
245
- const catalog = getEmbeddingCatalog().map(entry => ({
246
- id: entry.id,
247
- displayName: entry.displayName,
248
- availability: entry.availability,
249
- dimension: entry.dimension,
250
- totalBytes: entry.totalBytes,
251
- languages: Array.isArray(entry.languages) ? [...entry.languages] : [],
252
- rolesRequired: prefixesRequireRole(entry),
253
- // 能让用户选的来源(不是目录里写了几个 provider,而是那几个真的固定了 revision)。
254
- // 顺序就是默认顺序:第一个是 download() 不传 provider 时会用的那个。
255
- providers: resolveEmbeddingSources(entry).sources.map(source => ({ id: source.provider, label: source.label })),
256
- pendingReasons: [...(entry.pendingReasons || [])],
257
- license: entry.license?.base || null,
258
- }))
259
- let indexed = null
260
- try { indexed = migratorFor().membership() } catch { indexed = null }
261
- const runtime = runtimeStateView()
262
- return {
263
- catalog,
264
- installations: Object.fromEntries(catalog.map(entry => [entry.id, installationFor(entry.id, runtime)])),
265
- runtime,
266
- // 2026-11-15 扫雷:向量代际缺库显式化——WebUI/RPC 一眼看到哪个库没进向量库、怎么办。
267
- vector: { ...vectorStatus(), indexed, missingLibraries: getMissingVectorLibraries({ status: vectorStatus() }) },
268
- }
269
- }
270
-
271
- export function selectLocalVectorModel(id) {
272
- const status = getDownloader().getStatus(String(id), { deep: true })
273
- if (status.state !== 'installed' || status.verified !== true || status.fingerprintMatches === false) {
274
- const error = new Error('install and verify the local embedding model before selecting it')
275
- error.code = 'LOCAL_VECTOR_MODEL_NOT_INSTALLED'
276
- throw error
277
- }
278
- setRequestedProfile(profileFor(id), { status: 'requested' })
279
- return getLocalVectorState()
280
- }
281
-
282
- export async function downloadLocalVectorModel(id, options = {}) {
283
- const modelId = String(id)
284
- // provider 只影响「从哪个已固定的来源取字节」;落盘前每个文件都按目录 pin 的
285
- // sha256 校验,所以换源不会换向量空间,指纹里也没有 provider。
286
- const result = await getDownloader().download(modelId, {
287
- confirmed: options.confirmed === true,
288
- ...(options.provider ? { provider: String(options.provider) } : {}),
289
- })
290
- return { result, runtime: null, state: getLocalVectorState() }
291
- }
292
-
293
- export async function switchLocalVectorProfile(options = {}) {
294
- const state = vectorStatus()
295
- const requested = state.requested?.catalogId || options.id
296
- if (!requested) throw Object.assign(new Error('select a requested local embedding model first'), { code: 'LOCAL_VECTOR_REQUEST_MISSING' })
297
- const profile = profileFor(requested)
298
- if (!profile.runtimeDir) throw Object.assign(new Error('a verified managed runtime is required before switching local embeddings; install it from the managed vector settings first'), { code: 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE' })
299
- // force:同一个 profile 已经 active 时也重建一代。用于库集合变化(如恢复一个曾归档
300
- // 的库、或首次激活时漏掉了库)后把索引重新追平;不传 force 时保持 already-active
301
- // 的幂等口径(不重建、不重嵌入)。
302
- const result = await migratorFor().switchProfile({ profile, force: options.force === true })
303
- return { result, state: getLocalVectorState() }
304
- }
305
-
306
- export async function rollbackLocalVectorProfile() {
307
- const result = await migratorFor().rollbackProfile()
308
- return { result, state: getLocalVectorState() }
309
- }
310
-
311
- export function abortLocalVectorMigration() {
312
- const result = migratorFor().abortPending()
313
- return { result, state: getLocalVectorState() }
314
- }
315
-
316
- // 2026-11-15 扫雷补强:向量代际缺库的显式探测与自动追平。
317
- // 背景:非空库不在当前代际 databases.libraries 里时(profile 切换/迁移中断时缺席),
318
- // 写入侧 enroll 抛 REBUILD_REQUIRED → commit 降级"仅写索引",召回侧语义腿无 db。
319
- // 之前只有静默降级,用户没有可行动线索;这里给出状态出口 + 一次自动 force 重建。
320
- /** 列出「索引非空但不在当前向量代际」的私有库。空库不算:写入路径的 enroll 会自愈。 */
321
- export function getMissingVectorLibraries({ status = null } = {}) {
322
- const view = status || vectorStatus()
323
- if (view.status !== 'active' || !view.active?.databases) return []
324
- const enrolled = new Set(Object.keys(view.active.databases.libraries || {}))
325
- const missing = []
326
- for (const item of listLibraries()) {
327
- const libraryId = String(item?.id || item || '')
328
- if (!libraryId || libraryId === 'global' || enrolled.has(libraryId)) continue
329
- let entries = 0
330
- try { entries = Object.keys(loadPrivateIndex(libraryId).entries || {}).length } catch { continue }
331
- if (entries > 0) missing.push(libraryId)
332
- }
333
- return missing
334
- }
335
-
336
- // 每个向量代际最多自动重建 2 次(防 embed 端点不可用时空转重试);进程重启后清零,
337
- // 重启后再试一次是可接受的(缺库状态本身就在账上,不会丢)。
338
- const autoRebuildAttempts = new Map()
339
- let autoRebuildInFlight = false
340
-
341
- export function autoRebuildAttemptCount(generation) {
342
- return Number(autoRebuildAttempts.get(generation)) || 0
343
- }
344
-
345
- /**
346
- * 探测到缺库时自动 force 重建向量代际(重嵌入全部库,本地 worker,无 API 费用)。
347
- * 幂等护栏:向量未激活 / 有迁移在途 / 本进程同代际已试过 2 次 / 已有重建在跑 → 跳过。
348
- * 失败不抛——调用方(召回降级分支)是热路径,结果走 activity-log 可观测。
349
- */
350
- export async function maybeAutoRebuildVectorGeneration() {
351
- if (autoRebuildInFlight) return { skipped: 'already-in-flight' }
352
- const view = vectorStatus()
353
- if (view.status !== 'active' || !view.active) return { skipped: 'vector-not-active' }
354
- if (view.pending) return { skipped: 'migration-in-progress' }
355
- const missing = getMissingVectorLibraries({ status: view })
356
- if (!missing.length) return { skipped: 'nothing-missing' }
357
- const generation = view.active.generation
358
- const attempts = Number(autoRebuildAttempts.get(generation)) || 0
359
- if (attempts >= 2) return { skipped: 'attempt-cap-reached', generation, missing }
360
- autoRebuildAttempts.set(generation, attempts + 1)
361
- autoRebuildInFlight = true
362
- try {
363
- warn('vector auto-rebuild: generation ' + generation + ' is missing libraries (' + missing.join(', ') + ') — forcing a shadow rebuild')
364
- record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量代际缺库,自动 force 重建开始', detail: { generation, missing } })
365
- const result = await switchLocalVectorProfile({ id: view.active.profile?.catalogId ?? null, force: true })
366
- record({ kind: 'vector', level: 'info', scope: 'global', message: '向量代际缺库,自动 force 重建结束', detail: { generation, missing, result: result?.result ?? null } })
367
- return { started: true, generation, missing, result: result?.result ?? null }
368
- } catch (error) {
369
- const message = String(error?.message || error)
370
- warn('vector auto-rebuild failed: ' + message)
371
- record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量代际缺库,自动 force 重建失败', detail: { generation, missing, error: message.slice(0, 300) } })
372
- return { started: false, generation, missing, error: message.slice(0, 300) }
373
- } finally {
374
- autoRebuildInFlight = false
375
- }
376
- }
377
-
378
- /**
379
- * 启动 loopback worker 并真的打一次 POST /v1/embeddings:200 + 正确维度 + 有限数值才算就绪。
380
- * 失败一律带 fallback: 'lexical',上游照旧 fail-open,但错误必须留在日志/lastRecallError 里。
381
- */
382
- export async function healthCheckLocalVector(profile, { timeoutMs = 30_000 } = {}) {
383
- const endpoint = await embeddingWorkerManager().acquire(profile)
384
- const url = new URL('/v1/embeddings', endpoint.baseUrl).href
385
- // A profile with different query/document prefixes has no role-less reading: the
386
- // worker refuses a bare model id rather than pick one. Probe it as a document, which
387
- // is what the writing path (and the reindex migration) will ask for.
388
- const servedModel = endpoint.rolesRequired === true ? modelIdForRole(endpoint.model, 'document') : endpoint.model
389
- let response
390
- try {
391
- response = await fetch(url, {
392
- method: 'POST',
393
- headers: { 'content-type': 'application/json', authorization: 'Bearer ' + String(endpoint.token) },
394
- body: JSON.stringify({ model: servedModel, input: ['本地向量健康检查'] }),
395
- signal: AbortSignal.timeout(Math.max(1000, Number(timeoutMs) || 30_000)),
396
- })
397
- } catch (error) {
398
- throw Object.assign(new Error('the local embedding worker did not answer /v1/embeddings: ' + String(error?.message || error)), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical' })
399
- }
400
- if (!response.ok) {
401
- throw Object.assign(new Error('the local embedding worker answered /v1/embeddings with ' + response.status), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical', status: response.status })
402
- }
403
- const payload = await response.json().catch(() => null)
404
- const vector = payload?.data?.[0]?.embedding
405
- const dimension = Array.isArray(vector) ? vector.length : 0
406
- if (!Array.isArray(vector) || dimension !== Number(profile.dimension)) {
407
- throw Object.assign(new Error('the local embedding worker returned no ' + Number(profile.dimension) + '-dimension vector'), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical', dimension })
408
- }
409
- if (!vector.every(value => typeof value === 'number' && Number.isFinite(value))) {
410
- throw Object.assign(new Error('the local embedding worker returned non-finite vector components'), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical' })
411
- }
412
- return { ok: true, path: '/v1/embeddings', status: response.status, model: endpoint.model, dimension }
413
- }
414
-
415
- /**
416
- * 首用引导:runtime 复用(或确认后安装)→ 起 worker → /v1/embeddings 健康检查。
417
- * 没有云端回退:任一环失败都是 typed error + fallback=lexical。
418
- */
419
- export async function bootstrapLocalVector(options = {}) {
420
- const state = vectorStatus()
421
- const catalogId = options.id || state.active?.profile?.catalogId || state.requested?.catalogId || null
422
- if (!catalogId) throw Object.assign(new Error('select a local embedding model before bootstrapping the local runtime'), { code: 'LOCAL_VECTOR_NOT_SELECTED' })
423
- const before = localVectorRuntimeStatus({ modelId: catalogId })
424
- let runtime
425
- if (before.status === 'configured') {
426
- runtime = { status: 'configured', ready: true, source: 'env', path: before.path, reused: true }
427
- } else {
428
- try {
429
- runtime = await getInstaller().ensure({
430
- modelId: catalogId,
431
- confirmed: options.confirmed === true,
432
- reuseOnly: options.confirmed !== true,
433
- signal: options.signal,
434
- onProgress: options.onProgress,
435
- })
436
- } catch (error) {
437
- // 引导失败照旧 fail-open 到词法:错误如实抛出,但必须带上降级标记。
438
- if (error && typeof error === 'object' && error.fallback === undefined) error.fallback = 'lexical'
439
- throw error
440
- }
441
- }
442
- const health = await healthCheckLocalVector(profileFor(catalogId), { timeoutMs: options.timeoutMs })
443
- return { ok: true, runtime: { status: runtime.status, ready: true, path: runtime.path || null, key: runtime.key || null, source: runtime.source || 'managed', reused: runtime.reused === true }, model: health.model, dimension: health.dimension, health, state: getLocalVectorState() }
444
- }
445
-
446
- export async function testLocalVector() {
447
- return bootstrapLocalVector({ confirmed: false })
448
- }
449
-
450
- export function closeLocalVectorService() {
451
- try { getDownloader().dispose() } catch {}
452
- try { getInstaller().abort() } catch {}
453
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { downloadsDir, warn } from './paths.js'
4
+ import { record } from './activity-log.js'
5
+ import { listLibraries, loadPrivateIndex, loadGlobalIndex, saveGlobalIndex, updatePrivateIndex } from './state.js'
6
+ import { commit as memuCommit, listFiles as memuListFiles, forget as memuForget } from './memu.js'
7
+ import { getEmbeddingCatalog, prefixesRequireRole, resolveEmbeddingSources } from './embedding-catalog.js'
8
+ import { createEmbeddingDownloadManager } from './embedding-download.js'
9
+ import { createVectorMigrator } from './vector-migration.js'
10
+ import { profileFromCatalog, setRequestedProfile, vectorStatus, assertProfileVerified } from './vector-profile.js'
11
+ import { embeddingWorkerManager } from './local-embedding-manager.js'
12
+ import { modelIdForRole } from './local-embedding-protocol.js'
13
+ import { managedEmbeddingRuntime } from './embedding-runtime.js'
14
+
15
+ const root = path.join(downloadsDir(), 'embeddings')
16
+ // 受管 runtime 与模型制品分开放:模型在 downloads/embeddings/<id>,运行时在
17
+ // downloads/embeddings/runtime/<key>。切换/回滚模型永远不碰运行时目录。
18
+ const runtimeRoot = path.join(root, 'runtime')
19
+ let downloader
20
+ let migrator
21
+ let installer
22
+ let runtimeJob = null
23
+ // getLocalVectorState 的短缓存(见该函数):只在没有安装/迁移在跑时生效。
24
+ const VIEW_TTL_MS = 1500
25
+ let viewCache = null
26
+ let vectorMutationBusy = 0
27
+
28
+ function getDownloader() {
29
+ return downloader ||= createEmbeddingDownloadManager({ root })
30
+ }
31
+
32
+ // warn 走 paths.js 的 sink(index.js 装成 ctx.logger.warn):安装失败必须留可观测信号
33
+ // (§1 规则 10),但它绝不能把召回一起拖垮——召回仍然 fail-open 到词法。
34
+ function getInstaller() {
35
+ return installer ||= managedEmbeddingRuntime({ root: runtimeRoot, logger: { warn: message => warn(message) } })
36
+ }
37
+
38
+ function envRuntimeDir() {
39
+ const value = String(process.env.DSH_MEMU_EMBED_RUNTIME_DIR || '').trim()
40
+ return value ? path.resolve(value) : null
41
+ }
42
+
43
+ /** 目录里真的有一套可 require 的运行时吗(不是「env 设了就算」)。 */
44
+ export function hasEmbeddingRuntimePackages(dir) {
45
+ if (typeof dir !== 'string' || !dir.trim()) return false
46
+ try {
47
+ return fs.statSync(path.join(path.resolve(dir.trim()), 'node_modules', 'onnxruntime-node', 'package.json')).isFile()
48
+ } catch {
49
+ return false
50
+ }
51
+ }
52
+
53
+ /**
54
+ * 运行时状态 = 受管安装事实 + 用户 env 覆盖事实,两者都如实报告。
55
+ * env 指到一个没有运行时的目录时不会被当成 ready,而是回落到受管目录并留 warn。
56
+ */
57
+ export function localVectorRuntimeStatus(options = {}) {
58
+ const env = envRuntimeDir()
59
+ const envUsable = env != null && hasEmbeddingRuntimePackages(env)
60
+ let status
61
+ try {
62
+ status = getInstaller().getStatus({ deep: options.deep === true, modelId: options.modelId || null })
63
+ } catch (error) {
64
+ status = { status: 'unsupported', ready: false, path: null, platform: null, key: null, error: { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_UNVERIFIED'), message: String(error?.message || error) } }
65
+ }
66
+ if (envUsable) return { ...status, status: 'configured', ready: true, source: 'env', path: env, managedStatus: status.status, error: null }
67
+ return { ...status, source: status.status === 'installed' ? 'managed' : null, ...(env ? { envIgnored: true } : {}) }
68
+ }
69
+
70
+ // The installer owns the live job; pause/stop must survive the moment after the
71
+ // abort (when that job is already gone) so the UI can still show the partial bytes
72
+ // and let the user switch source before resuming.
73
+ export function runtimeStateView() {
74
+ const base = localVectorRuntimeStatus()
75
+ if (!runtimeJob) return base
76
+ const progress = runtimeJob.progress || base.progress || null
77
+ if (runtimeJob.status === 'downloading') {
78
+ return {
79
+ ...base,
80
+ status: 'downloading',
81
+ ready: false,
82
+ path: null,
83
+ downloadSource: runtimeJob.source || base.downloadSource || null,
84
+ progress: progress ? { ...progress, speedBps: Number(progress.speedBps) || 0 } : null,
85
+ }
86
+ }
87
+ return {
88
+ ...base,
89
+ status: runtimeJob.status,
90
+ ready: false,
91
+ path: null,
92
+ downloadSource: runtimeJob.source || null,
93
+ progress: progress ? { ...progress, speedBps: 0 } : null,
94
+ error: runtimeJob.error || null,
95
+ }
96
+ }
97
+
98
+ /**
99
+ * 受管安装:只有 confirmed === true 才会联网下载 catalog 里 pin 住的制品。
100
+ * action=pause/stop 只中断当前下载并保留 .part;再次 start 会从稳定缓存续传。
101
+ */
102
+ export async function installLocalVectorRuntime(options = {}) {
103
+ const action = String(options.action || 'start')
104
+ // 运行时的状态会在这里被改动(开始/暂停/停止),让下一次读取重新算,别把
105
+ // 开始安装前那份缓存当成现状。
106
+ invalidateLocalVectorView()
107
+ const installer = getInstaller()
108
+ if (action === 'pause' || action === 'stop') {
109
+ if (runtimeJob && runtimeJob.status === 'downloading') {
110
+ runtimeJob.stopRequested = action === 'stop'
111
+ runtimeJob.status = action === 'stop' ? 'stopped' : 'paused'
112
+ runtimeJob.progress = runtimeJob.progress ? { ...runtimeJob.progress, speedBps: 0 } : runtimeJob.progress
113
+ try { runtimeJob.controller.abort() } catch {}
114
+ }
115
+ return { runtime: runtimeStateView(), action }
116
+ }
117
+ if (runtimeJob?.status === 'downloading') {
118
+ throw Object.assign(new Error('a managed runtime install is already running'), { code: 'LOCAL_VECTOR_RUNTIME_BUSY' })
119
+ }
120
+ if (runtimeJob?.run) {
121
+ try { await runtimeJob.run } catch {}
122
+ }
123
+ runtimeJob = null
124
+ const controller = new AbortController()
125
+ const onExternalAbort = () => controller.abort()
126
+ options.signal?.addEventListener?.('abort', onExternalAbort, { once: true })
127
+ const job = { status: 'downloading', source: options.source || null, progress: null, controller, stopRequested: false, run: null, error: null }
128
+ runtimeJob = job
129
+ const run = installer.ensure({
130
+ modelId: options.modelId || null,
131
+ confirmed: options.confirmed === true,
132
+ reuseOnly: options.reuseOnly === true,
133
+ source: options.source || null,
134
+ signal: controller.signal,
135
+ onProgress: (progress) => {
136
+ if (runtimeJob === job) job.progress = { ...progress }
137
+ try { options.onProgress?.(progress) } catch {}
138
+ },
139
+ })
140
+ job.run = run
141
+ try {
142
+ const result = await run
143
+ job.status = 'installed'
144
+ if (runtimeJob === job) runtimeJob = null
145
+ invalidateLocalVectorView()
146
+ return { runtime: result, state: getLocalVectorState() }
147
+ } catch (error) {
148
+ if (controller.signal.aborted || error?.code === 'LOCAL_VECTOR_RUNTIME_ABORTED' || error?.name === 'AbortError') {
149
+ job.status = job.stopRequested ? 'stopped' : 'paused'
150
+ job.progress = job.progress ? { ...job.progress, speedBps: 0 } : job.progress
151
+ return { runtime: runtimeStateView(), paused: job.status === 'paused', stopped: job.status === 'stopped' }
152
+ }
153
+ job.status = 'failed'
154
+ job.error = { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_INSTALL_FAILED'), message: String(error?.message || error) }
155
+ throw error
156
+ } finally {
157
+ options.signal?.removeEventListener?.('abort', onExternalAbort)
158
+ if (runtimeJob === job && job.status !== 'paused' && job.status !== 'stopped') runtimeJob = null
159
+ invalidateLocalVectorView()
160
+ }
161
+ }
162
+
163
+ /** 生效的运行时目录:用户显式 env > 已核实的受管目录 > profile 里记录的旧值。 */
164
+ function runtimeDirFor(profile) {
165
+ const env = envRuntimeDir()
166
+ if (env && hasEmbeddingRuntimePackages(env)) return env
167
+ if (env) warn('DSH_MEMU_EMBED_RUNTIME_DIR does not contain the managed runtime packages; using the managed runtime instead')
168
+ const recorded = typeof profile?.runtimeDir === 'string' && profile.runtimeDir.trim() ? profile.runtimeDir.trim() : ''
169
+ if (recorded && hasEmbeddingRuntimePackages(recorded)) return path.resolve(recorded)
170
+ const status = getInstaller().getStatus({ modelId: profile?.catalogId || null })
171
+ return status.status === 'installed' ? status.path : null
172
+ }
173
+
174
+ function profileFor(catalogId) {
175
+ const id = String(catalogId)
176
+ return profileFromCatalog(id, { modelDir: path.join(root, id), runtimeDir: runtimeDirFor({ catalogId: id }) })
177
+ }
178
+
179
+ function installationFor(id, sharedRuntime = null) {
180
+ const status = getDownloader().getStatus(id, { deep: true })
181
+ // 所有可用模型 pin 的是同一个受管 runtime;每个模型各走一遍运行时目录树(几百个文件)
182
+ // 会让每次 getState 多花几百毫秒。上层已经算过一次就复用。
183
+ const runtime = sharedRuntime || localVectorRuntimeStatus({ modelId: id })
184
+ const degraded = status.state === 'installed' && status.verified === false
185
+ return {
186
+ status: degraded ? 'degraded' : status.state,
187
+ installed: status.installed === true && !degraded,
188
+ verified: status.verified ?? null,
189
+ modelDir: status.installed && !degraded ? path.join(root, id) : null,
190
+ runtimeDir: runtime.ready ? runtime.path : null,
191
+ fingerprintMatches: status.fingerprintMatches ?? null,
192
+ error: degraded ? { code: 'EMBEDDING_INSTALL_TAMPERED', message: 'installed embedding files failed deep verification' } : (status.error || null),
193
+ progress: status.progress || null,
194
+ }
195
+ }
196
+
197
+ /**
198
+ * MemU `commit` 只认 `{ recall_files, resource, user }` 信封(写入与策划路径都走这个形状)。
199
+ * 迁移器原先直接把 `{ name, description, ...entry }` 裸对象传进去:MemU 返回成功却一行
200
+ * 都没写,随后回读不到 → 每条都 `VECTOR_READBACK_FAILED`,整次重建作废。
201
+ */
202
+ export function migrationCommitPayload(item) {
203
+ const entry = item?.entry || {}
204
+ const text = String(entry.content ?? item?.text ?? '')
205
+ const title = String(entry.title ?? item?.text ?? item?.id ?? '')
206
+ return {
207
+ recall_files: [{ name: String(item?.id ?? ''), track: 'memory', description: title.slice(0, 180), content: text }],
208
+ resource: [],
209
+ user: {},
210
+ }
211
+ }
212
+
213
+ function migratorFor() {
214
+ return migrator ||= createVectorMigrator({
215
+ listLibraries: () => listLibraries().map(item => item.id),
216
+ loadIndex: libraryId => libraryId == null ? loadGlobalIndex() : loadPrivateIndex(libraryId),
217
+ commit: ({ db, item, profile }) => {
218
+ assertProfileVerified(profile)
219
+ return memuCommit({
220
+ db,
221
+ vectorProfile: profile,
222
+ route: 'managed-local',
223
+ payload: migrationCommitPayload(item),
224
+ })
225
+ },
226
+ forget: ({ db, itemId }) => memuForget({ db, name: itemId, route: 'managed-local' }),
227
+ listFiles: ({ db, profile }) => {
228
+ assertProfileVerified(profile)
229
+ return memuListFiles({ db, vectorProfile: profile, route: 'managed-local' })
230
+ },
231
+ clearVectorPending: ({ libraryId, ids }) => {
232
+ const wanted = new Set((Array.isArray(ids) ? ids : []).map(String).filter(Boolean))
233
+ if (!wanted.size) return
234
+ const clear = (index) => {
235
+ let touched = 0
236
+ for (const id of wanted) {
237
+ const entry = index.entries?.[id]
238
+ if (entry && entry.vectorPending) { delete entry.vectorPending; touched += 1 }
239
+ }
240
+ return touched
241
+ }
242
+ // The global layer is its own index file; a private library has one each. Nothing
243
+ // crosses between them, so the scope decides which write path to take.
244
+ if (libraryId == null) {
245
+ const index = loadGlobalIndex()
246
+ if (clear(index)) saveGlobalIndex(index)
247
+ return
248
+ }
249
+ updatePrivateIndex(libraryId, (index) => { clear(index) })
250
+ },
251
+ })
252
+ }
253
+
254
+ export function getLocalVectorState() {
255
+ const now = Date.now()
256
+ // 完整向量状态包含 catalog、安装记录、代际成员表与缺库扫描,
257
+ // 对设置页的重复查询使用短期缓存以减少读盘。
258
+ // 短 TTL 复用上一次结果;有安装/迁移在跑(vectorMutationBusy / runtimeJob)时
259
+ // 完全不缓存,进度条照旧实时。
260
+ // 只有「真的在下载」的 runtimeJob 才会每帧变(进度);paused/stopped 是静态状态,
261
+ // paused/stopped 不产生下载进度变化,可以继续复用缓存。
262
+ const runtimeMoving = runtimeJob?.status === 'downloading'
263
+ if (!runtimeMoving && vectorMutationBusy === 0 && viewCache && viewCache.until > now) return viewCache.value
264
+ const value = buildLocalVectorState()
265
+ viewCache = (runtimeMoving || vectorMutationBusy > 0) ? null : { until: now + VIEW_TTL_MS, value }
266
+ return value
267
+ }
268
+
269
+ /** 让下一次 getLocalVectorState 重新算(安装/切换/回滚之后必须调)。 */
270
+ export function invalidateLocalVectorView() { viewCache = null }
271
+
272
+ function buildLocalVectorState() {
273
+ const catalog = getEmbeddingCatalog().map(entry => ({
274
+ id: entry.id,
275
+ displayName: entry.displayName,
276
+ availability: entry.availability,
277
+ dimension: entry.dimension,
278
+ totalBytes: entry.totalBytes,
279
+ languages: Array.isArray(entry.languages) ? [...entry.languages] : [],
280
+ rolesRequired: prefixesRequireRole(entry),
281
+ // 能让用户选的来源(不是目录里写了几个 provider,而是那几个真的固定了 revision)。
282
+ // 顺序就是默认顺序:第一个是 download() 不传 provider 时会用的那个。
283
+ providers: resolveEmbeddingSources(entry).sources.map(source => ({ id: source.provider, label: source.label })),
284
+ pendingReasons: [...(entry.pendingReasons || [])],
285
+ license: entry.license?.base || null,
286
+ }))
287
+ let indexed = null
288
+ try { indexed = migratorFor().membership() } catch { indexed = null }
289
+ const runtime = runtimeStateView()
290
+ return {
291
+ catalog,
292
+ installations: Object.fromEntries(catalog.map(entry => [entry.id, installationFor(entry.id, runtime)])),
293
+ runtime,
294
+ // 2026-11-15 扫雷:向量代际缺库显式化——WebUI/RPC 一眼看到哪个库没进向量库、怎么办。
295
+ vector: { ...vectorStatus(), indexed, missingLibraries: getMissingVectorLibraries({ status: vectorStatus() }) },
296
+ }
297
+ }
298
+
299
+ export function selectLocalVectorModel(id) {
300
+ const status = getDownloader().getStatus(String(id), { deep: true })
301
+ if (status.state !== 'installed' || status.verified !== true || status.fingerprintMatches === false) {
302
+ const error = new Error('install and verify the local embedding model before selecting it')
303
+ error.code = 'LOCAL_VECTOR_MODEL_NOT_INSTALLED'
304
+ throw error
305
+ }
306
+ setRequestedProfile(profileFor(id), { status: 'requested' })
307
+ invalidateLocalVectorView()
308
+ return getLocalVectorState()
309
+ }
310
+
311
+ export async function downloadLocalVectorModel(id, options = {}) {
312
+ const modelId = String(id)
313
+ // provider 只影响「从哪个已固定的来源取字节」;落盘前每个文件都按目录 pin 的
314
+ // sha256 校验,所以换源不会换向量空间,指纹里也没有 provider。
315
+ invalidateLocalVectorView()
316
+ vectorMutationBusy += 1
317
+ try {
318
+ const result = await getDownloader().download(modelId, {
319
+ confirmed: options.confirmed === true,
320
+ ...(options.provider ? { provider: String(options.provider) } : {}),
321
+ })
322
+ return { result, runtime: null, state: getLocalVectorState() }
323
+ } finally {
324
+ vectorMutationBusy -= 1
325
+ invalidateLocalVectorView()
326
+ }
327
+ }
328
+
329
+ export async function switchLocalVectorProfile(options = {}) {
330
+ const state = vectorStatus()
331
+ const requested = state.requested?.catalogId || options.id
332
+ if (!requested) throw Object.assign(new Error('select a requested local embedding model first'), { code: 'LOCAL_VECTOR_REQUEST_MISSING' })
333
+ const profile = profileFor(requested)
334
+ if (!profile.runtimeDir) throw Object.assign(new Error('a verified managed runtime is required before switching local embeddings; install it from the managed vector settings first'), { code: 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE' })
335
+ // force:同一个 profile 已经 active 时也重建一代。用于库集合变化(如恢复一个曾归档
336
+ // 的库、或首次激活时漏掉了库)后把索引重新追平;不传 force 时保持 already-active
337
+ // 的幂等口径(不重建、不重嵌入)。
338
+ vectorMutationBusy += 1
339
+ try {
340
+ const result = await migratorFor().switchProfile({ profile, force: options.force === true })
341
+ return { result, state: getLocalVectorState() }
342
+ } finally {
343
+ vectorMutationBusy -= 1
344
+ invalidateLocalVectorView()
345
+ }
346
+ }
347
+
348
+ export async function rollbackLocalVectorProfile() {
349
+ vectorMutationBusy += 1
350
+ try {
351
+ const result = await migratorFor().rollbackProfile()
352
+ return { result, state: getLocalVectorState() }
353
+ } finally {
354
+ vectorMutationBusy -= 1
355
+ invalidateLocalVectorView()
356
+ }
357
+ }
358
+
359
+ export function abortLocalVectorMigration() {
360
+ const result = migratorFor().abortPending()
361
+ // 取消本身就是一个状态变化:不清缓存的话,调用方拿到的回包可能是 1.5s 内那份
362
+ // 「仍在迁移中」的过期视图。
363
+ invalidateLocalVectorView()
364
+ return { result, state: getLocalVectorState() }
365
+ }
366
+
367
+ // 2026-11-15 扫雷补强:向量代际缺库的显式探测与自动追平。
368
+ // 背景:非空库不在当前代际 databases.libraries 里时(profile 切换/迁移中断时缺席),
369
+ // 写入侧 enroll 抛 REBUILD_REQUIRED → commit 降级"仅写索引",召回侧语义腿无 db。
370
+ // 之前只有静默降级,用户没有可行动线索;这里给出状态出口 + 一次自动 force 重建。
371
+ /** 列出「索引非空但不在当前向量代际」的私有库。空库不算:写入路径的 enroll 会自愈。 */
372
+ export function getMissingVectorLibraries({ status = null } = {}) {
373
+ const view = status || vectorStatus()
374
+ if (view.status !== 'active' || !view.active?.databases) return []
375
+ const enrolled = new Set(Object.keys(view.active.databases.libraries || {}))
376
+ const missing = []
377
+ for (const item of listLibraries()) {
378
+ const libraryId = String(item?.id || item || '')
379
+ if (!libraryId || libraryId === 'global' || enrolled.has(libraryId)) continue
380
+ let entries = 0
381
+ try { entries = Object.keys(loadPrivateIndex(libraryId).entries || {}).length } catch { continue }
382
+ if (entries > 0) missing.push(libraryId)
383
+ }
384
+ return missing
385
+ }
386
+
387
+ // 每个向量代际最多自动重建 2 次(防 embed 端点不可用时空转重试);进程重启后清零,
388
+ // 重启后再试一次是可接受的(缺库状态本身就在账上,不会丢)。
389
+ const autoRebuildAttempts = new Map()
390
+ let autoRebuildInFlight = false
391
+
392
+ export function autoRebuildAttemptCount(generation) {
393
+ return Number(autoRebuildAttempts.get(generation)) || 0
394
+ }
395
+
396
+ /**
397
+ * 探测到缺库时自动 force 重建向量代际(重嵌入全部库,本地 worker,无 API 费用)。
398
+ * 幂等护栏:向量未激活 / 有迁移在途 / 本进程同代际已试过 2 次 / 已有重建在跑 → 跳过。
399
+ * 失败不抛——调用方(召回降级分支)是热路径,结果走 activity-log 可观测。
400
+ */
401
+ export async function maybeAutoRebuildVectorGeneration() {
402
+ if (autoRebuildInFlight) return { skipped: 'already-in-flight' }
403
+ const view = vectorStatus()
404
+ if (view.status !== 'active' || !view.active) return { skipped: 'vector-not-active' }
405
+ if (view.pending) return { skipped: 'migration-in-progress' }
406
+ const missing = getMissingVectorLibraries({ status: view })
407
+ if (!missing.length) return { skipped: 'nothing-missing' }
408
+ const generation = view.active.generation
409
+ const attempts = Number(autoRebuildAttempts.get(generation)) || 0
410
+ if (attempts >= 2) return { skipped: 'attempt-cap-reached', generation, missing }
411
+ autoRebuildAttempts.set(generation, attempts + 1)
412
+ autoRebuildInFlight = true
413
+ try {
414
+ warn('vector auto-rebuild: generation ' + generation + ' is missing libraries (' + missing.join(', ') + ') — forcing a shadow rebuild')
415
+ record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量代际缺库,自动 force 重建开始', detail: { generation, missing } })
416
+ const result = await switchLocalVectorProfile({ id: view.active.profile?.catalogId ?? null, force: true })
417
+ record({ kind: 'vector', level: 'info', scope: 'global', message: '向量代际缺库,自动 force 重建结束', detail: { generation, missing, result: result?.result ?? null } })
418
+ return { started: true, generation, missing, result: result?.result ?? null }
419
+ } catch (error) {
420
+ const message = String(error?.message || error)
421
+ warn('vector auto-rebuild failed: ' + message)
422
+ record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量代际缺库,自动 force 重建失败', detail: { generation, missing, error: message.slice(0, 300) } })
423
+ return { started: false, generation, missing, error: message.slice(0, 300) }
424
+ } finally {
425
+ autoRebuildInFlight = false
426
+ }
427
+ }
428
+
429
+ /**
430
+ * 启动 loopback worker 并真的打一次 POST /v1/embeddings:200 + 正确维度 + 有限数值才算就绪。
431
+ * 失败一律带 fallback: 'lexical',上游照旧 fail-open,但错误必须留在日志/lastRecallError 里。
432
+ */
433
+ export async function healthCheckLocalVector(profile, { timeoutMs = 30_000 } = {}) {
434
+ const endpoint = await embeddingWorkerManager().acquire(profile)
435
+ const url = new URL('/v1/embeddings', endpoint.baseUrl).href
436
+ // A profile with different query/document prefixes has no role-less reading: the
437
+ // worker refuses a bare model id rather than pick one. Probe it as a document, which
438
+ // is what the writing path (and the reindex migration) will ask for.
439
+ const servedModel = endpoint.rolesRequired === true ? modelIdForRole(endpoint.model, 'document') : endpoint.model
440
+ let response
441
+ try {
442
+ response = await fetch(url, {
443
+ method: 'POST',
444
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + String(endpoint.token) },
445
+ body: JSON.stringify({ model: servedModel, input: ['本地向量健康检查'] }),
446
+ signal: AbortSignal.timeout(Math.max(1000, Number(timeoutMs) || 30_000)),
447
+ })
448
+ } catch (error) {
449
+ throw Object.assign(new Error('the local embedding worker did not answer /v1/embeddings: ' + String(error?.message || error)), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical' })
450
+ }
451
+ if (!response.ok) {
452
+ throw Object.assign(new Error('the local embedding worker answered /v1/embeddings with ' + response.status), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical', status: response.status })
453
+ }
454
+ const payload = await response.json().catch(() => null)
455
+ const vector = payload?.data?.[0]?.embedding
456
+ const dimension = Array.isArray(vector) ? vector.length : 0
457
+ if (!Array.isArray(vector) || dimension !== Number(profile.dimension)) {
458
+ throw Object.assign(new Error('the local embedding worker returned no ' + Number(profile.dimension) + '-dimension vector'), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical', dimension })
459
+ }
460
+ if (!vector.every(value => typeof value === 'number' && Number.isFinite(value))) {
461
+ throw Object.assign(new Error('the local embedding worker returned non-finite vector components'), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical' })
462
+ }
463
+ return { ok: true, path: '/v1/embeddings', status: response.status, model: endpoint.model, dimension }
464
+ }
465
+
466
+ /**
467
+ * 首用引导:runtime 复用(或确认后安装)→ 起 worker → /v1/embeddings 健康检查。
468
+ * 没有云端回退:任一环失败都是 typed error + fallback=lexical。
469
+ */
470
+ export async function bootstrapLocalVector(options = {}) {
471
+ const state = vectorStatus()
472
+ const catalogId = options.id || state.active?.profile?.catalogId || state.requested?.catalogId || null
473
+ if (!catalogId) throw Object.assign(new Error('select a local embedding model before bootstrapping the local runtime'), { code: 'LOCAL_VECTOR_NOT_SELECTED' })
474
+ const before = localVectorRuntimeStatus({ modelId: catalogId })
475
+ let runtime
476
+ if (before.status === 'configured') {
477
+ runtime = { status: 'configured', ready: true, source: 'env', path: before.path, reused: true }
478
+ } else {
479
+ try {
480
+ runtime = await getInstaller().ensure({
481
+ modelId: catalogId,
482
+ confirmed: options.confirmed === true,
483
+ reuseOnly: options.confirmed !== true,
484
+ signal: options.signal,
485
+ onProgress: options.onProgress,
486
+ })
487
+ } catch (error) {
488
+ // 引导失败照旧 fail-open 到词法:错误如实抛出,但必须带上降级标记。
489
+ if (error && typeof error === 'object' && error.fallback === undefined) error.fallback = 'lexical'
490
+ throw error
491
+ }
492
+ }
493
+ const health = await healthCheckLocalVector(profileFor(catalogId), { timeoutMs: options.timeoutMs })
494
+ return { ok: true, runtime: { status: runtime.status, ready: true, path: runtime.path || null, key: runtime.key || null, source: runtime.source || 'managed', reused: runtime.reused === true }, model: health.model, dimension: health.dimension, health, state: getLocalVectorState() }
495
+ }
496
+
497
+ export async function testLocalVector() {
498
+ return bootstrapLocalVector({ confirmed: false })
499
+ }
500
+
501
+ export function closeLocalVectorService() {
502
+ // 关服务等于放弃本进程这份视图:下一位读者不该读到上个连接留下的状态。
503
+ invalidateLocalVectorView()
504
+ try { getDownloader().dispose() } catch {}
505
+ try { getInstaller().abort() } catch {}
506
+ }