@zerogpu/browser-extension-sdk 0.1.4 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const SDK_VERSION = typeof "0.1.4+a9295b5" === 'string' && "0.1.4+a9295b5".length > 0
2
- ? "0.1.4+a9295b5"
1
+ const SDK_VERSION = typeof "0.1.7+371d38a" === 'string' && "0.1.7+371d38a".length > 0
2
+ ? "0.1.7+371d38a"
3
3
  : '0.0.0-dev';
4
4
 
5
5
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -8,16 +8,21 @@ const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' &
8
8
 
9
9
  // The orchestrator URL is baked in at build time per deployment (develop/staging/
10
10
  // production). See ./orchestrator-url for the env-var injection and fallback.
11
+ // Fallback re-registration delay (seconds) after a WebSocket close, used when
12
+ // the register response carried no configSettings for this SDK type.
13
+ const DEFAULT_REREGISTER_INTERVAL_SECONDS = 600;
11
14
  const DEFAULT_CONFIG = {
12
15
  sdkVersion: SDK_VERSION,
13
16
  orchestrator: {
14
17
  baseUrl: ORCHESTRATOR_BASE_URL,
15
- registerPath: '/register'
18
+ registerPath: '/register',
19
+ eventsPath: '/events'
16
20
  },
17
21
  telemetry: {
18
22
  enableConsoleLogs: false,
19
23
  locationData: false,
20
- cameraData: false
24
+ cameraData: false,
25
+ events: true
21
26
  }
22
27
  };
23
28
 
@@ -28,12 +33,14 @@ const resolveConfig = (overrides) => {
28
33
  sdkVersion: asNonEmptyString(merged.sdkVersion, base.sdkVersion),
29
34
  orchestrator: {
30
35
  baseUrl: asNonEmptyString(merged.orchestrator?.baseUrl, base.orchestrator.baseUrl),
31
- registerPath: asNonEmptyString(merged.orchestrator?.registerPath, base.orchestrator.registerPath)
36
+ registerPath: asNonEmptyString(merged.orchestrator?.registerPath, base.orchestrator.registerPath),
37
+ eventsPath: asNonEmptyString(merged.orchestrator?.eventsPath, base.orchestrator.eventsPath)
32
38
  },
33
39
  telemetry: {
34
40
  enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
35
41
  locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
36
- cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData)
42
+ cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData),
43
+ events: asBoolean(merged.telemetry?.events, base.telemetry.events)
37
44
  }
38
45
  };
39
46
  };
@@ -84,20 +91,21 @@ class Logger {
84
91
  console.error('[ZeroGPU]', ...args);
85
92
  }
86
93
  }
87
- let singleton = null;
94
+ let singleton$1 = null;
88
95
  const initLogger = (config) => {
89
- singleton = new Logger(config);
90
- return singleton;
96
+ singleton$1 = new Logger(config);
97
+ return singleton$1;
91
98
  };
