@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,5 +1,5 @@
1
1
  {
2
- "sdkVersion": "0.1.3+40f7add",
2
+ "sdkVersion": "0.1.6+9f0db3f",
3
3
  "transformersVersion": "2.17.2",
4
4
  "wllamaVersion": "2.3.5",
5
5
  "files": [
@@ -13,5 +13,5 @@
13
13
  "wllama/single-thread/wllama.wasm",
14
14
  "wllama/multi-thread/wllama.wasm"
15
15
  ],
16
- "builtAt": "2026-06-26T12:10:20.173Z"
16
+ "builtAt": "2026-07-03T02:08:19.009Z"
17
17
  }
@@ -1,5 +1,5 @@
1
- const SDK_VERSION = typeof "0.1.3+40f7add" === 'string' && "0.1.3+40f7add".length > 0
2
- ? "0.1.3+40f7add"
1
+ const SDK_VERSION = typeof "0.1.6+9f0db3f" === 'string' && "0.1.6+9f0db3f".length > 0
2
+ ? "0.1.6+9f0db3f"
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
@@ -8,6 +8,9 @@ const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' &
8
8
 
9
9
  // The orchestrator URL is baked in at build time per deployment (develop/staging/
10
10
  // production). See ./orchestrator-url for the env-var injection and fallback.
11
+ // Fallback re-registration delay (seconds) after a WebSocket close, used when
12
+ // the register response carried no configSettings for this SDK type.
13
+ const DEFAULT_REREGISTER_INTERVAL_SECONDS = 600;
11
14
  const DEFAULT_CONFIG = {
12
15
  sdkVersion: SDK_VERSION,
13
16
  orchestrator: {
@@ -522,6 +525,9 @@ class WebSocketClient {
522
525
  this.socket.onerror = this.handleError;
523
526
  this.socket.onclose = this.handleClose;
524
527
  }
528
+ isActive() {
529
+ return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
530
+ }
525
531
  send(payload) {
526
532
  this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
527
533
  this.socket.send(JSON.stringify(payload));
@@ -578,6 +584,12 @@ const setSessionKey = (sessionKey) => {
578
584
  const setWebSocket = (ws) => {
579
585
  state.ws = ws;
580
586
  };
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;
591
+ };
592
+ const getRegistrationSettings = () => state.registrationSettings ?? null;
581
593
  const setStatus = (status) => {
582
594
  state.status = status;
583
595
  };
@@ -867,22 +879,208 @@ const clearCachedModelInfo = (modelId) => {
867
879
  safeRemoveItem(CACHED_MODEL_ID_KEY);
868
880
  };
869
881
 
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 = () => {
908
+ 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') {
914
+ return null;
915
+ }
916
+ return parsed;
917
+ }
918
+ catch {
919
+ return null;
920
+ }
921
+ };
922
+ const writeState = (state) => {
923
+ try {
924
+ window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
925
+ }
926
+ 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 };
967
+ }
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
+ };
978
+
979
+ // Re-registration loop: when the server idle-closes the WebSocket (or it drops
980
+ // for any reason), wait device_timeout_interval_seconds and run the full
981
+ // 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
+ };
991
+ const resolveReregisterDelaySeconds = () => {
992
+ const value = getRegistrationSettings()?.device_timeout_interval_seconds;
993
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
994
+ ? value
995
+ : DEFAULT_REREGISTER_INTERVAL_SECONDS;
996
+ };
997
+ const scheduleReregistration = (options) => {
998
+ const logger = getLogger();
999
+ if (reregisterTimerId !== null) {
1000
+ logger.debug('[WS] Re-registration already scheduled; skipping');
1001
+ return;
1002
+ }
1003
+ const delaySeconds = resolveReregisterDelaySeconds();
1004
+ logger.info('[WS] Scheduling re-registration', { delaySeconds });
1005
+ reregisterTimerId = setTimeout(() => {
1006
+ reregisterTimerId = null;
1007
+ if (getWebSocket()?.isActive()) {
1008
+ logger.info('[WS] Active WebSocket present; skipping re-registration');
1009
+ return;
1010
+ }
1011
+ logger.info('[WS] Re-registration timer fired; restarting lifecycle');
1012
+ startLifecycle(options).catch((err) => {
1013
+ logger.error('[WS] Re-registration attempt failed; will retry', err);
1014
+ // Keep the loop alive on transient failures (register/network/model
1015
+ // errors). Auth failures and crash-loop cool-downs return cleanly from
1016
+ // startLifecycle without throwing, so they end the loop here.
1017
+ scheduleReregistration(options);
1018
+ });
1019
+ }, delaySeconds * 1000);
1020
+ };
1021
+ const extractRegistrationSettings = (configSettings) => {
1022
+ if (!configSettings || typeof configSettings !== 'object')
1023
+ return null;
1024
+ // The server nests settings under its resolved SDK type key; take the first
1025
+ // (only) entry rather than re-deriving our own type client-side.
1026
+ for (const value of Object.values(configSettings)) {
1027
+ if (value && typeof value === 'object')
1028
+ return value;
1029
+ }
1030
+ return null;
1031
+ };
870
1032
  const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
