@modusensus/dsh-mneme 0.8.2 → 0.8.4

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