@modusensus/dsh-mneme 0.8.3 → 0.8.5

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 (205) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +727 -636
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +510 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +506 -316
  7. package/lib/api.js +1403 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4657 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +615 -510
  12. package/lib/document.js +221 -0
  13. package/lib/dream/clustering.js +118 -118
  14. package/lib/dream/decisions.js +658 -658
  15. package/lib/dream/narratives.js +44 -0
  16. package/lib/dream/sleep.js +702 -700
  17. package/lib/dream.js +147 -16
  18. package/lib/embedding.js +177 -177
  19. package/lib/entities/extractor.js +249 -249
  20. package/lib/guide.js +44 -0
  21. package/lib/heat.js +144 -136
  22. package/lib/hot-memory.js +46 -46
  23. package/lib/index.js +515 -515
  24. package/lib/inject.js +375 -295
  25. package/lib/lang.js +208 -179
  26. package/lib/local-embedder.js +320 -320
  27. package/lib/mirror.js +198 -198
  28. package/lib/organize.js +450 -0
  29. package/lib/quality-filter.js +126 -126
  30. package/lib/recall-stats.js +125 -0
  31. package/lib/reranker.js +269 -269
  32. package/lib/runtime/adopt.js +176 -176
  33. package/lib/runtime/closure.js +172 -172
  34. package/lib/runtime/download.js +247 -247
  35. package/lib/runtime/layout.js +265 -235
  36. package/lib/runtime/loader.js +252 -249
  37. package/lib/runtime/model-fetch.js +361 -361
  38. package/lib/runtime/provision.js +237 -237
  39. package/lib/runtime/tarball.js +130 -130
  40. package/lib/runtime/verify.js +204 -191
  41. package/lib/scope.js +118 -118
  42. package/lib/search/adaptive.js +60 -22
  43. package/lib/search/bm25.js +96 -96
  44. package/lib/service.js +2324 -2087
  45. package/lib/settings.js +459 -420
  46. package/lib/store.js +2549 -2367
  47. package/lib/summarize.js +820 -449
  48. package/lib/tools.js +702 -574
  49. package/lib/vector-index.js +110 -110
  50. package/lib/version-check.js +122 -122
  51. package/package.json +109 -108
  52. package/runtime-manifest.json +526 -596
  53. package/scripts/benchmark-embed.js +201 -201
  54. package/scripts/benchmark-recall.js +199 -199
  55. package/scripts/benchmark-rerank.js +166 -166
  56. package/scripts/build-runtime-manifest.mjs +224 -217
  57. package/scripts/check-sync.js +42 -42
  58. package/scripts/e2e-dsh.js +220 -220
  59. package/scripts/mneme-runtime.mjs +277 -277
  60. package/scripts/stress-dsh.js +255 -255
  61. package/scripts/sync-lib.js +47 -47
  62. package/scripts/sync-test-badge.mjs +67 -61
  63. package/src/api-standalone.js +506 -316
  64. package/src/api.js +1403 -1316
  65. package/src/bootstrap.js +211 -0
  66. package/src/commands.js +95 -95
  67. package/src/config.js +615 -510
  68. package/src/document.js +221 -0
  69. package/src/dream/clustering.js +118 -118
  70. package/src/dream/decisions.js +658 -658
  71. package/src/dream/narratives.js +44 -0
  72. package/src/dream/sleep.js +702 -700
  73. package/src/dream.js +147 -16
  74. package/src/embedding.js +177 -177
  75. package/src/entities/extractor.js +249 -249
  76. package/src/guide.js +44 -0
  77. package/src/heat.js +144 -136
  78. package/src/hot-memory.js +46 -46
  79. package/src/index.js +515 -515
  80. package/src/inject.js +375 -295
  81. package/src/lang.js +208 -179
  82. package/src/local-embedder.js +320 -320
  83. package/src/mirror.js +198 -198
  84. package/src/organize.js +450 -0
  85. package/src/quality-filter.js +126 -126
  86. package/src/recall-stats.js +125 -0
  87. package/src/reranker.js +269 -269
  88. package/src/runtime/adopt.js +176 -176
  89. package/src/runtime/closure.js +172 -172
  90. package/src/runtime/download.js +247 -247
  91. package/src/runtime/layout.js +265 -235
  92. package/src/runtime/loader.js +252 -249
  93. package/src/runtime/model-fetch.js +361 -361
  94. package/src/runtime/provision.js +237 -237
  95. package/src/runtime/tarball.js +130 -130
  96. package/src/runtime/verify.js +204 -191
  97. package/src/scope.js +118 -118
  98. package/src/search/adaptive.js +60 -22
  99. package/src/search/bm25.js +96 -96
  100. package/src/service.js +2324 -2087
  101. package/src/settings.js +459 -420
  102. package/src/store.js +2549 -2367
  103. package/src/summarize.js +820 -449
  104. package/src/tools.js +702 -574
  105. package/src/vector-index.js +110 -110
  106. package/src/version-check.js +122 -122
  107. package/test/adaptive-inject-budget.test.js +85 -0
  108. package/test/api-routes-gaps.test.js +218 -218
  109. package/test/api.test.js +1640 -1482
  110. package/test/audit.test.js +448 -448
  111. package/test/benchmark.test.js +94 -94
  112. package/test/bootstrap.test.js +220 -0
  113. package/test/client.test.js +860 -736
  114. package/test/clustering.test.js +100 -100
  115. package/test/commands.test.js +106 -106
  116. package/test/config.test.js +66 -66
  117. package/test/conflict-freeze.test.js +300 -300
  118. package/test/document.test.js +523 -0
  119. package/test/dream-archive-guardrail.test.js +116 -116
  120. package/test/dream-candidate-hybrid.test.js +281 -281
  121. package/test/dream-coverage-degrade.test.js +86 -86
  122. package/test/dream.test.js +1308 -1254
  123. package/test/embedding-ready.test.js +196 -196
  124. package/test/entities.test.js +547 -547
  125. package/test/entity-recall.test.js +179 -0
  126. package/test/epistemic.test.js +298 -298
  127. package/test/fnew-0112.test.js +311 -311
  128. package/test/fnew-03.test.js +422 -422
  129. package/test/graph-api.test.js +175 -175
  130. package/test/heat.test.js +175 -148
  131. package/test/helpers/dream-mock.js +82 -82
  132. package/test/helpers/peer-worker.mjs +25 -25
  133. package/test/helpers/runtime-source.js +60 -60
  134. package/test/helpers/tar-builder.js +80 -80
  135. package/test/hot-memory.test.js +145 -145
  136. package/test/inject-content-cap.test.js +91 -0
  137. package/test/inject-first-round-bm25.test.js +89 -89
  138. package/test/inject-heat.test.js +61 -0
  139. package/test/inject-pools.test.js +170 -0
  140. package/test/inject-recall.test.js +105 -0
  141. package/test/inject-rotation.test.js +161 -161
  142. package/test/inject.test.js +283 -249
  143. package/test/lang.test.js +87 -87
  144. package/test/lib-smoke.test.js +96 -96
  145. package/test/llm-audit.test.js +462 -309
  146. package/test/llm-message-source.test.js +177 -177
  147. package/test/local-embedder.test.js +249 -249
  148. package/test/mcp-stdio.test.js +385 -0
  149. package/test/mirror-dirty.test.js +424 -424
  150. package/test/mirror-edit-digest.test.js +187 -187
  151. package/test/mirror-generation.test.js +499 -499
  152. package/test/mirror.test.js +249 -249
  153. package/test/narrative-bars.test.js +162 -0
  154. package/test/organize.test.js +418 -0
  155. package/test/peer-blockers.test.js +193 -193
  156. package/test/policy-epoch.test.js +259 -259
  157. package/test/quality-filter.test.js +186 -186
  158. package/test/reasoning-effort.test.js +746 -746
  159. package/test/recall-evals.test.js +235 -235
  160. package/test/recall-layer.test.js +326 -326
  161. package/test/recall-stats.test.js +123 -0
  162. package/test/receipt-chain.test.js +451 -451
  163. package/test/reflection.test.js +226 -226
  164. package/test/reindex-backfill.test.js +62 -62
  165. package/test/reranker-single-logit.test.js +73 -73
  166. package/test/reranker.test.js +197 -197
  167. package/test/resident-status.test.js +83 -0
  168. package/test/runtime-adopt.test.js +206 -206
  169. package/test/runtime-cli.test.js +89 -89
  170. package/test/runtime-closure.test.js +193 -193
  171. package/test/runtime-download.test.js +302 -302
  172. package/test/runtime-layout.test.js +163 -163
  173. package/test/runtime-loader.test.js +255 -237
  174. package/test/runtime-manifest.test.js +159 -158
  175. package/test/runtime-model-fetch.test.js +348 -348
  176. package/test/runtime-provision.test.js +101 -101
  177. package/test/runtime-tarball.test.js +81 -81
  178. package/test/runtime-verify.test.js +279 -214
  179. package/test/scope-candidates.test.js +239 -239
  180. package/test/scope-explicit.test.js +452 -452
  181. package/test/scope-retrieval.test.js +197 -197
  182. package/test/scope-storage.test.js +255 -255
  183. package/test/scope-strict.test.js +231 -231
  184. package/test/search-fusion.test.js +90 -90
  185. package/test/semantic.test.js +124 -124
  186. package/test/service-search.test.js +174 -174
  187. package/test/service.test.js +405 -405
  188. package/test/settings.test.js +261 -261
  189. package/test/skip-invalid-restore.test.js +262 -262
  190. package/test/sleep-action-set.test.js +422 -422
  191. package/test/sleep-heat.test.js +126 -125
  192. package/test/sleep-scheduler-rearm.test.js +89 -89
  193. package/test/sleep.test.js +410 -373
  194. package/test/standalone-api.test.js +544 -359
  195. package/test/store-vector-cache.test.js +98 -98
  196. package/test/store.test.js +396 -383
  197. package/test/stress.test.js +209 -209
  198. package/test/summarize.test.js +1288 -575
  199. package/test/tools-dto-schema-matrix.test.js +325 -0
  200. package/test/tools-memory-get-schema.test.js +65 -65
  201. package/test/tools.test.js +374 -341
  202. package/test/updated-at-semantics.test.js +113 -113
  203. package/test/vector-index.test.js +221 -221
  204. package/test/version-check.test.js +152 -152
  205. package/test/webServer-optional.test.js +82 -82
