@zerogpu/browser-extension-sdk 0.1.3 → 0.1.6

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.
@@ -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.3+40f7add" === 'string' && "0.1.3+40f7add".length > 0
8
- ? "0.1.3+40f7add"
7
+ const SDK_VERSION = typeof "0.1.6+9f0db3f" === 'string' && "0.1.6+9f0db3f".length > 0
8
+ ? "0.1.6+9f0db3f"
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
@@ -14,6 +14,9 @@
14
14
 
15
15
  // The orchestrator URL is baked in at build time per deployment (develop/staging/
16
16
  // production). See ./orchestrator-url for the env-var injection and fallback.
17
+ // Fallback re-registration delay (seconds) after a WebSocket close, used when
18
+ // the register response carried no configSettings for this SDK type.
19
+ const DEFAULT_REREGISTER_INTERVAL_SECONDS = 600;
17
20
  const DEFAULT_CONFIG = {
18
21
  sdkVersion: SDK_VERSION,
19
22
  orchestrator: {
@@ -528,6 +531,9 @@
528
531
  this.socket.onerror = this.handleError;
529
532
  this.socket.onclose = this.handleClose;
530
533
  }
534
+ isActive() {
535
+ return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
536
+ }
531
537
  send(payload) {
532
538
  this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
533
539
  this.socket.send(JSON.stringify(payload));
@@ -584,6 +590,12 @@
584
590
  const setWebSocket = (ws) => {
585
591
  state.ws = ws;
586
592
  };
593
+ // Safe before full init (unlike getState) — used by the re-registration guard.
594
+ const getWebSocket = () => state.ws;
595
+ const setRegistrationSettings = (settings) => {
596
+ state.registrationSettings = settings ?? null;
597
+ };
598
+ const getRegistrationSettings = () => state.registrationSettings ?? null;
587
599
  const setStatus = (status) => {
588
600
  state.status = status;
589
601
  };
@@ -873,22 +885,208 @@
873
885
  safeRemoveItem(CACHED_MODEL_ID_KEY);
874
886
  };
875
887
 
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 = () => {
914
+ 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') {
920
+ return null;
921
+ }
922
+ return parsed;
923
+ }
924
+ catch {
925
+ return null;
926
+ }
927
+ };
928
+ const writeState = (state) => {
929
+ try {
930
+ window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
931
+ }
932
+ 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 };
973
+ }
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
+ };
984
+
985
+ // Re-registration loop: when the server idle-closes the WebSocket (or it drops
986
+ // for any reason), wait device_timeout_interval_seconds and run the full
987
+ // 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
+ };
997
+ const resolveReregisterDelaySeconds = () => {
998
+ const value = getRegistrationSettings()?.device_timeout_interval_seconds;
999
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
1000
+ ? value
1001
+ : DEFAULT_REREGISTER_INTERVAL_SECONDS;
1002
+ };
1003
+ const scheduleReregistration = (options) => {
1004
+ const logger = getLogger();
1005
+ if (reregisterTimerId !== null) {
1006
+ logger.debug('[WS] Re-registration already scheduled; skipping');
1007
+ return;
1008
+ }
1009
+ const delaySeconds = resolveReregisterDelaySeconds();
1010
+ logger.info('[WS] Scheduling re-registration', { delaySeconds });
1011
+ reregisterTimerId = setTimeout(() => {
1012
+ reregisterTimerId = null;
1013
+ if (getWebSocket()?.isActive()) {
1014
+ logger.info('[WS] Active WebSocket present; skipping re-registration');
1015
+ return;
1016
+ }
1017
+ logger.info('[WS] Re-registration timer fired; restarting lifecycle');
1018
+ startLifecycle(options).catch((err) => {
1019
+ logger.error('[WS] Re-registration attempt failed; will retry', err);
1020
+ // Keep the loop alive on transient failures (register/network/model
1021
+ // errors). Auth failures and crash-loop cool-downs return cleanly from
1022
+ // startLifecycle without throwing, so they end the loop here.
1023
+ scheduleReregistration(options);
1024
+ });
1025
+ }, delaySeconds * 1000);
1026
+ };
1027
+ const extractRegistrationSettings = (configSettings) => {
1028
+ if (!configSettings || typeof configSettings !== 'object')
1029
+ return null;
1030
+ // The server nests settings under its resolved SDK type key; take the first
1031
+ // (only) entry rather than re-deriving our own type client-side.
1032
+ for (const value of Object.values(configSettings)) {
1033
+ if (value && typeof value === 'object')
1034
+ return value;
1035
+ }
1036
+ return null;
1037
+ };
876
1038
  const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
