@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.
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const SDK_VERSION = typeof "0.1.3+40f7add" === 'string' && "0.1.3+40f7add".length > 0
4
- ? "0.1.3+40f7add"
3
+ const SDK_VERSION = typeof "0.1.6+9f0db3f" === 'string' && "0.1.6+9f0db3f".length > 0
4
+ ? "0.1.6+9f0db3f"
5
5
  : '0.0.0-dev';
6
6
 
7
7
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -10,6 +10,9 @@ const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' &
10
10
 
11
11
  // The orchestrator URL is baked in at build time per deployment (develop/staging/
12
12
  // production). See ./orchestrator-url for the env-var injection and fallback.
13
+ // Fallback re-registration delay (seconds) after a WebSocket close, used when
14
+ // the register response carried no configSettings for this SDK type.
15
+ const DEFAULT_REREGISTER_INTERVAL_SECONDS = 600;
13
16
  const DEFAULT_CONFIG = {
14
17
  sdkVersion: SDK_VERSION,
15
18
  orchestrator: {
@@ -524,6 +527,9 @@ class WebSocketClient {
524
527
  this.socket.onerror = this.handleError;
525
528
  this.socket.onclose = this.handleClose;
526
529
  }
530
+ isActive() {
531
+ return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
532
+ }
527
533
  send(payload) {
528
534
  this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
529
535
  this.socket.send(JSON.stringify(payload));
@@ -580,6 +586,12 @@ const setSessionKey = (sessionKey) => {
580
586
  const setWebSocket = (ws) => {
581
587
  state.ws = ws;
582
588
  };
589
+ // Safe before full init (unlike getState) — used by the re-registration guard.
590
+ const getWebSocket = () => state.ws;
591
+ const setRegistrationSettings = (settings) => {
592
+ state.registrationSettings = settings ?? null;
593
+ };
594
+ const getRegistrationSettings = () => state.registrationSettings ?? null;
583
595
  const setStatus = (status) => {
584
596
  state.status = status;
585
597
  };
@@ -869,22 +881,208 @@ const clearCachedModelInfo = (modelId) => {
869
881
  safeRemoveItem(CACHED_MODEL_ID_KEY);
870
882
  };
871
883
 
884
+ /**
885
+ * Crash-loop guard for SDK initialization.
886
+ *
887
+ * On a brand-new device the lifecycle synchronously downloads and instantiates a
888
+ * full model (and runs a sample inference) before connecting the WebSocket. In a
889
+ * memory-constrained host such as a Telegram mini-app WebView this burst can
890
+ * crash/OOM the view. The host then reloads the mini-app, the SDK runs the same
891
+ * heavy first-run path again, crashes again, and the app appears to "refresh
892
+ * continuously".
893
+ *
894
+ * Nothing in the previous flow recorded a *failed* attempt: the cache pointer is
895
+ * only written after a fully successful load, so every reload looked like a fresh
896
+ * first run. This guard persists a small attempt counter *before* the heavy work
897
+ * and clears it only once init reaches a stable point. If we see several attempts
898
+ * in a short window that never completed, we assume a crash loop and skip the
899
+ * heavy init for a cool-down period, which breaks the refresh cycle and lets the
900
+ * host app stay up.
901
+ */
902
+ const INIT_STATE_KEY = 'zerogpu_init_state';
903
+ /** Attempts that never completed are only counted within this rolling window. */
904
+ const ATTEMPT_WINDOW_MS = 60000;
905
+ /** Number of uncompleted attempts in the window that trips the cool-down. */
906
+ const MAX_ATTEMPTS_IN_WINDOW = 3;
907
+ /** How long to skip heavy init once a crash loop is detected. */
908
+ const COOLDOWN_MS = 5 * 60000;
909
+ const readState = () => {
910
+ try {
911
+ const raw = window.localStorage.getItem(INIT_STATE_KEY);
912
+ if (!raw)
913
+ return null;
914
+ const parsed = JSON.parse(raw);
915
+ if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
916
+ return null;
917
+ }
918
+ return parsed;
919
+ }
920
+ catch {
921
+ return null;
922
+ }
923
+ };
924
+ const writeState = (state) => {
925
+ try {
926
+ window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
927
+ }
928
+ catch {
929
+ // Storage may be unavailable/partitioned; degrade silently.
930
+ }
931
+ };
932
+ const clearState = () => {
933
+ try {
934
+ window.localStorage.removeItem(INIT_STATE_KEY);
935
+ }
936
+ catch {
937
+ // ignore
938
+ }
939
+ };
940
+ /**
941
+ * Records the start of an init attempt and decides whether heavy init may
942
+ * proceed. Must be called once, before any heavy work, on every lifecycle start.
943
+ */
944
+ const beginInitAttempt = (now = Date.now()) => {
945
+ const state = readState();
946
+ // Still inside an active cool-down from a previously detected crash loop.
947
+ if (state?.cooldownUntil && state.cooldownUntil > now) {
948
+ return {
949
+ allowed: false,
950
+ cooldownRemainingMs: state.cooldownUntil - now,
951
+ attempts: state.attempts
952
+ };
953
+ }
954
+ // No prior state, or the previous window/cool-down has elapsed → start fresh.
955
+ if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
956
+ writeState({ attempts: 1, windowStart: now });
957
+ return { allowed: true, attempts: 1 };
958
+ }
959
+ const attempts = state.attempts + 1;
960
+ // Too many uncompleted attempts in the window → assume a crash loop and back
961
+ // off so the host app stops reloading.
962
+ if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
963
+ writeState({
964
+ attempts,
965
+ windowStart: state.windowStart,
966
+ cooldownUntil: now + COOLDOWN_MS
967
+ });
968
+ return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts };
969
+ }
970
+ writeState({ attempts, windowStart: state.windowStart });
971
+ return { allowed: true, attempts };
972
+ };
973
+ /**
974
+ * Clears crash tracking. Call once init reaches a stable point (e.g. the
975
+ * WebSocket is connected), so successful loads never accumulate toward a trip.
976
+ */
977
+ const markInitSuccess = () => {
978
+ clearState();
979
+ };
980
+
981
+ // Re-registration loop: when the server idle-closes the WebSocket (or it drops
982
+ // for any reason), wait device_timeout_interval_seconds and run the full
983
+ // lifecycle again — re-registering refreshes device metrics and yields a new
984
+ // session key + WS URL. A single pending timer at a time; before reconnecting
985
+ // we check no socket is already live (infinite-loop guard).
986
+ let reregisterTimerId = null;
987
+ const clearReregisterTimer = () => {
988
+ if (reregisterTimerId !== null) {
989
+ clearTimeout(reregisterTimerId);
990
+ reregisterTimerId = null;
991
+ }
992
+ };
993
+ const resolveReregisterDelaySeconds = () => {
994
+ const value = getRegistrationSettings()?.device_timeout_interval_seconds;
995
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
996
+ ? value
997
+ : DEFAULT_REREGISTER_INTERVAL_SECONDS;
998
+ };
999
+ const scheduleReregistration = (options) => {
1000
+ const logger = getLogger();
1001
+ if (reregisterTimerId !== null) {
1002
+ logger.debug('[WS] Re-registration already scheduled; skipping');
1003
+ return;
1004
+ }
1005
+ const delaySeconds = resolveReregisterDelaySeconds();
1006
+ logger.info('[WS] Scheduling re-registration', { delaySeconds });
1007
+ reregisterTimerId = setTimeout(() => {
1008
+ reregisterTimerId = null;
1009
+ if (getWebSocket()?.isActive()) {
1010
+ logger.info('[WS] Active WebSocket present; skipping re-registration');
1011
+ return;
1012
+ }
1013
+ logger.info('[WS] Re-registration timer fired; restarting lifecycle');
1014
+ startLifecycle(options).catch((err) => {
1015
+ logger.error('[WS] Re-registration attempt failed; will retry', err);
1016
+ // Keep the loop alive on transient failures (register/network/model
1017
+ // errors). Auth failures and crash-loop cool-downs return cleanly from
1018
+ // startLifecycle without throwing, so they end the loop here.
1019
+ scheduleReregistration(options);
1020
+ });
1021
+ }, delaySeconds * 1000);
1022
+ };
1023
+ const extractRegistrationSettings = (configSettings) => {
1024
+ if (!configSettings || typeof configSettings !== 'object')
1025
+ return null;
1026
+ // The server nests settings under its resolved SDK type key; take the first
1027
+ // (only) entry rather than re-deriving our own type client-side.
1028
+ for (const value of Object.values(configSettings)) {
1029
+ if (value && typeof value === 'object')
1030
+ return value;
1031
+ }
1032
+ return null;
1033
+ };
872
1034
  const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
