dsh-memu-memory 1.4.1 → 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 -108
  2. package/CHANGELOG.md +169 -848
  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 -72
  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 -0
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -840
  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 -9648
  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 -1035
  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 -4911
  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 -0
  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 -2518
  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 -1066
  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 -152
  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 -455
  182. package/tests/client-export.test.mjs +521 -520
  183. package/tests/client-render.test.mjs +2008 -1727
  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 -48
  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 -415
  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 -616
  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 -0
  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 -23
  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 -221
  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 -212
  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 -414
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,682 +1,682 @@
1
- import http from 'node:http'
2
- import fs from 'node:fs'
3
- import path from 'node:path'
4
- import crypto from 'node:crypto'
5
- import { createRequire } from 'node:module'
6
- import { pathToFileURL } from 'node:url'
7
- import {
8
- EMBEDDINGS_PATH,
9
- HEALTH_PATH,
10
- DEFAULT_MAX_BODY_BYTES,
11
- DEFAULT_MAX_BATCH,
12
- ENCODINGS,
13
- MAX_VECTOR_DIMENSION,
14
- LocalEmbeddingError,
15
- assertVector,
16
- buildEmbeddingResponse,
17
- errorBody,
18
- errorStatus,
19
- parseEmbeddingRequest,
20
- } from './local-embedding-protocol.js'
21
- import { prefixesRequireRole } from './embedding-catalog.js'
22
-
23
- // §14.5: loopback only, port 0, random high-entropy token from the parent. Nothing
24
- // here ever reaches the network, downloads a model, or logs a token or input text.
25
- export const LOOPBACK_HOSTS = Object.freeze(['127.0.0.1', '::1', 'localhost'])
26
- export const MIN_TOKEN_LENGTH = 16
27
- const SMOKE_TEXT = 'embedding readiness probe'
28
-
29
- function asError(message, code, status, detail = null) {
30
- return new LocalEmbeddingError(message, code, status, detail)
31
- }
32
-
33
- function isLoopbackHostname(hostname) {
34
- const text = String(hostname || '').toLowerCase()
35
- return LOOPBACK_HOSTS.includes(text)
36
- }
37
-
38
- // The model id is what MemU passes as MEMU_EMBED_MODEL: the stable catalog id plus
39
- // the pinned revision and processing protocol, so a different weight/quota/pooling
40
- // build can never silently answer for the old one (§14.8: same dimension but a
41
- // different space is still a different space).
42
- export function manifestModelId(manifest) {
43
- if (!manifest || typeof manifest !== 'object') return ''
44
- if (typeof manifest.model === 'string' && manifest.model.trim()) return manifest.model.trim()
45
- const id = typeof manifest.id === 'string' ? manifest.id.trim() : ''
46
- if (!id) return ''
47
- const revision = typeof manifest.revision === 'string' ? manifest.revision.trim() : ''
48
- const protocol = typeof manifest.protocol === 'string' ? manifest.protocol.trim() : ''
49
- const suffix = [revision, protocol].filter(Boolean).join('+')
50
- return suffix ? id + '@' + suffix : id
51
- }
52
-
53
- export function manifestDimension(manifest) {
54
- const candidates = [
55
- manifest && manifest.dimension,
56
- manifest && manifest.expectedDimension,
57
- manifest && manifest.output && manifest.output.dimension,
58
- manifest && manifest.embedding && manifest.embedding.dimension,
59
- ]
60
- for (const value of candidates) {
61
- const number = Number(value)
62
- if (Number.isInteger(number) && number > 0) {
63
- if (number > MAX_VECTOR_DIMENSION) throw asError('manifest dimension ' + number + ' exceeds the protocol limit', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
64
- return number
65
- }
66
- }
67
- return 0
68
- }
69
-
70
- // The prefix is a property of the model, never of the caller's text: an empty prefix
71
- // is a real choice (BGE/MiniLM read both sides the same), and a missing prefixes block
72
- // means exactly that. Roles are required only when the two sides differ (§14.4).
73
- function manifestPrefixes(manifest) {
74
- const raw = manifest && manifest.prefixes && typeof manifest.prefixes === 'object' ? manifest.prefixes : {}
75
- return {
76
- query: typeof raw.query === 'string' ? raw.query : '',
77
- document: typeof raw.document === 'string' ? raw.document : '',
78
- }
79
- }
80
-
81
- export function applyRolePrefix(inputs, prefixes, role) {
82
- const prefix = role === 'query' ? prefixes.query : prefixes.document
83
- return prefix ? inputs.map(text => prefix + text) : inputs
84
- }
85
-
86
- // A model is servable only when the installer marked it verified. pending /
87
- // candidate / downloading entries exist in the catalog, but a half-installed
88
- // artifact must never answer a request, and nothing here starts a download to
89
- // fix that (§14.4).
90
- export function assertServableManifest({ manifest, modelDir } = {}) {
91
- if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
92
- throw asError('a model manifest is required to start the embedding worker', 'LOCAL_VECTOR_MANIFEST_INVALID', 503)
93
- }
94
- const state = String(manifest.status || manifest.state || manifest.verification?.status || '').toLowerCase()
95
- if (manifest.pending === true || state === 'pending' || state === 'candidate' || state === 'downloading') {
96
- throw asError('model ' + (manifestModelId(manifest) || '(unnamed)') + ' is ' + (state || 'pending') + ', not verified; finish the managed download first', 'LOCAL_VECTOR_MANIFEST_UNVERIFIED', 503)
97
- }
98
- if (manifest.verified !== true && state !== 'verified') {
99
- throw asError('model ' + (manifestModelId(manifest) || '(unnamed)') + ' is not verified; refusing to serve it', 'LOCAL_VECTOR_MANIFEST_UNVERIFIED', 503)
100
- }
101
- const dir = typeof modelDir === 'string' ? modelDir.trim() : ''
102
- if (!dir) throw asError('modelDir is required', 'LOCAL_VECTOR_MODEL_DIR_MISSING', 503)
103
- let stat = null
104
- try { stat = fs.statSync(dir) } catch { stat = null }
105
- if (!stat || !stat.isDirectory()) throw asError('modelDir ' + dir + ' is missing; installed model files are required', 'LOCAL_VECTOR_MODEL_DIR_MISSING', 503)
106
- const model = manifestModelId(manifest)
107
- if (!model) throw asError('manifest is missing a stable id', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
108
- const dimension = manifestDimension(manifest)
109
- if (!dimension) throw asError('manifest is missing expected dimension', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
110
- const prefixes = manifestPrefixes(manifest)
111
- return { model, dimension, modelDir: path.resolve(dir), prefixes, rolesRequired: prefixesRequireRole({ prefixes }) }
112
- }
113
-
114
- // External-data graphs, tokenizer files and the model directory itself are all
115
- // attacker-adjacent input: absolute paths, .. segments, symlinks or junctions that
116
- // resolve outside the model directory are refused before anything is opened.
117
- export function resolveInsideModelDir(modelDir, relPath) {
118
- const dir = typeof modelDir === 'string' ? modelDir.trim() : ''
119
- if (!dir) throw asError('modelDir is required', 'LOCAL_VECTOR_MODEL_DIR_MISSING', 503)
120
- let root = null
121
- try { root = fs.realpathSync(path.resolve(dir)) } catch { root = null }
122
- if (!root) throw asError('modelDir ' + dir + ' is missing', 'LOCAL_VECTOR_MODEL_DIR_MISSING', 503)
123
- const rel = typeof relPath === 'string' ? relPath.trim() : ''
124
- if (!rel) throw asError('manifest names no model file', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
125
- if (path.isAbsolute(rel) || /^[A-Za-z]:/.test(rel)) {
126
- throw asError('model file ' + rel + ' must be relative to the model directory', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
127
- }
128
- const segments = rel.split(/[\\/]+/)
129
- if (segments.some((segment) => segment === '..')) {
130
- throw asError('model file ' + rel + ' escapes the model directory', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
131
- }
132
- const target = path.resolve(root, rel)
133
- if (target !== root && !target.startsWith(root + path.sep)) {
134
- throw asError('model file ' + rel + ' escapes the model directory', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
135
- }
136
- let real = null
137
- try { real = fs.realpathSync(target) } catch { real = null }
138
- if (!real) throw asError('model file ' + rel + ' is missing', 'LOCAL_VECTOR_MODEL_FILE_MISSING', 503)
139
- if (real !== root && !real.startsWith(root + path.sep)) {
140
- throw asError('model file ' + rel + ' resolves outside the model directory', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
141
- }
142
- return real
143
- }
144
-
145
- function runtimeUnavailable(kind, specifier, runtimeDir, error) {
146
- const where = runtimeDir ? ' in ' + runtimeDir : ''
147
- const reason = String((error && (error.code || error.message)) || error || 'not found')
148
- return asError(
149
- kind + ' module "' + specifier + '" is not installed' + where + ' (' + reason + '); install the pinned artifact instead of downloading at runtime',
150
- 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE',
151
- 503,
152
- { module: specifier, kind },
153
- )
154
- }
155
-
156
- // Resolve only from the explicitly installed managed runtime. Runtime imports never
157
- // consult the host application's node_modules and never trigger an install.
158
- async function importFrom(specifier, runtimeDir) {
159
- const value = String(specifier || '').trim()
160
- if (!value) throw new Error('module specifier is empty')
161
- if (path.isAbsolute(value) || value.startsWith('file:')) return import(value)
162
- if (!runtimeDir || !String(runtimeDir).trim()) {
163
- const error = new Error('managed runtimeDir is required for module ' + value)
164
- error.code = 'ERR_MODULE_NOT_FOUND'
165
- throw error
166
- }
167
- const requireFrom = createRequire(path.join(path.resolve(String(runtimeDir).trim()), 'entry.cjs'))
168
- const resolved = requireFrom.resolve(value)
169
- return import(pathToFileURL(resolved).href)
170
- }
171
-
172
- function manifestFilePath(manifest, role, fallback) {
173
- const files = Array.isArray(manifest?.files) ? manifest.files : []
174
- const match = files.find(file => file && file.role === role)
175
- const declared = role === 'graph' ? manifest?.graph?.path : (manifest?.tokenizer?.file || manifest?.tokenizer?.path)
176
- return declared || match?.path || fallback
177
- }
178
-
179
- async function openTokenizer(mod, modelDir, manifest = {}) {
180
- const tokenizerPath = resolveInsideModelDir(modelDir, manifestFilePath(manifest, 'tokenizer', 'tokenizer.json'))
181
- const configPath = resolveInsideModelDir(modelDir, manifestFilePath(manifest, 'tokenizer-config', 'tokenizer_config.json'))
182
- const Tokenizer = mod.Tokenizer || (mod.default && mod.default.Tokenizer)
183
- if (Tokenizer && typeof Tokenizer.fromFile === 'function') return Tokenizer.fromFile(tokenizerPath)
184
- if (Tokenizer && typeof Tokenizer === 'function') {
185
- const tokenizerJson = JSON.parse(fs.readFileSync(tokenizerPath, 'utf8'))
186
- let config = {}
187
- try { config = JSON.parse(fs.readFileSync(configPath, 'utf8')) } catch {}
188
- return new Tokenizer(tokenizerJson, config)
189
- }
190
- const fromFile = mod.fromFile || (mod.default && mod.default.fromFile)
191
- if (typeof fromFile === 'function') return fromFile(tokenizerPath)
192
- throw new Error('tokenizer module exposes no supported local tokenizer constructor')
193
- }
194
-
195
- function padRows(rows, pad, requestedWidth = null) {
196
- const width = Number.isInteger(requestedWidth) && requestedWidth > 0 ? requestedWidth : rows.reduce((max, row) => Math.max(max, row.length), 0)
197
- return rows.map((row) => {
198
- if (row.length === width) return row
199
- if (row.length > width) return row.slice(0, width)
200
- const next = row.slice()
201
- while (next.length < width) next.push(pad)
202
- return next
203
- })
204
- }
205
-
206
- // Two real tokenizer shapes: the Rust binding (encode -> Encoding with getIds) and
207
- // transformers.js (await tokenizer(texts, opts) -> {input_ids, attention_mask}).
208
- async function tokenizeBatch(tokenizer, texts, maxTokens) {
209
- const limit = Number.isInteger(maxTokens) && maxTokens > 0 ? maxTokens : 512
210
- if (tokenizer && typeof tokenizer.encode === 'function') {
211
- const ids = []
212
- const mask = []
213
- const types = []
214
- for (const text of texts) {
215
- let encoding = null
216
- try { encoding = await tokenizer.encode(String(text), { add_special_tokens: true, return_token_type_ids: true }) } catch { encoding = await tokenizer.encode(String(text)) }
217
- const rawIds = typeof encoding?.getIds === 'function' ? Array.from(encoding.getIds(), Number) : Array.isArray(encoding?.ids) ? Array.from(encoding.ids, Number) : null
218
- if (!rawIds) throw new Error('tokenizer.encode did not return token ids')
219
- const rawMask = typeof encoding?.getAttentionMask === 'function' ? Array.from(encoding.getAttentionMask(), Number) : Array.isArray(encoding?.attention_mask) ? Array.from(encoding.attention_mask, Number) : rawIds.map(() => 1)
220
- const rawTypes = typeof encoding?.getTypeIds === 'function' ? Array.from(encoding.getTypeIds(), Number) : Array.isArray(encoding?.token_type_ids) ? Array.from(encoding.token_type_ids, Number) : rawIds.map(() => 0)
221
- const truncate = (row) => row.length <= limit ? row : row.slice(0, Math.max(0, limit - 1)).concat(row.slice(-1))
222
- const rowIds = truncate(rawIds)
223
- const rowMask = truncate(rawMask)
224
- const rowTypes = truncate(rawTypes)
225
- ids.push(rowIds)
226
- mask.push(rowMask)
227
- types.push(rowTypes)
228
- }
229
- return { ids: padRows(ids, 0), mask: padRows(mask, 0), types: padRows(types, 0) }
230
- }
231
- if (typeof tokenizer === 'function') {
232
- const out = await tokenizer(texts, { padding: true, truncation: true, max_length: limit, return_tensor: false })
233
- const rows = (value) => (Array.isArray(value) && Array.isArray(value[0]) ? value : [value])
234
- const idsRows = rows(out && out.input_ids).map((row) => Array.from(row, Number).slice(0, limit))
235
- const maskRows = rows(out && (out.attention_mask || out.input_ids)).map((row) => Array.from(row, Number).slice(0, limit))
236
- return { ids: padRows(idsRows, 0), mask: padRows(maskRows, 0), types: idsRows.map((row) => row.map(() => 0)) }
237
- }
238
- throw new Error('unsupported tokenizer interface')
239
- }
240
-
241
- // 因果语言模型(Qwen3-Embedding 这一类)取最后一个非 pad token 的隐藏态:下标由
242
- // attention_mask 的累加和决定,所以右侧 padding 也一样准,与官方
243
- // 1_Pooling(pooling_mode_lasttoken) 的口径一致。
244
- function poolTensor(tensor, { pooling, mask, normalize }) {
245
- const dims = Array.from((tensor && tensor.dims) || [])
246
- const data = tensor && tensor.data
247
- if (!data || dims.length < 2) throw new Error('graph output is not a hidden-state tensor')
248
- const batch = dims[0]
249
- const hidden = dims[dims.length - 1]
250
- const tokens = dims.length >= 3 ? dims[1] : 1
251
- const out = []
252
- for (let row = 0; row < batch; row++) {
253
- const vector = new Array(hidden).fill(0)
254
- const base = row * tokens * hidden
255
- const weights = mask && mask[row] ? mask[row] : null
256
- if (pooling === 'last' && tokens > 1) {
257
- let last = tokens - 1
258
- if (weights) {
259
- for (let token = tokens - 1; token >= 0; token--) {
260
- if (Number(weights[token]) || 0) { last = token; break }
261
- }
262
- }
263
- for (let unit = 0; unit < hidden; unit++) vector[unit] = Number(data[base + last * hidden + unit])
264
- } else if (pooling === 'mean' && tokens > 1) {
265
- let total = 0
266
- for (let token = 0; token < tokens; token++) {
267
- const weight = weights ? Number(weights[token]) || 0 : 1
268
- if (!weight) continue
269
- total += weight
270
- for (let unit = 0; unit < hidden; unit++) vector[unit] += Number(data[base + token * hidden + unit]) * weight
271
- }
272
- for (let unit = 0; unit < hidden; unit++) vector[unit] = total > 0 ? vector[unit] / total : 0
273
- } else {
274
- for (let unit = 0; unit < hidden; unit++) vector[unit] = Number(data[base + unit])
275
- }
276
- if (normalize !== false) {
277
- let norm = 0
278
- for (const value of vector) norm += value * value
279
- norm = Math.sqrt(norm)
280
- if (norm > 0) for (let unit = 0; unit < hidden; unit++) vector[unit] /= norm
281
- }
282
- out.push(vector)
283
- }
284
- return out
285
- }
286
-
287
- function toBigInt64(rows) {
288
- const flat = new BigInt64Array(rows.length * rows[0].length)
289
- for (let row = 0; row < rows.length; row++) {
290
- for (let column = 0; column < rows[row].length; column++) flat[row * rows[row].length + column] = BigInt(Math.trunc(Number(rows[row][column]) || 0))
291
- }
292
- return flat
293
- }
294
-
295
- // Real inference path: managed CPU ONNX Runtime + a pinned tokenizer. It is only
296
- // reached when no adapter is injected, and every failure is reported as
297
- // LOCAL_VECTOR_RUNTIME_UNAVAILABLE rather than papered over by a fallback model.
298
- export async function createOnnxAdapter({ modelDir, manifest = {}, runtimeDir, tokenizerModule, runtimeModule } = {}) {
299
- const graphPath = resolveInsideModelDir(modelDir, manifestFilePath(manifest, 'graph', manifest.onnx?.graph || 'model.onnx'))
300
- const runtimeSpec = runtimeModule || (manifest.runtime && manifest.runtime.module) || 'onnxruntime-node'
301
- let ort = null
302
- try { ort = await importFrom(runtimeSpec, runtimeDir) } catch (error) { throw runtimeUnavailable('runtime', runtimeSpec, runtimeDir, error) }
303
- const InferenceSession = ort.InferenceSession || (ort.default && ort.default.InferenceSession)
304
- if (!InferenceSession || typeof InferenceSession.create !== 'function') {
305
- throw runtimeUnavailable('runtime', runtimeSpec, runtimeDir, new Error('InferenceSession.create is missing'))
306
- }
307
- const tokenizerSpec = tokenizerModule || (manifest.tokenizer && manifest.tokenizer.module) || '@huggingface/tokenizers'
308
- let tokenizer = null
309
- try {
310
- const mod = await importFrom(tokenizerSpec, runtimeDir)
311
- tokenizer = await openTokenizer(mod, modelDir, manifest)
312
- } catch (error) {
313
- if (error instanceof LocalEmbeddingError) throw error
314
- throw runtimeUnavailable('tokenizer', tokenizerSpec, runtimeDir, error)
315
- }
316
-
317
- const threads = Number(manifest.runtime && manifest.runtime.threads)
318
- let session = null
319
- try {
320
- session = await InferenceSession.create(graphPath, {
321
- executionProviders: ['cpu'],
322
- graphOptimizationLevel: 'all',
323
- ...(Number.isInteger(threads) && threads > 0 ? { intraOpNumThreads: threads } : {}),
324
- })
325
- } catch (error) {
326
- throw asError('embedding graph failed to load: ' + String((error && error.message) || error), 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE', 503, { graph: path.basename(graphPath) })
327
- }
328
-
329
- const maxTokens = Number(manifest.maxTokens || (manifest.tokenizer && manifest.tokenizer.maxTokens) || 512)
330
- const pooling = String(manifest.pooling || 'cls').toLowerCase()
331
- const normalize = manifest.normalization ? String(manifest.normalization).toLowerCase() === 'l2' : manifest.normalize !== false
332
- const inputNames = Array.from(session.inputNames || Object.keys(session.inputMetadata || {}))
333
-
334
- const encode = async (texts) => {
335
- const batch = await tokenizeBatch(tokenizer, texts, maxTokens)
336
- const dims = [batch.ids.length, batch.ids[0].length]
337
- const feeds = {}
338
- for (const name of inputNames) {
339
- const key = name.toLowerCase()
340
- if (/token_type|segment/.test(key)) feeds[name] = new ort.Tensor('int64', toBigInt64(batch.types), dims)
341
- else if (/attention|mask/.test(key)) feeds[name] = new ort.Tensor('int64', toBigInt64(batch.mask), dims)
342
- else if (/input_ids|(^|_)ids$/.test(key)) feeds[name] = new ort.Tensor('int64', toBigInt64(batch.ids), dims)
343
- }
344
- const outputs = await session.run(feeds)
345
- const names = Array.from(session.outputNames || Object.keys(outputs))
346
- const tensor = outputs[names[0]] || Object.values(outputs)[0]
347
- return poolTensor(tensor, { pooling, mask: batch.mask, normalize })
348
- }
349
-
350
- return {
351
- // Quantized activations depend on other batch rows. Keep native inference
352
- // single-row so a document and the same query occupy one stable vector space.
353
- encode: async (texts) => {
354
- const vectors = []
355
- for (const text of texts) vectors.push(...await encode([text]))
356
- return vectors
357
- },
358
- close: async () => {
359
- try { await session.release() } catch {}
360
- },
361
- }
362
- }
363
-
364
- function bindAdapter(adapter) {
365
- if (!adapter || typeof adapter !== 'object') {
366
- throw asError('an embedding adapter with encode(inputs) is required', 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE', 503)
367
- }
368
- const fn = [adapter.encode, adapter.embed, adapter.embedBatch].find((candidate) => typeof candidate === 'function')
369
- if (!fn) throw asError('embedding adapter must expose encode(inputs)', 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE', 503)
370
- return {
371
- encode: (inputs) => fn.call(adapter, inputs),
372
- close: typeof adapter.close === 'function' ? () => adapter.close() : null,
373
- }
374
- }
375
-
376
- // Accepts the shapes a runtime or a test adapter plausibly returns, but never
377
- // guesses the count: a short/long result is an error, because a shifted batch
378
- // would silently attach the wrong vector to the wrong memory segment.
379
- function adapterVectors(output, expected, errorFactory) {
380
- let list = null
381
- if (Array.isArray(output)) list = output
382
- else if (output && typeof output === 'object') {
383
- if (Array.isArray(output.vectors)) list = output.vectors
384
- else if (Array.isArray(output.embeddings)) list = output.embeddings
385
- else if (Array.isArray(output.data)) list = output.data.map((entry) => (entry && typeof entry === 'object' && 'embedding' in entry ? entry.embedding : entry))
386
- }
387
- if (!list) throw errorFactory('embedding adapter returned no vectors', 'LOCAL_VECTOR_INVALID_VECTOR')
388
- if (list.length !== expected) {
389
- throw errorFactory('embedding adapter returned ' + list.length + ' vectors for ' + expected + ' inputs', 'LOCAL_VECTOR_VECTOR_COUNT_MISMATCH')
390
- }
391
- const usage = output && typeof output === 'object' && output.usage && typeof output.usage === 'object' ? output.usage : null
392
- return { vectors: list, usage }
393
- }
394
-
395
- function tokenMatches(header, token) {
396
- if (typeof header !== 'string' || typeof token !== 'string' || !token) return false
397
- const match = /^Bearer\s+(.+)$/i.exec(header.trim())
398
- if (!match) return false
399
- const provided = Buffer.from(match[1].trim(), 'utf8')
400
- const expected = Buffer.from(token, 'utf8')
401
- if (provided.length !== expected.length) return false
402
- return crypto.timingSafeEqual(provided, expected)
403
- }
404
-
405
- function sendJson(res, status, value, extraHeaders = null) {
406
- if (res.writableEnded || res.headersSent) return
407
- const payload = Buffer.from(JSON.stringify(value), 'utf8')
408
- res.writeHead(status, {
409
- 'content-type': 'application/json; charset=utf-8',
410
- 'content-length': String(payload.length),
411
- 'cache-control': 'no-store',
412
- 'x-content-type-options': 'nosniff',
413
- ...(extraHeaders || {}),
414
- })
415
- res.end(payload)
416
- }
417
-
418
- function readBody(req, limit) {
419
- return new Promise((resolve, reject) => {
420
- let size = 0
421
- let settled = false
422
- const chunks = []
423
- const finish = (error, value) => {
424
- if (settled) return
425
- settled = true
426
- if (error) reject(error)
427
- else resolve(value)
428
- }
429
- req.on('data', (chunk) => {
430
- size += chunk.length
431
- if (size > limit) {
432
- finish(asError('request body exceeds ' + limit + ' bytes', 'LOCAL_VECTOR_BODY_TOO_LARGE', 413))
433
- // Stop reading but keep the socket alive: the caller needs the 413 body,
434
- // so the connection is only torn down after the response is flushed.
435
- try { req.pause() } catch {}
436
- return
437
- }
438
- chunks.push(chunk)
439
- })
440
- req.on('end', () => finish(null, Buffer.concat(chunks).toString('utf8')))
441
- req.on('error', (error) => finish(asError('request body could not be read', 'LOCAL_VECTOR_BODY_UNREADABLE', 400, String((error && error.code) || error))))
442
- })
443
- }
444
-
445
- /**
446
- * §14.5 managed embedding worker: one loopback HTTP server speaking the OpenAI
447
- * embeddings subset MemU already uses, backed by either an injected adapter (tests
448
- * only) or the pinned managed ONNX runtime.
449
- *
450
- * @returns {Promise<{baseUrl: string, url: string, healthUrl: string, model: string, dimension: number, close: () => Promise<void>, lastError: object|null}>}
451
- * baseUrl is what MEMU_BASE_URL wants (http://host:port/v1); url is the full
452
- * embeddings endpoint; healthUrl is the readiness probe outside /v1. lastError is
453
- * live: set on any 5xx/inference failure and cleared by the next successful
454
- * request so a healthy worker stops reporting.
455
- */
456
- export async function startEmbeddingWorker(options = {}) {
457
- const {
458
- modelDir,
459
- manifest,
460
- runtimeDir,
461
- token,
462
- adapter = null,
463
- tokenizerModule,
464
- runtimeModule,
465
- host = '127.0.0.1',
466
- port = 0,
467
- logger = console,
468
- signal,
469
- maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
470
- maxBatch = DEFAULT_MAX_BATCH,
471
- } = options
472
-
473
- const { model, dimension, prefixes, rolesRequired } = assertServableManifest({ manifest, modelDir })
474
-
475
- if (typeof token !== 'string' || token.length < MIN_TOKEN_LENGTH) {
476
- throw asError('a random token of at least ' + MIN_TOKEN_LENGTH + ' characters is required', 'LOCAL_VECTOR_TOKEN_INVALID', 400)
477
- }
478
- if (!isLoopbackHostname(host)) {
479
- throw asError('embedding worker only binds loopback, refused ' + String(host), 'LOCAL_VECTOR_BAD_HOST', 400)
480
- }
481
- const port_ = Number(port)
482
- if (!Number.isInteger(port_) || port_ < 0 || port_ > 65535) {
483
- throw asError('port must be an integer between 0 and 65535', 'LOCAL_VECTOR_BAD_PORT', 400)
484
- }
485
- const bodyLimit = Number.isInteger(maxBodyBytes) && maxBodyBytes > 0 ? maxBodyBytes : DEFAULT_MAX_BODY_BYTES
486
- const batchLimit = Number.isInteger(maxBatch) && maxBatch > 0 ? maxBatch : DEFAULT_MAX_BATCH
487
-
488
- const encoder = adapter
489
- ? bindAdapter(adapter)
490
- : await createOnnxAdapter({ modelDir, manifest, runtimeDir, tokenizerModule, runtimeModule })
491
-
492
- const fail = (message, code, status, detail) => asError(message, code, status, detail)
493
- const encodeVectors = async (inputs) => {
494
- let output = null
495
- try {
496
- output = await encoder.encode(inputs)
497
- } catch (error) {
498
- if (error instanceof LocalEmbeddingError) throw error
499
- throw fail('embedding inference failed: ' + String((error && error.message) || error), 'LOCAL_VECTOR_INFERENCE_FAILED', 500)
500
- }
501
- return adapterVectors(output, inputs.length, fail)
502
- }
503
-
504
- let lastError = null
505
- const noteFailure = (error) => {
506
- if (errorStatus(error) < 500) return
507
- lastError = {
508
- at: new Date().toISOString(),
509
- code: String((error && error.code) || 'LOCAL_VECTOR_ERROR'),
510
- message: String((error && error.message) || 'embedding request failed'),
511
- }
512
- }
513
-
514
- // Ready means the graph/tokenizer answered once with a finite, correctly sized,
515
- // non-zero vector. Without this smoke test the first recall pays the failure.
516
- let encoderClosed = false
517
- try {
518
- const smoke = await encodeVectors([SMOKE_TEXT])
519
- assertVector(smoke.vectors[0], dimension, 0)
520
- } catch (error) {
521
- try { if (encoder.close && !encoderClosed) { encoderClosed = true; await encoder.close() } } catch {}
522
- if (error instanceof LocalEmbeddingError) throw error
523
- throw fail('embedding smoke test failed: ' + String((error && error.message) || error), 'LOCAL_VECTOR_SMOKE_FAILED', 503)
524
- }
525
-
526
- const startedAt = Date.now()
527
- const sockets = new Set()
528
- let closed = false
529
-
530
- const assertLocalOrigin = (req) => {
531
- // Any Origin header means a browser page is talking to us: refuse, and never
532
- // send CORS headers, so a web app cannot use the local index as an oracle.
533
- if (req.headers.origin !== undefined) throw fail('cross-origin requests are not accepted', 'LOCAL_VECTOR_CORS_REJECTED', 403)
534
- }
535
- const assertLocalHost = (req) => {
536
- const raw = String(req.headers.host || '')
537
- const hostname = raw.startsWith('[') ? raw.slice(1, raw.indexOf(']')) : raw.split(':')[0]
538
- if (!hostname) throw fail('host header is required', 'LOCAL_VECTOR_BAD_HOST', 403)
539
- if (!isLoopbackHostname(hostname)) throw fail('host header must be loopback', 'LOCAL_VECTOR_BAD_HOST', 403)
540
- }
541
- const assertAuthorized = (req) => {
542
- if (tokenMatches(req.headers.authorization, token)) return
543
- throw fail('missing or invalid bearer token', 'LOCAL_VECTOR_UNAUTHORIZED', 401)
544
- }
545
- const methodNotAllowed = (res, allowed) => {
546
- sendJson(res, 405, errorBody(fail('method not allowed', 'LOCAL_VECTOR_METHOD_NOT_ALLOWED', 405)), { allow: allowed })
547
- }
548
-
549
- const respondHealth = (req, res) => {
550
- if (req.method !== 'GET' && req.method !== 'HEAD') return methodNotAllowed(res, 'GET')
551
- lastError = null
552
- if (req.method === 'HEAD') {
553
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
554
- res.end()
555
- return
556
- }
557
- sendJson(res, 200, {
558
- object: 'local_embedding_health',
559
- status: 'ok',
560
- ready: !closed,
561
- model,
562
- dimension,
563
- maxBatch: batchLimit,
564
- encodings: ENCODINGS,
565
- rolesRequired,
566
- uptimeMs: Date.now() - startedAt,
567
- })
568
- }
569
-
570
- const respondEmbeddings = async (req, res) => {
571
- if (req.method !== 'POST') return methodNotAllowed(res, 'POST')
572
- const contentType = String(req.headers['content-type'] || '')
573
- if (!/^application\/json\b/i.test(contentType)) {
574
- throw fail('content-type must be application/json', 'LOCAL_VECTOR_UNSUPPORTED_MEDIA_TYPE', 415)
575
- }
576
- const declared = Number(req.headers['content-length'])
577
- if (Number.isFinite(declared) && declared > bodyLimit) {
578
- throw fail('request body exceeds ' + bodyLimit + ' bytes', 'LOCAL_VECTOR_BODY_TOO_LARGE', 413)
579
- }
580
- const raw = await readBody(req, bodyLimit)
581
- let body = null
582
- try { body = JSON.parse(raw) } catch { throw fail('request body is not valid JSON', 'LOCAL_VECTOR_BAD_REQUEST', 400) }
583
- const { inputs, encoding, role } = parseEmbeddingRequest(body, { model, maxBatch: batchLimit, rolesRequired })
584
- const encoded = await encodeVectors(applyRolePrefix(inputs, prefixes, role))
585
- const vectors = encoded.vectors.map((vector, index) => assertVector(vector, dimension, index))
586
- sendJson(res, 200, buildEmbeddingResponse({ model, vectors, encoding, usage: encoded.usage }))
587
- lastError = null
588
- }
589
-
590
- const server = http.createServer((req, res) => {
591
- const route = String(req.url || '/')
592
- const serve = async () => {
593
- assertLocalOrigin(req)
594
- assertLocalHost(req)
595
- assertAuthorized(req)
596
- const pathname = new URL(route, 'http://127.0.0.1').pathname
597
- if (pathname === HEALTH_PATH) return respondHealth(req, res)
598
- if (pathname === EMBEDDINGS_PATH) return respondEmbeddings(req, res)
599
- throw fail('unknown endpoint', 'LOCAL_VECTOR_NOT_FOUND', 404)
600
- }
601
- serve().catch((error) => {
602
- noteFailure(error)
603
- const status = errorStatus(error)
604
- try {
605
- logger.warn?.('[dsh-memu-memory] local embedding worker ' + status + ' ' + String((error && error.code) || 'LOCAL_VECTOR_ERROR') + ' ' + String((error && error.message) || error) + ' (' + pathnameOf(route) + ')')
606
- } catch {}
607
- sendJson(res, status, errorBody(error), status === 401 ? { 'www-authenticate': 'Bearer' } : null)
608
- if (status === 413) res.on('finish', () => { try { req.destroy() } catch {} })
609
- })
610
- })
611
- const pathnameOf = (route) => {
612
- try { return new URL(route, 'http://127.0.0.1').pathname } catch { return '/' }
613
- }
614
- server.maxHeadersCount = 64
615
- server.headersTimeout = 20_000
616
- server.requestTimeout = 120_000
617
- server.on('connection', (socket) => {
618
- sockets.add(socket)
619
- socket.on('close', () => sockets.delete(socket))
620
- })
621
-
622
- const close = async () => {
623
- if (closed) return
624
- closed = true
625
- if (signal) signal.removeEventListener?.('abort', onAbort)
626
- await new Promise((resolve) => {
627
- try {
628
- server.close(() => resolve())
629
- } catch {
630
- resolve()
631
- }
632
- for (const socket of sockets) {
633
- try { socket.destroy() } catch {}
634
- }
635
- sockets.clear()
636
- setTimeout(resolve, 2_000).unref?.()
637
- })
638
- if (encoder.close && !encoderClosed) {
639
- encoderClosed = true
640
- try { await encoder.close() } catch {}
641
- }
642
- }
643
- const onAbort = () => { void close() }
644
-
645
- await new Promise((resolve, reject) => {
646
- const onError = (error) => {
647
- server.removeListener('listening', onListening)
648
- reject(fail('embedding worker could not listen on ' + host + ':' + port_ + ' (' + String((error && error.code) || error) + ')', 'LOCAL_VECTOR_LISTEN_FAILED', 503))
649
- }
650
- const onListening = () => {
651
- server.removeListener('error', onError)
652
- resolve()
653
- }
654
- server.once('error', onError)
655
- server.once('listening', onListening)
656
- server.listen(port_, host)
657
- })
658
-
659
- if (signal) {
660
- if (signal.aborted) {
661
- await close()
662
- throw fail('embedding worker start aborted', 'LOCAL_VECTOR_ABORTED', 499)
663
- }
664
- signal.addEventListener?.('abort', onAbort, { once: true })
665
- }
666
-
667
- const address = server.address()
668
- const actualPort = address && typeof address === 'object' ? address.port : port_
669
- const hostForUrl = host === '::1' ? '[::1]' : host
670
- const origin = 'http://' + hostForUrl + ':' + actualPort
671
- const handle = {
672
- baseUrl: origin + '/v1',
673
- url: origin + EMBEDDINGS_PATH,
674
- healthUrl: origin + HEALTH_PATH,
675
- model,
676
- dimension,
677
- close,
678
- }
679
- Object.defineProperty(handle, 'lastError', { enumerable: true, get: () => lastError })
680
- try { logger.info?.('[dsh-memu-memory] local embedding worker ready on ' + origin + ' model=' + model + ' dimension=' + dimension) } catch {}
681
- return handle
682
- }
1
+ import http from 'node:http'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import crypto from 'node:crypto'
5
+ import { createRequire } from 'node:module'
6
+ import { pathToFileURL } from 'node:url'
7
+ import {
8
+ EMBEDDINGS_PATH,
9
+ HEALTH_PATH,
10
+ DEFAULT_MAX_BODY_BYTES,
11
+ DEFAULT_MAX_BATCH,
12
+ ENCODINGS,
13
+ MAX_VECTOR_DIMENSION,
14
+ LocalEmbeddingError,
15
+ assertVector,
16
+ buildEmbeddingResponse,
17
+ errorBody,
18
+ errorStatus,
19
+ parseEmbeddingRequest,
20
+ } from './local-embedding-protocol.js'
21
+ import { prefixesRequireRole } from './embedding-catalog.js'
22
+
23
+ // §14.5: loopback only, port 0, random high-entropy token from the parent. Nothing
24
+ // here ever reaches the network, downloads a model, or logs a token or input text.
25
+ export const LOOPBACK_HOSTS = Object.freeze(['127.0.0.1', '::1', 'localhost'])
26
+ export const MIN_TOKEN_LENGTH = 16
27
+ const SMOKE_TEXT = 'embedding readiness probe'
28
+
29
+ function asError(message, code, status, detail = null) {
30
+ return new LocalEmbeddingError(message, code, status, detail)
31
+ }
32
+
33
+ function isLoopbackHostname(hostname) {
34
+ const text = String(hostname || '').toLowerCase()
35
+ return LOOPBACK_HOSTS.includes(text)
36
+ }
37
+
38
+ // The model id is what MemU passes as MEMU_EMBED_MODEL: the stable catalog id plus
39
+ // the pinned revision and processing protocol, so a different weight/quota/pooling
40
+ // build can never silently answer for the old one (§14.8: same dimension but a
41
+ // different space is still a different space).
42
+ export function manifestModelId(manifest) {
43
+ if (!manifest || typeof manifest !== 'object') return ''
44
+ if (typeof manifest.model === 'string' && manifest.model.trim()) return manifest.model.trim()
45
+ const id = typeof manifest.id === 'string' ? manifest.id.trim() : ''
46
+ if (!id) return ''
47
+ const revision = typeof manifest.revision === 'string' ? manifest.revision.trim() : ''
48
+ const protocol = typeof manifest.protocol === 'string' ? manifest.protocol.trim() : ''
49
+ const suffix = [revision, protocol].filter(Boolean).join('+')
50
+ return suffix ? id + '@' + suffix : id
51
+ }
52
+
53
+ export function manifestDimension(manifest) {
54
+ const candidates = [
55
+ manifest && manifest.dimension,
56
+ manifest && manifest.expectedDimension,
57
+ manifest && manifest.output && manifest.output.dimension,
58
+ manifest && manifest.embedding && manifest.embedding.dimension,
59
+ ]
60
+ for (const value of candidates) {
61
+ const number = Number(value)
62
+ if (Number.isInteger(number) && number > 0) {
63
+ if (number > MAX_VECTOR_DIMENSION) throw asError('manifest dimension ' + number + ' exceeds the protocol limit', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
64
+ return number
65
+ }
66
+ }
67
+ return 0
68
+ }
69
+
70
+ // The prefix is a property of the model, never of the caller's text: an empty prefix
71
+ // is a real choice (BGE/MiniLM read both sides the same), and a missing prefixes block
72
+ // means exactly that. Roles are required only when the two sides differ (§14.4).
73
+ function manifestPrefixes(manifest) {
74
+ const raw = manifest && manifest.prefixes && typeof manifest.prefixes === 'object' ? manifest.prefixes : {}
75
+ return {
76
+ query: typeof raw.query === 'string' ? raw.query : '',
77
+ document: typeof raw.document === 'string' ? raw.document : '',
78
+ }
79
+ }
80
+
81
+ export function applyRolePrefix(inputs, prefixes, role) {
82
+ const prefix = role === 'query' ? prefixes.query : prefixes.document
83
+ return prefix ? inputs.map(text => prefix + text) : inputs
84
+ }
85
+
86
+ // A model is servable only when the installer marked it verified. pending /
87
+ // candidate / downloading entries exist in the catalog, but a half-installed
88
+ // artifact must never answer a request, and nothing here starts a download to
89
+ // fix that (§14.4).
90
+ export function assertServableManifest({ manifest, modelDir } = {}) {
91
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
92
+ throw asError('a model manifest is required to start the embedding worker', 'LOCAL_VECTOR_MANIFEST_INVALID', 503)
93
+ }
94
+ const state = String(manifest.status || manifest.state || manifest.verification?.status || '').toLowerCase()
95
+ if (manifest.pending === true || state === 'pending' || state === 'candidate' || state === 'downloading') {
96
+ throw asError('model ' + (manifestModelId(manifest) || '(unnamed)') + ' is ' + (state || 'pending') + ', not verified; finish the managed download first', 'LOCAL_VECTOR_MANIFEST_UNVERIFIED', 503)
97
+ }
98
+ if (manifest.verified !== true && state !== 'verified') {
99
+ throw asError('model ' + (manifestModelId(manifest) || '(unnamed)') + ' is not verified; refusing to serve it', 'LOCAL_VECTOR_MANIFEST_UNVERIFIED', 503)
100
+ }
101
+ const dir = typeof modelDir === 'string' ? modelDir.trim() : ''
102
+ if (!dir) throw asError('modelDir is required', 'LOCAL_VECTOR_MODEL_DIR_MISSING', 503)
103
+ let stat = null
104
+ try { stat = fs.statSync(dir) } catch { stat = null }
105
+ if (!stat || !stat.isDirectory()) throw asError('modelDir ' + dir + ' is missing; installed model files are required', 'LOCAL_VECTOR_MODEL_DIR_MISSING', 503)
106
+ const model = manifestModelId(manifest)
107
+ if (!model) throw asError('manifest is missing a stable id', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
108
+ const dimension = manifestDimension(manifest)
109
+ if (!dimension) throw asError('manifest is missing expected dimension', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
110
+ const prefixes = manifestPrefixes(manifest)
111
+ return { model, dimension, modelDir: path.resolve(dir), prefixes, rolesRequired: prefixesRequireRole({ prefixes }) }
112
+ }
113
+
114
+ // External-data graphs, tokenizer files and the model directory itself are all
115
+ // attacker-adjacent input: absolute paths, .. segments, symlinks or junctions that
116
+ // resolve outside the model directory are refused before anything is opened.
117
+ export function resolveInsideModelDir(modelDir, relPath) {
118
+ const dir = typeof modelDir === 'string' ? modelDir.trim() : ''
119
+ if (!dir) throw asError('modelDir is required', 'LOCAL_VECTOR_MODEL_DIR_MISSING', 503)
120
+ let root = null
121
+ try { root = fs.realpathSync(path.resolve(dir)) } catch { root = null }
122
+ if (!root) throw asError('modelDir ' + dir + ' is missing', 'LOCAL_VECTOR_MODEL_DIR_MISSING', 503)
123
+ const rel = typeof relPath === 'string' ? relPath.trim() : ''
124
+ if (!rel) throw asError('manifest names no model file', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
125
+ if (path.isAbsolute(rel) || /^[A-Za-z]:/.test(rel)) {
126
+ throw asError('model file ' + rel + ' must be relative to the model directory', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
127
+ }
128
+ const segments = rel.split(/[\\/]+/)
129
+ if (segments.some((segment) => segment === '..')) {
130
+ throw asError('model file ' + rel + ' escapes the model directory', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
131
+ }
132
+ const target = path.resolve(root, rel)
133
+ if (target !== root && !target.startsWith(root + path.sep)) {
134
+ throw asError('model file ' + rel + ' escapes the model directory', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
135
+ }
136
+ let real = null
137
+ try { real = fs.realpathSync(target) } catch { real = null }
138
+ if (!real) throw asError('model file ' + rel + ' is missing', 'LOCAL_VECTOR_MODEL_FILE_MISSING', 503)
139
+ if (real !== root && !real.startsWith(root + path.sep)) {
140
+ throw asError('model file ' + rel + ' resolves outside the model directory', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
141
+ }
142
+ return real
143
+ }
144
+
145
+ function runtimeUnavailable(kind, specifier, runtimeDir, error) {
146
+ const where = runtimeDir ? ' in ' + runtimeDir : ''
147
+ const reason = String((error && (error.code || error.message)) || error || 'not found')
148
+ return asError(
149
+ kind + ' module "' + specifier + '" is not installed' + where + ' (' + reason + '); install the pinned artifact instead of downloading at runtime',
150
+ 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE',
151
+ 503,
152
+ { module: specifier, kind },
153
+ )
154
+ }
155
+
156
+ // Resolve only from the explicitly installed managed runtime. Runtime imports never
157
+ // consult the host application's node_modules and never trigger an install.
158
+ async function importFrom(specifier, runtimeDir) {
159
+ const value = String(specifier || '').trim()
160
+ if (!value) throw new Error('module specifier is empty')
161
+ if (path.isAbsolute(value) || value.startsWith('file:')) return import(value)
162
+ if (!runtimeDir || !String(runtimeDir).trim()) {
163
+ const error = new Error('managed runtimeDir is required for module ' + value)
164
+ error.code = 'ERR_MODULE_NOT_FOUND'
165
+ throw error
166
+ }
167
+ const requireFrom = createRequire(path.join(path.resolve(String(runtimeDir).trim()), 'entry.cjs'))
168
+ const resolved = requireFrom.resolve(value)
169
+ return import(pathToFileURL(resolved).href)
170
+ }
171
+
172
+ function manifestFilePath(manifest, role, fallback) {
173
+ const files = Array.isArray(manifest?.files) ? manifest.files : []
174
+ const match = files.find(file => file && file.role === role)
175
+ const declared = role === 'graph' ? manifest?.graph?.path : (manifest?.tokenizer?.file || manifest?.tokenizer?.path)
176
+ return declared || match?.path || fallback
177
+ }
178
+
179
+ async function openTokenizer(mod, modelDir, manifest = {}) {
180
+ const tokenizerPath = resolveInsideModelDir(modelDir, manifestFilePath(manifest, 'tokenizer', 'tokenizer.json'))
181
+ const configPath = resolveInsideModelDir(modelDir, manifestFilePath(manifest, 'tokenizer-config', 'tokenizer_config.json'))
182
+ const Tokenizer = mod.Tokenizer || (mod.default && mod.default.Tokenizer)
183
+ if (Tokenizer && typeof Tokenizer.fromFile === 'function') return Tokenizer.fromFile(tokenizerPath)
184
+ if (Tokenizer && typeof Tokenizer === 'function') {
185
+ const tokenizerJson = JSON.parse(fs.readFileSync(tokenizerPath, 'utf8'))
186
+ let config = {}
187
+ try { config = JSON.parse(fs.readFileSync(configPath, 'utf8')) } catch {}
188
+ return new Tokenizer(tokenizerJson, config)
189
+ }
190
+ const fromFile = mod.fromFile || (mod.default && mod.default.fromFile)
191
+ if (typeof fromFile === 'function') return fromFile(tokenizerPath)
192
+ throw new Error('tokenizer module exposes no supported local tokenizer constructor')
193
+ }
194
+
195
+ function padRows(rows, pad, requestedWidth = null) {
196
+ const width = Number.isInteger(requestedWidth) && requestedWidth > 0 ? requestedWidth : rows.reduce((max, row) => Math.max(max, row.length), 0)
197
+ return rows.map((row) => {
198
+ if (row.length === width) return row
199
+ if (row.length > width) return row.slice(0, width)
200
+ const next = row.slice()
201
+ while (next.length < width) next.push(pad)
202
+ return next
203
+ })
204
+ }
205
+
206
+ // Two real tokenizer shapes: the Rust binding (encode -> Encoding with getIds) and
207
+ // transformers.js (await tokenizer(texts, opts) -> {input_ids, attention_mask}).
208
+ async function tokenizeBatch(tokenizer, texts, maxTokens) {
209
+ const limit = Number.isInteger(maxTokens) && maxTokens > 0 ? maxTokens : 512
210
+ if (tokenizer && typeof tokenizer.encode === 'function') {
211
+ const ids = []
212
+ const mask = []
213
+ const types = []
214
+ for (const text of texts) {
215
+ let encoding = null
216
+ try { encoding = await tokenizer.encode(String(text), { add_special_tokens: true, return_token_type_ids: true }) } catch { encoding = await tokenizer.encode(String(text)) }
217
+ const rawIds = typeof encoding?.getIds === 'function' ? Array.from(encoding.getIds(), Number) : Array.isArray(encoding?.ids) ? Array.from(encoding.ids, Number) : null
218
+ if (!rawIds) throw new Error('tokenizer.encode did not return token ids')
219
+ const rawMask = typeof encoding?.getAttentionMask === 'function' ? Array.from(encoding.getAttentionMask(), Number) : Array.isArray(encoding?.attention_mask) ? Array.from(encoding.attention_mask, Number) : rawIds.map(() => 1)
220
+ const rawTypes = typeof encoding?.getTypeIds === 'function' ? Array.from(encoding.getTypeIds(), Number) : Array.isArray(encoding?.token_type_ids) ? Array.from(encoding.token_type_ids, Number) : rawIds.map(() => 0)
221
+ const truncate = (row) => row.length <= limit ? row : row.slice(0, Math.max(0, limit - 1)).concat(row.slice(-1))
222
+ const rowIds = truncate(rawIds)
223
+ const rowMask = truncate(rawMask)
224
+ const rowTypes = truncate(rawTypes)
225
+ ids.push(rowIds)
226
+ mask.push(rowMask)
227
+ types.push(rowTypes)
228
+ }
229
+ return { ids: padRows(ids, 0), mask: padRows(mask, 0), types: padRows(types, 0) }
230
+ }
231
+ if (typeof tokenizer === 'function') {
232
+ const out = await tokenizer(texts, { padding: true, truncation: true, max_length: limit, return_tensor: false })
233
+ const rows = (value) => (Array.isArray(value) && Array.isArray(value[0]) ? value : [value])
234
+ const idsRows = rows(out && out.input_ids).map((row) => Array.from(row, Number).slice(0, limit))
235
+ const maskRows = rows(out && (out.attention_mask || out.input_ids)).map((row) => Array.from(row, Number).slice(0, limit))
236
+ return { ids: padRows(idsRows, 0), mask: padRows(maskRows, 0), types: idsRows.map((row) => row.map(() => 0)) }
237
+ }
238
+ throw new Error('unsupported tokenizer interface')
239
+ }
240
+
241
+ // 因果语言模型(Qwen3-Embedding 这一类)取最后一个非 pad token 的隐藏态:下标由
242
+ // attention_mask 的累加和决定,所以右侧 padding 也一样准,与官方
243
+ // 1_Pooling(pooling_mode_lasttoken) 的口径一致。
244
+ function poolTensor(tensor, { pooling, mask, normalize }) {
245
+ const dims = Array.from((tensor && tensor.dims) || [])
246
+ const data = tensor && tensor.data
247
+ if (!data || dims.length < 2) throw new Error('graph output is not a hidden-state tensor')
248
+ const batch = dims[0]
249
+ const hidden = dims[dims.length - 1]
250
+ const tokens = dims.length >= 3 ? dims[1] : 1
251
+ const out = []
252
+ for (let row = 0; row < batch; row++) {
253
+ const vector = new Array(hidden).fill(0)
254
+ const base = row * tokens * hidden
255
+ const weights = mask && mask[row] ? mask[row] : null
256
+ if (pooling === 'last' && tokens > 1) {
257
+ let last = tokens - 1
258
+ if (weights) {
259
+ for (let token = tokens - 1; token >= 0; token--) {
260
+ if (Number(weights[token]) || 0) { last = token; break }
261
+ }
262
+ }
263
+ for (let unit = 0; unit < hidden; unit++) vector[unit] = Number(data[base + last * hidden + unit])
264
+ } else if (pooling === 'mean' && tokens > 1) {
265
+ let total = 0
266
+ for (let token = 0; token < tokens; token++) {
267
+ const weight = weights ? Number(weights[token]) || 0 : 1
268
+ if (!weight) continue
269
+ total += weight
270
+ for (let unit = 0; unit < hidden; unit++) vector[unit] += Number(data[base + token * hidden + unit]) * weight
271
+ }
272
+ for (let unit = 0; unit < hidden; unit++) vector[unit] = total > 0 ? vector[unit] / total : 0
273
+ } else {
274
+ for (let unit = 0; unit < hidden; unit++) vector[unit] = Number(data[base + unit])
275
+ }
276
+ if (normalize !== false) {
277
+ let norm = 0
278
+ for (const value of vector) norm += value * value
279
+ norm = Math.sqrt(norm)
280
+ if (norm > 0) for (let unit = 0; unit < hidden; unit++) vector[unit] /= norm
281
+ }
282
+ out.push(vector)
283
+ }
284
+ return out
285
+ }
286
+
287
+ function toBigInt64(rows) {
288
+ const flat = new BigInt64Array(rows.length * rows[0].length)
289
+ for (let row = 0; row < rows.length; row++) {
290
+ for (let column = 0; column < rows[row].length; column++) flat[row * rows[row].length + column] = BigInt(Math.trunc(Number(rows[row][column]) || 0))
291
+ }
292
+ return flat
293
+ }
294
+
295
+ // Real inference path: managed CPU ONNX Runtime + a pinned tokenizer. It is only
296
+ // reached when no adapter is injected, and every failure is reported as
297
+ // LOCAL_VECTOR_RUNTIME_UNAVAILABLE rather than papered over by a fallback model.
298
+ export async function createOnnxAdapter({ modelDir, manifest = {}, runtimeDir, tokenizerModule, runtimeModule } = {}) {
299
+ const graphPath = resolveInsideModelDir(modelDir, manifestFilePath(manifest, 'graph', manifest.onnx?.graph || 'model.onnx'))
300
+ const runtimeSpec = runtimeModule || (manifest.runtime && manifest.runtime.module) || 'onnxruntime-node'
301
+ let ort = null
302
+ try { ort = await importFrom(runtimeSpec, runtimeDir) } catch (error) { throw runtimeUnavailable('runtime', runtimeSpec, runtimeDir, error) }
303
+ const InferenceSession = ort.InferenceSession || (ort.default && ort.default.InferenceSession)
304
+ if (!InferenceSession || typeof InferenceSession.create !== 'function') {
305
+ throw runtimeUnavailable('runtime', runtimeSpec, runtimeDir, new Error('InferenceSession.create is missing'))
306
+ }
307
+ const tokenizerSpec = tokenizerModule || (manifest.tokenizer && manifest.tokenizer.module) || '@huggingface/tokenizers'
308
+ let tokenizer = null
309
+ try {
310
+ const mod = await importFrom(tokenizerSpec, runtimeDir)
311
+ tokenizer = await openTokenizer(mod, modelDir, manifest)
312
+ } catch (error) {
313
+ if (error instanceof LocalEmbeddingError) throw error
314
+ throw runtimeUnavailable('tokenizer', tokenizerSpec, runtimeDir, error)
315
+ }
316
+
317
+ const threads = Number(manifest.runtime && manifest.runtime.threads)
318
+ let session = null
319
+ try {
320
+ session = await InferenceSession.create(graphPath, {
321
+ executionProviders: ['cpu'],
322
+ graphOptimizationLevel: 'all',
323
+ ...(Number.isInteger(threads) && threads > 0 ? { intraOpNumThreads: threads } : {}),
324
+ })
325
+ } catch (error) {
326
+ throw asError('embedding graph failed to load: ' + String((error && error.message) || error), 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE', 503, { graph: path.basename(graphPath) })
327
+ }
328
+
329
+ const maxTokens = Number(manifest.maxTokens || (manifest.tokenizer && manifest.tokenizer.maxTokens) || 512)
330
+ const pooling = String(manifest.pooling || 'cls').toLowerCase()
331
+ const normalize = manifest.normalization ? String(manifest.normalization).toLowerCase() === 'l2' : manifest.normalize !== false
332
+ const inputNames = Array.from(session.inputNames || Object.keys(session.inputMetadata || {}))
333
+
334
+ const encode = async (texts) => {
335
+ const batch = await tokenizeBatch(tokenizer, texts, maxTokens)
336
+ const dims = [batch.ids.length, batch.ids[0].length]
337
+ const feeds = {}
338
+ for (const name of inputNames) {
339
+ const key = name.toLowerCase()
340
+ if (/token_type|segment/.test(key)) feeds[name] = new ort.Tensor('int64', toBigInt64(batch.types), dims)
341
+ else if (/attention|mask/.test(key)) feeds[name] = new ort.Tensor('int64', toBigInt64(batch.mask), dims)
342
+ else if (/input_ids|(^|_)ids$/.test(key)) feeds[name] = new ort.Tensor('int64', toBigInt64(batch.ids), dims)
343
+ }
344
+ const outputs = await session.run(feeds)
345
+ const names = Array.from(session.outputNames || Object.keys(outputs))
346
+ const tensor = outputs[names[0]] || Object.values(outputs)[0]
347
+ return poolTensor(tensor, { pooling, mask: batch.mask, normalize })
348
+ }
349
+
350
+ return {
351
+ // Quantized activations depend on other batch rows. Keep native inference
352
+ // single-row so a document and the same query occupy one stable vector space.
353
+ encode: async (texts) => {
354
+ const vectors = []
355
+ for (const text of texts) vectors.push(...await encode([text]))
356
+ return vectors
357
+ },
358
+ close: async () => {
359
+ try { await session.release() } catch {}
360
+ },
361
+ }
362
+ }
363
+
364
+ function bindAdapter(adapter) {
365
+ if (!adapter || typeof adapter !== 'object') {
366
+ throw asError('an embedding adapter with encode(inputs) is required', 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE', 503)
367
+ }
368
+ const fn = [adapter.encode, adapter.embed, adapter.embedBatch].find((candidate) => typeof candidate === 'function')
369
+ if (!fn) throw asError('embedding adapter must expose encode(inputs)', 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE', 503)
370
+ return {
371
+ encode: (inputs) => fn.call(adapter, inputs),
372
+ close: typeof adapter.close === 'function' ? () => adapter.close() : null,
373
+ }
374
+ }
375
+
376
+ // Accepts the shapes a runtime or a test adapter plausibly returns, but never
377
+ // guesses the count: a short/long result is an error, because a shifted batch
378
+ // would silently attach the wrong vector to the wrong memory segment.
379
+ function adapterVectors(output, expected, errorFactory) {
380
+ let list = null
381
+ if (Array.isArray(output)) list = output
382
+ else if (output && typeof output === 'object') {
383
+ if (Array.isArray(output.vectors)) list = output.vectors
384
+ else if (Array.isArray(output.embeddings)) list = output.embeddings
385
+ else if (Array.isArray(output.data)) list = output.data.map((entry) => (entry && typeof entry === 'object' && 'embedding' in entry ? entry.embedding : entry))
386
+ }
387
+ if (!list) throw errorFactory('embedding adapter returned no vectors', 'LOCAL_VECTOR_INVALID_VECTOR')
388
+ if (list.length !== expected) {
389
+ throw errorFactory('embedding adapter returned ' + list.length + ' vectors for ' + expected + ' inputs', 'LOCAL_VECTOR_VECTOR_COUNT_MISMATCH')
390
+ }
391
+ const usage = output && typeof output === 'object' && output.usage && typeof output.usage === 'object' ? output.usage : null
392
+ return { vectors: list, usage }
393
+ }
394
+
395
+ function tokenMatches(header, token) {
396
+ if (typeof header !== 'string' || typeof token !== 'string' || !token) return false
397
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim())
398
+ if (!match) return false
399
+ const provided = Buffer.from(match[1].trim(), 'utf8')
400
+ const expected = Buffer.from(token, 'utf8')
401
+ if (provided.length !== expected.length) return false
402
+ return crypto.timingSafeEqual(provided, expected)
403
+ }
404
+
405
+ function sendJson(res, status, value, extraHeaders = null) {
406
+ if (res.writableEnded || res.headersSent) return
407
+ const payload = Buffer.from(JSON.stringify(value), 'utf8')
408
+ res.writeHead(status, {
409
+ 'content-type': 'application/json; charset=utf-8',
410
+ 'content-length': String(payload.length),
411
+ 'cache-control': 'no-store',
412
+ 'x-content-type-options': 'nosniff',
413
+ ...(extraHeaders || {}),
414
+ })
415
+ res.end(payload)
416
+ }
417
+
418
+ function readBody(req, limit) {
419
+ return new Promise((resolve, reject) => {
420
+ let size = 0
421
+ let settled = false
422
+ const chunks = []
423
+ const finish = (error, value) => {
424
+ if (settled) return
425
+ settled = true
426
+ if (error) reject(error)
427
+ else resolve(value)
428
+ }
429
+ req.on('data', (chunk) => {
430
+ size += chunk.length
431
+ if (size > limit) {
432
+ finish(asError('request body exceeds ' + limit + ' bytes', 'LOCAL_VECTOR_BODY_TOO_LARGE', 413))
433
+ // Stop reading but keep the socket alive: the caller needs the 413 body,
434
+ // so the connection is only torn down after the response is flushed.
435
+ try { req.pause() } catch {}
436
+ return
437
+ }
438
+ chunks.push(chunk)
439
+ })
440
+ req.on('end', () => finish(null, Buffer.concat(chunks).toString('utf8')))
441
+ req.on('error', (error) => finish(asError('request body could not be read', 'LOCAL_VECTOR_BODY_UNREADABLE', 400, String((error && error.code) || error))))
442
+ })
443
+ }
444
+
445
+ /**
446
+ * §14.5 managed embedding worker: one loopback HTTP server speaking the OpenAI
447
+ * embeddings subset MemU already uses, backed by either an injected adapter (tests
448
+ * only) or the pinned managed ONNX runtime.
449
+ *
450
+ * @returns {Promise<{baseUrl: string, url: string, healthUrl: string, model: string, dimension: number, close: () => Promise<void>, lastError: object|null}>}
451
+ * baseUrl is what MEMU_BASE_URL wants (http://host:port/v1); url is the full
452
+ * embeddings endpoint; healthUrl is the readiness probe outside /v1. lastError is
453
+ * live: set on any 5xx/inference failure and cleared by the next successful
454
+ * request so a healthy worker stops reporting.
455
+ */
456
+ export async function startEmbeddingWorker(options = {}) {
457
+ const {
458
+ modelDir,
459
+ manifest,
460
+ runtimeDir,
461
+ token,
462
+ adapter = null,
463
+ tokenizerModule,
464
+ runtimeModule,
465
+ host = '127.0.0.1',
466
+ port = 0,
467
+ logger = console,
468
+ signal,
469
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
470
+ maxBatch = DEFAULT_MAX_BATCH,
471
+ } = options
472
+
473
+ const { model, dimension, prefixes, rolesRequired } = assertServableManifest({ manifest, modelDir })
474
+
475
+ if (typeof token !== 'string' || token.length < MIN_TOKEN_LENGTH) {
476
+ throw asError('a random token of at least ' + MIN_TOKEN_LENGTH + ' characters is required', 'LOCAL_VECTOR_TOKEN_INVALID', 400)
477
+ }
478
+ if (!isLoopbackHostname(host)) {
479
+ throw asError('embedding worker only binds loopback, refused ' + String(host), 'LOCAL_VECTOR_BAD_HOST', 400)
480
+ }
481
+ const port_ = Number(port)
482
+ if (!Number.isInteger(port_) || port_ < 0 || port_ > 65535) {
483
+ throw asError('port must be an integer between 0 and 65535', 'LOCAL_VECTOR_BAD_PORT', 400)
484
+ }
485
+ const bodyLimit = Number.isInteger(maxBodyBytes) && maxBodyBytes > 0 ? maxBodyBytes : DEFAULT_MAX_BODY_BYTES
486
+ const batchLimit = Number.isInteger(maxBatch) && maxBatch > 0 ? maxBatch : DEFAULT_MAX_BATCH
487
+
488
+ const encoder = adapter
489
+ ? bindAdapter(adapter)
490
+ : await createOnnxAdapter({ modelDir, manifest, runtimeDir, tokenizerModule, runtimeModule })
491
+
492
+ const fail = (message, code, status, detail) => asError(message, code, status, detail)
493
+ const encodeVectors = async (inputs) => {
494
+ let output = null
495
+ try {
496
+ output = await encoder.encode(inputs)
497
+ } catch (error) {
498
+ if (error instanceof LocalEmbeddingError) throw error
499
+ throw fail('embedding inference failed: ' + String((error && error.message) || error), 'LOCAL_VECTOR_INFERENCE_FAILED', 500)
500
+ }
501
+ return adapterVectors(output, inputs.length, fail)
502
+ }
503
+
504
+ let lastError = null
505
+ const noteFailure = (error) => {
506
+ if (errorStatus(error) < 500) return
507
+ lastError = {
508
+ at: new Date().toISOString(),
509
+ code: String((error && error.code) || 'LOCAL_VECTOR_ERROR'),
510
+ message: String((error && error.message) || 'embedding request failed'),
511
+ }
512
+ }
513
+
514
+ // Ready means the graph/tokenizer answered once with a finite, correctly sized,
515
+ // non-zero vector. Without this smoke test the first recall pays the failure.
516
+ let encoderClosed = false
517
+ try {
518
+ const smoke = await encodeVectors([SMOKE_TEXT])
519
+ assertVector(smoke.vectors[0], dimension, 0)
520
+ } catch (error) {
521
+ try { if (encoder.close && !encoderClosed) { encoderClosed = true; await encoder.close() } } catch {}
522
+ if (error instanceof LocalEmbeddingError) throw error
523
+ throw fail('embedding smoke test failed: ' + String((error && error.message) || error), 'LOCAL_VECTOR_SMOKE_FAILED', 503)
524
+ }
525
+
526
+ const startedAt = Date.now()
527
+ const sockets = new Set()
528
+ let closed = false
529
+
530
+ const assertLocalOrigin = (req) => {
531
+ // Any Origin header means a browser page is talking to us: refuse, and never
532
+ // send CORS headers, so a web app cannot use the local index as an oracle.
533
+ if (req.headers.origin !== undefined) throw fail('cross-origin requests are not accepted', 'LOCAL_VECTOR_CORS_REJECTED', 403)
534
+ }
535
+ const assertLocalHost = (req) => {
536
+ const raw = String(req.headers.host || '')
537
+ const hostname = raw.startsWith('[') ? raw.slice(1, raw.indexOf(']')) : raw.split(':')[0]
538
+ if (!hostname) throw fail('host header is required', 'LOCAL_VECTOR_BAD_HOST', 403)
539
+ if (!isLoopbackHostname(hostname)) throw fail('host header must be loopback', 'LOCAL_VECTOR_BAD_HOST', 403)
540
+ }
541
+ const assertAuthorized = (req) => {
542
+ if (tokenMatches(req.headers.authorization, token)) return
543
+ throw fail('missing or invalid bearer token', 'LOCAL_VECTOR_UNAUTHORIZED', 401)
544
+ }
545
+ const methodNotAllowed = (res, allowed) => {
546
+ sendJson(res, 405, errorBody(fail('method not allowed', 'LOCAL_VECTOR_METHOD_NOT_ALLOWED', 405)), { allow: allowed })
547
+ }
548
+
549
+ const respondHealth = (req, res) => {
550
+ if (req.method !== 'GET' && req.method !== 'HEAD') return methodNotAllowed(res, 'GET')
551
+ lastError = null
552
+ if (req.method === 'HEAD') {
553
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
554
+ res.end()
555
+ return
556
+ }
557
+ sendJson(res, 200, {
558
+ object: 'local_embedding_health',
559
+ status: 'ok',
560
+ ready: !closed,
561
+ model,
562
+ dimension,
563
+ maxBatch: batchLimit,
564
+ encodings: ENCODINGS,
565
+ rolesRequired,
566
+ uptimeMs: Date.now() - startedAt,
567
+ })
568
+ }
569
+
570
+ const respondEmbeddings = async (req, res) => {
571
+ if (req.method !== 'POST') return methodNotAllowed(res, 'POST')
572
+ const contentType = String(req.headers['content-type'] || '')
573
+ if (!/^application\/json\b/i.test(contentType)) {
574
+ throw fail('content-type must be application/json', 'LOCAL_VECTOR_UNSUPPORTED_MEDIA_TYPE', 415)
575
+ }
576
+ const declared = Number(req.headers['content-length'])
577
+ if (Number.isFinite(declared) && declared > bodyLimit) {
578
+ throw fail('request body exceeds ' + bodyLimit + ' bytes', 'LOCAL_VECTOR_BODY_TOO_LARGE', 413)
579
+ }
580
+ const raw = await readBody(req, bodyLimit)
581
+ let body = null
582
+ try { body = JSON.parse(raw) } catch { throw fail('request body is not valid JSON', 'LOCAL_VECTOR_BAD_REQUEST', 400) }
583
+ const { inputs, encoding, role } = parseEmbeddingRequest(body, { model, maxBatch: batchLimit, rolesRequired })
584
+ const encoded = await encodeVectors(applyRolePrefix(inputs, prefixes, role))
585
+ const vectors = encoded.vectors.map((vector, index) => assertVector(vector, dimension, index))
586
+ sendJson(res, 200, buildEmbeddingResponse({ model, vectors, encoding, usage: encoded.usage }))
587
+ lastError = null
588
+ }
589
+
590
+ const server = http.createServer((req, res) => {
591
+ const route = String(req.url || '/')
592
+ const serve = async () => {
593
+ assertLocalOrigin(req)
594
+ assertLocalHost(req)
595
+ assertAuthorized(req)
596
+ const pathname = new URL(route, 'http://127.0.0.1').pathname
597
+ if (pathname === HEALTH_PATH) return respondHealth(req, res)
598
+ if (pathname === EMBEDDINGS_PATH) return respondEmbeddings(req, res)
599
+ throw fail('unknown endpoint', 'LOCAL_VECTOR_NOT_FOUND', 404)
600
+ }
601
+ serve().catch((error) => {
602
+ noteFailure(error)
603
+ const status = errorStatus(error)
604
+ try {
605
+ logger.warn?.('[dsh-memu-memory] local embedding worker ' + status + ' ' + String((error && error.code) || 'LOCAL_VECTOR_ERROR') + ' ' + String((error && error.message) || error) + ' (' + pathnameOf(route) + ')')
606
+ } catch {}
607
+ sendJson(res, status, errorBody(error), status === 401 ? { 'www-authenticate': 'Bearer' } : null)
608
+ if (status === 413) res.on('finish', () => { try { req.destroy() } catch {} })
609
+ })
610
+ })
611
+ const pathnameOf = (route) => {
612
+ try { return new URL(route, 'http://127.0.0.1').pathname } catch { return '/' }
613
+ }
614
+ server.maxHeadersCount = 64
615
+ server.headersTimeout = 20_000
616
+ server.requestTimeout = 120_000
617
+ server.on('connection', (socket) => {
618
+ sockets.add(socket)
619
+ socket.on('close', () => sockets.delete(socket))
620
+ })
621
+
622
+ const close = async () => {
623
+ if (closed) return
624
+ closed = true
625
+ if (signal) signal.removeEventListener?.('abort', onAbort)
626
+ await new Promise((resolve) => {
627
+ try {
628
+ server.close(() => resolve())
629
+ } catch {
630
+ resolve()
631
+ }
632
+ for (const socket of sockets) {
633
+ try { socket.destroy() } catch {}
634
+ }
635
+ sockets.clear()
636
+ setTimeout(resolve, 2_000).unref?.()
637
+ })
638
+ if (encoder.close && !encoderClosed) {
639
+ encoderClosed = true
640
+ try { await encoder.close() } catch {}
641
+ }
642
+ }
643
+ const onAbort = () => { void close() }
644
+
645
+ await new Promise((resolve, reject) => {
646
+ const onError = (error) => {
647
+ server.removeListener('listening', onListening)
648
+ reject(fail('embedding worker could not listen on ' + host + ':' + port_ + ' (' + String((error && error.code) || error) + ')', 'LOCAL_VECTOR_LISTEN_FAILED', 503))
649
+ }
650
+ const onListening = () => {
651
+ server.removeListener('error', onError)
652
+ resolve()
653
+ }
654
+ server.once('error', onError)
655
+ server.once('listening', onListening)
656
+ server.listen(port_, host)
657
+ })
658
+
659
+ if (signal) {
660
+ if (signal.aborted) {
661
+ await close()
662
+ throw fail('embedding worker start aborted', 'LOCAL_VECTOR_ABORTED', 499)
663
+ }
664
+ signal.addEventListener?.('abort', onAbort, { once: true })
665
+ }
666
+
667
+ const address = server.address()
668
+ const actualPort = address && typeof address === 'object' ? address.port : port_
669
+ const hostForUrl = host === '::1' ? '[::1]' : host
670
+ const origin = 'http://' + hostForUrl + ':' + actualPort
671
+ const handle = {
672
+ baseUrl: origin + '/v1',
673
+ url: origin + EMBEDDINGS_PATH,
674
+ healthUrl: origin + HEALTH_PATH,
675
+ model,
676
+ dimension,
677
+ close,
678
+ }
679
+ Object.defineProperty(handle, 'lastError', { enumerable: true, get: () => lastError })
680
+ try { logger.info?.('[dsh-memu-memory] local embedding worker ready on ' + origin + ' model=' + model + ' dimension=' + dimension) } catch {}
681
+ return handle
682
+ }