871
1033
  initLogger(config.telemetry);
872
1034
  const logger = getLogger();
873
1035
  setConfig(config);
1036
+ // A fresh (manual or scheduled) start supersedes any pending reconnect timer.
1037
+ clearReregisterTimer();
1038
+ const lifecycleOptions = {
1039
+ config,
1040
+ appUserId,
1041
+ edgeOperatorKey,
1042
+ deviceId: providedDeviceId
1043
+ };
1044
+ // Deterministic preflight validation runs before the crash-loop guard so a
1045
+ // misconfigured integration never consumes a crash-loop attempt (and never
1046
+ // triggers the camera/geo prompts below).
1047
+ if (!edgeOperatorKey) {
1048
+ throw new Error('Missing required header: x-edge-operator-key');
1049
+ }
1050
+ // Break runaway crash/reload loops (e.g. a constrained Telegram WebView that
1051
+ // OOM-crashes during the heavy first-run model load and is reloaded by the
1052
+ // host). If we detect several attempts in a short window that never reached a
1053
+ // stable point, skip heavy init for a cool-down so the app stops refreshing.
1054
+ const guard = beginInitAttempt();
1055
+ if (!guard.allowed) {
1056
+ setStatus('error');
1057
+ logger.warn('Init skipped: crash-loop guard active', {
1058
+ attempts: guard.attempts,
1059
+ cooldownRemainingMs: guard.cooldownRemainingMs
1060
+ });
1061
+ return;
1062
+ }
874
1063
  const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
875
1064
  const isFreshDevice = !providedDeviceId && !storedDeviceId;
876
1065
  const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
877
1066
  if (providedDeviceId) {
878
1067
  setDeviceId(providedDeviceId);
879
1068
  }
1069
+ logger.info('[Init] Starting lifecycle', {
1070
+ sdkVersion: config.sdkVersion,
1071
+ deviceId,
1072
+ isFreshDevice,
1073
+ providedDeviceId: Boolean(providedDeviceId),
1074
+ orchestrator: config.orchestrator?.baseUrl
1075
+ });
880
1076
  const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
881
1077
  const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
882
1078
  setDeviceContext(deviceId, sanitizedDeviceInfo);
