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