agent-working-memory 0.8.5 → 0.8.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 (53) hide show
  1. package/README.md +4 -2
  2. package/dist/adapters/common.d.ts.map +1 -1
  3. package/dist/adapters/common.js +108 -8
  4. package/dist/adapters/common.js.map +1 -1
  5. package/dist/api/routes.js +1 -1
  6. package/dist/cli/migrate.js +29 -29
  7. package/dist/cli.js +1 -1
  8. package/dist/coordination/circuit-breaker.js +23 -23
  9. package/dist/core/lite-compress.d.ts +26 -0
  10. package/dist/core/lite-compress.d.ts.map +1 -0
  11. package/dist/core/lite-compress.js +105 -0
  12. package/dist/core/lite-compress.js.map +1 -0
  13. package/dist/mcp.d.ts +5 -1
  14. package/dist/mcp.d.ts.map +1 -1
  15. package/dist/mcp.js +58 -4
  16. package/dist/mcp.js.map +1 -1
  17. package/dist/storage/pglite-schema.js +143 -143
  18. package/dist/storage/pglite.js +138 -138
  19. package/package.json +4 -3
  20. package/src/adapters/common.ts +108 -8
  21. package/src/api/index.ts +3 -3
  22. package/src/api/routes.ts +1 -1
  23. package/src/cli/migrate.ts +307 -307
  24. package/src/cli.ts +1 -1
  25. package/src/coordination/circuit-breaker.ts +83 -83
  26. package/src/coordination/failure-modes.ts +50 -50
  27. package/src/core/decay.ts +63 -63
  28. package/src/core/embeddings.ts +110 -110
  29. package/src/core/index.ts +5 -5
  30. package/src/core/lite-compress.ts +129 -0
  31. package/src/core/logger.ts +36 -36
  32. package/src/core/ml-worker-entry.ts +194 -194
  33. package/src/core/ml-worker.ts +281 -281
  34. package/src/core/query-expander.ts +122 -122
  35. package/src/core/reranker.ts +119 -119
  36. package/src/engine/confidence.ts +120 -120
  37. package/src/engine/connections.ts +162 -162
  38. package/src/engine/consolidation-scheduler.ts +242 -242
  39. package/src/engine/eval.ts +102 -102
  40. package/src/engine/eviction.ts +101 -101
  41. package/src/engine/index.ts +8 -8
  42. package/src/engine/retraction.ts +366 -366
  43. package/src/engine/staging.ts +74 -74
  44. package/src/mcp.ts +70 -4
  45. package/src/storage/factory.ts +147 -147
  46. package/src/storage/index.ts +3 -3
  47. package/src/storage/pglite-schema.ts +166 -166
  48. package/src/storage/pglite.ts +1363 -1363
  49. package/src/storage/store.ts +80 -80
  50. package/src/types/agent.ts +67 -67
  51. package/src/types/checkpoint.ts +46 -46
  52. package/src/types/eval.ts +100 -100
  53. package/src/types/index.ts +6 -6