883
- if (!edgeOperatorKey) {
884
- throw new Error('Missing required header: x-edge-operator-key');
885
- }
1079
+ logger.info('[Init] Device info collected', {
1080
+ platform: sanitizedDeviceInfo.platform,
1081
+ deviceType: sanitizedDeviceInfo.deviceType,
1082
+ gpuRenderer: sanitizedDeviceInfo.gpuRenderer
1083
+ });
886
1084
  if (rawDeviceInfo.camera?.previewDataUrl) {
887
1085
  try {
888
1086
  window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
@@ -1055,6 +1253,11 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1055
1253
  const modelStatuses = {};
1056
1254
  let loadErrorMessage;
1057
1255
  let postRegisterSample;
1256
+ logger.info('[Register] Sending register request', {
1257
+ deviceId,
1258
+ cachedModels: registerPayload.cachedModels,
1259
+ sdkVersion: config.sdkVersion
1260
+ });
1058
1261
  try {
1059
1262
  registerResponse = await registerDevice(config, registerPayload, {
1060
1263
  edgeOperatorKey
@@ -1064,19 +1267,37 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1064
1267
  if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
1065
1268
  logger.warn('Register auth failed, stopping lifecycle');
1066
1269
  logFlow('Auth failure; no WS connection', { status: err.status });
1270
+ markInitSuccess(); // Clean exit, not a crash loop.
1067
1271
  return;
1068
1272
  }
1273
+ markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
1069
1274
  throw err;
1070
1275
  }
1071
1276
  logger.info('Register response received:', {
1072
1277
  deviceId: registerResponse.deviceId,
1073
1278
  wsUrl: registerResponse.wsUrl
1074
1279
  });
1280
+ const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
1281
+ setRegistrationSettings(registrationSettings);
1282
+ if (registrationSettings) {
1283
+ logger.info('[Register] Registration settings received', registrationSettings);
1284
+ }
1075
1285
  if (!registerResponse.wsUrl) {
1286
+ markInitSuccess(); // Clean exit, not a crash loop.
1076
1287
  return;
1077
1288
  }
1078
1289
  assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
1079
1290
  const primaryModel = assignedModels[0];
1291
+ logger.info('[Register] Models assigned', {
1292
+ count: assignedModels.length,
1293
+ models: assignedModels.map((m) => ({
1294
+ modelId: m.modelId,
1295
+ framework: m.inferenceFramework,
1296
+ taskType: m.taskType,
1297
+ quantized: m.quantized,
1298
+ sizeBytes: m.sizeBytes
1299
+ }))
1300
+ });
1080
1301
  for (const model of assignedModels) {
1081
1302
  modelStatuses[getModelStatusKey(model)] = 'idle';
1082
1303
  modelInfosByModelId[model.modelId] = model;
@@ -1086,6 +1307,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1086
1307
  await clearTransformersCaches().catch(() => { });
1087
1308
  clearCachedModelInfo(cachedModelId);
1088
1309
  setCachedModelId(null);
1310
+ markInitSuccess(); // Clean exit (server assigned no model), not a crash loop.
1089
1311
  return;
1090
1312
  }
1091
1313
  setSessionKey(registerResponse.sessionKey);
@@ -1114,11 +1336,31 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1114
1336
  if (!factory) {
1115
1337
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1116
1338
  loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
1339
+ logger.error('[Model] No adapter factory for primary model', {
1340
+ modelId: primaryModel.modelId,
1341
+ framework: slmConfig.inferenceFramework,
1342
+ taskType: slmConfig.taskType
1343
+ });
1117
1344
  }
1118
1345
  else {
1346
+ logger.info('[Model] Loading primary model', {
1347
+ modelId: primaryModel.modelId,
1348
+ framework: slmConfig.inferenceFramework,
1349
+ taskType: slmConfig.taskType,
1350
+ quantized: slmConfig.quantized,
1351
+ sizeBytes: primaryModel.sizeBytes,
1352
+ modelRepoId: primaryModel.modelRepoId
1353
+ });
1354
+ const primaryLoadStart = performance.now();
1119
1355
  const loadResult = await factory.load(slmConfig);
1356
+ const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
1120
1357
  loadErrorMessage = loadResult.error?.message;
1121
1358
  if (loadResult.adapter) {
1359
+ logger.info('[Model] Primary model loaded', {
1360
+ modelId: primaryModel.modelId,
1361
+ ms: primaryLoadMs,
1362
+ sizeBytes: loadResult.metrics?.sizeBytes
1363
+ });
1122
1364
  adaptersByModelId[primaryModel.modelId] = loadResult.adapter;
1123
1365
  setAdapter(primaryModel.modelId, loadResult.adapter);
1124
1366
  setCachedModelId(primaryModel.modelId);
@@ -1138,6 +1380,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1138
1380
  }
1139
1381
  else {
1140
1382
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1383
+ logger.error('[Model] Primary model load failed', {
1384
+ modelId: primaryModel.modelId,
1385
+ framework: slmConfig.inferenceFramework,
1386
+ taskType: slmConfig.taskType,
1387
+ ms: primaryLoadMs,
1388
+ error: loadErrorMessage
1389
+ });
1141
1390
  }
1142
1391
  }
1143
1392
  }
@@ -1227,14 +1476,23 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1227
1476
  throw new Error(`primary_model_load_failed:${reason}`);
1228
1477
  }
1229
1478
  if (primaryAdapter && primaryModel.sample?.text) {
1479
+ logger.info('[Sample] Running post-register sample inference', {
1480
+ taskType: primaryModel.taskType
1481
+ });
1230
1482
  postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1231
- logger.info('Post-register sample test result', {
1483
+ const sampleLog = {
1232
1484
  taskType: primaryModel.taskType,
1233
1485
  ok: postRegisterSample.ok,
1234
1486
  error: postRegisterSample.error,
1235
1487
  errorMessage: postRegisterSample.errorMessage,
1236
1488
  processingTimeMs: postRegisterSample.processingTimeMs
1237
- });
1489
+ };
1490
+ if (postRegisterSample.error || !postRegisterSample.ok) {
1491
+ logger.error('[Sample] Post-register sample failed', sampleLog);
1492
+ }
1493
+ else {
1494
+ logger.info('[Sample] Post-register sample ok', sampleLog);
1495
+ }
1238
1496
  if (postRegisterSample.error) {
1239
1497
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1240
1498
  }
@@ -1252,6 +1510,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1252
1510
  sdkVersion: config.sdkVersion,
1253
1511
  slmConfig: helloSlmConfig
1254
1512
  };
1513
+ logger.info('[WS] Connecting WebSocket', {
1514
+ wsUrl: registerResponse.wsUrl,
1515
+ models: helloSlmConfig
1516
+ });
1255
1517
  const client = new WebSocketClient({
1256
1518
  url: registerResponse.wsUrl,
1257
1519
  hello,
@@ -1261,22 +1523,40 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1261
1523
  }
1262
1524
  else if ('type' in message && message.type === 'hello_ack') {
1263
1525
  const ack = message;
1264
- logger.info('Received WS hello_ack', ack);
1526
+ logger.info('[WS] Received hello_ack', ack);
1265
1527
  setStatus(ack.status === 'error' ? 'error' : 'idle');
1266
1528
  }
1267
1529
  else {
1268
- logger.debug('Unhandled WS message', message);
1530
+ logger.debug('[WS] Unhandled message', message);
1269
1531
  }
1270
1532
  },
1271
- onClose: () => {
1533
+ onClose: (event) => {
1534
+ logger.warn('[WS] Connection closed', { code: event.code, reason: event.reason });
1535
+ // Ignore closes from superseded sockets — a newer lifecycle run owns the
1536
+ // connection now.
1537
+ if (getWebSocket() !== client) {
1538
+ return;
1539
+ }
1272
1540
  setStatus('error');
1541
+ scheduleReregistration(lifecycleOptions);
1273
1542
  },
1274
1543
  onError: () => {
1275
- setStatus('error');
1544
+ logger.error('[WS] Connection error');
1545
+ if (getWebSocket() === client) {
1546
+ setStatus('error');
1547
+ }
1276
1548
  }
1277
1549
  });