92
99
  const getLogger = () => {
93
- if (!singleton) {
94
- singleton = new Logger({
100
+ if (!singleton$1) {
101
+ singleton$1 = new Logger({
95
102
  enableConsoleLogs: false,
96
103
  locationData: false,
97
- cameraData: false
104
+ cameraData: false,
105
+ events: true
98
106
  });
99
107
  }
100
- return singleton;
108
+ return singleton$1;
101
109
  };
102
110
 
103
111
  const DEVICE_ID_KEY = 'zerogpu_device_id';
@@ -461,6 +469,7 @@ class WebSocketClient {
461
469
  this.consoleWithVerbose = console;
462
470
  this.handleOpen = () => {
463
471
  this.logger.info('WebSocket connection opened');
472
+ this.options.onOpen?.();
464
473
  this.logger.debug('Sending hello message:', this.options.hello);
465
474
  this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
466
475
  this.send(this.options.hello);
@@ -522,6 +531,9 @@ class WebSocketClient {
522
531
  this.socket.onerror = this.handleError;
523
532
  this.socket.onclose = this.handleClose;
524
533
  }
534
+ isActive() {
535
+ return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
536
+ }
525
537
  send(payload) {
526
538
  this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
527
539
  this.socket.send(JSON.stringify(payload));
@@ -578,6 +590,12 @@ const setSessionKey = (sessionKey) => {
578
590
  const setWebSocket = (ws) => {
579
591
  state.ws = ws;
580
592
  };
593
+ // Safe before full init (unlike getState) — used by the re-registration guard.
594
+ const getWebSocket = () => state.ws;
595
+ const setRegistrationSettings = (settings) => {
596
+ state.registrationSettings = settings ?? null;
597
+ };
598
+ const getRegistrationSettings = () => state.registrationSettings ?? null;
581
599
  const setStatus = (status) => {
582
600
  state.status = status;
583
601
  };
@@ -600,6 +618,360 @@ const getAdapterFactory = (framework, taskType) => {
600
618
  return factories.find((factory) => factory.capabilities.some((capability) => matches(capability, framework, taskType)));
601
619
  };
602
620
 
621
+ // Local mirror of the device lifecycle event vocabulary from
622
+ // @zerogpu/global-types. The SDK keeps its own copy so it stays zero-runtime-
623
+ // dependency; an alignment test (event-types.alignment.test.ts) pins these
624
+ // values to the published package so the two can never drift.
625
+ const DEVICE_EVENT_SEVERITY = {
626
+ 'sdk.init_started': 'info',
627
+ 'sdk.init_succeeded': 'info',
628
+ 'sdk.init_failed': 'error',
629
+ 'sdk.shutdown': 'info',
630
+ 'sdk.crash_detected': 'fatal',
631
+ 'host.foreground': 'info',
632
+ 'host.background': 'info',
633
+ 'register.started': 'info',
634
+ 'register.succeeded': 'info',
635
+ 'register.failed': 'error',
636
+ 'register.rejected': 'warning',
637
+ 'model.assigned': 'info',
638
+ 'model.cache_hit': 'info',
639
+ 'model.cache_invalid': 'warning',
640
+ 'model.cache_purged': 'info',
641
+ 'model.download_started': 'info',
642
+ 'model.download_succeeded': 'info',
643
+ 'model.download_failed': 'error',
644
+ 'model.load_started': 'info',
645
+ 'model.load_succeeded': 'info',
646
+ 'model.load_failed': 'error',
647
+ 'model.sample_succeeded': 'info',
648
+ 'model.sample_failed': 'error',
649
+ 'model.evicted': 'warning',
650
+ 'ws.connect_started': 'info',
651
+ 'ws.connected': 'info',
652
+ 'ws.hello_ack': 'info',
653
+ 'ws.closed': 'warning',
654
+ 'ws.error': 'error',
655
+ 'ws.reconnect_scheduled': 'info',
656
+ 'ws.init_failure_reported': 'error',
657
+ 'task.failed': 'error',
658
+ 'task.rejected': 'warning',
659
+ 'task.slow': 'warning',
660
+ 'guardrail.preflight_blocked': 'warning',
661
+ 'guardrail.pressure_warning': 'warning',
662
+ 'guardrail.degraded': 'warning',
663
+ 'guardrail.shutdown': 'fatal',
664
+ 'guardrail.model_blocklisted': 'warning',
665
+ 'ws.session_opened': 'info',
666
+ 'ws.session_authenticated': 'info',
667
+ 'ws.session_rejected': 'warning',
668
+ 'ws.session_superseded': 'info',
669
+ 'ws.session_closed': 'info',
670
+ 'dispatch.sent': 'info',
671
+ 'dispatch.completed': 'info',
672
+ 'dispatch.timeout': 'error',
673
+ 'dispatch.failed_offline': 'warning',
674
+ 'registry.status_changed': 'info'
675
+ };
676
+ const HELLO_ACK_OK_CODES = new Set(['ok', 'idle', 'ready']);
677
+ const getDeviceEventSeverity = (type, code) => {
678
+ if (type === 'ws.hello_ack' && code && !HELLO_ACK_OK_CODES.has(code)) {
679
+ return 'error';
680
+ }
681
+ return DEVICE_EVENT_SEVERITY[type] ?? 'info';
682
+ };
683
+
684
+ // Persisted ring buffer for events that couldn't be delivered (offline, non-2xx,
685
+ // or a terminal flush that never returned). Oldest events drop first. Drained on
686
+ // the next successful init so a session that died before connecting still reports
687
+ // its failures. All storage access is swallowed — a full/blocked localStorage
688
+ // must never break the SDK.
689
+ const EVENT_BUFFER_KEY = 'zerogpu_event_buffer';
690
+ const MAX_BUFFERED_EVENTS = 100;
691
+ const safeGet = (key) => {
692
+ try {
693
+ return window.localStorage.getItem(key);
694
+ }
695
+ catch {
696
+ return null;
697
+ }
698
+ };
699
+ const safeSet = (key, value) => {
700
+ try {
701
+ window.localStorage.setItem(key, value);
702
+ }
703
+ catch {
704
+ // Quota exceeded / private mode / partitioned storage — degrade silently.
705
+ }
706
+ };
707
+ const loadBufferedEvents = () => {
708
+ const raw = safeGet(EVENT_BUFFER_KEY);
709
+ if (!raw)
710
+ return [];
711
+ try {
712
+ const parsed = JSON.parse(raw);
713
+ return Array.isArray(parsed) ? parsed : [];
714
+ }
715
+ catch {
716
+ return [];
717
+ }
718
+ };
719
+ const saveBufferedEvents = (events) => {
720
+ const trimmed = events.length > MAX_BUFFERED_EVENTS ? events.slice(-MAX_BUFFERED_EVENTS) : events;
721
+ safeSet(EVENT_BUFFER_KEY, JSON.stringify(trimmed));
722
+ };
723
+ const appendBufferedEvents = (events) => {
724
+ if (events.length === 0)
725
+ return;
726
+ saveBufferedEvents([...loadBufferedEvents(), ...events]);
727
+ };
728
+ const clearBufferedEvents = () => {
729
+ try {
730
+ window.localStorage.removeItem(EVENT_BUFFER_KEY);
731
+ }
732
+ catch {
733
+ // ignore storage failures
734
+ }
735
+ };
736
+
737
+ // One sessionId per SDK boot, created at module load. The re-registration loop
738
+ // re-runs startLifecycle per cycle, so this must NOT be minted inside it — the
739
+ // seq counter keeps climbing across reconnects within a single boot.
740
+ const SESSION_ID = createUuid();
741
+ const FLUSH_INTERVAL_MS = 10000;
742
+ const FLUSH_BATCH_SIZE = 20;
743
+ const MAX_EVENTS_PER_REQUEST = 20;
744
+ const SESSION_EVENT_CAP = 200;
745
+ const DEDUP_WINDOW_MS = 30000;
746
+ const MESSAGE_MAX_CHARS = 256;
747
+ class EventReporter {
748
+ constructor(options) {
749
+ this.options = options;
750
+ this.queue = [];
751
+ this.seq = 0;
752
+ this.emittedCount = 0;
753
+ this.capped = false;
754
+ this.timer = null;
755
+ this.lastByTypeCode = new Map();
756
+ this.listenersBound = false;
757
+ this.boundPageHide = null;
758
+ this.boundVisibilityChange = null;
759
+ if (!options.enabled)
760
+ return;
761
+ // Drain any events from a previous (possibly crashed) session first, so
762
+ // register.failed / crash markers reach the registry on the next boot.
763
+ this.queue.push(...loadBufferedEvents());
764
+ clearBufferedEvents();
765
+ this.bindTerminalFlush();
766
+ this.timer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
767
+ }
768
+ setSessionKey(key) {
769
+ this.sessionKey = key;
770
+ }
771
+ // True when this instance already owns the boot's session state, so
772
+ // initEventReporter can keep it alive across reconnects instead of rebuilding.
773
+ matches(deviceId, enabled) {
774
+ return this.options.enabled === enabled && this.options.deviceId === deviceId;
775
+ }
776
+ // Stops the flush timer and unbinds the terminal-flush listeners. Called when a
777
+ // new reporter replaces this one so neither intervals nor window listeners
778
+ // accumulate across startLifecycle re-registrations.
779
+ dispose() {
780
+ if (this.timer !== null) {
781
+ clearInterval(this.timer);
782
+ this.timer = null;
783
+ }
784
+ if (typeof window !== 'undefined') {
785
+ if (this.boundPageHide)
786
+ window.removeEventListener('pagehide', this.boundPageHide);
787
+ if (this.boundVisibilityChange)
788
+ window.removeEventListener('visibilitychange', this.boundVisibilityChange);
789
+ }
790
+ this.boundPageHide = null;
791
+ this.boundVisibilityChange = null;
792
+ this.listenersBound = false;
793
+ }
794
+ report(type, fields = {}) {
795
+ try {
796
+ if (!this.options.enabled)
797
+ return;
798
+ if (this.emittedCount >= SESSION_EVENT_CAP) {
799
+ if (!this.capped) {
800
+ this.capped = true;
801
+ this.enqueue({ type: 'sdk.shutdown', fields: { code: 'unknown', data: { capped: true } } });
802
+ this.flush();
803
+ }
804
+ return;
805
+ }
806
+ const now = Date.now();
807
+ const dedupKey = `${type}:${fields.code ?? ''}`;
808
+ const prior = this.lastByTypeCode.get(dedupKey);
809
+ if (prior && now - prior.at < DEDUP_WINDOW_MS) {
810
+ const repeat = (Number(prior.event.data?.repeat) || 1) + 1;
811
+ prior.event.data = { ...(prior.event.data ?? {}), repeat };
812
+ prior.at = now;
813
+ return;
814
+ }
815
+ const event = this.enqueue({ type, fields });
816
+ this.lastByTypeCode.set(dedupKey, { event, at: now });
817
+ const severity = event.severity;
818
+ if (this.queue.length >= FLUSH_BATCH_SIZE || severity === 'error' || severity === 'fatal') {
819
+ // Detach from the hot path; flush() is itself fully guarded.
820
+ void Promise.resolve().then(() => this.flush());
821
+ }
822
+ }
823
+ catch {
824
+ // Telemetry must never throw into the SDK.
825
+ }
826
+ }
827
+ flush(opts = {}) {
828
+ try {
829
+ if (!this.options.enabled || this.queue.length === 0)
830
+ return;
831
+ const batch = this.queue.slice(0, MAX_EVENTS_PER_REQUEST);
832
+ this.queue = this.queue.slice(MAX_EVENTS_PER_REQUEST);
833
+ // Drop dedup tracking for events leaving the queue. FLUSH_INTERVAL_MS (10s)
834
+ // is shorter than DEDUP_WINDOW_MS (30s), so without this a duplicate arriving
835
+ // after the original was flushed would mutate an already-sent event and be
836
+ // lost. Clearing the entry forces the next duplicate to enqueue afresh.
837
+ const inFlight = new Set(batch);
838
+ for (const [key, entry] of this.lastByTypeCode) {
839
+ if (inFlight.has(entry.event))
840
+ this.lastByTypeCode.delete(key);
841
+ }
842
+ const envelope = {
843
+ v: 1,
844
+ deviceId: this.options.deviceId,
845
+ sessionId: SESSION_ID,
846
+ sdkVersion: this.options.sdkVersion,
847
+ edgeSdkType: this.options.edgeSdkType,
848
+ platform: this.options.platform,
849
+ ...(this.sessionKey ? { sessionKey: this.sessionKey } : {}),
850
+ events: batch
851
+ };
852
+ if (opts.beacon) {
853
+ this.sendBeacon(envelope, batch);
854
+ return;
855
+ }
856
+ this.sendFetch(envelope, batch);
857
+ }
858
+ catch {
859
+ // ignore
860
+ }
861
+ }
862
+ enqueue(params) {
863
+ const { type, fields } = params;
864
+ const event = {
865
+ eventId: createUuid(),
866
+ type,
867
+ ts: new Date().toISOString(),
868
+ seq: this.seq++,
869
+ severity: getDeviceEventSeverity(type, fields.code),
870
+ code: fields.code,
871
+ message: fields.message ? fields.message.slice(0, MESSAGE_MAX_CHARS) : undefined,
872
+ modelId: fields.modelId,
873
+ modelVersion: fields.modelVersion,
874
+ taskType: fields.taskType,
875
+ durationMs: fields.durationMs,
876
+ bytes: fields.bytes,
877
+ data: fields.data
878
+ };
879
+ this.queue.push(event);
880
+ this.emittedCount += 1;
881
+ return event;
882
+ }
883
+ // sendBeacon cannot set headers, so the operator key rides inside the
884
+ // envelope (the /events handler accepts body.edgeOperatorKey as a fallback).
885
+ sendBeacon(envelope, batch) {
886
+ const body = JSON.stringify({ ...envelope, edgeOperatorKey: this.options.operatorKey });
887
+ let sent = false;
888
+ try {
889
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
890
+ sent = navigator.sendBeacon(this.options.endpointUrl, new Blob([body], { type: 'application/json' }));
891
+ }
892
+ }
893
+ catch {
894
+ sent = false;
895
+ }
896
+ if (!sent) {
897
+ // Fallback: keepalive fetch survives the unload of the page too.
898
+ try {
899
+ void fetch(this.options.endpointUrl, {
900
+ method: 'POST',
901
+ keepalive: true,
902
+ headers: { 'content-type': 'application/json', 'x-edge-operator-key': this.options.operatorKey },
903
+ body
904
+ }).catch(() => appendBufferedEvents(batch));
905
+ }
906
+ catch {
907
+ appendBufferedEvents(batch);
908
+ }
909
+ }
910
+ }
911
+ sendFetch(envelope, batch) {
912
+ try {
913
+ void fetch(this.options.endpointUrl, {
914
+ method: 'POST',
915
+ keepalive: true,
916
+ headers: { 'content-type': 'application/json', 'x-edge-operator-key': this.options.operatorKey },
917
+ body: JSON.stringify(envelope)
918
+ })
919
+ .then((res) => {
920
+ // Any non-2xx: drop-and-move-on but persist for next boot's drain.
921
+ if (!res.ok)
922
+ appendBufferedEvents(batch);
923
+ })
924
+ .catch(() => appendBufferedEvents(batch));
925
+ }
926
+ catch {
927
+ appendBufferedEvents(batch);
928
+ }
929
+ }
930
+ bindTerminalFlush() {
931
+ if (this.listenersBound || typeof window === 'undefined')
932
+ return;
933
+ this.listenersBound = true;
934
+ try {
935
+ this.boundPageHide = () => this.flush({ beacon: true });
936
+ this.boundVisibilityChange = () => {
937
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
938
+ this.flush({ beacon: true });
939
+ }
940
+ };
941
+ window.addEventListener('pagehide', this.boundPageHide);
942
+ window.addEventListener('visibilitychange', this.boundVisibilityChange);
943
+ }
944
+ catch {
945
+ // Listener binding failures are non-fatal.
946
+ }
947
+ }
948
+ }
949
+ let singleton = null;
950
+ // A disabled/uninitialized reporter is a real object whose methods are no-ops,
951
+ // so callers never need to null-check getEventReporter().
952
+ const NOOP = new EventReporter({
953
+ enabled: false,
954
+ endpointUrl: '',
955
+ operatorKey: '',
956
+ deviceId: '',
957
+ sdkVersion: '',
958
+ platform: ''
959
+ });
960
+ const initEventReporter = (options) => {
961
+ // startLifecycle() calls this on every re-registration, but the session cap,
962
+ // dedup window, and seq counter are per-boot. Keep the live reporter across
963
+ // reconnects so those don't reset each cycle; only rebuild it on a genuine
964
+ // identity/enablement change (or a true cold start, where singleton is null).
965
+ if (singleton && singleton.matches(options.deviceId, options.enabled))
966
+ return;
967
+ // Flush anything the previous instance still held, then stop its timer and
968
+ // unbind its listeners before replacing it.
969
+ singleton?.flush();
970
+ singleton?.dispose();
971
+ singleton = new EventReporter(options);
972
+ };
973
+ const getEventReporter = () => singleton ?? NOOP;
974
+
603
975
  let executing = false;
604
976
  const buildInferenceInput = (request) => {
605
977
  const input = request.input ?? {};
@@ -657,6 +1029,7 @@ const executeSingleRequest = async (request) => {
657
1029
  adapter = await lazyLoadAdapter(request.modelId);
658
1030
  }
659
1031
  if (!adapter) {
1032
+ getEventReporter().report('task.rejected', { code: 'not_ready', modelId: request.modelId });
660
1033
  return {
661
1034
  requestId: request.requestId,
662
1035
  modelId: request.modelId,
@@ -686,6 +1059,12 @@ const executeSingleRequest = async (request) => {
686
1059
  }
687
1060
  catch (error) {
688
1061
  logger.error('Task failed', error);
1062
+ getEventReporter().report('task.failed', {
1063
+ code: 'adapter_error',
1064
+ modelId: request.modelId,
1065
+ durationMs: Math.round(performance.now() - start),
1066
+ message: error.message
1067
+ });
689
1068
  return {
690
1069
  requestId: request.requestId,
691
1070
  modelId: request.modelId,
@@ -714,6 +1093,7 @@ const handleIncomingMessage = async (msg) => {
714
1093
  return;
715
1094
  }
716
1095
  if (executing) {
1096
+ getEventReporter().report('task.rejected', { code: 'busy' });
717
1097
  sendBatchResponse(msg.requests.map((request) => ({
718
1098
  requestId: request.requestId,
719
1099
  modelId: request.modelId,
@@ -867,22 +1247,219 @@ const clearCachedModelInfo = (modelId) => {
867
1247
  safeRemoveItem(CACHED_MODEL_ID_KEY);
868
1248
  };
869
1249
 
1250
+ /**
1251
+ * Crash-loop guard for SDK initialization.
1252
+ *
1253
+ * On a brand-new device the lifecycle synchronously downloads and instantiates a
1254
+ * full model (and runs a sample inference) before connecting the WebSocket. In a
1255
+ * memory-constrained host such as a Telegram mini-app WebView this burst can
1256
+ * crash/OOM the view. The host then reloads the mini-app, the SDK runs the same
1257
+ * heavy first-run path again, crashes again, and the app appears to "refresh
1258
+ * continuously".
1259
+ *
1260
+ * Nothing in the previous flow recorded a *failed* attempt: the cache pointer is
1261
+ * only written after a fully successful load, so every reload looked like a fresh
1262
+ * first run. This guard persists a small attempt counter *before* the heavy work
1263
+ * and clears it only once init reaches a stable point. If we see several attempts
1264
+ * in a short window that never completed, we assume a crash loop and skip the
1265
+ * heavy init for a cool-down period, which breaks the refresh cycle and lets the
1266
+ * host app stay up.
1267
+ */
1268
+ const INIT_STATE_KEY = 'zerogpu_init_state';
1269
+ /** Attempts that never completed are only counted within this rolling window. */
1270
+ const ATTEMPT_WINDOW_MS = 60000;
1271
+ /** Number of uncompleted attempts in the window that trips the cool-down. */
1272
+ const MAX_ATTEMPTS_IN_WINDOW = 3;
1273
+ /** How long to skip heavy init once a crash loop is detected. */
1274
+ const COOLDOWN_MS = 5 * 60000;
1275
+ const readState = () => {
1276
+ try {
1277
+ const raw = window.localStorage.getItem(INIT_STATE_KEY);
1278
+ if (!raw)
1279
+ return null;
1280
+ const parsed = JSON.parse(raw);
1281
+ if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
1282
+ return null;
1283
+ }
1284
+ return parsed;
1285
+ }
1286
+ catch {
1287
+ return null;
1288
+ }
1289
+ };
1290
+ const writeState = (state) => {
1291
+ try {
1292
+ window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
1293
+ }
1294
+ catch {
1295
+ // Storage may be unavailable/partitioned; degrade silently.
1296
+ }
1297
+ };
1298
+ const clearState = () => {
1299
+ try {
1300
+ window.localStorage.removeItem(INIT_STATE_KEY);
1301
+ }
1302
+ catch {
1303
+ // ignore
1304
+ }
1305
+ };
1306
+ /**
1307
+ * Records the start of an init attempt and decides whether heavy init may
1308
+ * proceed. Must be called once, before any heavy work, on every lifecycle start.
1309
+ */
1310
+ const beginInitAttempt = (now = Date.now()) => {
1311
+ const state = readState();
1312
+ // Still inside an active cool-down from a previously detected crash loop.
1313
+ if (state?.cooldownUntil && state.cooldownUntil > now) {
1314
+ return {
1315
+ allowed: false,
1316
+ cooldownRemainingMs: state.cooldownUntil - now,
1317
+ attempts: state.attempts
1318
+ };
1319
+ }
1320
+ // No prior state, or the previous window/cool-down has elapsed → start fresh.
1321
+ if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
1322
+ writeState({ attempts: 1, windowStart: now });
1323
+ return { allowed: true, attempts: 1 };
1324
+ }
1325
+ const attempts = state.attempts + 1;
1326
+ // Too many uncompleted attempts in the window → assume a crash loop and back
1327
+ // off so the host app stops reloading.
1328
+ if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
1329
+ writeState({
1330
+ attempts,
1331
+ windowStart: state.windowStart,
1332
+ cooldownUntil: now + COOLDOWN_MS
1333
+ });
1334
+ return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts };
1335
+ }
1336
+ writeState({ attempts, windowStart: state.windowStart });
1337
+ return { allowed: true, attempts };
1338
+ };
1339
+ /**
1340
+ * Clears crash tracking. Call once init reaches a stable point (e.g. the
1341
+ * WebSocket is connected), so successful loads never accumulate toward a trip.
1342
+ */
1343
+ const markInitSuccess = () => {
1344
+ clearState();
1345
+ };
1346
+
1347
+ // Re-registration loop: when the server idle-closes the WebSocket (or it drops
1348
+ // for any reason), wait device_timeout_interval_seconds and run the full
1349
+ // lifecycle again — re-registering refreshes device metrics and yields a new
1350
+ // session key + WS URL. A single pending timer at a time; before reconnecting
1351
+ // we check no socket is already live (infinite-loop guard).
1352
+ let reregisterTimerId = null;
1353
+ const clearReregisterTimer = () => {
1354
+ if (reregisterTimerId !== null) {
1355
+ clearTimeout(reregisterTimerId);
1356
+ reregisterTimerId = null;
1357
+ }
1358
+ };
1359
+ const resolveReregisterDelaySeconds = () => {
1360
+ const value = getRegistrationSettings()?.device_timeout_interval_seconds;
1361
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
1362
+ ? value
1363
+ : DEFAULT_REREGISTER_INTERVAL_SECONDS;
1364
+ };
1365
+ const scheduleReregistration = (options) => {
1366
+ const logger = getLogger();
1367
+ if (reregisterTimerId !== null) {
1368
+ logger.debug('[WS] Re-registration already scheduled; skipping');
1369
+ return;
1370
+ }
1371
+ const delaySeconds = resolveReregisterDelaySeconds();
1372
+ logger.info('[WS] Scheduling re-registration', { delaySeconds });
1373
+ reregisterTimerId = setTimeout(() => {
1374
+ reregisterTimerId = null;
1375
+ if (getWebSocket()?.isActive()) {
1376
+ logger.info('[WS] Active WebSocket present; skipping re-registration');
1377
+ return;
1378
+ }
1379
+ logger.info('[WS] Re-registration timer fired; restarting lifecycle');
1380
+ startLifecycle(options).catch((err) => {
1381
+ logger.error('[WS] Re-registration attempt failed; will retry', err);
1382
+ // Keep the loop alive on transient failures (register/network/model
1383
+ // errors). Auth failures and crash-loop cool-downs return cleanly from
1384
+ // startLifecycle without throwing, so they end the loop here.
1385
+ scheduleReregistration(options);
1386
+ });
1387
+ }, delaySeconds * 1000);
1388
+ };
1389
+ const extractRegistrationSettings = (configSettings) => {
1390
+ if (!configSettings || typeof configSettings !== 'object')
1391
+ return null;
1392
+ // The server nests settings under its resolved SDK type key; take the first
1393
+ // (only) entry rather than re-deriving our own type client-side.
1394
+ for (const value of Object.values(configSettings)) {
1395
+ if (value && typeof value === 'object')
1396
+ return value;
1397
+ }
1398
+ return null;
1399
+ };
870
1400
  const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
871
1401
  initLogger(config.telemetry);
872
1402
  const logger = getLogger();
873
1403
  setConfig(config);
1404
+ // A fresh (manual or scheduled) start supersedes any pending reconnect timer.
1405
+ clearReregisterTimer();
1406
+ const lifecycleOptions = {
1407
+ config,
1408
+ appUserId,
1409
+ edgeOperatorKey,
1410
+ deviceId: providedDeviceId
1411
+ };
1412
+ // Deterministic preflight validation runs before the crash-loop guard so a
1413
+ // misconfigured integration never consumes a crash-loop attempt (and never
1414
+ // triggers the camera/geo prompts below).
1415
+ if (!edgeOperatorKey) {
1416
+ throw new Error('Missing required header: x-edge-operator-key');
1417
+ }
1418
+ // Break runaway crash/reload loops (e.g. a constrained Telegram WebView that
1419
+ // OOM-crashes during the heavy first-run model load and is reloaded by the
1420
+ // host). If we detect several attempts in a short window that never reached a
1421
+ // stable point, skip heavy init for a cool-down so the app stops refreshing.
1422
+ const guard = beginInitAttempt();
1423
+ if (!guard.allowed) {
1424
+ setStatus('error');
1425
+ logger.warn('Init skipped: crash-loop guard active', {
1426
+ attempts: guard.attempts,
1427
+ cooldownRemainingMs: guard.cooldownRemainingMs
1428
+ });
1429
+ return;
1430
+ }
1431
+ const bootStartedAt = performance.now();
874
1432
  const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
875
1433
  const isFreshDevice = !providedDeviceId && !storedDeviceId;
876
1434
  const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
877
1435
  if (providedDeviceId) {
878
1436
  setDeviceId(providedDeviceId);
879
1437
  }
1438
+ logger.info('[Init] Starting lifecycle', {
1439
+ sdkVersion: config.sdkVersion,
1440
+ deviceId,
1441
+ isFreshDevice,
1442
+ providedDeviceId: Boolean(providedDeviceId),
1443
+ orchestrator: config.orchestrator?.baseUrl
1444
+ });
880
1445
  const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
881
1446
  const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
882
1447
  setDeviceContext(deviceId, sanitizedDeviceInfo);
883
- if (!edgeOperatorKey) {
884
- throw new Error('Missing required header: x-edge-operator-key');
885
- }
1448
+ initEventReporter({
1449
+ enabled: config.telemetry.events,
1450
+ endpointUrl: `${config.orchestrator.baseUrl}${config.orchestrator.eventsPath}`,
1451
+ operatorKey: edgeOperatorKey,
1452
+ deviceId,
1453
+ sdkVersion: config.sdkVersion,
1454
+ platform: sanitizedDeviceInfo.platform
1455
+ });
1456
+ const reporter = getEventReporter();
1457
+ reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
1458
+ logger.info('[Init] Device info collected', {
1459
+ platform: sanitizedDeviceInfo.platform,
1460
+ deviceType: sanitizedDeviceInfo.deviceType,
1461
+ gpuRenderer: sanitizedDeviceInfo.gpuRenderer
1462
+ });
886
1463
  if (rawDeviceInfo.camera?.previewDataUrl) {
887
1464
  try {
888
1465
  window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
@@ -1031,15 +1608,23 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1031
1608
  logFlow('Cached sample evaluated', cachedSampleMetrics);
1032
1609
  }
1033
1610
  if (cacheInvalid) {
1611
+ reporter.report('model.cache_invalid', {
1612
+ code: mapCacheInvalidCode(cachedSampleMetrics?.errorMessage),
1613
+ modelId: cachedInfo?.modelId ?? cachedModelId ?? undefined
1614
+ });
1034
1615
  await clearAllModels().catch(() => { });
1035
1616
  await clearTransformersCaches().catch(() => { });
1036
1617
  clearCachedModelInfo(cachedModelId);
1037
1618
  setCachedModelId(null);
1619
+ reporter.report('model.cache_purged');
1038
1620
  cachedInfo = null;
1039
1621
  cachedAdapter = undefined;
1040
1622
  setAdaptersByModelId({});
1041
1623
  setModelInfosByModelId({});
1042
1624
  }
1625
+ else if (cachedInfo && cachedAdapter) {
1626
+ reporter.report('model.cache_hit', { modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion });
1627
+ }
1043
1628
  const registerPayload = {
1044
1629
  deviceId,
1045
1630
  sdkVersion: config.sdkVersion,
@@ -1055,6 +1640,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1055
1640
  const modelStatuses = {};
1056
1641
  let loadErrorMessage;
1057
1642
  let postRegisterSample;
1643
+ logger.info('[Register] Sending register request', {
1644
+ deviceId,
1645
+ cachedModels: registerPayload.cachedModels,
1646
+ sdkVersion: config.sdkVersion
1647
+ });
1648
+ reporter.report('register.started');
1649
+ const registerStartedAt = performance.now();
1058
1650
  try {
1059
1651
  registerResponse = await registerDevice(config, registerPayload, {
1060
1652
  edgeOperatorKey
@@ -1064,19 +1656,50 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1064
1656
  if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
1065
1657
  logger.warn('Register auth failed, stopping lifecycle');
1066
1658
  logFlow('Auth failure; no WS connection', { status: err.status });
1659
+ reporter.report('register.failed', { code: 'auth' });
1660
+ reporter.report('sdk.init_failed', { code: 'auth' });
1661
+ markInitSuccess(); // Clean exit, not a crash loop.
1067
1662
  return;
1068
1663
  }
1664
+ reporter.report('register.failed', { code: mapRegisterErrorCode(err), message: err.message });
1665
+ reporter.report('sdk.init_failed', { code: mapRegisterErrorCode(err) });
1666
+ markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
1069
1667
  throw err;
1070
1668
  }
1669
+ reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
1670
+ reporter.setSessionKey(registerResponse.sessionKey);
1071
1671
  logger.info('Register response received:', {
1072
1672
  deviceId: registerResponse.deviceId,
1073
1673
  wsUrl: registerResponse.wsUrl
1074
1674
  });
1675
+ const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
1676
+ setRegistrationSettings(registrationSettings);
1677
+ if (registrationSettings) {
1678
+ logger.info('[Register] Registration settings received', registrationSettings);
1679
+ }
1075
1680
  if (!registerResponse.wsUrl) {
1681
+ markInitSuccess(); // Clean exit, not a crash loop.
1076
1682
  return;
1077
1683
  }
1078
1684
  assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
1079
1685
  const primaryModel = assignedModels[0];
1686
+ if (primaryModel) {
1687
+ reporter.report('model.assigned', {
1688
+ modelId: primaryModel.modelId,
1689
+ modelVersion: primaryModel.modelVersion,
1690
+ bytes: primaryModel.sizeBytes
1691
+ });
1692
+ }
1693
+ logger.info('[Register] Models assigned', {
1694
+ count: assignedModels.length,
1695
+ models: assignedModels.map((m) => ({
1696
+ modelId: m.modelId,
1697
+ framework: m.inferenceFramework,
1698
+ taskType: m.taskType,
1699
+ quantized: m.quantized,
1700
+ sizeBytes: m.sizeBytes
1701
+ }))
1702
+ });
1080
1703
  for (const model of assignedModels) {
1081
1704
  modelStatuses[getModelStatusKey(model)] = 'idle';
1082
1705
  modelInfosByModelId[model.modelId] = model;
@@ -1086,6 +1709,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1086
1709
  await clearTransformersCaches().catch(() => { });
1087
1710
  clearCachedModelInfo(cachedModelId);
1088
1711
  setCachedModelId(null);
1712
+ markInitSuccess(); // Clean exit (server assigned no model), not a crash loop.
1089
1713
  return;
1090
1714
  }
1091
1715
  setSessionKey(registerResponse.sessionKey);
@@ -1114,11 +1738,43 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1114
1738
  if (!factory) {
1115
1739
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1116
1740
  loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
1741
+ reporter.report('model.load_failed', {
1742
+ code: 'no_adapter_factory',
1743
+ modelId: primaryModel.modelId,
1744
+ modelVersion: primaryModel.modelVersion
1745
+ });
1746
+ logger.error('[Model] No adapter factory for primary model', {
1747
+ modelId: primaryModel.modelId,
1748
+ framework: slmConfig.inferenceFramework,
1749
+ taskType: slmConfig.taskType
1750
+ });
1117
1751
  }
1118
1752
  else {
1753
+ logger.info('[Model] Loading primary model', {
1754
+ modelId: primaryModel.modelId,
1755
+ framework: slmConfig.inferenceFramework,
1756
+ taskType: slmConfig.taskType,
1757
+ quantized: slmConfig.quantized,
1758
+ sizeBytes: primaryModel.sizeBytes,
1759
+ modelRepoId: primaryModel.modelRepoId
1760
+ });
1761
+ reporter.report('model.load_started', { modelId: primaryModel.modelId, modelVersion: primaryModel.modelVersion });
1762
+ const primaryLoadStart = performance.now();
1119
1763
  const loadResult = await factory.load(slmConfig);
1764
+ const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
1120
1765
  loadErrorMessage = loadResult.error?.message;
1121
1766
  if (loadResult.adapter) {
1767
+ reporter.report('model.load_succeeded', {
1768
+ modelId: primaryModel.modelId,
1769
+ modelVersion: primaryModel.modelVersion,
1770
+ durationMs: primaryLoadMs,
1771
+ bytes: loadResult.metrics?.sizeBytes
1772
+ });
1773
+ logger.info('[Model] Primary model loaded', {
1774
+ modelId: primaryModel.modelId,
1775
+ ms: primaryLoadMs,
1776
+ sizeBytes: loadResult.metrics?.sizeBytes
1777
+ });
1122
1778
  adaptersByModelId[primaryModel.modelId] = loadResult.adapter;
1123
1779
  setAdapter(primaryModel.modelId, loadResult.adapter);
1124
1780
  setCachedModelId(primaryModel.modelId);
@@ -1138,6 +1794,20 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1138
1794
  }
1139
1795
  else {
1140
1796
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1797
+ reporter.report('model.load_failed', {
1798
+ code: mapModelLoadErrorCode(loadErrorMessage),
1799
+ modelId: primaryModel.modelId,
1800
+ modelVersion: primaryModel.modelVersion,
1801
+ durationMs: primaryLoadMs,
1802
+ message: loadErrorMessage
1803
+ });
1804
+ logger.error('[Model] Primary model load failed', {
1805
+ modelId: primaryModel.modelId,
1806
+ framework: slmConfig.inferenceFramework,
1807
+ taskType: slmConfig.taskType,
1808
+ ms: primaryLoadMs,
1809
+ error: loadErrorMessage
1810
+ });
1141
1811
  }
1142
1812
  }
1143
1813
  }
@@ -1217,7 +1887,9 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1217
1887
  errorMessage: `primary_model_load_failed:${reason}`
1218
1888
  }
1219
1889
  }).catch(() => { });
1890
+ reporter.report('ws.init_failure_reported', { code: 'primary_model_load_failed', message: reason });
1220
1891
  }
1892
+ reporter.report('sdk.init_failed', { code: 'primary_model_load_failed', message: reason });
1221
1893
  logger.error('Primary model failed to initialize; aborting lifecycle before WebSocket connect', {
1222
1894
  modelId: primaryModel.modelId,
1223
1895
  modelVersion: primaryModel.modelVersion,
@@ -1227,14 +1899,34 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1227
1899
  throw new Error(`primary_model_load_failed:${reason}`);
1228
1900
  }
1229
1901
  if (primaryAdapter && primaryModel.sample?.text) {
1902
+ logger.info('[Sample] Running post-register sample inference', {
1903
+ taskType: primaryModel.taskType
1904
+ });
1230
1905
  postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1231
- logger.info('Post-register sample test result', {
1906
+ const sampleLog = {
1232
1907
  taskType: primaryModel.taskType,
1233
1908
  ok: postRegisterSample.ok,
1234
1909
  error: postRegisterSample.error,
1235
1910
  errorMessage: postRegisterSample.errorMessage,
1236
1911
  processingTimeMs: postRegisterSample.processingTimeMs
1237
- });
1912
+ };
1913
+ if (postRegisterSample.error || !postRegisterSample.ok) {
1914
+ reporter.report('model.sample_failed', {
1915
+ modelId: primaryModel.modelId,
1916
+ durationMs: postRegisterSample.processingTimeMs,
1917
+ message: postRegisterSample.errorMessage,
1918
+ data: { phase: 'post_register' }
1919
+ });
1920
+ logger.error('[Sample] Post-register sample failed', sampleLog);
1921
+ }
1922
+ else {
1923
+ reporter.report('model.sample_succeeded', {
1924
+ modelId: primaryModel.modelId,
1925
+ durationMs: postRegisterSample.processingTimeMs,
1926
+ data: { phase: 'post_register' }
1927
+ });
1928
+ logger.info('[Sample] Post-register sample ok', sampleLog);
1929
+ }
1238
1930
  if (postRegisterSample.error) {
1239
1931
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1240
1932
  }
@@ -1252,31 +1944,91 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1252
1944
  sdkVersion: config.sdkVersion,
1253
1945
  slmConfig: helloSlmConfig
1254
1946
  };
1947
+ logger.info('[WS] Connecting WebSocket', {
1948
+ wsUrl: registerResponse.wsUrl,
1949
+ models: helloSlmConfig
1950
+ });
1951
+ reporter.report('ws.connect_started');
1255
1952
  const client = new WebSocketClient({
1256
1953
  url: registerResponse.wsUrl,
1257
1954
  hello,
1955
+ onOpen: () => reporter.report('ws.connected'),
1258
1956
  onMessage: (message) => {
1259
1957
  if ('requests' in message && Array.isArray(message.requests)) {
1260
1958
  handleIncomingMessage(message);
1261
1959
  }
1262
1960
  else if ('type' in message && message.type === 'hello_ack') {
1263
1961
  const ack = message;
1264
- logger.info('Received WS hello_ack', ack);
1962
+ logger.info('[WS] Received hello_ack', ack);
1963
+ reporter.report('ws.hello_ack', {
1964
+ code: ack.status,
1965
+ message: ack.errorMessage
1966
+ });
1265
1967
  setStatus(ack.status === 'error' ? 'error' : 'idle');
1266
1968
  }
1267
1969
  else {
1268
- logger.debug('Unhandled WS message', message);
1970
+ logger.debug('[WS] Unhandled message', message);
1269
1971
  }
1270
1972
  },
1271
- onClose: () => {
1973
+ onClose: (event) => {
1974
+ logger.warn('[WS] Connection closed', { code: event.code, reason: event.reason });
1975
+ // Ignore closes from superseded sockets — a newer lifecycle run owns the
1976
+ // connection now.
1977
+ if (getWebSocket() !== client) {
1978
+ return;
1979
+ }
1980
+ reporter.report('ws.closed', {
1981
+ code: `close_${event.code}`,
1982
+ data: { wasClean: event.wasClean }
1983
+ });
1272
1984
  setStatus('error');
1985
+ scheduleReregistration(lifecycleOptions);
1273
1986
  },
1274
1987
  onError: () => {
1275
- setStatus('error');
1988
+ logger.error('[WS] Connection error');
1989
+ reporter.report('ws.error');
1990
+ if (getWebSocket() === client) {
1991
+ setStatus('error');
1992
+ }
1276
1993
  }
1277
1994
  });
1278
1995
  setWebSocket(client);
1279
1996
  setStatus('idle');
1997
+ reporter.report('sdk.init_succeeded', { durationMs: Math.round(performance.now() - bootStartedAt) });
1998
+ logger.info('[Init] SDK ready', {
1999
+ deviceId,
2000
+ primaryModelId: primaryModel.modelId,
2001
+ taskType: primaryModel.taskType
2002
+ });
2003
+ // Reached a stable point (model loaded, WebSocket connected) — this load was
2004
+ // not a crash loop, so clear the attempt counter.
2005
+ markInitSuccess();
2006
+ };
2007
+ const mapCacheInvalidCode = (errorMessage) => {
2008
+ if (errorMessage === 'no_adapter_factory')
2009
+ return 'no_adapter_factory';
2010
+ if (errorMessage === 'sample_failed')
2011
+ return 'sample_failed';
2012
+ return 'files_missing';
2013
+ };
2014
+ const mapRegisterErrorCode = (err) => {
2015
+ if (err instanceof RegisterError)
2016
+ return `http_${err.status}`;
2017
+ const message = err?.message ?? '';
2018
+ if (/timeout/i.test(message))
2019
+ return 'timeout';
2020
+ return 'network';
2021
+ };
2022
+ const mapModelLoadErrorCode = (message) => {
2023
+ if (!message)
2024
+ return 'init_error';
2025
+ if (/no_adapter_factory/.test(message))
2026
+ return 'no_adapter_factory';
2027
+ if (/oom|out of memory|RangeError/i.test(message))
2028
+ return 'oom';
2029
+ if (/wasm|abort/i.test(message))
2030
+ return 'wasm_abort';
2031
+ return 'init_error';
1280
2032
  };
1281
2033
  const normalizeAssignedModels = (slmConfig) => {
1282
2034
  if (!Array.isArray(slmConfig))
@@ -1450,15 +2202,21 @@ const ensureTransformersRuntime = () => {
1450
2202
  return Promise.resolve();
1451
2203
  }
1452
2204
  if (!transformersRuntimePromise) {
2205
+ const logger = getLogger();
1453
2206
  transformersRuntimePromise = (async () => {
1454
2207
  try {
1455
2208
  const runtimeUrl = TRANSFORMERS_CDN;
2209
+ logger.info('[Runtime] Importing Transformers runtime from CDN', { runtimeUrl });
2210
+ const importStart = performance.now();
1456
2211
  const transformersModule = await import(/* @vite-ignore */ runtimeUrl);
1457
2212
  const pipeline = transformersModule?.pipeline;
1458
2213
  const env = transformersModule?.env;
1459
2214
  if (typeof pipeline !== 'function' || !env) {
1460
2215
  throw new Error('Transformers runtime missing pipeline/env exports');
1461
2216
  }
2217
+ logger.info('[Runtime] Transformers runtime ready', {
2218
+ ms: Math.round(performance.now() - importStart)
2219
+ });
1462
2220
  env.allowLocalModels = true;
1463
2221
  env.allowRemoteModels = true;
1464
2222
  if (env?.backends?.onnx?.env) {
@@ -2921,6 +3679,12 @@ const registerZeroGpuOffscreenMessaging = (options = {}) => {
2921
3679
  }));
2922
3680
  return true;
2923
3681
  }
3682
+ if (message.type === ZEROGPU_OFFSCREEN_MESSAGES.disable) {
3683
+ // The offscreen document may be torn down after this — flush pending
3684
+ // events before the runtime reclaims it.
3685
+ getEventReporter().report('sdk.shutdown', { code: 'host_stop' });
3686
+ getEventReporter().flush({ beacon: true });
3687
+ }
2924
3688
  });
2925
3689
  return state;
2926
3690
  };