877
1039
  initLogger(config.telemetry);
878
1040
  const logger = getLogger();
879
1041
  setConfig(config);
1042
+ // A fresh (manual or scheduled) start supersedes any pending reconnect timer.
1043
+ clearReregisterTimer();
1044
+ const lifecycleOptions = {
1045
+ config,
1046
+ appUserId,
1047
+ edgeOperatorKey,
1048
+ deviceId: providedDeviceId
1049
+ };
1050
+ // Deterministic preflight validation runs before the crash-loop guard so a
1051
+ // misconfigured integration never consumes a crash-loop attempt (and never
1052
+ // triggers the camera/geo prompts below).
1053
+ if (!edgeOperatorKey) {
1054
+ throw new Error('Missing required header: x-edge-operator-key');
1055
+ }
1056
+ // Break runaway crash/reload loops (e.g. a constrained Telegram WebView that
1057
+ // OOM-crashes during the heavy first-run model load and is reloaded by the
1058
+ // host). If we detect several attempts in a short window that never reached a
1059
+ // stable point, skip heavy init for a cool-down so the app stops refreshing.
1060
+ const guard = beginInitAttempt();
1061
+ if (!guard.allowed) {
1062
+ setStatus('error');
1063
+ logger.warn('Init skipped: crash-loop guard active', {
1064
+ attempts: guard.attempts,
1065
+ cooldownRemainingMs: guard.cooldownRemainingMs
1066
+ });
1067
+ return;
1068
+ }
880
1069
  const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
881
1070
  const isFreshDevice = !providedDeviceId && !storedDeviceId;
882
1071
  const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
883
1072
  if (providedDeviceId) {
884
1073
  setDeviceId(providedDeviceId);
885
1074
  }
1075
+ logger.info('[Init] Starting lifecycle', {
1076
+ sdkVersion: config.sdkVersion,
1077
+ deviceId,
1078
+ isFreshDevice,
1079
+ providedDeviceId: Boolean(providedDeviceId),
1080
+ orchestrator: config.orchestrator?.baseUrl
1081
+ });
886
1082
  const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
887
1083
  const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
888
1084
  setDeviceContext(deviceId, sanitizedDeviceInfo);