@@ -1,281 +1,281 @@
1
- // Copyright 2026 Robert Winter / Complete Ideas
2
- // SPDX-License-Identifier: Apache-2.0
3
- /**
4
- * ML inference dispatch pool.
5
- *
6
- * STATUS (AWM 0.8.x P1 REVISE, 2026-05-25): worker_threads were the original
7
- * plan, but @huggingface/transformers in Node only supports the `cpu`
8
- * (native ONNX) and `dml` (Windows GPU) backends. Neither is safe inside
9
- * a worker_thread — onnxruntime-node's native bindings store V8 handles
10
- * that get invalidated when crossing isolate boundaries, causing
11
- * `v8::HandleScope::CreateHandle()` crashes on first inference call.
12
- * The browser-only `wasm` backend is not loaded in Node builds of
13
- * transformers.js.
14
- *
15
- * The dispatch abstraction is preserved so a future child_process pool
16
- * or HTTP sidecar (see AWM_ML_SIDECAR_URL design in docs/awm-architecture-history.md)
17
- * can plug in. For now ALL inference runs in-process. The freeze fix from
18
- * P0 (sleep-only consolidation) already eliminates the multi-second
19
- * in-band blocks. Individual inference calls (~50ms each) on the main
20
- * thread are accepted as-is.
21
- *
22
- * Test / dev mode: AWM_ML_INPROCESS=1 is honored but is now the default.
23
- * The env var remains as a no-op for backwards compatibility.
24
- */
25
-
26
- import { Worker } from 'node:worker_threads';
27
- import { fileURLToPath } from 'node:url';
28
- import { dirname, join } from 'node:path';
29
- import { existsSync } from 'node:fs';
30
-
31
- type WorkerRole = 'embed' | 'rerank' | 'expand';
32
-
33
- interface PendingRequest {
34
- resolve: (value: any) => void;
35
- reject: (err: Error) => void;
36
- timeoutHandle?: ReturnType<typeof setTimeout>;
37
- }
38
-
39
- interface ManagedWorker {
40
- role: WorkerRole;
41
- worker: Worker | null;
42
- ready: Promise<void>;
43
- setReady: () => void;
44
- setFailed: (err: Error) => void;
45
- pending: Map<number, PendingRequest>;
46
- buffered: Array<{ id: number; op: WorkerRole; args: any }>;
47
- isReady: boolean;
48
- restartTimestamps: number[]; // unix-ms of recent restarts (for backoff cap)
49
- }
50
-
51
- let inProcessMode = false;
52
- let workers: Record<WorkerRole, ManagedWorker> | null = null;
53
- let nextId = 1;
54
-
55
- // In-process fallback handles (used in tests and as crash escape hatch).
56
- let inProcessEmbed: ((args: any) => Promise<number[][]>) | null = null;
57
- let inProcessRerank: ((args: any) => Promise<Array<{ index: number; score: number }>>) | null = null;
58
- let inProcessExpand: ((args: any) => Promise<string>) | null = null;
59
-
60
- const REQUEST_TIMEOUT_MS = 60_000; // any single inference call > 60s is treated as failed
61
- const MAX_RESTARTS_PER_MINUTE = 3;
62
-
63
- function shouldUseInProcess(): boolean {
64
- // AWM 0.8.x P1 REVISE: worker_threads were removed because @huggingface/transformers
65
- // in Node is not worker_threads-safe (see file header). Always in-process for now.
66
- // The dispatch abstraction is preserved for a future child_process pool or
67
- // HTTP sidecar pivot.
68
- return true;
69
- }
70
-
71
- function createWorker(role: WorkerRole): ManagedWorker {
72
- const m: ManagedWorker = {
73
- role,
74
- worker: null,
75
- ready: Promise.resolve(),
76
- setReady: () => {},
77
- setFailed: () => {},
78
- pending: new Map(),
79
- buffered: [],
80
- isReady: false,
81
- restartTimestamps: [],
82
- };
83
- m.ready = new Promise<void>((resolve, reject) => {
84
- m.setReady = () => { m.isReady = true; resolve(); };
85
- m.setFailed = (err) => reject(err);
86
- });
87
- spawnWorker(m);
88
- return m;
89
- }
90
-
91
- function workerEntryPath(): string {
92
- // Resolve to the compiled .js. Two possible locations:
93
- // 1. Same directory as this file (when running from dist/core/)
94
- // 2. Sibling dist/core/ (when running from src/core/ via tsx)
95
- // Always prefer the compiled file. If neither exists, shouldUseInProcess()
96
- // will detect the missing entry and fall back to in-process mode.
97
- const here = dirname(fileURLToPath(import.meta.url));
98
- const samedir = join(here, 'ml-worker-entry.js');
99
- if (existsSync(samedir)) return samedir;
100
- // From src/core/ml-worker.ts, dist/core/ml-worker-entry.js is at ../../dist/core/
101
- const distSibling = join(here, '..', '..', 'dist', 'core', 'ml-worker-entry.js');
102
- if (existsSync(distSibling)) return distSibling;
103
- // Fallback to the same-dir path (will fail existsSync in shouldUseInProcess
104
- // and trigger in-process mode)
105
- return samedir;
106
- }
107
-
108
- function spawnWorker(m: ManagedWorker): void {
109
- const w = new Worker(workerEntryPath(), { workerData: { role: m.role } });
110
- m.worker = w;
111
-
112
- w.on('message', (msg: any) => {
113
- if (msg?.ready === true) {
114
- m.setReady();
115
- // Drain buffered messages
116
- for (const buf of m.buffered) w.postMessage(buf);
117
- m.buffered = [];
118
- return;
119
- }
120
- if (msg?.ready === false) {
121
- m.setFailed(new Error(`worker ${m.role} failed to load model: ${msg.error}`));
122
- return;
123
- }
124
- if (msg?.shutdown === 'done') return;
125
- if (typeof msg?.id !== 'number') return;
126
-
127
- const p = m.pending.get(msg.id);
128
- if (!p) return;
129
- m.pending.delete(msg.id);
130
- if (p.timeoutHandle) clearTimeout(p.timeoutHandle);
131
- if (msg.ok) p.resolve(msg.result);
132
- else p.reject(new Error(msg.error ?? 'worker error'));
133
- });
134
-
135
- w.on('error', (err) => {
136
- console.error(`[ml-worker:${m.role}] error:`, err);
137
- });
138
-
139
- w.on('exit', (code) => {
140
- if (code === 0) return; // graceful exit
141
- console.warn(`[ml-worker:${m.role}] exited with code ${code} — recovering`);
142
- // Reject all pending requests
143
- for (const [, p] of m.pending) {
144
- if (p.timeoutHandle) clearTimeout(p.timeoutHandle);
145
- p.reject(new Error(`worker ${m.role} crashed (exit ${code})`));
146
- }
147
- m.pending.clear();
148
-
149
- // Restart-rate backoff
150
- const now = Date.now();
151
- m.restartTimestamps = m.restartTimestamps.filter(t => now - t < 60_000);
152
- m.restartTimestamps.push(now);
153
-
154
- if (m.restartTimestamps.length > MAX_RESTARTS_PER_MINUTE) {
155
- console.error(`[ml-worker:${m.role}] crashed ${m.restartTimestamps.length} times in 60s — falling back to in-process`);
156
- m.worker = null;
157
- m.isReady = false;
158
- inProcessMode = true;
159
- return;
160
- }
161
-
162
- // Reset ready promise + respawn
163
- m.isReady = false;
164
- m.ready = new Promise<void>((resolve, reject) => {
165
- m.setReady = () => { m.isReady = true; resolve(); };
166
- m.setFailed = (err) => reject(err);
167
- });
168
- spawnWorker(m);
169
- });
170
- }
171
-
172
- /** Initialize the pool. Idempotent — safe to call multiple times. */
173
- export function initMLPool(): void {
174
- if (shouldUseInProcess()) {
175
- inProcessMode = true;
176
- return;
177
- }
178
- if (workers) return;
179
- workers = {
180
- embed: createWorker('embed'),
181
- rerank: createWorker('rerank'),
182
- expand: createWorker('expand'),
183
- };
184
- }
185
-
186
- /** Register in-process fallback handlers. Called once by the consumer modules. */
187
- export function registerInProcessHandlers(handlers: {
188
- embed?: typeof inProcessEmbed;
189
- rerank?: typeof inProcessRerank;
190
- expand?: typeof inProcessExpand;
191
- }): void {
192
- if (handlers.embed) inProcessEmbed = handlers.embed;
193
- if (handlers.rerank) inProcessRerank = handlers.rerank;
194
- if (handlers.expand) inProcessExpand = handlers.expand;
195
- }
196
-
197
- /** True if the pool is operating in in-process mode (no workers). */
198
- export function isInProcessMode(): boolean {
199
- return inProcessMode;
200
- }
201
-
202
- async function dispatchToWorker<T>(role: WorkerRole, args: any): Promise<T> {
203
- if (!workers) initMLPool();
204
- if (inProcessMode) {
205
- return dispatchInProcess<T>(role, args);
206
- }
207
-
208
- const m = workers![role];
209
- await m.ready;
210
- if (inProcessMode) {
211
- // Fallback flipped while we awaited ready
212
- return dispatchInProcess<T>(role, args);
213
- }
214
-
215
- const id = nextId++;
216
- return new Promise<T>((resolve, reject) => {
217
- const req: PendingRequest = {
218
- resolve,
219
- reject,
220
- timeoutHandle: setTimeout(() => {
221
- m.pending.delete(id);
222
- reject(new Error(`ml-worker:${role} request ${id} timed out after ${REQUEST_TIMEOUT_MS}ms`));
223
- }, REQUEST_TIMEOUT_MS),
224
- };
225
- m.pending.set(id, req);
226
- const msg = { id, op: role, args };
227
- if (m.isReady && m.worker) {
228
- m.worker.postMessage(msg);
229
- } else {
230
- m.buffered.push(msg);
231
- }
232
- });
233
- }
234
-
235
- async function dispatchInProcess<T>(role: WorkerRole, args: any): Promise<T> {
236
- switch (role) {
237
- case 'embed':
238
- if (!inProcessEmbed) throw new Error('in-process embed handler not registered');
239
- return inProcessEmbed(args) as Promise<T>;
240
- case 'rerank':
241
- if (!inProcessRerank) throw new Error('in-process rerank handler not registered');
242
- return inProcessRerank(args) as Promise<T>;
243
- case 'expand':
244
- if (!inProcessExpand) throw new Error('in-process expand handler not registered');
245
- return inProcessExpand(args) as Promise<T>;
246
- }
247
- }
248
-
249
- // --- Public API used by the consumer modules ---
250
-
251
- export async function dispatchEmbed(args: { texts: string[]; pooling: 'cls' | 'mean'; dimensions: number }): Promise<number[][]> {
252
- return dispatchToWorker<number[][]>('embed', args);
253
- }
254
-
255
- export async function dispatchRerank(args: { query: string; passages: string[] }): Promise<Array<{ index: number; score: number }>> {
256
- return dispatchToWorker<Array<{ index: number; score: number }>>('rerank', args);
257
- }
258
-
259
- export async function dispatchExpand(args: { prompt: string; maxNewTokens: number; noRepeatNgramSize: number }): Promise<string> {
260
- return dispatchToWorker<string>('expand', args);
261
- }
262
-
263
- /** Graceful shutdown. Waits up to 2s for queue drain, then terminates. */
264
- export async function shutdownMLPool(): Promise<void> {
265
- if (!workers) return;
266
- const promises: Promise<void>[] = [];
267
- for (const role of ['embed', 'rerank', 'expand'] as WorkerRole[]) {
268
- const m = workers[role];
269
- if (!m.worker) continue;
270
- const w = m.worker;
271
- promises.push(new Promise<void>((resolve) => {
272
- const timeout = setTimeout(() => {
273
- w.terminate().finally(() => resolve());
274
- }, 2000);
275
- w.once('exit', () => { clearTimeout(timeout); resolve(); });
276
- w.postMessage({ shutdown: true });
277
- }));
278
- }
279
- await Promise.all(promises);
280
- workers = null;
281
- }
1
+ // Copyright 2026 Robert Winter / Complete Ideas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * ML inference dispatch pool.
5
+ *
6
+ * STATUS (AWM 0.8.x P1 REVISE, 2026-05-25): worker_threads were the original
7
+ * plan, but @huggingface/transformers in Node only supports the `cpu`
8
+ * (native ONNX) and `dml` (Windows GPU) backends. Neither is safe inside
9
+ * a worker_thread — onnxruntime-node's native bindings store V8 handles
10
+ * that get invalidated when crossing isolate boundaries, causing
11
+ * `v8::HandleScope::CreateHandle()` crashes on first inference call.
12
+ * The browser-only `wasm` backend is not loaded in Node builds of
13
+ * transformers.js.
14
+ *
15
+ * The dispatch abstraction is preserved so a future child_process pool
16
+ * or HTTP sidecar (see AWM_ML_SIDECAR_URL design in docs/awm-architecture-history.md)
17
+ * can plug in. For now ALL inference runs in-process. The freeze fix from
18
+ * P0 (sleep-only consolidation) already eliminates the multi-second
19
+ * in-band blocks. Individual inference calls (~50ms each) on the main
20
+ * thread are accepted as-is.
21
+ *
22
+ * Test / dev mode: AWM_ML_INPROCESS=1 is honored but is now the default.
23
+ * The env var remains as a no-op for backwards compatibility.
24
+ */
25
+
26
+ import { Worker } from 'node:worker_threads';
27
+ import { fileURLToPath } from 'node:url';
28
+ import { dirname, join } from 'node:path';
29
+ import { existsSync } from 'node:fs';
30
+
31
+ type WorkerRole = 'embed' | 'rerank' | 'expand';
32
+
33
+ interface PendingRequest {
34
+ resolve: (value: any) => void;
35
+ reject: (err: Error) => void;
36
+ timeoutHandle?: ReturnType<typeof setTimeout>;
37
+ }
38
+
39
+ interface ManagedWorker {
40
+ role: WorkerRole;
41
+ worker: Worker | null;
42
+ ready: Promise<void>;
43
+ setReady: () => void;
44
+ setFailed: (err: Error) => void;
45
+ pending: Map<number, PendingRequest>;
46
+ buffered: Array<{ id: number; op: WorkerRole; args: any }>;
47
+ isReady: boolean;
48
+ restartTimestamps: number[]; // unix-ms of recent restarts (for backoff cap)
49
+ }
50
+
51
+ let inProcessMode = false;
52
+ let workers: Record<WorkerRole, ManagedWorker> | null = null;
53
+ let nextId = 1;
54
+
55
+ // In-process fallback handles (used in tests and as crash escape hatch).
56
+ let inProcessEmbed: ((args: any) => Promise<number[][]>) | null = null;
57
+ let inProcessRerank: ((args: any) => Promise<Array<{ index: number; score: number }>>) | null = null;
58
+ let inProcessExpand: ((args: any) => Promise<string>) | null = null;
59
+
60
+ const REQUEST_TIMEOUT_MS = 60_000; // any single inference call > 60s is treated as failed
61
+ const MAX_RESTARTS_PER_MINUTE = 3;
62
+
63
+ function shouldUseInProcess(): boolean {
64
+ // AWM 0.8.x P1 REVISE: worker_threads were removed because @huggingface/transformers
65
+ // in Node is not worker_threads-safe (see file header). Always in-process for now.
66
+ // The dispatch abstraction is preserved for a future child_process pool or
67
+ // HTTP sidecar pivot.
68
+ return true;
69
+ }
70
+
71
+ function createWorker(role: WorkerRole): ManagedWorker {
72
+ const m: ManagedWorker = {
73
+ role,
74
+ worker: null,
75
+ ready: Promise.resolve(),
76
+ setReady: () => {},
77
+ setFailed: () => {},
78
+ pending: new Map(),
79
+ buffered: [],
80
+ isReady: false,
81
+ restartTimestamps: [],
82
+ };
83
+ m.ready = new Promise<void>((resolve, reject) => {
84
+ m.setReady = () => { m.isReady = true; resolve(); };
85
+ m.setFailed = (err) => reject(err);
86
+ });
87
+ spawnWorker(m);
88
+ return m;
89
+ }
90
+
91
+ function workerEntryPath(): string {
92
+ // Resolve to the compiled .js. Two possible locations:
93
+ // 1. Same directory as this file (when running from dist/core/)
94
+ // 2. Sibling dist/core/ (when running from src/core/ via tsx)
95
+ // Always prefer the compiled file. If neither exists, shouldUseInProcess()
96
+ // will detect the missing entry and fall back to in-process mode.
97
+ const here = dirname(fileURLToPath(import.meta.url));
98
+ const samedir = join(here, 'ml-worker-entry.js');
99
+ if (existsSync(samedir)) return samedir;
100
+ // From src/core/ml-worker.ts, dist/core/ml-worker-entry.js is at ../../dist/core/
101
+ const distSibling = join(here, '..', '..', 'dist', 'core', 'ml-worker-entry.js');
102
+ if (existsSync(distSibling)) return distSibling;
103
+ // Fallback to the same-dir path (will fail existsSync in shouldUseInProcess
104
+ // and trigger in-process mode)
105
+ return samedir;
106
+ }
107
+
108
+ function spawnWorker(m: ManagedWorker): void {
109
+ const w = new Worker(workerEntryPath(), { workerData: { role: m.role } });
110
+ m.worker = w;
111
+
112
+ w.on('message', (msg: any) => {
113
+ if (msg?.ready === true) {
114
+ m.setReady();
115
+ // Drain buffered messages
116
+ for (const buf of m.buffered) w.postMessage(buf);
117
+ m.buffered = [];
118
+ return;
119
+ }
120
+ if (msg?.ready === false) {
121
+ m.setFailed(new Error(`worker ${m.role} failed to load model: ${msg.error}`));
122
+ return;
123
+ }
124
+ if (msg?.shutdown === 'done') return;
125
+ if (typeof msg?.id !== 'number') return;
126
+
127
+ const p = m.pending.get(msg.id);
128
+ if (!p) return;
129
+ m.pending.delete(msg.id);
130
+ if (p.timeoutHandle) clearTimeout(p.timeoutHandle);
131
+ if (msg.ok) p.resolve(msg.result);
132
+ else p.reject(new Error(msg.error ?? 'worker error'));
133
+ });
134
+
135
+ w.on('error', (err) => {
136
+ console.error(`[ml-worker:${m.role}] error:`, err);
137
+ });
138
+
139
+ w.on('exit', (code) => {
140
+ if (code === 0) return; // graceful exit
141
+ console.warn(`[ml-worker:${m.role}] exited with code ${code} — recovering`);
142
+ // Reject all pending requests
143
+ for (const [, p] of m.pending) {
144
+ if (p.timeoutHandle) clearTimeout(p.timeoutHandle);
145
+ p.reject(new Error(`worker ${m.role} crashed (exit ${code})`));
146
+ }
147
+ m.pending.clear();
148
+
149
+ // Restart-rate backoff
150
+ const now = Date.now();
151
+ m.restartTimestamps = m.restartTimestamps.filter(t => now - t < 60_000);
152
+ m.restartTimestamps.push(now);
153
+
154
+ if (m.restartTimestamps.length > MAX_RESTARTS_PER_MINUTE) {
155
+ console.error(`[ml-worker:${m.role}] crashed ${m.restartTimestamps.length} times in 60s — falling back to in-process`);
156
+ m.worker = null;
157
+ m.isReady = false;
158
+ inProcessMode = true;
159
+ return;
160
+ }
161
+
162
+ // Reset ready promise + respawn
163
+ m.isReady = false;
164
+ m.ready = new Promise<void>((resolve, reject) => {
165
+ m.setReady = () => { m.isReady = true; resolve(); };
166
+ m.setFailed = (err) => reject(err);
167
+ });
168
+ spawnWorker(m);
169
+ });
170
+ }
171
+
172
+ /** Initialize the pool. Idempotent — safe to call multiple times. */
173
+ export function initMLPool(): void {
174
+ if (shouldUseInProcess()) {
175
+ inProcessMode = true;
176
+ return;
177
+ }
178
+ if (workers) return;
179
+ workers = {
180
+ embed: createWorker('embed'),
181
+ rerank: createWorker('rerank'),
182
+ expand: createWorker('expand'),
183
+ };
184
+ }
185
+
186
+ /** Register in-process fallback handlers. Called once by the consumer modules. */
187
+ export function registerInProcessHandlers(handlers: {
188
+ embed?: typeof inProcessEmbed;
189
+ rerank?: typeof inProcessRerank;
190
+ expand?: typeof inProcessExpand;
191
+ }): void {
192
+ if (handlers.embed) inProcessEmbed = handlers.embed;
193
+ if (handlers.rerank) inProcessRerank = handlers.rerank;
194
+ if (handlers.expand) inProcessExpand = handlers.expand;
195
+ }
196
+
197
+ /** True if the pool is operating in in-process mode (no workers). */
198
+ export function isInProcessMode(): boolean {
199
+ return inProcessMode;
200
+ }
201
+
202
+ async function dispatchToWorker<T>(role: WorkerRole, args: any): Promise<T> {
203
+ if (!workers) initMLPool();
204
+ if (inProcessMode) {
205
+ return dispatchInProcess<T>(role, args);
206
+ }
207
+
208
+ const m = workers![role];
209
+ await m.ready;
210
+ if (inProcessMode) {
211
+ // Fallback flipped while we awaited ready
212
+ return dispatchInProcess<T>(role, args);
213
+ }
214
+
215
+ const id = nextId++;
216
+ return new Promise<T>((resolve, reject) => {
217
+ const req: PendingRequest = {
218
+ resolve,
219
+ reject,
220
+ timeoutHandle: setTimeout(() => {
221
+ m.pending.delete(id);
222
+ reject(new Error(`ml-worker:${role} request ${id} timed out after ${REQUEST_TIMEOUT_MS}ms`));
223
+ }, REQUEST_TIMEOUT_MS),
224
+ };
225
+ m.pending.set(id, req);
226
+ const msg = { id, op: role, args };
227
+ if (m.isReady && m.worker) {
228
+ m.worker.postMessage(msg);
229
+ } else {
230
+ m.buffered.push(msg);
231
+ }
232
+ });
233
+ }
234
+
235
+ async function dispatchInProcess<T>(role: WorkerRole, args: any): Promise<T> {
236
+ switch (role) {
237
+ case 'embed':
238
+ if (!inProcessEmbed) throw new Error('in-process embed handler not registered');
239
+ return inProcessEmbed(args) as Promise<T>;
240
+ case 'rerank':
241
+ if (!inProcessRerank) throw new Error('in-process rerank handler not registered');
242
+ return inProcessRerank(args) as Promise<T>;
243
+ case 'expand':
244
+ if (!inProcessExpand) throw new Error('in-process expand handler not registered');
245
+ return inProcessExpand(args) as Promise<T>;
246
+ }
247
+ }
248
+
249
+ // --- Public API used by the consumer modules ---
250
+
251
+ export async function dispatchEmbed(args: { texts: string[]; pooling: 'cls' | 'mean'; dimensions: number }): Promise<number[][]> {
252
+ return dispatchToWorker<number[][]>('embed', args);
253
+ }
254
+
255
+ export async function dispatchRerank(args: { query: string; passages: string[] }): Promise<Array<{ index: number; score: number }>> {
256
+ return dispatchToWorker<Array<{ index: number; score: number }>>('rerank', args);
257
+ }
258
+
259
+ export async function dispatchExpand(args: { prompt: string; maxNewTokens: number; noRepeatNgramSize: number }): Promise<string> {
260
+ return dispatchToWorker<string>('expand', args);
261
+ }
262
+
263
+ /** Graceful shutdown. Waits up to 2s for queue drain, then terminates. */
264
+ export async function shutdownMLPool(): Promise<void> {
265
+ if (!workers) return;
266
+ const promises: Promise<void>[] = [];
267
+ for (const role of ['embed', 'rerank', 'expand'] as WorkerRole[]) {
268
+ const m = workers[role];
269
+ if (!m.worker) continue;
270
+ const w = m.worker;
271
+ promises.push(new Promise<void>((resolve) => {
272
+ const timeout = setTimeout(() => {
273
+ w.terminate().finally(() => resolve());
274
+ }, 2000);
275
+ w.once('exit', () => { clearTimeout(timeout); resolve(); });
276
+ w.postMessage({ shutdown: true });
277
+ }));
278
+ }
279
+ await Promise.all(promises);
280
+ workers = null;
281
+ }