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,946 +1,946 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
- import crypto from 'node:crypto'
4
- import { spawn } from 'node:child_process'
5
- import { ensureDir, readJsonStrict, writeJson } from './paths.js'
6
- import { getEmbeddingCatalog, getEmbeddingModel } from './embedding-catalog.js'
7
-
8
- // §14.13 受管 embedding runtime 安装器。
9
- //
10
- // 目标:用户装好插件、MemU 和已核实的 BGE 制品后,不需要再手写
11
- // DSH_MEMU_EMBED_RUNTIME_DIR,也不需要装 Ollama 之类的第二个服务——首次需要时由本模块
12
- // 把目录里 pin 住的运行时制品装进受管目录,然后原子切一个 active 指针。
13
- //
14
- // 硬约束(每一条都由下面的代码守卫,不是注释口号):
15
- // 1. 只用 catalog 里显式写出的 https URL + 逐字节 sha256/bytes;缺任何一项就拒绝安装
16
- // (LOCAL_VECTOR_RUNTIME_UNVERIFIED),绝不猜 hash、绝不落到「装了个大概能用的东西」。
17
- // 2. 不跑 npm、不跑 postinstall、不读宿主 node_modules:tarball 按白名单解包,
18
- // postinstall 专用依赖(adm-zip/global-agent/...)根本不落盘。
19
- // 3. 不支持的平台(catalog 没有该平台原生库 hash)fail-closed 报 unsupported。
20
- // 4. staging → 字节/hash 校验 → 解包 → 逐文件核对 → 原生加载 smoke → 原子发布。
21
- // 失败、取消、hash 不符都在 staging 里结束,active 指针保持不动。
22
- // 5. 幂等 + 并发安全:同进程 join 同一个 promise,跨进程用 staging 里的 pid 锁;
23
- // 已安装且核对通过就直接复用,重启后不重下 115 MB。
24
-
25
- export const RUNTIME_RECORD = 'installed.json'
26
- export const RUNTIME_ACTIVE = 'active.json'
27
- export const RUNTIME_STAGING = '.staging'
28
- export const RUNTIME_CACHE = '.cache'
29
- export const RUNTIME_LAYOUT = 'node_modules'
30
-
31
- const DEFAULT_MAX_ARTIFACT_BYTES = 256 * 1024 * 1024
32
- const DEFAULT_MAX_FILE_BYTES = 128 * 1024 * 1024
33
- const DEFAULT_SMOKE_TIMEOUT_MS = 120_000
34
- const DEFAULT_FETCH_TIMEOUT_MS = 600_000
35
- // 分块 stall 超时:连续这么久没收到任何 chunk 就判定连接半开并 abort(S-1)。
36
- const DEFAULT_STALL_TIMEOUT_MS = 30_000
37
- const READY_LIMIT = 8_192
38
-
39
- // The child smoke process needs the OS basics and nothing else: an inherited proxy
40
- // variable could reroute a request and an inherited *_API_KEY would hand a cloud
41
- // credential to a process whose whole job is loading a local .node file.
42
- const DENIED_ENV_NAMES = Object.freeze(['http_proxy', 'https_proxy', 'all_proxy', 'no_proxy', 'node_options', 'node_path'])
43
- const DENIED_ENV_PREFIXES = Object.freeze(['memu_', 'dsh_memu_embed_', 'openai_', 'azure_openai_', 'anthropic_', 'gemini_', 'google_', 'cohere_'])
44
-
45
- function failure(code, message, extra) {
46
- const error = new Error(message)
47
- error.code = code
48
- if (extra) Object.assign(error, extra)
49
- return error
50
- }
51
-
52
- // S-16:下载前预检目标盘剩余空间,避免下到一半 ENOSPC 留下 .part 占空间。
53
- // statfsSync 在部分平台/挂载点会抛错或回报 0,此时不拦(fail-open),让写入
54
- // 路径自己报错,别因为一个探针就挡住本来能装成功的下载。
55
- function ensureFreeSpace(dir, requiredBytes) {
56
- if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
57
- let available = null
58
- try {
59
- const stat = fs.statfsSync(dir)
60
- available = Number(stat.bavail) * Number(stat.bsize)
61
- } catch {
62
- return
63
- }
64
- if (!Number.isFinite(available) || available <= 0) return
65
- // 留一倍余量给解包与安装副本,别把盘压到 0。
66
- if (available < requiredBytes * 2) {
67
- throw failure('LOCAL_VECTOR_RUNTIME_DISK_ERROR', `not enough free space for the managed runtime: need ~${requiredBytes * 2} bytes, only ${available} available`)
68
- }
69
- }
70
-
71
- function isPlainObject(value) {
72
- return !!value && typeof value === 'object' && !Array.isArray(value)
73
- }
74
-
75
- function isSha256(value) {
76
- return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value)
77
- }
78
-
79
- function isAbort(error, signal) {
80
- return Boolean(signal?.aborted) || error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED' || error?.code === 'LOCAL_VECTOR_RUNTIME_ABORTED'
81
- }
82
-
83
- function sha256Of(buffer) {
84
- return crypto.createHash('sha256').update(buffer).digest('hex')
85
- }
86
-
87
- function sha256File(file) {
88
- return new Promise((resolve, reject) => {
89
- const hash = crypto.createHash('sha256')
90
- const stream = fs.createReadStream(file)
91
- stream.on('data', chunk => hash.update(chunk))
92
- stream.on('error', reject)
93
- stream.on('end', () => resolve(hash.digest('hex')))
94
- })
95
- }
96
-
97
- function artifactSafeName(artifact) {
98
- return String(artifact?.name || 'artifact').replace(/[^A-Za-z0-9._@-]+/g, '-')
99
- }
100
-
101
- function cachePaths(cacheDir, artifact) {
102
- const base = path.join(cacheDir, `${artifactSafeName(artifact)}-${artifact.sha256}.tgz`)
103
- return { final: base, part: base + '.part' }
104
- }
105
-
106
- export function embeddingRuntimePlatform(platform = process.platform, arch = process.arch) {
107
- return String(platform) + '-' + String(arch)
108
- }
109
-
110
- // catalog 的 <platform> 占位符是 'win32/x64' 这种目录形状,catalog 的 key 是 'win32-x64'。
111
- export function runtimeNativeDir(platform) {
112
- return String(platform).replace('-', '/')
113
- }
114
-
115
- export function runtimeKeyFor(entry, platform = embeddingRuntimePlatform()) {
116
- const runtime = isPlainObject(entry?.runtime) ? entry.runtime : {}
117
- return [String(runtime.engine || 'onnxruntime-node'), String(runtime.version || 'unpinned'), String(runtime.abi || 'unknown'), String(platform)].join('@').replace(/[^A-Za-z0-9._@-]+/g, '-')
118
- }
119
-
120
- /** 把 catalog 条目里的 runtime 事实整成一个可执行的安装计划;任何一项不完整都 fail-closed。 */
121
- export function runtimePlan(entry, platform = embeddingRuntimePlatform()) {
122
- const errors = []
123
- const reject = (code, message) => errors.push({ code, message })
124
- const runtime = isPlainObject(entry?.runtime) ? entry.runtime : null
125
- const key = runtimeKeyFor(entry, platform)
126
- const empty = { ok: false, errors, key, platform, engine: null, version: null, abi: null, artifacts: [], packageFiles: [], native: [], sources: [] }
127
- if (!runtime) {
128
- reject('RUNTIME_SPEC_MISSING', 'the catalog entry has no runtime spec')
129
- return empty
130
- }
131
- if (entry?.availability !== 'available') reject('RUNTIME_ENTRY_NOT_AVAILABLE', `${String(entry?.id ?? 'unknown model')} is not an available catalog entry; no runtime may be installed for it`)
132
- const engine = String(runtime.engine || '').trim()
133
- const version = String(runtime.version || '').trim()
134
- const abi = String(runtime.abi || '').trim()
135
- if (!engine) reject('RUNTIME_ENGINE_MISSING', 'runtime.engine is required')
136
- if (!version) reject('RUNTIME_VERSION_UNPINNED', 'runtime.version must be a pinned version, not null')
137
- if (!abi) reject('RUNTIME_ABI_MISSING', 'runtime.abi is required')
138
- const artifacts = []
139
- const sourcesById = new Map()
140
- for (const artifact of Array.isArray(runtime.artifacts) ? runtime.artifacts : []) {
141
- if (!isPlainObject(artifact)) { reject('RUNTIME_ARTIFACT_INVALID', 'each runtime artifact must be an object'); continue }
142
- const name = String(artifact.name || '')
143
- if (!/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(name)) reject('RUNTIME_ARTIFACT_NAME_INVALID', `invalid artifact name: ${JSON.stringify(artifact.name)}`)
144
- let url = null
145
- try { url = new URL(String(artifact.url || '')) } catch { url = null }
146
- if (!url || url.protocol !== 'https:') reject('RUNTIME_ARTIFACT_URL_INVALID', `artifact ${name} needs a pinned https URL`)
147
- if (!Number.isInteger(artifact.bytes) || artifact.bytes <= 0) reject('RUNTIME_ARTIFACT_BYTES_INVALID', `artifact ${name} needs exact bytes`)
148
- if (!isSha256(artifact.sha256)) reject('RUNTIME_ARTIFACT_SHA256_INVALID', `artifact ${name} needs a lowercase sha256; guessed hashes are not accepted`)
149
- if (!Array.isArray(artifact.extract) || !artifact.extract.length) reject('RUNTIME_ARTIFACT_EXTRACT_MISSING', `artifact ${name} needs an explicit extraction allow-list`)
150
- const sourceList = []
151
- for (const source of Array.isArray(artifact.sources) ? artifact.sources : []) {
152
- if (!isPlainObject(source)) { reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} has a non-object source`); continue }
153
- const id = String(source.id || '').trim()
154
- let sourceUrl = null
155
- try { sourceUrl = new URL(String(source.url || '')) } catch { sourceUrl = null }
156
- if (!id || !/^[a-z0-9._-]+$/.test(id) || !sourceUrl || sourceUrl.protocol !== 'https:') {
157
- reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} has an invalid source: ${JSON.stringify(source.id || source.url)}`)
158
- continue
159
- }
160
- if (sourceList.some(item => item.id === id)) { reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} repeats source ${id}`); continue }
161
- sourceList.push({ id, label: String(source.label || id).slice(0, 80), url: sourceUrl.href })
162
- }
163
- if (!sourceList.length && url) sourceList.push({ id: 'npmjs', label: 'npmjs', url: url.href })
164
- for (const source of sourceList) {
165
- if (!sourcesById.has(source.id)) sourcesById.set(source.id, { id: source.id, label: source.label })
166
- }
167
- artifacts.push({
168
- name,
169
- version: String(artifact.version || version),
170
- url: url ? url.href : null,
171
- sources: sourceList,
172
- bytes: Number.isInteger(artifact.bytes) ? artifact.bytes : null,
173
- sha256: String(artifact.sha256 || ''),
174
- integrity: typeof artifact.integrity === 'string' ? artifact.integrity : null,
175
- license: typeof artifact.license === 'string' ? artifact.license : null,
176
- extract: Array.isArray(artifact.extract) ? artifact.extract.map(item => String(item)) : [],
177
- })
178
- }
179
- if (!artifacts.length) reject('RUNTIME_ARTIFACTS_MISSING', 'the runtime spec lists no pinned artifacts; nothing will be downloaded')
180
- const packageFiles = []
181
- for (const file of Array.isArray(runtime.packageFiles) ? runtime.packageFiles : []) {
182
- if (!isPlainObject(file) || typeof file.package !== 'string' || !file.package) { reject('RUNTIME_PACKAGE_FILE_INVALID', 'each packageFiles entry needs a package name'); continue }
183
- if (!Number.isInteger(file.bytes) || file.bytes <= 0) reject('RUNTIME_PACKAGE_FILE_INVALID', `packageFiles ${file.package} needs exact bytes`)
184
- if (!isSha256(file.sha256)) reject('RUNTIME_PACKAGE_FILE_INVALID', `packageFiles ${file.package} needs a lowercase sha256`)
185
- packageFiles.push({ package: file.package, path: `${RUNTIME_LAYOUT}/${file.package}/package.json`, bytes: Number(file.bytes), sha256: String(file.sha256) })
186
- }
187
- if (!packageFiles.length) reject('RUNTIME_PACKAGE_FILES_MISSING', 'the runtime spec pins no package.json facts; the extracted tree cannot be verified')
188
- const native = []
189
- for (const file of Array.isArray(runtime.native?.[platform]) ? runtime.native[platform] : []) {
190
- if (!isPlainObject(file) || typeof file.path !== 'string' || !file.path.startsWith(RUNTIME_LAYOUT + '/')) { reject('RUNTIME_NATIVE_INVALID', 'each native file needs a path inside node_modules'); continue }
191
- if (file.path.includes('..') || path.isAbsolute(file.path) || file.path.includes('\\')) { reject('RUNTIME_NATIVE_INVALID', `unsafe native path: ${JSON.stringify(file.path)}`); continue }
192
- if (!Number.isInteger(file.bytes) || file.bytes <= 0) reject('RUNTIME_NATIVE_INVALID', `native file ${file.path} needs exact bytes`)
193
- if (!isSha256(file.sha256)) reject('RUNTIME_NATIVE_INVALID', `native file ${file.path} needs a lowercase sha256`)
194
- native.push({ path: file.path, bytes: Number(file.bytes), sha256: String(file.sha256) })
195
- }
196
- if (!native.length) reject('RUNTIME_NATIVE_MISSING', `no verified native runtime is pinned for ${platform}; refusing to install on this platform`)
197
- return {
198
- ok: errors.length === 0,
199
- errors,
200
- key,
201
- platform,
202
- engine: engine || null,
203
- version: version || null,
204
- abi: abi || null,
205
- artifacts,
206
- packageFiles,
207
- native,
208
- sources: [...sourcesById.values()],
209
- }
210
- }
211
-
212
- /** 下载到的字节必须与 pin 的 bytes+sha256 完全一致;不匹配一律拒绝执行。 */
213
- export function verifyRuntimeArtifact(bytes, artifact) {
214
- const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? [])
215
- if (!isSha256(artifact?.sha256)) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${String(artifact?.name || '?')} has no pinned sha256; refusing to install`)
216
- if (!Number.isSafeInteger(artifact?.bytes) || artifact.bytes <= 0) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${String(artifact?.name || '?')} has no exact byte count`)
217
- if (buffer.length !== artifact.bytes) {
218
- throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `artifact ${String(artifact.name)} is ${buffer.length} bytes, expected ${artifact.bytes}`)
219
- }
220
- const digest = sha256Of(buffer)
221
- if (digest !== artifact.sha256) {
222
- throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `artifact ${String(artifact.name)} sha256 ${digest} does not match the pinned ${artifact.sha256}`)
223
- }
224
- return digest
225
- }
226
-
227
- /** tar 条目白名单:只允许 catalog 里写出的前缀,且必须换成该平台的原生库目录。 */
228
- export function extractAllowList(artifact, platform) {
229
- const nativeDir = runtimeNativeDir(platform)
230
- return (Array.isArray(artifact?.extract) ? artifact.extract : [])
231
- .map(item => String(item).replace('<platform>', nativeDir))
232
- .map(item => item.replace(/^\/+/, '').replace(/\/+$/, ''))
233
- .filter(Boolean)
234
- }
235
-
236
- // Windows 上刚写完的目录会被杀软/索引器短暂占用,rename 会抛 EPERM/EBUSY;
237
- // 这是可恢复的瞬时错误,重试几次再判失败,别把「正在被扫描」当成「装坏了」。
238
- async function renameWithRetry(from, to, options = {}) {
239
- const attempts = Number.isFinite(options.attempts) ? options.attempts : 6
240
- const delayMs = Number.isFinite(options.delayMs) ? options.delayMs : 60
241
- let last = null
242
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
243
- try {
244
- fs.renameSync(from, to)
245
- return
246
- } catch (error) {
247
- last = error
248
- const code = String(error?.code || '')
249
- if (attempt === attempts || !['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY'].includes(code)) break
250
- await new Promise(resolve => setTimeout(resolve, delayMs * attempt))
251
- }
252
- }
253
- throw last
254
- }
255
-
256
- export function createEmbeddingRuntimeInstaller(options = {}) {
257
- const root = options.root
258
- if (typeof root !== 'string' || !root.trim()) throw new TypeError('createEmbeddingRuntimeInstaller requires a root directory')
259
- const baseDir = path.resolve(root)
260
- const platform = String(options.platform || embeddingRuntimePlatform())
261
- const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : fetch
262
- const spawnImpl = typeof options.spawnImpl === 'function' ? options.spawnImpl : spawn
263
- const executable = String(options.executable || process.execPath)
264
- const now = typeof options.now === 'function' ? options.now : () => new Date().toISOString()
265
- const logger = options.logger || null
266
- const maxArtifactBytes = Number.isInteger(options.maxArtifactBytes) ? options.maxArtifactBytes : DEFAULT_MAX_ARTIFACT_BYTES
267
- const maxFileBytes = Number.isInteger(options.maxFileBytes) ? options.maxFileBytes : DEFAULT_MAX_FILE_BYTES
268
- const smokeTimeoutMs = Number.isInteger(options.smokeTimeoutMs) ? options.smokeTimeoutMs : DEFAULT_SMOKE_TIMEOUT_MS
269
- const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
270
- const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
271
- const extract = typeof options.extract === 'function' ? options.extract : defaultExtract
272
- const smoke = typeof options.smoke === 'function' ? options.smoke : defaultSmoke
273
- const resolveEntry = typeof options.resolveEntry === 'function' ? options.resolveEntry : id => (id ? getEmbeddingModel(String(id)) : null)
274
- const activeFile = path.join(baseDir, RUNTIME_ACTIVE)
275
- const cacheDir = path.join(baseDir, RUNTIME_CACHE)
276
- const inflight = new Map()
277
- let job = null
278
- let outcome = null
279
- let disposed = false
280
-
281
- const warn = message => { try { logger?.warn?.(message) } catch {} }
282
-
283
- function insideRoot(target) {
284
- const resolved = path.resolve(target)
285
- if (resolved !== baseDir && !resolved.startsWith(baseDir + path.sep)) {
286
- throw failure('LOCAL_VECTOR_RUNTIME_PATH_ESCAPE', `refusing to touch a path outside the managed runtime root: ${resolved}`)
287
- }
288
- return resolved
289
- }
290
-
291
- function readActive() {
292
- const result = readJsonStrict(activeFile)
293
- if (!result.ok || !isPlainObject(result.value)) return null
294
- const value = result.value
295
- if (typeof value.key !== 'string' || typeof value.dir !== 'string' || typeof value.platform !== 'string') return null
296
- return value
297
- }
298
-
299
- function readRecord(dir) {
300
- const result = readJsonStrict(path.join(dir, RUNTIME_RECORD))
301
- return result.ok && isPlainObject(result.value) ? result.value : null
302
- }
303
-
304
- // The archive hash authenticates every extracted file, not only package/native pins.
305
- // Keep that complete inventory and reject new files or links before any runtime reuse.
306
- function inventoryTree(plan, dir, { deep = true, allowRecord = false } = {}) {
307
- const files = []
308
- const allowed = plan.artifacts.flatMap(artifact => extractAllowList(artifact, plan.platform).map(prefix => RUNTIME_LAYOUT + '/' + artifact.name + '/' + prefix))
309
- if (!fs.lstatSync(dir).isDirectory() || fs.lstatSync(dir).isSymbolicLink()) throw failure('LOCAL_VECTOR_RUNTIME_PATH_ESCAPE', 'runtime root must be a real directory')
310
- const visit = (parent, relative = '') => {
311
- for (const name of fs.readdirSync(parent).sort()) {
312
- const rel = relative ? relative + '/' + name : name
313
- const target = path.join(parent, name)
314
- const stat = fs.lstatSync(target)
315
- if (stat.isSymbolicLink()) throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', 'runtime inventory contains a link: ' + rel)
316
- if (allowRecord && rel === RUNTIME_RECORD && stat.isFile()) continue
317
- if (stat.isDirectory()) {
318
- if (!allowed.some(prefix => prefix === rel || prefix.startsWith(rel + '/') || rel.startsWith(prefix + '/'))) throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', 'runtime inventory contains an unlisted directory: ' + rel)
319
- visit(target, rel)
320
- } else if (stat.isFile()) {
321
- if (!allowed.some(prefix => rel === prefix || rel.startsWith(prefix + '/'))) throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', 'runtime inventory contains an unlisted file: ' + rel)
322
- if (stat.size > maxFileBytes) throw failure('LOCAL_VECTOR_RUNTIME_TOO_LARGE', 'runtime inventory file exceeds its limit: ' + rel)
323
- files.push({ path: rel, bytes: stat.size, ...(deep ? { sha256: sha256Of(fs.readFileSync(target)) } : {}) })
324
- } else {
325
- throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', 'runtime inventory contains a non-regular entry: ' + rel)
326
- }
327
- }
328
- }
329
- visit(dir)
330
- return files
331
- }
332
-
333
- // 复用判定:便宜(只比字节数)还是彻底(重算 sha256)由调用方决定。
334
- // 便宜路径抓「文件被删/被换/明显截断」,彻底路径抓内容差异;两者都不猜。
335
- function inspectPlan(plan, { deep = false } = {}) {
336
- const active = readActive()
337
- if (!active) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_ABSENT' }
338
- if (active.key !== plan.key || active.platform !== plan.platform) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_STALE' }
339
- let dir
340
- try { dir = insideRoot(active.dir) } catch { return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_PATH_ESCAPE' } }
341
- const record = readRecord(dir)
342
- if (!record) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_MISSING' }
343
- if (record.key !== plan.key || record.platform !== plan.platform || record.engine !== plan.engine || record.version !== plan.version || record.abi !== plan.abi) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_STALE' }
344
- const recordedArtifacts = Array.isArray(record.artifacts) ? record.artifacts : []
345
- if (recordedArtifacts.length !== plan.artifacts.length || plan.artifacts.some(artifact => {
346
- const saved = recordedArtifacts.find(item => item && item.name === artifact.name)
347
- return !saved || saved.version !== artifact.version || saved.url !== artifact.url || saved.bytes !== artifact.bytes || saved.sha256 !== artifact.sha256
348
- })) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_STALE' }
349
- const expected = [...plan.packageFiles, ...plan.native]
350
- const recorded = Array.isArray(record.files) ? record.files : []
351
- if (record.inventoryVersion !== 1 || recorded.length < expected.length) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_INCOMPLETE' }
352
- const byPath = new Map()
353
- for (const file of recorded) {
354
- if (!file || typeof file.path !== 'string' || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || !isSha256(file.sha256) || byPath.has(file.path)) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_INCOMPLETE' }
355
- byPath.set(file.path, file)
356
- }
357
- for (const file of expected) {
358
- const pinned = byPath.get(file.path)
359
- if (!pinned || pinned.sha256 !== file.sha256 || pinned.bytes !== file.bytes) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_STALE', path: file.path }
360
- }
361
- let actual
362
- try { actual = inventoryTree(plan, dir, { deep, allowRecord: true }) } catch (error) { return { ok: false, code: error?.code || 'LOCAL_VECTOR_RUNTIME_INCOMPLETE' } }
363
- if (actual.length !== recorded.length) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE' }
364
- for (const file of actual) {
365
- const pinned = byPath.get(file.path)
366
- if (!pinned) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', path: file.path }
367
- if (file.bytes !== pinned.bytes) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_INCOMPLETE', path: file.path }
368
- if (deep && file.sha256 !== pinned.sha256) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', path: file.path }
369
- }
370
- return { ok: true, dir, record }
371
- }
372
-
373
- function planFor(modelId) {
374
- const entry = resolveEntry(modelId)
375
- if (!entry) {
376
- const fallback = getEmbeddingCatalog().find(item => item.availability === 'available')
377
- if (!fallback) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', 'no available catalog entry pins a runtime; nothing will be installed')
378
- return { entry: fallback, plan: runtimePlan(fallback, platform) }
379
- }
380
- return { entry, plan: runtimePlan(entry, platform) }
381
- }
382
-
383
- function status({ deep = false, modelId = null } = {}) {
384
- const base = { source: 'managed', platform, root: baseDir }
385
- let resolved = null
386
- try { resolved = planFor(modelId) } catch (error) { return { ...base, status: 'unsupported', ready: false, key: null, path: null, error: { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_UNVERIFIED'), message: String(error?.message || error) } } }
387
- const entry = resolved.entry
388
- const plan = resolved.plan
389
- const pinned = { key: plan.key, engine: plan.engine, version: plan.version, abi: plan.abi, artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256, license: item.license })), sources: plan.sources, verifiedPlatforms: Object.keys(entry?.runtime?.install?.platforms || {}) }
390
- if (!plan.ok) {
391
- return { ...base, ...pinned, status: 'unsupported', ready: false, path: null, error: { code: 'LOCAL_VECTOR_RUNTIME_UNVERIFIED', message: 'the catalog does not pin a complete runtime for this platform', errors: plan.errors } }
392
- }
393
- if (job && job.key === plan.key) {
394
- return { ...base, ...pinned, status: job.state, ready: false, path: null, progress: { ...job.progress }, startedAt: job.startedAt, downloadSource: job.source || null }
395
- }
396
- const inspect = inspectPlan(plan, { deep })
397
- if (inspect.ok) {
398
- return { ...base, ...pinned, status: 'installed', ready: true, path: inspect.dir, installedAt: inspect.record.installedAt || null, verifiedAt: inspect.record.verifiedAt || null, checks: Array.isArray(inspect.record.checks) ? [...inspect.record.checks] : [], smoke: inspect.record.smoke || null }
399
- }
400
- if (outcome && outcome.key === plan.key && outcome.status === 'failed') {
401
- return { ...base, ...pinned, status: 'failed', ready: false, path: null, error: { ...outcome.error }, inspect: inspect.code }
402
- }
403
- return { ...base, ...pinned, status: 'absent', ready: false, path: null, inspect: inspect.code }
404
- }
405
-
406
- function activeDir({ deep = false, modelId = null } = {}) {
407
- const current = status({ deep, modelId })
408
- return current.status === 'installed' ? current.path : null
409
- }
410
-
411
- function acquireLock(stagingRoot) {
412
- ensureDir(stagingRoot)
413
- const lockFile = path.join(stagingRoot, 'install.lock')
414
- const token = crypto.randomUUID()
415
- const contents = JSON.stringify({ pid: process.pid, at: Date.now(), token })
416
- const release = () => {
417
- try { if (fs.readFileSync(lockFile, 'utf8') === contents) fs.unlinkSync(lockFile) } catch {}
418
- }
419
- for (let attempt = 0; attempt < 2; attempt++) {
420
- try {
421
- const fd = fs.openSync(lockFile, 'wx', 0o600)
422
- try { fs.writeFileSync(fd, contents) } finally { fs.closeSync(fd) }
423
- return release
424
- } catch (error) {
425
- if (error?.code !== 'EEXIST') throw error
426
- let owner = null
427
- let observed = null
428
- try { observed = fs.readFileSync(lockFile, 'utf8'); owner = JSON.parse(observed) } catch {}
429
- // Age is not proof of death. Unknown owners and EPERM probes stay busy.
430
- let dead = false
431
- if (owner && Number.isSafeInteger(owner.pid) && owner.pid > 0) {
432
- try { process.kill(owner.pid, 0) } catch (probe) { dead = probe?.code === 'ESRCH' }
433
- }
434
- if (!dead) throw failure('LOCAL_VECTOR_RUNTIME_BUSY', 'another process is installing the managed embedding runtime; retry when it finishes')
435
- try { if (fs.readFileSync(lockFile, 'utf8') === observed) fs.unlinkSync(lockFile) } catch {}
436
- }
437
- }
438
- throw failure('LOCAL_VECTOR_RUNTIME_BUSY', 'cannot take the managed runtime install lock; retry later')
439
- }
440
-
441
- function seedArtifactCache(plan, stagingRoot) {
442
- ensureDir(insideRoot(cacheDir))
443
- let dirs = []
444
- try {
445
- dirs = fs.readdirSync(stagingRoot, { withFileTypes: true })
446
- .filter(entry => entry.isDirectory() && entry.name.startsWith('install-'))
447
- .map(entry => entry.name)
448
- } catch { return }
449
- for (const artifact of plan.artifacts) {
450
- const paths = cachePaths(cacheDir, artifact)
451
- if (fs.existsSync(paths.final)) continue
452
- let currentPart = 0
453
- try { currentPart = fs.statSync(paths.part).size } catch {}
454
- const wanted = `${artifactSafeName(artifact)}.tgz`
455
- let best = null
456
- for (const dir of dirs) {
457
- const artifactDir = path.join(stagingRoot, dir, '.artifacts')
458
- let files = []
459
- try { files = fs.readdirSync(artifactDir) } catch { continue }
460
- for (const name of files) {
461
- if (name !== wanted) continue
462
- try {
463
- const stat = fs.statSync(path.join(artifactDir, name))
464
- if (stat.isFile() && stat.size > 0 && stat.size <= artifact.bytes && (!best || stat.size > best.size)) {
465
- best = { file: path.join(artifactDir, name), size: stat.size }
466
- }
467
- } catch {}
468
- }
469
- }
470
- if (!best || best.size <= currentPart) continue
471
- try {
472
- fs.copyFileSync(best.file, paths.part)
473
- warn(`seeded runtime artifact cache from previous staging: ${artifact.name} (${best.size} bytes)`)
474
- } catch (error) {
475
- warn(`cannot seed runtime artifact cache for ${artifact.name}: ${error?.message || error}`)
476
- }
477
- }
478
- }
479
-
480
- async function downloadArtifact(artifact, sourceId, controller, report) {
481
- if (!Number.isInteger(artifact.bytes) || artifact.bytes <= 0) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${artifact.name} has no exact byte count`)
482
- if (artifact.bytes > maxArtifactBytes) throw failure('LOCAL_VECTOR_RUNTIME_TOO_LARGE', `artifact ${artifact.name} declares ${artifact.bytes} bytes, above the ${maxArtifactBytes} byte cap`)
483
- const source = artifact.sources.find(item => item.id === sourceId) || artifact.sources[0] || null
484
- const url = source?.url || artifact.url
485
- if (!url) throw failure('LOCAL_VECTOR_RUNTIME_ARTIFACT_URL_INVALID', `artifact ${artifact.name} has no download URL`)
486
- ensureDir(insideRoot(cacheDir))
487
- const paths = cachePaths(cacheDir, artifact)
488
- const bump = (bytes) => {
489
- job.progress.bytes += bytes
490
- const nowMs = Date.now()
491
- const elapsed = (nowMs - (job.progress.speedAt || nowMs)) / 1000
492
- if (elapsed >= 0.5) {
493
- job.progress.speedBps = Math.max(0, (job.progress.bytes - (job.progress.speedBytes || 0)) / elapsed)
494
- job.progress.speedAt = nowMs
495
- job.progress.speedBytes = job.progress.bytes
496
- report()
497
- }
498
- }
499
- try {
500
- const complete = fs.statSync(paths.final)
501
- if (complete.size === artifact.bytes) {
502
- const digest = await sha256File(paths.final)
503
- if (digest === artifact.sha256) {
504
- job.progress.bytes += artifact.bytes
505
- report()
506
- return { path: paths.final, bytes: artifact.bytes, sha256: digest, source: source?.id || null, cached: true }
507
- }
508
- }
509
- try { fs.rmSync(paths.final, { force: true }) } catch {}
510
- } catch {}
511
- let existing = 0
512
- try { existing = fs.statSync(paths.part).size } catch {}
513
- if (existing > artifact.bytes) {
514
- try { fs.rmSync(paths.part, { force: true }) } catch {}
515
- existing = 0
516
- }
517
- if (existing === artifact.bytes) {
518
- const digest = await sha256File(paths.part)
519
- if (digest === artifact.sha256) {
520
- await renameWithRetry(paths.part, paths.final)
521
- job.progress.bytes += artifact.bytes
522
- report()
523
- return { path: paths.final, bytes: artifact.bytes, sha256: digest, source: source?.id || null, cached: true }
524
- }
525
- try { fs.rmSync(paths.part, { force: true }) } catch {}
526
- existing = 0
527
- }
528
- if (existing > 0) {
529
- job.progress.bytes += existing
530
- // Speed is about the bytes this process receives, not the part inherited
531
- // from the previous run; anchor the sample at the resumed offset.
532
- job.progress.speedBytes = job.progress.bytes
533
- job.progress.speedAt = Date.now()
534
- job.progress.current = artifact.name
535
- report()
536
- }
537
- const headers = { 'accept-encoding': 'identity' }
538
- if (existing > 0) headers.Range = `bytes=${existing}-`
539
- // S-1:fetch 总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
540
- // 连接让 for-await 永久 pending;超时单独记账,别被 install() 误判成用户取消。
541
- let timedOut = false
542
- const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
543
- totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
544
- const stallController = new AbortController()
545
- let stallTimer = null
546
- const armStall = () => {
547
- if (stallTimer) clearTimeout(stallTimer)
548
- stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
549
- stallTimer.unref?.()
550
- }
551
- const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
552
- const timeoutFailure = cause => failure('LOCAL_VECTOR_RUNTIME_DOWNLOAD_TIMEOUT', `${artifact.name} download timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
553
- const abortedFailure = cause => failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted', { cause })
554
- // for-await 被 signal 中断时抛原生 AbortError,按来源还原成明确失败码;
555
- // 磁盘写失败(ENOSPC/EIO/...)清掉 .part,别让半成品占着空间(S-16)。
556
- let removePart = false
557
- const streamFailure = error => {
558
- if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
559
- if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
560
- if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
561
- removePart = true
562
- return failure('LOCAL_VECTOR_RUNTIME_DISK_ERROR', `${artifact.name} download failed with ${error.code}; partial download removed`, { cause: error })
563
- }
564
- return error
565
- }
566
- armStall()
567
- const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
568
- let response
569
- try {
570
- response = await fetchImpl(url, { signal, redirect: 'follow', headers })
571
- } catch (error) {
572
- if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
573
- if (isAbort(error, controller.signal)) throw abortedFailure(error)
574
- throw failure('LOCAL_VECTOR_RUNTIME_NETWORK_ERROR', `cannot fetch ${artifact.name}: ${error?.message || error}`, { cause: error })
575
- }
576
- if (!response || !response.ok) throw failure('LOCAL_VECTOR_RUNTIME_HTTP_ERROR', `registry returned ${response?.status ?? 'no response'} for ${artifact.name}`)
577
- let append = existing > 0
578
- if (append && response.status === 200) {
579
- // The source ignored Range. Keep the file correct by starting over; a later
580
- // attempt may still resume from the new bytes.
581
- job.progress.bytes = Math.max(0, job.progress.bytes - existing)
582
- append = false
583
- existing = 0
584
- } else if (append) {
585
- const contentRange = String(response.headers?.get?.('content-range') || '')
586
- const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(contentRange)
587
- if (!match || Number(match[1]) !== existing || Number(match[3]) !== artifact.bytes) {
588
- throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} returned an unexpected Content-Range: ${contentRange || '(missing)'}`)
589
- }
590
- const declared = Number(response.headers?.get?.('content-length'))
591
- if (Number.isFinite(declared) && declared > 0 && declared !== artifact.bytes - existing) {
592
- throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} content-length ${declared} does not match the remaining ${artifact.bytes - existing} bytes`)
593
- }
594
- } else {
595
- const declared = Number(response.headers?.get?.('content-length'))
596
- if (Number.isFinite(declared) && declared > 0 && declared !== artifact.bytes) {
597
- throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} content-length ${declared} does not match the pinned ${artifact.bytes} bytes`)
598
- }
599
- }
600
- let size = existing
601
- const fd = fs.openSync(paths.part, append ? 'a' : 'w', 0o600)
602
- try {
603
- const body = response.body
604
- if (body && typeof body[Symbol.asyncIterator] === 'function') {
605
- try {
606
- for await (const chunk of body) {
607
- if (controller.signal.aborted) throw abortedFailure(null)
608
- armStall()
609
- size += chunk.length
610
- if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
611
- fs.writeSync(fd, chunk)
612
- bump(chunk.length)
613
- }
614
- } catch (error) { throw streamFailure(error) }
615
- } else {
616
- try {
617
- const buffer = Buffer.from(await response.arrayBuffer())
618
- size += buffer.length
619
- if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
620
- fs.writeSync(fd, buffer)
621
- bump(buffer.length)
622
- } catch (error) { throw streamFailure(error) }
623
- }
624
- } finally {
625
- clearStall()
626
- try { fs.closeSync(fd) } catch {}
627
- if (removePart) { try { fs.rmSync(paths.part, { force: true }) } catch {} }
628
- }
629
- if (size !== artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} is ${size} bytes, expected ${artifact.bytes}`)
630
- const digest = await sha256File(paths.part)
631
- if (digest !== artifact.sha256) {
632
- try { fs.rmSync(paths.part, { force: true }) } catch {}
633
- throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `${artifact.name} sha256 ${digest} does not match the pinned ${artifact.sha256}`)
634
- }
635
- await renameWithRetry(paths.part, paths.final)
636
- return { path: paths.final, bytes: size, sha256: digest, source: source?.id || null, cached: false }
637
- }
638
-
639
- function verifyExtracted(plan, dir) {
640
- const checks = []
641
- for (const file of plan.packageFiles) {
642
- const target = path.join(dir, ...file.path.split('/'))
643
- let bytes
644
- try { bytes = fs.readFileSync(target) } catch { throw failure('LOCAL_VECTOR_RUNTIME_INCOMPLETE', `the extracted tree has no ${file.path}`) }
645
- if (bytes.length !== file.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${file.path} is ${bytes.length} bytes, expected ${file.bytes}`)
646
- const digest = sha256Of(bytes)
647
- if (digest !== file.sha256) throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
648
- checks.push(`${file.path}@${digest.slice(0, 12)}`)
649
- }
650
- for (const file of plan.native) {
651
- const target = path.join(dir, ...file.path.split('/'))
652
- let stat
653
- try { stat = fs.statSync(target) } catch { throw failure('LOCAL_VECTOR_RUNTIME_INCOMPLETE', `the extracted tree has no ${file.path}`) }
654
- if (!stat.isFile() || stat.size !== file.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${file.path} is not the pinned ${file.bytes} bytes`)
655
- const digest = sha256Of(fs.readFileSync(target))
656
- if (digest !== file.sha256) throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
657
- checks.push(`${path.posix.basename(file.path)}@${digest.slice(0, 12)}`)
658
- }
659
- // 解包白名单不能被绕过成「多装了别的东西」:平台目录里只许出现 pin 住的文件。
660
- const nativeRoot = path.posix.join(RUNTIME_LAYOUT, 'onnxruntime-node', 'bin', plan.abi?.startsWith('napi') ? plan.abi : 'napi-v6', runtimeNativeDir(plan.platform))
661
- const expectedNative = new Set(plan.native.map(file => String(file.path).split('/').pop()))
662
- let entries = []
663
- try { entries = fs.readdirSync(path.join(dir, ...nativeRoot.split('/'))) } catch { entries = [] }
664
- if (entries.length) {
665
- const unexpected = entries.filter(name => !expectedNative.has(name))
666
- if (unexpected.length) throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', `the extracted native directory contains unexpected files: ${unexpected.join(', ')}`)
667
- }
668
- return checks
669
- }
670
-
671
- async function install(plan, options) {
672
- const requestedSource = options.source ? String(options.source) : null
673
- const source = requestedSource
674
- ? plan.sources.find(item => item.id === requestedSource)
675
- : plan.sources[0] || null
676
- if (requestedSource && !source) throw failure('LOCAL_VECTOR_RUNTIME_SOURCE_UNKNOWN', `unknown runtime download source: ${requestedSource}`)
677
- const downloadSource = source?.id || null
678
- const controller = new AbortController()
679
- const onAbort = () => controller.abort()
680
- options.signal?.addEventListener('abort', onAbort, { once: true })
681
- const totalBytes = plan.artifacts.reduce((sum, artifact) => sum + (artifact.bytes || 0), 0)
682
- job = {
683
- key: plan.key,
684
- state: 'downloading',
685
- startedAt: now(),
686
- source: downloadSource,
687
- controller,
688
- progress: { artifacts: plan.artifacts.length, done: 0, bytes: 0, totalBytes, current: null, speedBps: 0, speedAt: Date.now(), speedBytes: 0 },
689
- }
690
- const report = () => { try { options.onProgress?.({ ...job.progress }) } catch {} }
691
- let staging = null
692
- let release = null
693
- let published = false
694
- try {
695
- const stagingRoot = insideRoot(path.join(baseDir, RUNTIME_STAGING))
696
- release = acquireLock(stagingRoot)
697
- // 抢到锁之后先重看一眼:另一个进程可能刚刚装完,这时直接复用,不重复下载 115 MB。
698
- const existing = inspectPlan(plan, { deep: true })
699
- if (existing.ok) {
700
- job = null
701
- return { status: 'installed', ready: true, reused: true, key: plan.key, platform: plan.platform, path: existing.dir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: existing.record.installedAt || null, verifiedAt: existing.record.verifiedAt || null, checks: Array.isArray(existing.record.checks) ? existing.record.checks : [], artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: existing.record.smoke || null }
702
- }
703
- // S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
704
- ensureFreeSpace(baseDir, totalBytes)
705
- // Pick up a partial download from an interrupted process. Old installers kept
706
- // the tarball inside their own staging dir; this stable cache is what makes a
707
- // restart resume instead of re-downloading 115 MB.
708
- seedArtifactCache(plan, stagingRoot)
709
- staging = fs.mkdtempSync(path.join(stagingRoot, 'install-'))
710
- const archives = []
711
- for (const artifact of plan.artifacts) {
712
- if (controller.signal.aborted) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted')
713
- job.progress.current = artifact.name
714
- report()
715
- const saved = await downloadArtifact(artifact, downloadSource, controller, report)
716
- archives.push({ artifact, file: saved.path })
717
- job.progress.done += 1
718
- report()
719
- }
720
- job.state = 'verifying'
721
- job.progress.current = null
722
- report()
723
- for (const { artifact, file } of archives) {
724
- const allowList = extractAllowList(artifact, plan.platform)
725
- if (!allowList.length) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${artifact.name} has an empty extraction allow-list`)
726
- const target = ensureDir(path.join(staging, RUNTIME_LAYOUT, artifact.name))
727
- await extract({ file, cwd: target, allowList, maxFileBytes, artifact })
728
- }
729
- const checks = verifyExtracted(plan, staging)
730
- const files = inventoryTree(plan, staging)
731
- job.state = 'installing'
732
- report()
733
- const smokeResult = await smoke({ dir: staging, plan, executable, spawnImpl, timeoutMs: smokeTimeoutMs })
734
- if (!smokeResult || smokeResult.ok !== true) {
735
- throw failure('LOCAL_VECTOR_RUNTIME_SMOKE_FAILED', `the extracted runtime cannot load its native modules: ${String(smokeResult?.message || 'unknown reason')}`)
736
- }
737
- if (JSON.stringify(inventoryTree(plan, staging)) !== JSON.stringify(files)) throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', 'runtime files changed during install smoke')
738
- const record = {
739
- schema: 1,
740
- key: plan.key,
741
- platform: plan.platform,
742
- engine: plan.engine,
743
- version: plan.version,
744
- abi: plan.abi,
745
- installedAt: now(),
746
- verifiedAt: now(),
747
- source: 'catalog-pinned',
748
- downloadSource,
749
- postinstall: 'never-run',
750
- inventoryVersion: 1,
751
- artifacts: plan.artifacts.map(artifact => ({ name: artifact.name, version: artifact.version, url: artifact.url, bytes: artifact.bytes, sha256: artifact.sha256, integrity: artifact.integrity, license: artifact.license })),
752
- files,
753
- checks: [...checks, ...(Array.isArray(smokeResult.checks) ? smokeResult.checks : [])],
754
- smoke: { ok: true, ortVersion: smokeResult.ortVersion || null, tokenizer: smokeResult.tokenizer === true },
755
- }
756
- writeJson(path.join(staging, RUNTIME_RECORD), record)
757
- // Every install gets its own generation. Keep the old active directory in place
758
- // until the active pointer commit succeeds; this makes pointer-write failure safe.
759
- const previousActive = readActive()
760
- const finalDir = insideRoot(path.join(baseDir, plan.key + '-' + crypto.randomUUID()))
761
- try {
762
- await renameWithRetry(staging, finalDir)
763
- staging = null
764
- published = true
765
- } catch (error) {
766
- throw failure('LOCAL_VECTOR_RUNTIME_INSTALL_FAILED', `cannot move the verified runtime into place: ${error?.message || error}`, { cause: error })
767
- }
768
- try {
769
- writeJson(activeFile, { schema: 1, key: plan.key, platform: plan.platform, dir: finalDir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: record.installedAt, verifiedAt: record.verifiedAt })
770
- } catch (error) {
771
- try { fs.rmSync(finalDir, { recursive: true, force: true }) } catch {}
772
- throw failure('LOCAL_VECTOR_RUNTIME_INSTALL_FAILED', `cannot publish the managed runtime active pointer: ${error?.message || error}`, { cause: error })
773
- }
774
- // Cleanup is deliberately after pointer publication. A stale cleanup failure is harmless.
775
- if (previousActive?.dir && previousActive.dir !== finalDir) {
776
- try { fs.rmSync(insideRoot(previousActive.dir), { recursive: true, force: true }) } catch {}
777
- }
778
- outcome = null
779
- job = null
780
- return { status: 'installed', ready: true, reused: false, key: plan.key, platform: plan.platform, path: finalDir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: record.installedAt, verifiedAt: record.verifiedAt, checks: record.checks, artifacts: record.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: record.smoke }
781
- } catch (error) {
782
- const aborted = isAbort(error, controller.signal)
783
- const code = aborted ? 'LOCAL_VECTOR_RUNTIME_ABORTED' : (typeof error?.code === 'string' && error.code.startsWith('LOCAL_VECTOR_RUNTIME_') ? error.code : 'LOCAL_VECTOR_RUNTIME_INSTALL_FAILED')
784
- const failed = code === error?.code ? error : failure(code, `installing the managed embedding runtime failed: ${error?.message || error}`, { cause: error })
785
- outcome = { key: plan.key, status: 'failed', error: { code, message: String(failed.message || error) } }
786
- job = null
787
- warn(`managed embedding runtime install failed (${code}): ${failed.message}`)
788
- throw failed
789
- } finally {
790
- options.signal?.removeEventListener?.('abort', onAbort)
791
- try { release?.() } catch {}
792
- if (staging && !published) { try { fs.rmSync(staging, { recursive: true, force: true }) } catch {} }
793
- }
794
- }
795
-
796
- async function ensure(options = {}) {
797
- if (disposed) throw failure('LOCAL_VECTOR_RUNTIME_CLOSED', 'the managed runtime installer is closed')
798
- const { entry, plan } = planFor(options.modelId || options.id || null)
799
- if (!plan.ok) {
800
- const error = failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `no verified managed runtime is available for ${plan.platform}`, { errors: plan.errors, entry: entry?.id ?? null })
801
- throw error
802
- }
803
- const existing = inspectPlan(plan, { deep: true })
804
- if (existing.ok) {
805
- return { status: 'installed', ready: true, reused: true, key: plan.key, platform: plan.platform, path: existing.dir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: existing.record.installedAt || null, verifiedAt: existing.record.verifiedAt || null, checks: Array.isArray(existing.record.checks) ? existing.record.checks : [], artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: existing.record.smoke || null }
806
- }
807
- const pending = inflight.get(plan.key)
808
- if (pending) return pending
809
- if (options.reuseOnly === true) throw failure('LOCAL_VECTOR_RUNTIME_ABSENT', 'the managed embedding runtime is not installed yet', { inspect: existing.code })
810
- if (options.confirmed !== true) throw failure('LOCAL_VECTOR_RUNTIME_CONFIRMATION_REQUIRED', 'installing the managed embedding runtime downloads pinned artifacts and needs explicit confirmation: ensure({ confirmed: true })')
811
- if (options.signal?.aborted) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted before it started')
812
- const run = install(plan, options).finally(() => { inflight.delete(plan.key) })
813
- inflight.set(plan.key, run)
814
- return run
815
- }
816
-
817
- function abort() {
818
- try { job?.controller?.abort() } catch {}
819
- }
820
-
821
- function dispose() {
822
- disposed = true
823
- abort()
824
- }
825
-
826
- return { root: baseDir, platform, getStatus: status, ensure, activeDir, abort, dispose }
827
- }
828
-
829
- // ------------------------------------------------------------------ 默认解包 / 默认 smoke
830
-
831
- async function defaultExtract({ file, cwd, allowList, maxFileBytes }) {
832
- const { x } = await import('tar')
833
- ensureDir(cwd)
834
- const allowed = rel => allowList.some(prefix => rel === prefix || rel.startsWith(prefix + '/'))
835
- const allowDir = rel => allowList.some(prefix => prefix === rel || prefix.startsWith(rel + '/') || rel.startsWith(prefix + '/'))
836
- await x({
837
- file,
838
- cwd,
839
- strip: 1,
840
- strict: true,
841
- preservePaths: false,
842
- filter: (name, entry) => {
843
- const rel = String(name || '').replace(/^package\//, '')
844
- if (!rel || rel === String(name)) return false
845
- if (rel.includes('..') || path.isAbsolute(rel) || rel.includes('\\')) return false
846
- if (entry?.type === 'Directory') return allowDir(rel)
847
- if (entry?.type !== 'File') return false
848
- if (!allowed(rel)) return false
849
- return Number(entry.size || 0) <= maxFileBytes
850
- },
851
- })
852
- }
853
-
854
- const SMOKE_SOURCE = [
855
- "const path = require('node:path')",
856
- "const { createRequire } = require('node:module')",
857
- "const write = value => process.stdout.write(JSON.stringify(value) + '\\n')",
858
- "try {",
859
- " const from = createRequire(path.join(__dirname, 'entry.cjs'))",
860
- " const ort = from('onnxruntime-node')",
861
- " if (!ort || typeof ort.InferenceSession !== 'function') throw new Error('onnxruntime-node exposes no InferenceSession')",
862
- " const pkg = from('onnxruntime-node/package.json')",
863
- " const tok = from('@huggingface/tokenizers')",
864
- " const Tokenizer = tok && (tok.Tokenizer || (tok.default && tok.default.Tokenizer))",
865
- " if (typeof Tokenizer === 'undefined') throw new Error('@huggingface/tokenizers exposes no Tokenizer')",
866
- " write({ ok: true, ortVersion: String((pkg && pkg.version) || ''), tokenizer: true })",
867
- "} catch (error) {",
868
- " write({ ok: false, message: String((error && error.message) || error) })",
869
- " process.exitCode = 1",
870
- "}",
871
- ].join('\n')
872
-
873
- function smokeEnv(extra) {
874
- const env = {}
875
- for (const [name, value] of Object.entries(process.env)) {
876
- if (typeof value !== 'string') continue
877
- const lower = name.toLowerCase()
878
- if (DENIED_ENV_NAMES.includes(lower) || lower.includes('proxy')) continue
879
- if (DENIED_ENV_PREFIXES.some(prefix => lower.startsWith(prefix))) continue
880
- env[name] = value
881
- }
882
- return { ...env, ...extra }
883
- }
884
-
885
- async function defaultSmoke({ dir, executable, spawnImpl, timeoutMs }) {
886
- const script = path.join(dir, '.runtime-smoke.cjs')
887
- fs.writeFileSync(script, SMOKE_SOURCE + '\n', { mode: 0o600, flag: 'w' })
888
- try {
889
- return await new Promise(resolve => {
890
- let stdout = ''
891
- let settled = false
892
- let timer = null
893
- const finish = value => {
894
- if (settled) return
895
- settled = true
896
- if (timer) clearTimeout(timer)
897
- resolve(value)
898
- }
899
- let child = null
900
- try {
901
- child = spawnImpl(executable, [script], {
902
- windowsHide: true,
903
- stdio: ['ignore', 'pipe', 'pipe'],
904
- env: smokeEnv({ ELECTRON_RUN_AS_NODE: '1' }),
905
- })
906
- } catch (error) {
907
- finish({ ok: false, message: `cannot start the runtime smoke process: ${error?.message || error}` })
908
- return
909
- }
910
- timer = setTimeout(() => {
911
- try { child?.kill() } catch {}
912
- finish({ ok: false, message: 'the runtime smoke process did not finish in time' })
913
- }, timeoutMs)
914
- timer.unref?.()
915
- try { child?.stdin?.on?.('error', () => {}) } catch {}
916
- try { child?.stderr?.on?.('data', () => {}) } catch {}
917
- child?.on?.('error', error => finish({ ok: false, message: `the runtime smoke process failed: ${error?.message || error}` }))
918
- child?.stdout?.on?.('data', chunk => {
919
- stdout += String(chunk)
920
- if (stdout.length > READY_LIMIT) {
921
- try { child?.kill() } catch {}
922
- finish({ ok: false, message: 'the runtime smoke output exceeded the limit' })
923
- }
924
- })
925
- child?.on?.('close', code => {
926
- const line = stdout.split(String.fromCharCode(10)).map(item => item.replace(/\r+$/, '')).filter(Boolean)[0] || ''
927
- let parsed = null
928
- try { parsed = JSON.parse(line) } catch { parsed = null }
929
- if (parsed && parsed.ok === true) finish({ ok: true, ortVersion: parsed.ortVersion || null, tokenizer: parsed.tokenizer === true, checks: [`smoke:onnxruntime-node@${parsed.ortVersion || 'unknown'}`] })
930
- else finish({ ok: false, message: String(parsed?.message || `the runtime smoke process exited with code ${code}`) })
931
- })
932
- })
933
- } finally {
934
- try { fs.rmSync(script, { force: true }) } catch {}
935
- }
936
- }
937
-
938
- let singleton = null
939
- export function managedEmbeddingRuntime(options = {}) {
940
- if (!singleton || options.root && path.resolve(options.root) !== singleton.root) singleton = createEmbeddingRuntimeInstaller(options)
941
- return singleton
942
- }
943
- export function resetManagedEmbeddingRuntime() {
944
- try { singleton?.dispose() } catch {}
945
- singleton = null
946
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+ import { spawn } from 'node:child_process'
5
+ import { ensureDir, readJsonStrict, writeJson } from './paths.js'
6
+ import { getEmbeddingCatalog, getEmbeddingModel } from './embedding-catalog.js'
7
+
8
+ // §14.13 受管 embedding runtime 安装器。
9
+ //
10
+ // 目标:用户装好插件、MemU 和已核实的 BGE 制品后,不需要再手写
11
+ // DSH_MEMU_EMBED_RUNTIME_DIR,也不需要装 Ollama 之类的第二个服务——首次需要时由本模块
12
+ // 把目录里 pin 住的运行时制品装进受管目录,然后原子切一个 active 指针。
13
+ //
14
+ // 硬约束(每一条都由下面的代码守卫,不是注释口号):
15
+ // 1. 只用 catalog 里显式写出的 https URL + 逐字节 sha256/bytes;缺任何一项就拒绝安装
16
+ // (LOCAL_VECTOR_RUNTIME_UNVERIFIED),绝不猜 hash、绝不落到「装了个大概能用的东西」。
17
+ // 2. 不跑 npm、不跑 postinstall、不读宿主 node_modules:tarball 按白名单解包,
18
+ // postinstall 专用依赖(adm-zip/global-agent/...)根本不落盘。
19
+ // 3. 不支持的平台(catalog 没有该平台原生库 hash)fail-closed 报 unsupported。
20
+ // 4. staging → 字节/hash 校验 → 解包 → 逐文件核对 → 原生加载 smoke → 原子发布。
21
+ // 失败、取消、hash 不符都在 staging 里结束,active 指针保持不动。
22
+ // 5. 幂等 + 并发安全:同进程 join 同一个 promise,跨进程用 staging 里的 pid 锁;
23
+ // 已安装且核对通过就直接复用,重启后不重下 115 MB。
24
+
25
+ export const RUNTIME_RECORD = 'installed.json'
26
+ export const RUNTIME_ACTIVE = 'active.json'
27
+ export const RUNTIME_STAGING = '.staging'
28
+ export const RUNTIME_CACHE = '.cache'
29
+ export const RUNTIME_LAYOUT = 'node_modules'
30
+
31
+ const DEFAULT_MAX_ARTIFACT_BYTES = 256 * 1024 * 1024
32
+ const DEFAULT_MAX_FILE_BYTES = 128 * 1024 * 1024
33
+ const DEFAULT_SMOKE_TIMEOUT_MS = 120_000
34
+ const DEFAULT_FETCH_TIMEOUT_MS = 600_000
35
+ // 分块 stall 超时:连续这么久没收到任何 chunk 就判定连接半开并 abort(S-1)。
36
+ const DEFAULT_STALL_TIMEOUT_MS = 30_000
37
+ const READY_LIMIT = 8_192
38
+
39
+ // The child smoke process needs the OS basics and nothing else: an inherited proxy
40
+ // variable could reroute a request and an inherited *_API_KEY would hand a cloud
41
+ // credential to a process whose whole job is loading a local .node file.
42
+ const DENIED_ENV_NAMES = Object.freeze(['http_proxy', 'https_proxy', 'all_proxy', 'no_proxy', 'node_options', 'node_path'])
43
+ const DENIED_ENV_PREFIXES = Object.freeze(['memu_', 'dsh_memu_embed_', 'openai_', 'azure_openai_', 'anthropic_', 'gemini_', 'google_', 'cohere_'])
44
+
45
+ function failure(code, message, extra) {
46
+ const error = new Error(message)
47
+ error.code = code
48
+ if (extra) Object.assign(error, extra)
49
+ return error
50
+ }
51
+
52
+ // S-16:下载前预检目标盘剩余空间,避免下到一半 ENOSPC 留下 .part 占空间。
53
+ // statfsSync 在部分平台/挂载点会抛错或回报 0,此时不拦(fail-open),让写入
54
+ // 路径自己报错,别因为一个探针就挡住本来能装成功的下载。
55
+ function ensureFreeSpace(dir, requiredBytes) {
56
+ if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
57
+ let available = null
58
+ try {
59
+ const stat = fs.statfsSync(dir)
60
+ available = Number(stat.bavail) * Number(stat.bsize)
61
+ } catch {
62
+ return
63
+ }
64
+ if (!Number.isFinite(available) || available <= 0) return
65
+ // 留一倍余量给解包与安装副本,别把盘压到 0。
66
+ if (available < requiredBytes * 2) {
67
+ throw failure('LOCAL_VECTOR_RUNTIME_DISK_ERROR', `not enough free space for the managed runtime: need ~${requiredBytes * 2} bytes, only ${available} available`)
68
+ }
69
+ }
70
+
71
+ function isPlainObject(value) {
72
+ return !!value && typeof value === 'object' && !Array.isArray(value)
73
+ }
74
+
75
+ function isSha256(value) {
76
+ return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value)
77
+ }
78
+
79
+ function isAbort(error, signal) {
80
+ return Boolean(signal?.aborted) || error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED' || error?.code === 'LOCAL_VECTOR_RUNTIME_ABORTED'
81
+ }
82
+
83
+ function sha256Of(buffer) {
84
+ return crypto.createHash('sha256').update(buffer).digest('hex')
85
+ }
86
+
87
+ function sha256File(file) {
88
+ return new Promise((resolve, reject) => {
89
+ const hash = crypto.createHash('sha256')
90
+ const stream = fs.createReadStream(file)
91
+ stream.on('data', chunk => hash.update(chunk))
92
+ stream.on('error', reject)
93
+ stream.on('end', () => resolve(hash.digest('hex')))
94
+ })
95
+ }
96
+
97
+ function artifactSafeName(artifact) {
98
+ return String(artifact?.name || 'artifact').replace(/[^A-Za-z0-9._@-]+/g, '-')
99
+ }
100
+
101
+ function cachePaths(cacheDir, artifact) {
102
+ const base = path.join(cacheDir, `${artifactSafeName(artifact)}-${artifact.sha256}.tgz`)
103
+ return { final: base, part: base + '.part' }
104
+ }
105
+
106
+ export function embeddingRuntimePlatform(platform = process.platform, arch = process.arch) {
107
+ return String(platform) + '-' + String(arch)
108
+ }
109
+
110
+ // catalog 的 <platform> 占位符是 'win32/x64' 这种目录形状,catalog 的 key 是 'win32-x64'。
111
+ export function runtimeNativeDir(platform) {
112
+ return String(platform).replace('-', '/')
113
+ }
114
+
115
+ export function runtimeKeyFor(entry, platform = embeddingRuntimePlatform()) {
116
+ const runtime = isPlainObject(entry?.runtime) ? entry.runtime : {}
117
+ return [String(runtime.engine || 'onnxruntime-node'), String(runtime.version || 'unpinned'), String(runtime.abi || 'unknown'), String(platform)].join('@').replace(/[^A-Za-z0-9._@-]+/g, '-')
118
+ }
119
+
120
+ /** 把 catalog 条目里的 runtime 事实整成一个可执行的安装计划;任何一项不完整都 fail-closed。 */
121
+ export function runtimePlan(entry, platform = embeddingRuntimePlatform()) {
122
+ const errors = []
123
+ const reject = (code, message) => errors.push({ code, message })
124
+ const runtime = isPlainObject(entry?.runtime) ? entry.runtime : null
125
+ const key = runtimeKeyFor(entry, platform)
126
+ const empty = { ok: false, errors, key, platform, engine: null, version: null, abi: null, artifacts: [], packageFiles: [], native: [], sources: [] }
127
+ if (!runtime) {
128
+ reject('RUNTIME_SPEC_MISSING', 'the catalog entry has no runtime spec')
129
+ return empty
130
+ }
131
+ if (entry?.availability !== 'available') reject('RUNTIME_ENTRY_NOT_AVAILABLE', `${String(entry?.id ?? 'unknown model')} is not an available catalog entry; no runtime may be installed for it`)
132
+ const engine = String(runtime.engine || '').trim()
133
+ const version = String(runtime.version || '').trim()
134
+ const abi = String(runtime.abi || '').trim()
135
+ if (!engine) reject('RUNTIME_ENGINE_MISSING', 'runtime.engine is required')
136
+ if (!version) reject('RUNTIME_VERSION_UNPINNED', 'runtime.version must be a pinned version, not null')
137
+ if (!abi) reject('RUNTIME_ABI_MISSING', 'runtime.abi is required')
138
+ const artifacts = []
139
+ const sourcesById = new Map()
140
+ for (const artifact of Array.isArray(runtime.artifacts) ? runtime.artifacts : []) {
141
+ if (!isPlainObject(artifact)) { reject('RUNTIME_ARTIFACT_INVALID', 'each runtime artifact must be an object'); continue }
142
+ const name = String(artifact.name || '')
143
+ if (!/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(name)) reject('RUNTIME_ARTIFACT_NAME_INVALID', `invalid artifact name: ${JSON.stringify(artifact.name)}`)
144
+ let url = null
145
+ try { url = new URL(String(artifact.url || '')) } catch { url = null }
146
+ if (!url || url.protocol !== 'https:') reject('RUNTIME_ARTIFACT_URL_INVALID', `artifact ${name} needs a pinned https URL`)
147
+ if (!Number.isInteger(artifact.bytes) || artifact.bytes <= 0) reject('RUNTIME_ARTIFACT_BYTES_INVALID', `artifact ${name} needs exact bytes`)
148
+ if (!isSha256(artifact.sha256)) reject('RUNTIME_ARTIFACT_SHA256_INVALID', `artifact ${name} needs a lowercase sha256; guessed hashes are not accepted`)
149
+ if (!Array.isArray(artifact.extract) || !artifact.extract.length) reject('RUNTIME_ARTIFACT_EXTRACT_MISSING', `artifact ${name} needs an explicit extraction allow-list`)
150
+ const sourceList = []
151
+ for (const source of Array.isArray(artifact.sources) ? artifact.sources : []) {
152
+ if (!isPlainObject(source)) { reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} has a non-object source`); continue }
153
+ const id = String(source.id || '').trim()
154
+ let sourceUrl = null
155
+ try { sourceUrl = new URL(String(source.url || '')) } catch { sourceUrl = null }
156
+ if (!id || !/^[a-z0-9._-]+$/.test(id) || !sourceUrl || sourceUrl.protocol !== 'https:') {
157
+ reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} has an invalid source: ${JSON.stringify(source.id || source.url)}`)
158
+ continue
159
+ }
160
+ if (sourceList.some(item => item.id === id)) { reject('RUNTIME_ARTIFACT_SOURCE_INVALID', `artifact ${name} repeats source ${id}`); continue }
161
+ sourceList.push({ id, label: String(source.label || id).slice(0, 80), url: sourceUrl.href })
162
+ }
163
+ if (!sourceList.length && url) sourceList.push({ id: 'npmjs', label: 'npmjs', url: url.href })
164
+ for (const source of sourceList) {
165
+ if (!sourcesById.has(source.id)) sourcesById.set(source.id, { id: source.id, label: source.label })
166
+ }
167
+ artifacts.push({
168
+ name,
169
+ version: String(artifact.version || version),
170
+ url: url ? url.href : null,
171
+ sources: sourceList,
172
+ bytes: Number.isInteger(artifact.bytes) ? artifact.bytes : null,
173
+ sha256: String(artifact.sha256 || ''),
174
+ integrity: typeof artifact.integrity === 'string' ? artifact.integrity : null,
175
+ license: typeof artifact.license === 'string' ? artifact.license : null,
176
+ extract: Array.isArray(artifact.extract) ? artifact.extract.map(item => String(item)) : [],
177
+ })
178
+ }
179
+ if (!artifacts.length) reject('RUNTIME_ARTIFACTS_MISSING', 'the runtime spec lists no pinned artifacts; nothing will be downloaded')
180
+ const packageFiles = []
181
+ for (const file of Array.isArray(runtime.packageFiles) ? runtime.packageFiles : []) {
182
+ if (!isPlainObject(file) || typeof file.package !== 'string' || !file.package) { reject('RUNTIME_PACKAGE_FILE_INVALID', 'each packageFiles entry needs a package name'); continue }
183
+ if (!Number.isInteger(file.bytes) || file.bytes <= 0) reject('RUNTIME_PACKAGE_FILE_INVALID', `packageFiles ${file.package} needs exact bytes`)
184
+ if (!isSha256(file.sha256)) reject('RUNTIME_PACKAGE_FILE_INVALID', `packageFiles ${file.package} needs a lowercase sha256`)
185
+ packageFiles.push({ package: file.package, path: `${RUNTIME_LAYOUT}/${file.package}/package.json`, bytes: Number(file.bytes), sha256: String(file.sha256) })
186
+ }
187
+ if (!packageFiles.length) reject('RUNTIME_PACKAGE_FILES_MISSING', 'the runtime spec pins no package.json facts; the extracted tree cannot be verified')
188
+ const native = []
189
+ for (const file of Array.isArray(runtime.native?.[platform]) ? runtime.native[platform] : []) {
190
+ if (!isPlainObject(file) || typeof file.path !== 'string' || !file.path.startsWith(RUNTIME_LAYOUT + '/')) { reject('RUNTIME_NATIVE_INVALID', 'each native file needs a path inside node_modules'); continue }
191
+ if (file.path.includes('..') || path.isAbsolute(file.path) || file.path.includes('\\')) { reject('RUNTIME_NATIVE_INVALID', `unsafe native path: ${JSON.stringify(file.path)}`); continue }
192
+ if (!Number.isInteger(file.bytes) || file.bytes <= 0) reject('RUNTIME_NATIVE_INVALID', `native file ${file.path} needs exact bytes`)
193
+ if (!isSha256(file.sha256)) reject('RUNTIME_NATIVE_INVALID', `native file ${file.path} needs a lowercase sha256`)
194
+ native.push({ path: file.path, bytes: Number(file.bytes), sha256: String(file.sha256) })
195
+ }
196
+ if (!native.length) reject('RUNTIME_NATIVE_MISSING', `no verified native runtime is pinned for ${platform}; refusing to install on this platform`)
197
+ return {
198
+ ok: errors.length === 0,
199
+ errors,
200
+ key,
201
+ platform,
202
+ engine: engine || null,
203
+ version: version || null,
204
+ abi: abi || null,
205
+ artifacts,
206
+ packageFiles,
207
+ native,
208
+ sources: [...sourcesById.values()],
209
+ }
210
+ }
211
+
212
+ /** 下载到的字节必须与 pin 的 bytes+sha256 完全一致;不匹配一律拒绝执行。 */
213
+ export function verifyRuntimeArtifact(bytes, artifact) {
214
+ const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? [])
215
+ if (!isSha256(artifact?.sha256)) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${String(artifact?.name || '?')} has no pinned sha256; refusing to install`)
216
+ if (!Number.isSafeInteger(artifact?.bytes) || artifact.bytes <= 0) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${String(artifact?.name || '?')} has no exact byte count`)
217
+ if (buffer.length !== artifact.bytes) {
218
+ throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `artifact ${String(artifact.name)} is ${buffer.length} bytes, expected ${artifact.bytes}`)
219
+ }
220
+ const digest = sha256Of(buffer)
221
+ if (digest !== artifact.sha256) {
222
+ throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `artifact ${String(artifact.name)} sha256 ${digest} does not match the pinned ${artifact.sha256}`)
223
+ }
224
+ return digest
225
+ }
226
+
227
+ /** tar 条目白名单:只允许 catalog 里写出的前缀,且必须换成该平台的原生库目录。 */
228
+ export function extractAllowList(artifact, platform) {
229
+ const nativeDir = runtimeNativeDir(platform)
230
+ return (Array.isArray(artifact?.extract) ? artifact.extract : [])
231
+ .map(item => String(item).replace('<platform>', nativeDir))
232
+ .map(item => item.replace(/^\/+/, '').replace(/\/+$/, ''))
233
+ .filter(Boolean)
234
+ }
235
+
236
+ // Windows 上刚写完的目录会被杀软/索引器短暂占用,rename 会抛 EPERM/EBUSY;
237
+ // 这是可恢复的瞬时错误,重试几次再判失败,别把「正在被扫描」当成「装坏了」。
238
+ async function renameWithRetry(from, to, options = {}) {
239
+ const attempts = Number.isFinite(options.attempts) ? options.attempts : 6
240
+ const delayMs = Number.isFinite(options.delayMs) ? options.delayMs : 60
241
+ let last = null
242
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
243
+ try {
244
+ fs.renameSync(from, to)
245
+ return
246
+ } catch (error) {
247
+ last = error
248
+ const code = String(error?.code || '')
249
+ if (attempt === attempts || !['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY'].includes(code)) break
250
+ await new Promise(resolve => setTimeout(resolve, delayMs * attempt))
251
+ }
252
+ }
253
+ throw last
254
+ }
255
+
256
+ export function createEmbeddingRuntimeInstaller(options = {}) {
257
+ const root = options.root
258
+ if (typeof root !== 'string' || !root.trim()) throw new TypeError('createEmbeddingRuntimeInstaller requires a root directory')
259
+ const baseDir = path.resolve(root)
260
+ const platform = String(options.platform || embeddingRuntimePlatform())
261
+ const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : fetch
262
+ const spawnImpl = typeof options.spawnImpl === 'function' ? options.spawnImpl : spawn
263
+ const executable = String(options.executable || process.execPath)
264
+ const now = typeof options.now === 'function' ? options.now : () => new Date().toISOString()
265
+ const logger = options.logger || null
266
+ const maxArtifactBytes = Number.isInteger(options.maxArtifactBytes) ? options.maxArtifactBytes : DEFAULT_MAX_ARTIFACT_BYTES
267
+ const maxFileBytes = Number.isInteger(options.maxFileBytes) ? options.maxFileBytes : DEFAULT_MAX_FILE_BYTES
268
+ const smokeTimeoutMs = Number.isInteger(options.smokeTimeoutMs) ? options.smokeTimeoutMs : DEFAULT_SMOKE_TIMEOUT_MS
269
+ const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
270
+ const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
271
+ const extract = typeof options.extract === 'function' ? options.extract : defaultExtract
272
+ const smoke = typeof options.smoke === 'function' ? options.smoke : defaultSmoke
273
+ const resolveEntry = typeof options.resolveEntry === 'function' ? options.resolveEntry : id => (id ? getEmbeddingModel(String(id)) : null)
274
+ const activeFile = path.join(baseDir, RUNTIME_ACTIVE)
275
+ const cacheDir = path.join(baseDir, RUNTIME_CACHE)
276
+ const inflight = new Map()
277
+ let job = null
278
+ let outcome = null
279
+ let disposed = false
280
+
281
+ const warn = message => { try { logger?.warn?.(message) } catch {} }
282
+
283
+ function insideRoot(target) {
284
+ const resolved = path.resolve(target)
285
+ if (resolved !== baseDir && !resolved.startsWith(baseDir + path.sep)) {
286
+ throw failure('LOCAL_VECTOR_RUNTIME_PATH_ESCAPE', `refusing to touch a path outside the managed runtime root: ${resolved}`)
287
+ }
288
+ return resolved
289
+ }
290
+
291
+ function readActive() {
292
+ const result = readJsonStrict(activeFile)
293
+ if (!result.ok || !isPlainObject(result.value)) return null
294
+ const value = result.value
295
+ if (typeof value.key !== 'string' || typeof value.dir !== 'string' || typeof value.platform !== 'string') return null
296
+ return value
297
+ }
298
+
299
+ function readRecord(dir) {
300
+ const result = readJsonStrict(path.join(dir, RUNTIME_RECORD))
301
+ return result.ok && isPlainObject(result.value) ? result.value : null
302
+ }
303
+
304
+ // The archive hash authenticates every extracted file, not only package/native pins.
305
+ // Keep that complete inventory and reject new files or links before any runtime reuse.
306
+ function inventoryTree(plan, dir, { deep = true, allowRecord = false } = {}) {
307
+ const files = []
308
+ const allowed = plan.artifacts.flatMap(artifact => extractAllowList(artifact, plan.platform).map(prefix => RUNTIME_LAYOUT + '/' + artifact.name + '/' + prefix))
309
+ if (!fs.lstatSync(dir).isDirectory() || fs.lstatSync(dir).isSymbolicLink()) throw failure('LOCAL_VECTOR_RUNTIME_PATH_ESCAPE', 'runtime root must be a real directory')
310
+ const visit = (parent, relative = '') => {
311
+ for (const name of fs.readdirSync(parent).sort()) {
312
+ const rel = relative ? relative + '/' + name : name
313
+ const target = path.join(parent, name)
314
+ const stat = fs.lstatSync(target)
315
+ if (stat.isSymbolicLink()) throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', 'runtime inventory contains a link: ' + rel)
316
+ if (allowRecord && rel === RUNTIME_RECORD && stat.isFile()) continue
317
+ if (stat.isDirectory()) {
318
+ if (!allowed.some(prefix => prefix === rel || prefix.startsWith(rel + '/') || rel.startsWith(prefix + '/'))) throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', 'runtime inventory contains an unlisted directory: ' + rel)
319
+ visit(target, rel)
320
+ } else if (stat.isFile()) {
321
+ if (!allowed.some(prefix => rel === prefix || rel.startsWith(prefix + '/'))) throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', 'runtime inventory contains an unlisted file: ' + rel)
322
+ if (stat.size > maxFileBytes) throw failure('LOCAL_VECTOR_RUNTIME_TOO_LARGE', 'runtime inventory file exceeds its limit: ' + rel)
323
+ files.push({ path: rel, bytes: stat.size, ...(deep ? { sha256: sha256Of(fs.readFileSync(target)) } : {}) })
324
+ } else {
325
+ throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', 'runtime inventory contains a non-regular entry: ' + rel)
326
+ }
327
+ }
328
+ }
329
+ visit(dir)
330
+ return files
331
+ }
332
+
333
+ // 复用判定:便宜(只比字节数)还是彻底(重算 sha256)由调用方决定。
334
+ // 便宜路径抓「文件被删/被换/明显截断」,彻底路径抓内容差异;两者都不猜。
335
+ function inspectPlan(plan, { deep = false } = {}) {
336
+ const active = readActive()
337
+ if (!active) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_ABSENT' }
338
+ if (active.key !== plan.key || active.platform !== plan.platform) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_STALE' }
339
+ let dir
340
+ try { dir = insideRoot(active.dir) } catch { return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_PATH_ESCAPE' } }
341
+ const record = readRecord(dir)
342
+ if (!record) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_MISSING' }
343
+ if (record.key !== plan.key || record.platform !== plan.platform || record.engine !== plan.engine || record.version !== plan.version || record.abi !== plan.abi) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_STALE' }
344
+ const recordedArtifacts = Array.isArray(record.artifacts) ? record.artifacts : []
345
+ if (recordedArtifacts.length !== plan.artifacts.length || plan.artifacts.some(artifact => {
346
+ const saved = recordedArtifacts.find(item => item && item.name === artifact.name)
347
+ return !saved || saved.version !== artifact.version || saved.url !== artifact.url || saved.bytes !== artifact.bytes || saved.sha256 !== artifact.sha256
348
+ })) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_STALE' }
349
+ const expected = [...plan.packageFiles, ...plan.native]
350
+ const recorded = Array.isArray(record.files) ? record.files : []
351
+ if (record.inventoryVersion !== 1 || recorded.length < expected.length) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_INCOMPLETE' }
352
+ const byPath = new Map()
353
+ for (const file of recorded) {
354
+ if (!file || typeof file.path !== 'string' || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || !isSha256(file.sha256) || byPath.has(file.path)) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_INCOMPLETE' }
355
+ byPath.set(file.path, file)
356
+ }
357
+ for (const file of expected) {
358
+ const pinned = byPath.get(file.path)
359
+ if (!pinned || pinned.sha256 !== file.sha256 || pinned.bytes !== file.bytes) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_RECORD_STALE', path: file.path }
360
+ }
361
+ let actual
362
+ try { actual = inventoryTree(plan, dir, { deep, allowRecord: true }) } catch (error) { return { ok: false, code: error?.code || 'LOCAL_VECTOR_RUNTIME_INCOMPLETE' } }
363
+ if (actual.length !== recorded.length) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE' }
364
+ for (const file of actual) {
365
+ const pinned = byPath.get(file.path)
366
+ if (!pinned) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', path: file.path }
367
+ if (file.bytes !== pinned.bytes) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_INCOMPLETE', path: file.path }
368
+ if (deep && file.sha256 !== pinned.sha256) return { ok: false, code: 'LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', path: file.path }
369
+ }
370
+ return { ok: true, dir, record }
371
+ }
372
+
373
+ function planFor(modelId) {
374
+ const entry = resolveEntry(modelId)
375
+ if (!entry) {
376
+ const fallback = getEmbeddingCatalog().find(item => item.availability === 'available')
377
+ if (!fallback) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', 'no available catalog entry pins a runtime; nothing will be installed')
378
+ return { entry: fallback, plan: runtimePlan(fallback, platform) }
379
+ }
380
+ return { entry, plan: runtimePlan(entry, platform) }
381
+ }
382
+
383
+ function status({ deep = false, modelId = null } = {}) {
384
+ const base = { source: 'managed', platform, root: baseDir }
385
+ let resolved = null
386
+ try { resolved = planFor(modelId) } catch (error) { return { ...base, status: 'unsupported', ready: false, key: null, path: null, error: { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_UNVERIFIED'), message: String(error?.message || error) } } }
387
+ const entry = resolved.entry
388
+ const plan = resolved.plan
389
+ const pinned = { key: plan.key, engine: plan.engine, version: plan.version, abi: plan.abi, artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256, license: item.license })), sources: plan.sources, verifiedPlatforms: Object.keys(entry?.runtime?.install?.platforms || {}) }
390
+ if (!plan.ok) {
391
+ return { ...base, ...pinned, status: 'unsupported', ready: false, path: null, error: { code: 'LOCAL_VECTOR_RUNTIME_UNVERIFIED', message: 'the catalog does not pin a complete runtime for this platform', errors: plan.errors } }
392
+ }
393
+ if (job && job.key === plan.key) {
394
+ return { ...base, ...pinned, status: job.state, ready: false, path: null, progress: { ...job.progress }, startedAt: job.startedAt, downloadSource: job.source || null }
395
+ }
396
+ const inspect = inspectPlan(plan, { deep })
397
+ if (inspect.ok) {
398
+ return { ...base, ...pinned, status: 'installed', ready: true, path: inspect.dir, installedAt: inspect.record.installedAt || null, verifiedAt: inspect.record.verifiedAt || null, checks: Array.isArray(inspect.record.checks) ? [...inspect.record.checks] : [], smoke: inspect.record.smoke || null }
399
+ }
400
+ if (outcome && outcome.key === plan.key && outcome.status === 'failed') {
401
+ return { ...base, ...pinned, status: 'failed', ready: false, path: null, error: { ...outcome.error }, inspect: inspect.code }
402
+ }
403
+ return { ...base, ...pinned, status: 'absent', ready: false, path: null, inspect: inspect.code }
404
+ }
405
+
406
+ function activeDir({ deep = false, modelId = null } = {}) {
407
+ const current = status({ deep, modelId })
408
+ return current.status === 'installed' ? current.path : null
409
+ }
410
+
411
+ function acquireLock(stagingRoot) {
412
+ ensureDir(stagingRoot)
413
+ const lockFile = path.join(stagingRoot, 'install.lock')
414
+ const token = crypto.randomUUID()
415
+ const contents = JSON.stringify({ pid: process.pid, at: Date.now(), token })
416
+ const release = () => {
417
+ try { if (fs.readFileSync(lockFile, 'utf8') === contents) fs.unlinkSync(lockFile) } catch {}
418
+ }
419
+ for (let attempt = 0; attempt < 2; attempt++) {
420
+ try {
421
+ const fd = fs.openSync(lockFile, 'wx', 0o600)
422
+ try { fs.writeFileSync(fd, contents) } finally { fs.closeSync(fd) }
423
+ return release
424
+ } catch (error) {
425
+ if (error?.code !== 'EEXIST') throw error
426
+ let owner = null
427
+ let observed = null
428
+ try { observed = fs.readFileSync(lockFile, 'utf8'); owner = JSON.parse(observed) } catch {}
429
+ // Age is not proof of death. Unknown owners and EPERM probes stay busy.
430
+ let dead = false
431
+ if (owner && Number.isSafeInteger(owner.pid) && owner.pid > 0) {
432
+ try { process.kill(owner.pid, 0) } catch (probe) { dead = probe?.code === 'ESRCH' }
433
+ }
434
+ if (!dead) throw failure('LOCAL_VECTOR_RUNTIME_BUSY', 'another process is installing the managed embedding runtime; retry when it finishes')
435
+ try { if (fs.readFileSync(lockFile, 'utf8') === observed) fs.unlinkSync(lockFile) } catch {}
436
+ }
437
+ }
438
+ throw failure('LOCAL_VECTOR_RUNTIME_BUSY', 'cannot take the managed runtime install lock; retry later')
439
+ }
440
+
441
+ function seedArtifactCache(plan, stagingRoot) {
442
+ ensureDir(insideRoot(cacheDir))
443
+ let dirs = []
444
+ try {
445
+ dirs = fs.readdirSync(stagingRoot, { withFileTypes: true })
446
+ .filter(entry => entry.isDirectory() && entry.name.startsWith('install-'))
447
+ .map(entry => entry.name)
448
+ } catch { return }
449
+ for (const artifact of plan.artifacts) {
450
+ const paths = cachePaths(cacheDir, artifact)
451
+ if (fs.existsSync(paths.final)) continue
452
+ let currentPart = 0
453
+ try { currentPart = fs.statSync(paths.part).size } catch {}
454
+ const wanted = `${artifactSafeName(artifact)}.tgz`
455
+ let best = null
456
+ for (const dir of dirs) {
457
+ const artifactDir = path.join(stagingRoot, dir, '.artifacts')
458
+ let files = []
459
+ try { files = fs.readdirSync(artifactDir) } catch { continue }
460
+ for (const name of files) {
461
+ if (name !== wanted) continue
462
+ try {
463
+ const stat = fs.statSync(path.join(artifactDir, name))
464
+ if (stat.isFile() && stat.size > 0 && stat.size <= artifact.bytes && (!best || stat.size > best.size)) {
465
+ best = { file: path.join(artifactDir, name), size: stat.size }
466
+ }
467
+ } catch {}
468
+ }
469
+ }
470
+ if (!best || best.size <= currentPart) continue
471
+ try {
472
+ fs.copyFileSync(best.file, paths.part)
473
+ warn(`seeded runtime artifact cache from previous staging: ${artifact.name} (${best.size} bytes)`)
474
+ } catch (error) {
475
+ warn(`cannot seed runtime artifact cache for ${artifact.name}: ${error?.message || error}`)
476
+ }
477
+ }
478
+ }
479
+
480
+ async function downloadArtifact(artifact, sourceId, controller, report) {
481
+ if (!Number.isInteger(artifact.bytes) || artifact.bytes <= 0) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${artifact.name} has no exact byte count`)
482
+ if (artifact.bytes > maxArtifactBytes) throw failure('LOCAL_VECTOR_RUNTIME_TOO_LARGE', `artifact ${artifact.name} declares ${artifact.bytes} bytes, above the ${maxArtifactBytes} byte cap`)
483
+ const source = artifact.sources.find(item => item.id === sourceId) || artifact.sources[0] || null
484
+ const url = source?.url || artifact.url
485
+ if (!url) throw failure('LOCAL_VECTOR_RUNTIME_ARTIFACT_URL_INVALID', `artifact ${artifact.name} has no download URL`)
486
+ ensureDir(insideRoot(cacheDir))
487
+ const paths = cachePaths(cacheDir, artifact)
488
+ const bump = (bytes) => {
489
+ job.progress.bytes += bytes
490
+ const nowMs = Date.now()
491
+ const elapsed = (nowMs - (job.progress.speedAt || nowMs)) / 1000
492
+ if (elapsed >= 0.5) {
493
+ job.progress.speedBps = Math.max(0, (job.progress.bytes - (job.progress.speedBytes || 0)) / elapsed)
494
+ job.progress.speedAt = nowMs
495
+ job.progress.speedBytes = job.progress.bytes
496
+ report()
497
+ }
498
+ }
499
+ try {
500
+ const complete = fs.statSync(paths.final)
501
+ if (complete.size === artifact.bytes) {
502
+ const digest = await sha256File(paths.final)
503
+ if (digest === artifact.sha256) {
504
+ job.progress.bytes += artifact.bytes
505
+ report()
506
+ return { path: paths.final, bytes: artifact.bytes, sha256: digest, source: source?.id || null, cached: true }
507
+ }
508
+ }
509
+ try { fs.rmSync(paths.final, { force: true }) } catch {}
510
+ } catch {}
511
+ let existing = 0
512
+ try { existing = fs.statSync(paths.part).size } catch {}
513
+ if (existing > artifact.bytes) {
514
+ try { fs.rmSync(paths.part, { force: true }) } catch {}
515
+ existing = 0
516
+ }
517
+ if (existing === artifact.bytes) {
518
+ const digest = await sha256File(paths.part)
519
+ if (digest === artifact.sha256) {
520
+ await renameWithRetry(paths.part, paths.final)
521
+ job.progress.bytes += artifact.bytes
522
+ report()
523
+ return { path: paths.final, bytes: artifact.bytes, sha256: digest, source: source?.id || null, cached: true }
524
+ }
525
+ try { fs.rmSync(paths.part, { force: true }) } catch {}
526
+ existing = 0
527
+ }
528
+ if (existing > 0) {
529
+ job.progress.bytes += existing
530
+ // Speed is about the bytes this process receives, not the part inherited
531
+ // from the previous run; anchor the sample at the resumed offset.
532
+ job.progress.speedBytes = job.progress.bytes
533
+ job.progress.speedAt = Date.now()
534
+ job.progress.current = artifact.name
535
+ report()
536
+ }
537
+ const headers = { 'accept-encoding': 'identity' }
538
+ if (existing > 0) headers.Range = `bytes=${existing}-`
539
+ // S-1:fetch 总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
540
+ // 连接让 for-await 永久 pending;超时单独记账,别被 install() 误判成用户取消。
541
+ let timedOut = false
542
+ const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
543
+ totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
544
+ const stallController = new AbortController()
545
+ let stallTimer = null
546
+ const armStall = () => {
547
+ if (stallTimer) clearTimeout(stallTimer)
548
+ stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
549
+ stallTimer.unref?.()
550
+ }
551
+ const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
552
+ const timeoutFailure = cause => failure('LOCAL_VECTOR_RUNTIME_DOWNLOAD_TIMEOUT', `${artifact.name} download timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
553
+ const abortedFailure = cause => failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted', { cause })
554
+ // for-await 被 signal 中断时抛原生 AbortError,按来源还原成明确失败码;
555
+ // 磁盘写失败(ENOSPC/EIO/...)清掉 .part,别让半成品占着空间(S-16)。
556
+ let removePart = false
557
+ const streamFailure = error => {
558
+ if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
559
+ if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
560
+ if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
561
+ removePart = true
562
+ return failure('LOCAL_VECTOR_RUNTIME_DISK_ERROR', `${artifact.name} download failed with ${error.code}; partial download removed`, { cause: error })
563
+ }
564
+ return error
565
+ }
566
+ armStall()
567
+ const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
568
+ let response
569
+ try {
570
+ response = await fetchImpl(url, { signal, redirect: 'follow', headers })
571
+ } catch (error) {
572
+ if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
573
+ if (isAbort(error, controller.signal)) throw abortedFailure(error)
574
+ throw failure('LOCAL_VECTOR_RUNTIME_NETWORK_ERROR', `cannot fetch ${artifact.name}: ${error?.message || error}`, { cause: error })
575
+ }
576
+ if (!response || !response.ok) throw failure('LOCAL_VECTOR_RUNTIME_HTTP_ERROR', `registry returned ${response?.status ?? 'no response'} for ${artifact.name}`)
577
+ let append = existing > 0
578
+ if (append && response.status === 200) {
579
+ // The source ignored Range. Keep the file correct by starting over; a later
580
+ // attempt may still resume from the new bytes.
581
+ job.progress.bytes = Math.max(0, job.progress.bytes - existing)
582
+ append = false
583
+ existing = 0
584
+ } else if (append) {
585
+ const contentRange = String(response.headers?.get?.('content-range') || '')
586
+ const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(contentRange)
587
+ if (!match || Number(match[1]) !== existing || Number(match[3]) !== artifact.bytes) {
588
+ throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} returned an unexpected Content-Range: ${contentRange || '(missing)'}`)
589
+ }
590
+ const declared = Number(response.headers?.get?.('content-length'))
591
+ if (Number.isFinite(declared) && declared > 0 && declared !== artifact.bytes - existing) {
592
+ throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} content-length ${declared} does not match the remaining ${artifact.bytes - existing} bytes`)
593
+ }
594
+ } else {
595
+ const declared = Number(response.headers?.get?.('content-length'))
596
+ if (Number.isFinite(declared) && declared > 0 && declared !== artifact.bytes) {
597
+ throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} content-length ${declared} does not match the pinned ${artifact.bytes} bytes`)
598
+ }
599
+ }
600
+ let size = existing
601
+ const fd = fs.openSync(paths.part, append ? 'a' : 'w', 0o600)
602
+ try {
603
+ const body = response.body
604
+ if (body && typeof body[Symbol.asyncIterator] === 'function') {
605
+ try {
606
+ for await (const chunk of body) {
607
+ if (controller.signal.aborted) throw abortedFailure(null)
608
+ armStall()
609
+ size += chunk.length
610
+ if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
611
+ fs.writeSync(fd, chunk)
612
+ bump(chunk.length)
613
+ }
614
+ } catch (error) { throw streamFailure(error) }
615
+ } else {
616
+ try {
617
+ const buffer = Buffer.from(await response.arrayBuffer())
618
+ size += buffer.length
619
+ if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
620
+ fs.writeSync(fd, buffer)
621
+ bump(buffer.length)
622
+ } catch (error) { throw streamFailure(error) }
623
+ }
624
+ } finally {
625
+ clearStall()
626
+ try { fs.closeSync(fd) } catch {}
627
+ if (removePart) { try { fs.rmSync(paths.part, { force: true }) } catch {} }
628
+ }
629
+ if (size !== artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} is ${size} bytes, expected ${artifact.bytes}`)
630
+ const digest = await sha256File(paths.part)
631
+ if (digest !== artifact.sha256) {
632
+ try { fs.rmSync(paths.part, { force: true }) } catch {}
633
+ throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `${artifact.name} sha256 ${digest} does not match the pinned ${artifact.sha256}`)
634
+ }
635
+ await renameWithRetry(paths.part, paths.final)
636
+ return { path: paths.final, bytes: size, sha256: digest, source: source?.id || null, cached: false }
637
+ }
638
+
639
+ function verifyExtracted(plan, dir) {
640
+ const checks = []
641
+ for (const file of plan.packageFiles) {
642
+ const target = path.join(dir, ...file.path.split('/'))
643
+ let bytes
644
+ try { bytes = fs.readFileSync(target) } catch { throw failure('LOCAL_VECTOR_RUNTIME_INCOMPLETE', `the extracted tree has no ${file.path}`) }
645
+ if (bytes.length !== file.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${file.path} is ${bytes.length} bytes, expected ${file.bytes}`)
646
+ const digest = sha256Of(bytes)
647
+ if (digest !== file.sha256) throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
648
+ checks.push(`${file.path}@${digest.slice(0, 12)}`)
649
+ }
650
+ for (const file of plan.native) {
651
+ const target = path.join(dir, ...file.path.split('/'))
652
+ let stat
653
+ try { stat = fs.statSync(target) } catch { throw failure('LOCAL_VECTOR_RUNTIME_INCOMPLETE', `the extracted tree has no ${file.path}`) }
654
+ if (!stat.isFile() || stat.size !== file.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${file.path} is not the pinned ${file.bytes} bytes`)
655
+ const digest = sha256Of(fs.readFileSync(target))
656
+ if (digest !== file.sha256) throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
657
+ checks.push(`${path.posix.basename(file.path)}@${digest.slice(0, 12)}`)
658
+ }
659
+ // 解包白名单不能被绕过成「多装了别的东西」:平台目录里只许出现 pin 住的文件。
660
+ const nativeRoot = path.posix.join(RUNTIME_LAYOUT, 'onnxruntime-node', 'bin', plan.abi?.startsWith('napi') ? plan.abi : 'napi-v6', runtimeNativeDir(plan.platform))
661
+ const expectedNative = new Set(plan.native.map(file => String(file.path).split('/').pop()))
662
+ let entries = []
663
+ try { entries = fs.readdirSync(path.join(dir, ...nativeRoot.split('/'))) } catch { entries = [] }
664
+ if (entries.length) {
665
+ const unexpected = entries.filter(name => !expectedNative.has(name))
666
+ if (unexpected.length) throw failure('LOCAL_VECTOR_RUNTIME_UNEXPECTED_FILE', `the extracted native directory contains unexpected files: ${unexpected.join(', ')}`)
667
+ }
668
+ return checks
669
+ }
670
+
671
+ async function install(plan, options) {
672
+ const requestedSource = options.source ? String(options.source) : null
673
+ const source = requestedSource
674
+ ? plan.sources.find(item => item.id === requestedSource)
675
+ : plan.sources[0] || null
676
+ if (requestedSource && !source) throw failure('LOCAL_VECTOR_RUNTIME_SOURCE_UNKNOWN', `unknown runtime download source: ${requestedSource}`)
677
+ const downloadSource = source?.id || null
678
+ const controller = new AbortController()
679
+ const onAbort = () => controller.abort()
680
+ options.signal?.addEventListener('abort', onAbort, { once: true })
681
+ const totalBytes = plan.artifacts.reduce((sum, artifact) => sum + (artifact.bytes || 0), 0)
682
+ job = {
683
+ key: plan.key,
684
+ state: 'downloading',
685
+ startedAt: now(),
686
+ source: downloadSource,
687
+ controller,
688
+ progress: { artifacts: plan.artifacts.length, done: 0, bytes: 0, totalBytes, current: null, speedBps: 0, speedAt: Date.now(), speedBytes: 0 },
689
+ }
690
+ const report = () => { try { options.onProgress?.({ ...job.progress }) } catch {} }
691
+ let staging = null
692
+ let release = null
693
+ let published = false
694
+ try {
695
+ const stagingRoot = insideRoot(path.join(baseDir, RUNTIME_STAGING))
696
+ release = acquireLock(stagingRoot)
697
+ // 抢到锁之后先重看一眼:另一个进程可能刚刚装完,这时直接复用,不重复下载 115 MB。
698
+ const existing = inspectPlan(plan, { deep: true })
699
+ if (existing.ok) {
700
+ job = null
701
+ return { status: 'installed', ready: true, reused: true, key: plan.key, platform: plan.platform, path: existing.dir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: existing.record.installedAt || null, verifiedAt: existing.record.verifiedAt || null, checks: Array.isArray(existing.record.checks) ? existing.record.checks : [], artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: existing.record.smoke || null }
702
+ }
703
+ // S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
704
+ ensureFreeSpace(baseDir, totalBytes)
705
+ // Pick up a partial download from an interrupted process. Old installers kept
706
+ // the tarball inside their own staging dir; this stable cache is what makes a
707
+ // restart resume instead of re-downloading 115 MB.
708
+ seedArtifactCache(plan, stagingRoot)
709
+ staging = fs.mkdtempSync(path.join(stagingRoot, 'install-'))
710
+ const archives = []
711
+ for (const artifact of plan.artifacts) {
712
+ if (controller.signal.aborted) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted')
713
+ job.progress.current = artifact.name
714
+ report()
715
+ const saved = await downloadArtifact(artifact, downloadSource, controller, report)
716
+ archives.push({ artifact, file: saved.path })
717
+ job.progress.done += 1
718
+ report()
719
+ }
720
+ job.state = 'verifying'
721
+ job.progress.current = null
722
+ report()
723
+ for (const { artifact, file } of archives) {
724
+ const allowList = extractAllowList(artifact, plan.platform)
725
+ if (!allowList.length) throw failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `artifact ${artifact.name} has an empty extraction allow-list`)
726
+ const target = ensureDir(path.join(staging, RUNTIME_LAYOUT, artifact.name))
727
+ await extract({ file, cwd: target, allowList, maxFileBytes, artifact })
728
+ }
729
+ const checks = verifyExtracted(plan, staging)
730
+ const files = inventoryTree(plan, staging)
731
+ job.state = 'installing'
732
+ report()
733
+ const smokeResult = await smoke({ dir: staging, plan, executable, spawnImpl, timeoutMs: smokeTimeoutMs })
734
+ if (!smokeResult || smokeResult.ok !== true) {
735
+ throw failure('LOCAL_VECTOR_RUNTIME_SMOKE_FAILED', `the extracted runtime cannot load its native modules: ${String(smokeResult?.message || 'unknown reason')}`)
736
+ }
737
+ if (JSON.stringify(inventoryTree(plan, staging)) !== JSON.stringify(files)) throw failure('LOCAL_VECTOR_RUNTIME_HASH_MISMATCH', 'runtime files changed during install smoke')
738
+ const record = {
739
+ schema: 1,
740
+ key: plan.key,
741
+ platform: plan.platform,
742
+ engine: plan.engine,
743
+ version: plan.version,
744
+ abi: plan.abi,
745
+ installedAt: now(),
746
+ verifiedAt: now(),
747
+ source: 'catalog-pinned',
748
+ downloadSource,
749
+ postinstall: 'never-run',
750
+ inventoryVersion: 1,
751
+ artifacts: plan.artifacts.map(artifact => ({ name: artifact.name, version: artifact.version, url: artifact.url, bytes: artifact.bytes, sha256: artifact.sha256, integrity: artifact.integrity, license: artifact.license })),
752
+ files,
753
+ checks: [...checks, ...(Array.isArray(smokeResult.checks) ? smokeResult.checks : [])],
754
+ smoke: { ok: true, ortVersion: smokeResult.ortVersion || null, tokenizer: smokeResult.tokenizer === true },
755
+ }
756
+ writeJson(path.join(staging, RUNTIME_RECORD), record)
757
+ // Every install gets its own generation. Keep the old active directory in place
758
+ // until the active pointer commit succeeds; this makes pointer-write failure safe.
759
+ const previousActive = readActive()
760
+ const finalDir = insideRoot(path.join(baseDir, plan.key + '-' + crypto.randomUUID()))
761
+ try {
762
+ await renameWithRetry(staging, finalDir)
763
+ staging = null
764
+ published = true
765
+ } catch (error) {
766
+ throw failure('LOCAL_VECTOR_RUNTIME_INSTALL_FAILED', `cannot move the verified runtime into place: ${error?.message || error}`, { cause: error })
767
+ }
768
+ try {
769
+ writeJson(activeFile, { schema: 1, key: plan.key, platform: plan.platform, dir: finalDir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: record.installedAt, verifiedAt: record.verifiedAt })
770
+ } catch (error) {
771
+ try { fs.rmSync(finalDir, { recursive: true, force: true }) } catch {}
772
+ throw failure('LOCAL_VECTOR_RUNTIME_INSTALL_FAILED', `cannot publish the managed runtime active pointer: ${error?.message || error}`, { cause: error })
773
+ }
774
+ // Cleanup is deliberately after pointer publication. A stale cleanup failure is harmless.
775
+ if (previousActive?.dir && previousActive.dir !== finalDir) {
776
+ try { fs.rmSync(insideRoot(previousActive.dir), { recursive: true, force: true }) } catch {}
777
+ }
778
+ outcome = null
779
+ job = null
780
+ return { status: 'installed', ready: true, reused: false, key: plan.key, platform: plan.platform, path: finalDir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: record.installedAt, verifiedAt: record.verifiedAt, checks: record.checks, artifacts: record.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: record.smoke }
781
+ } catch (error) {
782
+ const aborted = isAbort(error, controller.signal)
783
+ const code = aborted ? 'LOCAL_VECTOR_RUNTIME_ABORTED' : (typeof error?.code === 'string' && error.code.startsWith('LOCAL_VECTOR_RUNTIME_') ? error.code : 'LOCAL_VECTOR_RUNTIME_INSTALL_FAILED')
784
+ const failed = code === error?.code ? error : failure(code, `installing the managed embedding runtime failed: ${error?.message || error}`, { cause: error })
785
+ outcome = { key: plan.key, status: 'failed', error: { code, message: String(failed.message || error) } }
786
+ job = null
787
+ warn(`managed embedding runtime install failed (${code}): ${failed.message}`)
788
+ throw failed
789
+ } finally {
790
+ options.signal?.removeEventListener?.('abort', onAbort)
791
+ try { release?.() } catch {}
792
+ if (staging && !published) { try { fs.rmSync(staging, { recursive: true, force: true }) } catch {} }
793
+ }
794
+ }
795
+
796
+ async function ensure(options = {}) {
797
+ if (disposed) throw failure('LOCAL_VECTOR_RUNTIME_CLOSED', 'the managed runtime installer is closed')
798
+ const { entry, plan } = planFor(options.modelId || options.id || null)
799
+ if (!plan.ok) {
800
+ const error = failure('LOCAL_VECTOR_RUNTIME_UNVERIFIED', `no verified managed runtime is available for ${plan.platform}`, { errors: plan.errors, entry: entry?.id ?? null })
801
+ throw error
802
+ }
803
+ const existing = inspectPlan(plan, { deep: true })
804
+ if (existing.ok) {
805
+ return { status: 'installed', ready: true, reused: true, key: plan.key, platform: plan.platform, path: existing.dir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: existing.record.installedAt || null, verifiedAt: existing.record.verifiedAt || null, checks: Array.isArray(existing.record.checks) ? existing.record.checks : [], artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: existing.record.smoke || null }
806
+ }
807
+ const pending = inflight.get(plan.key)
808
+ if (pending) return pending
809
+ if (options.reuseOnly === true) throw failure('LOCAL_VECTOR_RUNTIME_ABSENT', 'the managed embedding runtime is not installed yet', { inspect: existing.code })
810
+ if (options.confirmed !== true) throw failure('LOCAL_VECTOR_RUNTIME_CONFIRMATION_REQUIRED', 'installing the managed embedding runtime downloads pinned artifacts and needs explicit confirmation: ensure({ confirmed: true })')
811
+ if (options.signal?.aborted) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted before it started')
812
+ const run = install(plan, options).finally(() => { inflight.delete(plan.key) })
813
+ inflight.set(plan.key, run)
814
+ return run
815
+ }
816
+
817
+ function abort() {
818
+ try { job?.controller?.abort() } catch {}
819
+ }
820
+
821
+ function dispose() {
822
+ disposed = true
823
+ abort()
824
+ }
825
+
826
+ return { root: baseDir, platform, getStatus: status, ensure, activeDir, abort, dispose }
827
+ }
828
+
829
+ // ------------------------------------------------------------------ 默认解包 / 默认 smoke
830
+
831
+ async function defaultExtract({ file, cwd, allowList, maxFileBytes }) {
832
+ const { x } = await import('tar')
833
+ ensureDir(cwd)
834
+ const allowed = rel => allowList.some(prefix => rel === prefix || rel.startsWith(prefix + '/'))
835
+ const allowDir = rel => allowList.some(prefix => prefix === rel || prefix.startsWith(rel + '/') || rel.startsWith(prefix + '/'))
836
+ await x({
837
+ file,
838
+ cwd,
839
+ strip: 1,
840
+ strict: true,
841
+ preservePaths: false,
842
+ filter: (name, entry) => {
843
+ const rel = String(name || '').replace(/^package\//, '')
844
+ if (!rel || rel === String(name)) return false
845
+ if (rel.includes('..') || path.isAbsolute(rel) || rel.includes('\\')) return false
846
+ if (entry?.type === 'Directory') return allowDir(rel)
847
+ if (entry?.type !== 'File') return false
848
+ if (!allowed(rel)) return false
849
+ return Number(entry.size || 0) <= maxFileBytes
850
+ },
851
+ })
852
+ }
853
+
854
+ const SMOKE_SOURCE = [
855
+ "const path = require('node:path')",
856
+ "const { createRequire } = require('node:module')",
857
+ "const write = value => process.stdout.write(JSON.stringify(value) + '\\n')",
858
+ "try {",
859
+ " const from = createRequire(path.join(__dirname, 'entry.cjs'))",
860
+ " const ort = from('onnxruntime-node')",
861
+ " if (!ort || typeof ort.InferenceSession !== 'function') throw new Error('onnxruntime-node exposes no InferenceSession')",
862
+ " const pkg = from('onnxruntime-node/package.json')",
863
+ " const tok = from('@huggingface/tokenizers')",
864
+ " const Tokenizer = tok && (tok.Tokenizer || (tok.default && tok.default.Tokenizer))",
865
+ " if (typeof Tokenizer === 'undefined') throw new Error('@huggingface/tokenizers exposes no Tokenizer')",
866
+ " write({ ok: true, ortVersion: String((pkg && pkg.version) || ''), tokenizer: true })",
867
+ "} catch (error) {",
868
+ " write({ ok: false, message: String((error && error.message) || error) })",
869
+ " process.exitCode = 1",
870
+ "}",
871
+ ].join('\n')
872
+
873
+ function smokeEnv(extra) {
874
+ const env = {}
875
+ for (const [name, value] of Object.entries(process.env)) {
876
+ if (typeof value !== 'string') continue
877
+ const lower = name.toLowerCase()
878
+ if (DENIED_ENV_NAMES.includes(lower) || lower.includes('proxy')) continue
879
+ if (DENIED_ENV_PREFIXES.some(prefix => lower.startsWith(prefix))) continue
880
+ env[name] = value
881
+ }
882
+ return { ...env, ...extra }
883
+ }
884
+
885
+ async function defaultSmoke({ dir, executable, spawnImpl, timeoutMs }) {
886
+ const script = path.join(dir, '.runtime-smoke.cjs')
887
+ fs.writeFileSync(script, SMOKE_SOURCE + '\n', { mode: 0o600, flag: 'w' })
888
+ try {
889
+ return await new Promise(resolve => {
890
+ let stdout = ''
891
+ let settled = false
892
+ let timer = null
893
+ const finish = value => {
894
+ if (settled) return
895
+ settled = true
896
+ if (timer) clearTimeout(timer)
897
+ resolve(value)
898
+ }
899
+ let child = null
900
+ try {
901
+ child = spawnImpl(executable, [script], {
902
+ windowsHide: true,
903
+ stdio: ['ignore', 'pipe', 'pipe'],
904
+ env: smokeEnv({ ELECTRON_RUN_AS_NODE: '1' }),
905
+ })
906
+ } catch (error) {
907
+ finish({ ok: false, message: `cannot start the runtime smoke process: ${error?.message || error}` })
908
+ return
909
+ }
910
+ timer = setTimeout(() => {
911
+ try { child?.kill() } catch {}
912
+ finish({ ok: false, message: 'the runtime smoke process did not finish in time' })
913
+ }, timeoutMs)
914
+ timer.unref?.()
915
+ try { child?.stdin?.on?.('error', () => {}) } catch {}
916
+ try { child?.stderr?.on?.('data', () => {}) } catch {}
917
+ child?.on?.('error', error => finish({ ok: false, message: `the runtime smoke process failed: ${error?.message || error}` }))
918
+ child?.stdout?.on?.('data', chunk => {
919
+ stdout += String(chunk)
920
+ if (stdout.length > READY_LIMIT) {
921
+ try { child?.kill() } catch {}
922
+ finish({ ok: false, message: 'the runtime smoke output exceeded the limit' })
923
+ }
924
+ })
925
+ child?.on?.('close', code => {
926
+ const line = stdout.split(String.fromCharCode(10)).map(item => item.replace(/\r+$/, '')).filter(Boolean)[0] || ''
927
+ let parsed = null
928
+ try { parsed = JSON.parse(line) } catch { parsed = null }
929
+ if (parsed && parsed.ok === true) finish({ ok: true, ortVersion: parsed.ortVersion || null, tokenizer: parsed.tokenizer === true, checks: [`smoke:onnxruntime-node@${parsed.ortVersion || 'unknown'}`] })
930
+ else finish({ ok: false, message: String(parsed?.message || `the runtime smoke process exited with code ${code}`) })
931
+ })
932
+ })
933
+ } finally {
934
+ try { fs.rmSync(script, { force: true }) } catch {}
935
+ }
936
+ }
937
+
938
+ let singleton = null
939
+ export function managedEmbeddingRuntime(options = {}) {
940
+ if (!singleton || options.root && path.resolve(options.root) !== singleton.root) singleton = createEmbeddingRuntimeInstaller(options)
941
+ return singleton
942
+ }
943
+ export function resetManagedEmbeddingRuntime() {
944
+ try { singleton?.dispose() } catch {}
945
+ singleton = null
946
+ }