889
- if (!edgeOperatorKey) {
890
- throw new Error('Missing required header: x-edge-operator-key');
891
- }
1085
+ logger.info('[Init] Device info collected', {
1086
+ platform: sanitizedDeviceInfo.platform,
1087
+ deviceType: sanitizedDeviceInfo.deviceType,
1088
+ gpuRenderer: sanitizedDeviceInfo.gpuRenderer
1089
+ });
892
1090
  if (rawDeviceInfo.camera?.previewDataUrl) {
893
1091
  try {
894
1092
  window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
@@ -1061,6 +1259,11 @@
1061
1259
  const modelStatuses = {};
1062
1260
  let loadErrorMessage;
1063
1261
  let postRegisterSample;
1262
+ logger.info('[Register] Sending register request', {
1263
+ deviceId,
1264
+ cachedModels: registerPayload.cachedModels,
1265
+ sdkVersion: config.sdkVersion
1266
+ });
1064
1267
  try {
1065
1268
  registerResponse = await registerDevice(config, registerPayload, {
1066
1269
  edgeOperatorKey
@@ -1070,19 +1273,37 @@
1070
1273
  if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
1071
1274
  logger.warn('Register auth failed, stopping lifecycle');
1072
1275
  logFlow('Auth failure; no WS connection', { status: err.status });
1276
+ markInitSuccess(); // Clean exit, not a crash loop.
1073
1277
  return;
1074
1278
  }
1279
+ markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
1075
1280
  throw err;
1076
1281
  }
1077
1282
  logger.info('Register response received:', {
1078
1283
  deviceId: registerResponse.deviceId,
1079
1284
  wsUrl: registerResponse.wsUrl
1080
1285
  });
1286
+ const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
1287
+ setRegistrationSettings(registrationSettings);
1288
+ if (registrationSettings) {
1289
+ logger.info('[Register] Registration settings received', registrationSettings);
1290
+ }
1081
1291
  if (!registerResponse.wsUrl) {
1292
+ markInitSuccess(); // Clean exit, not a crash loop.
1082
1293
  return;
1083
1294
  }
1084
1295
  assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
1085
1296
  const primaryModel = assignedModels[0];
1297
+ logger.info('[Register] Models assigned', {
1298
+ count: assignedModels.length,
1299
+ models: assignedModels.map((m) => ({
1300
+ modelId: m.modelId,
1301
+ framework: m.inferenceFramework,
1302
+ taskType: m.taskType,
1303
+ quantized: m.quantized,
1304
+ sizeBytes: m.sizeBytes
1305
+ }))
1306
+ });
1086
1307
  for (const model of assignedModels) {
1087
1308
  modelStatuses[getModelStatusKey(model)] = 'idle';
1088
1309
  modelInfosByModelId[model.modelId] = model;
@@ -1092,6 +1313,7 @@
1092
1313
  await clearTransformersCaches().catch(() => { });
1093
1314
  clearCachedModelInfo(cachedModelId);
1094
1315
  setCachedModelId(null);
1316
+ markInitSuccess(); // Clean exit (server assigned no model), not a crash loop.
1095
1317
  return;
1096
1318
  }
1097
1319
  setSessionKey(registerResponse.sessionKey);
@@ -1120,11 +1342,31 @@
1120
1342
  if (!factory) {
1121
1343
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1122
1344
  loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
1345
+ logger.error('[Model] No adapter factory for primary model', {
1346
+ modelId: primaryModel.modelId,
1347
+ framework: slmConfig.inferenceFramework,
1348
+ taskType: slmConfig.taskType
1349
+ });
1123
1350
  }
1124
1351
  else {
1352
+ logger.info('[Model] Loading primary model', {
1353
+ modelId: primaryModel.modelId,
1354
+ framework: slmConfig.inferenceFramework,
1355
+ taskType: slmConfig.taskType,
1356
+ quantized: slmConfig.quantized,
1357
+ sizeBytes: primaryModel.sizeBytes,
1358
+ modelRepoId: primaryModel.modelRepoId
1359
+ });
1360
+ const primaryLoadStart = performance.now();
1125
1361
  const loadResult = await factory.load(slmConfig);
1362
+ const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
1126
1363
  loadErrorMessage = loadResult.error?.message;
1127
1364
  if (loadResult.adapter) {
1365
+ logger.info('[Model] Primary model loaded', {
1366
+ modelId: primaryModel.modelId,
1367
+ ms: primaryLoadMs,
1368
+ sizeBytes: loadResult.metrics?.sizeBytes
1369
+ });
1128
1370
  adaptersByModelId[primaryModel.modelId] = loadResult.adapter;
1129
1371
  setAdapter(primaryModel.modelId, loadResult.adapter);
1130
1372
  setCachedModelId(primaryModel.modelId);
@@ -1144,6 +1386,13 @@
1144
1386
  }
1145
1387
  else {
1146
1388
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1389
+ logger.error('[Model] Primary model load failed', {
1390
+ modelId: primaryModel.modelId,
1391
+ framework: slmConfig.inferenceFramework,
1392
+ taskType: slmConfig.taskType,
1393
+ ms: primaryLoadMs,
1394
+ error: loadErrorMessage
1395
+ });
1147
1396
  }
1148
1397
  }
1149
1398
  }
@@ -1233,14 +1482,23 @@
1233
1482
  throw new Error(`primary_model_load_failed:${reason}`);
1234
1483
  }
1235
1484
  if (primaryAdapter && primaryModel.sample?.text) {
1485
+ logger.info('[Sample] Running post-register sample inference', {
1486
+ taskType: primaryModel.taskType
1487
+ });
1236
1488
  postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1237
- logger.info('Post-register sample test result', {
1489
+ const sampleLog = {
1238
1490
  taskType: primaryModel.taskType,
1239
1491
  ok: postRegisterSample.ok,
1240
1492
  error: postRegisterSample.error,
1241
1493
  errorMessage: postRegisterSample.errorMessage,
1242
1494
  processingTimeMs: postRegisterSample.processingTimeMs
1243
- });
1495
+ };
1496
+ if (postRegisterSample.error || !postRegisterSample.ok) {
1497
+ logger.error('[Sample] Post-register sample failed', sampleLog);
1498
+ }
1499
+ else {
1500
+ logger.info('[Sample] Post-register sample ok', sampleLog);
1501
+ }
1244
1502
  if (postRegisterSample.error) {
1245
1503
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1246
1504
  }
@@ -1258,6 +1516,10 @@
1258
1516
  sdkVersion: config.sdkVersion,
1259
1517
  slmConfig: helloSlmConfig
1260
1518
  };
1519
+ logger.info('[WS] Connecting WebSocket', {
1520
+ wsUrl: registerResponse.wsUrl,
1521
+ models: helloSlmConfig
1522
+ });
1261
1523
  const client = new WebSocketClient({
1262
1524
  url: registerResponse.wsUrl,
1263
1525
  hello,
@@ -1267,22 +1529,40 @@
1267
1529
  }
1268
1530
  else if ('type' in message && message.type === 'hello_ack') {
1269
1531
  const ack = message;
1270
- logger.info('Received WS hello_ack', ack);
1532
+ logger.info('[WS] Received hello_ack', ack);
1271
1533
  setStatus(ack.status === 'error' ? 'error' : 'idle');
1272
1534
  }
1273
1535
  else {
1274
- logger.debug('Unhandled WS message', message);
1536
+ logger.debug('[WS] Unhandled message', message);
1275
1537
  }
1276
1538
  },
1277
- onClose: () => {
1539
+ onClose: (event) => {
1540
+ logger.warn('[WS] Connection closed', { code: event.code, reason: event.reason });
1541
+ // Ignore closes from superseded sockets — a newer lifecycle run owns the
1542
+ // connection now.
1543
+ if (getWebSocket() !== client) {
1544
+ return;
1545
+ }
1278
1546
  setStatus('error');
1547
+ scheduleReregistration(lifecycleOptions);
1279
1548
  },
1280
1549
  onError: () => {
1281
- setStatus('error');
1550
+ logger.error('[WS] Connection error');
1551
+ if (getWebSocket() === client) {
1552
+ setStatus('error');
1553
+ }
1282
1554
  }
1283
1555
  });
