@reftrixmcp/ml 0.1.7

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 (97) hide show
  1. package/LICENSE +661 -0
  2. package/dist/dinov2/index.d.ts +7 -0
  3. package/dist/dinov2/index.d.ts.map +1 -0
  4. package/dist/dinov2/index.js +7 -0
  5. package/dist/dinov2/index.js.map +1 -0
  6. package/dist/dinov2/service.d.ts +106 -0
  7. package/dist/dinov2/service.d.ts.map +1 -0
  8. package/dist/dinov2/service.js +446 -0
  9. package/dist/dinov2/service.js.map +1 -0
  10. package/dist/dinov2/worker-thread-types.d.ts +77 -0
  11. package/dist/dinov2/worker-thread-types.d.ts.map +1 -0
  12. package/dist/dinov2/worker-thread-types.js +4 -0
  13. package/dist/dinov2/worker-thread-types.js.map +1 -0
  14. package/dist/dinov2/worker-thread.d.ts +2 -0
  15. package/dist/dinov2/worker-thread.d.ts.map +1 -0
  16. package/dist/dinov2/worker-thread.js +231 -0
  17. package/dist/dinov2/worker-thread.js.map +1 -0
  18. package/dist/embeddings/index.d.ts +12 -0
  19. package/dist/embeddings/index.d.ts.map +1 -0
  20. package/dist/embeddings/index.js +13 -0
  21. package/dist/embeddings/index.js.map +1 -0
  22. package/dist/embeddings/multimodal-embedding.service.d.ts +400 -0
  23. package/dist/embeddings/multimodal-embedding.service.d.ts.map +1 -0
  24. package/dist/embeddings/multimodal-embedding.service.js +650 -0
  25. package/dist/embeddings/multimodal-embedding.service.js.map +1 -0
  26. package/dist/embeddings/service.d.ts +261 -0
  27. package/dist/embeddings/service.d.ts.map +1 -0
  28. package/dist/embeddings/service.js +1093 -0
  29. package/dist/embeddings/service.js.map +1 -0
  30. package/dist/embeddings/style-embedding.service.d.ts +117 -0
  31. package/dist/embeddings/style-embedding.service.d.ts.map +1 -0
  32. package/dist/embeddings/style-embedding.service.js +157 -0
  33. package/dist/embeddings/style-embedding.service.js.map +1 -0
  34. package/dist/embeddings/types.d.ts +83 -0
  35. package/dist/embeddings/types.d.ts.map +1 -0
  36. package/dist/embeddings/types.js +4 -0
  37. package/dist/embeddings/types.js.map +1 -0
  38. package/dist/embeddings/vision-embedding.service.d.ts +70 -0
  39. package/dist/embeddings/vision-embedding.service.d.ts.map +1 -0
  40. package/dist/embeddings/vision-embedding.service.js +221 -0
  41. package/dist/embeddings/vision-embedding.service.js.map +1 -0
  42. package/dist/embeddings/vision-embedding.types.d.ts +102 -0
  43. package/dist/embeddings/vision-embedding.types.d.ts.map +1 -0
  44. package/dist/embeddings/vision-embedding.types.js +4 -0
  45. package/dist/embeddings/vision-embedding.types.js.map +1 -0
  46. package/dist/embeddings/worker-thread-types.d.ts +152 -0
  47. package/dist/embeddings/worker-thread-types.d.ts.map +1 -0
  48. package/dist/embeddings/worker-thread-types.js +4 -0
  49. package/dist/embeddings/worker-thread-types.js.map +1 -0
  50. package/dist/embeddings/worker-thread.d.ts +4 -0
  51. package/dist/embeddings/worker-thread.d.ts.map +1 -0
  52. package/dist/embeddings/worker-thread.js +441 -0
  53. package/dist/embeddings/worker-thread.js.map +1 -0
  54. package/dist/index.d.ts +18 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.js +19 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/search/fulltext-helpers.d.ts +30 -0
  59. package/dist/search/fulltext-helpers.d.ts.map +1 -0
  60. package/dist/search/fulltext-helpers.js +40 -0
  61. package/dist/search/fulltext-helpers.js.map +1 -0
  62. package/dist/search/hybrid.d.ts +40 -0
  63. package/dist/search/hybrid.d.ts.map +1 -0
  64. package/dist/search/hybrid.js +61 -0
  65. package/dist/search/hybrid.js.map +1 -0
  66. package/dist/search/index.d.ts +12 -0
  67. package/dist/search/index.d.ts.map +1 -0
  68. package/dist/search/index.js +11 -0
  69. package/dist/search/index.js.map +1 -0
  70. package/dist/search/rrf.d.ts +69 -0
  71. package/dist/search/rrf.d.ts.map +1 -0
  72. package/dist/search/rrf.js +108 -0
  73. package/dist/search/rrf.js.map +1 -0
  74. package/dist/search/types.d.ts +130 -0
  75. package/dist/search/types.d.ts.map +1 -0
  76. package/dist/search/types.js +4 -0
  77. package/dist/search/types.js.map +1 -0
  78. package/package.json +65 -0
  79. package/src/dinov2/index.ts +21 -0
  80. package/src/dinov2/service.ts +539 -0
  81. package/src/dinov2/worker-thread-types.ts +103 -0
  82. package/src/dinov2/worker-thread.ts +306 -0
  83. package/src/embeddings/index.ts +74 -0
  84. package/src/embeddings/multimodal-embedding.service.ts +992 -0
  85. package/src/embeddings/service.ts +1287 -0
  86. package/src/embeddings/style-embedding.service.ts +201 -0
  87. package/src/embeddings/types.ts +95 -0
  88. package/src/embeddings/vision-embedding.service.ts +273 -0
  89. package/src/embeddings/vision-embedding.types.ts +117 -0
  90. package/src/embeddings/worker-thread-types.ts +194 -0
  91. package/src/embeddings/worker-thread.ts +529 -0
  92. package/src/index.ts +70 -0
  93. package/src/search/fulltext-helpers.ts +45 -0
  94. package/src/search/hybrid.ts +107 -0
  95. package/src/search/index.ts +25 -0
  96. package/src/search/rrf.ts +154 -0
  97. package/src/search/types.ts +141 -0
