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