@@ -1,320 +1,320 @@
1
- // Fully-local embedding backends for dsh-mneme: ONNX via transformers.js,
2
- // Ollama's HTTP API, and the OpenAI-compatible HTTP API (extracted from the
3
- // old embedding.js logic). All classes share one interface so the orchestrator
4
- // can pick a backend by provider name and degrade gracefully on failure.
5
- // Methods throw on error — the caller decides the fallback chain.
6
- import { defaultModelCacheDir, defaultRuntimeDir } from "./runtime/layout.js";
7
- import { installResilientFetch } from "./runtime/model-fetch.js";
8
- import { loadTransformers } from "./runtime/loader.js";
9
-
10
- const DEFAULT_TIMEOUT_MS = 15000;
11
-
12
- /** djb2 — stable, fast fingerprint for a provider/model string. */
13
- function hashString(s) {
14
- let h = 5381;
15
- for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
16
- return h.toString(16);
17
- }
18
-
19
- /** Full provider+model fingerprint used for index-consistency checks. */
20
- function modelHash(model) {
21
- return `${model}#${hashString(model)}`;
22
- }
23
-
24
- /**
25
- * Lazy default loader: dynamic import keeps module load cheap.
26
- *
27
- * 经 runtime/loader.js 的三层解析取运行时(自管 payload 优先,其次宿主裸 specifier):
28
- * 这样 PR-B 把 @huggingface/transformers 从 dependencies 摘掉、pnpm 把宿主那份 prune
29
- * 掉之后,本地嵌入仍然可用;而在那之前,宿主那份照样能被第 ② 层兜住。
30
- * runtimeDir 从 options 里取走后再传 pipeline,免得把插件自己的配置项混进
31
- * transformers 的选项里。
32
- */
33
- async function defaultPipelineLoader(task, model, options) {
34
- const { runtimeDir, remoteHost, resilientModelDownload, logger, ...pipelineOptions } = options ?? {};
35
- const { module } = await loadTransformers({
36
- runtimeDir: runtimeDir || defaultRuntimeDir()
37
- });
38
- const { env, pipeline } = module;
39
- // issue #13: transformers.js's get_tokenizer_files() drops the caller's
40
- // cache_dir when it pre-checks tokenizer_config.json metadata, so the HEAD
41
- // request falls back to env.cacheDir and hits the network even when the
42
- // model is fully cached locally. Mirroring the cache_dir onto env.cacheDir
43
- // makes that pre-check resolve locally too — fully offline loading.
44
- if (pipelineOptions.cache_dir) env.cacheDir = pipelineOptions.cache_dir;
45
- // issue #188 补充:embedModelMirror 此前是死配置(定义了但全仓无人读取)。
46
- // transformers.js 不认 HF_ENDPOINT(那是 Python huggingface_hub 的变量),
47
- // 模型下载源由 env.remoteHost 决定——把镜像接到真正的开关上,否则
48
- // huggingface.co 不可达的网络连模型都下不下来。
49
- if (remoteHost) env.remoteHost = remoteHost;
50
- // issue #194:模型文件(几百 MB~1GB)下载中断后从断点续传。开关关 = env.fetch 一字不动。
51
- installResilientFetch(env, {
52
- enabled: resilientModelDownload === true,
53
- cacheDir: pipelineOptions.cache_dir,
54
- logger
55
- });
56
- return pipeline(task, model, pipelineOptions);
57
- }
58
-
59
- /** Flatten a transformers.js Tensor [batch, dim] into number[][]. */
60
- function tensorToRows(tensor) {
61
- const { data, dims } = tensor;
62
- const rowLen = dims[dims.length - 1] || 0;
63
- const rows = [];
64
- for (let i = 0; i < data.length; i += rowLen) {
65
- rows.push(Array.from(data.subarray(i, i + rowLen)));
66
- }
67
- // Single-text input may come back without the batch axis.
68
- if (rows.length === 0 && rowLen > 0) rows.push(Array.from(data));
69
- return rows;
70
- }
71
-
72
- /**
73
- * ONNX text embedder backed by transformers.js (onnxruntime-node underneath).
74
- * Runs fully offline with mean pooling + L2 normalization for BERT-style
75
- * models like bge-small-zh. `engineFactory` is injectable for tests.
76
- */
77
- export class LocalEmbedder {
78
- constructor(opts = {}) {
79
- this.model = opts.model || "Xenova/bge-small-zh-v1.5";
80
- this._dimension = opts.dimension || 512;
81
- this.device = opts.device || "cpu";
82
- this.batchSize = opts.batchSize || 8;
83
- this.cacheDir = String(opts.cacheDir ?? "").trim() || defaultModelCacheDir();
84
- // 自管运行时根目录(issue #131):空表示用默认位置,具体解析交给 loader。
85
- this.runtimeDir = String(opts.runtimeDir ?? "").trim();
86
- // issue #194:模型文件下载断点续传。只在显式传 true 时启用——直连构造的旧调用方
87
- // (含测试)保持裸 fetch 的现状,配置默认值由 index.js 传进来。
88
- this.resilientModelDownload = opts.resilientModelDownload === true;
89
- this.useDtype = opts.useDtype || "q8";
90
- // 模型镜像下载源(embedModelMirror,#188 补充):空 = transformers 默认。
91
- this.remoteHost = String(opts.remoteHost ?? "").trim();
92
- this.logger = opts.logger ?? null;
93
- // Test hook: replace the pipeline factory without touching modules.
94
- this.engineFactory = opts.engineFactory || defaultPipelineLoader;
95
- this.extractor = null;
96
- // issue #6: readiness flag for the service's scheduleEmbed gate. False until
97
- // init() succeeds, so "ready" in embedder is observable even pre-init.
98
- this.ready = false;
99
- }
100
-
101
- /** Load the model; throws when it cannot be loaded. Idempotent. */
102
- async init() {
103
- if (this.extractor) return this; // already initialized: no-op
104
- const options = {
105
- dtype: this.useDtype,
106
- device: this.device
107
- };
108
- if (this.cacheDir) options.cache_dir = this.cacheDir;
109
- // 传给注入的 engineFactory,由 defaultPipelineLoader 取走后交给三层解析。
110
- if (this.runtimeDir) options.runtimeDir = this.runtimeDir;
111
- if (this.remoteHost) options.remoteHost = this.remoteHost;
112
- options.resilientModelDownload = this.resilientModelDownload;
113
- options.logger = this.logger;
114
- this.extractor = await this.engineFactory("feature-extraction", this.model, options);
115
- this.ready = true; // service reads this to flush queued re-embeds
116
- this.logger?.info?.(
117
- `[dsh-mneme] local embedder ready: ${this.model} (dim=${this._dimension}, device=${this.device})`
118
- );
119
- return this;
120
- }
121
-
122
- /** Embed many texts with mean pooling; chunks at batchSize. */
123
- async embed(texts) {
124
- if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
125
- if (!this.extractor) throw new Error("LocalEmbedder not initialized");
126
- const out = [];
127
- for (let i = 0; i < texts.length; i += this.batchSize) {
128
- const chunk = texts.slice(i, i + this.batchSize);
129
- const tensor = await this.extractor(chunk, { pooling: "mean", normalize: true });
130
- out.push(...tensorToRows(tensor));
131
- }
132
- return out;
133
- }
134
-
135
- async embedSingle(text) {
136
- const rows = await this.embed([String(text)]);
137
- return rows[0];
138
- }
139
-
140
- get dimension() {
141
- return this._dimension;
142
- }
143
-
144
- get modelHash() {
145
- return modelHash(this.model);
146
- }
147
-
148
- dispose() {
149
- try {
150
- this.extractor?.dispose?.();
151
- } catch {
152
- // best-effort: some engines free resources on GC
153
- }
154
- this.extractor = null;
155
- this.ready = false;
156
- }
157
- }
158
-
159
- /** Chunk texts into batches of at most `size`. */
160
- function chunk(texts, size) {
161
- const out = [];
162
- for (let i = 0; i < texts.length; i += size) out.push(texts.slice(i, i + size));
163
- return out;
164
- }
165
-
166
- /**
167
- * Ollama embedder over its native HTTP API. `dimension` is inferred from the
168
- * first response. init() verifies reachability and that the model exists.
169
- */
170
- export class OllamaEmbedder {
171
- constructor(opts = {}) {
172
- this.baseUrl = String(opts.baseUrl ?? "http://localhost:11434").trim().replace(/\/+$/, "");
173
- this.model = String(opts.model ?? "nomic-embed-text").trim();
174
- this.logger = opts.logger ?? null;
175
- this._dimension = null;
176
- // #118: async-init embedders expose `ready` so the service queues re-embeds
177
- // until init lands and the status card can show "initializing".
178
- this.ready = false;
179
- }
180
-
181
- async _post(body) {
182
- return fetch(`${this.baseUrl}/api/embeddings`, {
183
- method: "POST",
184
- headers: { "Content-Type": "application/json" },
185
- body: JSON.stringify(body),
186
- signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS)
187
- });
188
- }
189
-
190
- /** Probe the server with a tiny prompt; throws when unreachable/missing. */
191
- async init() {
192
- const res = await this._post({ model: this.model, prompt: "ping" });
193
- if (!res.ok) throw new Error(`Ollama ${this.model} unavailable: HTTP ${res.status}`);
194
- const body = await res.json();
195
- if (!Array.isArray(body?.embedding)) throw new Error(`Ollama ${this.model} returned no embedding`);
196
- this._dimension = body.embedding.length;
197
- this.ready = true;
198
- this.logger?.info?.(
199
- `[dsh-mneme] ollama embedder ready: ${this.model} (dim=${this._dimension})`
200
- );
201
- return this;
202
- }
203
-
204
- async embed(texts) {
205
- if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
206
- const out = [];
207
- for (const text of texts) out.push(await this.embedSingle(text));
208
- return out;
209
- }
210
-
211
- async embedSingle(text) {
212
- const res = await this._post({ model: this.model, prompt: String(text).slice(0, 8000) });
213
- if (!res.ok) throw new Error(`Ollama embed failed: HTTP ${res.status}`);
214
- const body = await res.json();
215
- const vec = body?.embedding;
216
- if (!Array.isArray(vec) || !vec.length) throw new Error("Ollama returned no embedding");
217
- if (this._dimension == null) this._dimension = vec.length;
218
- return Array.from(vec);
219
- }
220
-
221
- get dimension() {
222
- return this._dimension ?? 0;
223
- }
224
-
225
- get modelHash() {
226
- return modelHash(this.model);
227
- }
228
-
229
- dispose() {
230
- this._dimension = null;
231
- }
232
- }
233
-
234
- /**
235
- * OpenAI-compatible embedder (OpenAI, SiliconFlow, Zhipu, local proxies).
236
- * Backward-compatible behavior lifted from embedding.js, but batchable and
237
- * throwing on failure instead of returning null.
238
- */
239
- export class OpenAIEmbedder {
240
- constructor(opts = {}) {
241
- this.baseUrl = String(opts.baseUrl ?? "").trim().replace(/\/+$/, "");
242
- this.apiKey = String(opts.apiKey ?? "").trim();
243
- this.model = String(opts.model ?? "").trim();
244
- this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
245
- this.logger = opts.logger ?? null;
246
- this._dimension = null;
247
- // Accept both "https://host/v1" and a full path ending in /embeddings.
248
- this._url = /\/embeddings$/i.test(this.baseUrl)
249
- ? this.baseUrl
250
- : this.baseUrl ? `${this.baseUrl}/embeddings` : "";
251
- }
252
-
253
- async init() {
254
- if (!this._url || !this.apiKey || !this.model) {
255
- throw new Error("OpenAI embedder requires baseUrl, apiKey and model");
256
- }
257
- this.logger?.info?.(`[dsh-mneme] openai embedder ready: ${this.model}`);
258
- return this;
259
- }
260
-
261
- async embed(texts) {
262
- if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
263
- const out = [];
264
- for (const batch of chunk(texts, 32)) {
265
- const res = await fetch(this._url, {
266
- method: "POST",
267
- headers: {
268
- "Content-Type": "application/json",
269
- "Authorization": `Bearer ${this.apiKey}`
270
- },
271
- body: JSON.stringify({ model: this.model, input: batch.map((t) => String(t).slice(0, 8000)) }),
272
- signal: AbortSignal.timeout(this.timeoutMs)
273
- });
274
- if (!res.ok) throw new Error(`Embedding API failed: HTTP ${res.status}`);
275
- const body = await res.json();
276
- const list = body?.data;
277
- if (!Array.isArray(list) || list.length !== batch.length) {
278
- throw new Error("Embedding API returned unexpected payload");
279
- }
280
- for (const item of list) {
281
- const vec = item?.embedding;
282
- if (!Array.isArray(vec) || !vec.length) throw new Error("Embedding API returned empty vector");
283
- if (this._dimension == null) this._dimension = vec.length;
284
- out.push(Array.from(vec));
285
- }
286
- }
287
- return out;
288
- }
289
-
290
- async embedSingle(text) {
291
- const rows = await this.embed([String(text)]);
292
- return rows[0];
293
- }
294
-
295
- get dimension() {
296
- return this._dimension ?? 0;
297
- }
298
-
299
- get modelHash() {
300
- return modelHash(this.model);
301
- }
302
-
303
- dispose() {
304
- this._dimension = null;
305
- }
306
- }
307
-
308
- /** Pick a backend instance by provider name. Throws on unknown providers. */
309
- export function createEmbedderByProvider(provider, opts) {
310
- switch (String(provider ?? "").toLowerCase()) {
311
- case "local":
312
- return new LocalEmbedder(opts);
313
- case "ollama":
314
- return new OllamaEmbedder(opts);
315
- case "openai":
316
- return new OpenAIEmbedder(opts);
317
- default:
318
- throw new Error(`Unknown embedding provider: ${provider}`);
319
- }
320
- }
1
+ // Fully-local embedding backends for dsh-mneme: ONNX via transformers.js,
2
+ // Ollama's HTTP API, and the OpenAI-compatible HTTP API (extracted from the
3
+ // old embedding.js logic). All classes share one interface so the orchestrator
4
+ // can pick a backend by provider name and degrade gracefully on failure.
5
+ // Methods throw on error — the caller decides the fallback chain.
6
+ import { defaultModelCacheDir, defaultRuntimeDir } from "./runtime/layout.js";
7
+ import { installResilientFetch } from "./runtime/model-fetch.js";
8
+ import { loadTransformers } from "./runtime/loader.js";
9
+
10
+ const DEFAULT_TIMEOUT_MS = 15000;
11
+
12
+ /** djb2 — stable, fast fingerprint for a provider/model string. */
13
+ function hashString(s) {
14
+ let h = 5381;
15
+ for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
16
+ return h.toString(16);
17
+ }
18
+
19
+ /** Full provider+model fingerprint used for index-consistency checks. */
20
+ function modelHash(model) {
21
+ return `${model}#${hashString(model)}`;
22
+ }
23
+
24
+ /**
25
+ * Lazy default loader: dynamic import keeps module load cheap.
26
+ *
27
+ * 经 runtime/loader.js 的三层解析取运行时(自管 payload 优先,其次宿主裸 specifier):
28
+ * 这样 PR-B 把 @huggingface/transformers 从 dependencies 摘掉、pnpm 把宿主那份 prune
29
+ * 掉之后,本地嵌入仍然可用;而在那之前,宿主那份照样能被第 ② 层兜住。
30
+ * runtimeDir 从 options 里取走后再传 pipeline,免得把插件自己的配置项混进
31
+ * transformers 的选项里。
32
+ */
33
+ async function defaultPipelineLoader(task, model, options) {
34
+ const { runtimeDir, remoteHost, resilientModelDownload, logger, ...pipelineOptions } = options ?? {};
35
+ const { module } = await loadTransformers({
36
+ runtimeDir: runtimeDir || defaultRuntimeDir()
37
+ });
38
+ const { env, pipeline } = module;
39
+ // issue #13: transformers.js's get_tokenizer_files() drops the caller's
40
+ // cache_dir when it pre-checks tokenizer_config.json metadata, so the HEAD
41
+ // request falls back to env.cacheDir and hits the network even when the
42
+ // model is fully cached locally. Mirroring the cache_dir onto env.cacheDir
43
+ // makes that pre-check resolve locally too — fully offline loading.
44
+ if (pipelineOptions.cache_dir) env.cacheDir = pipelineOptions.cache_dir;
45
+ // issue #188 补充:embedModelMirror 此前是死配置(定义了但全仓无人读取)。
46
+ // transformers.js 不认 HF_ENDPOINT(那是 Python huggingface_hub 的变量),
47
+ // 模型下载源由 env.remoteHost 决定——把镜像接到真正的开关上,否则
48
+ // huggingface.co 不可达的网络连模型都下不下来。
49
+ if (remoteHost) env.remoteHost = remoteHost;
50
+ // issue #194:模型文件(几百 MB~1GB)下载中断后从断点续传。开关关 = env.fetch 一字不动。
51
+ installResilientFetch(env, {
52
+ enabled: resilientModelDownload === true,
53
+ cacheDir: pipelineOptions.cache_dir,
54
+ logger
55
+ });
56
+ return pipeline(task, model, pipelineOptions);
57
+ }
58
+
59
+ /** Flatten a transformers.js Tensor [batch, dim] into number[][]. */
60
+ function tensorToRows(tensor) {
61
+ const { data, dims } = tensor;
62
+ const rowLen = dims[dims.length - 1] || 0;
63
+ const rows = [];
64
+ for (let i = 0; i < data.length; i += rowLen) {
65
+ rows.push(Array.from(data.subarray(i, i + rowLen)));
66
+ }
67
+ // Single-text input may come back without the batch axis.
68
+ if (rows.length === 0 && rowLen > 0) rows.push(Array.from(data));
69
+ return rows;
70
+ }
71
+
72
+ /**
73
+ * ONNX text embedder backed by transformers.js (onnxruntime-node underneath).
74
+ * Runs fully offline with mean pooling + L2 normalization for BERT-style
75
+ * models like bge-small-zh. `engineFactory` is injectable for tests.
76
+ */
77
+ export class LocalEmbedder {
78
+ constructor(opts = {}) {
79
+ this.model = opts.model || "Xenova/bge-small-zh-v1.5";
80
+ this._dimension = opts.dimension || 512;
81
+ this.device = opts.device || "cpu";
82
+ this.batchSize = opts.batchSize || 8;
83
+ this.cacheDir = String(opts.cacheDir ?? "").trim() || defaultModelCacheDir();
84
+ // 自管运行时根目录(issue #131):空表示用默认位置,具体解析交给 loader。
85
+ this.runtimeDir = String(opts.runtimeDir ?? "").trim();
86
+ // issue #194:模型文件下载断点续传。只在显式传 true 时启用——直连构造的旧调用方
87
+ // (含测试)保持裸 fetch 的现状,配置默认值由 index.js 传进来。
88
+ this.resilientModelDownload = opts.resilientModelDownload === true;
89
+ this.useDtype = opts.useDtype || "q8";
90
+ // 模型镜像下载源(embedModelMirror,#188 补充):空 = transformers 默认。
91
+ this.remoteHost = String(opts.remoteHost ?? "").trim();
92
+ this.logger = opts.logger ?? null;
93
+ // Test hook: replace the pipeline factory without touching modules.
94
+ this.engineFactory = opts.engineFactory || defaultPipelineLoader;
95
+ this.extractor = null;
96
+ // issue #6: readiness flag for the service's scheduleEmbed gate. False until
97
+ // init() succeeds, so "ready" in embedder is observable even pre-init.
98
+ this.ready = false;
99
+ }
100
+
101
+ /** Load the model; throws when it cannot be loaded. Idempotent. */
102
+ async init() {
103
+ if (this.extractor) return this; // already initialized: no-op
104
+ const options = {
105
+ dtype: this.useDtype,
106
+ device: this.device
107
+ };
108
+ if (this.cacheDir) options.cache_dir = this.cacheDir;
109
+ // 传给注入的 engineFactory,由 defaultPipelineLoader 取走后交给三层解析。
110
+ if (this.runtimeDir) options.runtimeDir = this.runtimeDir;
111
+ if (this.remoteHost) options.remoteHost = this.remoteHost;
112
+ options.resilientModelDownload = this.resilientModelDownload;
113
+ options.logger = this.logger;
114
+ this.extractor = await this.engineFactory("feature-extraction", this.model, options);
115
+ this.ready = true; // service reads this to flush queued re-embeds
116
+ this.logger?.info?.(
117
+ `[dsh-mneme] local embedder ready: ${this.model} (dim=${this._dimension}, device=${this.device})`
118
+ );
119
+ return this;
120
+ }
121
+
122
+ /** Embed many texts with mean pooling; chunks at batchSize. */
123
+ async embed(texts) {
124
+ if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
125
+ if (!this.extractor) throw new Error("LocalEmbedder not initialized");
126
+ const out = [];
127
+ for (let i = 0; i < texts.length; i += this.batchSize) {
128
+ const chunk = texts.slice(i, i + this.batchSize);
129
+ const tensor = await this.extractor(chunk, { pooling: "mean", normalize: true });
130
+ out.push(...tensorToRows(tensor));
131
+ }
132
+ return out;
133
+ }
134
+
135
+ async embedSingle(text) {
136
+ const rows = await this.embed([String(text)]);
137
+ return rows[0];
138
+ }
139
+
140
+ get dimension() {
141
+ return this._dimension;
142
+ }
143
+
144
+ get modelHash() {
145
+ return modelHash(this.model);
146
+ }
147
+
148
+ dispose() {
149
+ try {
150
+ this.extractor?.dispose?.();
151
+ } catch {
152
+ // best-effort: some engines free resources on GC
153
+ }
154
+ this.extractor = null;
155
+ this.ready = false;
156
+ }
157
+ }
158
+
159
+ /** Chunk texts into batches of at most `size`. */
160
+ function chunk(texts, size) {
161
+ const out = [];
162
+ for (let i = 0; i < texts.length; i += size) out.push(texts.slice(i, i + size));
163
+ return out;
164
+ }
165
+
166
+ /**
167
+ * Ollama embedder over its native HTTP API. `dimension` is inferred from the
168
+ * first response. init() verifies reachability and that the model exists.
169
+ */
170
+ export class OllamaEmbedder {
171
+ constructor(opts = {}) {
172
+ this.baseUrl = String(opts.baseUrl ?? "http://localhost:11434").trim().replace(/\/+$/, "");
173
+ this.model = String(opts.model ?? "nomic-embed-text").trim();
174
+ this.logger = opts.logger ?? null;
175
+ this._dimension = null;
176
+ // #118: async-init embedders expose `ready` so the service queues re-embeds
177
+ // until init lands and the status card can show "initializing".
178
+ this.ready = false;
179
+ }
180
+
181
+ async _post(body) {
182
+ return fetch(`${this.baseUrl}/api/embeddings`, {
183
+ method: "POST",
184
+ headers: { "Content-Type": "application/json" },
185
+ body: JSON.stringify(body),
186
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS)
187
+ });
188
+ }
189
+
190
+ /** Probe the server with a tiny prompt; throws when unreachable/missing. */
191
+ async init() {
192
+ const res = await this._post({ model: this.model, prompt: "ping" });
193
+ if (!res.ok) throw new Error(`Ollama ${this.model} unavailable: HTTP ${res.status}`);
194
+ const body = await res.json();
195
+ if (!Array.isArray(body?.embedding)) throw new Error(`Ollama ${this.model} returned no embedding`);
196
+ this._dimension = body.embedding.length;
197
+ this.ready = true;
198
+ this.logger?.info?.(
199
+ `[dsh-mneme] ollama embedder ready: ${this.model} (dim=${this._dimension})`
200
+ );
201
+ return this;
202
+ }
203
+
204
+ async embed(texts) {
205
+ if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
206
+ const out = [];
207
+ for (const text of texts) out.push(await this.embedSingle(text));
208
+ return out;
209
+ }
210
+
211
+ async embedSingle(text) {
212
+ const res = await this._post({ model: this.model, prompt: String(text).slice(0, 8000) });
213
+ if (!res.ok) throw new Error(`Ollama embed failed: HTTP ${res.status}`);
214
+ const body = await res.json();
215
+ const vec = body?.embedding;
216
+ if (!Array.isArray(vec) || !vec.length) throw new Error("Ollama returned no embedding");
217
+ if (this._dimension == null) this._dimension = vec.length;
218
+ return Array.from(vec);
219
+ }
220
+
221
+ get dimension() {
222
+ return this._dimension ?? 0;
223
+ }
224
+
225
+ get modelHash() {
226
+ return modelHash(this.model);
227
+ }
228
+
229
+ dispose() {
230
+ this._dimension = null;
231
+ }
232
+ }
233
+
234
+ /**
235
+ * OpenAI-compatible embedder (OpenAI, SiliconFlow, Zhipu, local proxies).
236
+ * Backward-compatible behavior lifted from embedding.js, but batchable and
237
+ * throwing on failure instead of returning null.
238
+ */
239
+ export class OpenAIEmbedder {
240
+ constructor(opts = {}) {
241
+ this.baseUrl = String(opts.baseUrl ?? "").trim().replace(/\/+$/, "");
242
+ this.apiKey = String(opts.apiKey ?? "").trim();
243
+ this.model = String(opts.model ?? "").trim();
244
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
245
+ this.logger = opts.logger ?? null;
246
+ this._dimension = null;
247
+ // Accept both "https://host/v1" and a full path ending in /embeddings.
248
+ this._url = /\/embeddings$/i.test(this.baseUrl)
249
+ ? this.baseUrl
250
+ : this.baseUrl ? `${this.baseUrl}/embeddings` : "";
251
+ }
252
+
253
+ async init() {
254
+ if (!this._url || !this.apiKey || !this.model) {
255
+ throw new Error("OpenAI embedder requires baseUrl, apiKey and model");
256
+ }
257
+ this.logger?.info?.(`[dsh-mneme] openai embedder ready: ${this.model}`);
258
+ return this;
259
+ }
260
+
261
+ async embed(texts) {
262
+ if (!Array.isArray(texts)) throw new TypeError("embed expects an array of strings");
263
+ const out = [];
264
+ for (const batch of chunk(texts, 32)) {
265
+ const res = await fetch(this._url, {
266
+ method: "POST",
267
+ headers: {
268
+ "Content-Type": "application/json",
269
+ "Authorization": `Bearer ${this.apiKey}`
270
+ },
271
+ body: JSON.stringify({ model: this.model, input: batch.map((t) => String(t).slice(0, 8000)) }),
272
+ signal: AbortSignal.timeout(this.timeoutMs)
273
+ });
274
+ if (!res.ok) throw new Error(`Embedding API failed: HTTP ${res.status}`);
275
+ const body = await res.json();
276
+ const list = body?.data;
277
+ if (!Array.isArray(list) || list.length !== batch.length) {
278
+ throw new Error("Embedding API returned unexpected payload");
279
+ }
280
+ for (const item of list) {
281
+ const vec = item?.embedding;
282
+ if (!Array.isArray(vec) || !vec.length) throw new Error("Embedding API returned empty vector");
283
+ if (this._dimension == null) this._dimension = vec.length;
284
+ out.push(Array.from(vec));
285
+ }
286
+ }
287
+ return out;
288
+ }
289
+
290
+ async embedSingle(text) {
291
+ const rows = await this.embed([String(text)]);
292
+ return rows[0];
293
+ }
294
+
295
+ get dimension() {
296
+ return this._dimension ?? 0;
297
+ }
298
+
299
+ get modelHash() {
300
+ return modelHash(this.model);
301
+ }
302
+
303
+ dispose() {
304
+ this._dimension = null;
305
+ }
306
+ }
307
+
308
+ /** Pick a backend instance by provider name. Throws on unknown providers. */
309
+ export function createEmbedderByProvider(provider, opts) {
310
+ switch (String(provider ?? "").toLowerCase()) {
311
+ case "local":
312
+ return new LocalEmbedder(opts);
313
+ case "ollama":
314
+ return new OllamaEmbedder(opts);
315
+ case "openai":
316
+ return new OpenAIEmbedder(opts);
317
+ default:
318
+ throw new Error(`Unknown embedding provider: ${provider}`);
319
+ }
320
+ }