@@ -0,0 +1,261 @@
1
+ import type { EmbeddingTextType, EmbeddingServiceConfig, CacheStats } from "./types.js";
2
+ /**
3
+ * Default maximum cache size for LRU cache
4
+ * Prevents unbounded memory growth
5
+ */
6
+ export declare const DEFAULT_MAX_CACHE_SIZE = 5000;
7
+ /**
8
+ * Default number of inferences before recycling the ONNX pipeline.
9
+ *
10
+ * onnxruntime-node uses a native C++ arena allocator that grows monotonically
11
+ * during inference (~65-100MB per inference) but never returns memory to the OS.
12
+ * Pipeline recycling (dispose + recreate) tears down the InferenceSession via
13
+ * session.release(), which frees the arena's native memory back to the OS.
14
+ *
15
+ * With threshold=10, the arena is reset every 10 inferences, keeping peak
16
+ * additional native memory to ~650MB-1GB before each recycle. Model reload
17
+ * takes ~1.5-2s per recycle.
18
+ *
19
+ * v0.1.0: Reduced from 20 to 10 for universal embedding chunking.
20
+ * v0.1.0: Increased from 10 to 30 — chunking already limits items per chunk
21
+ * to 30, so threshold=30 means at most 1 recycle per chunk. With threshold=10,
22
+ * 3 recycles occurred per chunk, and model reload (~1.5-2s each) caused
23
+ * re-initialization overhead of ~45%. threshold=30 aligns with chunk size.
24
+ *
25
+ * Note: This project uses onnxruntime-node (native C++ bindings), NOT WASM.
26
+ * dispose() correctly frees native memory unlike WASM backing store pages.
27
+ */
28
+ export declare const DEFAULT_PIPELINE_RECYCLE_THRESHOLD = 30;
29
+ /**
30
+ * Calculate cosine similarity between two vectors
31
+ */
32
+ export declare function cosineSimilarity(a: number[], b: number[]): number;
33
+ /**
34
+ * EmbeddingService - Generates embeddings using multilingual-e5-base
35
+ *
36
+ * v0.1.0: ONNX inference is offloaded to a Worker Thread by default.
37
+ * The main thread retains the LRU cache and E5 prefix logic. Only the
38
+ * actual ONNX pipeline.call() runs in the worker, keeping the main
39
+ * event loop responsive for BullMQ heartbeats and IPC messages.
40
+ */
41
+ export declare class EmbeddingService {
42
+ private config;
43
+ private cache;
44
+ private cacheHits;
45
+ private cacheMisses;
46
+ private cacheEvictions;
47
+ private useWorkerThread;
48
+ private worker;
49
+ private workerInitPromise;
50
+ private workerReady;
51
+ private workerRestartCount;
52
+ private pendingRequests;
53
+ /** Timestamp of last worker crash, used to enforce cooldown between restarts. */
54
+ private lastCrashTime;
55
+ private currentProvider;
56
+ private idleTimer;
57
+ private idleTimeoutMs;
58
+ private pipeline;
59
+ private initPromise;
60
+ /**
61
+ * Number of inference calls since the last pipeline recycle.
62
+ * In worker-thread mode, the worker manages its own counter.
63
+ * In fallback mode, this counter is used directly.
64
+ */
65
+ private inferencesSinceRecycle;
66
+ /**
67
+ * Total number of pipeline recycles performed during this service's lifetime.
68
+ * In worker-thread mode, the count is approximate (tracked by dispose calls).
69
+ */
70
+ private totalRecycles;
71
+ constructor(config?: EmbeddingServiceConfig);
72
+ /**
73
+ * Spawn the worker thread and send init message.
74
+ * Enforces a cooldown after crashes to prevent rapid spawn-crash-spawn cycles
75
+ * that consume memory (~10GB per CUDA init attempt).
76
+ */
77
+ private ensureWorkerReady;
78
+ private spawnAndInitWorker;
79
+ /**
80
+ * Send a message to the worker and return a Promise for the response.
81
+ */
82
+ private sendWorkerMessage;
83
+ /**
84
+ * Route a response from the worker to the pending request's promise.
85
+ */
86
+ private handleWorkerResponse;
87
+ /**
88
+ * Handle worker thread crash: reject all pending requests, attempt restart.
89
+ */
90
+ private handleWorkerCrash;
91
+ /**
92
+ * Check if the worker can be restarted (under max restart limit).
93
+ */
94
+ private canRestartWorker;
95
+ /**
96
+ * Initialize the in-process embedding pipeline (lazy loading).
97
+ * Used when worker thread is disabled.
98
+ *
99
+ * If the configured device is 'cuda' but initialization fails (e.g. because
100
+ * LD_LIBRARY_PATH was not set at the OS level), automatically falls back to CPU.
101
+ */
102
+ private initializeInProcess;
103
+ /**
104
+ * Recycle the in-process pipeline if threshold reached.
105
+ */
106
+ private recyclePipelineIfNeeded;
107
+ /**
108
+ * Dispose the in-process pipeline.
109
+ */
110
+ private disposeInProcess;
111
+ /**
112
+ * Generate a single embedding in-process (fallback).
113
+ */
114
+ private generateInProcess;
115
+ /**
116
+ * Generate batch embeddings in-process (fallback).
117
+ */
118
+ private generateBatchInProcess;
119
+ /**
120
+ * Set the idle timeout for automatic VRAM release.
121
+ *
122
+ * When set to a positive value (ms), the service will automatically call
123
+ * dispose() after no embedding generation activity for the specified duration.
124
+ * This frees GPU VRAM (e.g. 1,406 MiB for multilingual-e5-base on CUDA)
125
+ * so that other GPU consumers (e.g. Ollama Vision at 11.7 GB) can use it.
126
+ *
127
+ * dispose() preserves the CUDA provider setting, so the next inference call
128
+ * will re-initialize with CUDA automatically (unlike releaseGpu() which
129
+ * forces CPU).
130
+ *
131
+ * @param ms - Timeout in milliseconds. 0 disables the idle timer.
132
+ */
133
+ setIdleTimeout(ms: number): void;
134
+ /**
135
+ * Reset the idle timer after an embedding generation completes.
136
+ * Called in finally blocks of generateEmbedding() and generateBatchEmbeddings().
137
+ */
138
+ private resetIdleTimer;
139
+ /**
140
+ * Check if the model is initialized (worker thread is ready or pipeline loaded).
141
+ */
142
+ isInitialized(): boolean;
143
+ /**
144
+ * Get the total number of pipeline recycles performed.
145
+ */
146
+ getRecycleCount(): number;
147
+ /**
148
+ * Get the number of inferences since the last pipeline recycle.
149
+ * In worker-thread mode this is approximate (tracked via dispose calls).
150
+ */
151
+ getInferencesSinceRecycle(): number;
152
+ /**
153
+ * Generate cache key for embedding
154
+ */
155
+ private getCacheKey;
156
+ /**
157
+ * Set cache entry with LRU eviction
158
+ */
159
+ private setCacheEntry;
160
+ /**
161
+ * Get cache entry with LRU update (move to end)
162
+ */
163
+ private getCacheEntry;
164
+ /**
165
+ * Generate embedding for a single text
166
+ *
167
+ * @param text - Input text to embed
168
+ * @param type - Type of text ('query' or 'passage')
169
+ * @returns 768-dimensional normalized embedding vector
170
+ */
171
+ generateEmbedding(text: string, type: EmbeddingTextType): Promise<number[]>;
172
+ /**
173
+ * Generate embedding via Worker Thread, with crash recovery.
174
+ */
175
+ private generateViaWorker;
176
+ /**
177
+ * Generate batch embeddings via Worker Thread, with crash recovery.
178
+ */
179
+ private generateBatchViaWorker;
180
+ /**
181
+ * Generate embeddings for multiple texts
182
+ *
183
+ * @param texts - Array of input texts
184
+ * @param type - Type of texts ('query' or 'passage')
185
+ * @returns Array of 768-dimensional normalized embedding vectors
186
+ */
187
+ generateBatchEmbeddings(texts: string[], type: EmbeddingTextType): Promise<number[][]>;
188
+ /**
189
+ * Dispose the ONNX pipeline to free native memory.
190
+ *
191
+ * In worker-thread mode, sends a dispose message to the worker.
192
+ * In fallback mode, disposes the in-process pipeline.
193
+ *
194
+ * After disposal, the next inference call will re-initialize automatically.
195
+ */
196
+ dispose(): Promise<void>;
197
+ /**
198
+ * Terminate the worker thread completely and clean up.
199
+ * After this, the service cannot be used until a new instance is created.
200
+ */
201
+ terminate(): Promise<void>;
202
+ /**
203
+ * Get cache statistics
204
+ */
205
+ getCacheStats(): CacheStats;
206
+ /**
207
+ * Clear the embedding cache
208
+ */
209
+ clearCache(): void;
210
+ /**
211
+ * Whether this service is using a Worker Thread for inference.
212
+ */
213
+ isUsingWorkerThread(): boolean;
214
+ /**
215
+ * Get the current ONNX execution provider ('cpu' or 'cuda').
216
+ */
217
+ getCurrentProvider(): "cpu" | "cuda";
218
+ /**
219
+ * Switch ONNX execution provider at runtime.
220
+ *
221
+ * In worker-thread mode: sends a switch-provider message to the worker,
222
+ * which disposes the current pipeline and updates the device config.
223
+ * In in-process mode: disposes the pipeline and updates the config
224
+ * so the next inference call re-initializes with the new provider.
225
+ *
226
+ * @param provider - The target execution provider ('cpu' or 'cuda').
227
+ * @returns true if the switch succeeded and the requested provider is now
228
+ * active; false if the switch was not possible (e.g. CUDA not
229
+ * available) — in that case the service remains on CPU.
230
+ */
231
+ switchProvider(provider: "cpu" | "cuda"): Promise<boolean>;
232
+ /**
233
+ * Switch provider via Worker Thread message.
234
+ */
235
+ private switchProviderViaWorker;
236
+ /**
237
+ * Switch provider in-process (fallback mode).
238
+ */
239
+ private switchProviderInProcess;
240
+ /**
241
+ * Release GPU resources by disposing the pipeline and switching to CPU.
242
+ *
243
+ * Safe to call even if already on CPU — acts as a dispose + ensures
244
+ * the provider is set to CPU.
245
+ */
246
+ releaseGpu(): Promise<void>;
247
+ /**
248
+ * Release GPU via Worker Thread message.
249
+ */
250
+ private releaseGpuViaWorker;
251
+ /**
252
+ * Release GPU in-process (fallback mode).
253
+ */
254
+ private releaseGpuInProcess;
255
+ /**
256
+ * Get the number of worker thread restarts that have occurred.
257
+ */
258
+ getWorkerRestartCount(): number;
259
+ }
260
+ export declare const embeddingService: EmbeddingService;
261
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/embeddings/service.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,YAAY,CA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