1278
1550
  setWebSocket(client);
1279
1551
  setStatus('idle');
1552
+ logger.info('[Init] SDK ready', {
1553
+ deviceId,
1554
+ primaryModelId: primaryModel.modelId,
1555
+ taskType: primaryModel.taskType
1556
+ });
1557
+ // Reached a stable point (model loaded, WebSocket connected) — this load was
1558
+ // not a crash loop, so clear the attempt counter.
1559
+ markInitSuccess();
1280
1560
  };
1281
1561
  const normalizeAssignedModels = (slmConfig) => {
1282
1562
  if (!Array.isArray(slmConfig))
@@ -1450,15 +1730,21 @@ const ensureTransformersRuntime = () => {
1450
1730
  return Promise.resolve();
1451
1731
  }
1452
1732
  if (!transformersRuntimePromise) {
1733
+ const logger = getLogger();
1453
1734
  transformersRuntimePromise = (async () => {
1454
1735
  try {
1455
1736
  const runtimeUrl = TRANSFORMERS_CDN;
1737
+ logger.info('[Runtime] Importing Transformers runtime from CDN', { runtimeUrl });
1738
+ const importStart = performance.now();
1456
1739
  const transformersModule = await import(/* @vite-ignore */ runtimeUrl);
1457
1740
  const pipeline = transformersModule?.pipeline;
1458
1741
  const env = transformersModule?.env;
1459
1742
  if (typeof pipeline !== 'function' || !env) {
1460
1743
  throw new Error('Transformers runtime missing pipeline/env exports');
1461
1744
  }
1745
+ logger.info('[Runtime] Transformers runtime ready', {
1746
+ ms: Math.round(performance.now() - importStart)
1747
+ });
1462
1748
  env.allowLocalModels = true;
1463
1749
  env.allowRemoteModels = true;
1464
1750
  if (env?.backends?.onnx?.env) {
@@ -2757,6 +3043,23 @@ const resolveAssetsBaseUrl = (explicit) => {
2757
3043
  }
2758
3044
  return 'vendor/zerogpu/';
2759
3045
  };
3046
+ /**
3047
+ * Silence the bundled model runtimes' informational and warning console output so
3048
+ * the extension's Errors panel surfaces only genuine errors. `console.error` (and
3049
+ * uncaught exceptions) are left intact. Applied only when console logs are disabled
3050
+ * — pass `enableConsoleLogs: true` to keep full verbosity while debugging.
3051
+ */
3052
+ const silenceNonErrorConsole = () => {
3053
+ const flag = window;
3054
+ if (flag.__zgpuConsoleSilenced)
3055
+ return;
3056
+ flag.__zgpuConsoleSilenced = true;
3057
+ const noop = () => { };
3058
+ console.log = noop;
3059
+ console.info = noop;
3060
+ console.debug = noop;
3061
+ console.warn = noop;
3062
+ };
2760
3063
  /** Load the local transformers.js build and expose it via the SDK's globals. */
2761
3064
  const loadTransformersRuntime = async (assetsBaseUrl) => {
2762
3065
  if (window.TransformersPipeline)
@@ -2822,6 +3125,10 @@ const buildOverrides = (options) => {
2822
3125
  */
2823
3126
  const initZeroGpuOffscreen = async (options = {}) => {
2824
3127
  const assetsBaseUrl = resolveAssetsBaseUrl(options.assetsBaseUrl);
3128
+ // Errors-only console unless the host opts into verbose logs.
3129
+ if (!options.enableConsoleLogs) {
3130
+ silenceNonErrorConsole();
3131
+ }
2825
3132
  await loadTransformersRuntime(assetsBaseUrl);
2826
3133
  try {
2827
3134
  await loadWllamaRuntime(assetsBaseUrl);