@zerogpu/browser-extension-sdk 0.1.6 → 0.2.0-dev.202607211328.gc9a2a62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +7 -0
  2. package/bin/zerogpu.mjs +7 -13
  3. package/dist/assets/zerogpu-assets.json +3 -2
  4. package/dist/extension/zerogpu-offscreen.js +1420 -178
  5. package/dist/extension/zerogpu-offscreen.js.map +1 -1
  6. package/dist/manifest.json +6 -5
  7. package/dist/types/config/types.d.ts +20 -0
  8. package/dist/types/public-api.d.ts +29 -1
  9. package/dist/types/runtime/guardrails.d.ts +36 -0
  10. package/dist/types/runtime/host-api.d.ts +22 -0
  11. package/dist/types/runtime/init-guard.d.ts +38 -15
  12. package/dist/types/runtime/reregister.d.ts +10 -0
  13. package/dist/types/runtime/resource-gate.d.ts +23 -0
  14. package/dist/types/runtime/shutdown.d.ts +22 -0
  15. package/dist/types/runtime/watchdog.d.ts +35 -0
  16. package/dist/types/telemetry/event-buffer.d.ts +5 -0
  17. package/dist/types/telemetry/event-reporter.d.ts +42 -0
  18. package/dist/types/telemetry/event-types.d.ts +5 -0
  19. package/dist/types/telemetry/types.d.ts +26 -0
  20. package/dist/types/transport/http.d.ts +13 -0
  21. package/dist/types/transport/websocket.d.ts +2 -1
  22. package/dist/v/{zerogpu-browser-sdk.8729e27b5aa1.umd.js → zerogpu-browser-sdk.de2e6d71813f.umd.js} +1416 -169
  23. package/dist/v/zerogpu-browser-sdk.de2e6d71813f.umd.js.map +1 -0
  24. package/dist/zerogpu-browser-sdk.cjs +1415 -168
  25. package/dist/zerogpu-browser-sdk.cjs.map +1 -1
  26. package/dist/zerogpu-browser-sdk.esm.js +1415 -168
  27. package/dist/zerogpu-browser-sdk.esm.js.map +1 -1
  28. package/dist/zerogpu-browser-sdk.umd.js +1415 -168
  29. package/dist/zerogpu-browser-sdk.umd.js.map +1 -1
  30. package/docs/auto-update-loader.md +6 -0
  31. package/docs/extension-developer-guide.md +7 -0
  32. package/package.json +7 -4
  33. package/dist/v/zerogpu-browser-sdk.8729e27b5aa1.umd.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const SDK_VERSION = typeof "0.1.6+9f0db3f" === 'string' && "0.1.6+9f0db3f".length > 0
4
- ? "0.1.6+9f0db3f"
3
+ const SDK_VERSION = typeof "0.2.0-dev.202607211328.gc9a2a62+c9a2a62" === 'string' && "0.2.0-dev.202607211328.gc9a2a62+c9a2a62".length > 0
4
+ ? "0.2.0-dev.202607211328.gc9a2a62+c9a2a62"
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
@@ -17,12 +17,14 @@ const DEFAULT_CONFIG = {
17
17
  sdkVersion: SDK_VERSION,
18
18
  orchestrator: {
19
19
  baseUrl: ORCHESTRATOR_BASE_URL,
20
- registerPath: '/register'
20
+ registerPath: '/register',
21
+ eventsPath: '/events'
21
22
  },
22
23
  telemetry: {
23
24
  enableConsoleLogs: false,
24
25
  locationData: false,
25
- cameraData: false
26
+ cameraData: false,
27
+ events: true
26
28
  }
27
29
  };
28
30
 
@@ -33,12 +35,14 @@ const resolveConfig = (overrides) => {
33
35
  sdkVersion: asNonEmptyString(merged.sdkVersion, base.sdkVersion),
34
36
  orchestrator: {
35
37
  baseUrl: asNonEmptyString(merged.orchestrator?.baseUrl, base.orchestrator.baseUrl),
36
- 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)
37
40
  },
38
41
  telemetry: {
39
42
  enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
40
43
  locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
41
- 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)
42
46
  }
43
47
  };
44
48
  };
@@ -89,20 +93,21 @@ class Logger {
89
93
  console.error('[ZeroGPU]', ...args);
90
94
  }
91
95
  }
92
- let singleton = null;
96
+ let singleton$1 = null;
93
97
  const initLogger = (config) => {
94
- singleton = new Logger(config);
95
- return singleton;
98
+ singleton$1 = new Logger(config);
99
+ return singleton$1;
96
100
  };