873
1035
  initLogger(config.telemetry);
874
1036
  const logger = getLogger();
875
1037
  setConfig(config);
1038
+ // A fresh (manual or scheduled) start supersedes any pending reconnect timer.
1039
+ clearReregisterTimer();
1040
+ const lifecycleOptions = {
1041
+ config,
1042
+ appUserId,
1043
+ edgeOperatorKey,
1044
+ deviceId: providedDeviceId
1045
+ };
1046
+ // Deterministic preflight validation runs before the crash-loop guard so a
1047
+ // misconfigured integration never consumes a crash-loop attempt (and never
1048
+ // triggers the camera/geo prompts below).
1049
+ if (!edgeOperatorKey) {
1050
+ throw new Error('Missing required header: x-edge-operator-key');
1051
+ }
1052
+ // Break runaway crash/reload loops (e.g. a constrained Telegram WebView that
1053
+ // OOM-crashes during the heavy first-run model load and is reloaded by the
1054
+ // host). If we detect several attempts in a short window that never reached a
1055
+ // stable point, skip heavy init for a cool-down so the app stops refreshing.
1056
+ const guard = beginInitAttempt();
1057
+ if (!guard.allowed) {
1058
+ setStatus('error');
1059
+ logger.warn('Init skipped: crash-loop guard active', {
1060
+ attempts: guard.attempts,
1061
+ cooldownRemainingMs: guard.cooldownRemainingMs
1062
+ });
1063
+ return;
1064
+ }
876
1065
  const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
