@cortexkit/pi-magic-context 0.49.84 → 0.49.86

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 (32) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +5 -4
  3. package/dist/{embedding-backfill-yh10bmx5.js → embedding-backfill-7a01ns95.js} +6 -5
  4. package/dist/embedding-worker.js +14 -27
  5. package/dist/{index-e0zdn1p3.js → index-53fgdt6n.js} +1 -1
  6. package/dist/{index-47g3pgzk.js → index-5n3bqhp9.js} +9 -8
  7. package/dist/{index-xz5b9t4g.js → index-7yz95h83.js} +38 -736
  8. package/dist/{index-a7kcxjc4.js → index-8631kxcp.js} +25 -18
  9. package/dist/index-8x8wtn3t.js +1083 -0
  10. package/dist/{index-hna2sxy8.js → index-94z1xzmr.js} +3 -3
  11. package/dist/{index-0apatd37.js → index-bjr11ay6.js} +24 -26
  12. package/dist/{index-gdy08gn6.js → index-ex9te7tc.js} +1 -1
  13. package/dist/{index-qxwed9sk.js → index-fd57gfnn.js} +4 -4
  14. package/dist/{index-nmmge3j6.js → index-gbc29ysq.js} +1 -1
  15. package/dist/{index-txcs0vnj.js → index-rqdjb6j3.js} +461 -273
  16. package/dist/{index-k8xz22jc.js → index-sqp84q6s.js} +1 -1
  17. package/dist/{index-3g1wy4z9.js → index-wy6h2wn2.js} +22 -10
  18. package/dist/index.js +61 -57
  19. package/dist/migration-worker.js +5 -4
  20. package/dist/{project-embedding-registry-3sss39rx.js → project-embedding-registry-agkd7egh.js} +7 -4
  21. package/dist/raw-ordinal-warmup-worker.js +2 -2
  22. package/dist/{render-05gdzxc2.js → render-rphfegr8.js} +7 -6
  23. package/dist/{search-archive-32pv4687.js → search-archive-7p43e77j.js} +1 -1
  24. package/dist/{search-dh4ryftv.js → search-rdvsnxky.js} +9 -8
  25. package/dist/{store-mmd2tmm1.js → store-ekaexkvc.js} +1 -1
  26. package/dist/{store-reader-ypd6m0ke.js → store-reader-vwphd51b.js} +1 -1
  27. package/dist/subagent-entry.js +17 -17
  28. package/dist/tag-snapshot-worker-pi.js +5 -4
  29. package/dist/{v2-archive-reader-1ny52akc.js → v2-archive-reader-qc4c9wrp.js} +1 -1
  30. package/package.json +1 -1
  31. package/dist/index-81nthk8j.js +0 -193
  32. /package/dist/{index-2zre7sck.js → index-ddfjg278.js} +0 -0
@@ -1,30 +1,480 @@
1
- import {
2
- DEFAULT_LOCAL_EMBEDDING_MODEL
3
- } from "./index-vcegxfwg.js";
4
- import {
5
- getSynapseLaneIdentity
6
- } from "./index-5rcjs14a.js";
7
1
  import {
8
2
  getHarness2
9
3
  } from "./index-0h2mkab2.js";
10
4
  import {
11
5
  getMagicContextStorageDir,
12
6
  importPluginModule,
13
- log2
7
+ log2,
8
+ flushLogger2
14
9
  } from "./index-tm11k42a.js";
15
10
  import {
16
11
  inRootAsyncContext2
17
12
  } from "./index-2qtx0q6h.js";
