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