877
1066
  const isFreshDevice = !providedDeviceId && !storedDeviceId;
878
1067
  const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
879
1068
  if (providedDeviceId) {
880
1069
  setDeviceId(providedDeviceId);
881
1070
  }
1071
+ logger.info('[Init] Starting lifecycle', {
1072
+ sdkVersion: config.sdkVersion,
1073
+ deviceId,
1074
+ isFreshDevice,
1075
+ providedDeviceId: Boolean(providedDeviceId),
1076
+ orchestrator: config.orchestrator?.baseUrl
1077
+ });
882
1078
  const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
883
1079
  const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
884
1080
  setDeviceContext(deviceId, sanitizedDeviceInfo);
885
- if (!edgeOperatorKey) {
886
- throw new Error('Missing required header: x-edge-operator-key');
887
- }
1081
+ logger.info('[Init] Device info collected', {
1082
+ platform: sanitizedDeviceInfo.platform,
1083
+ deviceType: sanitizedDeviceInfo.deviceType,
1084
+ gpuRenderer: sanitizedDeviceInfo.gpuRenderer
1085
+ });
888
1086
  if (rawDeviceInfo.camera?.previewDataUrl) {
889
1087
  try {
890
1088
  window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
@@ -1057,6 +1255,11 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1057
1255
  const modelStatuses = {};
1058
1256
  let loadErrorMessage;
1059
1257
  let postRegisterSample;
1258
+ logger.info('[Register] Sending register request', {
1259
+ deviceId,
1260
+ cachedModels: registerPayload.cachedModels,
1261
+ sdkVersion: config.sdkVersion
1262
+ });
1060
1263
  try {
1061
1264
  registerResponse = await registerDevice(config, registerPayload, {
1062
1265
  edgeOperatorKey
@@ -1066,19 +1269,37 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1066
1269
  if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
1067
1270
  logger.warn('Register auth failed, stopping lifecycle');
1068
1271
  logFlow('Auth failure; no WS connection', { status: err.status });
1272
+ markInitSuccess(); // Clean exit, not a crash loop.
1069
1273
  return;
1070
1274
  }
1275
+ markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
1071
1276
  throw err;
1072
1277
  }
1073
1278
  logger.info('Register response received:', {
1074
1279
  deviceId: registerResponse.deviceId,
1075
1280
  wsUrl: registerResponse.wsUrl
1076
1281
  });
1282
+ const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
1283
+ setRegistrationSettings(registrationSettings);
1284
+ if (registrationSettings) {
1285
+ logger.info('[Register] Registration settings received', registrationSettings);
1286
+ }
1077
1287
  if (!registerResponse.wsUrl) {
1288
+ markInitSuccess(); // Clean exit, not a crash loop.
1078
1289
  return;
1079
1290
  }
1080
1291
  assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
1081
1292
  const primaryModel = assignedModels[0];
1293
+ logger.info('[Register] Models assigned', {
1294
+ count: assignedModels.length,
1295
+ models: assignedModels.map((m) => ({
1296
+ modelId: m.modelId,
1297
+ framework: m.inferenceFramework,
1298
+ taskType: m.taskType,
1299
+ quantized: m.quantized,
1300
+ sizeBytes: m.sizeBytes
1301
+ }))
1302
+ });
1082
1303
  for (const model of assignedModels) {
1083
1304
  modelStatuses[getModelStatusKey(model)] = 'idle';
1084
1305
  modelInfosByModelId[model.modelId] = model;
@@ -1088,6 +1309,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1088
1309
  await clearTransformersCaches().catch(() => { });
1089
1310
  clearCachedModelInfo(cachedModelId);
1090
1311
  setCachedModelId(null);
1312
+ markInitSuccess(); // Clean exit (server assigned no model), not a crash loop.
1091
1313
  return;
1092
1314
  }
1093
1315
  setSessionKey(registerResponse.sessionKey);
@@ -1116,11 +1338,31 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1116
1338
  if (!factory) {
1117
1339
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1118
1340
  loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
1341
+ logger.error('[Model] No adapter factory for primary model', {
1342
+ modelId: primaryModel.modelId,
1343
+ framework: slmConfig.inferenceFramework,
1344
+ taskType: slmConfig.taskType
1345
+ });
1119
1346
  }
1120
1347
  else {
1348
+ logger.info('[Model] Loading primary model', {
1349
+ modelId: primaryModel.modelId,
1350
+ framework: slmConfig.inferenceFramework,
1351
+ taskType: slmConfig.taskType,
1352
+ quantized: slmConfig.quantized,
1353
+ sizeBytes: primaryModel.sizeBytes,
1354
+ modelRepoId: primaryModel.modelRepoId
1355
+ });
1356
+ const primaryLoadStart = performance.now();
1121
1357
  const loadResult = await factory.load(slmConfig);
1358
+ const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
1122
1359
  loadErrorMessage = loadResult.error?.message;
1123
1360
  if (loadResult.adapter) {
1361
+ logger.info('[Model] Primary model loaded', {
1362
+ modelId: primaryModel.modelId,
1363
+ ms: primaryLoadMs,
1364
+ sizeBytes: loadResult.metrics?.sizeBytes
1365
+ });
1124
1366
  adaptersByModelId[primaryModel.modelId] = loadResult.adapter;
1125
1367
  setAdapter(primaryModel.modelId, loadResult.adapter);
1126
1368
  setCachedModelId(primaryModel.modelId);
@@ -1140,6 +1382,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1140
1382
  }
1141
1383
  else {
1142
1384
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1385
+ logger.error('[Model] Primary model load failed', {
1386
+ modelId: primaryModel.modelId,
1387
+ framework: slmConfig.inferenceFramework,
1388
+ taskType: slmConfig.taskType,
1389
+ ms: primaryLoadMs,
1390
+ error: loadErrorMessage
1391
+ });
1143
1392
  }
1144
1393
  }
1145
1394
  }
@@ -1229,14 +1478,23 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1229
1478
  throw new Error(`primary_model_load_failed:${reason}`);
1230
1479
  }
1231
1480
  if (primaryAdapter && primaryModel.sample?.text) {
1481
+ logger.info('[Sample] Running post-register sample inference', {
1482
+ taskType: primaryModel.taskType
1483
+ });
1232
1484
  postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1233
- logger.info('Post-register sample test result', {
1485
+ const sampleLog = {
1234
1486
  taskType: primaryModel.taskType,
1235
1487
  ok: postRegisterSample.ok,
1236
1488
  error: postRegisterSample.error,
1237
1489
  errorMessage: postRegisterSample.errorMessage,
1238
1490
  processingTimeMs: postRegisterSample.processingTimeMs
1239
- });
1491
+ };
1492
+ if (postRegisterSample.error || !postRegisterSample.ok) {
1493
+ logger.error('[Sample] Post-register sample failed', sampleLog);
1494
+ }
1495
+ else {
1496
+ logger.info('[Sample] Post-register sample ok', sampleLog);
1497
+ }
1240
1498
  if (postRegisterSample.error) {
1241
1499
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1242
1500
  }
@@ -1254,6 +1512,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1254
1512
  sdkVersion: config.sdkVersion,
1255
1513
  slmConfig: helloSlmConfig
1256
1514
  };
1515
+ logger.info('[WS] Connecting WebSocket', {
1516
+ wsUrl: registerResponse.wsUrl,
1517
+ models: helloSlmConfig
1518
+ });
1257
1519
  const client = new WebSocketClient({
1258
1520
  url: registerResponse.wsUrl,
1259
1521
  hello,
@@ -1263,22 +1525,40 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1263
1525
  }
1264
1526
  else if ('type' in message && message.type === 'hello_ack') {
1265
1527
  const ack = message;
1266
- logger.info('Received WS hello_ack', ack);
1528
+ logger.info('[WS] Received hello_ack', ack);
1267
1529
  setStatus(ack.status === 'error' ? 'error' : 'idle');
1268
1530
  }
1269
1531
  else {
1270
- logger.debug('Unhandled WS message', message);
1532
+ logger.debug('[WS] Unhandled message', message);
1271
1533
  }
1272
1534
  },
1273
- onClose: () => {
1535
+ onClose: (event) => {
1536
+ logger.warn('[WS] Connection closed', { code: event.code, reason: event.reason });
1537
+ // Ignore closes from superseded sockets — a newer lifecycle run owns the
1538
+ // connection now.
1539
+ if (getWebSocket() !== client) {
1540
+ return;
1541
+ }
1274
1542
  setStatus('error');
1543
+ scheduleReregistration(lifecycleOptions);
1275
1544
  },
1276
1545
  onError: () => {
1277
- setStatus('error');
1546
+ logger.error('[WS] Connection error');
1547
+ if (getWebSocket() === client) {
1548
+ setStatus('error');
1549
+ }
1278
1550
  }
1279
1551
  });