1284
1556
  setWebSocket(client);
1285
1557
  setStatus('idle');
1558
+ logger.info('[Init] SDK ready', {
1559
+ deviceId,
1560
+ primaryModelId: primaryModel.modelId,
1561
+ taskType: primaryModel.taskType
1562
+ });
1563
+ // Reached a stable point (model loaded, WebSocket connected) — this load was
1564
+ // not a crash loop, so clear the attempt counter.
1565
+ markInitSuccess();
1286
1566
  };
1287
1567
  const normalizeAssignedModels = (slmConfig) => {
1288
1568
  if (!Array.isArray(slmConfig))
@@ -1456,15 +1736,21 @@
1456
1736
  return Promise.resolve();
1457
1737
  }
1458
1738
  if (!transformersRuntimePromise) {
1739
+ const logger = getLogger();
1459
1740
  transformersRuntimePromise = (async () => {
1460
1741
  try {
1461
1742
  const runtimeUrl = TRANSFORMERS_CDN;
1743
+ logger.info('[Runtime] Importing Transformers runtime from CDN', { runtimeUrl });
1744
+ const importStart = performance.now();
1462
1745
  const transformersModule = await import(/* @vite-ignore */ runtimeUrl);
1463
1746
  const pipeline = transformersModule?.pipeline;
1464
1747
  const env = transformersModule?.env;
1465
1748
  if (typeof pipeline !== 'function' || !env) {
1466
1749
  throw new Error('Transformers runtime missing pipeline/env exports');
1467
1750
  }
1751
+ logger.info('[Runtime] Transformers runtime ready', {
1752
+ ms: Math.round(performance.now() - importStart)
1753
+ });
1468
1754
  env.allowLocalModels = true;
1469
1755
  env.allowRemoteModels = true;
1470
1756
  if (env?.backends?.onnx?.env) {