dsh-memu-memory 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +173 -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 +85 -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 +1020 -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 +1587 -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 +132 -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 +1522 -1429
@@ -1,607 +1,637 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
- import crypto from 'node:crypto'
4
- import {
5
- getEmbeddingCatalog,
6
- getEmbeddingModel,
7
- PROVIDERS,
8
- readOnnxGraphHeader,
9
- resolveEmbeddingSources,
10
- validateEmbeddingManifest,
11
- } from './embedding-catalog.js'
12
-
13
- // §14.4/§14.7 受管隔离下载器:
14
- // staging → bytes/sha256 校验 → 模型 smoke(图头 + config/tokenizer 结构)→ 原子安装。
15
- // 硬约束:
16
- // 1. 只有用户在 UI 里明确确认(confirmed: true)才会联网;没有确认就绝不发请求。
17
- // 2. 只从 manifest 里显式固定的 repo+revision 生成 URL;没有固定 revision 的来源不下载。
18
- // 3. 失败、取消、hash 不符、smoke 不过一律不改动已安装目录——它代表"当前的 profiles",
19
- // 写 active 是另一个模块的事,本模块永远不写 active/profile 指针(§14.8)。
20
- // 4. 下载走独立 .cache 里的 .part + Range 断点续传,半成品不进 staging;
21
- // 安装前校验完整总 hash,磁盘写失败清 .part 并给明确错误。
22
-
23
- const INSTALL_RECORD = 'installed.json'
24
- const STAGING_DIR = '.staging'
25
- const TRASH_DIR = '.trash'
26
- const CACHE_DIR = '.cache'
27
- // 单文件上限。512 MiB 装不下已经逐字节核实过的 Qwen3-Embedding int8 图(600,223,343 B),
28
- // 所以按「最大的一条 pin 住制品 + 余量」定;目录条目仍各自带 exact bytes,超限一律拒。
29
- const DEFAULT_MAX_FILE_BYTES = 1024 * 1024 * 1024
30
- // S-1:网络总超时与分块 stall 超时,避免半开连接把下载永久挂住。
31
- const DEFAULT_FETCH_TIMEOUT_MS = 600_000
32
- const DEFAULT_STALL_TIMEOUT_MS = 30_000
33
-
34
- function fail(code, message, extra) {
35
- const error = new Error(message)
36
- error.code = code
37
- if (extra) Object.assign(error, extra)
38
- return error
39
- }
40
-
41
- function sha256FileSync(file) {
42
- const hash = crypto.createHash('sha256')
43
- const fd = fs.openSync(file, 'r')
44
- try {
45
- const buffer = Buffer.allocUnsafe(64 * 1024)
46
- let read
47
- while ((read = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, read))
48
- } finally {
49
- fs.closeSync(fd)
50
- }
51
- return hash.digest('hex')
52
- }
53
-
54
- // S-16:下载前预检目标盘剩余空间。statfsSync 抛错/回报 0 时不拦(fail-open),
55
- // 让写入路径自己报错,别因为一个探针就挡住本来能装成功的下载。
56
- function ensureFreeSpace(dir, requiredBytes) {
57
- if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
58
- let available = null
59
- try {
60
- const stat = fs.statfsSync(dir)
61
- available = Number(stat.bavail) * Number(stat.bsize)
62
- } catch {
63
- return
64
- }
65
- if (!Number.isFinite(available) || available <= 0) return
66
- // 留一倍余量给 .part + staging 双份与安装副本,别把盘压到 0。
67
- if (available < requiredBytes * 2) {
68
- throw fail('EMBEDDING_DISK_FULL', `not enough free space to download the model: need ~${requiredBytes * 2} bytes, only ${available} available`)
69
- }
70
- }
71
-
72
- function isAbort(error, signal) {
73
- return Boolean(signal?.aborted) || error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED' || error?.code === 'EMBEDDING_DOWNLOAD_ABORTED'
74
- }
75
-
76
- function readJsonFile(file) {
77
- try {
78
- return JSON.parse(fs.readFileSync(file, 'utf8'))
79
- } catch {
80
- return null
81
- }
82
- }
83
-
84
- // Installed records are local state, not a trusted manifest. Resolve every
85
- // recorded file without following symlinks out of its model directory.
86
- function modelFileTarget(dir, relative) {
87
- const text = String(relative || '')
88
- if (!text || text.includes('\\') || path.isAbsolute(text)) return null
89
- const parts = text.split('/')
90
- if (parts.some(part => !part || part === '.' || part === '..')) return null
91
- const root = path.resolve(dir)
92
- const target = path.resolve(root, ...parts)
93
- if (target !== root && !target.startsWith(root + path.sep)) return null
94
- try {
95
- const rootReal = fs.realpathSync(root)
96
- const targetReal = fs.realpathSync(target)
97
- if (targetReal !== rootReal && !targetReal.startsWith(rootReal + path.sep)) return null
98
- } catch {
99
- return null
100
- }
101
- return target
102
- }
103
-
104
- function isRegularNonSymlink(file) {
105
- try {
106
- const stat = fs.lstatSync(file)
107
- return stat.isFile() && !stat.isSymbolicLink()
108
- } catch {
109
- return false
110
- }
111
- }
112
-
113
- function writeJsonAtomic(file, value) {
114
- fs.mkdirSync(path.dirname(file), { recursive: true })
115
- const temporary = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
116
- fs.writeFileSync(temporary, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600, flag: 'wx' })
117
- fs.renameSync(temporary, file)
118
- }
119
-
120
- /**
121
- * 默认模型 smoke:不需要 onnxruntime。读 config/tokenizer/图头,核对 manifest 声明的
122
- * 维度、最大长度、输入输出名与 dtype、opset、自包含性、词表规模。真实推理 smoke 要等
123
- * ORT 装好后再加(§14.11),这里不假装它已经跑过。
124
- */
125
- export async function verifyStagedArtifacts({ entry, dir }) {
126
- const checks = []
127
- const fileOf = role => (entry.files || []).find(file => file.role === role) || null
128
- const bytesOf = role => {
129
- const file = fileOf(role)
130
- if (!file) return null
131
- return fs.readFileSync(path.join(dir, ...String(file.path).split('/')))
132
- }
133
-
134
- const configBytes = bytesOf('config')
135
- if (!configBytes) throw new Error('staged artifact has no config.json')
136
- const config = JSON.parse(configBytes.toString('utf8'))
137
- if (config.hidden_size !== entry.dimension) throw new Error(`config.hidden_size ${config.hidden_size} does not match manifest dimension ${entry.dimension}`)
138
- checks.push('config.hidden_size=' + config.hidden_size)
139
- // 分窗不能超过制品自己声明的位置上限——超过就是必炸的输入;比它小是刻意的策略
140
- // (例如 32k 上下文的模型按 8k 切,避免单条记忆把 CPU 推理拖到请求超时),
141
- // 而这个选择本来就在 profile 指纹里,可复现。
142
- if (entry.maxTokens !== null && config.max_position_embeddings && config.max_position_embeddings < entry.maxTokens) {
143
- throw new Error(`manifest maxTokens ${entry.maxTokens} exceeds the artifact's max_position_embeddings ${config.max_position_embeddings}`)
144
- }
145
- if (config.max_position_embeddings) checks.push('config.max_position_embeddings=' + config.max_position_embeddings + ' window=' + (entry.maxTokens ?? 'unset'))
146
-
147
- const vocabBytes = bytesOf('vocab')
148
- if (vocabBytes && Number.isInteger(config.vocab_size)) {
149
- const vocabLines = vocabBytes.toString('utf8').split(/\r?\n/).filter(line => line.length > 0).length
150
- if (vocabLines !== config.vocab_size) throw new Error(`vocab.txt has ${vocabLines} entries but config.vocab_size is ${config.vocab_size}`)
151
- checks.push('vocab.txt=' + vocabLines)
152
- }
153
-
154
- const tokenizerBytes = bytesOf('tokenizer')
155
- if (tokenizerBytes) {
156
- const tokenizer = JSON.parse(tokenizerBytes.toString('utf8'))
157
- const vocab = tokenizer?.model?.vocab
158
- if (!vocab || typeof vocab !== 'object' || Object.keys(vocab).length < 2) throw new Error('tokenizer.json has no usable model.vocab')
159
- checks.push('tokenizer.vocab=' + Object.keys(vocab).length)
160
- }
161
-
162
- const poolingBytes = bytesOf('pooling-config')
163
- if (poolingBytes) {
164
- const pooling = JSON.parse(poolingBytes.toString('utf8'))
165
- if (entry.pooling === 'cls' && pooling.pooling_mode_cls_token !== true) throw new Error('pooling config is not CLS pooling')
166
- if (entry.pooling === 'mean' && pooling.pooling_mode_mean_tokens !== true) throw new Error('pooling config is not mean pooling')
167
- // 因果 LM 的卡片最容易踩的坑:目录写着 last、制品其实是 mean。lasttoken 是基座自己
168
- // 声明的字段,能对得上才继续。
169
- if (entry.pooling === 'last' && pooling.pooling_mode_lasttoken !== true) throw new Error('pooling config is not last-token pooling')
170
- if (Number.isInteger(pooling.word_embedding_dimension) && pooling.word_embedding_dimension !== entry.dimension) {
171
- throw new Error(`pooling word_embedding_dimension ${pooling.word_embedding_dimension} does not match dimension ${entry.dimension}`)
172
- }
173
- checks.push('pooling=' + entry.pooling)
174
- }
175
-
176
- const graphFile = fileOf('graph')
177
- if (!graphFile) throw new Error('staged artifact has no graph file')
178
- const graphBytes = bytesOf('graph')
179
- const header = readOnnxGraphHeader(graphBytes)
180
- if (!header.selfContained) throw new Error('graph references external data or has no initializer bytes; this build only installs self-contained graphs')
181
- checks.push('graph.selfContained=true', 'graph.initializerBytes=' + header.initializerBytes)
182
- const declared = entry.graph || {}
183
- const declaredInputs = (declared.inputs || []).map(io => io.name).sort()
184
- const actualInputs = header.inputs.map(io => io.name).sort()
185
- if (declaredInputs.join(',') !== actualInputs.join(',')) {
186
- throw new Error(`graph inputs ${actualInputs.join(',')} do not match manifest ${declaredInputs.join(',')}`)
187
- }
188
- for (const io of declared.inputs || []) {
189
- const actual = header.inputs.find(item => item.name === io.name)
190
- if (actual.dtype !== io.dtype) throw new Error(`graph input ${io.name} dtype ${actual.dtype} does not match manifest ${io.dtype}`)
191
- }
192
- const declaredOutput = (declared.outputs || [])[0]
193
- const actualOutput = header.outputs[0]
194
- if (!actualOutput) throw new Error('graph has no outputs')
195
- if (declaredOutput && actualOutput.name !== declaredOutput.name) throw new Error(`graph output ${actualOutput.name} does not match manifest ${declaredOutput.name}`)
196
- // float32 与 float16 都能被 worker 池化(fp16 走 Number() 取值),但别的 dtype
197
- // (int8 输出、string)不是 embedding worker 该假装能吃的东西。声明与实际必须一致。
198
- if (!['float32', 'float16'].includes(actualOutput.dtype)) throw new Error(`graph output dtype ${actualOutput.dtype} is not float32/float16`)
199
- if (declaredOutput && declaredOutput.dtype && actualOutput.dtype !== declaredOutput.dtype) {
200
- throw new Error(`graph output dtype ${actualOutput.dtype} does not match manifest ${declaredOutput.dtype}`)
201
- }
202
- const lastDim = Array.isArray(actualOutput.shape) ? actualOutput.shape[actualOutput.shape.length - 1] : null
203
- if (lastDim !== entry.dimension) throw new Error(`graph output last dim ${lastDim} does not match dimension ${entry.dimension}`)
204
- checks.push('graph.output=' + actualOutput.name + ':' + actualOutput.dtype + '[' + lastDim + ']')
205
- if (Number.isInteger(declared.opset)) {
206
- const defaultOpset = header.opsets.find(opset => !opset.domain)
207
- if (!defaultOpset || defaultOpset.version !== declared.opset) {
208
- throw new Error(`graph opset ${defaultOpset?.version} does not match manifest ${declared.opset}`)
209
- }
210
- checks.push('graph.opset=' + defaultOpset.version)
211
- }
212
- return { ok: true, checks }
213
- }
214
-
215
- /**
216
- * createEmbeddingDownloadManager({ root, catalog?, fetchImpl?, verifyModel? })
217
- * root: 本插件受管模型目录(复用 paths.js 的数据目录,不要放进宿主 app.asar)。
218
- */
219
- export function createEmbeddingDownloadManager(options = {}) {
220
- const { root, fetchImpl = fetch, verifyModel, maxFileBytes = DEFAULT_MAX_FILE_BYTES, now = () => new Date().toISOString() } = options
221
- if (typeof root !== 'string' || !root.trim()) throw new TypeError('createEmbeddingDownloadManager requires a root directory')
222
- const baseDir = path.resolve(root)
223
- const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
224
- const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
225
- const extraCatalog = Array.isArray(options.catalog) ? options.catalog : []
226
- const jobs = new Map()
227
- // 失败/取消结果单独记账:jobs 只表示「在途」,所以重试不会被误判成 BUSY,
228
- // 但 UI 仍能读到上一次的失败原因(§14.7 的 failed 状态)。
229
- const outcomes = new Map()
230
-
231
- const lookup = id => extraCatalog.find(entry => entry && entry.id === id) || getEmbeddingModel(id)
232
-
233
- function insideRoot(target) {
234
- const resolved = path.resolve(target)
235
- if (resolved !== baseDir && !resolved.startsWith(baseDir + path.sep)) {
236
- throw fail('EMBEDDING_PATH_ESCAPE', `refusing to touch a path outside the model root: ${resolved}`)
237
- }
238
- return resolved
239
- }
240
-
241
- const modelDir = id => insideRoot(path.join(baseDir, id))
242
- const recordPath = id => path.join(modelDir(id), INSTALL_RECORD)
243
- // S-16:续传用的稳定 .part 放在独立 .cache,与 .staging 隔离(staging 仍保持
244
- // 「安装成功后必须为空」的既有语义)。文件名带 sha256,换源/换版本不会误复用。
245
- const partPathFor = file => {
246
- const safe = String(file.path).split('/').pop().replace(/[^A-Za-z0-9._-]+/g, '-')
247
- return path.join(insideRoot(path.join(baseDir, CACHE_DIR)), `${safe}-${file.sha256}.part`)
248
- }
249
-
250
- function readInstall(entry) {
251
- const dir = modelDir(entry.id)
252
- try {
253
- const dirStat = fs.lstatSync(dir)
254
- if (!dirStat.isDirectory() || dirStat.isSymbolicLink()) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
255
- } catch { return null }
256
- const record = readJsonFile(recordPath(entry.id))
257
- if (!record || typeof record !== 'object') return null
258
- if (record.id !== entry.id) return { ok: false, code: 'EMBEDDING_INSTALL_MISMATCH' }
259
- const files = Array.isArray(record.files) ? record.files : []
260
- if (!files.length) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
261
- for (const file of files) {
262
- const target = modelFileTarget(dir, file.path)
263
- if (!target || !isRegularNonSymlink(target)) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
264
- let stat
265
- try { stat = fs.lstatSync(target) } catch { return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' } }
266
- if (stat.size !== file.bytes) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
267
- }
268
- return { ok: true, record }
269
- }
270
-
271
- function deepVerify(entry, record) {
272
- const dir = modelDir(entry.id)
273
- for (const file of record.files || []) {
274
- const target = modelFileTarget(dir, file.path)
275
- if (!target || !isRegularNonSymlink(target)) return false
276
- let hash
277
- try { hash = crypto.createHash('sha256').update(fs.readFileSync(target)).digest('hex') } catch { return false }
278
- if (hash !== file.sha256) return false
279
- }
280
- return true
281
- }
282
-
283
- function getStatus(id, statusOptions = {}) {
284
- const key = typeof id === 'string' ? id : String(id || '')
285
- const entry = lookup(key)
286
- if (!entry) {
287
- return { id: key, known: false, state: 'unknown', installed: false, active: false, downloadable: false, error: { code: 'EMBEDDING_MODEL_UNKNOWN', message: `unknown embedding model: ${key}` } }
288
- }
289
- const base = {
290
- id: entry.id,
291
- known: true,
292
- availability: entry.availability,
293
- downloadable: entry.availability === 'available',
294
- active: false, // 下载器永远不激活 profile(§14.8);active 由迁移模块负责
295
- dimension: entry.dimension,
296
- maxTokens: entry.maxTokens,
297
- pooling: entry.pooling,
298
- normalization: entry.normalization,
299
- totalBytes: entry.totalBytes,
300
- fingerprint: entry.profileFingerprint,
301
- license: entry.license?.base || null,
302
- pendingReasons: [...(entry.pendingReasons || [])],
303
- }
304
- const job = jobs.get(entry.id)
305
- if (job && (job.state === 'downloading' || job.state === 'verifying')) {
306
- return { ...base, state: job.state, installed: false, provider: job.provider, revision: job.revision, startedAt: job.startedAt, progress: { ...job.progress } }
307
- }
308
- const install = readInstall(entry)
309
- if (install?.ok) {
310
- return {
311
- ...base,
312
- state: 'installed',
313
- installed: true,
314
- provider: install.record.provider || null,
315
- revision: install.record.revision || null,
316
- installedAt: install.record.installedAt || null,
317
- fingerprintMatches: install.record.fingerprint === entry.profileFingerprint,
318
- checks: Array.isArray(install.record.checks) ? [...install.record.checks] : [],
319
- verified: statusOptions.deep ? deepVerify(entry, install.record) : null,
320
- }
321
- }
322
- if (install && !install.ok) {
323
- return { ...base, state: 'failed', installed: false, error: { code: install.code, message: 'existing install record does not match the files on disk' } }
324
- }
325
- const outcome = outcomes.get(entry.id)
326
- if (outcome) return { ...base, state: outcome.state, installed: false, error: outcome.error || null }
327
- return { ...base, state: 'absent', installed: false }
328
- }
329
-
330
- async function download(id, downloadOptions = {}) {
331
- const { confirmed = false, signal, provider = null } = downloadOptions || {}
332
- const entry = lookup(typeof id === 'string' ? id : String(id || ''))
333
- if (!entry) throw fail('EMBEDDING_MODEL_UNKNOWN', `unknown embedding model: ${id}`)
334
- if (provider !== null && !PROVIDERS[provider]) {
335
- throw fail('EMBEDDING_PROVIDER_UNKNOWN', `unknown download provider: ${String(provider)}`)
336
- }
337
- const report = validateEmbeddingManifest(entry)
338
- if (!report.ok) {
339
- throw fail('EMBEDDING_MANIFEST_INVALID', `${entry.id} manifest is not installable: ${report.errors.map(item => item.code).join(', ')}`, { errors: report.errors })
340
- }
341
- if (entry.availability !== 'available') {
342
- throw fail('EMBEDDING_MODEL_UNAVAILABLE', `${entry.id} has no verified artifact; nothing will be downloaded`, { pendingReasons: [...(entry.pendingReasons || [])] })
343
- }
344
- if (confirmed !== true) {
345
- throw fail('EMBEDDING_CONFIRMATION_REQUIRED', 'downloading a model needs explicit user confirmation: download(id, { confirmed: true })')
346
- }
347
- if (jobs.has(entry.id)) throw fail('EMBEDDING_DOWNLOAD_BUSY', `${entry.id} is already downloading`)
348
- if (signal?.aborted) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted before it started`)
349
- // 默认取目录顺序里第一个已固定的来源(Qwen3 卡片因此默认 hf-mirror);显式传
350
- // provider 时只解析那一个,解析不出可用来源就如实报错,绝不回退到别的源去下载。
351
- const resolved = provider ? resolveEmbeddingSources(entry, { providers: [provider] }) : resolveEmbeddingSources(entry)
352
- const source = provider ? resolved.sources.find(item => item.provider === provider) || null : resolved.primary
353
- if (!source) {
354
- throw fail('EMBEDDING_SOURCE_UNAVAILABLE', `no source with a pinned revision is available for ${entry.id}${provider ? ' on ' + provider : ''}`, { skipped: resolved.skipped })
355
- }
356
-
357
- const controller = new AbortController()
358
- const onAbort = () => controller.abort()
359
- signal?.addEventListener('abort', onAbort, { once: true })
360
- const job = {
361
- id: entry.id,
362
- state: 'downloading',
363
- provider: source.provider,
364
- revision: source.revision,
365
- startedAt: now(),
366
- controller,
367
- progress: { files: source.files.length, done: 0, bytes: 0, totalBytes: entry.totalBytes, current: null },
368
- }
369
- jobs.set(entry.id, job)
370
- outcomes.delete(entry.id)
371
- let staging = null
372
- let installed = false
373
- const parts = []
374
- try {
375
- // S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
376
- fs.mkdirSync(baseDir, { recursive: true })
377
- ensureFreeSpace(baseDir, entry.totalBytes)
378
- const stagingRoot = insideRoot(path.join(baseDir, STAGING_DIR))
379
- fs.mkdirSync(stagingRoot, { recursive: true })
380
- staging = fs.mkdtempSync(path.join(stagingRoot, `${entry.id}-`))
381
- for (const file of source.files) {
382
- if (controller.signal.aborted) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`)
383
- if (!Number.isInteger(file.bytes) || file.bytes < 0) throw fail('EMBEDDING_MANIFEST_INVALID', `file ${file.path} has no exact byte count`)
384
- if (file.bytes > maxFileBytes) throw fail('EMBEDDING_FILE_TOO_LARGE', `file ${file.path} declares ${file.bytes} bytes, above the ${maxFileBytes} byte cap`)
385
- const target = path.join(staging, ...String(file.path).split('/'))
386
- if (!path.resolve(target).startsWith(path.resolve(staging) + path.sep)) throw fail('EMBEDDING_PATH_ESCAPE', `file ${file.path} escapes the staging directory`)
387
- fs.mkdirSync(path.dirname(target), { recursive: true })
388
- job.progress.current = file.path
389
-
390
- // S-16:稳定 .part 缓存(独立于 .staging)+ Range 续传。半成品只进 .cache,
391
- // 保持 staging「安装成功后必须为空」的既有语义。
392
- const part = partPathFor(file)
393
- parts.push(part)
394
- fs.mkdirSync(path.dirname(part), { recursive: true })
395
- let existing = 0
396
- try { existing = fs.statSync(part).size } catch {}
397
- if (existing > file.bytes) {
398
- try { fs.rmSync(part, { force: true }) } catch {}
399
- existing = 0
400
- }
401
- if (existing > 0 && existing === file.bytes) {
402
- let reusable = false
403
- try { reusable = sha256FileSync(part) === file.sha256 } catch { reusable = false }
404
- if (reusable) {
405
- fs.copyFileSync(part, target)
406
- job.progress.bytes += file.bytes
407
- job.progress.done += 1
408
- continue
409
- }
410
- // 长度对但 hash 不符:这份半成品不可信,从头下。
411
- try { fs.rmSync(part, { force: true }) } catch {}
412
- existing = 0
413
- }
414
-
415
- // S-1:总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
416
- // 连接让 for-await 永久 pending;超时单独记账,别被误判成用户取消。
417
- let timedOut = false
418
- const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
419
- totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
420
- const stallController = new AbortController()
421
- let stallTimer = null
422
- const armStall = () => {
423
- if (stallTimer) clearTimeout(stallTimer)
424
- stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
425
- stallTimer.unref?.()
426
- }
427
- const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
428
- const timeoutFailure = cause => fail('EMBEDDING_DOWNLOAD_TIMEOUT', `download of ${file.path} timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
429
- const abortedFailure = cause => fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`, { cause })
430
- // 磁盘写失败清 .part;超时/取消保留 .part 供下次 Range 续传。
431
- let removePart = false
432
- const streamFailure = error => {
433
- if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
434
- if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
435
- if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
436
- removePart = true
437
- return fail('EMBEDDING_DISK_FULL', `cannot write ${file.path}: ${error.code}; partial download removed`, { cause: error })
438
- }
439
- return error
440
- }
441
- armStall()
442
- const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
443
- const headers = { 'accept-encoding': 'identity' }
444
- if (existing > 0) headers.Range = `bytes=${existing}-`
445
- let response
446
- try {
447
- response = await fetchImpl(file.url, { signal, redirect: 'follow', headers })
448
- } catch (error) {
449
- if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
450
- if (isAbort(error, controller.signal)) throw abortedFailure(error)
451
- throw fail('EMBEDDING_NETWORK_ERROR', `cannot fetch ${file.path} from ${source.provider}: ${error?.message || error}`, { cause: error })
452
- }
453
- if (!response || !response.ok) {
454
- throw fail('EMBEDDING_HTTP_ERROR', `${source.provider} returned ${response?.status ?? 'no response'} for ${file.path}`)
455
- }
456
- let append = existing > 0
457
- if (append && response.status === 200) {
458
- // 源忽略了 Range,丢弃 .part 从头下,避免把整段内容追加到半成品后面。
459
- job.progress.bytes = Math.max(0, job.progress.bytes - existing)
460
- try { fs.rmSync(part, { force: true }) } catch {}
461
- append = false
462
- existing = 0
463
- } else if (append) {
464
- const contentRange = String(response.headers?.get?.('content-range') || '')
465
- const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(contentRange)
466
- if (response.status !== 206 || !match || Number(match[1]) !== existing || Number(match[3]) !== file.bytes) {
467
- throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} returned an unexpected Content-Range for resume: ${contentRange || '(missing)'}`)
468
- }
469
- }
470
- // 没有 content-length(hf-mirror 对小文件用 chunked 传输)等于「未知」,不是 0:
471
- // 当成 0 会把每个小文件都误判成大小不符。真正的门槛是下面落盘后的 sha256。
472
- const declaredHeader = response.headers?.get?.('content-length')
473
- const declaredLength = Number(declaredHeader)
474
- const expectedLength = file.bytes - existing
475
- if (declaredHeader != null && Number.isInteger(declaredLength) && declaredLength > 0 && declaredLength !== expectedLength) {
476
- throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} content-length ${declaredLength} does not match the expected ${expectedLength} bytes`)
477
- }
478
- let size = existing
479
- const fd = fs.openSync(part, append ? 'a' : 'w', 0o600)
480
- try {
481
- const body = response.body
482
- if (body && typeof body[Symbol.asyncIterator] === 'function') {
483
- try {
484
- for await (const chunk of body) {
485
- if (controller.signal.aborted) throw abortedFailure(null)
486
- armStall()
487
- size += chunk.length
488
- if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
489
- fs.writeSync(fd, chunk)
490
- job.progress.bytes += chunk.length
491
- }
492
- } catch (error) { throw streamFailure(error) }
493
- } else {
494
- try {
495
- const buffer = Buffer.from(await response.arrayBuffer())
496
- size += buffer.length
497
- if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
498
- fs.writeSync(fd, buffer)
499
- job.progress.bytes += buffer.length
500
- } catch (error) { throw streamFailure(error) }
501
- }
502
- } finally {
503
- clearStall()
504
- try { fs.closeSync(fd) } catch {}
505
- if (removePart) { try { fs.rmSync(part, { force: true }) } catch {} }
506
- }
507
- if (size !== file.bytes) {
508
- try { fs.rmSync(part, { force: true }) } catch {}
509
- throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} is ${size} bytes, expected ${file.bytes}`)
510
- }
511
- const digest = sha256FileSync(part)
512
- if (digest !== file.sha256) {
513
- try { fs.rmSync(part, { force: true }) } catch {}
514
- throw fail('EMBEDDING_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
515
- }
516
- try {
517
- fs.copyFileSync(part, target)
518
- } catch (error) {
519
- throw fail('EMBEDDING_INSTALL_FAILED', `cannot stage ${file.path}: ${error?.code || error?.message || error}; partial download removed`, { cause: error })
520
- }
521
- job.progress.done += 1
522
- }
523
- job.state = 'verifying'
524
- job.progress.current = null
525
- const verifier = typeof verifyModel === 'function' ? verifyModel : verifyStagedArtifacts
526
- let smoke
527
- try {
528
- smoke = await verifier({ id: entry.id, dir: staging, entry, manifest: entry, provider: source.provider, revision: source.revision })
529
- } catch (error) {
530
- if (isAbort(error, controller.signal)) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`, { cause: error })
531
- throw fail('EMBEDDING_SMOKE_FAILED', `model smoke failed for ${entry.id}: ${error?.message || error}`, { cause: error })
532
- }
533
- if (smoke && smoke.ok === false) throw fail('EMBEDDING_SMOKE_FAILED', `model smoke rejected ${entry.id}`, { smoke })
534
-
535
- const record = {
536
- id: entry.id,
537
- revision: source.revision,
538
- repo: source.repo,
539
- provider: source.provider,
540
- fingerprint: entry.profileFingerprint,
541
- installedAt: now(),
542
- totalBytes: entry.totalBytes,
543
- files: (entry.files || []).map(file => ({ path: file.path, role: file.role, bytes: file.bytes, sha256: file.sha256 })),
544
- checks: Array.isArray(smoke?.checks) ? smoke.checks : [],
545
- verifiedBy: typeof verifyModel === 'function' ? 'custom-verify-model' : 'sha256+structural-smoke',
546
- // 明确记录:安装≠启用。active profile 由迁移模块的受验证切换流程负责。
547
- active: false,
548
- }
549
- writeJsonAtomic(path.join(staging, INSTALL_RECORD), record)
550
-
551
- const finalDir = modelDir(entry.id)
552
- const previousExists = fs.existsSync(finalDir)
553
- let trash = null
554
- if (previousExists) {
555
- const trashRoot = insideRoot(path.join(baseDir, TRASH_DIR))
556
- fs.mkdirSync(trashRoot, { recursive: true })
557
- trash = path.join(trashRoot, `${entry.id}-${crypto.randomUUID()}`)
558
- fs.renameSync(finalDir, trash)
559
- }
560
- try {
561
- fs.renameSync(staging, finalDir)
562
- staging = null
563
- installed = true
564
- } catch (error) {
565
- if (trash) { try { fs.renameSync(trash, finalDir) } catch {} }
566
- throw fail('EMBEDDING_INSTALL_FAILED', `cannot move the verified artifact into place: ${error?.message || error}`, { cause: error })
567
- }
568
- if (trash) { try { fs.rmSync(trash, { recursive: true, force: true }) } catch {} }
569
- job.state = 'installed'
570
- jobs.delete(entry.id)
571
- outcomes.delete(entry.id)
572
- return getStatus(entry.id)
573
- } catch (error) {
574
- const aborted = isAbort(error, controller.signal)
575
- const code = aborted ? 'EMBEDDING_DOWNLOAD_ABORTED' : (typeof error?.code === 'string' && error.code.startsWith('EMBEDDING_') ? error.code : 'EMBEDDING_DOWNLOAD_FAILED')
576
- const failed = code === error?.code ? error : fail(code, `download of ${entry.id} failed: ${error?.message || error}`, { cause: error })
577
- // S-16:非可续传类失败清掉 .part,别让半成品占空间;网络错误/超时/取消
578
- // 保留 .part 供下次 Range 续传(S-1)。
579
- if (!['EMBEDDING_DOWNLOAD_ABORTED', 'EMBEDDING_NETWORK_ERROR', 'EMBEDDING_DOWNLOAD_TIMEOUT'].includes(code)) {
580
- for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} }
581
- }
582
- job.state = aborted ? 'cancelled' : 'failed'
583
- job.error = { code, message: String(failed.message || error) }
584
- jobs.delete(entry.id)
585
- outcomes.set(entry.id, { state: job.state, error: { ...job.error } })
586
- throw failed
587
- } finally {
588
- signal?.removeEventListener('abort', onAbort)
589
- if (staging && !installed) { try { fs.rmSync(staging, { recursive: true, force: true }) } catch {} }
590
- // 安装成功后本次的 .part 已完成使命,清掉避免长期占空间。
591
- if (installed) { for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} } }
592
- }
593
- }
594
-
595
- function dispose() {
596
- // 只中止在途下载;状态与错误原因留给 getStatus 展示。
597
- for (const job of jobs.values()) { try { job.controller?.abort() } catch {} }
598
- }
599
-
600
- return {
601
- root: baseDir,
602
- catalogIds: [...getEmbeddingCatalog().map(entry => entry.id), ...extraCatalog.map(entry => entry?.id).filter(Boolean)],
603
- getStatus,
604
- download,
605
- dispose,
606
- }
607
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+ import {
5
+ getEmbeddingCatalog,
6
+ getEmbeddingModel,
7
+ PROVIDERS,
8
+ readOnnxGraphHeader,
9
+ resolveEmbeddingSources,
10
+ validateEmbeddingManifest,
11
+ } from './embedding-catalog.js'
12
+
13
+ // §14.4/§14.7 受管隔离下载器:
14
+ // staging → bytes/sha256 校验 → 模型 smoke(图头 + config/tokenizer 结构)→ 原子安装。
15
+ // 硬约束:
16
+ // 1. 只有用户在 UI 里明确确认(confirmed: true)才会联网;没有确认就绝不发请求。
17
+ // 2. 只从 manifest 里显式固定的 repo+revision 生成 URL;没有固定 revision 的来源不下载。
18
+ // 3. 失败、取消、hash 不符、smoke 不过一律不改动已安装目录——它代表"当前的 profiles",
19
+ // 写 active 是另一个模块的事,本模块永远不写 active/profile 指针(§14.8)。
20
+ // 4. 下载走独立 .cache 里的 .part + Range 断点续传,半成品不进 staging;
21
+ // 安装前校验完整总 hash,磁盘写失败清 .part 并给明确错误。
22
+
23
+ const INSTALL_RECORD = 'installed.json'
24
+ const STAGING_DIR = '.staging'
25
+ const TRASH_DIR = '.trash'
26
+ const CACHE_DIR = '.cache'
27
+ // 单文件上限。512 MiB 装不下已经逐字节核实过的 Qwen3-Embedding int8 图(600,223,343 B),
28
+ // 所以按「最大的一条 pin 住制品 + 余量」定;目录条目仍各自带 exact bytes,超限一律拒。
29
+ const DEFAULT_MAX_FILE_BYTES = 1024 * 1024 * 1024
30
+ // S-1:网络总超时与分块 stall 超时,避免半开连接把下载永久挂住。
31
+ const DEFAULT_FETCH_TIMEOUT_MS = 600_000
32
+ const DEFAULT_STALL_TIMEOUT_MS = 30_000
33
+
34
+ function fail(code, message, extra) {
35
+ const error = new Error(message)
36
+ error.code = code
37
+ if (extra) Object.assign(error, extra)
38
+ return error
39
+ }
40
+
41
+ function sha256FileSync(file) {
42
+ const hash = crypto.createHash('sha256')
43
+ const fd = fs.openSync(file, 'r')
44
+ try {
45
+ const buffer = Buffer.allocUnsafe(64 * 1024)
46
+ let read
47
+ while ((read = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, read))
48
+ } finally {
49
+ fs.closeSync(fd)
50
+ }
51
+ return hash.digest('hex')
52
+ }
53
+
54
+ // S-16:下载前预检目标盘剩余空间。statfsSync 抛错/回报 0 时不拦(fail-open),
55
+ // 让写入路径自己报错,别因为一个探针就挡住本来能装成功的下载。
56
+ function ensureFreeSpace(dir, requiredBytes) {
57
+ if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
58
+ let available = null
59
+ try {
60
+ const stat = fs.statfsSync(dir)
61
+ available = Number(stat.bavail) * Number(stat.bsize)
62
+ } catch {
63
+ return
64
+ }
65
+ if (!Number.isFinite(available) || available <= 0) return
66
+ // 留一倍余量给 .part + staging 双份与安装副本,别把盘压到 0。
67
+ if (available < requiredBytes * 2) {
68
+ throw fail('EMBEDDING_DISK_FULL', `not enough free space to download the model: need ~${requiredBytes * 2} bytes, only ${available} available`)
69
+ }
70
+ }
71
+
72
+ function isAbort(error, signal) {
73
+ return Boolean(signal?.aborted) || error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED' || error?.code === 'EMBEDDING_DOWNLOAD_ABORTED'
74
+ }
75
+
76
+ function readJsonFile(file) {
77
+ try {
78
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
79
+ } catch {
80
+ return null
81
+ }
82
+ }
83
+
84
+ // Installed records are local state, not a trusted manifest. Resolve every
85
+ // recorded file without following symlinks out of its model directory.
86
+ function modelFileTarget(dir, relative) {
87
+ const text = String(relative || '')
88
+ if (!text || text.includes('\\') || path.isAbsolute(text)) return null
89
+ const parts = text.split('/')
90
+ if (parts.some(part => !part || part === '.' || part === '..')) return null
91
+ const root = path.resolve(dir)
92
+ const target = path.resolve(root, ...parts)
93
+ if (target !== root && !target.startsWith(root + path.sep)) return null
94
+ try {
95
+ const rootReal = fs.realpathSync(root)
96
+ const targetReal = fs.realpathSync(target)
97
+ if (targetReal !== rootReal && !targetReal.startsWith(rootReal + path.sep)) return null
98
+ } catch {
99
+ return null
100
+ }
101
+ return target
102
+ }
103
+
104
+ function isRegularNonSymlink(file) {
105
+ try {
106
+ const stat = fs.lstatSync(file)
107
+ return stat.isFile() && !stat.isSymbolicLink()
108
+ } catch {
109
+ return false
110
+ }
111
+ }
112
+
113
+ function writeJsonAtomic(file, value) {
114
+ fs.mkdirSync(path.dirname(file), { recursive: true })
115
+ const temporary = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
116
+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600, flag: 'wx' })
117
+ fs.renameSync(temporary, file)
118
+ }
119
+
120
+ /**
121
+ * 默认模型 smoke:不需要 onnxruntime。读 config/tokenizer/图头,核对 manifest 声明的
122
+ * 维度、最大长度、输入输出名与 dtype、opset、自包含性、词表规模。真实推理 smoke 要等
123
+ * ORT 装好后再加(§14.11),这里不假装它已经跑过。
124
+ */
125
+ export async function verifyStagedArtifacts({ entry, dir }) {
126
+ const checks = []
127
+ const fileOf = role => (entry.files || []).find(file => file.role === role) || null
128
+ const bytesOf = role => {
129
+ const file = fileOf(role)
130
+ if (!file) return null
131
+ return fs.readFileSync(path.join(dir, ...String(file.path).split('/')))
132
+ }
133
+
134
+ const configBytes = bytesOf('config')
135
+ if (!configBytes) throw new Error('staged artifact has no config.json')
136
+ const config = JSON.parse(configBytes.toString('utf8'))
137
+ if (config.hidden_size !== entry.dimension) throw new Error(`config.hidden_size ${config.hidden_size} does not match manifest dimension ${entry.dimension}`)
138
+ checks.push('config.hidden_size=' + config.hidden_size)
139
+ // 分窗不能超过制品声明的位置上限;使用更小窗口可以控制推理成本
140
+ // (例如 32k 上下文的模型按 8k 切,避免单条记忆把 CPU 推理拖到请求超时),
141
+ // 而这个选择本来就在 profile 指纹里,可复现。
142
+ if (entry.maxTokens !== null && config.max_position_embeddings && config.max_position_embeddings < entry.maxTokens) {
143
+ throw new Error(`manifest maxTokens ${entry.maxTokens} exceeds the artifact's max_position_embeddings ${config.max_position_embeddings}`)
144
+ }
145
+ if (config.max_position_embeddings) checks.push('config.max_position_embeddings=' + config.max_position_embeddings + ' window=' + (entry.maxTokens ?? 'unset'))
146
+
147
+ const vocabBytes = bytesOf('vocab')
148
+ if (vocabBytes && Number.isInteger(config.vocab_size)) {
149
+ const vocabLines = vocabBytes.toString('utf8').split(/\r?\n/).filter(line => line.length > 0).length
150
+ if (vocabLines !== config.vocab_size) throw new Error(`vocab.txt has ${vocabLines} entries but config.vocab_size is ${config.vocab_size}`)
151
+ checks.push('vocab.txt=' + vocabLines)
152
+ }
153
+
154
+ const tokenizerBytes = bytesOf('tokenizer')
155
+ if (tokenizerBytes) {
156
+ const tokenizer = JSON.parse(tokenizerBytes.toString('utf8'))
157
+ const vocab = tokenizer?.model?.vocab
158
+ if (!vocab || typeof vocab !== 'object' || Object.keys(vocab).length < 2) throw new Error('tokenizer.json has no usable model.vocab')
159
+ checks.push('tokenizer.vocab=' + Object.keys(vocab).length)
160
+ }
161
+
162
+ const poolingBytes = bytesOf('pooling-config')
163
+ if (poolingBytes) {
164
+ const pooling = JSON.parse(poolingBytes.toString('utf8'))
165
+ if (entry.pooling === 'cls' && pooling.pooling_mode_cls_token !== true) throw new Error('pooling config is not CLS pooling')
166
+ if (entry.pooling === 'mean' && pooling.pooling_mode_mean_tokens !== true) throw new Error('pooling config is not mean pooling')
167
+ // last-token pooling 必须与基座配置中的 lasttoken 声明一致。
168
+ if (entry.pooling === 'last' && pooling.pooling_mode_lasttoken !== true) throw new Error('pooling config is not last-token pooling')
169
+ if (Number.isInteger(pooling.word_embedding_dimension) && pooling.word_embedding_dimension !== entry.dimension) {
170
+ throw new Error(`pooling word_embedding_dimension ${pooling.word_embedding_dimension} does not match dimension ${entry.dimension}`)
171
+ }
172
+ checks.push('pooling=' + entry.pooling)
173
+ }
174
+
175
+ const graphFile = fileOf('graph')
176
+ if (!graphFile) throw new Error('staged artifact has no graph file')
177
+ const graphBytes = bytesOf('graph')
178
+ const header = readOnnxGraphHeader(graphBytes)
179
+ if (!header.selfContained) throw new Error('graph references external data or has no initializer bytes; this build only installs self-contained graphs')
180
+ checks.push('graph.selfContained=true', 'graph.initializerBytes=' + header.initializerBytes)
181
+ const declared = entry.graph || {}
182
+ const declaredInputs = (declared.inputs || []).map(io => io.name).sort()
183
+ const actualInputs = header.inputs.map(io => io.name).sort()
184
+ if (declaredInputs.join(',') !== actualInputs.join(',')) {
185
+ throw new Error(`graph inputs ${actualInputs.join(',')} do not match manifest ${declaredInputs.join(',')}`)
186
+ }
187
+ for (const io of declared.inputs || []) {
188
+ const actual = header.inputs.find(item => item.name === io.name)
189
+ if (actual.dtype !== io.dtype) throw new Error(`graph input ${io.name} dtype ${actual.dtype} does not match manifest ${io.dtype}`)
190
+ }
191
+ const declaredOutput = (declared.outputs || [])[0]
192
+ const actualOutput = header.outputs[0]
193
+ if (!actualOutput) throw new Error('graph has no outputs')
194
+ if (declaredOutput && actualOutput.name !== declaredOutput.name) throw new Error(`graph output ${actualOutput.name} does not match manifest ${declaredOutput.name}`)
195
+ // float32 与 float16 都能被 worker 池化(fp16 走 Number() 取值),但别的 dtype
196
+ // (int8 输出、string)不是 embedding worker 该假装能吃的东西。声明与实际必须一致。
197
+ if (!['float32', 'float16'].includes(actualOutput.dtype)) throw new Error(`graph output dtype ${actualOutput.dtype} is not float32/float16`)
198
+ if (declaredOutput && declaredOutput.dtype && actualOutput.dtype !== declaredOutput.dtype) {
199
+ throw new Error(`graph output dtype ${actualOutput.dtype} does not match manifest ${declaredOutput.dtype}`)
200
+ }
201
+ const lastDim = Array.isArray(actualOutput.shape) ? actualOutput.shape[actualOutput.shape.length - 1] : null
202
+ if (lastDim !== entry.dimension) throw new Error(`graph output last dim ${lastDim} does not match dimension ${entry.dimension}`)
203
+ checks.push('graph.output=' + actualOutput.name + ':' + actualOutput.dtype + '[' + lastDim + ']')
204
+ if (Number.isInteger(declared.opset)) {
205
+ const defaultOpset = header.opsets.find(opset => !opset.domain)
206
+ if (!defaultOpset || defaultOpset.version !== declared.opset) {
207
+ throw new Error(`graph opset ${defaultOpset?.version} does not match manifest ${declared.opset}`)
208
+ }
209
+ checks.push('graph.opset=' + defaultOpset.version)
210
+ }
211
+ return { ok: true, checks }
212
+ }
213
+
214
+ /**
215
+ * createEmbeddingDownloadManager({ root, catalog?, fetchImpl?, verifyModel? })
216
+ * root: 本插件受管模型目录(复用 paths.js 的数据目录,不要放进宿主 app.asar)。
217
+ */
218
+ export function createEmbeddingDownloadManager(options = {}) {
219
+ const { root, fetchImpl = fetch, verifyModel, maxFileBytes = DEFAULT_MAX_FILE_BYTES, now = () => new Date().toISOString() } = options
220
+ if (typeof root !== 'string' || !root.trim()) throw new TypeError('createEmbeddingDownloadManager requires a root directory')
221
+ const baseDir = path.resolve(root)
222
+ const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
223
+ const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
224
+ const extraCatalog = Array.isArray(options.catalog) ? options.catalog : []
225
+ const jobs = new Map()
226
+ // 失败/取消结果单独记账:jobs 只表示「在途」,所以重试不会被误判成 BUSY,
227
+ // 但 UI 仍能读到上一次的失败原因(§14.7 的 failed 状态)。
228
+ const outcomes = new Map()
229
+
230
+ const lookup = id => extraCatalog.find(entry => entry && entry.id === id) || getEmbeddingModel(id)
231
+
232
+ function insideRoot(target) {
233
+ const resolved = path.resolve(target)
234
+ if (resolved !== baseDir && !resolved.startsWith(baseDir + path.sep)) {
235
+ throw fail('EMBEDDING_PATH_ESCAPE', `refusing to touch a path outside the model root: ${resolved}`)
236
+ }
237
+ return resolved
238
+ }
239
+
240
+ const modelDir = id => insideRoot(path.join(baseDir, id))
241
+ const recordPath = id => path.join(modelDir(id), INSTALL_RECORD)
242
+ // S-16:续传用的稳定 .part 放在独立 .cache,与 .staging 隔离(staging 仍保持
243
+ // 「安装成功后必须为空」的既有语义)。文件名带 sha256,换源/换版本不会误复用。
244
+ const partPathFor = file => {
245
+ const safe = String(file.path).split('/').pop().replace(/[^A-Za-z0-9._-]+/g, '-')
246
+ return path.join(insideRoot(path.join(baseDir, CACHE_DIR)), `${safe}-${file.sha256}.part`)
247
+ }
248
+
249
+ function readInstall(entry) {
250
+ const dir = modelDir(entry.id)
251
+ try {
252
+ const dirStat = fs.lstatSync(dir)
253
+ if (!dirStat.isDirectory() || dirStat.isSymbolicLink()) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
254
+ } catch { return null }
255
+ const record = readJsonFile(recordPath(entry.id))
256
+ if (!record || typeof record !== 'object') return null
257
+ if (record.id !== entry.id) return { ok: false, code: 'EMBEDDING_INSTALL_MISMATCH' }
258
+ const files = Array.isArray(record.files) ? record.files : []
259
+ if (!files.length) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
260
+ for (const file of files) {
261
+ const target = modelFileTarget(dir, file.path)
262
+ if (!target || !isRegularNonSymlink(target)) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
263
+ let stat
264
+ try { stat = fs.lstatSync(target) } catch { return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' } }
265
+ if (stat.size !== file.bytes) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
266
+ }
267
+ return { ok: true, record }
268
+ }
269
+
270
+ // 深校验需要读取并哈希全部模型文件。按文件 size、mtime 与安装记录中的 sha256
271
+ // 缓存校验结论,避免设置页重复查询时反复读盘;指纹变化后重新校验。
272
+ const deepVerdicts = new Map()
273
+
274
+ function deepFingerprint(dir, record) {
275
+ const parts = []
276
+ for (const file of record.files || []) {
277
+ const target = modelFileTarget(dir, file.path)
278
+ if (!target || !isRegularNonSymlink(target)) return null
279
+ let stat
280
+ try { stat = fs.lstatSync(target) } catch { return null }
281
+ // readInstall 已经查过 size;这里再查一次是因为缓存要能识别「同尺寸换内容」以外
282
+ // 的一切改动,而 mtime 只在真有写入时才变。
283
+ if (stat.size !== file.bytes) return null
284
+ // ino/ctimeMs 一起进指纹:同尺寸 + 同 mtime 的「整体替换」(tar 还原、touch -r、
285
+ // FAT 的 2s 粒度)靠这两项才抓得住。
286
+ parts.push(`${file.path}\u0000${file.bytes}\u0000${stat.mtimeMs}\u0000${stat.ctimeMs}\u0000${stat.ino}\u0000${file.sha256}`)
287
+ }
288
+ return parts.join('\u0001')
289
+ }
290
+
291
+ function deepVerify(entry, record) {
292
+ const dir = modelDir(entry.id)
293
+ const key = deepFingerprint(dir, record)
294
+ if (key === null) return false
295
+ const cached = deepVerdicts.get(entry.id)
296
+ if (cached && cached.key === key) return cached.verdict
297
+ let verdict = true
298
+ for (const file of record.files || []) {
299
+ const target = modelFileTarget(dir, file.path)
300
+ if (!target) { verdict = false; break }
301
+ let hash
302
+ try { hash = crypto.createHash('sha256').update(fs.readFileSync(target)).digest('hex') } catch {
303
+ // A transient read failure is not a content verdict; retry unchanged files next time.
304
+ deepVerdicts.delete(entry.id)
305
+ return false
306
+ }
307
+ if (hash !== file.sha256) { verdict = false; break }
308
+ }
309
+ deepVerdicts.set(entry.id, { key, verdict })
310
+ return verdict
311
+ }
312
+
313
+ function getStatus(id, statusOptions = {}) {
314
+ const key = typeof id === 'string' ? id : String(id || '')
315
+ const entry = lookup(key)
316
+ if (!entry) {
317
+ return { id: key, known: false, state: 'unknown', installed: false, active: false, downloadable: false, error: { code: 'EMBEDDING_MODEL_UNKNOWN', message: `unknown embedding model: ${key}` } }
318
+ }
319
+ const base = {
320
+ id: entry.id,
321
+ known: true,
322
+ availability: entry.availability,
323
+ downloadable: entry.availability === 'available',
324
+ active: false, // 下载器永远不激活 profile(§14.8);active 由迁移模块负责
325
+ dimension: entry.dimension,
326
+ maxTokens: entry.maxTokens,
327
+ pooling: entry.pooling,
328
+ normalization: entry.normalization,
329
+ totalBytes: entry.totalBytes,
330
+ fingerprint: entry.profileFingerprint,
331
+ license: entry.license?.base || null,
332
+ pendingReasons: [...(entry.pendingReasons || [])],
333
+ }
334
+ const job = jobs.get(entry.id)
335
+ if (job && (job.state === 'downloading' || job.state === 'verifying')) {
336
+ return { ...base, state: job.state, installed: false, provider: job.provider, revision: job.revision, startedAt: job.startedAt, progress: { ...job.progress } }
337
+ }
338
+ const install = readInstall(entry)
339
+ if (install?.ok) {
340
+ return {
341
+ ...base,
342
+ state: 'installed',
343
+ installed: true,
344
+ provider: install.record.provider || null,
345
+ revision: install.record.revision || null,
346
+ installedAt: install.record.installedAt || null,
347
+ fingerprintMatches: install.record.fingerprint === entry.profileFingerprint,
348
+ checks: Array.isArray(install.record.checks) ? [...install.record.checks] : [],
349
+ verified: statusOptions.deep ? deepVerify(entry, install.record) : null,
350
+ }
351
+ }
352
+ if (install && !install.ok) {
353
+ return { ...base, state: 'failed', installed: false, error: { code: install.code, message: 'existing install record does not match the files on disk' } }
354
+ }
355
+ const outcome = outcomes.get(entry.id)
356
+ if (outcome) return { ...base, state: outcome.state, installed: false, error: outcome.error || null }
357
+ return { ...base, state: 'absent', installed: false }
358
+ }
359
+
360
+ async function download(id, downloadOptions = {}) {
361
+ const { confirmed = false, signal, provider = null } = downloadOptions || {}
362
+ const entry = lookup(typeof id === 'string' ? id : String(id || ''))
363
+ if (!entry) throw fail('EMBEDDING_MODEL_UNKNOWN', `unknown embedding model: ${id}`)
364
+ if (provider !== null && !PROVIDERS[provider]) {
365
+ throw fail('EMBEDDING_PROVIDER_UNKNOWN', `unknown download provider: ${String(provider)}`)
366
+ }
367
+ const report = validateEmbeddingManifest(entry)
368
+ if (!report.ok) {
369
+ throw fail('EMBEDDING_MANIFEST_INVALID', `${entry.id} manifest is not installable: ${report.errors.map(item => item.code).join(', ')}`, { errors: report.errors })
370
+ }
371
+ if (entry.availability !== 'available') {
372
+ throw fail('EMBEDDING_MODEL_UNAVAILABLE', `${entry.id} has no verified artifact; nothing will be downloaded`, { pendingReasons: [...(entry.pendingReasons || [])] })
373
+ }
374
+ if (confirmed !== true) {
375
+ throw fail('EMBEDDING_CONFIRMATION_REQUIRED', 'downloading a model needs explicit user confirmation: download(id, { confirmed: true })')
376
+ }
377
+ if (jobs.has(entry.id)) throw fail('EMBEDDING_DOWNLOAD_BUSY', `${entry.id} is already downloading`)
378
+ if (signal?.aborted) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted before it started`)
379
+ // 默认取目录顺序里第一个已固定的来源(Qwen3 卡片因此默认 hf-mirror);显式传
380
+ // provider 时只解析那一个,解析不出可用来源就如实报错,绝不回退到别的源去下载。
381
+ const resolved = provider ? resolveEmbeddingSources(entry, { providers: [provider] }) : resolveEmbeddingSources(entry)
382
+ const source = provider ? resolved.sources.find(item => item.provider === provider) || null : resolved.primary
383
+ if (!source) {
384
+ throw fail('EMBEDDING_SOURCE_UNAVAILABLE', `no source with a pinned revision is available for ${entry.id}${provider ? ' on ' + provider : ''}`, { skipped: resolved.skipped })
385
+ }
386
+
387
+ const controller = new AbortController()
388
+ const onAbort = () => controller.abort()
389
+ signal?.addEventListener('abort', onAbort, { once: true })
390
+ const job = {
391
+ id: entry.id,
392
+ state: 'downloading',
393
+ provider: source.provider,
394
+ revision: source.revision,
395
+ startedAt: now(),
396
+ controller,
397
+ progress: { files: source.files.length, done: 0, bytes: 0, totalBytes: entry.totalBytes, current: null },
398
+ }
399
+ jobs.set(entry.id, job)
400
+ outcomes.delete(entry.id)
401
+ let staging = null
402
+ let installed = false
403
+ const parts = []
404
+ try {
405
+ // S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
406
+ fs.mkdirSync(baseDir, { recursive: true })
407
+ ensureFreeSpace(baseDir, entry.totalBytes)
408
+ const stagingRoot = insideRoot(path.join(baseDir, STAGING_DIR))
409
+ fs.mkdirSync(stagingRoot, { recursive: true })
410
+ staging = fs.mkdtempSync(path.join(stagingRoot, `${entry.id}-`))
411
+ for (const file of source.files) {
412
+ if (controller.signal.aborted) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`)
413
+ if (!Number.isInteger(file.bytes) || file.bytes < 0) throw fail('EMBEDDING_MANIFEST_INVALID', `file ${file.path} has no exact byte count`)
414
+ if (file.bytes > maxFileBytes) throw fail('EMBEDDING_FILE_TOO_LARGE', `file ${file.path} declares ${file.bytes} bytes, above the ${maxFileBytes} byte cap`)
415
+ const target = path.join(staging, ...String(file.path).split('/'))
416
+ if (!path.resolve(target).startsWith(path.resolve(staging) + path.sep)) throw fail('EMBEDDING_PATH_ESCAPE', `file ${file.path} escapes the staging directory`)
417
+ fs.mkdirSync(path.dirname(target), { recursive: true })
418
+ job.progress.current = file.path
419
+
420
+ // S-16:稳定 .part 缓存(独立于 .staging)+ Range 续传。半成品只进 .cache,
421
+ // 保持 staging「安装成功后必须为空」的既有语义。
422
+ const part = partPathFor(file)
423
+ parts.push(part)
424
+ fs.mkdirSync(path.dirname(part), { recursive: true })
425
+ let existing = 0
426
+ try { existing = fs.statSync(part).size } catch {}
427
+ if (existing > file.bytes) {
428
+ try { fs.rmSync(part, { force: true }) } catch {}
429
+ existing = 0
430
+ }
431
+ if (existing > 0 && existing === file.bytes) {
432
+ let reusable = false
433
+ try { reusable = sha256FileSync(part) === file.sha256 } catch { reusable = false }
434
+ if (reusable) {
435
+ fs.copyFileSync(part, target)
436
+ job.progress.bytes += file.bytes
437
+ job.progress.done += 1
438
+ continue
439
+ }
440
+ // 长度对但 hash 不符:这份半成品不可信,从头下。
441
+ try { fs.rmSync(part, { force: true }) } catch {}
442
+ existing = 0
443
+ }
444
+
445
+ // S-1:总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
446
+ // 连接让 for-await 永久 pending;超时单独记账,别被误判成用户取消。
447
+ let timedOut = false
448
+ const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
449
+ totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
450
+ const stallController = new AbortController()
451
+ let stallTimer = null
452
+ const armStall = () => {
453
+ if (stallTimer) clearTimeout(stallTimer)
454
+ stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
455
+ stallTimer.unref?.()
456
+ }
457
+ const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
458
+ const timeoutFailure = cause => fail('EMBEDDING_DOWNLOAD_TIMEOUT', `download of ${file.path} timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
459
+ const abortedFailure = cause => fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`, { cause })
460
+ // 磁盘写失败清 .part;超时/取消保留 .part 供下次 Range 续传。
461
+ let removePart = false
462
+ const streamFailure = error => {
463
+ if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
464
+ if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
465
+ if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
466
+ removePart = true
467
+ return fail('EMBEDDING_DISK_FULL', `cannot write ${file.path}: ${error.code}; partial download removed`, { cause: error })
468
+ }
469
+ return error
470
+ }
471
+ armStall()
472
+ const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
473
+ const headers = { 'accept-encoding': 'identity' }
474
+ if (existing > 0) headers.Range = `bytes=${existing}-`
475
+ let response
476
+ try {
477
+ response = await fetchImpl(file.url, { signal, redirect: 'follow', headers })
478
+ } catch (error) {
479
+ if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
480
+ if (isAbort(error, controller.signal)) throw abortedFailure(error)
481
+ throw fail('EMBEDDING_NETWORK_ERROR', `cannot fetch ${file.path} from ${source.provider}: ${error?.message || error}`, { cause: error })
482
+ }
483
+ if (!response || !response.ok) {
484
+ throw fail('EMBEDDING_HTTP_ERROR', `${source.provider} returned ${response?.status ?? 'no response'} for ${file.path}`)
485
+ }
486
+ let append = existing > 0
487
+ if (append && response.status === 200) {
488
+ // 源忽略了 Range,丢弃 .part 从头下,避免把整段内容追加到半成品后面。
489
+ job.progress.bytes = Math.max(0, job.progress.bytes - existing)
490
+ try { fs.rmSync(part, { force: true }) } catch {}
491
+ append = false
492
+ existing = 0
493
+ } else if (append) {
494
+ const contentRange = String(response.headers?.get?.('content-range') || '')
495
+ const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(contentRange)
496
+ if (response.status !== 206 || !match || Number(match[1]) !== existing || Number(match[3]) !== file.bytes) {
497
+ throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} returned an unexpected Content-Range for resume: ${contentRange || '(missing)'}`)
498
+ }
499
+ }
500
+ // 没有 content-length(hf-mirror 对小文件用 chunked 传输)等于「未知」,不是 0:
501
+ // 当成 0 会把每个小文件都误判成大小不符。真正的门槛是下面落盘后的 sha256。
502
+ const declaredHeader = response.headers?.get?.('content-length')
503
+ const declaredLength = Number(declaredHeader)
504
+ const expectedLength = file.bytes - existing
505
+ if (declaredHeader != null && Number.isInteger(declaredLength) && declaredLength > 0 && declaredLength !== expectedLength) {
506
+ throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} content-length ${declaredLength} does not match the expected ${expectedLength} bytes`)
507
+ }
508
+ let size = existing
509
+ const fd = fs.openSync(part, append ? 'a' : 'w', 0o600)
510
+ try {
511
+ const body = response.body
512
+ if (body && typeof body[Symbol.asyncIterator] === 'function') {
513
+ try {
514
+ for await (const chunk of body) {
515
+ if (controller.signal.aborted) throw abortedFailure(null)
516
+ armStall()
517
+ size += chunk.length
518
+ if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
519
+ fs.writeSync(fd, chunk)
520
+ job.progress.bytes += chunk.length
521
+ }
522
+ } catch (error) { throw streamFailure(error) }
523
+ } else {
524
+ try {
525
+ const buffer = Buffer.from(await response.arrayBuffer())
526
+ size += buffer.length
527
+ if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
528
+ fs.writeSync(fd, buffer)
529
+ job.progress.bytes += buffer.length
530
+ } catch (error) { throw streamFailure(error) }
531
+ }
532
+ } finally {
533
+ clearStall()
534
+ try { fs.closeSync(fd) } catch {}
535
+ if (removePart) { try { fs.rmSync(part, { force: true }) } catch {} }
536
+ }
537
+ if (size !== file.bytes) {
538
+ try { fs.rmSync(part, { force: true }) } catch {}
539
+ throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} is ${size} bytes, expected ${file.bytes}`)
540
+ }
541
+ const digest = sha256FileSync(part)
542
+ if (digest !== file.sha256) {
543
+ try { fs.rmSync(part, { force: true }) } catch {}
544
+ throw fail('EMBEDDING_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
545
+ }
546
+ try {
547
+ fs.copyFileSync(part, target)
548
+ } catch (error) {
549
+ throw fail('EMBEDDING_INSTALL_FAILED', `cannot stage ${file.path}: ${error?.code || error?.message || error}; partial download removed`, { cause: error })
550
+ }
551
+ job.progress.done += 1
552
+ }
553
+ job.state = 'verifying'
554
+ job.progress.current = null
555
+ const verifier = typeof verifyModel === 'function' ? verifyModel : verifyStagedArtifacts
556
+ let smoke
557
+ try {
558
+ smoke = await verifier({ id: entry.id, dir: staging, entry, manifest: entry, provider: source.provider, revision: source.revision })
559
+ } catch (error) {
560
+ if (isAbort(error, controller.signal)) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`, { cause: error })
561
+ throw fail('EMBEDDING_SMOKE_FAILED', `model smoke failed for ${entry.id}: ${error?.message || error}`, { cause: error })
562
+ }
563
+ if (smoke && smoke.ok === false) throw fail('EMBEDDING_SMOKE_FAILED', `model smoke rejected ${entry.id}`, { smoke })
564
+
565
+ const record = {
566
+ id: entry.id,
567
+ revision: source.revision,
568
+ repo: source.repo,
569
+ provider: source.provider,
570
+ fingerprint: entry.profileFingerprint,
571
+ installedAt: now(),
572
+ totalBytes: entry.totalBytes,
573
+ files: (entry.files || []).map(file => ({ path: file.path, role: file.role, bytes: file.bytes, sha256: file.sha256 })),
574
+ checks: Array.isArray(smoke?.checks) ? smoke.checks : [],
575
+ verifiedBy: typeof verifyModel === 'function' ? 'custom-verify-model' : 'sha256+structural-smoke',
576
+ // 明确记录:安装≠启用。active profile 由迁移模块的受验证切换流程负责。
577
+ active: false,
578
+ }
579
+ writeJsonAtomic(path.join(staging, INSTALL_RECORD), record)
580
+
581
+ const finalDir = modelDir(entry.id)
582
+ const previousExists = fs.existsSync(finalDir)
583
+ let trash = null
584
+ if (previousExists) {
585
+ const trashRoot = insideRoot(path.join(baseDir, TRASH_DIR))
586
+ fs.mkdirSync(trashRoot, { recursive: true })
587
+ trash = path.join(trashRoot, `${entry.id}-${crypto.randomUUID()}`)
588
+ fs.renameSync(finalDir, trash)
589
+ }
590
+ try {
591
+ fs.renameSync(staging, finalDir)
592
+ staging = null
593
+ installed = true
594
+ } catch (error) {
595
+ if (trash) { try { fs.renameSync(trash, finalDir) } catch {} }
596
+ throw fail('EMBEDDING_INSTALL_FAILED', `cannot move the verified artifact into place: ${error?.message || error}`, { cause: error })
597
+ }
598
+ if (trash) { try { fs.rmSync(trash, { recursive: true, force: true }) } catch {} }
599
+ job.state = 'installed'
600
+ jobs.delete(entry.id)
601
+ outcomes.delete(entry.id)
602
+ return getStatus(entry.id)
603
+ } catch (error) {
604
+ const aborted = isAbort(error, controller.signal)
605
+ const code = aborted ? 'EMBEDDING_DOWNLOAD_ABORTED' : (typeof error?.code === 'string' && error.code.startsWith('EMBEDDING_') ? error.code : 'EMBEDDING_DOWNLOAD_FAILED')
606
+ const failed = code === error?.code ? error : fail(code, `download of ${entry.id} failed: ${error?.message || error}`, { cause: error })
607
+ // S-16:非可续传类失败清掉 .part,别让半成品占空间;网络错误/超时/取消
608
+ // 保留 .part 供下次 Range 续传(S-1)。
609
+ if (!['EMBEDDING_DOWNLOAD_ABORTED', 'EMBEDDING_NETWORK_ERROR', 'EMBEDDING_DOWNLOAD_TIMEOUT'].includes(code)) {
610
+ for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} }
611
+ }
612
+ job.state = aborted ? 'cancelled' : 'failed'
613
+ job.error = { code, message: String(failed.message || error) }
614
+ jobs.delete(entry.id)
615
+ outcomes.set(entry.id, { state: job.state, error: { ...job.error } })
616
+ throw failed
617
+ } finally {
618
+ signal?.removeEventListener('abort', onAbort)
619
+ if (staging && !installed) { try { fs.rmSync(staging, { recursive: true, force: true }) } catch {} }
620
+ // 安装成功后本次的 .part 已完成使命,清掉避免长期占空间。
621
+ if (installed) { for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} } }
622
+ }
623
+ }
624
+
625
+ function dispose() {
626
+ // 只中止在途下载;状态与错误原因留给 getStatus 展示。
627
+ for (const job of jobs.values()) { try { job.controller?.abort() } catch {} }
628
+ }
629
+
630
+ return {
631
+ root: baseDir,
632
+ catalogIds: [...getEmbeddingCatalog().map(entry => entry.id), ...extraCatalog.map(entry => entry?.id).filter(Boolean)],
633
+ getStatus,
634
+ download,
635
+ dispose,
636
+ }
637
+ }