18
13
  import {
19
- computeNormalizedHash
20
- } from "./index-9x1f96r8.js";
14
+ DEFAULT_LOCAL_EMBEDDING_MODEL
15
+ } from "./index-vcegxfwg.js";
16
+ import {
17
+ getSynapseLaneIdentity
18
+ } from "./index-5rcjs14a.js";
21
19
  import {
22
20
  shouldEnforcePrivateStoragePermissions,
23
21
  ensureStorageDirectorySync,
24
22
  writeStorageFileAsync,
25
23
  writeStorageFileHandleAsync,
26
24
  createStorageFileHandleAsync
27
- } from "./index-81nthk8j.js";
25
+ } from "./index-8x8wtn3t.js";
26
+ import {
27
+ computeNormalizedHash
28
+ } from "./index-9x1f96r8.js";
29
+
30
+ // ../plugin/src/features/magic-context/memory/embedding-worker-client.ts
31
+ import { fork } from "node:child_process";
32
+ import { Worker } from "node:worker_threads";
33
+
34
+ // ../plugin/src/features/magic-context/memory/embedding-worker-loop.ts
35
+ var EMBEDDING_WORKER_STOPPING_ERROR = "embedding worker stopping";
36
+ function isEmbeddingWorkerStopNotice(message) {
37
+ return typeof message === "object" && message !== null && "control" in message && (message.control === "stopping" || message.control === "stopped");
38
+ }
39
+ function serveEmbeddingWorker(port, model, options) {
40
+ const now = options.now ?? (() => performance.now());
41
+ let queue = Promise.resolve();
42
+ let stopping = false;
43
+ let busySince = null;
44
+ const refuse = (id) => port.postMessage({ id, loaded: false, error: EMBEDDING_WORKER_STOPPING_ERROR });
45
+ const handle = async (request) => {
46
+ if (stopping)
47
+ return refuse(request.id);
48
+ busySince = now();
49
+ try {
50
+ const loaded = await model.initialize();
51
+ let vectors;
52
+ if (loaded && request.texts) {
53
+ vectors = [];
54
+ for (let offset = 0;offset < request.texts.length; offset += options.batchSize) {
55
+ if (offset > 0)
56
+ await new Promise((resolve) => setImmediate(resolve));
57
+ if (stopping)
58
+ throw new Error(EMBEDDING_WORKER_STOPPING_ERROR);
59
+ vectors.push(...await model.embedBatch(request.texts.slice(offset, offset + options.batchSize)));
60
+ }
61
+ }
62
+ port.postMessage({
63
+ id: request.id,
64
+ loaded,
65
+ vectors,
66
+ failure: model.getLastFailureReason(),
67
+ stats: options.stats?.()
68
+ }, vectors?.flatMap((vector) => vector ? [vector.buffer] : []) ?? []);
69
+ } catch (error) {
70
+ port.postMessage({ id: request.id, loaded: false, error: String(error) });
71
+ } finally {
72
+ busySince = null;
73
+ }
74
+ };
75
+ const stop = async () => {
76
+ stopping = true;
77
+ const requestedAt = now();
78
+ const busy = busySince !== null;
79
+ port.postMessage({
80
+ control: "stopping",
81
+ busy,
82
+ busyMs: busySince === null ? 0 : requestedAt - busySince
83
+ });
84
+ await queue;
85
+ try {
86
+ await model.dispose();
87
+ } catch {}
88
+ port.postMessage({
89
+ control: "stopped",
90
+ busy,
91
+ waitedMs: now() - requestedAt
92
+ });
93
+ options.exit();
94
+ };
95
+ port.on("message", (message) => {
96
+ if (message?.stop === true) {
97
+ if (!stopping)
98
+ stop();
99
+ return;
100
+ }
101
+ const request = message;
102
+ if (stopping)
103
+ return refuse(request.id);
104
+ queue = queue.then(() => handle(request));
105
+ });
106
+ }
107
+
108
+ // ../plugin/src/features/magic-context/memory/onnx-telemetry.ts
109
+ import { isMainThread } from "node:worker_threads";
110
+ var FFI_SPECIFIER = "bun:ffi";
111
+ async function prepareNativeOnnxTelemetry() {
112
+ if (process.platform === "win32")
113
+ return true;
114
+ if (!process.versions.bun) {
115
+ if (!isMainThread)
116
+ return false;
117
+ process.env.ORT_DISABLE_TELEMETRY = "1";
118
+ return true;
119
+ }
120
+ let ffi;
121
+ try {
122
+ ffi = await import(FFI_SPECIFIER);
123
+ } catch {
124
+ return false;
125
+ }
126
+ const { dlopen, FFIType } = ffi;
127
+ const paths = process.platform === "darwin" ? ["/usr/lib/libSystem.B.dylib"] : ["libc.so.6", `/lib/ld-musl-${process.arch === "arm64" ? "aarch64" : "x86_64"}.so.1`];
128
+ for (const path of paths) {
129
+ try {
130
+ const library = dlopen(path, {
131
+ setenv: {
132
+ args: [FFIType.cstring, FFIType.cstring, FFIType.i32],
133
+ returns: FFIType.i32
134
+ },
135
+ getenv: { args: [FFIType.cstring], returns: FFIType.cstring }
136
+ });
137
+ try {
138
+ const name = Buffer.from("ORT_DISABLE_TELEMETRY\x00");
139
+ const value = Buffer.from("1\x00");
140
+ const disabled = library.symbols.setenv(name, value, 1) === 0 && String(library.symbols.getenv(name)) === "1";
141
+ if (disabled)
142
+ process.env.ORT_DISABLE_TELEMETRY = "1";
143
+ return disabled;
144
+ } finally {
145
+ library.close();
146
+ }
147
+ } catch {}
148
+ }
149
+ return false;
150
+ }
151
+
152
+ // ../plugin/src/features/magic-context/memory/embedding-worker-client.ts
153
+ var warnedWindowsTelemetry = false;
154
+ var EMBEDDING_WORKER_STOP_GRACE_MS = 5000;
155
+ var EMBEDDING_WORKER_FORCED_EXIT_WAIT_MS = 2000;
156
+ var EMBEDDING_WORKER_SIGKILL_WAIT_MS = 200;
157
+ var EMBEDDING_WORKER_STOP_MAX_MS = EMBEDDING_WORKER_STOP_GRACE_MS + EMBEDDING_WORKER_FORCED_EXIT_WAIT_MS + EMBEDDING_WORKER_SIGKILL_WAIT_MS;
158
+ function busySince(state) {
159
+ let oldest = null;
160
+ for (const sentAt of state.dispatched.values()) {
161
+ if (oldest === null || sentAt < oldest)
162
+ oldest = sentAt;
163
+ }
164
+ return oldest;
165
+ }
166
+ async function exitsWithin(exit, ms) {
167
+ let timer;
168
+ try {
169
+ return await Promise.race([
170
+ exit.then(() => true),
171
+ new Promise((resolve) => {
172
+ timer = setTimeout(() => resolve(false), ms);
173
+ })
174
+ ]);
175
+ } finally {
176
+ clearTimeout(timer);
177
+ }
178
+ }
179
+ function describeRunning(since, at) {
180
+ return since === null ? "no" : `yes (for ${Math.max(0, Math.round(at - since))}ms)`;
181
+ }
182
+ function describeStuckWorker(state, stopSince) {
183
+ const notice = state.stopNotice;
184
+ const at = performance.now();
185
+ if (notice)
186
+ return describeRunning(notice.busy ? notice.receivedAt - notice.busyMs : null, at);
187
+ return `${describeRunning(stopSince, at)}, no answer to the stop request`;
188
+ }
189
+
190
+ class EmbeddingWorkerClient {
191
+ data;
192
+ entry;
193
+ timeoutMs;
194
+ prepareTelemetry;
195
+ idleMs;
196
+ options;
197
+ worker = null;
198
+ startPromise = null;
199
+ states = new WeakMap;
200
+ stopping = new Set;
201
+ nextId = 1;
202
+ pending = new Map;
203
+ disposed = false;
204
+ activeRequests = 0;
205
+ idleTimer = null;
206
+ constructor(data, entry = new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./embedding-worker.ts" : "./embedding-worker.js", import.meta.url), timeoutMs = 5 * 60000, prepareTelemetry = prepareNativeOnnxTelemetry, idleMs = 10 * 60000, options = {}) {
207
+ this.data = data;
208
+ this.entry = entry;
209
+ this.timeoutMs = timeoutMs;
210
+ this.prepareTelemetry = prepareTelemetry;
211
+ this.idleMs = idleMs;
212
+ this.options = options;
213
+ }
214
+ start() {
215
+ if (this.startPromise)
216
+ return this.startPromise;
217
+ this.startPromise = inRootAsyncContext2(() => this.startOwner()).finally(() => {
218
+ this.startPromise = null;
219
+ });
220
+ return this.startPromise;
221
+ }
222
+ async startOwner() {
223
+ if (this.disposed)
224
+ throw new Error("embedding worker disposed");
225
+ if (this.worker)
226
+ return this.worker;
227
+ const compiledBun = process.versions.bun && globalThis.Bun?.isStandaloneExecutable;
228
+ const inProcess = !compiledBun && await this.prepareTelemetry();
229
+ if (this.disposed)
230
+ throw new Error("embedding worker disposed");
231
+ const worker = inProcess ? new Worker(this.entry, { workerData: this.data }) : fork(new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./embedding-worker-process.ts" : "./embedding-worker-process.js", import.meta.url), [], {
232
+ env: {
233
+ ...process.env,
234
+ ORT_DISABLE_TELEMETRY: "1",
235
+ ...process.versions.bun ? { BUN_BE_BUN: "1" } : {}
236
+ },
237
+ execArgv: [],
238
+ serialization: "json",
239
+ ...{ windowsHide: true },
240
+ stdio: ["ignore", "inherit", "inherit", "ipc"]
241
+ });
242
+ if (process.platform === "win32" && this.data.runtimePreference !== "wasm") {
243
+ if (!warnedWindowsTelemetry) {
244
+ warnedWindowsTelemetry = true;
245
+ const warning = "[magic-context] ORT_DISABLE_TELEMETRY=1 prevents ONNX uploads on POSIX. Windows native ONNX uses OS-controlled ETW diagnostics instead and exposes no JavaScript telemetry-disable API; Windows diagnostic settings and trace collectors govern collection.";
246
+ log2(warning);
247
+ }
248
+ }
249
+ this.worker = worker;
250
+ let markExited;
251
+ const state = {
252
+ dispatched: new Map,
253
+ stopNotice: null,
254
+ exited: false,
255
+ exit: new Promise((resolve) => {
256
+ markExited = resolve;
257
+ })
258
+ };
259
+ this.states.set(worker, state);
260
+ worker.once("exit", () => {
261
+ state.exited = true;
262
+ markExited();
263
+ });
264
+ worker.unref();
265
+ if (!(worker instanceof Worker))
266
+ worker.channel?.unref?.();
267
+ worker.on("message", (wire) => {
268
+ if (isEmbeddingWorkerStopNotice(wire)) {
269
+ if (wire.control === "stopping")
270
+ state.stopNotice = {
271
+ busy: wire.busy,
272
+ busyMs: wire.busyMs,
273
+ receivedAt: performance.now()
274
+ };
275
+ return;
276
+ }
277
+ const reply = worker instanceof Worker ? wire : {
278
+ ...wire,
279
+ vectors: wire.vectors?.map((vector) => vector === null ? null : new Float32Array(Uint8Array.from(Buffer.from(vector, "base64")).buffer))
280
+ };
281
+ state.dispatched.delete(reply.id);
282
+ if (this.worker !== worker)
283
+ return;
284
+ const request = this.pending.get(reply.id);
285
+ if (!request)
286
+ return;
287
+ clearTimeout(request.timer);
288
+ this.pending.delete(reply.id);
289
+ if (reply.error)
290
+ request.reject(new Error(reply.error));
291
+ else
292
+ request.resolve(reply);
293
+ if (this.pending.size === 0) {
294
+ worker.unref();
295
+ if (!(worker instanceof Worker))
296
+ worker.channel?.unref?.();
297
+ }
298
+ });
299
+ const fail = (error) => {
300
+ if (this.worker !== worker)
301
+ return;
302
+ this.clearIdleTimer();
303
+ this.worker = null;
304
+ for (const request of this.pending.values()) {
305
+ clearTimeout(request.timer);
306
+ request.reject(error);
307
+ }
308
+ this.pending.clear();
309
+ log2("[magic-context] embedding worker exited unexpectedly:", error);
310
+ if (worker instanceof Worker)
311
+ worker.terminate();
312
+ else
313
+ worker.kill();
314
+ };
315
+ worker.on("error", fail);
316
+ worker.on("exit", (code, signal) => fail(new Error(`embedding worker exited (${signal ?? code})`)));
317
+ if (!(worker instanceof Worker))
318
+ worker.send({ entry: this.entry.href, data: this.data });
319
+ return worker;
320
+ }
321
+ isRunning() {
322
+ return this.worker !== null;
323
+ }
324
+ async request(texts, signal) {
325
+ if (signal?.aborted)
326
+ return Promise.reject(new Error("embedding request aborted"));
327
+ this.activeRequests++;
328
+ this.clearIdleTimer();
329
+ try {
330
+ return await this.requestOnWorker(texts, signal);
331
+ } finally {
332
+ this.activeRequests--;
333
+ this.armIdleTimer();
334
+ }
335
+ }
336
+ clearIdleTimer() {
337
+ if (this.idleTimer)
338
+ clearTimeout(this.idleTimer);
339
+ this.idleTimer = null;
340
+ }
341
+ armIdleTimer() {
342
+ if (this.disposed || this.activeRequests !== 0 || !this.worker)
343
+ return;
344
+ this.clearIdleTimer();
345
+ this.idleTimer = inRootAsyncContext2(() => setTimeout(() => {
346
+ this.idleTimer = null;
347
+ this.stop(new Error("embedding worker idle"));
348
+ }, this.idleMs));
349
+ this.idleTimer.unref();
350
+ }
351
+ async requestOnWorker(texts, signal) {
352
+ const worker = await this.start();
353
+ if (this.disposed)
354
+ throw new Error("embedding worker disposed");
355
+ if (signal?.aborted)
356
+ throw new Error("embedding request aborted");
357
+ return new Promise((resolve, reject) => {
358
+ const id = this.nextId++;
359
+ const timer = setTimeout(() => {
360
+ this.stop(new Error("embedding worker request timed out"));
361
+ }, this.timeoutMs);
362
+ const abort = () => {
363
+ clearTimeout(timer);
364
+ this.pending.delete(id);
365
+ signal?.removeEventListener("abort", abort);
366
+ reject(new Error("embedding request aborted"));
367
+ if (this.pending.size === 0) {
368
+ worker.unref();
369
+ if (!(worker instanceof Worker))
370
+ worker.channel?.unref?.();
371
+ }
372
+ };
373
+ signal?.addEventListener("abort", abort, { once: true });
374
+ const cleanup = () => signal?.removeEventListener("abort", abort);
375
+ this.pending.set(id, {
376
+ timer,
377
+ resolve: (reply) => {
378
+ cleanup();
379
+ resolve(reply);
380
+ },
381
+ reject: (error) => {
382
+ cleanup();
383
+ reject(error);
384
+ }
385
+ });
386
+ worker.ref();
387
+ if (!(worker instanceof Worker))
388
+ worker.channel?.ref?.();
389
+ this.states.get(worker)?.dispatched.set(id, performance.now());
390
+ try {
391
+ if (worker instanceof Worker)
392
+ worker.postMessage({ id, texts });
393
+ else
394
+ worker.send({ id, texts }, (error) => {
395
+ if (error && this.worker === worker)
396
+ this.stop(error);
397
+ });
398
+ } catch (error) {
399
+ this.stop(error instanceof Error ? error : new Error(String(error)));
400
+ }
401
+ });
402
+ }
403
+ async stop(error) {
404
+ this.clearIdleTimer();
405
+ const worker = this.worker;
406
+ this.worker = null;
407
+ for (const request of this.pending.values()) {
408
+ clearTimeout(request.timer);
409
+ request.reject(error);
410
+ }
411
+ this.pending.clear();
412
+ if (!worker)
413
+ return;
414
+ const stopped = this.stopWorker(worker, error.message);
415
+ this.stopping.add(stopped);
416
+ try {
417
+ await stopped;
418
+ } finally {
419
+ this.stopping.delete(stopped);
420
+ }
421
+ }
422
+ async stopWorker(worker, reason) {
423
+ const state = this.states.get(worker);
424
+ if (!state || state.exited)
425
+ return;
426
+ const writeLog = this.options.log ?? log2;
427
+ const graceMs = this.options.stopGraceMs ?? EMBEDDING_WORKER_STOP_GRACE_MS;
428
+ const forcedExitWaitMs = this.options.forcedExitWaitMs ?? EMBEDDING_WORKER_FORCED_EXIT_WAIT_MS;
429
+ const owner = worker instanceof Worker ? `pid ${process.pid}` : `pid ${process.pid}, worker pid ${worker.pid ?? "unknown"}`;
430
+ const startedAt = performance.now();
431
+ const stopSince = busySince(state);
432
+ worker.ref();
433
+ if (!(worker instanceof Worker))
434
+ worker.channel?.ref?.();
435
+ const request = { stop: true };
436
+ try {
437
+ if (worker instanceof Worker)
438
+ worker.postMessage(request);
439
+ else if (worker.connected)
440
+ worker.send(request, () => {});
441
+ } catch {}
442
+ if (await exitsWithin(state.exit, graceMs)) {
443
+ writeLog(`[magic-context] embedding worker stopped (${reason}; ${owner}; inference running: ${describeRunning(stopSince, startedAt)}; stop took ${Math.round(performance.now() - startedAt)}ms)`);
444
+ flushLogger2();
445
+ return;
446
+ }
447
+ writeLog(`[magic-context] embedding worker did not stop within ${graceMs}ms; terminating it (${reason}; ${owner}; inference running: ${describeStuckWorker(state, stopSince)})`);
448
+ flushLogger2();
449
+ try {
450
+ if (worker instanceof Worker)
451
+ worker.terminate().catch(() => {});
452
+ else
453
+ worker.kill();
454
+ } catch {}
455
+ if (await exitsWithin(state.exit, forcedExitWaitMs))
456
+ return;
457
+ let killed = false;
458
+ if (!(worker instanceof Worker) && process.platform !== "win32") {
459
+ try {
460
+ killed = worker.kill("SIGKILL");
461
+ } catch {}
462
+ if (await exitsWithin(state.exit, EMBEDDING_WORKER_SIGKILL_WAIT_MS))
463
+ return;
464
+ }
465
+ writeLog(`[magic-context] embedding worker has not exited ${forcedExitWaitMs}ms after it was terminated${killed ? " and sent SIGKILL" : ""}; no longer waiting for it (${reason}; ${owner})`);
466
+ flushLogger2();
467
+ worker.unref();
468
+ if (!(worker instanceof Worker))
469
+ worker.channel?.unref?.();
470
+ }
471
+ async dispose() {
472
+ this.disposed = true;
473
+ await this.startPromise?.catch(() => {});
474
+ await this.stop(new Error("embedding worker disposed"));
475
+ await Promise.all([...this.stopping]);
476
+ }
477
+ }
28
478
 
