@memberjunction/ng-conversations 6.2.2 → 6.3.0-edge.1
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.
- package/README.md +49 -24
- package/dist/assets/edge-ai.worker.js +32515 -0
- package/dist/lib/components/artifact/artifact-share-modal.component.d.ts +39 -6
- package/dist/lib/components/artifact/artifact-share-modal.component.d.ts.map +1 -1
- package/dist/lib/components/artifact/artifact-share-modal.component.js +620 -74
- package/dist/lib/components/artifact/artifact-share-modal.component.js.map +1 -1
- package/dist/lib/components/collection/artifact-create-modal.component.js +4 -4
- package/dist/lib/components/collection/artifact-create-modal.component.js.map +1 -1
- package/dist/lib/components/collection/collection-form-modal.component.js +3 -3
- package/dist/lib/components/collection/collection-form-modal.component.js.map +1 -1
- package/dist/lib/components/collection/collection-tree.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-tree.component.js +19 -18
- package/dist/lib/components/collection/collection-tree.component.js.map +1 -1
- package/dist/lib/components/collection/collection-view.component.d.ts +6 -4
- package/dist/lib/components/collection/collection-view.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-view.component.js +35 -17
- package/dist/lib/components/collection/collection-view.component.js.map +1 -1
- package/dist/lib/components/collection/collections-full-view.component.d.ts +1 -0
- package/dist/lib/components/collection/collections-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collections-full-view.component.js +109 -107
- package/dist/lib/components/collection/collections-full-view.component.js.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +76 -11
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.js +236 -50
- package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
- package/dist/lib/components/conversation/conversation-list.component.d.ts +49 -1
- package/dist/lib/components/conversation/conversation-list.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-list.component.js +151 -41
- package/dist/lib/components/conversation/conversation-list.component.js.map +1 -1
- package/dist/lib/components/conversation/conversation-remote-browser-controller.d.ts +11 -3
- package/dist/lib/components/conversation/conversation-remote-browser-controller.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-remote-browser-controller.js +40 -4
- package/dist/lib/components/conversation/conversation-remote-browser-controller.js.map +1 -1
- package/dist/lib/components/export/export-modal.component.d.ts +7 -2
- package/dist/lib/components/export/export-modal.component.d.ts.map +1 -1
- package/dist/lib/components/export/export-modal.component.js +13 -2
- package/dist/lib/components/export/export-modal.component.js.map +1 -1
- package/dist/lib/components/library/library-create-dialog.component.d.ts +136 -0
- package/dist/lib/components/library/library-create-dialog.component.d.ts.map +1 -0
- package/dist/lib/components/library/library-create-dialog.component.js +1620 -0
- package/dist/lib/components/library/library-create-dialog.component.js.map +1 -0
- package/dist/lib/components/library/library-full-view.component.d.ts +10 -4
- package/dist/lib/components/library/library-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/library/library-full-view.component.js +216 -40
- package/dist/lib/components/library/library-full-view.component.js.map +1 -1
- package/dist/lib/components/library/library-remote-drive-pane.component.d.ts +97 -0
- package/dist/lib/components/library/library-remote-drive-pane.component.d.ts.map +1 -0
- package/dist/lib/components/library/library-remote-drive-pane.component.js +1229 -0
- package/dist/lib/components/library/library-remote-drive-pane.component.js.map +1 -0
- package/dist/lib/components/library/library-workspace.component.d.ts +265 -0
- package/dist/lib/components/library/library-workspace.component.d.ts.map +1 -0
- package/dist/lib/components/library/library-workspace.component.js +4420 -0
- package/dist/lib/components/library/library-workspace.component.js.map +1 -0
- package/dist/lib/components/library/library.models.d.ts +162 -0
- package/dist/lib/components/library/library.models.d.ts.map +1 -0
- package/dist/lib/components/library/library.models.js +2 -0
- package/dist/lib/components/library/library.models.js.map +1 -0
- package/dist/lib/components/message/conversation-message-rating.component.d.ts +5 -0
- package/dist/lib/components/message/conversation-message-rating.component.d.ts.map +1 -1
- package/dist/lib/components/message/conversation-message-rating.component.js +72 -16
- package/dist/lib/components/message/conversation-message-rating.component.js.map +1 -1
- package/dist/lib/components/message/message-input.component.d.ts +26 -14
- package/dist/lib/components/message/message-input.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-input.component.js +91 -56
- package/dist/lib/components/message/message-input.component.js.map +1 -1
- package/dist/lib/components/message/message-item.component.d.ts +35 -1
- package/dist/lib/components/message/message-item.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-item.component.js +583 -392
- package/dist/lib/components/message/message-item.component.js.map +1 -1
- package/dist/lib/components/message/message-list.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-list.component.js +2 -0
- package/dist/lib/components/message/message-list.component.js.map +1 -1
- package/dist/lib/components/navigation/conversation-navigation.component.js +9 -9
- package/dist/lib/components/navigation/conversation-navigation.component.js.map +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.d.ts +94 -6
- package/dist/lib/components/overlay/chat-overlay.component.d.ts.map +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.js +249 -59
- package/dist/lib/components/overlay/chat-overlay.component.js.map +1 -1
- package/dist/lib/components/project/project-form-modal.component.d.ts +6 -0
- package/dist/lib/components/project/project-form-modal.component.d.ts.map +1 -1
- package/dist/lib/components/project/project-form-modal.component.js +81 -61
- package/dist/lib/components/project/project-form-modal.component.js.map +1 -1
- package/dist/lib/components/project/project-selector.component.d.ts +5 -0
- package/dist/lib/components/project/project-selector.component.d.ts.map +1 -1
- package/dist/lib/components/project/project-selector.component.js +11 -4
- package/dist/lib/components/project/project-selector.component.js.map +1 -1
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-channel.d.ts +55 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-channel.d.ts.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-channel.js +944 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-channel.js.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-engine.d.ts +66 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-engine.d.ts.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-engine.js +253 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-engine.js.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-types.d.ts +80 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-types.d.ts.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-types.js +49 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-types.js.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/realtime-artifact-workspace-surface.component.d.ts +54 -0
- package/dist/lib/components/realtime/artifact-workspace/realtime-artifact-workspace-surface.component.d.ts.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/realtime-artifact-workspace-surface.component.js +386 -0
- package/dist/lib/components/realtime/artifact-workspace/realtime-artifact-workspace-surface.component.js.map +1 -0
- package/dist/lib/components/realtime/channels/client-context-channel.d.ts +20 -4
- package/dist/lib/components/realtime/channels/client-context-channel.d.ts.map +1 -1
- package/dist/lib/components/realtime/channels/client-context-channel.js +62 -8
- package/dist/lib/components/realtime/channels/client-context-channel.js.map +1 -1
- package/dist/lib/components/realtime/interactive-component/interactive-component-channel.d.ts +1 -0
- package/dist/lib/components/realtime/interactive-component/interactive-component-channel.d.ts.map +1 -1
- package/dist/lib/components/realtime/interactive-component/interactive-component-channel.js +15 -2
- package/dist/lib/components/realtime/interactive-component/interactive-component-channel.js.map +1 -1
- package/dist/lib/components/realtime/realtime-agent-banner.component.js +2 -2
- package/dist/lib/components/realtime/realtime-agent-banner.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-agent-picker.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-agent-picker.component.js +3 -3
- package/dist/lib/components/realtime/realtime-agent-picker.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-composer.component.js +5 -3
- package/dist/lib/components/realtime/realtime-composer.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-session-overlay.component.d.ts +81 -32
- package/dist/lib/components/realtime/realtime-session-overlay.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-session-overlay.component.js +506 -185
- package/dist/lib/components/realtime/realtime-session-overlay.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-session-thread.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-session-thread.component.js +89 -4
- package/dist/lib/components/realtime/realtime-session-thread.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-stage.model.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-stage.model.js +2 -1
- package/dist/lib/components/realtime/realtime-surface-stage.model.js.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-tab-style.d.ts +4 -4
- package/dist/lib/components/realtime/realtime-surface-tab-style.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-tab-style.js +5 -5
- package/dist/lib/components/realtime/realtime-surface-tab-style.js.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-tabs.model.d.ts +7 -9
- package/dist/lib/components/realtime/realtime-surface-tabs.model.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-tabs.model.js +12 -13
- package/dist/lib/components/realtime/realtime-surface-tabs.model.js.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-channel.d.ts +27 -0
- package/dist/lib/components/realtime/remote-browser/remote-browser-channel.d.ts.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-channel.js +141 -2
- package/dist/lib/components/realtime/remote-browser/remote-browser-channel.js.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.d.ts +101 -3
- package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.js +503 -55
- package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.js.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-tools.d.ts.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-tools.js +2 -2
- package/dist/lib/components/realtime/remote-browser/remote-browser-tools.js.map +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-artifact-viewer.component.d.ts +48 -5
- package/dist/lib/components/realtime/whiteboard/whiteboard-artifact-viewer.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-artifact-viewer.component.js +249 -53
- package/dist/lib/components/realtime/whiteboard/whiteboard-artifact-viewer.component.js.map +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-channel.d.ts.map +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-channel.js +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-channel.js.map +1 -1
- package/dist/lib/components/search/search-panel.component.d.ts +10 -0
- package/dist/lib/components/search/search-panel.component.d.ts.map +1 -1
- package/dist/lib/components/search/search-panel.component.js +25 -3
- package/dist/lib/components/search/search-panel.component.js.map +1 -1
- package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts +28 -1
- package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts.map +1 -1
- package/dist/lib/components/sidebar/conversation-sidebar.component.js +51 -6
- package/dist/lib/components/sidebar/conversation-sidebar.component.js.map +1 -1
- package/dist/lib/components/task/tasks-full-view.component.d.ts +31 -8
- package/dist/lib/components/task/tasks-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/task/tasks-full-view.component.js +692 -497
- package/dist/lib/components/task/tasks-full-view.component.js.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.js +15 -2
- package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
- package/dist/lib/conversations.module.d.ts +66 -61
- package/dist/lib/conversations.module.d.ts.map +1 -1
- package/dist/lib/conversations.module.js +60 -1
- package/dist/lib/conversations.module.js.map +1 -1
- package/dist/lib/events/chat-events.d.ts +45 -0
- package/dist/lib/events/chat-events.d.ts.map +1 -1
- package/dist/lib/events/chat-events.js +64 -0
- package/dist/lib/events/chat-events.js.map +1 -1
- package/dist/lib/models/agent-turn.model.d.ts +7 -1
- package/dist/lib/models/agent-turn.model.d.ts.map +1 -1
- package/dist/lib/models/agent-turn.model.js.map +1 -1
- package/dist/lib/services/agent-state.service.d.ts.map +1 -1
- package/dist/lib/services/agent-state.service.js +14 -3
- package/dist/lib/services/agent-state.service.js.map +1 -1
- package/dist/lib/services/artifact-permission.service.d.ts.map +1 -1
- package/dist/lib/services/artifact-permission.service.js +14 -3
- package/dist/lib/services/artifact-permission.service.js.map +1 -1
- package/dist/lib/services/artifact-state.service.d.ts.map +1 -1
- package/dist/lib/services/artifact-state.service.js +43 -11
- package/dist/lib/services/artifact-state.service.js.map +1 -1
- package/dist/lib/services/conversation-agent.service.d.ts +8 -3
- package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
- package/dist/lib/services/conversation-agent.service.js +9 -3
- package/dist/lib/services/conversation-agent.service.js.map +1 -1
- package/dist/lib/services/conversation-tasks-filter.d.ts +59 -2
- package/dist/lib/services/conversation-tasks-filter.d.ts.map +1 -1
- package/dist/lib/services/conversation-tasks-filter.js +222 -18
- package/dist/lib/services/conversation-tasks-filter.js.map +1 -1
- package/dist/lib/services/edge-ai/edge-agent-pre-discovery.service.d.ts +85 -0
- package/dist/lib/services/edge-ai/edge-agent-pre-discovery.service.d.ts.map +1 -0
- package/dist/lib/services/edge-ai/edge-agent-pre-discovery.service.js +257 -0
- package/dist/lib/services/edge-ai/edge-agent-pre-discovery.service.js.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai-protocol.d.ts +85 -0
- package/dist/lib/services/edge-ai/edge-ai-protocol.d.ts.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai-protocol.js +10 -0
- package/dist/lib/services/edge-ai/edge-ai-protocol.js.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai-worker-host.d.ts +90 -0
- package/dist/lib/services/edge-ai/edge-ai-worker-host.d.ts.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai-worker-host.js +386 -0
- package/dist/lib/services/edge-ai/edge-ai-worker-host.js.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai.worker.d.ts +13 -0
- package/dist/lib/services/edge-ai/edge-ai.worker.d.ts.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai.worker.js +201 -0
- package/dist/lib/services/edge-ai/edge-ai.worker.js.map +1 -0
- package/dist/lib/services/export.service.d.ts +64 -0
- package/dist/lib/services/export.service.d.ts.map +1 -1
- package/dist/lib/services/export.service.js +185 -6
- package/dist/lib/services/export.service.js.map +1 -1
- package/dist/lib/services/library-creation.service.d.ts +304 -0
- package/dist/lib/services/library-creation.service.d.ts.map +1 -0
- package/dist/lib/services/library-creation.service.js +1244 -0
- package/dist/lib/services/library-creation.service.js.map +1 -0
- package/dist/lib/services/realtime-audio-recorder.d.ts +10 -8
- package/dist/lib/services/realtime-audio-recorder.d.ts.map +1 -1
- package/dist/lib/services/realtime-audio-recorder.js +28 -12
- package/dist/lib/services/realtime-audio-recorder.js.map +1 -1
- package/dist/lib/services/realtime-pairing.d.ts +3 -3
- package/dist/lib/services/realtime-pairing.js +4 -4
- package/dist/lib/services/realtime-pairing.js.map +1 -1
- package/dist/lib/services/realtime-session-review.service.d.ts +14 -0
- package/dist/lib/services/realtime-session-review.service.d.ts.map +1 -1
- package/dist/lib/services/realtime-session-review.service.js +46 -4
- package/dist/lib/services/realtime-session-review.service.js.map +1 -1
- package/dist/lib/services/realtime-session.service.d.ts +10 -3
- package/dist/lib/services/realtime-session.service.d.ts.map +1 -1
- package/dist/lib/services/realtime-session.service.js +8 -3
- package/dist/lib/services/realtime-session.service.js.map +1 -1
- package/dist/lib/services/search.service.d.ts +19 -2
- package/dist/lib/services/search.service.d.ts.map +1 -1
- package/dist/lib/services/search.service.js +99 -36
- package/dist/lib/services/search.service.js.map +1 -1
- package/dist/lib/utils/agent-artifact-summary.d.ts +1 -1
- package/dist/lib/utils/agent-artifact-summary.d.ts.map +1 -1
- package/dist/lib/utils/agent-artifact-summary.js +1 -1
- package/dist/lib/utils/agent-artifact-summary.js.map +1 -1
- package/dist/lib/utils/decision-routing.d.ts +5 -2
- package/dist/lib/utils/decision-routing.d.ts.map +1 -1
- package/dist/lib/utils/decision-routing.js +9 -4
- package/dist/lib/utils/decision-routing.js.map +1 -1
- package/dist/public-api.d.ts +13 -0
- package/dist/public-api.d.ts.map +1 -1
- package/dist/public-api.js +15 -1
- package/dist/public-api.js.map +1 -1
- package/package.json +42 -37
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Singleton host managing the shared lazy Edge AI Web Worker
|
|
3
|
+
* (`bge-small-en-v1.5` bi-encoder + `ms-marco-MiniLM-L-6-v2` cross-encoder).
|
|
4
|
+
*
|
|
5
|
+
* Designed for non-blocking background initialization, strict per-call deadlines,
|
|
6
|
+
* concurrent request multiplexing by `RequestId`, and circuit-breaker fallback
|
|
7
|
+
* when offline, CSP-restricted, or WASM-unsupported.
|
|
8
|
+
*
|
|
9
|
+
* @module @memberjunction/ng-conversations
|
|
10
|
+
*/
|
|
11
|
+
import { BaseSingleton, GetGlobalObjectStore } from '@memberjunction/global';
|
|
12
|
+
import { EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL, EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL, } from '@memberjunction/ai-core-plus';
|
|
13
|
+
/** Global object store key where host apps (e.g., MJExplorer) register their bundled Worker constructor. */
|
|
14
|
+
export const EDGE_AI_WORKER_FACTORY_STORE_KEY = '___MJ_EDGE_AI_WORKER_FACTORY__';
|
|
15
|
+
/** Default deadline for initial WASM + model weight load (cold cache). */
|
|
16
|
+
export const EDGE_WORKER_DEFAULT_INIT_TIMEOUT_MS = 30_000;
|
|
17
|
+
/** Default deadline for warm single-query operations. */
|
|
18
|
+
export const EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS = 120;
|
|
19
|
+
/** Number of consecutive worker failures/timeouts before opening the circuit breaker. */
|
|
20
|
+
export const EDGE_WORKER_CIRCUIT_FAILURE_THRESHOLD = 3;
|
|
21
|
+
/** Cooldown duration before retrying after the circuit breaker opens. */
|
|
22
|
+
export const EDGE_WORKER_CIRCUIT_COOLDOWN_MS = 60_000;
|
|
23
|
+
class BrowserEdgeWorkerPort {
|
|
24
|
+
worker;
|
|
25
|
+
OnReply = null;
|
|
26
|
+
constructor(worker) {
|
|
27
|
+
this.worker = worker;
|
|
28
|
+
worker.onmessage = (event) => {
|
|
29
|
+
this.OnReply?.(event.data);
|
|
30
|
+
};
|
|
31
|
+
worker.onerror = (event) => {
|
|
32
|
+
this.OnReply?.({
|
|
33
|
+
Type: 'error',
|
|
34
|
+
Message: event.message || 'Edge AI worker crashed',
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
Post(message, transfer) {
|
|
39
|
+
this.worker.postMessage(message, transfer);
|
|
40
|
+
}
|
|
41
|
+
Terminate() {
|
|
42
|
+
this.worker.onmessage = null;
|
|
43
|
+
this.worker.onerror = null;
|
|
44
|
+
this.worker.terminate();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Shared singleton managing one lazy ONNX/WASM Web Worker for both Edge Agent
|
|
49
|
+
* Pre-Discovery (Stage 6C.1) and the Client-Only Semantic Omnibox (Stage 6C.2).
|
|
50
|
+
*/
|
|
51
|
+
export class EdgeAIWorkerHost extends BaseSingleton {
|
|
52
|
+
port = null;
|
|
53
|
+
portFactory = null;
|
|
54
|
+
initPromise = null;
|
|
55
|
+
isReady = false;
|
|
56
|
+
isCrossEncoderReady = false;
|
|
57
|
+
consecutiveFailures = 0;
|
|
58
|
+
circuitOpenUntil = 0;
|
|
59
|
+
nextRequestSeq = 1;
|
|
60
|
+
pending = new Map();
|
|
61
|
+
initOptions = {
|
|
62
|
+
BiEncoderModelId: EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL,
|
|
63
|
+
CrossEncoderModelId: EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL,
|
|
64
|
+
Device: 'wasm',
|
|
65
|
+
DType: 'q8',
|
|
66
|
+
LoadCrossEncoder: false,
|
|
67
|
+
};
|
|
68
|
+
constructor() {
|
|
69
|
+
super();
|
|
70
|
+
}
|
|
71
|
+
static get Instance() {
|
|
72
|
+
return super.getInstance();
|
|
73
|
+
}
|
|
74
|
+
/** True when the runtime supports Web Workers (or a test port factory is configured). */
|
|
75
|
+
get IsSupported() {
|
|
76
|
+
return this.portFactory !== null || typeof Worker !== 'undefined';
|
|
77
|
+
}
|
|
78
|
+
/** True once the bi-encoder pipeline inside the worker has warmed and reported ready. */
|
|
79
|
+
get IsWarm() {
|
|
80
|
+
return this.isReady && !this.IsCircuitOpen;
|
|
81
|
+
}
|
|
82
|
+
/** True once the cross-encoder reranker has also loaded inside the worker. */
|
|
83
|
+
get IsCrossEncoderWarm() {
|
|
84
|
+
return this.isCrossEncoderReady && !this.IsCircuitOpen;
|
|
85
|
+
}
|
|
86
|
+
/** True while the circuit breaker is open after repeated worker failures/timeouts. */
|
|
87
|
+
get IsCircuitOpen() {
|
|
88
|
+
if (this.consecutiveFailures < EDGE_WORKER_CIRCUIT_FAILURE_THRESHOLD) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
if (Date.now() >= this.circuitOpenUntil) {
|
|
92
|
+
// Half-open: allow one retry
|
|
93
|
+
this.consecutiveFailures = EDGE_WORKER_CIRCUIT_FAILURE_THRESHOLD - 1;
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
/** Configures a custom worker port factory (primarily for unit/stress tests). */
|
|
99
|
+
SetPortFactoryForTesting(factory) {
|
|
100
|
+
this.ResetForTesting();
|
|
101
|
+
this.portFactory = factory;
|
|
102
|
+
}
|
|
103
|
+
/** Terminates the worker and clears all cached state and circuit-breaker counters. */
|
|
104
|
+
ResetForTesting() {
|
|
105
|
+
this.Dispose();
|
|
106
|
+
this.portFactory = null;
|
|
107
|
+
this.consecutiveFailures = 0;
|
|
108
|
+
this.circuitOpenUntil = 0;
|
|
109
|
+
this.initOptions = {
|
|
110
|
+
BiEncoderModelId: EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL,
|
|
111
|
+
CrossEncoderModelId: EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL,
|
|
112
|
+
Device: 'wasm',
|
|
113
|
+
DType: 'q8',
|
|
114
|
+
LoadCrossEncoder: false,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Lazily spawns and warms the Web Worker. Coalesces concurrent callers.
|
|
119
|
+
* Never throws; returns `false` when unsupported, offline/erroring, or timed out.
|
|
120
|
+
*/
|
|
121
|
+
async EnsureWarm(options, timeoutMs = EDGE_WORKER_DEFAULT_INIT_TIMEOUT_MS) {
|
|
122
|
+
if (!this.IsSupported || this.IsCircuitOpen) {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
const merged = { ...this.initOptions, ...options };
|
|
126
|
+
const needsCross = Boolean(merged.LoadCrossEncoder) && !this.isCrossEncoderReady;
|
|
127
|
+
if (this.isReady && !needsCross) {
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
if (this.initPromise && !needsCross) {
|
|
131
|
+
return this.initPromise;
|
|
132
|
+
}
|
|
133
|
+
this.initOptions = merged;
|
|
134
|
+
const runInit = (async () => {
|
|
135
|
+
const port = this.ensurePort();
|
|
136
|
+
if (!port) {
|
|
137
|
+
this.recordFailure();
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
const requestId = this.nextRequestId('init');
|
|
141
|
+
const reply = await this.sendRequest(port, {
|
|
142
|
+
Type: 'init',
|
|
143
|
+
RequestId: requestId,
|
|
144
|
+
BiEncoderModelId: merged.BiEncoderModelId,
|
|
145
|
+
CrossEncoderModelId: merged.CrossEncoderModelId,
|
|
146
|
+
Device: merged.Device ?? 'wasm',
|
|
147
|
+
DType: merged.DType ?? 'q8',
|
|
148
|
+
LoadCrossEncoder: merged.LoadCrossEncoder ?? false,
|
|
149
|
+
LocalModelPath: merged.LocalModelPath,
|
|
150
|
+
AllowRemoteModels: merged.AllowRemoteModels,
|
|
151
|
+
WasmPaths: merged.WasmPaths,
|
|
152
|
+
}, [], timeoutMs);
|
|
153
|
+
if (reply?.Type === 'ready') {
|
|
154
|
+
this.isReady = true;
|
|
155
|
+
if (reply.CrossEncoderLoaded) {
|
|
156
|
+
this.isCrossEncoderReady = true;
|
|
157
|
+
}
|
|
158
|
+
this.consecutiveFailures = 0;
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
this.recordFailure();
|
|
162
|
+
return false;
|
|
163
|
+
})();
|
|
164
|
+
this.initPromise = runInit;
|
|
165
|
+
try {
|
|
166
|
+
return await runInit;
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
if (this.initPromise === runInit) {
|
|
170
|
+
this.initPromise = null;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Embeds `texts` using the worker's `bge-small-en-v1.5` pipeline, lazily warming
|
|
176
|
+
* the worker first if needed. Returns `null` on timeout, circuit open, or error.
|
|
177
|
+
*/
|
|
178
|
+
async Embed(texts, timeoutMs = EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS, modelId) {
|
|
179
|
+
if (texts.length === 0) {
|
|
180
|
+
return [];
|
|
181
|
+
}
|
|
182
|
+
if (!this.IsSupported || this.IsCircuitOpen) {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
const warm = await this.EnsureWarm(modelId ? { BiEncoderModelId: modelId } : undefined, Math.max(timeoutMs, EDGE_WORKER_DEFAULT_INIT_TIMEOUT_MS));
|
|
186
|
+
if (!warm || !this.port) {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
return this.runEmbed(this.port, [...texts], timeoutMs, modelId);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Embeds `texts` ONLY if the worker is already warm — returns `null` immediately
|
|
193
|
+
* when cold so interactive paths (typing in Omnibar, sending a message) never block
|
|
194
|
+
* on model downloads.
|
|
195
|
+
*/
|
|
196
|
+
async EmbedIfWarm(texts, timeoutMs = EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS, modelId) {
|
|
197
|
+
if (texts.length === 0) {
|
|
198
|
+
return [];
|
|
199
|
+
}
|
|
200
|
+
if (!this.IsWarm || !this.port) {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
return this.runEmbed(this.port, [...texts], timeoutMs, modelId);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Reranks `[query, doc]` pairs using the worker's `ms-marco-MiniLM-L-6-v2`
|
|
207
|
+
* cross-encoder, returning raw logits. Returns `null` on timeout/error/cold failure.
|
|
208
|
+
*/
|
|
209
|
+
async Rerank(query, documents, timeoutMs = EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS, modelId) {
|
|
210
|
+
if (documents.length === 0) {
|
|
211
|
+
return [];
|
|
212
|
+
}
|
|
213
|
+
if (!this.IsSupported || this.IsCircuitOpen) {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
const warm = await this.EnsureWarm({
|
|
217
|
+
LoadCrossEncoder: true,
|
|
218
|
+
...(modelId ? { CrossEncoderModelId: modelId } : {}),
|
|
219
|
+
}, Math.max(timeoutMs, EDGE_WORKER_DEFAULT_INIT_TIMEOUT_MS));
|
|
220
|
+
if (!warm || !this.port) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
return this.runRerank(this.port, query, [...documents], timeoutMs, modelId);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Reranks `documents` ONLY when the worker's cross-encoder is already warm.
|
|
227
|
+
*/
|
|
228
|
+
async RerankIfWarm(query, documents, timeoutMs = EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS, modelId) {
|
|
229
|
+
if (documents.length === 0) {
|
|
230
|
+
return [];
|
|
231
|
+
}
|
|
232
|
+
if (!this.IsCrossEncoderWarm || !this.port) {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
return this.runRerank(this.port, query, [...documents], timeoutMs, modelId);
|
|
236
|
+
}
|
|
237
|
+
/** Terminates the active worker and rejects/clears any pending callers gracefully. */
|
|
238
|
+
Dispose() {
|
|
239
|
+
this.isReady = false;
|
|
240
|
+
this.isCrossEncoderReady = false;
|
|
241
|
+
this.initPromise = null;
|
|
242
|
+
for (const [id, waiter] of this.pending) {
|
|
243
|
+
clearTimeout(waiter.Timer);
|
|
244
|
+
waiter.Resolve({ Type: 'error', RequestId: id, Message: 'Edge AI worker disposed' });
|
|
245
|
+
}
|
|
246
|
+
this.pending.clear();
|
|
247
|
+
if (this.port) {
|
|
248
|
+
this.port.OnReply = null;
|
|
249
|
+
this.port.Terminate();
|
|
250
|
+
this.port = null;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
async runEmbed(port, texts, timeoutMs, modelId) {
|
|
254
|
+
const requestId = this.nextRequestId('embed');
|
|
255
|
+
const reply = await this.sendRequest(port, {
|
|
256
|
+
Type: 'embed',
|
|
257
|
+
RequestId: requestId,
|
|
258
|
+
Texts: texts,
|
|
259
|
+
ModelId: modelId ?? this.initOptions.BiEncoderModelId,
|
|
260
|
+
Device: this.initOptions.Device ?? 'wasm',
|
|
261
|
+
DType: this.initOptions.DType ?? 'q8',
|
|
262
|
+
}, [], timeoutMs);
|
|
263
|
+
if (reply?.Type === 'embedded') {
|
|
264
|
+
this.consecutiveFailures = 0;
|
|
265
|
+
return reply.Vectors.map((buf) => new Float32Array(buf));
|
|
266
|
+
}
|
|
267
|
+
this.recordFailure();
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
async runRerank(port, query, documents, timeoutMs, modelId) {
|
|
271
|
+
const requestId = this.nextRequestId('rerank');
|
|
272
|
+
const reply = await this.sendRequest(port, {
|
|
273
|
+
Type: 'rerank',
|
|
274
|
+
RequestId: requestId,
|
|
275
|
+
Query: query,
|
|
276
|
+
Documents: documents,
|
|
277
|
+
ModelId: modelId ?? this.initOptions.CrossEncoderModelId,
|
|
278
|
+
Device: this.initOptions.Device ?? 'wasm',
|
|
279
|
+
DType: this.initOptions.DType ?? 'q8',
|
|
280
|
+
}, [], timeoutMs);
|
|
281
|
+
if (reply?.Type === 'reranked') {
|
|
282
|
+
this.isCrossEncoderReady = true;
|
|
283
|
+
this.consecutiveFailures = 0;
|
|
284
|
+
return reply.Logits;
|
|
285
|
+
}
|
|
286
|
+
this.recordFailure();
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
ensurePort() {
|
|
290
|
+
if (this.port) {
|
|
291
|
+
return this.port;
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
const port = this.portFactory ? this.portFactory() : this.createBrowserWorkerPort();
|
|
295
|
+
port.OnReply = (reply) => this.handleReply(reply);
|
|
296
|
+
this.port = port;
|
|
297
|
+
return port;
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
createBrowserWorkerPort() {
|
|
304
|
+
const globalStore = GetGlobalObjectStore();
|
|
305
|
+
const hostFactory = globalStore[EDGE_AI_WORKER_FACTORY_STORE_KEY];
|
|
306
|
+
if (typeof hostFactory === 'function') {
|
|
307
|
+
const custom = hostFactory();
|
|
308
|
+
if (custom && typeof custom.Post === 'function') {
|
|
309
|
+
return custom;
|
|
310
|
+
}
|
|
311
|
+
return new BrowserEdgeWorkerPort(custom);
|
|
312
|
+
}
|
|
313
|
+
// Resolve the pre-bundled worker asset copied from @memberjunction/ng-explorer-app/dist/assets
|
|
314
|
+
// relative to the document base URI so consumer apps require zero app-level worker wiring.
|
|
315
|
+
const baseUri = typeof document !== 'undefined' && document.baseURI
|
|
316
|
+
? document.baseURI
|
|
317
|
+
: typeof globalThis.location !== 'undefined' && globalThis.location.href
|
|
318
|
+
? globalThis.location.href
|
|
319
|
+
: undefined;
|
|
320
|
+
const workerUrl = baseUri
|
|
321
|
+
? new URL('assets/edge-ai.worker.js', baseUri)
|
|
322
|
+
: new URL('./edge-ai.worker.js', import.meta.url);
|
|
323
|
+
const worker = new Worker(workerUrl, { type: 'module' });
|
|
324
|
+
return new BrowserEdgeWorkerPort(worker);
|
|
325
|
+
}
|
|
326
|
+
handleReply(reply) {
|
|
327
|
+
const reqId = 'RequestId' in reply ? reply.RequestId : undefined;
|
|
328
|
+
if (reqId && this.pending.has(reqId)) {
|
|
329
|
+
const waiter = this.pending.get(reqId);
|
|
330
|
+
this.pending.delete(reqId);
|
|
331
|
+
clearTimeout(waiter.Timer);
|
|
332
|
+
waiter.Resolve(reply);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
// Uncorrelated worker error (e.g. worker.onerror crash): fail all pending requests
|
|
336
|
+
if (reply.Type === 'error' && !reqId) {
|
|
337
|
+
this.isReady = false;
|
|
338
|
+
this.isCrossEncoderReady = false;
|
|
339
|
+
for (const [id, waiter] of this.pending) {
|
|
340
|
+
clearTimeout(waiter.Timer);
|
|
341
|
+
waiter.Resolve({ Type: 'error', RequestId: id, Message: reply.Message });
|
|
342
|
+
}
|
|
343
|
+
this.pending.clear();
|
|
344
|
+
if (this.port) {
|
|
345
|
+
this.port.OnReply = null;
|
|
346
|
+
this.port.Terminate();
|
|
347
|
+
this.port = null;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
sendRequest(port, request, transfer, timeoutMs) {
|
|
352
|
+
const requestId = request.RequestId;
|
|
353
|
+
return new Promise((resolve) => {
|
|
354
|
+
const timer = setTimeout(() => {
|
|
355
|
+
this.pending.delete(requestId);
|
|
356
|
+
resolve(null);
|
|
357
|
+
}, Math.max(1, timeoutMs));
|
|
358
|
+
this.pending.set(requestId, {
|
|
359
|
+
Timer: timer,
|
|
360
|
+
Resolve: (reply) => resolve(reply),
|
|
361
|
+
});
|
|
362
|
+
try {
|
|
363
|
+
port.Post(request, transfer);
|
|
364
|
+
}
|
|
365
|
+
catch (err) {
|
|
366
|
+
this.pending.delete(requestId);
|
|
367
|
+
clearTimeout(timer);
|
|
368
|
+
resolve({
|
|
369
|
+
Type: 'error',
|
|
370
|
+
RequestId: requestId,
|
|
371
|
+
Message: err instanceof Error ? err.message : String(err),
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
recordFailure() {
|
|
377
|
+
this.consecutiveFailures++;
|
|
378
|
+
if (this.consecutiveFailures >= EDGE_WORKER_CIRCUIT_FAILURE_THRESHOLD) {
|
|
379
|
+
this.circuitOpenUntil = Date.now() + EDGE_WORKER_CIRCUIT_COOLDOWN_MS;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
nextRequestId(prefix) {
|
|
383
|
+
return `${prefix}-${this.nextRequestSeq++}`;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
//# sourceMappingURL=edge-ai-worker-host.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edge-ai-worker-host.js","sourceRoot":"","sources":["../../../../src/lib/services/edge-ai/edge-ai-worker-host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACH,mCAAmC,EACnC,sCAAsC,GACzC,MAAM,8BAA8B,CAAC;AAQtC,4GAA4G;AAC5G,MAAM,CAAC,MAAM,gCAAgC,GAAG,gCAAgC,CAAC;AAEjF,0EAA0E;AAC1E,MAAM,CAAC,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAE1D,yDAAyD;AACzD,MAAM,CAAC,MAAM,oCAAoC,GAAG,GAAG,CAAC;AAExD,yFAAyF;AACzF,MAAM,CAAC,MAAM,qCAAqC,GAAG,CAAC,CAAC;AAEvD,yEAAyE;AACzE,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v1.5` bi-encoder + `ms-marco-MiniLM-L-6-v2` cross-encoder).\n *\n * Designed for non-blocking background initialization, strict per-call deadlines,\n * concurrent request multiplexing by `RequestId`, and circuit-breaker fallback\n * when offline, CSP-restricted, or WASM-unsupported.\n *\n * @module @memberjunction/ng-conversations\n */\n\nimport { BaseSingleton, GetGlobalObjectStore } from '@memberjunction/global';\nimport {\n EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL,\n EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL,\n} from '@memberjunction/ai-core-plus';\nimport type {\n EdgeWorkerInitOptions,\n EdgeWorkerPort,\n EdgeWorkerReply,\n EdgeWorkerRequest,\n} from './edge-ai-protocol';\n\n/** Global object store key where host apps (e.g., MJExplorer) register their bundled Worker constructor. */\nexport const EDGE_AI_WORKER_FACTORY_STORE_KEY = '___MJ_EDGE_AI_WORKER_FACTORY__';\n\n/** Default deadline for initial WASM + model weight load (cold cache). */\nexport const EDGE_WORKER_DEFAULT_INIT_TIMEOUT_MS = 30_000;\n\n/** Default deadline for warm single-query operations. */\nexport const EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS = 120;\n\n/** Number of consecutive worker failures/timeouts before opening the circuit breaker. */\nexport const EDGE_WORKER_CIRCUIT_FAILURE_THRESHOLD = 3;\n\n/** Cooldown duration before retrying after the circuit breaker opens. */\nexport const EDGE_WORKER_CIRCUIT_COOLDOWN_MS = 60_000;\n\n/** Internal non-exported DOM Worker slice so naming-conventions stays clean. */\ninterface BrowserWorkerLike {\n postMessage(message: unknown, transfer?: Transferable[]): void;\n terminate(): void;\n onmessage: ((event: MessageEvent<EdgeWorkerReply>) => void) | null;\n onerror: ((event: ErrorEvent) => void) | null;\n}\n\nclass BrowserEdgeWorkerPort implements EdgeWorkerPort {\n public OnReply: ((reply: EdgeWorkerReply) => void) | null = null;\n\n constructor(private readonly worker: BrowserWorkerLike) {\n worker.onmessage = (event: MessageEvent<EdgeWorkerReply>) => {\n this.OnReply?.(event.data);\n };\n worker.onerror = (event: ErrorEvent) => {\n this.OnReply?.({\n Type: 'error',\n Message: event.message || 'Edge AI worker crashed',\n });\n };\n }\n\n public Post(message: EdgeWorkerRequest, transfer: Transferable[]): void {\n this.worker.postMessage(message, transfer);\n }\n\n public Terminate(): void {\n this.worker.onmessage = null;\n this.worker.onerror = null;\n this.worker.terminate();\n }\n}\n\ninterface PendingWaiter {\n Resolve: (reply: EdgeWorkerReply) => void;\n Timer: ReturnType<typeof setTimeout>;\n}\n\n/** Factory function creating an {@link EdgeWorkerPort}. */\nexport type EdgeWorkerPortFactory = () => EdgeWorkerPort;\n\n/**\n * Shared singleton managing one lazy ONNX/WASM Web Worker for both Edge Agent\n * Pre-Discovery (Stage 6C.1) and the Client-Only Semantic Omnibox (Stage 6C.2).\n */\nexport class EdgeAIWorkerHost extends BaseSingleton<EdgeAIWorkerHost> {\n private port: EdgeWorkerPort | null = null;\n private portFactory: EdgeWorkerPortFactory | null = null;\n private initPromise: Promise<boolean> | null = null;\n private isReady = false;\n private isCrossEncoderReady = false;\n private consecutiveFailures = 0;\n private circuitOpenUntil = 0;\n private nextRequestSeq = 1;\n private readonly pending = new Map<string, PendingWaiter>();\n private initOptions: EdgeWorkerInitOptions = {\n BiEncoderModelId: EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL,\n CrossEncoderModelId: EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL,\n Device: 'wasm',\n DType: 'q8',\n LoadCrossEncoder: false,\n };\n\n protected constructor() {\n super();\n }\n\n public static get Instance(): EdgeAIWorkerHost {\n return super.getInstance<EdgeAIWorkerHost>();\n }\n\n /** True when the runtime supports Web Workers (or a test port factory is configured). */\n public get IsSupported(): boolean {\n return this.portFactory !== null || typeof Worker !== 'undefined';\n }\n\n /** True once the bi-encoder pipeline inside the worker has warmed and reported ready. */\n public get IsWarm(): boolean {\n return this.isReady && !this.IsCircuitOpen;\n }\n\n /** True once the cross-encoder reranker has also loaded inside the worker. */\n public get IsCrossEncoderWarm(): boolean {\n return this.isCrossEncoderReady && !this.IsCircuitOpen;\n }\n\n /** True while the circuit breaker is open after repeated worker failures/timeouts. */\n public get IsCircuitOpen(): boolean {\n if (this.consecutiveFailures < EDGE_WORKER_CIRCUIT_FAILURE_THRESHOLD) {\n return false;\n }\n if (Date.now() >= this.circuitOpenUntil) {\n // Half-open: allow one retry\n this.consecutiveFailures = EDGE_WORKER_CIRCUIT_FAILURE_THRESHOLD - 1;\n return false;\n }\n return true;\n }\n\n /** Configures a custom worker port factory (primarily for unit/stress tests). */\n public SetPortFactoryForTesting(factory: EdgeWorkerPortFactory | null): void {\n this.ResetForTesting();\n this.portFactory = factory;\n }\n\n /** Terminates the worker and clears all cached state and circuit-breaker counters. */\n public ResetForTesting(): void {\n this.Dispose();\n this.portFactory = null;\n this.consecutiveFailures = 0;\n this.circuitOpenUntil = 0;\n this.initOptions = {\n BiEncoderModelId: EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL,\n CrossEncoderModelId: EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL,\n Device: 'wasm',\n DType: 'q8',\n LoadCrossEncoder: false,\n };\n }\n\n /**\n * Lazily spawns and warms the Web Worker. Coalesces concurrent callers.\n * Never throws; returns `false` when unsupported, offline/erroring, or timed out.\n */\n public async EnsureWarm(\n options?: EdgeWorkerInitOptions,\n timeoutMs: number = EDGE_WORKER_DEFAULT_INIT_TIMEOUT_MS\n ): Promise<boolean> {\n if (!this.IsSupported || this.IsCircuitOpen) {\n return false;\n }\n const merged: EdgeWorkerInitOptions = { ...this.initOptions, ...options };\n const needsCross = Boolean(merged.LoadCrossEncoder) && !this.isCrossEncoderReady;\n if (this.isReady && !needsCross) {\n return true;\n }\n if (this.initPromise && !needsCross) {\n return this.initPromise;\n }\n\n this.initOptions = merged;\n const runInit = (async (): Promise<boolean> => {\n const port = this.ensurePort();\n if (!port) {\n this.recordFailure();\n return false;\n }\n const requestId = this.nextRequestId('init');\n const reply = await this.sendRequest(\n port,\n {\n Type: 'init',\n RequestId: requestId,\n BiEncoderModelId: merged.BiEncoderModelId,\n CrossEncoderModelId: merged.CrossEncoderModelId,\n Device: merged.Device ?? 'wasm',\n DType: merged.DType ?? 'q8',\n LoadCrossEncoder: merged.LoadCrossEncoder ?? false,\n LocalModelPath: merged.LocalModelPath,\n AllowRemoteModels: merged.AllowRemoteModels,\n WasmPaths: merged.WasmPaths,\n },\n [],\n timeoutMs\n );\n\n if (reply?.Type === 'ready') {\n this.isReady = true;\n if (reply.CrossEncoderLoaded) {\n this.isCrossEncoderReady = true;\n }\n this.consecutiveFailures = 0;\n return true;\n }\n this.recordFailure();\n return false;\n })();\n\n this.initPromise = runInit;\n try {\n return await runInit;\n } finally {\n if (this.initPromise === runInit) {\n this.initPromise = null;\n }\n }\n }\n\n /**\n * Embeds `texts` using the worker's `bge-small-en-v1.5` pipeline, lazily warming\n * the worker first if needed. Returns `null` on timeout, circuit open, or error.\n */\n public async Embed(\n texts: ReadonlyArray<string>,\n timeoutMs: number = EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS,\n modelId?: string\n ): Promise<Float32Array[] | null> {\n if (texts.length === 0) {\n return [];\n }\n if (!this.IsSupported || this.IsCircuitOpen) {\n return null;\n }\n const warm = await this.EnsureWarm(\n modelId ? { BiEncoderModelId: modelId } : undefined,\n Math.max(timeoutMs, EDGE_WORKER_DEFAULT_INIT_TIMEOUT_MS)\n );\n if (!warm || !this.port) {\n return null;\n }\n return this.runEmbed(this.port, [...texts], timeoutMs, modelId);\n }\n\n /**\n * Embeds `texts` ONLY if the worker is already warm — returns `null` immediately\n * when cold so interactive paths (typing in Omnibar, sending a message) never block\n * on model downloads.\n */\n public async EmbedIfWarm(\n texts: ReadonlyArray<string>,\n timeoutMs: number = EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS,\n modelId?: string\n ): Promise<Float32Array[] | null> {\n if (texts.length === 0) {\n return [];\n }\n if (!this.IsWarm || !this.port) {\n return null;\n }\n return this.runEmbed(this.port, [...texts], timeoutMs, modelId);\n }\n\n /**\n * Reranks `[query, doc]` pairs using the worker's `ms-marco-MiniLM-L-6-v2`\n * cross-encoder, returning raw logits. Returns `null` on timeout/error/cold failure.\n */\n public async Rerank(\n query: string,\n documents: ReadonlyArray<string>,\n timeoutMs: number = EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS,\n modelId?: string\n ): Promise<number[] | null> {\n if (documents.length === 0) {\n return [];\n }\n if (!this.IsSupported || this.IsCircuitOpen) {\n return null;\n }\n const warm = await this.EnsureWarm(\n {\n LoadCrossEncoder: true,\n ...(modelId ? { CrossEncoderModelId: modelId } : {}),\n },\n Math.max(timeoutMs, EDGE_WORKER_DEFAULT_INIT_TIMEOUT_MS)\n );\n if (!warm || !this.port) {\n return null;\n }\n return this.runRerank(this.port, query, [...documents], timeoutMs, modelId);\n }\n\n /**\n * Reranks `documents` ONLY when the worker's cross-encoder is already warm.\n */\n public async RerankIfWarm(\n query: string,\n documents: ReadonlyArray<string>,\n timeoutMs: number = EDGE_WORKER_DEFAULT_QUERY_TIMEOUT_MS,\n modelId?: string\n ): Promise<number[] | null> {\n if (documents.length === 0) {\n return [];\n }\n if (!this.IsCrossEncoderWarm || !this.port) {\n return null;\n }\n return this.runRerank(this.port, query, [...documents], timeoutMs, modelId);\n }\n\n /** Terminates the active worker and rejects/clears any pending callers gracefully. */\n public Dispose(): void {\n this.isReady = false;\n this.isCrossEncoderReady = false;\n this.initPromise = null;\n\n for (const [id, waiter] of this.pending) {\n clearTimeout(waiter.Timer);\n waiter.Resolve({ Type: 'error', RequestId: id, Message: 'Edge AI worker disposed' });\n }\n this.pending.clear();\n\n if (this.port) {\n this.port.OnReply = null;\n this.port.Terminate();\n this.port = null;\n }\n }\n\n private async runEmbed(\n port: EdgeWorkerPort,\n texts: string[],\n timeoutMs: number,\n modelId?: string\n ): Promise<Float32Array[] | null> {\n const requestId = this.nextRequestId('embed');\n const reply = await this.sendRequest(\n port,\n {\n Type: 'embed',\n RequestId: requestId,\n Texts: texts,\n ModelId: modelId ?? this.initOptions.BiEncoderModelId,\n Device: this.initOptions.Device ?? 'wasm',\n DType: this.initOptions.DType ?? 'q8',\n },\n [],\n timeoutMs\n );\n if (reply?.Type === 'embedded') {\n this.consecutiveFailures = 0;\n return reply.Vectors.map((buf) => new Float32Array(buf));\n }\n this.recordFailure();\n return null;\n }\n\n private async runRerank(\n port: EdgeWorkerPort,\n query: string,\n documents: string[],\n timeoutMs: number,\n modelId?: string\n ): Promise<number[] | null> {\n const requestId = this.nextRequestId('rerank');\n const reply = await this.sendRequest(\n port,\n {\n Type: 'rerank',\n RequestId: requestId,\n Query: query,\n Documents: documents,\n ModelId: modelId ?? this.initOptions.CrossEncoderModelId,\n Device: this.initOptions.Device ?? 'wasm',\n DType: this.initOptions.DType ?? 'q8',\n },\n [],\n timeoutMs\n );\n if (reply?.Type === 'reranked') {\n this.isCrossEncoderReady = true;\n this.consecutiveFailures = 0;\n return reply.Logits;\n }\n this.recordFailure();\n return null;\n }\n\n private ensurePort(): EdgeWorkerPort | null {\n if (this.port) {\n return this.port;\n }\n try {\n const port = this.portFactory ? this.portFactory() : this.createBrowserWorkerPort();\n port.OnReply = (reply) => this.handleReply(reply);\n this.port = port;\n return port;\n } catch {\n return null;\n }\n }\n\n private createBrowserWorkerPort(): EdgeWorkerPort {\n const globalStore = GetGlobalObjectStore() as Record<string, unknown>;\n const hostFactory = globalStore[EDGE_AI_WORKER_FACTORY_STORE_KEY];\n if (typeof hostFactory === 'function') {\n const custom = (hostFactory as () => BrowserWorkerLike | EdgeWorkerPort)();\n if (custom && typeof (custom as EdgeWorkerPort).Post === 'function') {\n return custom as EdgeWorkerPort;\n }\n return new BrowserEdgeWorkerPort(custom as BrowserWorkerLike);\n }\n // Resolve the pre-bundled worker asset copied from @memberjunction/ng-explorer-app/dist/assets\n // relative to the document base URI so consumer apps require zero app-level worker wiring.\n const baseUri =\n typeof document !== 'undefined' && document.baseURI\n ? document.baseURI\n : typeof globalThis.location !== 'undefined' && globalThis.location.href\n ? globalThis.location.href\n : undefined;\n const workerUrl = baseUri\n ? new URL('assets/edge-ai.worker.js', baseUri)\n : new URL('./edge-ai.worker.js', import.meta.url);\n const worker = new Worker(workerUrl, { type: 'module' });\n return new BrowserEdgeWorkerPort(worker as unknown as BrowserWorkerLike);\n }\n\n private handleReply(reply: EdgeWorkerReply): void {\n const reqId = 'RequestId' in reply ? reply.RequestId : undefined;\n if (reqId && this.pending.has(reqId)) {\n const waiter = this.pending.get(reqId)!;\n this.pending.delete(reqId);\n clearTimeout(waiter.Timer);\n waiter.Resolve(reply);\n return;\n }\n // Uncorrelated worker error (e.g. worker.onerror crash): fail all pending requests\n if (reply.Type === 'error' && !reqId) {\n this.isReady = false;\n this.isCrossEncoderReady = false;\n for (const [id, waiter] of this.pending) {\n clearTimeout(waiter.Timer);\n waiter.Resolve({ Type: 'error', RequestId: id, Message: reply.Message });\n }\n this.pending.clear();\n if (this.port) {\n this.port.OnReply = null;\n this.port.Terminate();\n this.port = null;\n }\n }\n }\n\n private sendRequest(\n port: EdgeWorkerPort,\n request: EdgeWorkerRequest,\n transfer: Transferable[],\n timeoutMs: number\n ): Promise<EdgeWorkerReply | null> {\n const requestId = request.RequestId;\n return new Promise<EdgeWorkerReply | null>((resolve) => {\n const timer = setTimeout(() => {\n this.pending.delete(requestId);\n resolve(null);\n }, Math.max(1, timeoutMs));\n\n this.pending.set(requestId, {\n Timer: timer,\n Resolve: (reply) => resolve(reply),\n });\n\n try {\n port.Post(request, transfer);\n } catch (err: unknown) {\n this.pending.delete(requestId);\n clearTimeout(timer);\n resolve({\n Type: 'error',\n RequestId: requestId,\n Message: err instanceof Error ? err.message : String(err),\n });\n }\n });\n }\n\n private recordFailure(): void {\n this.consecutiveFailures++;\n if (this.consecutiveFailures >= EDGE_WORKER_CIRCUIT_FAILURE_THRESHOLD) {\n this.circuitOpenUntil = Date.now() + EDGE_WORKER_CIRCUIT_COOLDOWN_MS;\n }\n }\n\n private nextRequestId(prefix: string): string {\n return `${prefix}-${this.nextRequestSeq++}`;\n }\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Dedicated lazy Web Worker running quantized (`q8`) ONNX inference in WASM
|
|
3
|
+
* (`Xenova/bge-small-en-v1.5` bi-encoder + `Xenova/ms-marco-MiniLM-L-6-v2` cross-encoder).
|
|
4
|
+
*
|
|
5
|
+
* Loaded ONLY on demand via `new Worker(new URL('./edge-ai.worker.js', import.meta.url), { type: 'module' })`
|
|
6
|
+
* so zero `@huggingface/transformers` or ONNX WASM code enters Explorer's initial bundle.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Attaches the Edge AI message handler inside a Web Worker global scope.
|
|
10
|
+
* Exported so host apps (e.g., MJExplorer) with `sideEffects: false` retain the worker bundle cleanly.
|
|
11
|
+
*/
|
|
12
|
+
export declare function BootstrapEdgeAIWorker(): void;
|
|
13
|
+
//# sourceMappingURL=edge-ai.worker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edge-ai.worker.d.ts","sourceRoot":"","sources":["../../../../src/lib/services/edge-ai/edge-ai.worker.ts"],"names":[],"mappings":"AACA;;;;;;GAMG;AA2QH;;;GAGG;AACH,wBAAgB,qBAAqB,IAAI,IAAI,CAQ5C"}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/// <reference lib="webworker" />
|
|
2
|
+
/**
|
|
3
|
+
* @fileoverview Dedicated lazy Web Worker running quantized (`q8`) ONNX inference in WASM
|
|
4
|
+
* (`Xenova/bge-small-en-v1.5` bi-encoder + `Xenova/ms-marco-MiniLM-L-6-v2` cross-encoder).
|
|
5
|
+
*
|
|
6
|
+
* Loaded ONLY on demand via `new Worker(new URL('./edge-ai.worker.js', import.meta.url), { type: 'module' })`
|
|
7
|
+
* so zero `@huggingface/transformers` or ONNX WASM code enters Explorer's initial bundle.
|
|
8
|
+
*/
|
|
9
|
+
import { EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL, EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL, } from '@memberjunction/ai-core-plus';
|
|
10
|
+
let transformersPromise = null;
|
|
11
|
+
let biEncoderPromise = null;
|
|
12
|
+
let biEncoderKey = '';
|
|
13
|
+
let crossEncoderPromise = null;
|
|
14
|
+
let crossEncoderKey = '';
|
|
15
|
+
function loadTransformers() {
|
|
16
|
+
if (!transformersPromise) {
|
|
17
|
+
// Dynamic import, category 3 (genuine bundle-size deferral, Rule 8) + category 2 (optionalDependency):
|
|
18
|
+
// '@huggingface/transformers' and ONNX WASM runtime load strictly inside this lazy Web Worker
|
|
19
|
+
// so Explorer's initial and app-module bundles incur 0 B overhead.
|
|
20
|
+
transformersPromise = import('@huggingface/transformers').catch((err) => {
|
|
21
|
+
transformersPromise = null;
|
|
22
|
+
throw err;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
return transformersPromise;
|
|
26
|
+
}
|
|
27
|
+
async function ensureBiEncoder(modelId, device, dtype) {
|
|
28
|
+
const key = `${modelId}|${device}|${dtype}`;
|
|
29
|
+
if (!biEncoderPromise || biEncoderKey !== key) {
|
|
30
|
+
biEncoderKey = key;
|
|
31
|
+
biEncoderPromise = (async () => {
|
|
32
|
+
const tf = await loadTransformers();
|
|
33
|
+
return tf.pipeline('feature-extraction', modelId, { device, dtype });
|
|
34
|
+
})().catch((err) => {
|
|
35
|
+
if (biEncoderKey === key) {
|
|
36
|
+
biEncoderPromise = null;
|
|
37
|
+
biEncoderKey = '';
|
|
38
|
+
}
|
|
39
|
+
throw err;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
return biEncoderPromise;
|
|
43
|
+
}
|
|
44
|
+
async function ensureCrossEncoder(modelId, device, dtype) {
|
|
45
|
+
const key = `${modelId}|${device}|${dtype}`;
|
|
46
|
+
if (!crossEncoderPromise || crossEncoderKey !== key) {
|
|
47
|
+
crossEncoderKey = key;
|
|
48
|
+
crossEncoderPromise = (async () => {
|
|
49
|
+
const tf = await loadTransformers();
|
|
50
|
+
const [tok, mod] = await Promise.all([
|
|
51
|
+
tf.AutoTokenizer.from_pretrained(modelId),
|
|
52
|
+
tf.AutoModelForSequenceClassification.from_pretrained(modelId, { device, dtype }),
|
|
53
|
+
]);
|
|
54
|
+
return { Tokenizer: tok, Model: mod };
|
|
55
|
+
})().catch((err) => {
|
|
56
|
+
if (crossEncoderKey === key) {
|
|
57
|
+
crossEncoderPromise = null;
|
|
58
|
+
crossEncoderKey = '';
|
|
59
|
+
}
|
|
60
|
+
throw err;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return crossEncoderPromise;
|
|
64
|
+
}
|
|
65
|
+
function postReply(reply, transfer = []) {
|
|
66
|
+
self.postMessage(reply, transfer);
|
|
67
|
+
}
|
|
68
|
+
async function handleMessage(msg) {
|
|
69
|
+
const t0 = performance.now();
|
|
70
|
+
try {
|
|
71
|
+
switch (msg.Type) {
|
|
72
|
+
case 'init': {
|
|
73
|
+
const tf = await loadTransformers();
|
|
74
|
+
tf.env.allowLocalModels = Boolean(msg.LocalModelPath);
|
|
75
|
+
tf.env.allowRemoteModels = msg.AllowRemoteModels ?? true;
|
|
76
|
+
if (msg.LocalModelPath) {
|
|
77
|
+
tf.env.localModelPath = msg.LocalModelPath;
|
|
78
|
+
}
|
|
79
|
+
if (msg.WasmPaths && tf.env.backends?.onnx?.wasm) {
|
|
80
|
+
tf.env.backends.onnx.wasm.wasmPaths = msg.WasmPaths;
|
|
81
|
+
}
|
|
82
|
+
const device = msg.Device ?? 'wasm';
|
|
83
|
+
const dtype = msg.DType ?? 'q8';
|
|
84
|
+
const biModel = msg.BiEncoderModelId ?? EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL;
|
|
85
|
+
await ensureBiEncoder(biModel, device, dtype);
|
|
86
|
+
let crossLoaded = false;
|
|
87
|
+
if (msg.LoadCrossEncoder) {
|
|
88
|
+
const crossModel = msg.CrossEncoderModelId ?? EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL;
|
|
89
|
+
await ensureCrossEncoder(crossModel, device, dtype);
|
|
90
|
+
crossLoaded = true;
|
|
91
|
+
}
|
|
92
|
+
postReply({
|
|
93
|
+
Type: 'ready',
|
|
94
|
+
RequestId: msg.RequestId,
|
|
95
|
+
BiEncoderModelId: biModel,
|
|
96
|
+
CrossEncoderLoaded: crossLoaded,
|
|
97
|
+
LoadMs: performance.now() - t0,
|
|
98
|
+
});
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
case 'embed': {
|
|
102
|
+
if (msg.Texts.length === 0) {
|
|
103
|
+
postReply({
|
|
104
|
+
Type: 'embedded',
|
|
105
|
+
RequestId: msg.RequestId,
|
|
106
|
+
Vectors: [],
|
|
107
|
+
Dimensions: 0,
|
|
108
|
+
DurationMs: 0,
|
|
109
|
+
});
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const ext = await ensureBiEncoder(msg.ModelId ?? EDGE_PRE_DISCOVERY_BI_ENCODER_MODEL, msg.Device ?? 'wasm', msg.DType ?? 'q8');
|
|
113
|
+
const out = await ext(msg.Texts, { pooling: 'mean', normalize: true });
|
|
114
|
+
const dims = out.dims[1] ?? Math.floor(out.data.length / msg.Texts.length);
|
|
115
|
+
const buffers = [];
|
|
116
|
+
for (let i = 0; i < msg.Texts.length; i++) {
|
|
117
|
+
const slice = out.data.slice(i * dims, (i + 1) * dims);
|
|
118
|
+
const copy = new Float32Array(slice.length);
|
|
119
|
+
copy.set(slice);
|
|
120
|
+
buffers.push(copy.buffer);
|
|
121
|
+
}
|
|
122
|
+
postReply({
|
|
123
|
+
Type: 'embedded',
|
|
124
|
+
RequestId: msg.RequestId,
|
|
125
|
+
Vectors: buffers,
|
|
126
|
+
Dimensions: dims,
|
|
127
|
+
DurationMs: performance.now() - t0,
|
|
128
|
+
}, buffers);
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
case 'rerank': {
|
|
132
|
+
if (msg.Documents.length === 0) {
|
|
133
|
+
postReply({
|
|
134
|
+
Type: 'reranked',
|
|
135
|
+
RequestId: msg.RequestId,
|
|
136
|
+
Logits: [],
|
|
137
|
+
DurationMs: 0,
|
|
138
|
+
});
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const { Tokenizer, Model } = await ensureCrossEncoder(msg.ModelId ?? EDGE_PRE_DISCOVERY_CROSS_ENCODER_MODEL, msg.Device ?? 'wasm', msg.DType ?? 'q8');
|
|
142
|
+
const queries = new Array(msg.Documents.length).fill(msg.Query);
|
|
143
|
+
const inputs = Tokenizer(queries, {
|
|
144
|
+
text_pair: msg.Documents,
|
|
145
|
+
padding: true,
|
|
146
|
+
truncation: true,
|
|
147
|
+
});
|
|
148
|
+
const out = await Model(inputs);
|
|
149
|
+
const numLabels = out.logits.dims[1] ?? 1;
|
|
150
|
+
const logits = [];
|
|
151
|
+
for (let i = 0; i < msg.Documents.length; i++) {
|
|
152
|
+
const idx = numLabels === 1 ? i : i * numLabels + (numLabels - 1);
|
|
153
|
+
logits.push(Number(out.logits.data[idx] ?? Number.NEGATIVE_INFINITY));
|
|
154
|
+
}
|
|
155
|
+
postReply({
|
|
156
|
+
Type: 'reranked',
|
|
157
|
+
RequestId: msg.RequestId,
|
|
158
|
+
Logits: logits,
|
|
159
|
+
DurationMs: performance.now() - t0,
|
|
160
|
+
});
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
case 'dispose': {
|
|
164
|
+
biEncoderPromise = null;
|
|
165
|
+
biEncoderKey = '';
|
|
166
|
+
crossEncoderPromise = null;
|
|
167
|
+
crossEncoderKey = '';
|
|
168
|
+
postReply({
|
|
169
|
+
Type: 'disposed',
|
|
170
|
+
RequestId: msg.RequestId,
|
|
171
|
+
});
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
postReply({
|
|
178
|
+
Type: 'error',
|
|
179
|
+
RequestId: 'RequestId' in msg ? msg.RequestId : undefined,
|
|
180
|
+
Message: err instanceof Error ? err.message : String(err),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
let isBootstrapped = false;
|
|
185
|
+
/**
|
|
186
|
+
* Attaches the Edge AI message handler inside a Web Worker global scope.
|
|
187
|
+
* Exported so host apps (e.g., MJExplorer) with `sideEffects: false` retain the worker bundle cleanly.
|
|
188
|
+
*/
|
|
189
|
+
export function BootstrapEdgeAIWorker() {
|
|
190
|
+
if (isBootstrapped) {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
isBootstrapped = true;
|
|
194
|
+
self.onmessage = (event) => {
|
|
195
|
+
void handleMessage(event.data);
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
if (typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope) {
|
|
199
|
+
BootstrapEdgeAIWorker();
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=edge-ai.worker.js.map
|