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,1055 +1,1051 @@
1
- import crypto from 'node:crypto'
2
-
3
- // §14.4 模型目录:只读、无副作用。目录里的每个事实都带来源;没有核实过的制品一律
4
- // availability: 'pending' 且 files: []——绝不写猜测的 bytes/SHA-256(§14.4/§14.12)。
5
- // 这里不做下载、不做安装、不读不写任何 profile/active 状态(那是 embedding-download 与
6
- // 后续迁移模块的事)。
7
-
8
- export const CATALOG_SCHEMA_VERSION = 1
9
-
10
- // 默认来源顺序;只有 manifest 里显式写了 repo+revision 的来源才会生成 URL。
11
- export const PROVIDER_ORDER = Object.freeze(['modelscope', 'hf-mirror', 'huggingface'])
12
-
13
- export const PROVIDERS = Object.freeze({
14
- modelscope: Object.freeze({
15
- id: 'modelscope',
16
- label: 'ModelScope',
17
- url: ({ repo, revision, path }) => `https://modelscope.cn/api/v1/models/${repo}/repo?Revision=${revision}&FilePath=${encodeURIComponent(path)}`,
18
- }),
19
- 'hf-mirror': Object.freeze({
20
- id: 'hf-mirror',
21
- label: 'hf-mirror',
22
- url: ({ repo, revision, path }) => `https://hf-mirror.com/${repo}/resolve/${revision}/${encodePath(path)}`,
23
- }),
24
- huggingface: Object.freeze({
25
- id: 'huggingface',
26
- label: 'Hugging Face',
27
- url: ({ repo, revision, path }) => `https://huggingface.co/${repo}/resolve/${revision}/${encodePath(path)}`,
28
- }),
29
- })
30
-
31
- export const FILE_ROLES = Object.freeze(['graph', 'config', 'tokenizer', 'tokenizer-config', 'special-tokens', 'vocab', 'quantization', 'pooling-config', 'notice'])
32
-
33
- const ONNX_DTYPES = Object.freeze({
34
- 1: 'float32', 2: 'uint8', 3: 'int8', 4: 'uint16', 5: 'int16', 6: 'int32', 7: 'int64',
35
- 8: 'string', 9: 'bool', 10: 'float16', 11: 'double', 12: 'uint32', 13: 'uint64',
36
- })
37
-
38
- function encodePath(filePath) {
39
- return String(filePath).split('/').map(encodeURIComponent).join('/')
40
- }
41
-
42
- function sha256Of(value) {
43
- return crypto.createHash('sha256').update(value).digest('hex')
44
- }
45
-
46
- function canonical(value) {
47
- if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
48
- if (value && typeof value === 'object') {
49
- return `{${Object.keys(value).sort().filter(key => value[key] !== undefined).map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`
50
- }
51
- return JSON.stringify(value ?? null)
52
- }
53
-
54
- function deepFreeze(value) {
55
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
56
- Object.freeze(value)
57
- for (const key of Object.keys(value)) deepFreeze(value[key])
58
- }
59
- return value
60
- }
61
-
62
- // 核实证据(2026-10-30):ModelScope 可直连;huggingface.co 与 hf-mirror.com 在本机
63
- // fetch failed。逐文件 SHA-256 取自 ModelScope 文件清单,并与实际下载的字节复核一致,
64
- // 证据留在 .tmp-local-vector-20261030/probe/。
65
- const BGE_REPO = 'Xenova/bge-small-zh-v1.5'
66
- const BGE_REVISION = '313386ad7ffad360a4870fd1910f8ecaf1a05151'
67
- const BGE_COMMIT_TIME = '2025-07-22T11:41:37.000Z'
68
- const BAAI_REPO = 'BAAI/bge-small-zh-v1.5'
69
- const BAAI_POOLING_REVISION = '8399f11f8da998fe932df2684586c92024219d05'
70
-
71
- // 核实证据(2026-11-02):两条新条目同样只走 ModelScope 直连(huggingface.co 超时、
72
- // hf-mirror 重定向回 huggingface.co 后不可达)。revision 取仓库 HEAD commit;逐文件
73
- // bytes/sha256 取自 ModelScope 文件清单,并与实际下载字节、图头解析结果复核一致。
74
- const MINIML_REVISION = '5f19c574ce6bbb065d51869c525840f8a975dcc4'
75
- const MINIML_COMMIT_TIME = '2025-07-22T19:48:27.000Z'
76
- const MINIML_POOLING_REVISION = '524b52f1d626e9a5a16462e141fc9dffc25d5aeb'
77
- const E5_REVISION = '252d0dcb679dda2c7b6fd5bbfed15df3c7feaebf'
78
- const E5_COMMIT_TIME = '2025-07-22T22:49:03.000Z'
79
- const E5_POOLING_REVISION = 'bdd905ef05181adf3ebbfaac5cd5bd4ed9a58760'
80
-
81
- // 核实证据(2026-11-02):Qwen3-Embedding 的 ONNX 导出只在 huggingface 系(n24q02m 的仓库
82
- // 与基座 Qwen 的仓库在 ModelScope 上都没有对应条目)。本机 huggingface.co 连不上,
83
- // hf-mirror.com 通(它重定向到自己的 resolve-cache,不经过 huggingface.co),所以
84
- // 默认走 hf-mirror;两个 provider pin 同一个 commit,逐文件 sha256 与 HF 的 LFS oid 对过。
85
- const QWEN_EXPORT_REPO = 'n24q02m/Qwen3-Embedding-0.6B-ONNX'
86
- const QWEN_REVISION = 'dc873d64d6143f27ad68dadbd1f0d9a4371b994e'
87
- const QWEN_COMMIT_TIME = '2026-02-18T17:28:18.000Z'
88
- const QWEN_BASE_REPO = 'Qwen/Qwen3-Embedding-0.6B'
89
- const QWEN_BASE_REVISION = '97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3'
90
- // 官方默认 query prompt(config_sentence_transformers.json 的 prompts.query),document 侧
91
- // 官方明确「No need to add instruction for retrieval documents」→ 非对称,走角色通道。
92
- const QWEN_QUERY_PROMPT = 'Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:'
93
- // 两个 provider 都是同一个 commit 的同一份内容;每写一个文件都要过 sha256,所以
94
- // 允许见证制品在任一 provider 上取,而不是把源站整条封掉。
95
- const QWEN_MIRROR_PROVIDERS = ['hf-mirror', 'huggingface']
96
-
97
- // 三个模型 pin 的是同一棵受管 ONNX 运行时树:安装事实只写一次,条目里展开复用。
98
- // 指纹只看 engine/abi/version/os/arch 五个字段(§14.8),note 不参与,所以共享常量
99
- // 不会把某个模型的运行时事实悄悄改成另一个模型的。
100
- const PINNED_ONNX_RUNTIME = Object.freeze({
101
- engine: 'onnxruntime-node',
102
- version: '1.31.1',
103
- abi: 'napi-v6',
104
- os: 'win32',
105
- arch: 'x64',
106
- verified: true,
107
- tokenizer: { name: '@huggingface/tokenizers', version: '0.2.0', license: 'Apache-2.0', sha256: 'f6b9849b58de625c4fd79583242dd4506914b92082f9af17719d39416658ef24' },
108
- packages: [
109
- { name: 'onnxruntime-node', version: '1.31.1', license: 'MIT', sha256: '41aedb3e877786245ab4dc0f533cda63f7d971b5c5fec171eafca9fb9572a8d5' },
110
- { name: 'onnxruntime-common', version: '1.31.1', license: 'MIT', sha256: 'c8e59240260cd3d230f1417765e0dbe098323ef65a5785991059de1bd5d7cde0' },
111
- ],
112
- // 受管安装事实(2026-10-30):三个 npm tarball 本轮真实下载并核对 sha256/bytes;
113
- // 解包后的最小运行时树跑通真实 /v1/embeddings 推理(512 维、worker ready ≈559ms)。
114
- // 只允许从这些 URL 下载并按下面的 hash 校验;没有 hash 或没有该平台原生库一律拒绝安装。
115
- install: {
116
- scope: 'per-user-managed',
117
- layout: 'node_modules',
118
- postinstall: 'never-run',
119
- verifiedAt: '2026-10-30T03:45:00.000Z',
120
- verifiedOn: 'win32-x64',
121
- platforms: {
122
- 'win32-x64': 'smoke-verified',
123
- 'win32-arm64': 'artifact-pinned',
124
- 'linux-x64': 'artifact-pinned',
125
- 'linux-arm64': 'artifact-pinned',
126
- 'darwin-arm64': 'artifact-pinned',
127
- },
128
- evidence: 'npm tarball sha256 与 registry integrity 双向一致;解包最小树真实推理通过;原生库逐文件 sha256 取自同一棵已核实树',
129
- },
130
- // Every source serves the same npm tarball; the installer still verifies the pinned
131
- // bytes+sha256 after download, so a mirror can never change the runtime tree.
132
- artifacts: [
133
- {
134
- name: 'onnxruntime-node', version: '1.31.1', license: 'MIT',
135
- url: 'https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz',
136
- sources: [
137
- { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz' },
138
- { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz' },
139
- ],
140
- bytes: 115391311,
141
- sha256: 'd7a3de2b1bba92614abc74af909cc0ba4f4dd5347735418794edeb58cfef2d22',
142
- integrity: 'sha512-ijnSghbDHVWaQ2nDPmVccPlCHI8kH1Mx1aJ4a/qzRP16bBcVs4E3EqZQKZCkhWnbqN1tuQWxagimFtDpbPYYQw==',
143
- extract: ['package.json', 'README.md', 'dist', 'lib', 'bin/napi-v6/<platform>'],
144
- },
145
- {
146
- name: 'onnxruntime-common', version: '1.31.1', license: 'MIT',
147
- url: 'https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz',
148
- sources: [
149
- { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz' },
150
- { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz' },
151
- ],
152
- bytes: 72322,
153
- sha256: '967acac0c2a22122461e526aeda07305da7289d94f276920d8a6919483f07bfc',
154
- integrity: 'sha512-F+nnYNiQtmNJ95V6R/isBJqiVpdANCrsMEg1OaF+Bkbl3GAtzWLR7Ng17Ld0QtYtYJyotOHPJzOQn1Y6PLZjpg==',
155
- extract: ['package.json', 'README.md', 'dist', 'lib'],
156
- },
157
- {
158
- name: '@huggingface/tokenizers', version: '0.2.0', license: 'Apache-2.0',
159
- url: 'https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz',
160
- sources: [
161
- { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz' },
162
- { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz' },
163
- ],
164
- bytes: 87011,
165
- sha256: '2800014c83b8186b2e4210c20672f1fb65a12cef85d7e95e0f2003e022611b4a',
166
- integrity: 'sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==',
167
- extract: ['package.json', 'README.md', 'LICENSE', 'dist', 'types'],
168
- },
169
- ],
170
- // 解包后的 package.json 事实(字节数 + sha256):用于确认解出来的就是 pin 住的版本。
171
- packageFiles: [
172
- { package: 'onnxruntime-node', bytes: 1593, sha256: '41aedb3e877786245ab4dc0f533cda63f7d971b5c5fec171eafca9fb9572a8d5' },
173
- { package: 'onnxruntime-common', bytes: 977, sha256: 'c8e59240260cd3d230f1417765e0dbe098323ef65a5785991059de1bd5d7cde0' },
174
- { package: '@huggingface/tokenizers', bytes: 1965, sha256: 'f6b9849b58de625c4fd79583242dd4506914b92082f9af17719d39416658ef24' },
175
- ],
176
- // 判分/加载必需的原生库逐文件 hash。没有列出原生库的平台不得安装(不允许猜)。
177
- native: {
178
- 'win32-x64': [
179
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/x64/onnxruntime_binding.node', bytes: 358200, sha256: '8d9f996ff7dcc60c4899aa87aa7abe07d806f9c314882f44a001d0fd8a23d16f' },
180
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/x64/onnxruntime.dll', bytes: 31736672, sha256: 'beb6e1edba0e74c132453fe4df113da2ea2b99ef8ea7dfc25696a872efd11c45' },
181
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/x64/DirectML.dll', bytes: 18527544, sha256: 'd16be72fa002dd610cca93e376f0ef44865dfce43de4b7bf9738af22534f7a9d' },
182
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/x64/dxcompiler.dll', bytes: 17986400, sha256: '430eed027979399769a325b60319aca4e4afa4daebe475d3c763dcf2a0190a72' },
183
- ],
184
- 'win32-arm64': [
185
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/arm64/onnxruntime_binding.node', bytes: 504160, sha256: '6f34d4635793371c85e5260dbdc0864c2ef62ccfcb1f439afa3501ba6f8d530d' },
186
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/arm64/onnxruntime.dll', bytes: 32835936, sha256: '14d1cd398fa5bc8b5c61bdfba899f17b40550012ec2884955ce656a5d8a8ff77' },
187
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/arm64/DirectML.dll', bytes: 18444600, sha256: '4bb0639eb23a02de2c5f1eddd117f13330819f55b556e8c75068b68ad1a3516e' },
188
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/arm64/dxcompiler.dll', bytes: 22285624, sha256: '4a77bcadf4d437ad50d10517bb0b4a5a4c2fc84b1fde4d1cf5a5abe9e2dce431' },
189
- ],
190
- 'linux-x64': [
191
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/linux/x64/onnxruntime_binding.node', bytes: 519712, sha256: 'e3a108803b8bd33c8e9691b52921c37bede7a6886251aa41219f053d268ee231' },
192
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/linux/x64/libonnxruntime.so.1', bytes: 47552704, sha256: 'f19a4da48c4c65e0cdccff82354482f657fa91a3455b66174195b94ca55b0e6f' },
193
- ],
194
- 'linux-arm64': [
195
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/linux/arm64/onnxruntime_binding.node', bytes: 551752, sha256: '5d943f6bf8f65c40213bac636f19bcb227ee1d188417c4b6a6f70062579cfb84' },
196
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/linux/arm64/libonnxruntime.so.1', bytes: 25266408, sha256: '152fb7d2f4f06acc5a38627fbca3e56ba2a9b984cb060d2ac500ac272afbb9ba' },
197
- ],
198
- 'darwin-arm64': [
199
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/darwin/arm64/onnxruntime_binding.node', bytes: 323512, sha256: '95ab5698fbcb34d035ea98266156ad5a06b76d0ee739ea42d660df6901df390a' },
200
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/darwin/arm64/libonnxruntime.1.dylib', bytes: 45331560, sha256: '9a362365243b56da98a2ad65128a32d6f8066d1f39ce697e0fce997adf0586dc' },
201
- { path: 'node_modules/onnxruntime-node/bin/napi-v6/darwin/arm64/libonnxruntime.1.31.1.dylib', bytes: 45331560, sha256: '9a362365243b56da98a2ad65128a32d6f8066d1f39ce697e0fce997adf0586dc' },
202
- ],
203
- },
204
- })
205
-
206
- // Qwen3-Embedding 的两种量化各是一张卡片:int8 与 int4+fp16 的权重存储方式不同,
207
- // 落出来的向量空间也不同(§14.8 里 quantization 进指纹),所以必须分条目、分 DB,
208
- // 而不是一个条目两个文件让用户以为可以混用。
209
- function qwen3Card(variant) {
210
- const int8 = variant === 'int8'
211
- const graphPath = int8 ? 'onnx/model_quantized.onnx' : 'onnx/model_q4f16.onnx'
212
- const graphBytes = int8 ? 600223343 : 541820311
213
- const graphSha = int8
214
- ? '76dc4f417876e48b2fae7f325cb052f46099c890e6a7c1b60f91ff5027d751ef'
215
- : '2db238eb6122ce336c9de62df9c08113a4da7f41514298885a379451e952178e'
216
- const activation = int8 ? 'float32' : 'float16'
217
- return {
218
- id: `qwen3-embedding-0.6b-${variant}`,
219
- displayName: `Qwen3-Embedding-0.6B (${variant} ONNX)`,
220
- summary: int8
221
- ? 'Qwen3 0.6B 多语言检索模型(1024 维、last-token pooling + L2),默认下载的就是这份 int8。受管 ORT CPU 实测:图加载 2.06 s、短句一次编码 91 ms、380 字 437 ms、1520 字 4.29 s——比 BGE/MiniLM/e5 慢一到两个数量级,换来的是跨 100+ 语言与代码检索。查询侧带官方 Instruct 前缀(非对称 → 需要角色通道),实测加/不加前缀的同句余弦只有 0.8284;同一份 recall-bench 草稿上带前缀 R@1 0.6970 / MRR 0.8359,不带前缀 0.6667 / 0.8081(33 条可答样本,差一个样本,不当结论,但方向与官方说明一致)。'
222
- : '与 int8 卡片同一份 0.6B 权重的 int4 变体(float16 激活 + com.microsoft.MatMulNBits,block_size=128),制品 542 MB vs 600 MB。受管 ORT CPU 实测反而更慢:加载 11.4 s、短句 110 ms、380 字 870 ms、1520 字 5.86 s,且依赖 com.microsoft 私有算子域。在这份合成草稿上它没有变差(带前缀 R@1 0.7273 / MRR 0.8510,int8 是 0.6970 / 0.8359)——33 个样本的差距不足以排序两个变体的质量,能当依据的是实测到的加载慢 5.5 倍与贡献算子依赖。向量空间与 int8 卡片不同,切换 = 重建。',
223
- languages: ['zh', 'en', 'multilingual'],
224
- tier: int8 ? 'preferred' : 'optional',
225
- availability: 'available',
226
- pendingReasons: [],
227
- parameters: int8 ? 595776975 : 599217221,
228
- parameterSource: int8
229
- ? '图内 initializer 元素合计 595,776,975(int8 440,402,116 + uint8 155,309,057 + float32 65,802,不含 int64/bool 位置与掩码表);官方模型卡 0.6B'
230
- : '图内 initializer 元素合计 599,217,221(float16 158,815,301 + int4 按 uint8 打包 ×2 = 440,401,920);与 int8 变体同一份 0.6B 权重,存储方式不同所以计数略有出入',
231
- dimension: 1024,
232
- // 制品侧 config.max_position_embeddings=32768(tokenizer model_max_length 131072),
233
- // 这里按实测延迟取 4096:1520 字已经 4.3 s,按 32k 跑一条长记忆会直接顶到 worker 的
234
- // 120 s 请求超时。分窗是指纹字段,所以它是刻意的策略而不是「没核实」。
235
- maxTokens: 4096,
236
- // 因果 LM:官方 1_Pooling pooling_mode_lasttoken=true,其余全 false。
237
- pooling: 'last',
238
- normalization: 'l2',
239
- prefixes: { query: QWEN_QUERY_PROMPT, document: '' },
240
- quantization: int8
241
- ? {
242
- weights: 'qint8',
243
- scheme: 'dynamic-per-tensor',
244
- reduceRange: null,
245
- source: '导出仓库 README 声明 onnxruntime.quantization.quantize_dynamic(QInt8);图侧核实 196/196 个 MatMulInteger 的 scale/zero_point 都是 rank-0 标量、per-channel scale 向量 0 个,另有 DynamicQuantizeLinear 112 个 → 激活动态量化 + 权重 per-tensor,和 BGE/MiniLM/e5 的 per-channel 不是同一个空间',
246
- }
247
- : {
248
- weights: 'uint4-nbits',
249
- scheme: 'block-wise-int4-block128-fp16-activations',
250
- reduceRange: null,
251
- source: 'README 声明 MatMulNBitsQuantizer(block_size=128, symmetric) + FP16 cast;图侧核实 com.microsoft.MatMulNBits 196 个、打包权重形状 [out, blocks, 64](blocks×128 = 输入维、64 字节 = 128 个 nibble),其余 initializer 为 float16;opset 21 + com.microsoft v1',
252
- },
253
- runtime: {
254
- ...PINNED_ONNX_RUNTIME,
255
- note: int8
256
- ? '受管 ORT 1.31.1 CPU 真实加载/推理已核实(2026-11-02,win32-x64):1024 维、单位范数、重复编码余弦 1.0。'
257
- : '受管 ORT 1.31.1 CPU 真实加载/推理已核实(2026-11-02,win32-x64),但依赖 com.microsoft 贡献算子域;加载 11.4 s,仍在 worker 60 s ready 预算内。',
258
- },
259
- license: {
260
- base: { id: 'apache-2.0', source: 'hf-mirror 元数据 Qwen/Qwen3-Embedding-0.6B cardData.license = apache-2.0(2026-11-02 只读核对)' },
261
- onnxExport: { id: 'apache-2.0', source: 'n24q02m/Qwen3-Embedding-0.6B-ONNX 的 README front-matter license: apache-2.0(2026-11-02 核对下载字节)' },
262
- },
263
- verification: {
264
- status: 'verified',
265
- method: 'sha256+onnx-header+onnxruntime-inference',
266
- checkedAt: '2026-11-02T08:55:00.000Z',
267
- scope: `逐文件 bytes/sha256 与 HF 文件树声明一致(LFS 制品直接对 lfs.oid 的 sha256)+ ONNX 图头(opset 21、input_ids/attention_mask 两个 int64 输入、last_hidden_state ${activation}[1,sequence_length,1024]、自包含、固定 batch=1 导出)+ 基座 1_Pooling/2_Normalize 的 pooling 与归一化事实 + 受管 ORT CPU 真实推理与延迟测量`,
268
- evidence: int8
269
- ? '2026-11-02 实测(.tmp-model-adapt-20261102/qwen3*):onnx/model_quantized.onnx 600,223,343 B 的 sha256 与 HF LFS oid 76dc4f41…逐字节一致;加载 2057 ms、首帧 91 ms、380 字 437 ms、1520 字 4286 ms、单位范数 1.0、重复编码余弦 1.0;instruct 前缀漂移余弦 0.8284;42 条 recall-bench 草稿的 33 条可答样本上带前缀 R@1 0.6970 / R@3 0.9697 / MRR 0.8359、裸文本 0.6667 / 0.9394 / 0.8081;真机五路互切(MiniLM→本卡→q4f16→e5→BGE)各 6/6 条重建、0 失败、中英查询均召回'
270
- : '2026-11-02 实测(.tmp-model-adapt-20261102/qwen3*):onnx/model_q4f16.onnx 541,820,311 B 的 sha256 与 HF LFS oid 2db238eb…逐字节一致;加载 11401 ms、首帧 110 ms、380 字 870 ms、1520 字 5863 ms、单位范数 1.0、重复编码余弦 1.0;instruct 前缀漂移余弦 0.8203;同一份草稿带前缀 R@1 0.7273 / R@3 0.9697 / MRR 0.8510、裸文本 0.6667 / 0.9394 / 0.8081;真机五路互切里作为 g3 完成重建并召回',
271
- notVerified: [
272
- 'modelscope 上没有该导出仓库与基座仓库的对应条目(只读核对 record not found)',
273
- `huggingface.co 源站本机不可达:同一 commit 的同一批文件只在 hf-mirror 上做过逐字节复核`,
274
- '与 PyTorch 基座(float32/bfloat16)向量的数值等价性——本包不做参考实现比对,只保证同一制品重复编码一致',
275
- ],
276
- },
277
- sources: {
278
- 'hf-mirror': { repo: QWEN_EXPORT_REPO, revision: QWEN_REVISION, revisionVerified: true, commitTime: QWEN_COMMIT_TIME },
279
- huggingface: { repo: QWEN_EXPORT_REPO, revision: QWEN_REVISION, revisionVerified: false, commitTime: QWEN_COMMIT_TIME, note: '与 hf-mirror pin 同一个 commit;本机连不上 huggingface.co,所以未独立复核,但逐文件 sha256 是硬校验' },
280
- },
281
- witness: {
282
- provider: 'hf-mirror',
283
- repo: QWEN_BASE_REPO,
284
- revision: QWEN_BASE_REVISION,
285
- path: '1_Pooling/config.json',
286
- bytes: 313,
287
- sha256: '37bf193fa101f19101bfad9c31d3eb0f786e247b7b1e5cb7f007d730eed1ddbd',
288
- purpose: 'pooling 事实来源:pooling_mode_lasttoken=true 且 cls/mean/max/weightedmean 全 false、word_embedding_dimension=1024、include_prompt=true;同仓库 modules.json 含 2_Normalize(L2),config_sentence_transformers.json 的 prompts.query 给出官方 Instruct 前缀且 prompts.document 为空',
289
- },
290
- graph: {
291
- path: graphPath,
292
- opset: 21,
293
- producer: int8 ? 'onnx.quantize' : 'pytorch',
294
- producerVersion: int8 ? '0.1.0' : '2.10.0+cu128',
295
- selfContained: true,
296
- externalData: [],
297
- inputs: [
298
- { name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
299
- { name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
300
- ],
301
- // batch 维是字面量 1(导出时固定),所以一次只能喂一行。
302
- outputs: [{ name: 'last_hidden_state', dtype: activation, shape: [1, 'sequence_length', 1024] }],
303
- },
304
- files: [
305
- { path: 'config.json', role: 'config', bytes: 1416, sha256: '88014d4dd5f874bf4050a57e76029ffdb42bead2c0c9253b4eb21bc65da8a5d9' },
306
- { path: 'tokenizer.json', role: 'tokenizer', bytes: 11423701, sha256: '93623af029cdc69b87f2864d3b2cc2424fdf16684f15e139b5b9d08ec34ced91' },
307
- { path: 'tokenizer_config.json', role: 'tokenizer-config', bytes: 349, sha256: 'bc3e7cb4dad833a185d4bfbb4880562dc9b0cb101c47b8985078122a122d553a' },
308
- { path: graphPath, role: 'graph', bytes: graphBytes, sha256: graphSha },
309
- { path: 'README.md', role: 'notice', bytes: 2226, sha256: 'a5b65f56517933cc8b6724293b73e7123531569df121ae3ebe597dd8dd571a3f' },
310
- {
311
- path: '1_Pooling/config.json',
312
- role: 'pooling-config',
313
- bytes: 313,
314
- sha256: '37bf193fa101f19101bfad9c31d3eb0f786e247b7b1e5cb7f007d730eed1ddbd',
315
- origin: {
316
- provider: 'hf-mirror',
317
- providers: QWEN_MIRROR_PROVIDERS,
318
- repo: QWEN_BASE_REPO,
319
- revision: QWEN_BASE_REVISION,
320
- },
321
- },
322
- ],
323
- }
324
- }
325
-
326
- const rawCatalog = [
327
- {
328
- id: 'bge-small-zh-v1.5-int8',
329
- displayName: 'BGE small zh v1.5 (int8 ONNX)',
330
- summary: '中文优先的检索小模型;BGE v1.5 检索无需 instruction,CLS pooling + L2 归一化,512 维。',
331
- languages: ['zh', 'en'],
332
- tier: 'preferred',
333
- availability: 'available',
334
- pendingReasons: [],
335
- parameters: 24000000,
336
- parameterSource: 'BAAI 官方模型页 24M(docs/local-vector-construction.md §14.4 引用)',
337
- dimension: 512,
338
- maxTokens: 512,
339
- pooling: 'cls',
340
- normalization: 'l2',
341
- prefixes: { query: '', document: '' },
342
- quantization: {
343
- weights: 'qint8',
344
- scheme: 'dynamic-per-channel',
345
- reduceRange: true,
346
- source: 'quantize_config.json(per_channel=true, reduce_range=true, weight_type=QInt8) + 图内 MatMulInteger/DynamicQuantizeLinear',
347
- },
348
- runtime: {
349
- ...PINNED_ONNX_RUNTIME,
350
- note: '隔离目录真实 ORT CPU 加载/推理 smoke 已核实;仅允许固定版本,不隐式下载。',
351
- },
352
- license: {
353
- base: { id: 'mit', source: 'ModelScope BAAI/bge-small-zh-v1.5 的 License 字段 = mit(2026-10-30 只读核对)' },
354
- onnxExport: { id: 'undeclared', source: 'ModelScope Xenova/bge-small-zh-v1.5 的 License 字段为空,ONNX 导出未单独声明许可(2026-10-30 核对)' },
355
- },
356
- verification: {
357
- status: 'verified',
358
- method: 'sha256+onnx-header',
359
- checkedAt: '2026-10-30T00:20:00.000Z',
360
- scope: '逐文件 bytes/sha256 复核 + ONNX 图头(opset/输入输出/dtype/形状/自包含)+ config/tokenizer 解析',
361
- evidence: '.tmp-local-vector-20261030/probe/ 下的实测文件,sha256 与 ModelScope 清单逐字节一致',
362
- notVerified: ['huggingface/hf-mirror 上的对应 commit'],
363
- },
364
- sources: {
365
- modelscope: { repo: BGE_REPO, revision: BGE_REVISION, revisionVerified: true, commitTime: BGE_COMMIT_TIME },
366
- 'hf-mirror': { repo: BGE_REPO, revision: null, revisionVerified: false, note: 'hf-mirror.com 本机不可达,commit 未核实;不生成 URL' },
367
- huggingface: { repo: BGE_REPO, revision: null, revisionVerified: false, note: 'huggingface.co 本机不可达,commit 未核实;不生成 URL' },
368
- },
369
- witness: {
370
- provider: 'modelscope',
371
- repo: BAAI_REPO,
372
- revision: BAAI_POOLING_REVISION,
373
- path: '1_Pooling/config.json',
374
- bytes: 190,
375
- sha256: 'aaa8861589f80c961a03cc86c7eeaef7605c1676b9ab55329d33a304738769c6',
376
- purpose: 'pooling 事实来源:pooling_mode_cls_token=true、word_embedding_dimension=512',
377
- },
378
- graph: {
379
- path: 'onnx/model_quantized.onnx',
380
- opset: 11,
381
- producer: 'onnx.quantize',
382
- producerVersion: '0.1.0',
383
- selfContained: true,
384
- externalData: [],
385
- inputs: [
386
- { name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
387
- { name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
388
- { name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
389
- ],
390
- outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 512] }],
391
- },
392
- files: [
393
- { path: 'config.json', role: 'config', bytes: 716, sha256: 'd4193ead3a810fd694fa8a31d7fc72fbaebc0668b603e398734bf2f6538ff42f' },
394
- { path: 'tokenizer.json', role: 'tokenizer', bytes: 439125, sha256: '48cea5d44424912a6fd1ea647bf4fe50b55ab8b1e5879c3275f80e339e8fae26' },
395
- { path: 'tokenizer_config.json', role: 'tokenizer-config', bytes: 367, sha256: 'e6f3b96db926a37d4039995fbf5ad17de158dfb8f6343d607e4dbaad18d75f5a' },
396
- { path: 'special_tokens_map.json', role: 'special-tokens', bytes: 125, sha256: 'b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3' },
397
- { path: 'vocab.txt', role: 'vocab', bytes: 109540, sha256: '45bbac6b341c319adc98a532532882e91a9cefc0329aa57bac9ae761c27b291c' },
398
- { path: 'onnx/model_quantized.onnx', role: 'graph', bytes: 24010842, sha256: '15b717c382bcb518ba457b93ea6850ede7f4f1cd8937454aa06972366cd19bcc' },
399
- { path: 'quantize_config.json', role: 'quantization', bytes: 674, sha256: '2cc488b20fa05fe86aba2fdc2be44d24827e11e2b7c7a0753d1427da6797b46f' },
400
- { path: 'README.md', role: 'notice', bytes: 1057, sha256: 'cb22054df1a98f7ee9d5b281d023e67c27cc316e1733baf03fc994d95c3048ab' },
401
- {
402
- path: '1_Pooling/config.json',
403
- role: 'pooling-config',
404
- bytes: 190,
405
- sha256: 'aaa8861589f80c961a03cc86c7eeaef7605c1676b9ab55329d33a304738769c6',
406
- origin: { provider: 'modelscope', repo: BAAI_REPO, revision: BAAI_POOLING_REVISION },
407
- },
408
- ],
409
- },
410
- {
411
- id: 'all-minilm-l6-v2-int8',
412
- displayName: 'all-MiniLM-L6-v2 (int8 ONNX)',
413
- summary: '英文句子相似度小模型(384 维,mean pooling + L2)。中文能跑但明显弱于另外两个:同一份 recall-bench 草稿 33 条可答样本上 R@1 0.5455 / MRR@3 0.7525,BGE 是 0.6667 / 0.8106。它不是中文模型的等价替代,适合英文语料或只想装 23 MB 制品的场合。',
414
- languages: ['en'],
415
- tier: 'optional',
416
- availability: 'available',
417
- pendingReasons: [],
418
- parameters: 22565376,
419
- parameterSource: '实测图内 initializer 元素合计 22,565,376(uint8 11,917,824 + int8 10,616,832 + float32 30,720);官方模型页标 22.7M',
420
- dimension: 384,
421
- // 底座 config.max_position_embeddings=512、tokenizer model_max_length=512、图输出第三维=384
422
- // 三处一致;sentence_bert_config.json 的 max_seq_length=256 只是 SB wrapper 的窗口。
423
- // 分窗按制品本身取 512,和 BGE 同窗,切换模型不会顺带改分窗口径。
424
- maxTokens: 512,
425
- pooling: 'mean',
426
- normalization: 'l2',
427
- prefixes: { query: '', document: '' },
428
- quantization: {
429
- weights: 'qint8',
430
- scheme: 'dynamic-per-channel',
431
- reduceRange: null,
432
- source: '仓库未随附 quant_config.json;方案取自图本身:MatMulInteger(36)+DynamicQuantizeLinear(24),39/39 个 int8/uint8 二维权重都存在长度=输出通道数的一维 float32 scale,长度 1 的标量 scale=0',
433
- },
434
- runtime: { ...PINNED_ONNX_RUNTIME, note: '同一棵受管 ORT 1.31.1 CPU 树真实推理已核实(2026-11-02):384 维、单位范数、重复编码余弦 1.0。' },
435
- license: {
436
- base: { id: 'apache-2.0', source: 'ModelScope Xenova/all-MiniLM-L6-v2 元数据 License=apache-2.0(2026-11-02 只读核对)' },
437
- onnxExport: { id: 'apache-2.0', source: '导出仓库 README front-matter license: apache-2.0(2026-11-02 核对下载字节)' },
438
- },
439
- verification: {
440
- status: 'verified',
441
- method: 'sha256+onnx-header+onnxruntime-inference',
442
- checkedAt: '2026-11-02T08:00:00.000Z',
443
- scope: '逐文件 bytes/sha256 与 ModelScope 文件清单双向一致 + ONNX 图头(opset 11、3 个 int64 输入、last_hidden_state float32[batch,seq,384]、自包含 22,661,632 initializer 字节)+ vocab.txt 行数 30522=config.vocab_size + 受管 ORT CPU 真实推理',
444
- evidence: '2026-11-02 实测(.tmp-model-adapt-20261102):8 个文件 sha256 全部与清单一致;worker 单次编码 7ms、单位范数 1.0、重复编码余弦 1.0、>512 token 长文截断可用;42 条 recall-bench 草稿 33 条可答样本 R@1 0.5455 / R@3 1.0000 / MRR@3 0.7525',
445
- notVerified: ['huggingface/hf-mirror 上的对应 commit(本机不可达)'],
446
- },
447
- sources: {
448
- modelscope: { repo: 'Xenova/all-MiniLM-L6-v2', revision: MINIML_REVISION, revisionVerified: true, commitTime: MINIML_COMMIT_TIME },
449
- 'hf-mirror': { repo: 'Xenova/all-MiniLM-L6-v2', revision: null, revisionVerified: false, note: 'hf-mirror.com 本机不可达,commit 未核实;不生成 URL' },
450
- huggingface: { repo: 'sentence-transformers/all-MiniLM-L6-v2', revision: null, revisionVerified: false, note: 'huggingface.co 本机不可达,commit 未核实;不生成 URL' },
451
- },
452
- witness: {
453
- provider: 'modelscope',
454
- repo: 'sentence-transformers/all-MiniLM-L6-v2',
455
- revision: MINIML_POOLING_REVISION,
456
- path: '1_Pooling/config.json',
457
- bytes: 190,
458
- sha256: '4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23',
459
- purpose: 'pooling 事实来源:pooling_mode_mean_tokens=true、cls/max=false、word_embedding_dimension=384;同仓库 modules.json 含 2_Normalize(L2),sentence_bert_config.json max_seq_length=256',
460
- },
461
- graph: {
462
- path: 'onnx/model_quantized.onnx',
463
- opset: 11,
464
- producer: 'onnx.quantize',
465
- producerVersion: '0.1.0',
466
- selfContained: true,
467
- externalData: [],
468
- inputs: [
469
- { name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
470
- { name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
471
- { name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
472
- ],
473
- outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 384] }],
474
- },
475
- files: [
476
- { path: 'config.json', role: 'config', bytes: 650, sha256: '7135149f7cffa1a573466c6e4d8423ed73b62fd2332c575bf738a0d033f70df7' },
477
- { path: 'tokenizer.json', role: 'tokenizer', bytes: 711661, sha256: 'da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0' },
478
- { path: 'tokenizer_config.json', role: 'tokenizer-config', bytes: 366, sha256: '9261e7d79b44c8195c1cada2b453e55b00aeb81e907a6664974b4d7776172ab3' },
479
- { path: 'special_tokens_map.json', role: 'special-tokens', bytes: 125, sha256: 'b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3' },
480
- { path: 'vocab.txt', role: 'vocab', bytes: 231508, sha256: '07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3' },
481
- { path: 'onnx/model_quantized.onnx', role: 'graph', bytes: 22972370, sha256: 'afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1' },
482
- { path: 'README.md', role: 'notice', bytes: 1767, sha256: '63ea99bf681a2e9eda4f6a537d5ed8fda95d1677111656da37e9cfd080c3af02' },
483
- {
484
- path: '1_Pooling/config.json',
485
- role: 'pooling-config',
486
- bytes: 190,
487
- sha256: '4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23',
488
- origin: { provider: 'modelscope', repo: 'sentence-transformers/all-MiniLM-L6-v2', revision: MINIML_POOLING_REVISION },
489
- },
490
- ],
491
- },
492
- {
493
- id: 'multilingual-e5-small',
494
- displayName: 'multilingual-e5-small (int8 ONNX)',
495
- summary: '多语言检索模型(118M 参数、int8 制品 ≈118 MB、384 维,mean pooling + L2)。要 query/passage 前缀:worker 通过 model 字段的角色后缀拿到 role,绝不按文本猜角色。同一份 recall-bench 草稿上 R@1 0.6667 / R@3 1.0000 / MRR@3 0.8182,中文与 BGE 同级、英文 paraphrase 余弦 0.91/0.93(BGE 0.65/0.64);代价是制品比 BGE 大 4.8 倍、推理慢一倍左右。',
496
- languages: ['zh', 'en', 'multilingual'],
497
- tier: 'optional',
498
- availability: 'available',
499
- pendingReasons: [],
500
- parameters: 117505920,
501
- parameterSource: '实测图内 initializer 元素合计 117,505,920(uint8 96,211,584 + int8 21,233,664 + float32 60,672);官方模型页标 118M',
502
- dimension: 384,
503
- // 底座 config.max_position_embeddings=512、tokenizer model_max_length=512、
504
- // sentence_bert_config.json max_seq_length=512 三处一致。
505
- maxTokens: 512,
506
- pooling: 'mean',
507
- normalization: 'l2',
508
- // 非对称前缀 = query 与 document 落在两个不同的读法上,必须靠角色通道区分(§14.4)。
509
- prefixes: { query: 'query: ', document: 'passage: ' },
510
- quantization: {
511
- weights: 'qint8',
512
- scheme: 'dynamic-per-channel',
513
- reduceRange: true,
514
- source: 'quant_config.json(per_channel=true, reduce_range=true, weight_type=QInt8) + 图内 MatMulInteger(72)/DynamicQuantizeLinear(48);75/75 个 int8/uint8 二维权重都存在长度=输出通道数的一维 float32 scale',
515
- },
516
- runtime: { ...PINNED_ONNX_RUNTIME, note: '同一棵受管 ORT 1.31.1 CPU 树真实推理已核实(2026-11-02):XLM-R Unigram 分词可用、384 维、单位范数。' },
517
- license: {
518
- base: { id: 'mit', source: 'ModelScope intfloat/multilingual-e5-small 元数据 License=mit(2026-11-02 只读核对)' },
519
- onnxExport: { id: 'undeclared', source: 'ModelScope Xenova/multilingual-e5-small 的 README front-matter 只有 base_model/library_name,未声明 license(2026-11-02 核对下载字节)' },
520
- },
521
- verification: {
522
- status: 'verified',
523
- method: 'sha256+onnx-header+onnxruntime-inference',
524
- checkedAt: '2026-11-02T08:00:00.000Z',
525
- scope: '逐文件 bytes/sha256 与 ModelScope 文件清单双向一致 + ONNX 图头(opset 11、3 个 int64 输入、last_hidden_state float32[batch,seq,384]、自包含 117,687,936 initializer 字节)+ tokenizer.json Unigram 词表 250002 + 受管 ORT CPU 真实推理与前缀 A/B',
526
- evidence: '2026-11-02 实测(.tmp-model-adapt-20261102):8 个文件 sha256 全部与清单一致;单次编码 6ms、单位范数 1.0、重复编码余弦 1.0;前缀 A/B(33 条可答样本)asym R@1 0.6667/MRR 0.8182/分离度 0.1230、sym-passage 0.6364/0.8030/0.0867、sym-query 0.6667/0.8157/0.1155、无前缀 0.6364/0.8030/0.1139;query: 与 passage: 同文余弦 0.9811',
527
- notVerified: ['huggingface/hf-mirror 上的对应 commit(本机不可达)', 'intfloat 官方仓库里 470 MB fp32 onnx/model.onnx 与本报告使用的 int8 导出数值等价性'],
528
- },
529
- sources: {
530
- modelscope: { repo: 'Xenova/multilingual-e5-small', revision: E5_REVISION, revisionVerified: true, commitTime: E5_COMMIT_TIME },
531
- 'hf-mirror': { repo: 'Xenova/multilingual-e5-small', revision: null, revisionVerified: false, note: 'hf-mirror.com 本机不可达,commit 未核实;不生成 URL' },
532
- huggingface: { repo: 'intfloat/multilingual-e5-small', revision: null, revisionVerified: false, note: 'huggingface.co 本机不可达,commit 未核实;不生成 URL' },
533
- },
534
- witness: {
535
- provider: 'modelscope',
536
- repo: 'intfloat/multilingual-e5-small',
537
- revision: E5_POOLING_REVISION,
538
- path: '1_Pooling/config.json',
539
- bytes: 200,
540
- sha256: '987f7a67a38fa564c849bb5d277c52ab9088a84368fc0be31a354125aebb12a0',
541
- purpose: 'pooling 事实来源:pooling_mode_mean_tokens=true、cls/max=false、word_embedding_dimension=384;同仓库 modules.json 含 2_Normalize(L2),sentence_bert_config.json max_seq_length=512',
542
- },
543
- graph: {
544
- path: 'onnx/model_quantized.onnx',
545
- opset: 11,
546
- producer: 'onnx.quantize',
547
- producerVersion: '0.1.0',
548
- selfContained: true,
549
- externalData: [],
550
- inputs: [
551
- { name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
552
- { name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
553
- { name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
554
- ],
555
- outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 384] }],
556
- },
557
- files: [
558
- { path: 'config.json', role: 'config', bytes: 658, sha256: 'cb99455288675345e1a4f411438d5d0adbba5fbd3a67ea4fb03c015433b996c1' },
559
- { path: 'tokenizer.json', role: 'tokenizer', bytes: 17082730, sha256: '0b44a9d7b51c3c62626640cda0e2c2f70fdacdc25bbbd68038369d14ebdf4c39' },
560
- { path: 'tokenizer_config.json', role: 'tokenizer-config', bytes: 443, sha256: 'a1d6bc8734a6f635dc158508bef000f8e2e5a759c7d92f984b2c86e5ff53425b' },
561
- { path: 'special_tokens_map.json', role: 'special-tokens', bytes: 167, sha256: 'd05497f1da52c5e09554c0cd874037a083e1dc1b9cfd48034d1c717f1afc07a7' },
562
- { path: 'quant_config.json', role: 'quantization', bytes: 674, sha256: '59d175f15264115f18c698d76e443b5d49fc6c8c599911c421405ef4f236e87d' },
563
- { path: 'onnx/model_quantized.onnx', role: 'graph', bytes: 118308185, sha256: 'f80102d3f2a1229f387d3c81909990d8945513e347b0eab049f7de3c6f98c193' },
564
- { path: 'README.md', role: 'notice', bytes: 1077, sha256: '561a19594636657fe033f8b4427a7743b5f6f3a12f16cecc5f286feca0453245' },
565
- {
566
- path: '1_Pooling/config.json',
567
- role: 'pooling-config',
568
- bytes: 200,
569
- sha256: '987f7a67a38fa564c849bb5d277c52ab9088a84368fc0be31a354125aebb12a0',
570
- origin: { provider: 'modelscope', repo: 'intfloat/multilingual-e5-small', revision: E5_POOLING_REVISION },
571
- },
572
- ],
573
- },
574
- qwen3Card('int8'),
575
- qwen3Card('q4f16'),
576
- ]
577
-
578
- /**
579
- * profile fingerprint:任何会改变向量空间的字段(模型/revision/量化/pooling/tokenizer/
580
- * 前缀/维度/分窗)都必须进指纹(§14.8)。
581
- */
582
- export function profileFingerprint(entry) {
583
- const files = Array.isArray(entry?.files) ? entry.files : []
584
- const graphFile = files.find(file => file.role === 'graph') || null
585
- const tokenizerFile = files.find(file => file.role === 'tokenizer') || null
586
- const sources = entry?.sources && typeof entry.sources === 'object' ? entry.sources : {}
587
- const primary = PROVIDER_ORDER.map(id => sources[id]).find(source => source && typeof source.revision === 'string') || null
588
- return sha256Of(canonical({
589
- schema: CATALOG_SCHEMA_VERSION,
590
- id: entry?.id ?? null,
591
- repo: primary?.repo ?? null,
592
- revision: primary?.revision ?? null,
593
- dimension: entry?.dimension ?? null,
594
- maxTokens: entry?.maxTokens ?? null,
595
- pooling: entry?.pooling ?? null,
596
- normalization: entry?.normalization ?? null,
597
- prefixes: entry?.prefixes ?? null,
598
- quantization: entry?.quantization ? { weights: entry.quantization.weights, scheme: entry.quantization.scheme } : null,
599
- graph: graphFile ? graphFile.sha256 : null,
600
- tokenizer: tokenizerFile ? tokenizerFile.sha256 : null,
601
- runtime: entry?.runtime ? { engine: entry.runtime.engine, abi: entry.runtime.abi, version: entry.runtime.version, os: entry.runtime.os, arch: entry.runtime.arch } : null,
602
- files: files.map(({ path, role, bytes, sha256 }) => ({ path, role, bytes, sha256 })).sort((a, b) => a.path.localeCompare(b.path)),
603
- graphProtocol: entry?.graph ?? null,
604
- tokenizerProtocol: entry?.tokenizer ?? null,
605
- preprocessing: entry?.preprocessing ?? null,
606
- windowing: entry?.windowing ?? null,
607
- aggregation: entry?.aggregation ?? null,
608
- protocol: entry?.protocol ?? 'dsh-local-embedding-v1',
609
- }))
610
- }
611
-
612
- const catalog = deepFreeze(rawCatalog.map(entry => ({
613
- ...entry,
614
- schema: CATALOG_SCHEMA_VERSION,
615
- totalBytes: (entry.files || []).reduce((sum, file) => sum + (Number.isFinite(file.bytes) ? file.bytes : 0), 0),
616
- profileFingerprint: profileFingerprint(entry),
617
- })))
618
-
619
- /**
620
- * 把目录条目映射成"向量 profile 描述符"(供 lib/vector-profile.js 之类模块计算/比较指纹)。
621
- * 目的:一处是模型事实(catalog),另一处是激活状态(profile),两边必须用同一份指纹,
622
- * 否则安装/迁移会拿两套不可比的 hash 互相判等。这里只做映射,不读写任何 active 状态。
623
- */
624
- export function toProfileDescriptor(entry) {
625
- const files = Array.isArray(entry?.files) ? entry.files : []
626
- const tokenizerFile = files.find(file => file.role === "tokenizer") || null
627
- const sources = entry?.sources && typeof entry.sources === "object" ? entry.sources : {}
628
- const primary = PROVIDER_ORDER.map(id => sources[id]).find(source => source && typeof source.revision === "string") || null
629
- const runtime = entry?.runtime || {}
630
- return {
631
- id: entry?.id ?? "",
632
- model: entry?.id ?? "",
633
- repo: primary?.repo ?? "",
634
- revision: primary?.revision ?? "",
635
- runtime: runtime.version ? `${runtime.engine}@${runtime.version}` : String(runtime.engine || ""),
636
- tokenizer: tokenizerFile ? tokenizerFile.sha256 : null,
637
- preprocessing: {
638
- pooling: entry?.pooling ?? null,
639
- normalization: entry?.normalization ?? null,
640
- prefixes: entry?.prefixes ?? null,
641
- maxTokens: entry?.maxTokens ?? null,
642
- truncation: "keep-head",
643
- },
644
- pooling: entry?.pooling ?? "",
645
- normalization: entry?.normalization ?? "",
646
- prefixes: entry?.prefixes ?? null,
647
- maxTokens: entry?.maxTokens ?? null,
648
- dimension: entry?.dimension ?? null,
649
- protocol: "dsh-local-embedding-v1",
650
- fingerprint: entry?.profileFingerprint ?? null,
651
- }
652
- }
653
-
654
- /** 只读目录快照;返回冻结数组,调用方改不到目录本体。 */
655
- export function getEmbeddingCatalog() {
656
- return catalog
657
- }
658
-
659
- /** 按稳定 id 取单个模型;未知 id 返回 null(不猜测、不回退默认模型)。 */
660
- export function getEmbeddingModel(id) {
661
- if (typeof id !== 'string') return null
662
- return catalog.find(entry => entry.id === id) || null
663
- }
664
-
665
- /**
666
- * 非对称前缀(query ≠ document)= 同一个模型对两种输入有两种读法,请求通道必须带上角色,
667
- * 否则 worker 只能按文本猜——§14.4 明确不许猜。这里只从前缀派生,不另设开关:前缀本身在
668
- * 指纹里,所以「要不要角色通道」和「这个向量空间是什么」永远来自同一份事实。
669
- */
670
- export function prefixesRequireRole(entry) {
671
- const prefixes = entry?.prefixes
672
- return !!prefixes
673
- && typeof prefixes.query === 'string'
674
- && typeof prefixes.document === 'string'
675
- && prefixes.query !== prefixes.document
676
- }
677
-
678
- // ---------------------------------------------------------------- ONNX 图头
679
-
680
- function readVarint(buffer, offset) {
681
- let result = 0
682
- let shift = 0
683
- let position = offset
684
- for (;;) {
685
- if (position >= buffer.length) throw new Error('truncated varint')
686
- const byte = buffer[position++]
687
- result += (byte & 0x7f) * Math.pow(2, shift)
688
- shift += 7
689
- if ((byte & 0x80) === 0) break
690
- if (shift > 56) throw new Error('varint too long')
691
- }
692
- return [result, position]
693
- }
694
-
695
- function readFields(buffer) {
696
- const fields = []
697
- let position = 0
698
- while (position < buffer.length) {
699
- let key
700
- const keyRead = readVarint(buffer, position)
701
- key = keyRead[0]
702
- position = keyRead[1]
703
- const number = key >>> 3
704
- const wire = key & 7
705
- if (number === 0) throw new Error('invalid field number')
706
- if (wire === 0) {
707
- const valueRead = readVarint(buffer, position)
708
- position = valueRead[1]
709
- fields.push({ number, wire, value: valueRead[0] })
710
- } else if (wire === 2) {
711
- const lengthRead = readVarint(buffer, position)
712
- position = lengthRead[1]
713
- const length = lengthRead[0]
714
- if (position + length > buffer.length) throw new Error('length-prefixed field overruns buffer')
715
- fields.push({ number, wire, value: buffer.subarray(position, position + length) })
716
- position += length
717
- } else if (wire === 5) {
718
- if (position + 4 > buffer.length) throw new Error('truncated fixed32')
719
- fields.push({ number, wire, value: buffer.subarray(position, position + 4) })
720
- position += 4
721
- } else if (wire === 1) {
722
- if (position + 8 > buffer.length) throw new Error('truncated fixed64')
723
- fields.push({ number, wire, value: buffer.subarray(position, position + 8) })
724
- position += 8
725
- } else {
726
- throw new Error(`unsupported wire type ${wire}`)
727
- }
728
- }
729
- return fields
730
- }
731
-
732
- function textOf(field) {
733
- return field && Buffer.isBuffer(field.value) ? field.value.toString('utf8') : ''
734
- }
735
-
736
- function valueInfo(buffer) {
737
- const info = readFields(buffer)
738
- const name = textOf(info.find(field => field.number === 1))
739
- const typeField = info.find(field => field.number === 2)
740
- let dtype = null
741
- let shape = null
742
- if (typeField) {
743
- const tensorType = readFields(typeField.value).find(field => field.number === 1)
744
- if (tensorType) {
745
- const tensor = readFields(tensorType.value)
746
- const elemType = tensor.find(field => field.number === 1)
747
- if (elemType) dtype = ONNX_DTYPES[elemType.value] || `elem_type_${elemType.value}`
748
- const shapeField = tensor.find(field => field.number === 2)
749
- if (shapeField) {
750
- shape = readFields(shapeField.value)
751
- .filter(field => field.number === 1)
752
- .map(dimField => {
753
- const dim = readFields(dimField.value)
754
- const dimValue = dim.find(field => field.number === 1)
755
- if (dimValue) return dimValue.value
756
- const dimParam = dim.find(field => field.number === 2)
757
- return dimParam ? textOf(dimParam) : '?'
758
- })
759
- }
760
- }
761
- }
762
- return { name, dtype, shape }
763
- }
764
-
765
- /**
766
- * 只读解析 ONNX 图头:opset、生产者、输入/输出名与 dtype/形状、initializer 体积、
767
- * 是否引用 external_data。不执行图、不需要 onnxruntime(§14.4 第 1/2 条)。
768
- */
769
- export function readOnnxGraphHeader(buffer) {
770
- if (!Buffer.isBuffer(buffer) || buffer.length < 8) {
771
- const error = new Error('ONNX artifact is empty or too small to be a graph')
772
- error.code = 'EMBEDDING_ONNX_INVALID'
773
- throw error
774
- }
775
- try {
776
- const model = readFields(buffer)
777
- const graphField = model.find(field => field.number === 7)
778
- if (!graphField) {
779
- const error = new Error('ONNX artifact has no graph field')
780
- error.code = 'EMBEDDING_ONNX_INVALID'
781
- throw error
782
- }
783
- const graph = readFields(graphField.value)
784
- const initializers = graph.filter(field => field.number === 5)
785
- let initializerBytes = 0
786
- let externalDataEntries = 0
787
- for (const initializer of initializers) {
788
- const tensor = readFields(initializer.value)
789
- const raw = tensor.find(field => field.number === 9)
790
- if (raw) initializerBytes += raw.value.length
791
- externalDataEntries += tensor.filter(field => field.number === 13).length
792
- }
793
- return {
794
- irVersion: model.find(field => field.number === 1)?.value ?? null,
795
- producer: textOf(model.find(field => field.number === 2)) || null,
796
- producerVersion: textOf(model.find(field => field.number === 3)) || null,
797
- opsets: model.filter(field => field.number === 8).map(field => {
798
- const opset = readFields(field.value)
799
- return { domain: textOf(opset.find(item => item.number === 1)), version: opset.find(item => item.number === 2)?.value ?? null }
800
- }),
801
- inputs: graph.filter(field => field.number === 11).map(field => valueInfo(field.value)),
802
- outputs: graph.filter(field => field.number === 12).map(field => valueInfo(field.value)),
803
- initializerCount: initializers.length,
804
- initializerBytes,
805
- externalDataEntries,
806
- selfContained: externalDataEntries === 0 && initializerBytes > 0,
807
- }
808
- } catch (error) {
809
- if (error?.code === 'EMBEDDING_ONNX_INVALID') throw error
810
- const wrapped = new Error(`cannot parse ONNX graph header: ${error?.message || error}`)
811
- wrapped.code = 'EMBEDDING_ONNX_INVALID'
812
- throw wrapped
813
- }
814
- }
815
-
816
- // ---------------------------------------------------------------- manifest 校验
817
-
818
- function isPlainObject(value) {
819
- return !!value && typeof value === 'object' && !Array.isArray(value)
820
- }
821
-
822
- function isSafeRelativePath(filePath) {
823
- if (typeof filePath !== 'string' || !filePath || filePath.length > 240) return false
824
- if (filePath.includes('\\') || filePath.includes('\u0000')) return false
825
- if (filePath.startsWith('/') || /^[A-Za-z]:/.test(filePath)) return false
826
- return filePath.split('/').every(segment => segment && segment !== '.' && segment !== '..')
827
- }
828
-
829
- /**
830
- * 校验 manifest/目录条目。返回 { ok, errors, warnings }:errors 是"不可下载/不可安装",
831
- * warnings 是"可以下载但必须如实展示"(例如 ONNX 导出未单独声明许可、ORT 版本未实测)。
832
- */
833
- export function validateEmbeddingManifest(manifest) {
834
- const errors = []
835
- const warnings = []
836
- const error = (code, message) => errors.push({ code, message })
837
- const warn = (code, message) => warnings.push({ code, message })
838
-
839
- if (!isPlainObject(manifest)) {
840
- error('MANIFEST_NOT_OBJECT', 'manifest must be a plain object')
841
- return { ok: false, errors, warnings }
842
- }
843
- if (!/^[a-z0-9][a-z0-9._-]{2,63}$/.test(String(manifest.id || ''))) error('ID_INVALID', 'id must be a stable lowercase slug')
844
- if (typeof manifest.displayName !== 'string' || !manifest.displayName.trim()) error('DISPLAY_NAME_MISSING', 'displayName is required')
845
- if (!Array.isArray(manifest.languages) || !manifest.languages.length) error('LANGUAGES_INVALID', 'languages must be a non-empty array')
846
-
847
- const license = manifest.license
848
- if (!isPlainObject(license) || !isPlainObject(license.base) || typeof license.base.id !== 'string' || !license.base.id) {
849
- error('LICENSE_MISSING', 'license.base.id and its source are required (§14.4)')
850
- } else if (license.base.id === 'unverified' && manifest.availability === 'available') {
851
- error('LICENSE_UNVERIFIED', 'an available artifact must have a verified license')
852
- }
853
- if (isPlainObject(license) && isPlainObject(license.onnxExport) && !['declared', 'mit', 'apache-2.0'].includes(license.onnxExport.id)) {
854
- warn('LICENSE_DERIVATIVE_UNDECLARED', 'ONNX export license is not separately declared; show it as undeclared instead of inheriting the code licence')
855
- }
856
-
857
- if (!Number.isFinite(manifest.parameters) || manifest.parameters <= 0) error('PARAMETERS_INVALID', 'parameters must be a positive number')
858
- if (!Number.isInteger(manifest.dimension) || manifest.dimension < 1 || manifest.dimension > 8192) error('DIMENSION_INVALID', 'dimension must be an integer in 1..8192')
859
- if (!(manifest.maxTokens === null || (Number.isInteger(manifest.maxTokens) && manifest.maxTokens >= 32 && manifest.maxTokens <= 32768))) {
860
- error('MAX_TOKENS_INVALID', 'maxTokens must be null (unverified) or an integer in 32..32768')
861
- }
862
- // 'last' = 因果 LM 的最后一个非 pad token(Qwen3-Embedding 这一类);'max' 仍是
863
- // 目录允许声明但执行侧未实现,所以没有任何 available 条目使用它。
864
- if (!['cls', 'mean', 'max', 'last'].includes(manifest.pooling)) error('POOLING_INVALID', 'pooling must be cls/mean/max/last')
865
- if (!['l2', 'none'].includes(manifest.normalization)) error('NORMALIZATION_INVALID', 'normalization must be l2/none')
866
- if (!isPlainObject(manifest.prefixes) || typeof manifest.prefixes.query !== 'string' || typeof manifest.prefixes.document !== 'string') {
867
- error('PREFIXES_INVALID', 'prefixes.query/document must be strings (empty is allowed)')
868
- } else if (manifest.prefixes.query !== manifest.prefixes.document) {
869
- warn('PREFIX_ASYMMETRIC', 'query/document prefixes differ, so this model reads the same text two ways: serving it needs an explicit role channel and role-less requests must be refused')
870
- }
871
-
872
- const sources = manifest.sources
873
- if (!isPlainObject(sources) || !Object.keys(sources).length) error('SOURCES_MISSING', 'sources must map providers to explicit repo/revision')
874
- let pinnedSources = 0
875
- for (const provider of Object.keys(sources || {})) {
876
- const source = sources[provider]
877
- if (!PROVIDERS[provider]) { error('SOURCE_PROVIDER_UNKNOWN', `unknown provider ${provider}`); continue }
878
- if (!isPlainObject(source)) { error('SOURCE_INVALID', `source ${provider} must be an object`); continue }
879
- if (typeof source.repo !== 'string' || !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(source.repo)) {
880
- error('SOURCE_REPO_INVALID', `source ${provider}.repo must be owner/name`)
881
- }
882
- if (source.revision === null) {
883
- warn('SOURCE_REVISION_UNPINNED', `source ${provider} has no pinned revision; no URL may be derived from it`)
884
- } else if (typeof source.revision !== 'string' || !/^[0-9a-f]{40}$/.test(source.revision)) {
885
- error('SOURCE_REVISION_INVALID', `source ${provider}.revision must be a 40-char lowercase commit sha`)
886
- } else {
887
- pinnedSources++
888
- }
889
- }
890
-
891
- if (manifest.availability === 'available') {
892
- if (!pinnedSources) error('SOURCE_NOT_PINNED', 'an available artifact needs at least one provider with an explicit pinned revision')
893
- if (!isPlainObject(manifest.verification) || manifest.verification.status !== 'verified') {
894
- error('VERIFICATION_MISSING', 'an available artifact must carry verification.status = verified')
895
- } else {
896
- if (typeof manifest.verification.method !== 'string' || !manifest.verification.method) error('VERIFICATION_METHOD_MISSING', 'verification.method is required')
897
- if (typeof manifest.verification.checkedAt !== 'string' || Number.isNaN(Date.parse(manifest.verification.checkedAt))) {
898
- error('VERIFICATION_TIME_INVALID', 'verification.checkedAt must be an ISO timestamp')
899
- }
900
- }
901
- } else if (!Array.isArray(manifest.pendingReasons) || !manifest.pendingReasons.length) {
902
- error('PENDING_REASON_MISSING', 'a non-available model must state why it is pending')
903
- }
904
-
905
- const runtime = manifest.runtime
906
- if (!isPlainObject(runtime) || typeof runtime.engine !== 'string' || typeof runtime.abi !== 'string' || typeof runtime.os !== 'string' || typeof runtime.arch !== 'string') {
907
- error('RUNTIME_INVALID', 'runtime.engine/abi/os/arch are required (§14.4)')
908
- } else if (runtime.version === null) {
909
- warn('RUNTIME_VERSION_UNPINNED', 'runtime version is not pinned yet; enabling the profile must stay blocked until ORT is verified')
910
- }
911
-
912
- const files = manifest.files
913
- if (!Array.isArray(files)) {
914
- error('FILES_INVALID', 'files must be an array')
915
- } else {
916
- if (manifest.availability === 'available' && !files.length) error('FILES_MISSING', 'an available artifact must list its files')
917
- const seen = new Set()
918
- for (const file of files) {
919
- if (!isPlainObject(file)) { error('FILE_INVALID', 'each file must be an object'); continue }
920
- if (!isSafeRelativePath(file.path)) error('FILE_PATH_UNSAFE', `unsafe file path: ${JSON.stringify(file.path)}`)
921
- if (seen.has(file.path)) error('FILE_DUPLICATE', `duplicate file path ${file.path}`)
922
- seen.add(file.path)
923
- if (!Number.isInteger(file.bytes) || file.bytes < 0) error('FILE_BYTES_INVALID', `file ${file.path} needs exact bytes`)
924
- if (typeof file.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(file.sha256)) error('FILE_SHA256_INVALID', `file ${file.path} needs a lowercase sha256`)
925
- if (!FILE_ROLES.includes(file.role)) error('FILE_ROLE_INVALID', `file ${file.path} has unknown role ${file.role}`)
926
- if (file.origin !== undefined) {
927
- const origin = file.origin
928
- if (!isPlainObject(origin) || !PROVIDERS[origin.provider] || typeof origin.repo !== 'string' || !/^[0-9a-f]{40}$/.test(String(origin.revision))) {
929
- error('FILE_ORIGIN_INVALID', `file ${file.path} origin must pin provider/repo/revision`)
930
- } else if (origin.providers !== undefined
931
- && (!Array.isArray(origin.providers) || !origin.providers.length
932
- || !origin.providers.every(id => PROVIDERS[id]) || !origin.providers.includes(origin.provider))) {
933
- error('FILE_ORIGIN_INVALID', `file ${file.path} origin.providers must be a non-empty list of known providers that includes origin.provider`)
934
- }
935
- }
936
- }
937
- const graphs = files.filter(file => file.role === 'graph')
938
- if (manifest.availability === 'available' && graphs.length !== 1) error('GRAPH_MISSING', 'exactly one file must have role graph')
939
- for (const graphFile of graphs) if (!String(graphFile.path || '').endsWith('.onnx')) error('GRAPH_NOT_ONNX', `graph file must be .onnx: ${graphFile.path}`)
940
-
941
- // 目录构建器会给每条都补 totalBytes,而手写清单里那个「恰好等于文件之和」的值
942
- // 本来就是同一份事实——只有对不上才是错误。否则加一条条目就得假装没写它。
943
- const actual = files.reduce((sum, file) => sum + (Number.isFinite(file.bytes) ? file.bytes : 0), 0)
944
- if (manifest.totalBytes !== undefined && manifest.totalBytes !== actual) {
945
- error('TOTAL_BYTES_MISMATCH', `totalBytes ${manifest.totalBytes} does not equal the sum of files ${actual}`)
946
- }
947
- }
948
-
949
- const graph = manifest.graph
950
- if (manifest.availability === 'available') {
951
- if (!isPlainObject(graph)) {
952
- error('GRAPH_DESCRIPTOR_MISSING', 'graph descriptor (inputs/outputs/dtype) is required')
953
- } else {
954
- if (!Array.isArray(graph.inputs) || !graph.inputs.length || !Array.isArray(graph.outputs) || !graph.outputs.length) {
955
- error('GRAPH_IO_INVALID', 'graph.inputs/outputs must be non-empty arrays')
956
- }
957
- for (const io of [...(graph.inputs || []), ...(graph.outputs || [])]) {
958
- if (!isPlainObject(io) || typeof io.name !== 'string' || !io.name || typeof io.dtype !== 'string' || !io.dtype) {
959
- error('GRAPH_IO_INVALID', 'each graph input/output needs name and dtype')
960
- }
961
- }
962
- const output = (graph.outputs || [])[0]
963
- const last = Array.isArray(output?.shape) ? output.shape[output.shape.length - 1] : null
964
- if (Number.isInteger(manifest.dimension) && last !== manifest.dimension) {
965
- error('GRAPH_DIMENSION_MISMATCH', `graph output last dim ${last} does not match dimension ${manifest.dimension}`)
966
- }
967
- if (Array.isArray(graph.externalData) && graph.externalData.length && graph.selfContained !== false) {
968
- error('GRAPH_EXTERNAL_DATA_UNDECLARED', 'external data references must be listed and selfContained=false')
969
- }
970
- }
971
- }
972
-
973
- const graphFileInFiles = Array.isArray(files) ? files.find(file => file.role === 'graph') : null
974
- if (isPlainObject(graph) && graphFileInFiles && graph.path !== graphFileInFiles.path) {
975
- error('GRAPH_PATH_MISMATCH', `graph.path ${graph.path} must equal the graph file ${graphFileInFiles.path}`)
976
- }
977
-
978
- if (manifest.profileFingerprint !== undefined) {
979
- const expected = profileFingerprint(manifest)
980
- if (manifest.profileFingerprint !== expected) error('FINGERPRINT_MISMATCH', `profileFingerprint ${manifest.profileFingerprint} does not match the profile ${expected}`)
981
- }
982
-
983
- return { ok: errors.length === 0, errors, warnings }
984
- }
985
-
986
- /**
987
- * 只按 manifest 里显式写明的 repo+revision 生成 URL(§14.4)。默认顺序
988
- * modelscope → hf-mirror → huggingface;没有固定 revision 的来源不生成任何 URL,
989
- * 而是列进 skipped 并写明原因。
990
- */
991
- export function resolveEmbeddingSources(idOrEntry, options = {}) {
992
- const entry = typeof idOrEntry === 'string' ? getEmbeddingModel(idOrEntry) : idOrEntry
993
- if (!isPlainObject(entry)) {
994
- const error = new Error(`unknown embedding model: ${String(idOrEntry)}`)
995
- error.code = 'EMBEDDING_MODEL_UNKNOWN'
996
- throw error
997
- }
998
- const providers = Array.isArray(options.providers) && options.providers.length ? options.providers : PROVIDER_ORDER
999
- const files = Array.isArray(entry.files) ? entry.files : []
1000
- const skipped = []
1001
- const sources = []
1002
-
1003
- for (const providerId of providers) {
1004
- if (!PROVIDERS[providerId]) {
1005
- skipped.push({ provider: providerId, reason: 'provider-unknown' })
1006
- continue
1007
- }
1008
- const source = isPlainObject(entry.sources) ? entry.sources[providerId] : null
1009
- if (!isPlainObject(source)) { skipped.push({ provider: providerId, reason: 'not-mapped' }); continue }
1010
- if (typeof source.revision !== 'string' || !/^[0-9a-f]{40}$/.test(source.revision)) {
1011
- skipped.push({ provider: providerId, reason: 'revision-unpinned', repo: source.repo || null })
1012
- continue
1013
- }
1014
- if (typeof source.repo !== 'string' || !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(source.repo)) {
1015
- skipped.push({ provider: providerId, reason: 'repo-invalid' })
1016
- continue
1017
- }
1018
- const fileUrls = []
1019
- let blocked = null
1020
- for (const file of files) {
1021
- const origin = file.origin
1022
- // 见证制品默认绑死它被核实的那个 provider。镜像站族(hf-mirror / huggingface 是同一
1023
- // commit 的同一份内容)可以由 origin.providers 显式声明多个合法来源,否则换源会被
1024
- // 这条规则整条封掉;无论哪个来源,落盘都要过同一个 sha256。
1025
- const allowedProviders = origin && Array.isArray(origin.providers) && origin.providers.length ? origin.providers : [origin?.provider]
1026
- if (origin && !allowedProviders.includes(providerId)) {
1027
- blocked = { provider: providerId, reason: 'origin-provider-mismatch', path: file.path, originProvider: origin.provider }
1028
- break
1029
- }
1030
- const repo = origin?.repo || source.repo
1031
- const revision = origin?.revision || source.revision
1032
- fileUrls.push({
1033
- path: file.path,
1034
- role: file.role,
1035
- bytes: file.bytes,
1036
- sha256: file.sha256,
1037
- repo,
1038
- revision,
1039
- url: PROVIDERS[providerId].url({ repo, revision, path: file.path }),
1040
- })
1041
- }
1042
- if (blocked) { skipped.push(blocked); continue }
1043
- if (!fileUrls.length) { skipped.push({ provider: providerId, reason: 'no-files' }); continue }
1044
- sources.push({ provider: providerId, label: PROVIDERS[providerId].label, repo: source.repo, revision: source.revision, ready: true, files: fileUrls })
1045
- }
1046
-
1047
- return {
1048
- id: entry.id,
1049
- availability: entry.availability,
1050
- order: [...providers],
1051
- sources,
1052
- skipped,
1053
- primary: sources[0] || null,
1054
- }
1055
- }
1
+ import crypto from 'node:crypto'
2
+
3
+ // §14.4 模型目录:只读、无副作用。目录里的每个事实都带来源;没有核实过的制品一律
4
+ // availability: 'pending' 且 files: []——绝不写猜测的 bytes/SHA-256(§14.4/§14.12)。
5
+ // 这里不做下载、不做安装、不读不写任何 profile/active 状态(那是 embedding-download 与
6
+ // 后续迁移模块的事)。
7
+
8
+ export const CATALOG_SCHEMA_VERSION = 1
9
+
10
+ // 默认来源顺序;只有 manifest 里显式写了 repo+revision 的来源才会生成 URL。
11
+ export const PROVIDER_ORDER = Object.freeze(['modelscope', 'hf-mirror', 'huggingface'])
12
+
13
+ export const PROVIDERS = Object.freeze({
14
+ modelscope: Object.freeze({
15
+ id: 'modelscope',
16
+ label: 'ModelScope',
17
+ url: ({ repo, revision, path }) => `https://modelscope.cn/api/v1/models/${repo}/repo?Revision=${revision}&FilePath=${encodeURIComponent(path)}`,
18
+ }),
19
+ 'hf-mirror': Object.freeze({
20
+ id: 'hf-mirror',
21
+ label: 'hf-mirror',
22
+ url: ({ repo, revision, path }) => `https://hf-mirror.com/${repo}/resolve/${revision}/${encodePath(path)}`,
23
+ }),
24
+ huggingface: Object.freeze({
25
+ id: 'huggingface',
26
+ label: 'Hugging Face',
27
+ url: ({ repo, revision, path }) => `https://huggingface.co/${repo}/resolve/${revision}/${encodePath(path)}`,
28
+ }),
29
+ })
30
+
31
+ export const FILE_ROLES = Object.freeze(['graph', 'config', 'tokenizer', 'tokenizer-config', 'special-tokens', 'vocab', 'quantization', 'pooling-config', 'notice'])
32
+
33
+ const ONNX_DTYPES = Object.freeze({
34
+ 1: 'float32', 2: 'uint8', 3: 'int8', 4: 'uint16', 5: 'int16', 6: 'int32', 7: 'int64',
35
+ 8: 'string', 9: 'bool', 10: 'float16', 11: 'double', 12: 'uint32', 13: 'uint64',
36
+ })
37
+
38
+ function encodePath(filePath) {
39
+ return String(filePath).split('/').map(encodeURIComponent).join('/')
40
+ }
41
+
42
+ function sha256Of(value) {
43
+ return crypto.createHash('sha256').update(value).digest('hex')
44
+ }
45
+
46
+ function canonical(value) {
47
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
48
+ if (value && typeof value === 'object') {
49
+ return `{${Object.keys(value).sort().filter(key => value[key] !== undefined).map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`
50
+ }
51
+ return JSON.stringify(value ?? null)
52
+ }
53
+
54
+ function deepFreeze(value) {
55
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
56
+ Object.freeze(value)
57
+ for (const key of Object.keys(value)) deepFreeze(value[key])
58
+ }
59
+ return value
60
+ }
61
+
62
+ // BGE 制品固定到已核对的 ModelScope revision,逐文件 SHA-256 与下载字节一致。
63
+ // 未独立核对的镜像源不提供已验证的 revision。
64
+ const BGE_REPO = 'Xenova/bge-small-zh-v1.5'
65
+ const BGE_REVISION = '313386ad7ffad360a4870fd1910f8ecaf1a05151'
66
+ const BGE_COMMIT_TIME = '2025-07-22T11:41:37.000Z'
67
+ const BAAI_REPO = 'BAAI/bge-small-zh-v1.5'
68
+ const BAAI_POOLING_REVISION = '8399f11f8da998fe932df2684586c92024219d05'
69
+
70
+ // 核实证据(2026-11-02):两条新条目同样只走 ModelScope 直连(huggingface.co 超时、
71
+ // hf-mirror 重定向回 huggingface.co 后不可达)。revision 取仓库 HEAD commit;逐文件
72
+ // bytes/sha256 取自 ModelScope 文件清单,并与实际下载字节、图头解析结果复核一致。
73
+ const MINIML_REVISION = '5f19c574ce6bbb065d51869c525840f8a975dcc4'
74
+ const MINIML_COMMIT_TIME = '2025-07-22T19:48:27.000Z'
75
+ const MINIML_POOLING_REVISION = '524b52f1d626e9a5a16462e141fc9dffc25d5aeb'
76
+ const E5_REVISION = '252d0dcb679dda2c7b6fd5bbfed15df3c7feaebf'
77
+ const E5_COMMIT_TIME = '2025-07-22T22:49:03.000Z'
78
+ const E5_POOLING_REVISION = 'bdd905ef05181adf3ebbfaac5cd5bd4ed9a58760'
79
+
80
+ // Qwen3-Embedding 的导出制品通过 hf-mirror 核对。两个 provider 固定相同 commit,
81
+ // 逐文件 SHA-256 对应 HF LFS oid;源站未独立核对的范围在 verification 中列明。
82
+ const QWEN_EXPORT_REPO = 'n24q02m/Qwen3-Embedding-0.6B-ONNX'
83
+ const QWEN_REVISION = 'dc873d64d6143f27ad68dadbd1f0d9a4371b994e'
84
+ const QWEN_COMMIT_TIME = '2026-02-18T17:28:18.000Z'
85
+ const QWEN_BASE_REPO = 'Qwen/Qwen3-Embedding-0.6B'
86
+ const QWEN_BASE_REVISION = '97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3'
87
+ // 官方默认 query prompt(config_sentence_transformers.json 的 prompts.query),document 侧
88
+ // 官方明确「No need to add instruction for retrieval documents」→ 非对称,走角色通道。
89
+ const QWEN_QUERY_PROMPT = 'Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:'
90
+ // 两个 provider 都是同一个 commit 的同一份内容;每写一个文件都要过 sha256,所以
91
+ // 允许见证制品在任一 provider 上取,而不是把源站整条封掉。
92
+ const QWEN_MIRROR_PROVIDERS = ['hf-mirror', 'huggingface']
93
+
94
+ // 三个模型 pin 的是同一棵受管 ONNX 运行时树:安装事实只写一次,条目里展开复用。
95
+ // 指纹只看 engine/abi/version/os/arch 五个字段(§14.8),note 不参与,所以共享常量
96
+ // 不会把某个模型的运行时事实悄悄改成另一个模型的。
97
+ const PINNED_ONNX_RUNTIME = Object.freeze({
98
+ engine: 'onnxruntime-node',
99
+ version: '1.31.1',
100
+ abi: 'napi-v6',
101
+ os: 'win32',
102
+ arch: 'x64',
103
+ verified: true,
104
+ tokenizer: { name: '@huggingface/tokenizers', version: '0.2.0', license: 'Apache-2.0', sha256: 'f6b9849b58de625c4fd79583242dd4506914b92082f9af17719d39416658ef24' },
105
+ packages: [
106
+ { name: 'onnxruntime-node', version: '1.31.1', license: 'MIT', sha256: '41aedb3e877786245ab4dc0f533cda63f7d971b5c5fec171eafca9fb9572a8d5' },
107
+ { name: 'onnxruntime-common', version: '1.31.1', license: 'MIT', sha256: 'c8e59240260cd3d230f1417765e0dbe098323ef65a5785991059de1bd5d7cde0' },
108
+ ],
109
+ // 受管安装使用固定版本与逐文件校验值,运行时安装树只包含声明的制品。
110
+ // 只允许从这些 URL 下载并按下面的 hash 校验;没有 hash 或没有该平台原生库一律拒绝安装。
111
+ install: {
112
+ scope: 'per-user-managed',
113
+ layout: 'node_modules',
114
+ postinstall: 'never-run',
115
+ verifiedAt: '2026-10-30T03:45:00.000Z',
116
+ verifiedOn: 'win32-x64',
117
+ platforms: {
118
+ 'win32-x64': 'smoke-verified',
119
+ 'win32-arm64': 'artifact-pinned',
120
+ 'linux-x64': 'artifact-pinned',
121
+ 'linux-arm64': 'artifact-pinned',
122
+ 'darwin-arm64': 'artifact-pinned',
123
+ },
124
+ evidence: 'npm tarball sha256 与 registry integrity 双向一致;解包最小树真实推理通过;原生库逐文件 sha256 取自同一棵已核实树',
125
+ },
126
+ // Every source serves the same npm tarball; the installer still verifies the pinned
127
+ // bytes+sha256 after download, so a mirror can never change the runtime tree.
128
+ artifacts: [
129
+ {
130
+ name: 'onnxruntime-node', version: '1.31.1', license: 'MIT',
131
+ url: 'https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz',
132
+ sources: [
133
+ { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz' },
134
+ { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/onnxruntime-node/-/onnxruntime-node-1.31.1.tgz' },
135
+ ],
136
+ bytes: 115391311,
137
+ sha256: 'd7a3de2b1bba92614abc74af909cc0ba4f4dd5347735418794edeb58cfef2d22',
138
+ integrity: 'sha512-ijnSghbDHVWaQ2nDPmVccPlCHI8kH1Mx1aJ4a/qzRP16bBcVs4E3EqZQKZCkhWnbqN1tuQWxagimFtDpbPYYQw==',
139
+ extract: ['package.json', 'README.md', 'dist', 'lib', 'bin/napi-v6/<platform>'],
140
+ },
141
+ {
142
+ name: 'onnxruntime-common', version: '1.31.1', license: 'MIT',
143
+ url: 'https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz',
144
+ sources: [
145
+ { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz' },
146
+ { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/onnxruntime-common/-/onnxruntime-common-1.31.1.tgz' },
147
+ ],
148
+ bytes: 72322,
149
+ sha256: '967acac0c2a22122461e526aeda07305da7289d94f276920d8a6919483f07bfc',
150
+ integrity: 'sha512-F+nnYNiQtmNJ95V6R/isBJqiVpdANCrsMEg1OaF+Bkbl3GAtzWLR7Ng17Ld0QtYtYJyotOHPJzOQn1Y6PLZjpg==',
151
+ extract: ['package.json', 'README.md', 'dist', 'lib'],
152
+ },
153
+ {
154
+ name: '@huggingface/tokenizers', version: '0.2.0', license: 'Apache-2.0',
155
+ url: 'https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz',
156
+ sources: [
157
+ { id: 'npmjs', label: 'npmjs', url: 'https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz' },
158
+ { id: 'npmmirror', label: 'npmmirror(国内镜像)', url: 'https://registry.npmmirror.com/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz' },
159
+ ],
160
+ bytes: 87011,
161
+ sha256: '2800014c83b8186b2e4210c20672f1fb65a12cef85d7e95e0f2003e022611b4a',
162
+ integrity: 'sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==',
163
+ extract: ['package.json', 'README.md', 'LICENSE', 'dist', 'types'],
164
+ },
165
+ ],
166
+ // 解包后的 package.json 事实(字节数 + sha256):用于确认解出来的就是 pin 住的版本。
167
+ packageFiles: [
168
+ { package: 'onnxruntime-node', bytes: 1593, sha256: '41aedb3e877786245ab4dc0f533cda63f7d971b5c5fec171eafca9fb9572a8d5' },
169
+ { package: 'onnxruntime-common', bytes: 977, sha256: 'c8e59240260cd3d230f1417765e0dbe098323ef65a5785991059de1bd5d7cde0' },
170
+ { package: '@huggingface/tokenizers', bytes: 1965, sha256: 'f6b9849b58de625c4fd79583242dd4506914b92082f9af17719d39416658ef24' },
171
+ ],
172
+ // 判分/加载必需的原生库逐文件 hash。没有列出原生库的平台不得安装(不允许猜)。
173
+ native: {
174
+ 'win32-x64': [
175
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/x64/onnxruntime_binding.node', bytes: 358200, sha256: '8d9f996ff7dcc60c4899aa87aa7abe07d806f9c314882f44a001d0fd8a23d16f' },
176
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/x64/onnxruntime.dll', bytes: 31736672, sha256: 'beb6e1edba0e74c132453fe4df113da2ea2b99ef8ea7dfc25696a872efd11c45' },
177
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/x64/DirectML.dll', bytes: 18527544, sha256: 'd16be72fa002dd610cca93e376f0ef44865dfce43de4b7bf9738af22534f7a9d' },
178
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/x64/dxcompiler.dll', bytes: 17986400, sha256: '430eed027979399769a325b60319aca4e4afa4daebe475d3c763dcf2a0190a72' },
179
+ ],
180
+ 'win32-arm64': [
181
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/arm64/onnxruntime_binding.node', bytes: 504160, sha256: '6f34d4635793371c85e5260dbdc0864c2ef62ccfcb1f439afa3501ba6f8d530d' },
182
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/arm64/onnxruntime.dll', bytes: 32835936, sha256: '14d1cd398fa5bc8b5c61bdfba899f17b40550012ec2884955ce656a5d8a8ff77' },
183
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/arm64/DirectML.dll', bytes: 18444600, sha256: '4bb0639eb23a02de2c5f1eddd117f13330819f55b556e8c75068b68ad1a3516e' },
184
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/win32/arm64/dxcompiler.dll', bytes: 22285624, sha256: '4a77bcadf4d437ad50d10517bb0b4a5a4c2fc84b1fde4d1cf5a5abe9e2dce431' },
185
+ ],
186
+ 'linux-x64': [
187
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/linux/x64/onnxruntime_binding.node', bytes: 519712, sha256: 'e3a108803b8bd33c8e9691b52921c37bede7a6886251aa41219f053d268ee231' },
188
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/linux/x64/libonnxruntime.so.1', bytes: 47552704, sha256: 'f19a4da48c4c65e0cdccff82354482f657fa91a3455b66174195b94ca55b0e6f' },
189
+ ],
190
+ 'linux-arm64': [
191
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/linux/arm64/onnxruntime_binding.node', bytes: 551752, sha256: '5d943f6bf8f65c40213bac636f19bcb227ee1d188417c4b6a6f70062579cfb84' },
192
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/linux/arm64/libonnxruntime.so.1', bytes: 25266408, sha256: '152fb7d2f4f06acc5a38627fbca3e56ba2a9b984cb060d2ac500ac272afbb9ba' },
193
+ ],
194
+ 'darwin-arm64': [
195
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/darwin/arm64/onnxruntime_binding.node', bytes: 323512, sha256: '95ab5698fbcb34d035ea98266156ad5a06b76d0ee739ea42d660df6901df390a' },
196
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/darwin/arm64/libonnxruntime.1.dylib', bytes: 45331560, sha256: '9a362365243b56da98a2ad65128a32d6f8066d1f39ce697e0fce997adf0586dc' },
197
+ { path: 'node_modules/onnxruntime-node/bin/napi-v6/darwin/arm64/libonnxruntime.1.31.1.dylib', bytes: 45331560, sha256: '9a362365243b56da98a2ad65128a32d6f8066d1f39ce697e0fce997adf0586dc' },
198
+ ],
199
+ },
200
+ })
201
+
202
+ // Qwen3-Embedding 的两种量化各是一张卡片:int8 与 int4+fp16 的权重存储方式不同,
203
+ // 落出来的向量空间也不同(§14.8 里 quantization 进指纹),所以必须分条目、分 DB,
204
+ // 而不是一个条目两个文件让用户以为可以混用。
205
+ function qwen3Card(variant) {
206
+ const int8 = variant === 'int8'
207
+ const graphPath = int8 ? 'onnx/model_quantized.onnx' : 'onnx/model_q4f16.onnx'
208
+ const graphBytes = int8 ? 600223343 : 541820311
209
+ const graphSha = int8
210
+ ? '76dc4f417876e48b2fae7f325cb052f46099c890e6a7c1b60f91ff5027d751ef'
211
+ : '2db238eb6122ce336c9de62df9c08113a4da7f41514298885a379451e952178e'
212
+ const activation = int8 ? 'float32' : 'float16'
213
+ return {
214
+ id: `qwen3-embedding-0.6b-${variant}`,
215
+ displayName: `Qwen3-Embedding-0.6B (${variant} ONNX)`,
216
+ summary: int8
217
+ ? 'Qwen3 0.6B 多语言检索模型的 int8 ONNX 制品(1024 维、last-token pooling + L2)。查询侧使用 Instruct 前缀,需要显式区分查询与文档角色;CPU 推理成本随输入长度增加。'
218
+ : '同一 0.6B 模型的 int4 ONNX 变体,使用 float16 激活与 com.microsoft.MatMulNBits(block_size=128)。制品较小,依赖对应贡献算子;较小制品不保证更低推理延迟。向量空间与 int8 变体不同,切换需要重建。',
219
+ languages: ['zh', 'en', 'multilingual'],
220
+ tier: int8 ? 'preferred' : 'optional',
221
+ availability: 'available',
222
+ pendingReasons: [],
223
+ parameters: int8 ? 595776975 : 599217221,
224
+ parameterSource: int8
225
+ ? '图内 initializer 元素合计 595,776,975(int8 440,402,116 + uint8 155,309,057 + float32 65,802,不含 int64/bool 位置与掩码表);官方模型卡 0.6B'
226
+ : '图内 initializer 元素合计 599,217,221(float16 158,815,301 + int4 按 uint8 打包 ×2 = 440,401,920);与 int8 变体同一份 0.6B 权重,存储方式不同所以计数略有出入',
227
+ dimension: 1024,
228
+ // 制品侧 config.max_position_embeddings=32768(tokenizer model_max_length 131072),
229
+ // 使用 4096 token 窗口限制 CPU 推理成本。分窗配置属于向量空间指纹,
230
+ // 调整后需要重建,不能直接混用已有向量。
231
+ maxTokens: 4096,
232
+ // 因果 LM:官方 1_Pooling pooling_mode_lasttoken=true,其余全 false。
233
+ pooling: 'last',
234
+ normalization: 'l2',
235
+ prefixes: { query: QWEN_QUERY_PROMPT, document: '' },
236
+ quantization: int8
237
+ ? {
238
+ weights: 'qint8',
239
+ scheme: 'dynamic-per-tensor',
240
+ reduceRange: null,
241
+ source: '导出仓库 README 声明 onnxruntime.quantization.quantize_dynamic(QInt8);图侧核实 196/196 个 MatMulInteger 的 scale/zero_point 都是 rank-0 标量、per-channel scale 向量 0 个,另有 DynamicQuantizeLinear 112 个 → 激活动态量化 + 权重 per-tensor,和 BGE/MiniLM/e5 的 per-channel 不是同一个空间',
242
+ }
243
+ : {
244
+ weights: 'uint4-nbits',
245
+ scheme: 'block-wise-int4-block128-fp16-activations',
246
+ reduceRange: null,
247
+ source: 'README 声明 MatMulNBitsQuantizer(block_size=128, symmetric) + FP16 cast;图侧核实 com.microsoft.MatMulNBits 196 个、打包权重形状 [out, blocks, 64](blocks×128 = 输入维、64 字节 = 128 个 nibble),其余 initializer 为 float16;opset 21 + com.microsoft v1',
248
+ },
249
+ runtime: {
250
+ ...PINNED_ONNX_RUNTIME,
251
+ note: int8
252
+ ? '核对范围:win32-x64、受管 ORT 1.31.1 CPU 的模型加载、1024 维输出、范数与重复编码一致性。'
253
+ : '核对范围:win32-x64、受管 ORT 1.31.1 CPU 的模型加载与推理;需要 com.microsoft 贡献算子域。',
254
+ },
255
+ license: {
256
+ base: { id: 'apache-2.0', source: 'hf-mirror 元数据 Qwen/Qwen3-Embedding-0.6B cardData.license = apache-2.0(2026-11-02 只读核对)' },
257
+ onnxExport: { id: 'apache-2.0', source: 'n24q02m/Qwen3-Embedding-0.6B-ONNX 的 README front-matter license: apache-2.0(2026-11-02 核对下载字节)' },
258
+ },
259
+ verification: {
260
+ status: 'verified',
261
+ method: 'sha256+onnx-header+onnxruntime-inference',
262
+ checkedAt: '2026-11-02T08:55:00.000Z',
263
+ scope: `逐文件 bytes/sha256 与 HF 文件树声明一致(LFS 制品直接对 lfs.oid 的 sha256)+ ONNX 图头(opset 21、input_ids/attention_mask 两个 int64 输入、last_hidden_state ${activation}[1,sequence_length,1024]、自包含、固定 batch=1 导出)+ 基座 1_Pooling/2_Normalize 的 pooling 与归一化事实 + 受管 ORT CPU 真实推理与延迟测量`,
264
+ evidence: int8
265
+ ? 'int8 图文件的大小与 SHA-256 对应固定 revision 的 HF LFS 清单;记录覆盖 ONNX 图头、受管 ORT CPU 推理、范数与重复编码一致性。该记录不构成检索质量评估。'
266
+ : 'q4f16 图文件的大小与 SHA-256 对应固定 revision 的 HF LFS 清单;记录覆盖 ONNX 图头、受管 ORT CPU 推理、范数与重复编码一致性。未证明与 int8 变体具有相同向量空间。',
267
+ notVerified: [
268
+ 'modelscope 上没有该导出仓库与基座仓库的对应条目(只读核对 record not found)',
269
+ `huggingface.co 源站未独立核对;同一 commit 的文件只通过 hf-mirror 做过字节复核`,
270
+ '与 PyTorch 基座(float32/bfloat16)向量的数值等价性——本包不做参考实现比对,只保证同一制品重复编码一致',
271
+ ],
272
+ },
273
+ sources: {
274
+ 'hf-mirror': { repo: QWEN_EXPORT_REPO, revision: QWEN_REVISION, revisionVerified: true, commitTime: QWEN_COMMIT_TIME },
275
+ huggingface: { repo: QWEN_EXPORT_REPO, revision: QWEN_REVISION, revisionVerified: false, commitTime: QWEN_COMMIT_TIME, note: '与 hf-mirror 固定同一个 commit;源站未独立复核,下载仍需逐文件 SHA-256 校验' },
276
+ },
277
+ witness: {
278
+ provider: 'hf-mirror',
279
+ repo: QWEN_BASE_REPO,
280
+ revision: QWEN_BASE_REVISION,
281
+ path: '1_Pooling/config.json',
282
+ bytes: 313,
283
+ sha256: '37bf193fa101f19101bfad9c31d3eb0f786e247b7b1e5cb7f007d730eed1ddbd',
284
+ purpose: 'pooling 事实来源:pooling_mode_lasttoken=true 且 cls/mean/max/weightedmean 全 false、word_embedding_dimension=1024、include_prompt=true;同仓库 modules.json 含 2_Normalize(L2),config_sentence_transformers.json 的 prompts.query 给出官方 Instruct 前缀且 prompts.document 为空',
285
+ },
286
+ graph: {
287
+ path: graphPath,
288
+ opset: 21,
289
+ producer: int8 ? 'onnx.quantize' : 'pytorch',
290
+ producerVersion: int8 ? '0.1.0' : '2.10.0+cu128',
291
+ selfContained: true,
292
+ externalData: [],
293
+ inputs: [
294
+ { name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
295
+ { name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
296
+ ],
297
+ // batch 维是字面量 1(导出时固定),所以一次只能喂一行。
298
+ outputs: [{ name: 'last_hidden_state', dtype: activation, shape: [1, 'sequence_length', 1024] }],
299
+ },
300
+ files: [
301
+ { path: 'config.json', role: 'config', bytes: 1416, sha256: '88014d4dd5f874bf4050a57e76029ffdb42bead2c0c9253b4eb21bc65da8a5d9' },
302
+ { path: 'tokenizer.json', role: 'tokenizer', bytes: 11423701, sha256: '93623af029cdc69b87f2864d3b2cc2424fdf16684f15e139b5b9d08ec34ced91' },
303
+ { path: 'tokenizer_config.json', role: 'tokenizer-config', bytes: 349, sha256: 'bc3e7cb4dad833a185d4bfbb4880562dc9b0cb101c47b8985078122a122d553a' },
304
+ { path: graphPath, role: 'graph', bytes: graphBytes, sha256: graphSha },
305
+ { path: 'README.md', role: 'notice', bytes: 2226, sha256: 'a5b65f56517933cc8b6724293b73e7123531569df121ae3ebe597dd8dd571a3f' },
306
+ {
307
+ path: '1_Pooling/config.json',
308
+ role: 'pooling-config',
309
+ bytes: 313,
310
+ sha256: '37bf193fa101f19101bfad9c31d3eb0f786e247b7b1e5cb7f007d730eed1ddbd',
311
+ origin: {
312
+ provider: 'hf-mirror',
313
+ providers: QWEN_MIRROR_PROVIDERS,
314
+ repo: QWEN_BASE_REPO,
315
+ revision: QWEN_BASE_REVISION,
316
+ },
317
+ },
318
+ ],
319
+ }
320
+ }
321
+
322
+ const rawCatalog = [
323
+ {
324
+ id: 'bge-small-zh-v1.5-int8',
325
+ displayName: 'BGE small zh v1.5 (int8 ONNX)',
326
+ summary: '中文优先的检索小模型;BGE v1.5 检索无需 instruction,CLS pooling + L2 归一化,512 维。',
327
+ languages: ['zh', 'en'],
328
+ tier: 'preferred',
329
+ availability: 'available',
330
+ pendingReasons: [],
331
+ parameters: 24000000,
332
+ parameterSource: 'BAAI 官方模型页 24M(docs/local-vector-construction.md §14.4 引用)',
333
+ dimension: 512,
334
+ maxTokens: 512,
335
+ pooling: 'cls',
336
+ normalization: 'l2',
337
+ prefixes: { query: '', document: '' },
338
+ quantization: {
339
+ weights: 'qint8',
340
+ scheme: 'dynamic-per-channel',
341
+ reduceRange: true,
342
+ source: 'quantize_config.json(per_channel=true, reduce_range=true, weight_type=QInt8) + 图内 MatMulInteger/DynamicQuantizeLinear',
343
+ },
344
+ runtime: {
345
+ ...PINNED_ONNX_RUNTIME,
346
+ note: '隔离目录真实 ORT CPU 加载/推理 smoke 已核实;仅允许固定版本,不隐式下载。',
347
+ },
348
+ license: {
349
+ base: { id: 'mit', source: 'ModelScope BAAI/bge-small-zh-v1.5 的 License 字段 = mit(2026-10-30 只读核对)' },
350
+ onnxExport: { id: 'undeclared', source: 'ModelScope Xenova/bge-small-zh-v1.5 的 License 字段为空,ONNX 导出未单独声明许可(2026-10-30 核对)' },
351
+ },
352
+ verification: {
353
+ status: 'verified',
354
+ method: 'sha256+onnx-header',
355
+ checkedAt: '2026-10-30T00:20:00.000Z',
356
+ scope: '逐文件 bytes/sha256 复核 + ONNX 图头(opset/输入输出/dtype/形状/自包含)+ config/tokenizer 解析',
357
+ evidence: '制品文件的 SHA-256 已与固定 revision 的 ModelScope 清单核对;范围见 scope。',
358
+ notVerified: ['huggingface/hf-mirror 上的对应 commit'],
359
+ },
360
+ sources: {
361
+ modelscope: { repo: BGE_REPO, revision: BGE_REVISION, revisionVerified: true, commitTime: BGE_COMMIT_TIME },
362
+ 'hf-mirror': { repo: BGE_REPO, revision: null, revisionVerified: false, note: '对应来源的 commit 未核实;不生成 URL' },
363
+ huggingface: { repo: BGE_REPO, revision: null, revisionVerified: false, note: '对应来源的 commit 未核实;不生成 URL' },
364
+ },
365
+ witness: {
366
+ provider: 'modelscope',
367
+ repo: BAAI_REPO,
368
+ revision: BAAI_POOLING_REVISION,
369
+ path: '1_Pooling/config.json',
370
+ bytes: 190,
371
+ sha256: 'aaa8861589f80c961a03cc86c7eeaef7605c1676b9ab55329d33a304738769c6',
372
+ purpose: 'pooling 事实来源:pooling_mode_cls_token=true、word_embedding_dimension=512',
373
+ },
374
+ graph: {
375
+ path: 'onnx/model_quantized.onnx',
376
+ opset: 11,
377
+ producer: 'onnx.quantize',
378
+ producerVersion: '0.1.0',
379
+ selfContained: true,
380
+ externalData: [],
381
+ inputs: [
382
+ { name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
383
+ { name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
384
+ { name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
385
+ ],
386
+ outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 512] }],
387
+ },
388
+ files: [
389
+ { path: 'config.json', role: 'config', bytes: 716, sha256: 'd4193ead3a810fd694fa8a31d7fc72fbaebc0668b603e398734bf2f6538ff42f' },
390
+ { path: 'tokenizer.json', role: 'tokenizer', bytes: 439125, sha256: '48cea5d44424912a6fd1ea647bf4fe50b55ab8b1e5879c3275f80e339e8fae26' },
391
+ { path: 'tokenizer_config.json', role: 'tokenizer-config', bytes: 367, sha256: 'e6f3b96db926a37d4039995fbf5ad17de158dfb8f6343d607e4dbaad18d75f5a' },
392
+ { path: 'special_tokens_map.json', role: 'special-tokens', bytes: 125, sha256: 'b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3' },
393
+ { path: 'vocab.txt', role: 'vocab', bytes: 109540, sha256: '45bbac6b341c319adc98a532532882e91a9cefc0329aa57bac9ae761c27b291c' },
394
+ { path: 'onnx/model_quantized.onnx', role: 'graph', bytes: 24010842, sha256: '15b717c382bcb518ba457b93ea6850ede7f4f1cd8937454aa06972366cd19bcc' },
395
+ { path: 'quantize_config.json', role: 'quantization', bytes: 674, sha256: '2cc488b20fa05fe86aba2fdc2be44d24827e11e2b7c7a0753d1427da6797b46f' },
396
+ { path: 'README.md', role: 'notice', bytes: 1057, sha256: 'cb22054df1a98f7ee9d5b281d023e67c27cc316e1733baf03fc994d95c3048ab' },
397
+ {
398
+ path: '1_Pooling/config.json',
399
+ role: 'pooling-config',
400
+ bytes: 190,
401
+ sha256: 'aaa8861589f80c961a03cc86c7eeaef7605c1676b9ab55329d33a304738769c6',
402
+ origin: { provider: 'modelscope', repo: BAAI_REPO, revision: BAAI_POOLING_REVISION },
403
+ },
404
+ ],
405
+ },
406
+ {
407
+ id: 'all-minilm-l6-v2-int8',
408
+ displayName: 'all-MiniLM-L6-v2 (int8 ONNX)',
409
+ summary: '英文句子相似度小模型(384 维,mean pooling + L2),适合英文语料与较小制品需求。中文检索效果需要按目标语料单独评估。',
410
+ languages: ['en'],
411
+ tier: 'optional',
412
+ availability: 'available',
413
+ pendingReasons: [],
414
+ parameters: 22565376,
415
+ parameterSource: 'ONNX 图内 initializer 元素合计 22,565,376(uint8 11,917,824 + int8 10,616,832 + float32 30,720);官方模型页标 22.7M',
416
+ dimension: 384,
417
+ // 底座 config.max_position_embeddings=512、tokenizer model_max_length=512、图输出第三维=384
418
+ // 三处一致;sentence_bert_config.json 的 max_seq_length=256 只是 SB wrapper 的窗口。
419
+ // 分窗按制品本身取 512,和 BGE 同窗,切换模型不会顺带改分窗口径。
420
+ maxTokens: 512,
421
+ pooling: 'mean',
422
+ normalization: 'l2',
423
+ prefixes: { query: '', document: '' },
424
+ quantization: {
425
+ weights: 'qint8',
426
+ scheme: 'dynamic-per-channel',
427
+ reduceRange: null,
428
+ source: '仓库未随附 quant_config.json;方案取自图本身:MatMulInteger(36)+DynamicQuantizeLinear(24),39/39 个 int8/uint8 二维权重都存在长度=输出通道数的一维 float32 scale,长度 1 的标量 scale=0',
429
+ },
430
+ runtime: { ...PINNED_ONNX_RUNTIME, note: '同一棵受管 ORT 1.31.1 CPU 树真实推理已核实(2026-11-02):384 维、单位范数、重复编码余弦 1.0。' },
431
+ license: {
432
+ base: { id: 'apache-2.0', source: 'ModelScope Xenova/all-MiniLM-L6-v2 元数据 License=apache-2.0(2026-11-02 只读核对)' },
433
+ onnxExport: { id: 'apache-2.0', source: '导出仓库 README front-matter license: apache-2.0(2026-11-02 核对下载字节)' },
434
+ },
435
+ verification: {
436
+ status: 'verified',
437
+ method: 'sha256+onnx-header+onnxruntime-inference',
438
+ checkedAt: '2026-11-02T08:00:00.000Z',
439
+ scope: '逐文件 bytes/sha256 与 ModelScope 文件清单双向一致 + ONNX 图头(opset 11、3 个 int64 输入、last_hidden_state float32[batch,seq,384]、自包含 22,661,632 initializer 字节)+ vocab.txt 行数 30522=config.vocab_size + 受管 ORT CPU 真实推理',
440
+ evidence: '固定 revision 制品已完成逐文件 SHA-256、ONNX 图头与受管 ORT CPU 推理核对;记录覆盖范数、重复编码一致性和长文截断,不构成检索质量评估。',
441
+ notVerified: ['huggingface/hf-mirror 上的对应 commit'],
442
+ },
443
+ sources: {
444
+ modelscope: { repo: 'Xenova/all-MiniLM-L6-v2', revision: MINIML_REVISION, revisionVerified: true, commitTime: MINIML_COMMIT_TIME },
445
+ 'hf-mirror': { repo: 'Xenova/all-MiniLM-L6-v2', revision: null, revisionVerified: false, note: '对应来源的 commit 未核实;不生成 URL' },
446
+ huggingface: { repo: 'sentence-transformers/all-MiniLM-L6-v2', revision: null, revisionVerified: false, note: '对应来源的 commit 未核实;不生成 URL' },
447
+ },
448
+ witness: {
449
+ provider: 'modelscope',
450
+ repo: 'sentence-transformers/all-MiniLM-L6-v2',
451
+ revision: MINIML_POOLING_REVISION,
452
+ path: '1_Pooling/config.json',
453
+ bytes: 190,
454
+ sha256: '4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23',
455
+ purpose: 'pooling 事实来源:pooling_mode_mean_tokens=true、cls/max=false、word_embedding_dimension=384;同仓库 modules.json 含 2_Normalize(L2),sentence_bert_config.json max_seq_length=256',
456
+ },
457
+ graph: {
458
+ path: 'onnx/model_quantized.onnx',
459
+ opset: 11,
460
+ producer: 'onnx.quantize',
461
+ producerVersion: '0.1.0',
462
+ selfContained: true,
463
+ externalData: [],
464
+ inputs: [
465
+ { name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
466
+ { name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
467
+ { name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
468
+ ],
469
+ outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 384] }],
470
+ },
471
+ files: [
472
+ { path: 'config.json', role: 'config', bytes: 650, sha256: '7135149f7cffa1a573466c6e4d8423ed73b62fd2332c575bf738a0d033f70df7' },
473
+ { path: 'tokenizer.json', role: 'tokenizer', bytes: 711661, sha256: 'da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0' },
474
+ { path: 'tokenizer_config.json', role: 'tokenizer-config', bytes: 366, sha256: '9261e7d79b44c8195c1cada2b453e55b00aeb81e907a6664974b4d7776172ab3' },
475
+ { path: 'special_tokens_map.json', role: 'special-tokens', bytes: 125, sha256: 'b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3' },
476
+ { path: 'vocab.txt', role: 'vocab', bytes: 231508, sha256: '07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3' },
477
+ { path: 'onnx/model_quantized.onnx', role: 'graph', bytes: 22972370, sha256: 'afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1' },
478
+ { path: 'README.md', role: 'notice', bytes: 1767, sha256: '63ea99bf681a2e9eda4f6a537d5ed8fda95d1677111656da37e9cfd080c3af02' },
479
+ {
480
+ path: '1_Pooling/config.json',
481
+ role: 'pooling-config',
482
+ bytes: 190,
483
+ sha256: '4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23',
484
+ origin: { provider: 'modelscope', repo: 'sentence-transformers/all-MiniLM-L6-v2', revision: MINIML_POOLING_REVISION },
485
+ },
486
+ ],
487
+ },
488
+ {
489
+ id: 'multilingual-e5-small',
490
+ displayName: 'multilingual-e5-small (int8 ONNX)',
491
+ summary: '多语言检索模型(118M 参数、int8 制品约 118 MB、384 维,mean pooling + L2)。需要 query/passage 前缀;worker 根据 model 字段的角色后缀区分查询与文档。检索效果应按目标语料评估。',
492
+ languages: ['zh', 'en', 'multilingual'],
493
+ tier: 'optional',
494
+ availability: 'available',
495
+ pendingReasons: [],
496
+ parameters: 117505920,
497
+ parameterSource: 'ONNX 图内 initializer 元素合计 117,505,920(uint8 96,211,584 + int8 21,233,664 + float32 60,672);官方模型页标 118M',
498
+ dimension: 384,
499
+ // 底座 config.max_position_embeddings=512、tokenizer model_max_length=512、
500
+ // sentence_bert_config.json max_seq_length=512 三处一致。
501
+ maxTokens: 512,
502
+ pooling: 'mean',
503
+ normalization: 'l2',
504
+ // 非对称前缀 = query 与 document 落在两个不同的读法上,必须靠角色通道区分(§14.4)。
505
+ prefixes: { query: 'query: ', document: 'passage: ' },
506
+ quantization: {
507
+ weights: 'qint8',
508
+ scheme: 'dynamic-per-channel',
509
+ reduceRange: true,
510
+ source: 'quant_config.json(per_channel=true, reduce_range=true, weight_type=QInt8) + 图内 MatMulInteger(72)/DynamicQuantizeLinear(48);75/75 个 int8/uint8 二维权重都存在长度=输出通道数的一维 float32 scale',
511
+ },
512
+ runtime: { ...PINNED_ONNX_RUNTIME, note: '同一棵受管 ORT 1.31.1 CPU 树真实推理已核实(2026-11-02):XLM-R Unigram 分词可用、384 维、单位范数。' },
513
+ license: {
514
+ base: { id: 'mit', source: 'ModelScope intfloat/multilingual-e5-small 元数据 License=mit(2026-11-02 只读核对)' },
515
+ onnxExport: { id: 'undeclared', source: 'ModelScope Xenova/multilingual-e5-small 的 README front-matter 只有 base_model/library_name,未声明 license(2026-11-02 核对下载字节)' },
516
+ },
517
+ verification: {
518
+ status: 'verified',
519
+ method: 'sha256+onnx-header+onnxruntime-inference',
520
+ checkedAt: '2026-11-02T08:00:00.000Z',
521
+ scope: '逐文件 bytes/sha256 与 ModelScope 文件清单双向一致 + ONNX 图头(opset 11、3 个 int64 输入、last_hidden_state float32[batch,seq,384]、自包含 117,687,936 initializer 字节)+ tokenizer.json Unigram 词表 250002 + 受管 ORT CPU 真实推理与前缀 A/B',
522
+ evidence: '固定 revision 制品已完成逐文件 SHA-256、ONNX 图头与受管 ORT CPU 推理核对;记录覆盖范数、重复编码一致性及查询和文档前缀处理,不构成检索质量评估。',
523
+ notVerified: ['huggingface/hf-mirror 上的对应 commit', 'intfloat 官方仓库中 fp32 onnx/model.onnx 与本目录 int8 导出的数值等价性'],
524
+ },
525
+ sources: {
526
+ modelscope: { repo: 'Xenova/multilingual-e5-small', revision: E5_REVISION, revisionVerified: true, commitTime: E5_COMMIT_TIME },
527
+ 'hf-mirror': { repo: 'Xenova/multilingual-e5-small', revision: null, revisionVerified: false, note: '对应来源的 commit 未核实;不生成 URL' },
528
+ huggingface: { repo: 'intfloat/multilingual-e5-small', revision: null, revisionVerified: false, note: '对应来源的 commit 未核实;不生成 URL' },
529
+ },
530
+ witness: {
531
+ provider: 'modelscope',
532
+ repo: 'intfloat/multilingual-e5-small',
533
+ revision: E5_POOLING_REVISION,
534
+ path: '1_Pooling/config.json',
535
+ bytes: 200,
536
+ sha256: '987f7a67a38fa564c849bb5d277c52ab9088a84368fc0be31a354125aebb12a0',
537
+ purpose: 'pooling 事实来源:pooling_mode_mean_tokens=true、cls/max=false、word_embedding_dimension=384;同仓库 modules.json 含 2_Normalize(L2),sentence_bert_config.json max_seq_length=512',
538
+ },
539
+ graph: {
540
+ path: 'onnx/model_quantized.onnx',
541
+ opset: 11,
542
+ producer: 'onnx.quantize',
543
+ producerVersion: '0.1.0',
544
+ selfContained: true,
545
+ externalData: [],
546
+ inputs: [
547
+ { name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
548
+ { name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
549
+ { name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
550
+ ],
551
+ outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 384] }],
552
+ },
553
+ files: [
554
+ { path: 'config.json', role: 'config', bytes: 658, sha256: 'cb99455288675345e1a4f411438d5d0adbba5fbd3a67ea4fb03c015433b996c1' },
555
+ { path: 'tokenizer.json', role: 'tokenizer', bytes: 17082730, sha256: '0b44a9d7b51c3c62626640cda0e2c2f70fdacdc25bbbd68038369d14ebdf4c39' },
556
+ { path: 'tokenizer_config.json', role: 'tokenizer-config', bytes: 443, sha256: 'a1d6bc8734a6f635dc158508bef000f8e2e5a759c7d92f984b2c86e5ff53425b' },
557
+ { path: 'special_tokens_map.json', role: 'special-tokens', bytes: 167, sha256: 'd05497f1da52c5e09554c0cd874037a083e1dc1b9cfd48034d1c717f1afc07a7' },
558
+ { path: 'quant_config.json', role: 'quantization', bytes: 674, sha256: '59d175f15264115f18c698d76e443b5d49fc6c8c599911c421405ef4f236e87d' },
559
+ { path: 'onnx/model_quantized.onnx', role: 'graph', bytes: 118308185, sha256: 'f80102d3f2a1229f387d3c81909990d8945513e347b0eab049f7de3c6f98c193' },
560
+ { path: 'README.md', role: 'notice', bytes: 1077, sha256: '561a19594636657fe033f8b4427a7743b5f6f3a12f16cecc5f286feca0453245' },
561
+ {
562
+ path: '1_Pooling/config.json',
563
+ role: 'pooling-config',
564
+ bytes: 200,
565
+ sha256: '987f7a67a38fa564c849bb5d277c52ab9088a84368fc0be31a354125aebb12a0',
566
+ origin: { provider: 'modelscope', repo: 'intfloat/multilingual-e5-small', revision: E5_POOLING_REVISION },
567
+ },
568
+ ],
569
+ },
570
+ qwen3Card('int8'),
571
+ qwen3Card('q4f16'),
572
+ ]
573
+
574
+ /**
575
+ * profile fingerprint:任何会改变向量空间的字段(模型/revision/量化/pooling/tokenizer/
576
+ * 前缀/维度/分窗)都必须进指纹(§14.8)。
577
+ */
578
+ export function profileFingerprint(entry) {
579
+ const files = Array.isArray(entry?.files) ? entry.files : []
580
+ const graphFile = files.find(file => file.role === 'graph') || null
581
+ const tokenizerFile = files.find(file => file.role === 'tokenizer') || null
582
+ const sources = entry?.sources && typeof entry.sources === 'object' ? entry.sources : {}
583
+ const primary = PROVIDER_ORDER.map(id => sources[id]).find(source => source && typeof source.revision === 'string') || null
584
+ return sha256Of(canonical({
585
+ schema: CATALOG_SCHEMA_VERSION,
586
+ id: entry?.id ?? null,
587
+ repo: primary?.repo ?? null,
588
+ revision: primary?.revision ?? null,
589
+ dimension: entry?.dimension ?? null,
590
+ maxTokens: entry?.maxTokens ?? null,
591
+ pooling: entry?.pooling ?? null,
592
+ normalization: entry?.normalization ?? null,
593
+ prefixes: entry?.prefixes ?? null,
594
+ quantization: entry?.quantization ? { weights: entry.quantization.weights, scheme: entry.quantization.scheme } : null,
595
+ graph: graphFile ? graphFile.sha256 : null,
596
+ tokenizer: tokenizerFile ? tokenizerFile.sha256 : null,
597
+ runtime: entry?.runtime ? { engine: entry.runtime.engine, abi: entry.runtime.abi, version: entry.runtime.version, os: entry.runtime.os, arch: entry.runtime.arch } : null,
598
+ files: files.map(({ path, role, bytes, sha256 }) => ({ path, role, bytes, sha256 })).sort((a, b) => a.path.localeCompare(b.path)),
599
+ graphProtocol: entry?.graph ?? null,
600
+ tokenizerProtocol: entry?.tokenizer ?? null,
601
+ preprocessing: entry?.preprocessing ?? null,
602
+ windowing: entry?.windowing ?? null,
603
+ aggregation: entry?.aggregation ?? null,
604
+ protocol: entry?.protocol ?? 'dsh-local-embedding-v1',
605
+ }))
606
+ }
607
+
608
+ const catalog = deepFreeze(rawCatalog.map(entry => ({
609
+ ...entry,
610
+ schema: CATALOG_SCHEMA_VERSION,
611
+ totalBytes: (entry.files || []).reduce((sum, file) => sum + (Number.isFinite(file.bytes) ? file.bytes : 0), 0),
612
+ profileFingerprint: profileFingerprint(entry),
613
+ })))
614
+
615
+ /**
616
+ * 把目录条目映射成"向量 profile 描述符"(供 lib/vector-profile.js 之类模块计算/比较指纹)。
617
+ * 目的:一处是模型事实(catalog),另一处是激活状态(profile),两边必须用同一份指纹,
618
+ * 否则安装/迁移会拿两套不可比的 hash 互相判等。这里只做映射,不读写任何 active 状态。
619
+ */
620
+ export function toProfileDescriptor(entry) {
621
+ const files = Array.isArray(entry?.files) ? entry.files : []
622
+ const tokenizerFile = files.find(file => file.role === "tokenizer") || null
623
+ const sources = entry?.sources && typeof entry.sources === "object" ? entry.sources : {}
624
+ const primary = PROVIDER_ORDER.map(id => sources[id]).find(source => source && typeof source.revision === "string") || null
625
+ const runtime = entry?.runtime || {}
626
+ return {
627
+ id: entry?.id ?? "",
628
+ model: entry?.id ?? "",
629
+ repo: primary?.repo ?? "",
630
+ revision: primary?.revision ?? "",
631
+ runtime: runtime.version ? `${runtime.engine}@${runtime.version}` : String(runtime.engine || ""),
632
+ tokenizer: tokenizerFile ? tokenizerFile.sha256 : null,
633
+ preprocessing: {
634
+ pooling: entry?.pooling ?? null,
635
+ normalization: entry?.normalization ?? null,
636
+ prefixes: entry?.prefixes ?? null,
637
+ maxTokens: entry?.maxTokens ?? null,
638
+ truncation: "keep-head",
639
+ },
640
+ pooling: entry?.pooling ?? "",
641
+ normalization: entry?.normalization ?? "",
642
+ prefixes: entry?.prefixes ?? null,
643
+ maxTokens: entry?.maxTokens ?? null,
644
+ dimension: entry?.dimension ?? null,
645
+ protocol: "dsh-local-embedding-v1",
646
+ fingerprint: entry?.profileFingerprint ?? null,
647
+ }
648
+ }
649
+
650
+ /** 只读目录快照;返回冻结数组,调用方改不到目录本体。 */
651
+ export function getEmbeddingCatalog() {
652
+ return catalog
653
+ }
654
+
655
+ /** 按稳定 id 取单个模型;未知 id 返回 null(不猜测、不回退默认模型)。 */
656
+ export function getEmbeddingModel(id) {
657
+ if (typeof id !== 'string') return null
658
+ return catalog.find(entry => entry.id === id) || null
659
+ }
660
+
661
+ /**
662
+ * 非对称前缀(query ≠ document)= 同一个模型对两种输入有两种读法,请求通道必须带上角色,
663
+ * 否则 worker 只能按文本猜——§14.4 明确不许猜。这里只从前缀派生,不另设开关:前缀本身在
664
+ * 指纹里,所以「要不要角色通道」和「这个向量空间是什么」永远来自同一份事实。
665
+ */
666
+ export function prefixesRequireRole(entry) {
667
+ const prefixes = entry?.prefixes
668
+ return !!prefixes
669
+ && typeof prefixes.query === 'string'
670
+ && typeof prefixes.document === 'string'
671
+ && prefixes.query !== prefixes.document
672
+ }
673
+
674
+ // ---------------------------------------------------------------- ONNX 图头
675
+
676
+ function readVarint(buffer, offset) {
677
+ let result = 0
678
+ let shift = 0
679
+ let position = offset
680
+ for (;;) {
681
+ if (position >= buffer.length) throw new Error('truncated varint')
682
+ const byte = buffer[position++]
683
+ result += (byte & 0x7f) * Math.pow(2, shift)
684
+ shift += 7
685
+ if ((byte & 0x80) === 0) break
686
+ if (shift > 56) throw new Error('varint too long')
687
+ }
688
+ return [result, position]
689
+ }
690
+
691
+ function readFields(buffer) {
692
+ const fields = []
693
+ let position = 0
694
+ while (position < buffer.length) {
695
+ let key
696
+ const keyRead = readVarint(buffer, position)
697
+ key = keyRead[0]
698
+ position = keyRead[1]
699
+ const number = key >>> 3
700
+ const wire = key & 7
701
+ if (number === 0) throw new Error('invalid field number')
702
+ if (wire === 0) {
703
+ const valueRead = readVarint(buffer, position)
704
+ position = valueRead[1]
705
+ fields.push({ number, wire, value: valueRead[0] })
706
+ } else if (wire === 2) {
707
+ const lengthRead = readVarint(buffer, position)
708
+ position = lengthRead[1]
709
+ const length = lengthRead[0]
710
+ if (position + length > buffer.length) throw new Error('length-prefixed field overruns buffer')
711
+ fields.push({ number, wire, value: buffer.subarray(position, position + length) })
712
+ position += length
713
+ } else if (wire === 5) {
714
+ if (position + 4 > buffer.length) throw new Error('truncated fixed32')
715
+ fields.push({ number, wire, value: buffer.subarray(position, position + 4) })
716
+ position += 4
717
+ } else if (wire === 1) {
718
+ if (position + 8 > buffer.length) throw new Error('truncated fixed64')
719
+ fields.push({ number, wire, value: buffer.subarray(position, position + 8) })
720
+ position += 8
721
+ } else {
722
+ throw new Error(`unsupported wire type ${wire}`)
723
+ }
724
+ }
725
+ return fields
726
+ }
727
+
728
+ function textOf(field) {
729
+ return field && Buffer.isBuffer(field.value) ? field.value.toString('utf8') : ''
730
+ }
731
+
732
+ function valueInfo(buffer) {
733
+ const info = readFields(buffer)
734
+ const name = textOf(info.find(field => field.number === 1))
735
+ const typeField = info.find(field => field.number === 2)
736
+ let dtype = null
737
+ let shape = null
738
+ if (typeField) {
739
+ const tensorType = readFields(typeField.value).find(field => field.number === 1)
740
+ if (tensorType) {
741
+ const tensor = readFields(tensorType.value)
742
+ const elemType = tensor.find(field => field.number === 1)
743
+ if (elemType) dtype = ONNX_DTYPES[elemType.value] || `elem_type_${elemType.value}`
744
+ const shapeField = tensor.find(field => field.number === 2)
745
+ if (shapeField) {
746
+ shape = readFields(shapeField.value)
747
+ .filter(field => field.number === 1)
748
+ .map(dimField => {
749
+ const dim = readFields(dimField.value)
750
+ const dimValue = dim.find(field => field.number === 1)
751
+ if (dimValue) return dimValue.value
752
+ const dimParam = dim.find(field => field.number === 2)
753
+ return dimParam ? textOf(dimParam) : '?'
754
+ })
755
+ }
756
+ }
757
+ }
758
+ return { name, dtype, shape }
759
+ }
760
+
761
+ /**
762
+ * 只读解析 ONNX 图头:opset、生产者、输入/输出名与 dtype/形状、initializer 体积、
763
+ * 是否引用 external_data。不执行图、不需要 onnxruntime(§14.4 第 1/2 条)。
764
+ */
765
+ export function readOnnxGraphHeader(buffer) {
766
+ if (!Buffer.isBuffer(buffer) || buffer.length < 8) {
767
+ const error = new Error('ONNX artifact is empty or too small to be a graph')
768
+ error.code = 'EMBEDDING_ONNX_INVALID'
769
+ throw error
770
+ }
771
+ try {
772
+ const model = readFields(buffer)
773
+ const graphField = model.find(field => field.number === 7)
774
+ if (!graphField) {
775
+ const error = new Error('ONNX artifact has no graph field')
776
+ error.code = 'EMBEDDING_ONNX_INVALID'
777
+ throw error
778
+ }
779
+ const graph = readFields(graphField.value)
780
+ const initializers = graph.filter(field => field.number === 5)
781
+ let initializerBytes = 0
782
+ let externalDataEntries = 0
783
+ for (const initializer of initializers) {
784
+ const tensor = readFields(initializer.value)
785
+ const raw = tensor.find(field => field.number === 9)
786
+ if (raw) initializerBytes += raw.value.length
787
+ externalDataEntries += tensor.filter(field => field.number === 13).length
788
+ }
789
+ return {
790
+ irVersion: model.find(field => field.number === 1)?.value ?? null,
791
+ producer: textOf(model.find(field => field.number === 2)) || null,
792
+ producerVersion: textOf(model.find(field => field.number === 3)) || null,
793
+ opsets: model.filter(field => field.number === 8).map(field => {
794
+ const opset = readFields(field.value)
795
+ return { domain: textOf(opset.find(item => item.number === 1)), version: opset.find(item => item.number === 2)?.value ?? null }
796
+ }),
797
+ inputs: graph.filter(field => field.number === 11).map(field => valueInfo(field.value)),
798
+ outputs: graph.filter(field => field.number === 12).map(field => valueInfo(field.value)),
799
+ initializerCount: initializers.length,
800
+ initializerBytes,
801
+ externalDataEntries,
802
+ selfContained: externalDataEntries === 0 && initializerBytes > 0,
803
+ }
804
+ } catch (error) {
805
+ if (error?.code === 'EMBEDDING_ONNX_INVALID') throw error
806
+ const wrapped = new Error(`cannot parse ONNX graph header: ${error?.message || error}`)
807
+ wrapped.code = 'EMBEDDING_ONNX_INVALID'
808
+ throw wrapped
809
+ }
810
+ }
811
+
812
+ // ---------------------------------------------------------------- manifest 校验
813
+
814
+ function isPlainObject(value) {
815
+ return !!value && typeof value === 'object' && !Array.isArray(value)
816
+ }
817
+
818
+ function isSafeRelativePath(filePath) {
819
+ if (typeof filePath !== 'string' || !filePath || filePath.length > 240) return false
820
+ if (filePath.includes('\\') || filePath.includes('\u0000')) return false
821
+ if (filePath.startsWith('/') || /^[A-Za-z]:/.test(filePath)) return false
822
+ return filePath.split('/').every(segment => segment && segment !== '.' && segment !== '..')
823
+ }
824
+
825
+ /**
826
+ * 校验 manifest/目录条目。返回 { ok, errors, warnings }:errors 是"不可下载/不可安装",
827
+ * warnings 是"可以下载但必须如实展示"(例如 ONNX 导出未单独声明许可、ORT 版本未实测)。
828
+ */
829
+ export function validateEmbeddingManifest(manifest) {
830
+ const errors = []
831
+ const warnings = []
832
+ const error = (code, message) => errors.push({ code, message })
833
+ const warn = (code, message) => warnings.push({ code, message })
834
+
835
+ if (!isPlainObject(manifest)) {
836
+ error('MANIFEST_NOT_OBJECT', 'manifest must be a plain object')
837
+ return { ok: false, errors, warnings }
838
+ }
839
+ if (!/^[a-z0-9][a-z0-9._-]{2,63}$/.test(String(manifest.id || ''))) error('ID_INVALID', 'id must be a stable lowercase slug')
840
+ if (typeof manifest.displayName !== 'string' || !manifest.displayName.trim()) error('DISPLAY_NAME_MISSING', 'displayName is required')
841
+ if (!Array.isArray(manifest.languages) || !manifest.languages.length) error('LANGUAGES_INVALID', 'languages must be a non-empty array')
842
+
843
+ const license = manifest.license
844
+ if (!isPlainObject(license) || !isPlainObject(license.base) || typeof license.base.id !== 'string' || !license.base.id) {
845
+ error('LICENSE_MISSING', 'license.base.id and its source are required (§14.4)')
846
+ } else if (license.base.id === 'unverified' && manifest.availability === 'available') {
847
+ error('LICENSE_UNVERIFIED', 'an available artifact must have a verified license')
848
+ }
849
+ if (isPlainObject(license) && isPlainObject(license.onnxExport) && !['declared', 'mit', 'apache-2.0'].includes(license.onnxExport.id)) {
850
+ warn('LICENSE_DERIVATIVE_UNDECLARED', 'ONNX export license is not separately declared; show it as undeclared instead of inheriting the code licence')
851
+ }
852
+
853
+ if (!Number.isFinite(manifest.parameters) || manifest.parameters <= 0) error('PARAMETERS_INVALID', 'parameters must be a positive number')
854
+ if (!Number.isInteger(manifest.dimension) || manifest.dimension < 1 || manifest.dimension > 8192) error('DIMENSION_INVALID', 'dimension must be an integer in 1..8192')
855
+ if (!(manifest.maxTokens === null || (Number.isInteger(manifest.maxTokens) && manifest.maxTokens >= 32 && manifest.maxTokens <= 32768))) {
856
+ error('MAX_TOKENS_INVALID', 'maxTokens must be null (unverified) or an integer in 32..32768')
857
+ }
858
+ // 'last' = 因果 LM 的最后一个非 pad token(Qwen3-Embedding 这一类);'max' 仍是
859
+ // 目录允许声明但执行侧未实现,所以没有任何 available 条目使用它。
860
+ if (!['cls', 'mean', 'max', 'last'].includes(manifest.pooling)) error('POOLING_INVALID', 'pooling must be cls/mean/max/last')
861
+ if (!['l2', 'none'].includes(manifest.normalization)) error('NORMALIZATION_INVALID', 'normalization must be l2/none')
862
+ if (!isPlainObject(manifest.prefixes) || typeof manifest.prefixes.query !== 'string' || typeof manifest.prefixes.document !== 'string') {
863
+ error('PREFIXES_INVALID', 'prefixes.query/document must be strings (empty is allowed)')
864
+ } else if (manifest.prefixes.query !== manifest.prefixes.document) {
865
+ warn('PREFIX_ASYMMETRIC', 'query/document prefixes differ, so this model reads the same text two ways: serving it needs an explicit role channel and role-less requests must be refused')
866
+ }
867
+
868
+ const sources = manifest.sources
869
+ if (!isPlainObject(sources) || !Object.keys(sources).length) error('SOURCES_MISSING', 'sources must map providers to explicit repo/revision')
870
+ let pinnedSources = 0
871
+ for (const provider of Object.keys(sources || {})) {
872
+ const source = sources[provider]
873
+ if (!PROVIDERS[provider]) { error('SOURCE_PROVIDER_UNKNOWN', `unknown provider ${provider}`); continue }
874
+ if (!isPlainObject(source)) { error('SOURCE_INVALID', `source ${provider} must be an object`); continue }
875
+ if (typeof source.repo !== 'string' || !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(source.repo)) {
876
+ error('SOURCE_REPO_INVALID', `source ${provider}.repo must be owner/name`)
877
+ }
878
+ if (source.revision === null) {
879
+ warn('SOURCE_REVISION_UNPINNED', `source ${provider} has no pinned revision; no URL may be derived from it`)
880
+ } else if (typeof source.revision !== 'string' || !/^[0-9a-f]{40}$/.test(source.revision)) {
881
+ error('SOURCE_REVISION_INVALID', `source ${provider}.revision must be a 40-char lowercase commit sha`)
882
+ } else {
883
+ pinnedSources++
884
+ }
885
+ }
886
+
887
+ if (manifest.availability === 'available') {
888
+ if (!pinnedSources) error('SOURCE_NOT_PINNED', 'an available artifact needs at least one provider with an explicit pinned revision')
889
+ if (!isPlainObject(manifest.verification) || manifest.verification.status !== 'verified') {
890
+ error('VERIFICATION_MISSING', 'an available artifact must carry verification.status = verified')
891
+ } else {
892
+ if (typeof manifest.verification.method !== 'string' || !manifest.verification.method) error('VERIFICATION_METHOD_MISSING', 'verification.method is required')
893
+ if (typeof manifest.verification.checkedAt !== 'string' || Number.isNaN(Date.parse(manifest.verification.checkedAt))) {
894
+ error('VERIFICATION_TIME_INVALID', 'verification.checkedAt must be an ISO timestamp')
895
+ }
896
+ }
897
+ } else if (!Array.isArray(manifest.pendingReasons) || !manifest.pendingReasons.length) {
898
+ error('PENDING_REASON_MISSING', 'a non-available model must state why it is pending')
899
+ }
900
+
901
+ const runtime = manifest.runtime
902
+ if (!isPlainObject(runtime) || typeof runtime.engine !== 'string' || typeof runtime.abi !== 'string' || typeof runtime.os !== 'string' || typeof runtime.arch !== 'string') {
903
+ error('RUNTIME_INVALID', 'runtime.engine/abi/os/arch are required (§14.4)')
904
+ } else if (runtime.version === null) {
905
+ warn('RUNTIME_VERSION_UNPINNED', 'runtime version is not pinned yet; enabling the profile must stay blocked until ORT is verified')
906
+ }
907
+
908
+ const files = manifest.files
909
+ if (!Array.isArray(files)) {
910
+ error('FILES_INVALID', 'files must be an array')
911
+ } else {
912
+ if (manifest.availability === 'available' && !files.length) error('FILES_MISSING', 'an available artifact must list its files')
913
+ const seen = new Set()
914
+ for (const file of files) {
915
+ if (!isPlainObject(file)) { error('FILE_INVALID', 'each file must be an object'); continue }
916
+ if (!isSafeRelativePath(file.path)) error('FILE_PATH_UNSAFE', `unsafe file path: ${JSON.stringify(file.path)}`)
917
+ if (seen.has(file.path)) error('FILE_DUPLICATE', `duplicate file path ${file.path}`)
918
+ seen.add(file.path)
919
+ if (!Number.isInteger(file.bytes) || file.bytes < 0) error('FILE_BYTES_INVALID', `file ${file.path} needs exact bytes`)
920
+ if (typeof file.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(file.sha256)) error('FILE_SHA256_INVALID', `file ${file.path} needs a lowercase sha256`)
921
+ if (!FILE_ROLES.includes(file.role)) error('FILE_ROLE_INVALID', `file ${file.path} has unknown role ${file.role}`)
922
+ if (file.origin !== undefined) {
923
+ const origin = file.origin
924
+ if (!isPlainObject(origin) || !PROVIDERS[origin.provider] || typeof origin.repo !== 'string' || !/^[0-9a-f]{40}$/.test(String(origin.revision))) {
925
+ error('FILE_ORIGIN_INVALID', `file ${file.path} origin must pin provider/repo/revision`)
926
+ } else if (origin.providers !== undefined
927
+ && (!Array.isArray(origin.providers) || !origin.providers.length
928
+ || !origin.providers.every(id => PROVIDERS[id]) || !origin.providers.includes(origin.provider))) {
929
+ error('FILE_ORIGIN_INVALID', `file ${file.path} origin.providers must be a non-empty list of known providers that includes origin.provider`)
930
+ }
931
+ }
932
+ }
933
+ const graphs = files.filter(file => file.role === 'graph')
934
+ if (manifest.availability === 'available' && graphs.length !== 1) error('GRAPH_MISSING', 'exactly one file must have role graph')
935
+ for (const graphFile of graphs) if (!String(graphFile.path || '').endsWith('.onnx')) error('GRAPH_NOT_ONNX', `graph file must be .onnx: ${graphFile.path}`)
936
+
937
+ // 目录构建器会给每条都补 totalBytes,而手写清单里那个「恰好等于文件之和」的值
938
+ // 本来就是同一份事实——只有对不上才是错误。否则加一条条目就得假装没写它。
939
+ const actual = files.reduce((sum, file) => sum + (Number.isFinite(file.bytes) ? file.bytes : 0), 0)
940
+ if (manifest.totalBytes !== undefined && manifest.totalBytes !== actual) {
941
+ error('TOTAL_BYTES_MISMATCH', `totalBytes ${manifest.totalBytes} does not equal the sum of files ${actual}`)
942
+ }
943
+ }
944
+
945
+ const graph = manifest.graph
946
+ if (manifest.availability === 'available') {
947
+ if (!isPlainObject(graph)) {
948
+ error('GRAPH_DESCRIPTOR_MISSING', 'graph descriptor (inputs/outputs/dtype) is required')
949
+ } else {
950
+ if (!Array.isArray(graph.inputs) || !graph.inputs.length || !Array.isArray(graph.outputs) || !graph.outputs.length) {
951
+ error('GRAPH_IO_INVALID', 'graph.inputs/outputs must be non-empty arrays')
952
+ }
953
+ for (const io of [...(graph.inputs || []), ...(graph.outputs || [])]) {
954
+ if (!isPlainObject(io) || typeof io.name !== 'string' || !io.name || typeof io.dtype !== 'string' || !io.dtype) {
955
+ error('GRAPH_IO_INVALID', 'each graph input/output needs name and dtype')
956
+ }
957
+ }
958
+ const output = (graph.outputs || [])[0]
959
+ const last = Array.isArray(output?.shape) ? output.shape[output.shape.length - 1] : null
960
+ if (Number.isInteger(manifest.dimension) && last !== manifest.dimension) {
961
+ error('GRAPH_DIMENSION_MISMATCH', `graph output last dim ${last} does not match dimension ${manifest.dimension}`)
962
+ }
963
+ if (Array.isArray(graph.externalData) && graph.externalData.length && graph.selfContained !== false) {
964
+ error('GRAPH_EXTERNAL_DATA_UNDECLARED', 'external data references must be listed and selfContained=false')
965
+ }
966
+ }
967
+ }
968
+
969
+ const graphFileInFiles = Array.isArray(files) ? files.find(file => file.role === 'graph') : null
970
+ if (isPlainObject(graph) && graphFileInFiles && graph.path !== graphFileInFiles.path) {
971
+ error('GRAPH_PATH_MISMATCH', `graph.path ${graph.path} must equal the graph file ${graphFileInFiles.path}`)
972
+ }
973
+
974
+ if (manifest.profileFingerprint !== undefined) {
975
+ const expected = profileFingerprint(manifest)
976
+ if (manifest.profileFingerprint !== expected) error('FINGERPRINT_MISMATCH', `profileFingerprint ${manifest.profileFingerprint} does not match the profile ${expected}`)
977
+ }
978
+
979
+ return { ok: errors.length === 0, errors, warnings }
980
+ }
981
+
982
+ /**
983
+ * 只按 manifest 里显式写明的 repo+revision 生成 URL(§14.4)。默认顺序
984
+ * modelscope → hf-mirror → huggingface;没有固定 revision 的来源不生成任何 URL,
985
+ * 而是列进 skipped 并写明原因。
986
+ */
987
+ export function resolveEmbeddingSources(idOrEntry, options = {}) {
988
+ const entry = typeof idOrEntry === 'string' ? getEmbeddingModel(idOrEntry) : idOrEntry
989
+ if (!isPlainObject(entry)) {
990
+ const error = new Error(`unknown embedding model: ${String(idOrEntry)}`)
991
+ error.code = 'EMBEDDING_MODEL_UNKNOWN'
992
+ throw error
993
+ }
994
+ const providers = Array.isArray(options.providers) && options.providers.length ? options.providers : PROVIDER_ORDER
995
+ const files = Array.isArray(entry.files) ? entry.files : []
996
+ const skipped = []
997
+ const sources = []
998
+
999
+ for (const providerId of providers) {
1000
+ if (!PROVIDERS[providerId]) {
1001
+ skipped.push({ provider: providerId, reason: 'provider-unknown' })
1002
+ continue
1003
+ }
1004
+ const source = isPlainObject(entry.sources) ? entry.sources[providerId] : null
1005
+ if (!isPlainObject(source)) { skipped.push({ provider: providerId, reason: 'not-mapped' }); continue }
1006
+ if (typeof source.revision !== 'string' || !/^[0-9a-f]{40}$/.test(source.revision)) {
1007
+ skipped.push({ provider: providerId, reason: 'revision-unpinned', repo: source.repo || null })
1008
+ continue
1009
+ }
1010
+ if (typeof source.repo !== 'string' || !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(source.repo)) {
1011
+ skipped.push({ provider: providerId, reason: 'repo-invalid' })
1012
+ continue
1013
+ }
1014
+ const fileUrls = []
1015
+ let blocked = null
1016
+ for (const file of files) {
1017
+ const origin = file.origin
1018
+ // 见证制品默认绑死它被核实的那个 provider。镜像站族(hf-mirror / huggingface 是同一
1019
+ // commit 的同一份内容)可以由 origin.providers 显式声明多个合法来源,否则换源会被
1020
+ // 这条规则整条封掉;无论哪个来源,落盘都要过同一个 sha256。
1021
+ const allowedProviders = origin && Array.isArray(origin.providers) && origin.providers.length ? origin.providers : [origin?.provider]
1022
+ if (origin && !allowedProviders.includes(providerId)) {
1023
+ blocked = { provider: providerId, reason: 'origin-provider-mismatch', path: file.path, originProvider: origin.provider }
1024
+ break
1025
+ }
1026
+ const repo = origin?.repo || source.repo
1027
+ const revision = origin?.revision || source.revision
1028
+ fileUrls.push({
1029
+ path: file.path,
1030
+ role: file.role,
1031
+ bytes: file.bytes,
1032
+ sha256: file.sha256,
1033
+ repo,
1034
+ revision,
1035
+ url: PROVIDERS[providerId].url({ repo, revision, path: file.path }),
1036
+ })
1037
+ }
1038
+ if (blocked) { skipped.push(blocked); continue }
1039
+ if (!fileUrls.length) { skipped.push({ provider: providerId, reason: 'no-files' }); continue }
1040
+ sources.push({ provider: providerId, label: PROVIDERS[providerId].label, repo: source.repo, revision: source.revision, ready: true, files: fileUrls })
1041
+ }
1042
+
1043
+ return {
1044
+ id: entry.id,
1045
+ availability: entry.availability,
1046
+ order: [...providers],
1047
+ sources,
1048
+ skipped,
1049
+ primary: sources[0] || null,
1050
+ }
1051
+ }