29
479
  // ../plugin/src/features/magic-context/memory/embedding-model-match.ts
30
480
  function parseEmbeddingModel(model) {
@@ -671,268 +1121,6 @@ function dominantEmbeddingFailure(failures) {
671
1121
  return dominant?.failure;
672
1122
  }
673
1123
 
674
- // ../plugin/src/features/magic-context/memory/embedding-worker-client.ts
675
- import { fork } from "node:child_process";
676
- import { Worker } from "node:worker_threads";
677
-
678
- // ../plugin/src/features/magic-context/memory/onnx-telemetry.ts
679
- import { isMainThread } from "node:worker_threads";
680
- var FFI_SPECIFIER = "bun:ffi";
681
- async function prepareNativeOnnxTelemetry() {
682
- if (process.platform === "win32")
683
- return true;
684
- if (!process.versions.bun) {
685
- if (!isMainThread)
686
- return false;
687
- process.env.ORT_DISABLE_TELEMETRY = "1";
688
- return true;
689
- }
690
- let ffi;
691
- try {
692
- ffi = await import(FFI_SPECIFIER);
693
- } catch {
694
- return false;
695
- }
696
- const { dlopen, FFIType } = ffi;
697
- const paths = process.platform === "darwin" ? ["/usr/lib/libSystem.B.dylib"] : ["libc.so.6", `/lib/ld-musl-${process.arch === "arm64" ? "aarch64" : "x86_64"}.so.1`];
698
- for (const path of paths) {
699
- try {
700
- const library = dlopen(path, {
701
- setenv: {
702
- args: [FFIType.cstring, FFIType.cstring, FFIType.i32],
703
- returns: FFIType.i32
704
- },
705
- getenv: { args: [FFIType.cstring], returns: FFIType.cstring }
706
- });
707
- try {
708
- const name = Buffer.from("ORT_DISABLE_TELEMETRY\x00");
709
- const value = Buffer.from("1\x00");
710
- const disabled = library.symbols.setenv(name, value, 1) === 0 && String(library.symbols.getenv(name)) === "1";
711
- if (disabled)
712
- process.env.ORT_DISABLE_TELEMETRY = "1";
713
- return disabled;
714
- } finally {
715
- library.close();
716
- }
717
- } catch {}
718
- }
719
- return false;
720
- }
721
-
722
- // ../plugin/src/features/magic-context/memory/embedding-worker-client.ts
723
- var warnedWindowsTelemetry = false;
724
-
725
- class EmbeddingWorkerClient {
726
- data;
727
- entry;
728
- timeoutMs;
729
- prepareTelemetry;
730
- idleMs;
731
- worker = null;
732
- startPromise = null;
733
- nextId = 1;
734
- pending = new Map;
735
- disposed = false;
736
- activeRequests = 0;
737
- idleTimer = null;
738
- constructor(data, entry = new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./embedding-worker.ts" : "./embedding-worker.js", import.meta.url), timeoutMs = 5 * 60000, prepareTelemetry = prepareNativeOnnxTelemetry, idleMs = 10 * 60000) {
739
- this.data = data;
740
- this.entry = entry;
741
- this.timeoutMs = timeoutMs;
742
- this.prepareTelemetry = prepareTelemetry;
743
- this.idleMs = idleMs;
744
- }
745
- start() {
746
- if (this.startPromise)
747
- return this.startPromise;
748
- this.startPromise = inRootAsyncContext2(() => this.startOwner()).finally(() => {
749
- this.startPromise = null;
750
- });
751
- return this.startPromise;
752
- }
753
- async startOwner() {
754
- if (this.disposed)
755
- throw new Error("embedding worker disposed");
756
- if (this.worker)
757
- return this.worker;
758
- const compiledBun = process.versions.bun && globalThis.Bun?.isStandaloneExecutable;
759
- const inProcess = !compiledBun && await this.prepareTelemetry();
760
- if (this.disposed)
761
- throw new Error("embedding worker disposed");
762
- const worker = inProcess ? new Worker(this.entry, { workerData: this.data }) : fork(new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./embedding-worker-process.ts" : "./embedding-worker-process.js", import.meta.url), [], {
763
- env: {
764
- ...process.env,
765
- ORT_DISABLE_TELEMETRY: "1",
766
- ...process.versions.bun ? { BUN_BE_BUN: "1" } : {}
767
- },
768
- execArgv: [],
769
- serialization: "json",
770
- ...{ windowsHide: true },
771
- stdio: ["ignore", "inherit", "inherit", "ipc"]
772
- });
773
- if (process.platform === "win32" && this.data.runtimePreference !== "wasm") {
774
- if (!warnedWindowsTelemetry) {
775
- warnedWindowsTelemetry = true;
776
- const warning = "[magic-context] ORT_DISABLE_TELEMETRY=1 prevents ONNX uploads on POSIX. Windows native ONNX uses OS-controlled ETW diagnostics instead and exposes no JavaScript telemetry-disable API; Windows diagnostic settings and trace collectors govern collection.";
777
- log2(warning);
778
- }
779
- }
780
- this.worker = worker;
781
- worker.unref();
782
- if (!(worker instanceof Worker))
783
- worker.channel?.unref?.();
784
- worker.on("message", (wire) => {
785
- const reply = worker instanceof Worker ? wire : {
786
- ...wire,
787
- vectors: wire.vectors?.map((vector) => vector === null ? null : new Float32Array(Uint8Array.from(Buffer.from(vector, "base64")).buffer))
788
- };
789
- if (this.worker !== worker)
790
- return;
791
- const request = this.pending.get(reply.id);
792
- if (!request)
793
- return;
794
- clearTimeout(request.timer);
795
- this.pending.delete(reply.id);
796
- if (reply.error)
797
- request.reject(new Error(reply.error));
798
- else
799
- request.resolve(reply);
800
- if (this.pending.size === 0) {
801
- worker.unref();
802
- if (!(worker instanceof Worker))
803
- worker.channel?.unref?.();
804
- }
805
- });
806
- const fail = (error) => {
807
- if (this.worker !== worker)
808
- return;
809
- this.clearIdleTimer();
810
- this.worker = null;
811
- for (const request of this.pending.values()) {
812
- clearTimeout(request.timer);
813
- request.reject(error);
814
- }
815
- this.pending.clear();
816
- log2("[magic-context] embedding worker exited unexpectedly:", error);
817
- if (worker instanceof Worker)
818
- worker.terminate();
819
- else
820
- worker.kill();
821
- };
822
- worker.on("error", fail);
823
- worker.on("exit", (code, signal) => fail(new Error(`embedding worker exited (${signal ?? code})`)));
824
- if (!(worker instanceof Worker))
825
- worker.send({ entry: this.entry.href, data: this.data });
826
- return worker;
827
- }
828
- isRunning() {
829
- return this.worker !== null;
830
- }
831
- async request(texts, signal) {
832
- if (signal?.aborted)
833
- return Promise.reject(new Error("embedding request aborted"));
834
- this.activeRequests++;
835
- this.clearIdleTimer();
836
- try {
837
- return await this.requestOnWorker(texts, signal);
838
- } finally {
839
- this.activeRequests--;
840
- this.armIdleTimer();
841
- }
842
- }
843
- clearIdleTimer() {
844
- if (this.idleTimer)
845
- clearTimeout(this.idleTimer);
846
- this.idleTimer = null;
847
- }
848
- armIdleTimer() {
849
- if (this.disposed || this.activeRequests !== 0 || !this.worker)
850
- return;
851
- this.clearIdleTimer();
852
- this.idleTimer = inRootAsyncContext2(() => setTimeout(() => {
853
- this.idleTimer = null;
854
- this.stop(new Error("embedding worker idle"));
855
- }, this.idleMs));
856
- this.idleTimer.unref();
857
- }
858
- async requestOnWorker(texts, signal) {
859
- const worker = await this.start();
860
- if (this.disposed)
861
- throw new Error("embedding worker disposed");
862
- if (signal?.aborted)
863
- throw new Error("embedding request aborted");
864
- return new Promise((resolve, reject) => {
865
- const id = this.nextId++;
866
- const timer = setTimeout(() => {
867
- this.stop(new Error("embedding worker request timed out"));
868
- }, this.timeoutMs);
869
- const abort = () => {
870
- clearTimeout(timer);
871
- this.pending.delete(id);
872
- signal?.removeEventListener("abort", abort);
873
- reject(new Error("embedding request aborted"));
874
- if (this.pending.size === 0) {
875
- worker.unref();
876
- if (!(worker instanceof Worker))
877
- worker.channel?.unref?.();
878
- }
879
- };
880
- signal?.addEventListener("abort", abort, { once: true });
881
- const cleanup = () => signal?.removeEventListener("abort", abort);
882
- this.pending.set(id, {
883
- timer,
884
- resolve: (reply) => {
885
- cleanup();
886
- resolve(reply);
887
- },
888
- reject: (error) => {
889
- cleanup();
890
- reject(error);
891
- }
892
- });
893
- worker.ref();
894
- if (!(worker instanceof Worker))
895
- worker.channel?.ref?.();
896
- try {
897
- if (worker instanceof Worker)
898
- worker.postMessage({ id, texts });
899
- else
900
- worker.send({ id, texts }, (error) => {
901
- if (error && this.worker === worker)
902
- this.stop(error);
903
- });
904
- } catch (error) {
905
- this.stop(error instanceof Error ? error : new Error(String(error)));
906
- }
907
- });
908
- }
909
- async stop(error) {
910
- this.clearIdleTimer();
911
- const worker = this.worker;
912
- this.worker = null;
913
- for (const request of this.pending.values()) {
914
- clearTimeout(request.timer);
915
- request.reject(error);
916
- }
917
- this.pending.clear();
918
- if (worker instanceof Worker) {
919
- await worker.terminate();
920
- } else if (worker && worker.exitCode === null && worker.signalCode === null) {
921
- worker.ref();
922
- worker.channel?.ref?.();
923
- await new Promise((resolve) => {
924
- worker.once("exit", () => resolve());
925
- worker.kill();
926
- });
927
- }
928
- }
929
- async dispose() {
930
- this.disposed = true;
931
- await this.startPromise?.catch(() => {});
932
- await this.stop(new Error("embedding worker disposed"));
933
- }
934
- }
935
-
936
1124
  // ../plugin/src/features/magic-context/memory/transformers-remote-host.ts