1280
1552
  setWebSocket(client);
1281
1553
  setStatus('idle');
1554
+ logger.info('[Init] SDK ready', {
1555
+ deviceId,
1556
+ primaryModelId: primaryModel.modelId,
1557
+ taskType: primaryModel.taskType
1558
+ });
1559
+ // Reached a stable point (model loaded, WebSocket connected) — this load was
1560
+ // not a crash loop, so clear the attempt counter.
1561
+ markInitSuccess();
1282
1562
  };
1283
1563
  const normalizeAssignedModels = (slmConfig) => {
1284
1564
  if (!Array.isArray(slmConfig))
@@ -1452,15 +1732,21 @@ const ensureTransformersRuntime = () => {
1452
1732
  return Promise.resolve();
1453
1733
  }
1454
1734
  if (!transformersRuntimePromise) {
1735
+ const logger = getLogger();
1455
1736
  transformersRuntimePromise = (async () => {
1456
1737
  try {
1457
1738
  const runtimeUrl = TRANSFORMERS_CDN;
1739
+ logger.info('[Runtime] Importing Transformers runtime from CDN', { runtimeUrl });
1740
+ const importStart = performance.now();
1458
1741
  const transformersModule = await import(/* @vite-ignore */ runtimeUrl);
1459
1742
  const pipeline = transformersModule?.pipeline;
1460
1743
  const env = transformersModule?.env;
1461
1744
  if (typeof pipeline !== 'function' || !env) {
1462
1745
  throw new Error('Transformers runtime missing pipeline/env exports');
1463
1746
  }
1747
+ logger.info('[Runtime] Transformers runtime ready', {
1748
+ ms: Math.round(performance.now() - importStart)
1749
+ });
1464
1750
  env.allowLocalModels = true;
1465
1751
  env.allowRemoteModels = true;
1466
1752
  if (env?.backends?.onnx?.env) {