97
101
  const getLogger = () => {
98
- if (!singleton) {
99
- singleton = new Logger({
102
+ if (!singleton$1) {
103
+ singleton$1 = new Logger({
100
104
  enableConsoleLogs: false,
101
105
  locationData: false,
102
- cameraData: false
106
+ cameraData: false,
107
+ events: true
103
108
  });
104
109
  }
105
- return singleton;
110
+ return singleton$1;
106
111
  };
107
112
 
108
113
  const DEVICE_ID_KEY = 'zerogpu_device_id';
@@ -382,18 +387,29 @@ const parseRegisterResponseBody = async (response) => {
382
387
  return null;
383
388
  }
384
389
  };
385
- const isEdgeSdkTypeNotAllowedResponse = (payload) => {
390
+ /**
391
+ * Detects the server's "polite refusal" envelope: HTTP 200, `status: 'ok'`,
392
+ * and a reason/code — used for `edge_sdk_type_not_allowed` and for every
393
+ * admission-guard refusal (`model_too_large_for_memory`, `low_battery`,
394
+ * `guardrail_blocked`, …). Returns the reason code, or null.
395
+ */
396
+ const detectSoftRefusal = (payload) => {
386
397
  if (!payload || typeof payload !== 'object') {
387
- return false;
398
+ return null;
388
399
  }
389
400
  const body = payload;
390
401
  const status = typeof body.status === 'string' ? body.status.toLowerCase() : '';
391
402
  if (status !== 'ok') {
392
- return false;
403
+ return null;
393
404
  }
394
405
  const nestedError = body.error;
395
406
  const candidateCodes = [body.code, body.errorCode, body.reason, nestedError?.code];
396
- return candidateCodes.some((value) => typeof value === 'string' && value.toLowerCase() === 'edge_sdk_type_not_allowed');
407
+ for (const value of candidateCodes) {
408
+ if (typeof value === 'string' && value.trim().length > 0) {
409
+ return value.trim().toLowerCase();
410
+ }
411
+ }
412
+ return null;
397
413
  };
398
414
  const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
399
415
  const buildCurl = (url, body, headers) => {
@@ -422,24 +438,27 @@ const registerDevice = async (config, payload, auth) => {
422
438
  logger.info('Register request sent:', { url, status: response.status });
423
439
  getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
424
440
  const registerResponseBody = await parseRegisterResponseBody(response);
425
- const edgeSdkTypeNotAllowed = isEdgeSdkTypeNotAllowedResponse(registerResponseBody);
426
- if (!response.ok && !edgeSdkTypeNotAllowed) {
441
+ const refusalReason = detectSoftRefusal(registerResponseBody);
442
+ if (!response.ok && !refusalReason) {
427
443
  const text = typeof registerResponseBody === 'string'
428
444
  ? registerResponseBody
429
445
  : JSON.stringify(registerResponseBody ?? '');
430
446
  logger.error('Register request failed:', { status: response.status, text });
431
447
  throw new RegisterError(response.status, text);
432
448
  }
433
- if (registerResponseBody && typeof registerResponseBody === 'object' && !edgeSdkTypeNotAllowed) {
449
+ if (registerResponseBody && typeof registerResponseBody === 'object' && !refusalReason) {
434
450
  const registerResponse = registerResponseBody;
435
451
  logger.info('Register response parsed:', registerResponse);
436
452
  return registerResponse;
437
453
  }
438
- if (edgeSdkTypeNotAllowed) {
454
+ if (refusalReason) {
455
+ // A refusal is still a conversation, not an error: synthesize an accepted
456
+ // response with no wsUrl and carry the reason so the lifecycle can exit
457
+ // cleanly (and pick up any configSettings the server included).
439
458
  const responseObject = registerResponseBody && typeof registerResponseBody === 'object'
440
459
  ? registerResponseBody
441
460
  : {};
442
- const acceptedResponse = {
461
+ const refusedResponse = {
443
462
  deviceId: typeof responseObject.deviceId === 'string' && responseObject.deviceId
444
463
  ? responseObject.deviceId
445
464
  : payload.deviceId,
@@ -447,14 +466,18 @@ const registerDevice = async (config, payload, auth) => {
447
466
  wsUrl: typeof responseObject.wsUrl === 'string' ? responseObject.wsUrl : '',
448
467
  active: typeof responseObject.active === 'boolean' ? responseObject.active : false,
449
468
  ttlSeconds: typeof responseObject.ttlSeconds === 'number' ? responseObject.ttlSeconds : 0,
469
+ refusalReason,
470
+ configSettings: responseObject.configSettings && typeof responseObject.configSettings === 'object'
471
+ ? responseObject.configSettings
472
+ : undefined,
450
473
  slmConfig: typeof responseObject.slmConfig !== 'undefined'
451
474
  ? responseObject.slmConfig
452
475
  : typeof responseObject.modelInfo !== 'undefined'
453
476
  ? [responseObject.modelInfo]
454
477
  : undefined
455
478
  };
456
- logger.info('Handled edge_sdk_type_not_allowed register response');
457
- return acceptedResponse;
479
+ logger.info('Register politely refused by server', { reason: refusalReason });
480
+ return refusedResponse;
458
481
  }
459
482
  throw new RegisterError(response.status, 'Register response body is not valid JSON');
460
483
  };
@@ -466,6 +489,7 @@ class WebSocketClient {
466
489
  this.consoleWithVerbose = console;
467
490
  this.handleOpen = () => {
468
491
  this.logger.info('WebSocket connection opened');
492
+ this.options.onOpen?.();
469
493
  this.logger.debug('Sending hello message:', this.options.hello);
470
494
  this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
471
495
  this.send(this.options.hello);
@@ -534,8 +558,14 @@ class WebSocketClient {
534
558
  this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
535
559
  this.socket.send(JSON.stringify(payload));
536
560
  }
537
- close() {
538
- this.socket.close();
561
+ close(code, reason) {
562
+ if (typeof code === 'number') {
563
+ // Close reasons are capped at 123 bytes by the WS protocol.
564
+ this.socket.close(code, (reason ?? '').slice(0, 120));
565
+ }
566
+ else {
567
+ this.socket.close();
568
+ }
539
569
  }
540
570
  }
541
571
 
@@ -586,32 +616,977 @@ const setSessionKey = (sessionKey) => {
586
616
  const setWebSocket = (ws) => {
587
617
  state.ws = ws;
588
618
  };
589
- // Safe before full init (unlike getState) — used by the re-registration guard.
590
- const getWebSocket = () => state.ws;
591
- const setRegistrationSettings = (settings) => {
592
- state.registrationSettings = settings ?? null;
619
+ // Safe before full init (unlike getState) — used by the re-registration guard.
620
+ const getWebSocket = () => state.ws;
621
+ const setRegistrationSettings = (settings) => {
622
+ state.registrationSettings = settings ?? null;
623
+ };
624
+ const getRegistrationSettings = () => state.registrationSettings ?? null;
625
+ const setStatus = (status) => {
626
+ state.status = status;
627
+ };
628
+ const getState = () => {
629
+ if (!state.config || !state.deviceId || !state.deviceInfo) {
630
+ throw new Error('SDK state not initialized');
631
+ }
632
+ return state;
633
+ };
634
+
635
+ const factories = [];
636
+ const registerAdapter = (factory) => {
637
+ factories.push(factory);
638
+ };
639
+ const matches = (capability, framework, taskType) => capability.inferenceFramework.toLowerCase() === framework.toLowerCase() &&
640
+ capability.taskType.toLowerCase() === taskType.toLowerCase();
641
+ const getAdapterFactory = (framework, taskType) => {
642
+ if (!framework || !taskType)
643
+ return undefined;
644
+ return factories.find((factory) => factory.capabilities.some((capability) => matches(capability, framework, taskType)));
645
+ };
646
+
647
+ // Local mirror of the device lifecycle event vocabulary from
648
+ // @zerogpu/global-types. The SDK keeps its own copy so it stays zero-runtime-
649
+ // dependency; an alignment test (event-types.alignment.test.ts) pins these
650
+ // values to the published package so the two can never drift.
651
+ const DEVICE_EVENT_SEVERITY = {
652
+ 'sdk.init_started': 'info',
653
+ 'sdk.init_succeeded': 'info',
654
+ 'sdk.init_failed': 'error',
655
+ 'sdk.shutdown': 'info',
656
+ 'sdk.crash_detected': 'fatal',
657
+ 'host.foreground': 'info',
658
+ 'host.background': 'info',
659
+ 'register.started': 'info',
660
+ 'register.succeeded': 'info',
661
+ 'register.failed': 'error',
662
+ 'register.rejected': 'warning',
663
+ 'model.assigned': 'info',
664
+ 'model.cache_hit': 'info',
665
+ 'model.cache_invalid': 'warning',
666
+ 'model.cache_purged': 'info',
667
+ 'model.download_started': 'info',
668
+ 'model.download_succeeded': 'info',
669
+ 'model.download_failed': 'error',
670
+ 'model.load_started': 'info',
671
+ 'model.load_succeeded': 'info',
672
+ 'model.load_failed': 'error',
673
+ 'model.sample_succeeded': 'info',
674
+ 'model.sample_failed': 'error',
675
+ 'model.evicted': 'warning',
676
+ 'ws.connect_started': 'info',
677
+ 'ws.connected': 'info',
678
+ 'ws.hello_ack': 'info',
679
+ 'ws.closed': 'warning',
680
+ 'ws.error': 'error',
681
+ 'ws.reconnect_scheduled': 'info',
682
+ 'ws.init_failure_reported': 'error',
683
+ 'task.failed': 'error',
684
+ 'task.rejected': 'warning',
685
+ 'task.slow': 'warning',
686
+ 'guardrail.preflight_blocked': 'warning',
687
+ 'guardrail.pressure_warning': 'warning',
688
+ 'guardrail.degraded': 'warning',
689
+ 'guardrail.shutdown': 'fatal',
690
+ 'guardrail.model_blocklisted': 'warning',
691
+ 'ws.session_opened': 'info',
692
+ 'ws.session_authenticated': 'info',
693
+ 'ws.session_rejected': 'warning',
694
+ 'ws.session_superseded': 'info',
695
+ 'ws.session_closed': 'info',
696
+ 'dispatch.sent': 'info',
697
+ 'dispatch.completed': 'info',
698
+ 'dispatch.timeout': 'error',
699
+ 'dispatch.failed_offline': 'warning',
700
+ 'registry.status_changed': 'info'
701
+ };
702
+ const HELLO_ACK_OK_CODES = new Set(['ok', 'idle', 'ready']);
703
+ const getDeviceEventSeverity = (type, code) => {
704
+ if (type === 'ws.hello_ack' && code && !HELLO_ACK_OK_CODES.has(code)) {
705
+ return 'error';
706
+ }
707
+ return DEVICE_EVENT_SEVERITY[type] ?? 'info';
708
+ };
709
+
710
+ // Persisted ring buffer for events that couldn't be delivered (offline, non-2xx,
711
+ // or a terminal flush that never returned). Oldest events drop first. Drained on
712
+ // the next successful init so a session that died before connecting still reports
713
+ // its failures. All storage access is swallowed — a full/blocked localStorage
714
+ // must never break the SDK.
715
+ const EVENT_BUFFER_KEY = 'zerogpu_event_buffer';
716
+ const MAX_BUFFERED_EVENTS = 100;
717
+ const safeGet = (key) => {
718
+ try {
719
+ return window.localStorage.getItem(key);
720
+ }
721
+ catch {
722
+ return null;
723
+ }
724
+ };
725
+ const safeSet = (key, value) => {
726
+ try {
727
+ window.localStorage.setItem(key, value);
728
+ }
729
+ catch {
730
+ // Quota exceeded / private mode / partitioned storage — degrade silently.
731
+ }
732
+ };
733
+ const loadBufferedEvents = () => {
734
+ const raw = safeGet(EVENT_BUFFER_KEY);
735
+ if (!raw)
736
+ return [];
737
+ try {
738
+ const parsed = JSON.parse(raw);
739
+ return Array.isArray(parsed) ? parsed : [];
740
+ }
741
+ catch {
742
+ return [];
743
+ }
744
+ };
745
+ const saveBufferedEvents = (events) => {
746
+ const trimmed = events.length > MAX_BUFFERED_EVENTS ? events.slice(-MAX_BUFFERED_EVENTS) : events;
747
+ safeSet(EVENT_BUFFER_KEY, JSON.stringify(trimmed));
748
+ };
749
+ const appendBufferedEvents = (events) => {
750
+ if (events.length === 0)
751
+ return;
752
+ saveBufferedEvents([...loadBufferedEvents(), ...events]);
753
+ };
754
+ const clearBufferedEvents = () => {
755
+ try {
756
+ window.localStorage.removeItem(EVENT_BUFFER_KEY);
757
+ }
758
+ catch {
759
+ // ignore storage failures
760
+ }
761
+ };
762
+
763
+ // One sessionId per SDK boot, created at module load. The re-registration loop
764
+ // re-runs startLifecycle per cycle, so this must NOT be minted inside it — the
765
+ // seq counter keeps climbing across reconnects within a single boot.
766
+ const SESSION_ID = createUuid();
767
+ const FLUSH_INTERVAL_MS = 10000;
768
+ const FLUSH_BATCH_SIZE = 20;
769
+ const MAX_EVENTS_PER_REQUEST = 20;
770
+ const SESSION_EVENT_CAP = 200;
771
+ const DEDUP_WINDOW_MS = 30000;
772
+ const MESSAGE_MAX_CHARS = 256;
773
+ class EventReporter {
774
+ constructor(options) {
775
+ this.options = options;
776
+ this.queue = [];
777
+ this.seq = 0;
778
+ this.emittedCount = 0;
779
+ this.capped = false;
780
+ this.timer = null;
781
+ this.lastByTypeCode = new Map();
782
+ this.listenersBound = false;
783
+ this.boundPageHide = null;
784
+ this.boundVisibilityChange = null;
785
+ if (!options.enabled)
786
+ return;
787
+ // Drain any events from a previous (possibly crashed) session first, so
788
+ // register.failed / crash markers reach the registry on the next boot.
789
+ this.queue.push(...loadBufferedEvents());
790
+ clearBufferedEvents();
791
+ this.bindTerminalFlush();
792
+ this.timer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
793
+ }
794
+ setSessionKey(key) {
795
+ this.sessionKey = key;
796
+ }
797
+ // True when this instance already owns the boot's session state, so
798
+ // initEventReporter can keep it alive across reconnects instead of rebuilding.
799
+ matches(deviceId, enabled) {
800
+ return this.options.enabled === enabled && this.options.deviceId === deviceId;
801
+ }
802
+ // Stops the flush timer and unbinds the terminal-flush listeners. Called when a
803
+ // new reporter replaces this one so neither intervals nor window listeners
804
+ // accumulate across startLifecycle re-registrations.
805
+ dispose() {
806
+ if (this.timer !== null) {
807
+ clearInterval(this.timer);
808
+ this.timer = null;
809
+ }
810
+ if (typeof window !== 'undefined') {
811
+ if (this.boundPageHide)
812
+ window.removeEventListener('pagehide', this.boundPageHide);
813
+ if (this.boundVisibilityChange)
814
+ window.removeEventListener('visibilitychange', this.boundVisibilityChange);
815
+ }
816
+ this.boundPageHide = null;
817
+ this.boundVisibilityChange = null;
818
+ this.listenersBound = false;
819
+ }
820
+ report(type, fields = {}) {
821
+ try {
822
+ if (!this.options.enabled)
823
+ return;
824
+ if (this.emittedCount >= SESSION_EVENT_CAP) {
825
+ if (!this.capped) {
826
+ this.capped = true;
827
+ this.enqueue({ type: 'sdk.shutdown', fields: { code: 'unknown', data: { capped: true } } });
828
+ this.flush();
829
+ }
830
+ return;
831
+ }
832
+ const now = Date.now();
833
+ const dedupKey = `${type}:${fields.code ?? ''}`;
834
+ const prior = this.lastByTypeCode.get(dedupKey);
835
+ if (prior && now - prior.at < DEDUP_WINDOW_MS) {
836
+ const repeat = (Number(prior.event.data?.repeat) || 1) + 1;
837
+ prior.event.data = { ...(prior.event.data ?? {}), repeat };
838
+ prior.at = now;
839
+ return;
840
+ }
841
+ const event = this.enqueue({ type, fields });
842
+ this.lastByTypeCode.set(dedupKey, { event, at: now });
843
+ const severity = event.severity;
844
+ if (this.queue.length >= FLUSH_BATCH_SIZE || severity === 'error' || severity === 'fatal') {
845
+ // Detach from the hot path; flush() is itself fully guarded.
846
+ void Promise.resolve().then(() => this.flush());
847
+ }
848
+ }
849
+ catch {
850
+ // Telemetry must never throw into the SDK.
851
+ }
852
+ }
853
+ flush(opts = {}) {
854
+ try {
855
+ if (!this.options.enabled || this.queue.length === 0)
856
+ return;
857
+ const batch = this.queue.slice(0, MAX_EVENTS_PER_REQUEST);
858
+ this.queue = this.queue.slice(MAX_EVENTS_PER_REQUEST);
859
+ // Drop dedup tracking for events leaving the queue. FLUSH_INTERVAL_MS (10s)
860
+ // is shorter than DEDUP_WINDOW_MS (30s), so without this a duplicate arriving
861
+ // after the original was flushed would mutate an already-sent event and be
862
+ // lost. Clearing the entry forces the next duplicate to enqueue afresh.
863
+ const inFlight = new Set(batch);
864
+ for (const [key, entry] of this.lastByTypeCode) {
865
+ if (inFlight.has(entry.event))
866
+ this.lastByTypeCode.delete(key);
867
+ }
868
+ const envelope = {
869
+ v: 1,
870
+ deviceId: this.options.deviceId,
871
+ sessionId: SESSION_ID,
872
+ sdkVersion: this.options.sdkVersion,
873
+ edgeSdkType: this.options.edgeSdkType,
874
+ platform: this.options.platform,
875
+ ...(this.sessionKey ? { sessionKey: this.sessionKey } : {}),
876
+ events: batch
877
+ };
878
+ if (opts.beacon) {
879
+ this.sendBeacon(envelope, batch);
880
+ return;
881
+ }
882
+ this.sendFetch(envelope, batch);
883
+ }
884
+ catch {
885
+ // ignore
886
+ }
887
+ }
888
+ enqueue(params) {
889
+ const { type, fields } = params;
890
+ const event = {
891
+ eventId: createUuid(),
892
+ type,
893
+ ts: new Date().toISOString(),
894
+ seq: this.seq++,
895
+ severity: getDeviceEventSeverity(type, fields.code),
896
+ code: fields.code,
897
+ message: fields.message ? fields.message.slice(0, MESSAGE_MAX_CHARS) : undefined,
898
+ modelId: fields.modelId,
899
+ modelVersion: fields.modelVersion,
900
+ taskType: fields.taskType,
901
+ durationMs: fields.durationMs,
902
+ bytes: fields.bytes,
903
+ data: fields.data
904
+ };
905
+ this.queue.push(event);
906
+ this.emittedCount += 1;
907
+ return event;
908
+ }
909
+ // sendBeacon cannot set headers, so the operator key rides inside the
910
+ // envelope (the /events handler accepts body.edgeOperatorKey as a fallback).
911
+ sendBeacon(envelope, batch) {
912
+ const body = JSON.stringify({ ...envelope, edgeOperatorKey: this.options.operatorKey });
913
+ let sent = false;
914
+ try {
915
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
916
+ sent = navigator.sendBeacon(this.options.endpointUrl, new Blob([body], { type: 'application/json' }));
917
+ }
918
+ }
919
+ catch {
920
+ sent = false;
921
+ }
922
+ if (!sent) {
923
+ // Fallback: keepalive fetch survives the unload of the page too.
924
+ try {
925
+ void fetch(this.options.endpointUrl, {
926
+ method: 'POST',
927
+ keepalive: true,
928
+ headers: { 'content-type': 'application/json', 'x-edge-operator-key': this.options.operatorKey },
929
+ body
930
+ }).catch(() => appendBufferedEvents(batch));
931
+ }
932
+ catch {
933
+ appendBufferedEvents(batch);
934
+ }
935
+ }
936
+ }
937
+ sendFetch(envelope, batch) {
938
+ try {
939
+ void fetch(this.options.endpointUrl, {
940
+ method: 'POST',
941
+ keepalive: true,
942
+ headers: { 'content-type': 'application/json', 'x-edge-operator-key': this.options.operatorKey },
943
+ body: JSON.stringify(envelope)
944
+ })
945
+ .then((res) => {
946
+ // Any non-2xx: drop-and-move-on but persist for next boot's drain.
947
+ if (!res.ok)
948
+ appendBufferedEvents(batch);
949
+ })
950
+ .catch(() => appendBufferedEvents(batch));
951
+ }
952
+ catch {
953
+ appendBufferedEvents(batch);
954
+ }
955
+ }
956
+ bindTerminalFlush() {
957
+ if (this.listenersBound || typeof window === 'undefined')
958
+ return;
959
+ this.listenersBound = true;
960
+ try {
961
+ this.boundPageHide = () => this.flush({ beacon: true });
962
+ this.boundVisibilityChange = () => {
963
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
964
+ this.flush({ beacon: true });
965
+ }
966
+ };
967
+ window.addEventListener('pagehide', this.boundPageHide);
968
+ window.addEventListener('visibilitychange', this.boundVisibilityChange);
969
+ }
970
+ catch {
971
+ // Listener binding failures are non-fatal.
972
+ }
973
+ }
974
+ }
975
+ let singleton = null;
976
+ // A disabled/uninitialized reporter is a real object whose methods are no-ops,
977
+ // so callers never need to null-check getEventReporter().
978
+ const NOOP = new EventReporter({
979
+ enabled: false,
980
+ endpointUrl: '',
981
+ operatorKey: '',
982
+ deviceId: '',
983
+ sdkVersion: '',
984
+ platform: ''
985
+ });
986
+ const initEventReporter = (options) => {
987
+ // startLifecycle() calls this on every re-registration, but the session cap,
988
+ // dedup window, and seq counter are per-boot. Keep the live reporter across
989
+ // reconnects so those don't reset each cycle; only rebuild it on a genuine
990
+ // identity/enablement change (or a true cold start, where singleton is null).
991
+ if (singleton && singleton.matches(options.deviceId, options.enabled))
992
+ return;
993
+ // Flush anything the previous instance still held, then stop its timer and
994
+ // unbind its listeners before replacing it.
995
+ singleton?.flush();
996
+ singleton?.dispose();
997
+ singleton = new EventReporter(options);
998
+ };
999
+ const getEventReporter = () => singleton ?? NOOP;
1000
+
1001
+ /**
1002
+ * Host-facing lifecycle status and events. The SDK is a guest in someone
1003
+ * else's app: this module is how the host observes guardrail state (degraded /
1004
+ * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1005
+ * consumers get the same signals as `zerogpu:*` window events, matching the
1006
+ * existing `zerogpu:cameraPreview` pattern.
1007
+ */
1008
+ let lifecycleStatus = 'starting';
1009
+ const listeners = {
1010
+ degraded: new Set(),
1011
+ recovered: new Set(),
1012
+ shutdown: new Set()
1013
+ };
1014
+ const getLifecycleStatus = () => lifecycleStatus;
1015
+ const setLifecycleStatus = (status) => {
1016
+ // Shutdown is terminal (state machine B.3): recovery exists only from
1017
+ // warn/degrade, never from shutdown.
1018
+ if (lifecycleStatus === 'shutdown')
1019
+ return;
1020
+ lifecycleStatus = status;
1021
+ };
1022
+ const isShutdown = () => lifecycleStatus === 'shutdown';
1023
+ /** Degraded and shutting-down SDKs finish in-flight work but accept nothing new. */
1024
+ const isTaskGateActive = () => lifecycleStatus === 'degraded' || lifecycleStatus === 'shutdown';
1025
+ const onHostEvent = (name, listener) => {
1026
+ listeners[name]?.add(listener);
1027
+ return () => listeners[name]?.delete(listener);
1028
+ };
1029
+ const emitHostEvent = (name, detail = {}) => {
1030
+ for (const listener of listeners[name] ?? []) {
1031
+ try {
1032
+ listener(detail);
1033
+ }
1034
+ catch {
1035
+ // A host listener bug must never propagate into the SDK.
1036
+ }
1037
+ }
1038
+ try {
1039
+ if (typeof window !== 'undefined') {
1040
+ window.dispatchEvent(new CustomEvent(`zerogpu:${name}`, { detail }));
1041
+ }
1042
+ }
1043
+ catch {
1044
+ // ignore
1045
+ }
1046
+ };
1047
+
1048
+ const DEFAULT_FRAMEWORK_MULTIPLIERS = {
1049
+ onnx: 2.0,
1050
+ transformersjs: 2.5,
1051
+ transformers: 2.5,
1052
+ gguf: 1.4
1053
+ };
1054
+ const DEFAULT_FRAMEWORK_MULTIPLIER = 2.0;
1055
+ const DEFAULT_MEMORY_BUDGET_FRACTION = 0.3;
1056
+ /** Battery floor below which a discharging device defers model downloads. */
1057
+ const DEFAULT_MIN_BATTERY_LEVEL = 0.2;
1058
+ /** Downloads need headroom beyond the file size (IndexedDB overhead, temp copies). */
1059
+ const DEFAULT_STORAGE_HEADROOM = 1.2;
1060
+ /** Devices that report no memory are treated as modest 2 GB devices (same as the server). */
1061
+ const UNKNOWN_DEVICE_MEMORY_GB = 2;
1062
+ const DEFAULT_WATCHDOG = {
1063
+ warnPct: 0.7,
1064
+ degradePct: 0.85,
1065
+ shutdownPct: 0.95,
1066
+ sampleMs: 10000,
1067
+ recoverPct: 0.6,
1068
+ recoverHoldMs: 60000
1069
+ };
1070
+ let policy = {};
1071
+ let resolved = resolve(null);
1072
+ function positive(value) {
1073
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
1074
+ }
1075
+ function resolve(settings) {
1076
+ const watchdog = settings?.watchdog ?? {};
1077
+ // Non-positive served multipliers are treated as absent (same semantics as
1078
+ // the registry) so a bad settings edit cannot zero out the memory gate.
1079
+ const servedMultipliers = Object.fromEntries(Object.entries(settings?.frameworkMultipliers ?? {}).filter(([, v]) => positive(v) !== undefined));
1080
+ return {
1081
+ memoryBudgetFraction: positive(policy.memoryBudgetFraction) ??
1082
+ positive(settings?.memoryBudgetFraction) ??
1083
+ DEFAULT_MEMORY_BUDGET_FRACTION,
1084
+ frameworkMultipliers: {
1085
+ ...DEFAULT_FRAMEWORK_MULTIPLIERS,
1086
+ ...servedMultipliers
1087
+ },
1088
+ minBatteryLevel: positive(settings?.minBatteryLevel) ?? DEFAULT_MIN_BATTERY_LEVEL,
1089
+ storageHeadroom: positive(settings?.storageHeadroom) ?? DEFAULT_STORAGE_HEADROOM,
1090
+ unknownMemoryGb: positive(settings?.unknownMemoryGb) ?? UNKNOWN_DEVICE_MEMORY_GB,
1091
+ watchdog: {
1092
+ warnPct: positive(watchdog.warnPct) ?? DEFAULT_WATCHDOG.warnPct,
1093
+ degradePct: positive(watchdog.degradePct) ?? DEFAULT_WATCHDOG.degradePct,
1094
+ shutdownPct: positive(watchdog.shutdownPct) ?? DEFAULT_WATCHDOG.shutdownPct,
1095
+ sampleMs: positive(watchdog.sampleMs) ?? DEFAULT_WATCHDOG.sampleMs,
1096
+ recoverPct: positive(watchdog.recoverPct) ?? DEFAULT_WATCHDOG.recoverPct,
1097
+ recoverHoldMs: positive(watchdog.recoverHoldMs) ?? DEFAULT_WATCHDOG.recoverHoldMs
1098
+ }
1099
+ };
1100
+ }
1101
+ const setResourcePolicy = (next) => {
1102
+ policy = next ?? {};
1103
+ resolved = resolve(null);
1104
+ };
1105
+ const getResourcePolicy = () => policy;
1106
+ /** Called after every register with the server-tuned block (or null). */
1107
+ const applyRegistrationGuardrails = (settings) => {
1108
+ resolved = resolve(settings?.guardrails ?? null);
1109
+ };
1110
+ const getGuardrails = () => resolved;
1111
+ const multiplierFor = (framework) => {
1112
+ const key = framework?.trim().toLowerCase() ?? '';
1113
+ return resolved.frameworkMultipliers[key] ?? DEFAULT_FRAMEWORK_MULTIPLIER;
1114
+ };
1115
+ /**
1116
+ * The catalog's size column is megabytes but travels as `sizeBytes` unchanged
1117
+ * (deberta-v3-small -> 184). Values below 1e6 cannot be real byte counts for
1118
+ * an on-device model — interpret them as MB, identically to the registry.
1119
+ */
1120
+ const normalizeModelSizeBytes = (raw) => {
1121
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0)
1122
+ return 0;
1123
+ return raw < 1000000 ? raw * 1024 * 1024 : raw;
1124
+ };
1125
+
1126
+ /**
1127
+ * Crash-loop guard for SDK initialization, extended into the Layer 4 crash
1128
+ * marker + per-model breaker.
1129
+ *
1130
+ * On a brand-new device the lifecycle synchronously downloads and instantiates
1131
+ * a full model (and runs a sample inference) before connecting the WebSocket.
1132
+ * In a memory-constrained host such as a Telegram mini-app WebView this burst
1133
+ * can crash/OOM the view; the host reloads, the SDK repeats the same heavy
1134
+ * path, and the app "refreshes continuously".
1135
+ *
1136
+ * Two mechanisms share one persisted state (`zerogpu_init_state`):
1137
+ *
1138
+ * - the original attempt counter: several uncompleted attempts in a short
1139
+ * window trip a cool-down that skips heavy init entirely;
1140
+ * - the crash marker: a `phase` written before each dangerous step
1141
+ * (load/sample) and cleared on graceful shutdown. A phase surviving to the
1142
+ * next boot means the process died mid-step — that boot reports
1143
+ * `sdk.crash_detected`, and two deaths during one model's risky phases in
1144
+ * 24 h blocklist that model for 24 h so a single oversized model can't take
1145
+ * the host down repeatedly.
1146
+ */
1147
+ const INIT_STATE_KEY = 'zerogpu_init_state';
1148
+ /** Attempts that never completed are only counted within this rolling window. */
1149
+ const ATTEMPT_WINDOW_MS = 60000;
1150
+ /** Number of uncompleted attempts in the window that trips the cool-down. */
1151
+ const MAX_ATTEMPTS_IN_WINDOW = 3;
1152
+ /** How long to skip heavy init once a crash loop is detected. */
1153
+ const COOLDOWN_MS = 5 * 60000;
1154
+ /** Phases where a process death points at the model itself. */
1155
+ const RISKY_PHASES = new Set(['downloading', 'loading', 'sampling']);
1156
+ const CRASH_WINDOW_MS = 24 * 60 * 60 * 1000;
1157
+ const BLOCKLIST_MS = 24 * 60 * 60 * 1000;
1158
+ const CRASHES_TO_BLOCKLIST = 2;
1159
+ const readState = () => {
1160
+ try {
1161
+ const raw = window.localStorage.getItem(INIT_STATE_KEY);
1162
+ if (!raw)
1163
+ return null;
1164
+ const parsed = JSON.parse(raw);
1165
+ if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
1166
+ return null;
1167
+ }
1168
+ return parsed;
1169
+ }
1170
+ catch {
1171
+ return null;
1172
+ }
1173
+ };
1174
+ const writeState = (state) => {
1175
+ try {
1176
+ window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
1177
+ }
1178
+ catch {
1179
+ // Storage may be unavailable/partitioned; degrade silently.
1180
+ }
1181
+ };
1182
+ const modelKey = (modelId, modelVersion) => `${modelId}@${modelVersion ?? '1'}`;
1183
+ /** The breaker/marker fields that must survive attempt resets and successes. */
1184
+ const persistentFields = (state) => ({
1185
+ modelCrashes: state?.modelCrashes,
1186
+ blocklist: state?.blocklist,
1187
+ lastShutdown: state?.lastShutdown
1188
+ });
1189
+ const pruneBlocklist = (blocklist, now) => {
1190
+ if (!blocklist)
1191
+ return undefined;
1192
+ const live = Object.fromEntries(Object.entries(blocklist).filter(([, entry]) => entry.until > now));
1193
+ return Object.keys(live).length > 0 ? live : undefined;
1194
+ };
1195
+ /**
1196
+ * Extracts crash info from a surviving phase and applies the breaker rule.
1197
+ * Returns the mutated persistent fields plus the report for the caller.
1198
+ */
1199
+ const consumeCrashMarker = (state, now) => {
1200
+ let modelCrashes = state?.modelCrashes;
1201
+ let blocklist = pruneBlocklist(state?.blocklist, now);
1202
+ const phase = state?.phase;
1203
+ if (!phase)
1204
+ return { modelCrashes, blocklist };
1205
+ const risky = RISKY_PHASES.has(phase);
1206
+ let blocklistedModel;
1207
+ if (risky && state?.modelId) {
1208
+ const key = modelKey(state.modelId, state.modelVersion);
1209
+ const prior = modelCrashes?.[key];
1210
+ const inWindow = prior && now - prior.firstAt < CRASH_WINDOW_MS;
1211
+ const count = inWindow ? prior.count + 1 : 1;
1212
+ modelCrashes = { ...(modelCrashes ?? {}), [key]: { count, firstAt: inWindow ? prior.firstAt : now } };
1213
+ if (count >= CRASHES_TO_BLOCKLIST) {
1214
+ blocklist = { ...(blocklist ?? {}), [key]: { until: now + BLOCKLIST_MS } };
1215
+ blocklistedModel = key;
1216
+ }
1217
+ }
1218
+ return {
1219
+ crash: {
1220
+ code: risky ? 'oom_suspected' : 'unknown',
1221
+ phase,
1222
+ modelId: state?.modelId,
1223
+ modelVersion: state?.modelVersion,
1224
+ blocklistedModel
1225
+ },
1226
+ modelCrashes,
1227
+ blocklist
1228
+ };
1229
+ };
1230
+ /**
1231
+ * Records the start of an init attempt and decides whether heavy init may
1232
+ * proceed. Must be called once, before any heavy work, on every lifecycle start.
1233
+ */
1234
+ const beginInitAttempt = (now = Date.now()) => {
1235
+ const state = readState();
1236
+ // A surviving phase means the last process died mid-step; consume it first
1237
+ // so the crash is attributed exactly once.
1238
+ const { crash, modelCrashes, blocklist } = consumeCrashMarker(state, now);
1239
+ const persistent = {
1240
+ modelCrashes,
1241
+ blocklist,
1242
+ lastShutdown: state?.lastShutdown
1243
+ };
1244
+ // Still inside an active cool-down from a previously detected crash loop.
1245
+ if (state?.cooldownUntil && state.cooldownUntil > now) {
1246
+ writeState({ ...state, phase: undefined, modelId: undefined, modelVersion: undefined, ...persistent });
1247
+ return {
1248
+ allowed: false,
1249
+ cooldownRemainingMs: state.cooldownUntil - now,
1250
+ attempts: state.attempts,
1251
+ crash
1252
+ };
1253
+ }
1254
+ // No prior state, or the previous window/cool-down has elapsed → start fresh.
1255
+ if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
1256
+ writeState({ attempts: 1, windowStart: now, ...persistent });
1257
+ return { allowed: true, attempts: 1, crash };
1258
+ }
1259
+ const attempts = state.attempts + 1;
1260
+ // Too many uncompleted attempts in the window → assume a crash loop and back
1261
+ // off so the host app stops reloading.
1262
+ if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
1263
+ writeState({
1264
+ attempts,
1265
+ windowStart: state.windowStart,
1266
+ cooldownUntil: now + COOLDOWN_MS,
1267
+ ...persistent
1268
+ });
1269
+ return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts, crash };
1270
+ }
1271
+ writeState({ attempts, windowStart: state.windowStart, ...persistent });
1272
+ return { allowed: true, attempts, crash };
1273
+ };
1274
+ /**
1275
+ * Clears crash-loop tracking. Call once init reaches a stable point (e.g. the
1276
+ * WebSocket is connected), so successful loads never accumulate toward a trip.
1277
+ * Breaker history and the current phase survive — only the attempt counter
1278
+ * resets.
1279
+ */
1280
+ const markInitSuccess = () => {
1281
+ const state = readState();
1282
+ writeState({
1283
+ attempts: 0,
1284
+ windowStart: Date.now(),
1285
+ phase: state?.phase,
1286
+ modelId: state?.modelId,
1287
+ modelVersion: state?.modelVersion,
1288
+ ...persistentFields(state)
1289
+ });
1290
+ };
1291
+ /** Written before every dangerous step so an unclean death is attributable. */
1292
+ const setInitPhase = (phase, modelId, modelVersion) => {
1293
+ const state = readState();
1294
+ writeState({
1295
+ attempts: state?.attempts ?? 0,
1296
+ windowStart: state?.windowStart ?? Date.now(),
1297
+ cooldownUntil: state?.cooldownUntil,
1298
+ phase,
1299
+ modelId,
1300
+ modelVersion,
1301
+ ...persistentFields(state)
1302
+ });
1303
+ };
1304
+ /** The graceful shutdown sequence ran — the next boot must not count a crash. */
1305
+ const markCleanShutdown = (code) => {
1306
+ const state = readState();
1307
+ writeState({
1308
+ attempts: state?.attempts ?? 0,
1309
+ windowStart: state?.windowStart ?? Date.now(),
1310
+ cooldownUntil: state?.cooldownUntil,
1311
+ modelCrashes: state?.modelCrashes,
1312
+ blocklist: state?.blocklist,
1313
+ lastShutdown: { code, ts: Date.now() }
1314
+ });
1315
+ };
1316
+ /** Blocklisted models are refused before any I/O (breaker, Layer 4). */
1317
+ const isModelBlocklisted = (modelId, modelVersion) => {
1318
+ const state = readState();
1319
+ const entry = state?.blocklist?.[modelKey(modelId, modelVersion)];
1320
+ return Boolean(entry && entry.until > Date.now());
1321
+ };
1322
+
1323
+ /**
1324
+ * The single pending re-registration timer, isolated so both the lifecycle
1325
+ * (which schedules it) and the shutdown sequence (which must kill it — §4.7:
1326
+ * a guardrail shutdown closes the socket, and without this the re-register
1327
+ * loop would resurrect the SDK into the same memory conditions) can reach it
1328
+ * without importing each other.
1329
+ */
1330
+ let reregisterTimerId = null;
1331
+ const hasReregisterTimer = () => reregisterTimerId !== null;
1332
+ const setReregisterTimer = (callback, delayMs) => {
1333
+ clearReregisterTimer();
1334
+ reregisterTimerId = setTimeout(() => {
1335
+ reregisterTimerId = null;
1336
+ callback();
1337
+ }, delayMs);
1338
+ };
1339
+ const clearReregisterTimer = () => {
1340
+ if (reregisterTimerId !== null) {
1341
+ clearTimeout(reregisterTimerId);
1342
+ reregisterTimerId = null;
1343
+ }
1344
+ };
1345
+
1346
+ /** Guardrail shutdown close code; the registry records it as `close_4002`. */
1347
+ const CLOSE_GUARDRAIL = 4002;
1348
+ const CLOSE_NORMAL = 1000;
1349
+ /**
1350
+ * Client→server status update on the live session. The registry's
1351
+ * DeviceSession accepts a hello_ack-shaped message from an authenticated
1352
+ * socket and flips the device `idle`/`error` — the degrade/recover wire
1353
+ * contract, no new message type needed.
1354
+ */
1355
+ const sendStatusUpdate = (status) => {
1356
+ try {
1357
+ const state = getState();
1358
+ const ws = state.ws;
1359
+ if (!ws?.isActive() || !state.sessionKey)
1360
+ return;
1361
+ ws.send({
1362
+ type: 'hello_ack',
1363
+ deviceId: state.deviceId,
1364
+ sdkVersion: state.config.sdkVersion,
1365
+ sessionKey: state.sessionKey,
1366
+ status,
1367
+ timestamp: Date.now()
1368
+ });
1369
+ }
1370
+ catch {
1371
+ // Best effort only.
1372
+ }
1373
+ };
1374
+ /**
1375
+ * The ordered shutdown sequence (GRACEFUL_SHUTDOWN_IMPLEMENTATION.md §5):
1376
+ * mark terminal + kill the re-register loop → gate input → tell the server →
1377
+ * report + beacon-flush → free memory largest-first → mark the exit clean →
1378
+ * notify the host. Every step individually guarded; target ≤ 1 s. Terminal:
1379
+ * `startLifecycle` refuses to run again until the page restarts the SDK.
1380
+ */
1381
+ const runShutdownSequence = async ({ reason, guardrail = false }) => {
1382
+ if (getLifecycleStatus() === 'shutdown')
1383
+ return;
1384
+ const logger = getLogger();
1385
+ logger.warn('[Shutdown] Running shutdown sequence', { reason, guardrail });
1386
+ // 0. Terminal state — gates the router, blocks startLifecycle, and stops the
1387
+ // re-register loop from resurrecting us into the same conditions (§4.7).
1388
+ setLifecycleStatus('shutdown');
1389
+ clearReregisterTimer();
1390
+ // 1–2. Tell the server (best effort), then close with the right code.
1391
+ try {
1392
+ if (guardrail)
1393
+ sendStatusUpdate('error');
1394
+ }
1395
+ catch {
1396
+ /* best effort */
1397
+ }
1398
+ try {
1399
+ getWebSocket()?.close(guardrail ? CLOSE_GUARDRAIL : CLOSE_NORMAL, reason);
1400
+ }
1401
+ catch {
1402
+ /* best effort */
1403
+ }
1404
+ try {
1405
+ setWebSocket(undefined);
1406
+ setStatus('error');
1407
+ }
1408
+ catch {
1409
+ /* state may not be initialized */
1410
+ }
1411
+ // 3. Report + flush before anything else can kill the page. Failure is fine:
1412
+ // the offline buffer drains next boot.
1413
+ const reporter = getEventReporter();
1414
+ reporter.report(guardrail ? 'guardrail.shutdown' : 'sdk.shutdown', { code: reason });
1415
+ try {
1416
+ reporter.flush({ beacon: true });
1417
+ }
1418
+ catch {
1419
+ /* offline buffer covers it */
1420
+ }
1421
+ // 4. Free memory largest-first; files stay on disk (re-download is the
1422
+ // expensive part, and the trigger here is memory, not storage).
1423
+ try {
1424
+ const { adaptersByModelId, modelInfosByModelId } = getState();
1425
+ const entries = Object.entries(adaptersByModelId ?? {}).sort(([a], [b]) => normalizeModelSizeBytes(modelInfosByModelId?.[b]?.sizeBytes) -
1426
+ normalizeModelSizeBytes(modelInfosByModelId?.[a]?.sizeBytes));
1427
+ for (const [, adapter] of entries) {
1428
+ try {
1429
+ await adapter.dispose?.();
1430
+ }
1431
+ catch {
1432
+ /* a failing dispose must not stop the sequence */
1433
+ }
1434
+ }
1435
+ setAdaptersByModelId({});
1436
+ }
1437
+ catch {
1438
+ /* state may not be initialized */
1439
+ }
1440
+ // 5. Mark the exit clean so the next boot isn't counted as a crash.
1441
+ markCleanShutdown(reason);
1442
+ // 6. Notify the host.
1443
+ emitHostEvent('shutdown', { code: reason });
1444
+ };
1445
+
1446
+ class WatchdogLadder {
1447
+ constructor(thresholds, budgetBytes) {
1448
+ this.thresholds = thresholds;
1449
+ this.budgetBytes = budgetBytes;
1450
+ this.belowRecoverSince = null;
1451
+ this.state = 'normal';
1452
+ }
1453
+ /** Maps a memory sample to the raw action the ladder calls for, if any. */
1454
+ onSample(usedBytes, now) {
1455
+ if (this.budgetBytes <= 0)
1456
+ return null;
1457
+ const used = usedBytes / this.budgetBytes;
1458
+ const t = this.thresholds;
1459
+ if (used > t.shutdownPct)
1460
+ return 'shutdown';
1461
+ if (used > t.degradePct)
1462
+ return 'degrade';
1463
+ if (used > t.warnPct)
1464
+ return 'warn';
1465
+ if (used < t.recoverPct && this.state !== 'normal') {
1466
+ if (this.belowRecoverSince === null)
1467
+ this.belowRecoverSince = now;
1468
+ return now - this.belowRecoverSince >= t.recoverHoldMs ? 'recover' : null;
1469
+ }
1470
+ this.belowRecoverSince = null;
1471
+ return null;
1472
+ }
1473
+ /** Applies an action; returns it only when it is a real state transition. */
1474
+ transition(action) {
1475
+ if (this.state === 'shutdown')
1476
+ return null;
1477
+ switch (action) {
1478
+ case 'shutdown':
1479
+ this.state = 'shutdown';
1480
+ return 'shutdown';
1481
+ case 'degrade':
1482
+ this.belowRecoverSince = null;
1483
+ if (this.state === 'degraded')
1484
+ return null;
1485
+ this.state = 'degraded';
1486
+ return 'degrade';
1487
+ case 'warn':
1488
+ this.belowRecoverSince = null;
1489
+ // Warn never downgrades an active degrade.
1490
+ if (this.state !== 'normal')
1491
+ return null;
1492
+ this.state = 'warn';
1493
+ return 'warn';
1494
+ case 'recover':
1495
+ this.belowRecoverSince = null;
1496
+ if (this.state === 'normal')
1497
+ return null;
1498
+ this.state = 'normal';
1499
+ return 'recover';
1500
+ }
1501
+ }
1502
+ }
1503
+ let timerId = null;
1504
+ const readHeapUsedBytes = () => {
1505
+ const perf = globalThis.performance;
1506
+ const used = perf?.memory?.usedJSHeapSize;
1507
+ return typeof used === 'number' && used > 0 ? used : null;
593
1508
  };
594
- const getRegistrationSettings = () => state.registrationSettings ?? null;
595
- const setStatus = (status) => {
596
- state.status = status;
1509
+ const act = (ladder, action) => {
1510
+ const transition = action ? ladder.transition(action) : null;
1511
+ if (!transition)
1512
+ return;
1513
+ const reporter = getEventReporter();
1514
+ switch (transition) {
1515
+ case 'warn':
1516
+ reporter.report('guardrail.pressure_warning', { code: 'memory_pressure' });
1517
+ break;
1518
+ case 'degrade':
1519
+ // Finish in-flight, accept nothing new; the DO takes us out of rotation.
1520
+ setLifecycleStatus('degraded');
1521
+ sendStatusUpdate('error');
1522
+ reporter.report('guardrail.degraded', { code: 'memory_pressure' });
1523
+ emitHostEvent('degraded', { code: 'memory_pressure' });
1524
+ break;
1525
+ case 'recover':
1526
+ setLifecycleStatus('running');
1527
+ sendStatusUpdate('idle');
1528
+ emitHostEvent('recovered', {});
1529
+ break;
1530
+ case 'shutdown':
1531
+ stopWatchdog();
1532
+ void runShutdownSequence({ reason: 'memory_pressure', guardrail: true });
1533
+ break;
1534
+ }
597
1535
  };
598
- const getState = () => {
599
- if (!state.config || !state.deviceId || !state.deviceInfo) {
600
- throw new Error('SDK state not initialized');
1536
+ const startWatchdog = () => {
1537
+ if (timerId !== null || getResourcePolicy().disableGuardrails)
1538
+ return;
1539
+ if (readHeapUsedBytes() === null) {
1540
+ getLogger().debug('[Watchdog] performance.memory unavailable; watchdog inactive');
1541
+ return;
601
1542
  }
602
- return state;
1543
+ const guardrails = getGuardrails();
1544
+ let memoryGb = guardrails.unknownMemoryGb;
1545
+ try {
1546
+ const reported = getState().deviceInfo?.memoryGb;
1547
+ if (typeof reported === 'number' && reported > 0)
1548
+ memoryGb = reported;
1549
+ }
1550
+ catch {
1551
+ /* state not initialized yet */
1552
+ }
1553
+ const budgetBytes = guardrails.memoryBudgetFraction * memoryGb * 1024 * 1024 * 1024;
1554
+ const ladder = new WatchdogLadder(guardrails.watchdog, budgetBytes);
1555
+ timerId = setInterval(() => {
1556
+ try {
1557
+ if (getLifecycleStatus() === 'shutdown') {
1558
+ stopWatchdog();
1559
+ return;
1560
+ }
1561
+ // Hidden pages get throttled timers and misleading heap numbers; the
1562
+ // terminal-flush path owns backgrounding.
1563
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden')
1564
+ return;
1565
+ const used = readHeapUsedBytes();
1566
+ if (used === null)
1567
+ return;
1568
+ act(ladder, ladder.onSample(used, Date.now()));
1569
+ }
1570
+ catch {
1571
+ // The watchdog must never crash the host.
1572
+ }
1573
+ }, guardrails.watchdog.sampleMs);
603
1574
  };
604
-
605
- const factories = [];
606
- const registerAdapter = (factory) => {
607
- factories.push(factory);
1575
+ const stopWatchdog = () => {
1576
+ if (timerId !== null) {
1577
+ clearInterval(timerId);
1578
+ timerId = null;
1579
+ }
608
1580
  };
609
- const matches = (capability, framework, taskType) => capability.inferenceFramework.toLowerCase() === framework.toLowerCase() &&
610
- capability.taskType.toLowerCase() === taskType.toLowerCase();
611
- const getAdapterFactory = (framework, taskType) => {
612
- if (!framework || !taskType)
613
- return undefined;
614
- return factories.find((factory) => factory.capabilities.some((capability) => matches(capability, framework, taskType)));
1581
+ /**
1582
+ * Allocation-failure boundary (Layer 5): adapters that catch a RangeError /
1583
+ * wasm abort route here instead of propagating — we may be one allocation from
1584
+ * the OOM kill, so run the emergency variant immediately.
1585
+ */
1586
+ const onAllocationFailure = (message) => {
1587
+ stopWatchdog();
1588
+ void runShutdownSequence({ reason: 'oom', guardrail: true });
1589
+ getLogger().error('[Watchdog] Allocation failure — emergency shutdown', { message });
615
1590
  };
616
1591
 
617
1592
  let executing = false;
@@ -671,6 +1646,7 @@ const executeSingleRequest = async (request) => {
671
1646
  adapter = await lazyLoadAdapter(request.modelId);
672
1647
  }
673
1648
  if (!adapter) {
1649
+ getEventReporter().report('task.rejected', { code: 'not_ready', modelId: request.modelId });
674
1650
  return {
675
1651
  requestId: request.requestId,
676
1652
  modelId: request.modelId,
@@ -700,6 +1676,19 @@ const executeSingleRequest = async (request) => {
700
1676
  }
701
1677
  catch (error) {
702
1678
  logger.error('Task failed', error);
1679
+ const message = error.message ?? '';
1680
+ const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
1681
+ getEventReporter().report('task.failed', {
1682
+ code: isAllocationFailure ? 'oom' : 'adapter_error',
1683
+ modelId: request.modelId,
1684
+ durationMs: Math.round(performance.now() - start),
1685
+ message
1686
+ });
1687
+ if (isAllocationFailure) {
1688
+ // We may be one allocation from the OOM kill — emergency shutdown
1689
+ // (Layer 5 boundary); the error envelope below still goes out first.
1690
+ onAllocationFailure(message);
1691
+ }
703
1692
  return {
704
1693
  requestId: request.requestId,
705
1694
  modelId: request.modelId,
@@ -727,7 +1716,23 @@ const handleIncomingMessage = async (msg) => {
727
1716
  if (msg.requests.length === 0) {
728
1717
  return;
729
1718
  }
1719
+ // Degraded/shutting-down: finish in-flight work, accept nothing new — the
1720
+ // standard error envelope tells the server to route elsewhere immediately.
1721
+ if (isTaskGateActive()) {
1722
+ getEventReporter().report('task.rejected', { code: 'degraded' });
1723
+ sendBatchResponse(msg.requests.map((request) => ({
1724
+ requestId: request.requestId,
1725
+ modelId: request.modelId,
1726
+ modelVersion: request.modelVersion,
1727
+ response: { text: '' },
1728
+ error: true,
1729
+ errorMessage: 'degraded',
1730
+ metadata: { processingTime: 0 }
1731
+ })));
1732
+ return;
1733
+ }
730
1734
  if (executing) {
1735
+ getEventReporter().report('task.rejected', { code: 'busy' });
731
1736
  sendBatchResponse(msg.requests.map((request) => ({
732
1737
  requestId: request.requestId,
733
1738
  modelId: request.modelId,
@@ -881,115 +1886,88 @@ const clearCachedModelInfo = (modelId) => {
881
1886
  safeRemoveItem(CACHED_MODEL_ID_KEY);
882
1887
  };
883
1888
 
884
- /**
885
- * Crash-loop guard for SDK initialization.
886
- *
887
- * On a brand-new device the lifecycle synchronously downloads and instantiates a
888
- * full model (and runs a sample inference) before connecting the WebSocket. In a
889
- * memory-constrained host such as a Telegram mini-app WebView this burst can
890
- * crash/OOM the view. The host then reloads the mini-app, the SDK runs the same
891
- * heavy first-run path again, crashes again, and the app appears to "refresh
892
- * continuously".
893
- *
894
- * Nothing in the previous flow recorded a *failed* attempt: the cache pointer is
895
- * only written after a fully successful load, so every reload looked like a fresh
896
- * first run. This guard persists a small attempt counter *before* the heavy work
897
- * and clears it only once init reaches a stable point. If we see several attempts
898
- * in a short window that never completed, we assume a crash loop and skip the
899
- * heavy init for a cool-down period, which breaks the refresh cycle and lets the
900
- * host app stay up.
901
- */
902
- const INIT_STATE_KEY = 'zerogpu_init_state';
903
- /** Attempts that never completed are only counted within this rolling window. */
904
- const ATTEMPT_WINDOW_MS = 60000;
905
- /** Number of uncompleted attempts in the window that trips the cool-down. */
906
- const MAX_ATTEMPTS_IN_WINDOW = 3;
907
- /** How long to skip heavy init once a crash loop is detected. */
908
- const COOLDOWN_MS = 5 * 60000;
909
- const readState = () => {
1889
+ const BYTES_PER_GB = 1024 * 1024 * 1024;
1890
+ const evaluateResourceGate = async (model, stage, deviceInfo) => {
910
1891
  try {
911
- const raw = window.localStorage.getItem(INIT_STATE_KEY);
912
- if (!raw)
913
- return null;
914
- const parsed = JSON.parse(raw);
915
- if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
1892
+ if (getResourcePolicy().disableGuardrails)
916
1893
  return null;
1894
+ const guardrails = getGuardrails();
1895
+ const sizeBytes = normalizeModelSizeBytes(model.sizeBytes);
1896
+ if (sizeBytes > 0) {
1897
+ const maxModelBytes = getResourcePolicy().maxModelBytes;
1898
+ if (typeof maxModelBytes === 'number' && sizeBytes > maxModelBytes) {
1899
+ return {
1900
+ code: 'model_too_large_for_memory',
1901
+ message: `model ${sizeBytes} B exceeds host maxModelBytes ${maxModelBytes}`
1902
+ };
1903
+ }
1904
+ const multiplier = multiplierFor(model.inferenceFramework);
1905
+ const estimatedRuntimeBytes = sizeBytes * multiplier;
1906
+ const memoryGb = typeof deviceInfo?.memoryGb === 'number' && deviceInfo.memoryGb > 0
1907
+ ? deviceInfo.memoryGb
1908
+ : guardrails.unknownMemoryGb;
1909
+ const budgetBytes = guardrails.memoryBudgetFraction * memoryGb * BYTES_PER_GB;
1910
+ if (estimatedRuntimeBytes > budgetBytes) {
1911
+ return {
1912
+ code: 'model_too_large_for_memory',
1913
+ message: `estimated runtime ${Math.round(estimatedRuntimeBytes)} B > budget ${Math.round(budgetBytes)} B ` +
1914
+ `(fraction=${guardrails.memoryBudgetFraction}, multiplier=${multiplier}, memoryGb=${memoryGb})`
1915
+ };
1916
+ }
1917
+ // Heap headroom — Chromium only; other engines expose nothing and the
1918
+ // preflight above stays the only pre-load signal there.
1919
+ const perf = globalThis.performance;
1920
+ const heap = perf?.memory;
1921
+ if (heap && heap.jsHeapSizeLimit > 0 && heap.usedJSHeapSize + estimatedRuntimeBytes > heap.jsHeapSizeLimit) {
1922
+ return {
1923
+ code: 'model_too_large_for_memory',
1924
+ message: `heap used ${heap.usedJSHeapSize} + runtime ${Math.round(estimatedRuntimeBytes)} exceeds limit ${heap.jsHeapSizeLimit}`
1925
+ };
1926
+ }
1927
+ if (stage === 'download') {
1928
+ try {
1929
+ const estimate = await navigator.storage?.estimate?.();
1930
+ if (estimate && typeof estimate.quota === 'number' && typeof estimate.usage === 'number') {
1931
+ const free = estimate.quota - estimate.usage;
1932
+ if (sizeBytes * guardrails.storageHeadroom > free) {
1933
+ return {
1934
+ code: 'storage_quota_exceeded',
1935
+ message: `need ${Math.round(sizeBytes * guardrails.storageHeadroom)} B, quota headroom ${free} B`
1936
+ };
1937
+ }
1938
+ }
1939
+ }
1940
+ catch {
1941
+ // Storage estimate unavailable — skip the check.
1942
+ }
1943
+ }
1944
+ }
1945
+ if (stage === 'download') {
1946
+ const battery = deviceInfo?.battery;
1947
+ if (battery &&
1948
+ typeof battery.level === 'number' &&
1949
+ battery.level < guardrails.minBatteryLevel &&
1950
+ battery.charging !== true) {
1951
+ return {
1952
+ code: 'low_battery',
1953
+ message: `battery ${battery.level} below ${guardrails.minBatteryLevel} and not charging`
1954
+ };
1955
+ }
917
1956
  }
918
- return parsed;
919
- }
920
- catch {
921
1957
  return null;
922
1958
  }
923
- };
924
- const writeState = (state) => {
925
- try {
926
- window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
927
- }
928
1959
  catch {
929
- // Storage may be unavailable/partitioned; degrade silently.
930
- }
931
- };
932
- const clearState = () => {
933
- try {
934
- window.localStorage.removeItem(INIT_STATE_KEY);
935
- }
936
- catch {
937
- // ignore
938
- }
939
- };
940
- /**
941
- * Records the start of an init attempt and decides whether heavy init may
942
- * proceed. Must be called once, before any heavy work, on every lifecycle start.
943
- */
944
- const beginInitAttempt = (now = Date.now()) => {
945
- const state = readState();
946
- // Still inside an active cool-down from a previously detected crash loop.
947
- if (state?.cooldownUntil && state.cooldownUntil > now) {
948
- return {
949
- allowed: false,
950
- cooldownRemainingMs: state.cooldownUntil - now,
951
- attempts: state.attempts
952
- };
953
- }
954
- // No prior state, or the previous window/cool-down has elapsed → start fresh.
955
- if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
956
- writeState({ attempts: 1, windowStart: now });
957
- return { allowed: true, attempts: 1 };
958
- }
959
- const attempts = state.attempts + 1;
960
- // Too many uncompleted attempts in the window → assume a crash loop and back
961
- // off so the host app stops reloading.
962
- if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
963
- writeState({
964
- attempts,
965
- windowStart: state.windowStart,
966
- cooldownUntil: now + COOLDOWN_MS
967
- });
968
- return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts };
1960
+ // The gate itself must never break init.
1961
+ return null;
969
1962
  }
970
- writeState({ attempts, windowStart: state.windowStart });
971
- return { allowed: true, attempts };
972
- };
973
- /**
974
- * Clears crash tracking. Call once init reaches a stable point (e.g. the
975
- * WebSocket is connected), so successful loads never accumulate toward a trip.
976
- */
977
- const markInitSuccess = () => {
978
- clearState();
979
1963
  };
980
1964
 
981
1965
  // Re-registration loop: when the server idle-closes the WebSocket (or it drops
982
1966
  // for any reason), wait device_timeout_interval_seconds and run the full
983
1967
  // lifecycle again — re-registering refreshes device metrics and yields a new
984
- // session key + WS URL. A single pending timer at a time; before reconnecting
985
- // we check no socket is already live (infinite-loop guard).
986
- let reregisterTimerId = null;
987
- const clearReregisterTimer = () => {
988
- if (reregisterTimerId !== null) {
989
- clearTimeout(reregisterTimerId);
990
- reregisterTimerId = null;
991
- }
992
- };
1968
+ // session key + WS URL. The single pending timer lives in ./reregister so the
1969
+ // shutdown sequence can kill it (§4.7); before reconnecting we check no socket
1970
+ // is already live (infinite-loop guard).
993
1971
  const resolveReregisterDelaySeconds = () => {
994
1972
  const value = getRegistrationSettings()?.device_timeout_interval_seconds;
995
1973
  return typeof value === 'number' && Number.isFinite(value) && value > 0
@@ -998,14 +1976,17 @@ const resolveReregisterDelaySeconds = () => {
998
1976
  };
999
1977
  const scheduleReregistration = (options) => {
1000
1978
  const logger = getLogger();
1001
- if (reregisterTimerId !== null) {
1979
+ if (hasReregisterTimer()) {
1002
1980
  logger.debug('[WS] Re-registration already scheduled; skipping');
1003
1981
  return;
1004
1982
  }
1983
+ if (isShutdown()) {
1984
+ logger.debug('[WS] SDK is shut down; not scheduling re-registration');
1985
+ return;
1986
+ }
1005
1987
  const delaySeconds = resolveReregisterDelaySeconds();
1006
1988
  logger.info('[WS] Scheduling re-registration', { delaySeconds });
1007
- reregisterTimerId = setTimeout(() => {
1008
- reregisterTimerId = null;
1989
+ setReregisterTimer(() => {
1009
1990
  if (getWebSocket()?.isActive()) {
1010
1991
  logger.info('[WS] Active WebSocket present; skipping re-registration');
1011
1992
  return;
@@ -1034,6 +2015,13 @@ const extractRegistrationSettings = (configSettings) => {
1034
2015
  const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
1035
2016
  initLogger(config.telemetry);
1036
2017
  const logger = getLogger();
2018
+ // Shutdown is terminal until the host restarts the SDK (page reload): a
2019
+ // stray timer or caller must not resurrect us into the same conditions.
2020
+ if (isShutdown()) {
2021
+ logger.warn('[Init] SDK is shut down; refusing to start lifecycle');
2022
+ return;
2023
+ }
2024
+ setLifecycleStatus('starting');
1037
2025
  setConfig(config);
1038
2026
  // A fresh (manual or scheduled) start supersedes any pending reconnect timer.
1039
2027
  clearReregisterTimer();
@@ -1056,12 +2044,17 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1056
2044
  const guard = beginInitAttempt();
1057
2045
  if (!guard.allowed) {
1058
2046
  setStatus('error');
2047
+ setLifecycleStatus('error');
1059
2048
  logger.warn('Init skipped: crash-loop guard active', {
1060
2049
  attempts: guard.attempts,
1061
2050
  cooldownRemainingMs: guard.cooldownRemainingMs
1062
2051
  });
2052
+ // Reporter may exist from an earlier run on this page; best-effort only —
2053
+ // on a cold page the offline buffer picks the story up next boot.
2054
+ getEventReporter().report('sdk.init_failed', { code: 'crash_loop' });
1063
2055
  return;
1064
2056
  }
2057
+ const bootStartedAt = performance.now();
1065
2058
  const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
1066
2059
  const isFreshDevice = !providedDeviceId && !storedDeviceId;
1067
2060
  const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
@@ -1078,6 +2071,17 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1078
2071
  const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
1079
2072
  const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
1080
2073
  setDeviceContext(deviceId, sanitizedDeviceInfo);
2074
+ initEventReporter({
2075
+ enabled: config.telemetry.events,
2076
+ endpointUrl: `${config.orchestrator.baseUrl}${config.orchestrator.eventsPath}`,
2077
+ operatorKey: edgeOperatorKey,
2078
+ deviceId,
2079
+ sdkVersion: config.sdkVersion,
2080
+ platform: sanitizedDeviceInfo.platform
2081
+ });
2082
+ const reporter = getEventReporter();
2083
+ reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2084
+ reportCrashFromPreviousSession(guard.crash);
1081
2085
  logger.info('[Init] Device info collected', {
1082
2086
  platform: sanitizedDeviceInfo.platform,
1083
2087
  deviceType: sanitizedDeviceInfo.deviceType,
@@ -1100,6 +2104,20 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1100
2104
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
1101
2105
  setCachedModelId(cachedModelId);
1102
2106
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
2107
+ // Breaker short-circuit: a blocklisted model must not be validation-loaded
2108
+ // (that load is the exact thing that killed the host) and must not be
2109
+ // advertised in cachedModels. Files stay on disk; the entry lapses in 24 h.
2110
+ if (cachedInfo && isModelBlocklisted(cachedInfo.modelId, cachedInfo.modelVersion)) {
2111
+ reporter.report('guardrail.preflight_blocked', {
2112
+ code: 'model_blocklisted',
2113
+ modelId: cachedInfo.modelId,
2114
+ modelVersion: cachedInfo.modelVersion
2115
+ });
2116
+ logger.warn('[Guard] Cached model is blocklisted; skipping cache validation', {
2117
+ modelId: cachedInfo.modelId
2118
+ });
2119
+ cachedInfo = null;
2120
+ }
1103
2121
  if (!isFreshDevice) {
1104
2122
  logger.info('Cache lookup', {
1105
2123
  cachedModelId,
@@ -1173,6 +2191,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1173
2191
  });
1174
2192
  }
1175
2193
  else {
2194
+ setInitPhase('loading', cachedInfo.modelId, cachedInfo.modelVersion);
1176
2195
  const loadResult = await factory.load(slmConfig, { allowDownload: hasCachedFiles });
1177
2196
  if (!loadResult.adapter || loadResult.error) {
1178
2197
  cacheInvalid = true;
@@ -1192,6 +2211,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1192
2211
  cachedAdapter = loadResult.adapter;
1193
2212
  setAdapter(cachedInfo.modelId, cachedAdapter);
1194
2213
  const sample = cachedInfo.sample;
2214
+ setInitPhase('sampling', cachedInfo.modelId, cachedInfo.modelVersion);
1195
2215
  const sampleResult = await cachedAdapter.runSample(sample);
1196
2216
  cachedSampleMetrics = {
1197
2217
  taskType: cachedInfo.taskType,
@@ -1231,15 +2251,23 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1231
2251
  logFlow('Cached sample evaluated', cachedSampleMetrics);
1232
2252
  }
1233
2253
  if (cacheInvalid) {
2254
+ reporter.report('model.cache_invalid', {
2255
+ code: mapCacheInvalidCode(cachedSampleMetrics?.errorMessage),
2256
+ modelId: cachedInfo?.modelId ?? cachedModelId ?? undefined
2257
+ });
1234
2258
  await clearAllModels().catch(() => { });
1235
2259
  await clearTransformersCaches().catch(() => { });
1236
2260
  clearCachedModelInfo(cachedModelId);
1237
2261
  setCachedModelId(null);
2262
+ reporter.report('model.cache_purged');
1238
2263
  cachedInfo = null;
1239
2264
  cachedAdapter = undefined;
1240
2265
  setAdaptersByModelId({});
1241
2266
  setModelInfosByModelId({});
1242
2267
  }
2268
+ else if (cachedInfo && cachedAdapter) {
2269
+ reporter.report('model.cache_hit', { modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion });
2270
+ }
1243
2271
  const registerPayload = {
1244
2272
  deviceId,
1245
2273
  sdkVersion: config.sdkVersion,
@@ -1260,6 +2288,8 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1260
2288
  cachedModels: registerPayload.cachedModels,
1261
2289
  sdkVersion: config.sdkVersion
1262
2290
  });
2291
+ reporter.report('register.started');
2292
+ const registerStartedAt = performance.now();
1263
2293
  try {
1264
2294
  registerResponse = await registerDevice(config, registerPayload, {
1265
2295
  edgeOperatorKey
@@ -1269,27 +2299,57 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1269
2299
  if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
1270
2300
  logger.warn('Register auth failed, stopping lifecycle');
1271
2301
  logFlow('Auth failure; no WS connection', { status: err.status });
2302
+ reporter.report('register.failed', { code: 'auth' });
2303
+ reporter.report('sdk.init_failed', { code: 'auth' });
1272
2304
  markInitSuccess(); // Clean exit, not a crash loop.
1273
2305
  return;
1274
2306
  }
2307
+ reporter.report('register.failed', { code: mapRegisterErrorCode(err), message: err.message });
2308
+ reporter.report('sdk.init_failed', { code: mapRegisterErrorCode(err) });
1275
2309
  markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
1276
2310
  throw err;
1277
2311
  }
1278
- logger.info('Register response received:', {
1279
- deviceId: registerResponse.deviceId,
1280
- wsUrl: registerResponse.wsUrl
1281
- });
2312
+ // Settings (incl. server-tuned guardrails) apply on every outcome — a
2313
+ // refusal can still carry the tunables and the re-register interval.
1282
2314
  const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
1283
2315
  setRegistrationSettings(registrationSettings);
2316
+ applyRegistrationGuardrails(registrationSettings);
1284
2317
  if (registrationSettings) {
1285
2318
  logger.info('[Register] Registration settings received', registrationSettings);
1286
2319
  }
2320
+ if (registerResponse.refusalReason) {
2321
+ // The server deliberately declined this device (admission rules) — the
2322
+ // opposite of a failure. Exit cleanly, come back on the slow re-register
2323
+ // interval: battery/connection refusals are transient conditions.
2324
+ reporter.report('register.rejected', { code: registerResponse.refusalReason });
2325
+ logger.warn('[Register] Registration refused by server', {
2326
+ reason: registerResponse.refusalReason
2327
+ });
2328
+ setStatus('error');
2329
+ setLifecycleStatus('error');
2330
+ markInitSuccess(); // Clean exit, not a crash loop.
2331
+ scheduleReregistration(lifecycleOptions);
2332
+ return;
2333
+ }
2334
+ reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
2335
+ reporter.setSessionKey(registerResponse.sessionKey);
2336
+ logger.info('Register response received:', {
2337
+ deviceId: registerResponse.deviceId,
2338
+ wsUrl: registerResponse.wsUrl
2339
+ });
1287
2340
  if (!registerResponse.wsUrl) {
1288
2341
  markInitSuccess(); // Clean exit, not a crash loop.
1289
2342
  return;
1290
2343
  }
1291
2344
  assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
1292
2345
  const primaryModel = assignedModels[0];
2346
+ if (primaryModel) {
2347
+ reporter.report('model.assigned', {
2348
+ modelId: primaryModel.modelId,
2349
+ modelVersion: primaryModel.modelVersion,
2350
+ bytes: primaryModel.sizeBytes
2351
+ });
2352
+ }
1293
2353
  logger.info('[Register] Models assigned', {
1294
2354
  count: assignedModels.length,
1295
2355
  models: assignedModels.map((m) => ({
@@ -1335,9 +2395,33 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1335
2395
  setAdaptersByModelId({});
1336
2396
  const slmConfig = buildSlmConfigFromAssigned(primaryModel);
1337
2397
  const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
1338
- if (!factory) {
2398
+ // Layer 2/4 preflight: blocklisted or won't-fit models are refused before
2399
+ // any download/allocation. The model is reported `error` in the hello so
2400
+ // the device stays registered and auditable; the host stays alive.
2401
+ const preflightBlock = await preflightAssignedModel(primaryModel);
2402
+ if (preflightBlock) {
2403
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
2404
+ loadErrorMessage = `preflight_blocked:${preflightBlock.code}`;
2405
+ reporter.report('guardrail.preflight_blocked', {
2406
+ code: preflightBlock.code,
2407
+ modelId: primaryModel.modelId,
2408
+ modelVersion: primaryModel.modelVersion,
2409
+ message: preflightBlock.message
2410
+ });
2411
+ logger.warn('[Guard] Primary model blocked by preflight', {
2412
+ modelId: primaryModel.modelId,
2413
+ code: preflightBlock.code,
2414
+ message: preflightBlock.message
2415
+ });
2416
+ }
2417
+ else if (!factory) {
1339
2418
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1340
2419
  loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
2420
+ reporter.report('model.load_failed', {
2421
+ code: 'no_adapter_factory',
2422
+ modelId: primaryModel.modelId,
2423
+ modelVersion: primaryModel.modelVersion
2424
+ });
1341
2425
  logger.error('[Model] No adapter factory for primary model', {
1342
2426
  modelId: primaryModel.modelId,
1343
2427
  framework: slmConfig.inferenceFramework,
@@ -1353,11 +2437,19 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1353
2437
  sizeBytes: primaryModel.sizeBytes,
1354
2438
  modelRepoId: primaryModel.modelRepoId
1355
2439
  });
2440
+ reporter.report('model.load_started', { modelId: primaryModel.modelId, modelVersion: primaryModel.modelVersion });
2441
+ setInitPhase('loading', primaryModel.modelId, primaryModel.modelVersion);
1356
2442
  const primaryLoadStart = performance.now();
1357
2443
  const loadResult = await factory.load(slmConfig);
1358
2444
  const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
1359
2445
  loadErrorMessage = loadResult.error?.message;
1360
2446
  if (loadResult.adapter) {
2447
+ reporter.report('model.load_succeeded', {
2448
+ modelId: primaryModel.modelId,
2449
+ modelVersion: primaryModel.modelVersion,
2450
+ durationMs: primaryLoadMs,
2451
+ bytes: loadResult.metrics?.sizeBytes
2452
+ });
1361
2453
  logger.info('[Model] Primary model loaded', {
1362
2454
  modelId: primaryModel.modelId,
1363
2455
  ms: primaryLoadMs,
@@ -1382,6 +2474,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1382
2474
  }
1383
2475
  else {
1384
2476
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
2477
+ reporter.report('model.load_failed', {
2478
+ code: mapModelLoadErrorCode(loadErrorMessage),
2479
+ modelId: primaryModel.modelId,
2480
+ modelVersion: primaryModel.modelVersion,
2481
+ durationMs: primaryLoadMs,
2482
+ message: loadErrorMessage
2483
+ });
1385
2484
  logger.error('[Model] Primary model load failed', {
1386
2485
  modelId: primaryModel.modelId,
1387
2486
  framework: slmConfig.inferenceFramework,
@@ -1426,6 +2525,18 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1426
2525
  });
1427
2526
  continue;
1428
2527
  }
2528
+ const secondaryBlock = await preflightAssignedModel(model);
2529
+ if (secondaryBlock) {
2530
+ modelStatuses[getModelStatusKey(model)] = 'error';
2531
+ reporter.report('guardrail.preflight_blocked', {
2532
+ code: secondaryBlock.code,
2533
+ modelId: model.modelId,
2534
+ modelVersion: model.modelVersion,
2535
+ message: secondaryBlock.message
2536
+ });
2537
+ continue;
2538
+ }
2539
+ setInitPhase('loading', model.modelId, model.modelVersion);
1429
2540
  const loadResult = await factory.load(slmConfig);
1430
2541
  if (loadResult.adapter) {
1431
2542
  adaptersByModelId[model.modelId] = loadResult.adapter;
@@ -1468,7 +2579,9 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1468
2579
  errorMessage: `primary_model_load_failed:${reason}`
1469
2580
  }
1470
2581
  }).catch(() => { });
2582
+ reporter.report('ws.init_failure_reported', { code: 'primary_model_load_failed', message: reason });
1471
2583
  }
2584
+ reporter.report('sdk.init_failed', { code: 'primary_model_load_failed', message: reason });
1472
2585
  logger.error('Primary model failed to initialize; aborting lifecycle before WebSocket connect', {
1473
2586
  modelId: primaryModel.modelId,
1474
2587
  modelVersion: primaryModel.modelVersion,
@@ -1481,6 +2594,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1481
2594
  logger.info('[Sample] Running post-register sample inference', {
1482
2595
  taskType: primaryModel.taskType
1483
2596
  });
2597
+ setInitPhase('sampling', primaryModel.modelId, primaryModel.modelVersion);
1484
2598
  postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1485
2599
  const sampleLog = {
1486
2600
  taskType: primaryModel.taskType,
@@ -1490,9 +2604,20 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1490
2604
  processingTimeMs: postRegisterSample.processingTimeMs
1491
2605
  };
1492
2606
  if (postRegisterSample.error || !postRegisterSample.ok) {
2607
+ reporter.report('model.sample_failed', {
2608
+ modelId: primaryModel.modelId,
2609
+ durationMs: postRegisterSample.processingTimeMs,
2610
+ message: postRegisterSample.errorMessage,
2611
+ data: { phase: 'post_register' }
2612
+ });
1493
2613
  logger.error('[Sample] Post-register sample failed', sampleLog);
1494
2614
  }
1495
2615
  else {
2616
+ reporter.report('model.sample_succeeded', {
2617
+ modelId: primaryModel.modelId,
2618
+ durationMs: postRegisterSample.processingTimeMs,
2619
+ data: { phase: 'post_register' }
2620
+ });
1496
2621
  logger.info('[Sample] Post-register sample ok', sampleLog);
1497
2622
  }
1498
2623
  if (postRegisterSample.error) {
@@ -1516,9 +2641,11 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1516
2641
  wsUrl: registerResponse.wsUrl,
1517
2642
  models: helloSlmConfig
1518
2643
  });
2644
+ reporter.report('ws.connect_started');
1519
2645
  const client = new WebSocketClient({
1520
2646
  url: registerResponse.wsUrl,
1521
2647
  hello,
2648
+ onOpen: () => reporter.report('ws.connected'),
1522
2649
  onMessage: (message) => {
1523
2650
  if ('requests' in message && Array.isArray(message.requests)) {
1524
2651
  handleIncomingMessage(message);
@@ -1526,6 +2653,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1526
2653
  else if ('type' in message && message.type === 'hello_ack') {
1527
2654
  const ack = message;
1528
2655
  logger.info('[WS] Received hello_ack', ack);
2656
+ reporter.report('ws.hello_ack', {
2657
+ code: ack.status,
2658
+ message: ack.errorMessage
2659
+ });
1529
2660
  setStatus(ack.status === 'error' ? 'error' : 'idle');
1530
2661
  }
1531
2662
  else {
@@ -1539,11 +2670,16 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1539
2670
  if (getWebSocket() !== client) {
1540
2671
  return;
1541
2672
  }
2673
+ reporter.report('ws.closed', {
2674
+ code: `close_${event.code}`,
2675
+ data: { wasClean: event.wasClean }
2676
+ });
1542
2677
  setStatus('error');
1543
2678
  scheduleReregistration(lifecycleOptions);
1544
2679
  },
1545
2680
  onError: () => {
1546
2681
  logger.error('[WS] Connection error');
2682
+ reporter.report('ws.error');
1547
2683
  if (getWebSocket() === client) {
1548
2684
  setStatus('error');
1549
2685
  }
@@ -1551,6 +2687,11 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1551
2687
  });
1552
2688
  setWebSocket(client);
1553
2689
  setStatus('idle');
2690
+ // Model phases are behind us; a death from here on is not model-attributed.
2691
+ setInitPhase('running', primaryModel.modelId, primaryModel.modelVersion);
2692
+ setLifecycleStatus('running');
2693
+ startWatchdog();
2694
+ reporter.report('sdk.init_succeeded', { durationMs: Math.round(performance.now() - bootStartedAt) });
1554
2695
  logger.info('[Init] SDK ready', {
1555
2696
  deviceId,
1556
2697
  primaryModelId: primaryModel.modelId,
@@ -1560,6 +2701,72 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1560
2701
  // not a crash loop, so clear the attempt counter.
1561
2702
  markInitSuccess();
1562
2703
  };
2704
+ const mapCacheInvalidCode = (errorMessage) => {
2705
+ if (errorMessage === 'no_adapter_factory')
2706
+ return 'no_adapter_factory';
2707
+ if (errorMessage === 'sample_failed')
2708
+ return 'sample_failed';
2709
+ return 'files_missing';
2710
+ };
2711
+ const mapRegisterErrorCode = (err) => {
2712
+ if (err instanceof RegisterError)
2713
+ return `http_${err.status}`;
2714
+ const message = err?.message ?? '';
2715
+ if (/timeout/i.test(message))
2716
+ return 'timeout';
2717
+ return 'network';
2718
+ };
2719
+ const mapModelLoadErrorCode = (message) => {
2720
+ if (!message)
2721
+ return 'init_error';
2722
+ if (/preflight_blocked/.test(message))
2723
+ return 'guardrail_blocked';
2724
+ if (/no_adapter_factory/.test(message))
2725
+ return 'no_adapter_factory';
2726
+ if (/oom|out of memory|RangeError/i.test(message))
2727
+ return 'oom';
2728
+ if (/wasm|abort/i.test(message))
2729
+ return 'wasm_abort';
2730
+ return 'init_error';
2731
+ };
2732
+ /** Blocklist short-circuit, then the ResourceGate — before any I/O for a model. */
2733
+ const preflightAssignedModel = async (model) => {
2734
+ if (isModelBlocklisted(model.modelId, model.modelVersion)) {
2735
+ return { code: 'model_blocklisted', message: 'blocklisted after repeated crashes during load' };
2736
+ }
2737
+ let deviceInfo;
2738
+ try {
2739
+ deviceInfo = getState().deviceInfo;
2740
+ }
2741
+ catch {
2742
+ deviceInfo = undefined;
2743
+ }
2744
+ return evaluateResourceGate({
2745
+ modelId: model.modelId,
2746
+ modelVersion: model.modelVersion,
2747
+ sizeBytes: model.sizeBytes,
2748
+ inferenceFramework: model.inferenceFramework
2749
+ }, 'download', deviceInfo);
2750
+ };
2751
+ /** The previous process died mid-phase — attribute it now that the reporter is live. */
2752
+ const reportCrashFromPreviousSession = (crash) => {
2753
+ if (!crash)
2754
+ return;
2755
+ const reporter = getEventReporter();
2756
+ reporter.report('sdk.crash_detected', {
2757
+ code: crash.code,
2758
+ modelId: crash.modelId,
2759
+ modelVersion: crash.modelVersion,
2760
+ data: { phase: crash.phase }
2761
+ });
2762
+ if (crash.blocklistedModel) {
2763
+ reporter.report('guardrail.model_blocklisted', {
2764
+ modelId: crash.modelId,
2765
+ modelVersion: crash.modelVersion,
2766
+ message: crash.blocklistedModel
2767
+ });
2768
+ }
2769
+ };
1563
2770
  const normalizeAssignedModels = (slmConfig) => {
1564
2771
  if (!Array.isArray(slmConfig))
1565
2772
  return [];
@@ -3010,18 +4217,47 @@ const factory = {
3010
4217
  registerAdapter(factory);
3011
4218
 
3012
4219
  let initialized = false;
4220
+ const handle = {
4221
+ get status() {
4222
+ return getLifecycleStatus();
4223
+ },
4224
+ on: onHostEvent,
4225
+ shutdown: () => runShutdownSequence({ reason: 'host_stop' })
4226
+ };
4227
+ /**
4228
+ * Never rejects: the SDK is a guest in someone else's app, and a failed init
4229
+ * must degrade to "SDK not running" — observable via `handle.status` and the
4230
+ * reported `sdk.init_failed` events — never to an unhandled rejection in the
4231
+ * host. Existing `await initZeroGpuSdk(...)` callers are unaffected (the
4232
+ * returned handle is additive).
4233
+ */
3013
4234
  const initZeroGpuSdk = async (options) => {
3014
4235
  if (initialized) {
3015
- return;
4236
+ return handle;
3016
4237
  }
3017
- const config = resolveConfig(options?.overrides);
3018
- await startLifecycle({
3019
- config,
3020
- appUserId: options?.appUserId,
3021
- edgeOperatorKey: options?.edgeOperatorKey,
3022
- deviceId: options?.deviceId
3023
- });
3024
4238
  initialized = true;
4239
+ if (options?.resourcePolicy) {
4240
+ setResourcePolicy(options.resourcePolicy);
4241
+ if (options.resourcePolicy.disableGuardrails) {
4242
+ // Loud by design: a host running without guardrails should know it.
4243
+ console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
4244
+ }
4245
+ }
4246
+ const config = resolveConfig(options?.overrides);
4247
+ try {
4248
+ await startLifecycle({
4249
+ config,
4250
+ appUserId: options?.appUserId,
4251
+ edgeOperatorKey: options?.edgeOperatorKey,
4252
+ deviceId: options?.deviceId
4253
+ });
4254
+ }
4255
+ catch (err) {
4256
+ // Already reported inside the lifecycle (register.failed / sdk.init_failed
4257
+ // / init-failure hello); surface for the host without throwing into it.
4258
+ getLogger().error('[Init] SDK initialization failed', err);
4259
+ }
4260
+ return handle;
3025
4261
  };
3026
4262
 
3027
4263
  const readAttr = (script, names) => {
@@ -3115,14 +4351,25 @@ const autoInitFromScriptTag = () => {
3115
4351
  }
3116
4352
  return undefined;
3117
4353
  })();
3118
- if (enableConsoleLogs !== undefined) {
3119
- options.overrides = {
3120
- telemetry: {
3121
- enableConsoleLogs,
3122
- locationData: false,
3123
- cameraData: false
3124
- }
3125
- };
4354
+ const enableEvents = readBooleanAttr(script, ['data-zerogpu-telemetry-events', 'zerogpuTelemetryEvents']) ??
4355
+ (() => {
4356
+ const value = readSearchParam(searchParams, ['telemetry-events', 'zerogpuTelemetryEvents']);
4357
+ if (value === undefined)
4358
+ return undefined;
4359
+ const normalized = value.toLowerCase();
4360
+ if (normalized === 'true' || normalized === '1')
4361
+ return true;
4362
+ if (normalized === 'false' || normalized === '0')
4363
+ return false;
4364
+ return undefined;
4365
+ })();
4366
+ if (enableConsoleLogs !== undefined || enableEvents !== undefined) {
4367
+ const telemetry = {};
4368
+ if (enableConsoleLogs !== undefined)
4369
+ telemetry.enableConsoleLogs = enableConsoleLogs;
4370
+ if (enableEvents !== undefined)
4371
+ telemetry.events = enableEvents;
4372
+ options.overrides = { telemetry };
3126
4373
  }
3127
4374
  void initZeroGpuSdk(options).catch((error) => {
3128
4375
  console.error('[ZeroGpuSdk] Auto-init failed', error);