937
1125
  var DEFAULT_TRANSFORMERS_REMOTE_HOST = "https://huggingface.co/";
938
1126
  function readHuggingFaceEndpoint() {
@@ -1651,4 +1839,4 @@ class LocalEmbeddingProvider {
1651
1839
  }
1652
1840
  }
1653
1841
 
1654
- export { embeddingModelsMatch, resolveEmbeddingTextPrefixes, getCachedLocalEmbeddingPooling, logLocalEmbeddingPoolingDecisionOnce, preflightLocalEmbeddingPooling, logLocalEmbeddingPoolingUnavailableOnce, getEmbeddingProviderIdentity, dominantEmbeddingFailure, resolveLocalEmbeddingWorkerRuntime, getLocalEmbeddingNativeMemoryStats, LocalEmbeddingProvider };
1842
+ export { serveEmbeddingWorker, EMBEDDING_WORKER_STOP_MAX_MS, embeddingModelsMatch, resolveEmbeddingTextPrefixes, getCachedLocalEmbeddingPooling, logLocalEmbeddingPoolingDecisionOnce, preflightLocalEmbeddingPooling, logLocalEmbeddingPoolingUnavailableOnce, getEmbeddingProviderIdentity, dominantEmbeddingFailure, resolveLocalEmbeddingWorkerRuntime, getLocalEmbeddingNativeMemoryStats, LocalEmbeddingProvider };