@zerogpu/browser-extension-sdk 0.2.0 → 0.2.1-dev.202608031041.g7fab469

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.2.0+12c5b00" === 'string' && "0.2.0+12c5b00".length > 0
8
- ? "0.2.0+12c5b00"
7
+ const SDK_VERSION = typeof "0.2.1-dev.202608031041.g7fab469+7fab469" === 'string' && "0.2.1-dev.202608031041.g7fab469+7fab469".length > 0
8
+ ? "0.2.1-dev.202608031041.g7fab469+7fab469"
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
@@ -52,7 +52,11 @@
52
52
  };
53
53
  const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
54
54
  const deepMerge = (target, source) => {
55
- const result = Array.isArray(target) ? [...target] : { ...target };
55
+ // Structural clone first, then index it as a plain bag. `T extends object`
56
+ // admits interfaces without index signatures (SdkConfig is one), so the cast
57
+ // is what lets us walk it by key — the `as T` on the way out restores the
58
+ // caller's type, which the per-field validators below re-check anyway.
59
+ const result = (Array.isArray(target) ? [...target] : { ...target });
56
60
  for (const key of Object.keys(source)) {
57
61
  const srcValue = source[key];
58
62
  if (srcValue === undefined)
@@ -150,9 +154,27 @@
150
154
  setStoredDeviceId(deviceId);
151
155
  };
152
156
 
157
+ /**
158
+ * Typed accessors for the non-standard browser surfaces this SDK reads.
159
+ *
160
+ * None of these are in TypeScript's DOM lib: the Telegram Mini App bridge is
161
+ * injected by the host, and `userAgentData` / `deviceMemory` / `getBattery` /
162
+ * `connection` are all optional vendor extensions that may be absent on any
163
+ * given engine. Declaring them here once — rather than casting to `any` at each
164
+ * read — keeps the optionality visible at the call site, which matters because
165
+ * every one of these fields feeds a guardrail decision.
166
+ */
167
+ const extendedNavigator = () => navigator;
168
+ /** The injected Telegram bridge, or undefined when not running inside a Mini App. */
169
+ const telegramWebApp = () => {
170
+ if (typeof window === 'undefined')
171
+ return undefined;
172
+ return window.Telegram?.WebApp;
173
+ };
174
+
153
175
  const getPlatform = () => {
154
176
  const ua = navigator.userAgent.toLowerCase();
155
- const tg = window.Telegram?.WebApp;
177
+ const tg = telegramWebApp();
156
178
  if (tg?.platform)
157
179
  return tg.platform;
158
180
  if (tg)
@@ -169,7 +191,7 @@
169
191
  };
170
192
  const getDeviceType = () => {
171
193
  const ua = navigator.userAgent ?? '';
172
- const uaData = navigator.userAgentData;
194
+ const uaData = extendedNavigator().userAgentData;
173
195
  if (uaData?.mobile === true)
174
196
  return 'mobile';
175
197
  const isTablet = /iPad|Tablet|PlayBook|Silk/i.test(ua) || (navigator.maxTouchPoints > 1 && window.innerWidth >= 768);
@@ -194,8 +216,9 @@
194
216
  };
195
217
  const getBatteryInfo = async () => {
196
218
  try {
197
- if ('getBattery' in navigator) {
198
- const battery = await navigator.getBattery();
219
+ const getBattery = extendedNavigator().getBattery;
220
+ if (getBattery) {
221
+ const battery = await getBattery.call(navigator);
199
222
  return {
200
223
  level: battery.level,
201
224
  charging: battery.charging
@@ -208,7 +231,8 @@
208
231
  return undefined;
209
232
  };
210
233
  const getNetworkInfo = () => {
211
- const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
234
+ const nav = extendedNavigator();
235
+ const conn = nav.connection || nav.mozConnection || nav.webkitConnection;
212
236
  if (conn) {
213
237
  return {
214
238
  type: conn.effectiveType || 'unknown',
@@ -252,7 +276,7 @@
252
276
  }
253
277
  };
254
278
  const getTelegramUser = () => {
255
- const tg = window.Telegram?.WebApp;
279
+ const tg = telegramWebApp();
256
280
  const user = tg?.initDataUnsafe?.user;
257
281
  if (user) {
258
282
  return user;
@@ -269,7 +293,7 @@
269
293
  try {
270
294
  if (typeof window === 'undefined')
271
295
  return false;
272
- if (window.Telegram?.WebApp)
296
+ if (telegramWebApp())
273
297
  return true;
274
298
  return (window.location?.hash || '').includes('tgWebAppData');
275
299
  }
@@ -279,7 +303,7 @@
279
303
  };
280
304
  const collectDeviceInfo = async (config, appUserId, sdkDeviceId) => {
281
305
  const screen = window.screen || { width: null, height: null };
282
- const tg = window.Telegram?.WebApp;
306
+ const tg = telegramWebApp();
283
307
  const telegramUser = getTelegramUser();
284
308
  const telegramFullName = telegramUser?.first_name || telegramUser?.last_name
285
309
  ? [telegramUser?.first_name, telegramUser?.last_name].filter(Boolean).join(' ')
@@ -305,7 +329,7 @@
305
329
  themeParams: tg?.themeParams,
306
330
  // Hardware
307
331
  cpuCores: navigator.hardwareConcurrency || 1,
308
- memoryGb: navigator.deviceMemory,
332
+ memoryGb: extendedNavigator().deviceMemory,
309
333
  gpuRenderer: getWebGLRenderer(),
310
334
  webglFingerprint: getWebGLRenderer(), // Using renderer as simple fingerprint for now
311
335
  screen: {
@@ -508,6 +532,7 @@
508
532
  constructor(options) {
509
533
  this.options = options;
510
534
  this.logger = getLogger();
535
+ this.pingTimer = null;
511
536
  this.consoleWithVerbose = console;
512
537
  this.handleOpen = () => {
513
538
  this.logger.info('WebSocket connection opened');
@@ -515,6 +540,8 @@
515
540
  this.logger.debug('Sending hello message:', this.options.hello);
516
541
  this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
517
542
  this.send(this.options.hello);
543
+ // Keepalive starts only once the hello is on the wire.
544
+ this.startPing();
518
545
  if (this.options.ack) {
519
546
  // Send readiness/error ack immediately after hello.
520
547
  this.logger.info('[WS OUT] hello_ack:', JSON.stringify(this.options.ack));
@@ -531,8 +558,20 @@
531
558
  }
532
559
  };
533
560
  this.handleMessage = (event) => {
561
+ const raw = event.data;
562
+ // Bare-text control frames (the DO answers our keepalive `ping` with
563
+ // `pong`) are not JSON and must neither throw nor spam error logs.
564
+ if (typeof raw === 'string') {
565
+ const trimmed = raw.trim();
566
+ if (trimmed === 'pong')
567
+ return;
568
+ if (trimmed.length > 0 && trimmed[0] !== '{' && trimmed[0] !== '[') {
569
+ this.logger.debug('[WS IN] ignoring non-JSON frame:', trimmed.slice(0, 64));
570
+ return;
571
+ }
572
+ }
534
573
  try {
535
- const data = JSON.parse(event.data);
574
+ const data = JSON.parse(raw);
536
575
  if (this.logger.isEnabled()) {
537
576
  if (typeof this.consoleWithVerbose.verbose === 'function') {
538
577
  this.consoleWithVerbose.verbose('[ZeroGPU]', '[WS IN] payload:', data);
@@ -548,6 +587,7 @@
548
587
  }
549
588
  };
550
589
  this.handleError = (event) => {
590
+ this.stopPing();
551
591
  const ws = event.target;
552
592
  this.logger.error('WebSocket error', {
553
593
  url: ws.url,
@@ -557,6 +597,7 @@
557
597
  this.options.onError(event);
558
598
  };
559
599
  this.handleClose = (event) => {
600
+ this.stopPing();
560
601
  const ws = event.target;
561
602
  this.logger.warn('WebSocket closed', {
562
603
  url: ws.url,
@@ -566,6 +607,7 @@
566
607
  });
567
608
  this.options.onClose(event);
568
609
  };
610
+ this.pingIntervalMs = normalizePingIntervalMs(options.pingIntervalSeconds);
569
611
  this.logger.info('Creating WebSocket connection to:', options.url);
570
612
  this.socket = new WebSocket(options.url);
571
613
  this.socket.onopen = this.handleOpen;
@@ -573,6 +615,49 @@
573
615
  this.socket.onerror = this.handleError;
574
616
  this.socket.onclose = this.handleClose;
575
617
  }
618
+ /**
619
+ * Live retune (e.g. a `policy_update` mid-session): restarts the keepalive
620
+ * timer at the new cadence while the socket is open; 0/invalid stops it.
621
+ */
622
+ setPingIntervalSeconds(seconds) {
623
+ this.pingIntervalMs = normalizePingIntervalMs(seconds);
624
+ if (this.socket.readyState === WebSocket.OPEN) {
625
+ this.startPing();
626
+ }
627
+ else {
628
+ this.stopPing();
629
+ }
630
+ }
631
+ startPing() {
632
+ this.stopPing();
633
+ if (this.pingIntervalMs <= 0)
634
+ return;
635
+ this.pingTimer = setInterval(() => {
636
+ if (this.socket.readyState !== WebSocket.OPEN) {
637
+ this.stopPing();
638
+ return;
639
+ }
640
+ try {
641
+ // Literal text frame, not JSON — the DO's bare-`ping` fast path.
642
+ this.socket.send('ping');
643
+ }
644
+ catch (error) {
645
+ this.logger.debug('Keepalive ping failed', error);
646
+ }
647
+ try {
648
+ this.options.onPingTick?.();
649
+ }
650
+ catch {
651
+ // A piggybacked check must never break the keepalive loop.
652
+ }
653
+ }, this.pingIntervalMs);
654
+ }
655
+ stopPing() {
656
+ if (this.pingTimer !== null) {
657
+ clearInterval(this.pingTimer);
658
+ this.pingTimer = null;
659
+ }
660
+ }
576
661
  isActive() {
577
662
  return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
578
663
  }
@@ -581,6 +666,7 @@
581
666
  this.socket.send(JSON.stringify(payload));
582
667
  }
583
668
  close(code, reason) {
669
+ this.stopPing();
584
670
  if (typeof code === 'number') {
585
671
  // Close reasons are capped at 123 bytes by the WS protocol.
586
672
  this.socket.close(code, (reason ?? '').slice(0, 120));
@@ -590,6 +676,9 @@
590
676
  }
591
677
  }
592
678
  }
679
+ const normalizePingIntervalMs = (seconds) => typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0
680
+ ? Math.round(seconds * 1000)
681
+ : 0;
593
682
 
594
683
  const state = { status: 'idle' };
595
684
  const setConfig = (config) => {
@@ -1954,6 +2043,189 @@
1954
2043
  }
1955
2044
  };
1956
2045
 
2046
+ /**
2047
+ * Server-driven connection policy — the `connection` block of
2048
+ * `configSettings.<sdkType>` (device-registry docs/CONNECTION_POLICY_DESIGN.md §2).
2049
+ *
2050
+ * Same philosophy as the guardrails contract (runtime/guardrails.ts): lenient
2051
+ * parse, every numeric field individually validated and CLAMPED into a safe
2052
+ * range, absent/invalid fields fall back to built-in defaults — never to
2053
+ * "check disabled" and never to the raw served value. A typo of
2054
+ * `"ping_interval_seconds": 1` must not make 50 000 devices ping every second.
2055
+ *
2056
+ * When no `connection` block is served at all (`served: false`), the SDK keeps
2057
+ * its exact legacy behavior: no keepalive ping, no staleness safety net, and
2058
+ * the flat `device_timeout_interval_seconds`-or-600 s re-register delay.
2059
+ * Rollout is therefore pure opt-in via settings data.
2060
+ */
2061
+ // ---- defaults + clamp ranges (design §2, client-side law) ------------------
2062
+ const CONNECTION_POLICY_DEFAULTS = {
2063
+ pingIntervalSeconds: 30,
2064
+ strategy: 'exponential',
2065
+ initialDelayMs: 1000,
2066
+ multiplier: 2.0,
2067
+ maxDelayMs: 30000,
2068
+ jitterMs: 500,
2069
+ giveUpAfterAttempts: 0,
2070
+ maxStalenessSeconds: 86400,
2071
+ onRefusalRetrySeconds: 600,
2072
+ onAuthFailure: 'stop',
2073
+ idleTimeoutSeconds: 0
2074
+ };
2075
+ const CONNECTION_POLICY_CLAMPS = {
2076
+ pingIntervalSeconds: { min: 15, max: 120 },
2077
+ initialDelayMs: { min: 250, max: 60000 },
2078
+ multiplier: { min: 1.0, max: 4.0 },
2079
+ maxDelayMs: { min: 5000, max: 3600000 },
2080
+ jitterMs: { min: 0, max: 30000 },
2081
+ maxStalenessSeconds: { min: 3600, max: 604800 },
2082
+ onRefusalRetrySeconds: { min: 60, max: 86400 }
2083
+ };
2084
+ /** Cap on a served `reregister` directive's `delay_jitter_ms`; invalid → 60 s. */
2085
+ const DEFAULT_REREGISTER_DIRECTIVE_JITTER_MS = 60000;
2086
+ const MAX_REREGISTER_DIRECTIVE_JITTER_MS = 3600000;
2087
+ const finiteNumber = (value) => typeof value === 'number' && Number.isFinite(value) ? value : undefined;
2088
+ /** Positive-and-clamped, else default (verbatim guardrails semantics). */
2089
+ const clampPositive = (value, range, fallback) => {
2090
+ const num = finiteNumber(value);
2091
+ if (num === undefined || num <= 0)
2092
+ return fallback;
2093
+ return Math.min(Math.max(num, range.min), range.max);
2094
+ };
2095
+ /**
2096
+ * Jitter's range deliberately starts at 0: a served 0 means "no jitter" and is
2097
+ * honored (it is inside the documented 0..30000 range); only negative/absent/
2098
+ * invalid values fall back to the default.
2099
+ */
2100
+ const clampNonNegative = (value, range, fallback) => {
2101
+ const num = finiteNumber(value);
2102
+ if (num === undefined || num < 0)
2103
+ return fallback;
2104
+ return Math.min(Math.max(num, range.min), range.max);
2105
+ };
2106
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
2107
+ /**
2108
+ * Pure resolver: raw served `connection` block (or anything at all) →
2109
+ * fully-defaulted, fully-clamped policy. Unknown fields are ignored.
2110
+ */
2111
+ const resolveConnectionPolicy = (raw) => {
2112
+ const served = isRecord(raw);
2113
+ const block = served ? raw : {};
2114
+ const keepAlive = isRecord(block.keep_alive) ? block.keep_alive : {};
2115
+ const reconnect = isRecord(block.reconnect) ? block.reconnect : {};
2116
+ const reregister = isRecord(block.reregister) ? block.reregister : {};
2117
+ const socket = isRecord(block.socket) ? block.socket : {};
2118
+ const giveUpRaw = finiteNumber(reconnect.give_up_after_attempts);
2119
+ return {
2120
+ served,
2121
+ keepAlive: {
2122
+ pingIntervalSeconds: clampPositive(keepAlive.ping_interval_seconds, CONNECTION_POLICY_CLAMPS.pingIntervalSeconds, CONNECTION_POLICY_DEFAULTS.pingIntervalSeconds)
2123
+ },
2124
+ reconnect: {
2125
+ strategy: reconnect.strategy === 'fixed' ? 'fixed' : CONNECTION_POLICY_DEFAULTS.strategy,
2126
+ initialDelayMs: clampPositive(reconnect.initial_delay_ms, CONNECTION_POLICY_CLAMPS.initialDelayMs, CONNECTION_POLICY_DEFAULTS.initialDelayMs),
2127
+ multiplier: clampPositive(reconnect.multiplier, CONNECTION_POLICY_CLAMPS.multiplier, CONNECTION_POLICY_DEFAULTS.multiplier),
2128
+ maxDelayMs: clampPositive(reconnect.max_delay_ms, CONNECTION_POLICY_CLAMPS.maxDelayMs, CONNECTION_POLICY_DEFAULTS.maxDelayMs),
2129
+ jitterMs: clampNonNegative(reconnect.jitter_ms, CONNECTION_POLICY_CLAMPS.jitterMs, CONNECTION_POLICY_DEFAULTS.jitterMs),
2130
+ // 0 = never give up; negative/fractional/invalid → default (0).
2131
+ giveUpAfterAttempts: giveUpRaw !== undefined && giveUpRaw >= 0 && Number.isInteger(giveUpRaw)
2132
+ ? giveUpRaw
2133
+ : CONNECTION_POLICY_DEFAULTS.giveUpAfterAttempts
2134
+ },
2135
+ reregister: {
2136
+ maxStalenessSeconds: clampPositive(reregister.max_staleness_seconds, CONNECTION_POLICY_CLAMPS.maxStalenessSeconds, CONNECTION_POLICY_DEFAULTS.maxStalenessSeconds),
2137
+ onRefusalRetrySeconds: clampPositive(reregister.on_refusal_retry_seconds, CONNECTION_POLICY_CLAMPS.onRefusalRetrySeconds, CONNECTION_POLICY_DEFAULTS.onRefusalRetrySeconds),
2138
+ onAuthFailure: reregister.on_auth_failure === 'retry_slow'
2139
+ ? 'retry_slow'
2140
+ : CONNECTION_POLICY_DEFAULTS.onAuthFailure
2141
+ },
2142
+ socket: {
2143
+ // Echo only (0 = server never idle-closes); the SDK never self-closes.
2144
+ idleTimeoutSeconds: clampNonNegative(socket.idle_timeout_seconds, { min: 0, max: Number.MAX_SAFE_INTEGER }, CONNECTION_POLICY_DEFAULTS.idleTimeoutSeconds)
2145
+ }
2146
+ };
2147
+ };
2148
+ /**
2149
+ * Reconnect delay for the given zero-based attempt:
2150
+ * min(initial × multiplier^attempt, max) + uniform(0..jitter).
2151
+ * `fixed` strategy pins the base at initialDelayMs (still capped + jittered).
2152
+ * Math.pow overflow to Infinity is absorbed by the min() cap.
2153
+ */
2154
+ const computeReconnectDelayMs = (reconnect, attempt, random = Math.random) => {
2155
+ const safeAttempt = Number.isFinite(attempt) && attempt > 0 ? attempt : 0;
2156
+ const base = reconnect.strategy === 'fixed'
2157
+ ? reconnect.initialDelayMs
2158
+ : reconnect.initialDelayMs * Math.pow(reconnect.multiplier, safeAttempt);
2159
+ const capped = Math.min(base, reconnect.maxDelayMs);
2160
+ const jitter = reconnect.jitterMs > 0 ? random() * reconnect.jitterMs : 0;
2161
+ return Math.round(capped + jitter);
2162
+ };
2163
+ /** Flat retry (refusal / auth retry_slow) with the mandatory uniform jitter. */
2164
+ const computeRetryDelayMs = (retrySeconds, jitterMs, random = Math.random) => Math.round(retrySeconds * 1000 + (jitterMs > 0 ? random() * jitterMs : 0));
2165
+ /**
2166
+ * Delay for a server `reregister` directive: uniform(0..delay_jitter_ms),
2167
+ * defaulting the cap to 60 s when absent/invalid so a fleet-wide push never
2168
+ * becomes a register stampede. The cap itself is bounded at one hour.
2169
+ */
2170
+ const computeReregisterDirectiveDelayMs = (delayJitterMs, random = Math.random) => {
2171
+ const num = finiteNumber(delayJitterMs);
2172
+ const cap = num !== undefined && num >= 0
2173
+ ? Math.min(num, MAX_REREGISTER_DIRECTIVE_JITTER_MS)
2174
+ : DEFAULT_REREGISTER_DIRECTIVE_JITTER_MS;
2175
+ return Math.round(random() * cap);
2176
+ };
2177
+ /**
2178
+ * Flattened field-level diff between two resolved policies — feeds the
2179
+ * `changed` list for logging (and, once available in the shared vocabulary,
2180
+ * the `ws.policy_applied` event payload).
2181
+ */
2182
+ const diffConnectionPolicies = (before, after) => {
2183
+ const changed = [];
2184
+ const walk = (a, b, path) => {
2185
+ if (isRecord(a) && isRecord(b)) {
2186
+ for (const key of Object.keys(b))
2187
+ walk(a[key], b[key], path ? `${path}.${key}` : key);
2188
+ return;
2189
+ }
2190
+ if (a !== b)
2191
+ changed.push(path);
2192
+ };
2193
+ walk(before, after, '');
2194
+ return changed;
2195
+ };
2196
+
2197
+ let active = resolveConnectionPolicy(undefined);
2198
+ let reconnectAttempt = 0;
2199
+ let lastRegisterSuccessAt = null;
2200
+ /** Resolve (clamp/default) a served `connection` block and make it active. */
2201
+ const applyConnectionPolicy = (raw, source) => {
2202
+ const next = resolveConnectionPolicy(raw);
2203
+ const changed = diffConnectionPolicies(active, next);
2204
+ active = next;
2205
+ return { policy: next, source, changed };
2206
+ };
2207
+ const getConnectionPolicy = () => active;
2208
+ /** Zero-based attempt index for the next reconnect being scheduled. */
2209
+ const getReconnectAttempt = () => reconnectAttempt;
2210
+ const bumpReconnectAttempt = () => {
2211
+ reconnectAttempt += 1;
2212
+ };
2213
+ /** A successful register+connect resets the backoff curve. */
2214
+ const resetReconnectAttempts = () => {
2215
+ reconnectAttempt = 0;
2216
+ };
2217
+ const markRegisterSuccess = (now = Date.now()) => {
2218
+ lastRegisterSuccessAt = now;
2219
+ };
2220
+ /**
2221
+ * Safety net only (design §2): true when a policy was served and more than
2222
+ * `max_staleness_seconds` has passed since the last successful register.
2223
+ * With no served policy there is no net — exactly the shipped behavior.
2224
+ */
2225
+ const isRegistrationStale = (now = Date.now()) => active.served &&
2226
+ lastRegisterSuccessAt !== null &&
2227
+ now - lastRegisterSuccessAt > active.reregister.maxStalenessSeconds * 1000;
2228
+
1957
2229
  const DB_NAME = 'zerogpu-slm-cache';
1958
2230
  const STORE_NAME = 'models';
1959
2231
  const DB_VERSION = 1;
@@ -2189,18 +2461,23 @@
2189
2461
  sample.processingTimeMs > latencyBudgetMs);
2190
2462
  }
2191
2463
  // Re-registration loop: when the server idle-closes the WebSocket (or it drops
2192
- // for any reason), wait device_timeout_interval_seconds and run the full
2193
- // lifecycle again — re-registering refreshes device metrics and yields a new
2194
- // session key + WS URL. The single pending timer lives in ./reregister so the
2195
- // shutdown sequence can kill it (§4.7); before reconnecting we check no socket
2196
- // is already live (infinite-loop guard).
2464
+ // for any reason), schedule the full lifecycle again — re-registering
2465
+ // refreshes device metrics and yields a new session key + WS URL. The delay is
2466
+ // policy-driven when the server served a `connection` block (exponential
2467
+ // backoff + jitter for closes, flat-but-jittered retry for refusals); with no
2468
+ // served block it stays the legacy flat device_timeout_interval_seconds-or-600s
2469
+ // wait. The single pending timer lives in ./reregister so the shutdown
2470
+ // sequence can kill it (§4.7); before reconnecting we check no socket is
2471
+ // already live (infinite-loop guard). The crash-loop guard keeps outranking
2472
+ // any policy: beginInitAttempt() inside startLifecycle refuses the attempt and
2473
+ // returns cleanly, ending the loop, no matter how fast the policy retries.
2197
2474
  const resolveReregisterDelaySeconds = () => {
2198
2475
  const value = getRegistrationSettings()?.device_timeout_interval_seconds;
2199
2476
  return typeof value === 'number' && Number.isFinite(value) && value > 0
2200
2477
  ? value
2201
2478
  : DEFAULT_REREGISTER_INTERVAL_SECONDS;
2202
2479
  };
2203
- const scheduleReregistration = (options) => {
2480
+ const scheduleReconnect = (options, reason) => {
2204
2481
  const logger = getLogger();
2205
2482
  if (hasReregisterTimer()) {
2206
2483
  logger.debug('[WS] Re-registration already scheduled; skipping');
@@ -2210,8 +2487,35 @@
2210
2487
  logger.debug('[WS] SDK is shut down; not scheduling re-registration');
2211
2488
  return;
2212
2489
  }
2213
- const delaySeconds = resolveReregisterDelaySeconds();
2214
- logger.info('[WS] Scheduling re-registration', { delaySeconds });
2490
+ const policy = getConnectionPolicy();
2491
+ let delayMs;
2492
+ let attempt;
2493
+ if (!policy.served) {
2494
+ // Legacy path, byte-for-byte: flat interval, no jitter, for every reason.
2495
+ delayMs = resolveReregisterDelaySeconds() * 1000;
2496
+ }
2497
+ else if (reason === 'socket_closed') {
2498
+ attempt = getReconnectAttempt();
2499
+ const giveUpAfter = policy.reconnect.giveUpAfterAttempts;
2500
+ if (giveUpAfter > 0 && attempt >= giveUpAfter) {
2501
+ logger.warn('[WS] Reconnect give-up threshold reached; not rescheduling', {
2502
+ attempt,
2503
+ giveUpAfter
2504
+ });
2505
+ return;
2506
+ }
2507
+ delayMs = computeReconnectDelayMs(policy.reconnect, attempt);
2508
+ bumpReconnectAttempt();
2509
+ }
2510
+ else {
2511
+ delayMs = computeRetryDelayMs(policy.reregister.onRefusalRetrySeconds, policy.reconnect.jitterMs);
2512
+ }
2513
+ getEventReporter().report('ws.reconnect_scheduled', {
2514
+ code: reason,
2515
+ durationMs: delayMs,
2516
+ data: attempt !== undefined ? { attempt } : undefined
2517
+ });
2518
+ logger.info('[WS] Scheduling re-registration', { reason, delayMs, attempt });
2215
2519
  setReregisterTimer(() => {
2216
2520
  if (getWebSocket()?.isActive()) {
2217
2521
  logger.info('[WS] Active WebSocket present; skipping re-registration');
@@ -2223,9 +2527,33 @@
2223
2527
  // Keep the loop alive on transient failures (register/network/model
2224
2528
  // errors). Auth failures and crash-loop cool-downs return cleanly from
2225
2529
  // startLifecycle without throwing, so they end the loop here.
2226
- scheduleReregistration(options);
2530
+ scheduleReconnect(options, reason);
2227
2531
  });
2228
- }, delaySeconds * 1000);
2532
+ }, delayMs);
2533
+ };
2534
+ // Full lifecycle restart while a socket may still be live (server `reregister`
2535
+ // directive or the max_staleness safety net). The current socket is superseded
2536
+ // *before* closing so its onClose does not also schedule a backoff reconnect
2537
+ // for a restart we are performing on purpose.
2538
+ const triggerFullReregister = (options, reason) => {
2539
+ const logger = getLogger();
2540
+ if (isShutdown()) {
2541
+ logger.debug('[WS] SDK is shut down; ignoring re-register trigger');
2542
+ return;
2543
+ }
2544
+ logger.info('[WS] Running full re-register', { reason });
2545
+ const ws = getWebSocket();
2546
+ setWebSocket(undefined);
2547
+ try {
2548
+ ws?.close(1000, reason);
2549
+ }
2550
+ catch {
2551
+ // Best effort — the register flow below supersedes the session anyway.
2552
+ }
2553
+ startLifecycle(options).catch((err) => {
2554
+ logger.error('[WS] Full re-register failed; scheduling retry', err);
2555
+ scheduleReconnect(options, 'socket_closed');
2556
+ });
2229
2557
  };
2230
2558
  const extractRegistrationSettings = (configSettings) => {
2231
2559
  if (!configSettings || typeof configSettings !== 'object')
@@ -2523,11 +2851,20 @@
2523
2851
  }
2524
2852
  catch (err) {
2525
2853
  if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
2526
- logger.warn('Register auth failed, stopping lifecycle');
2527
2854
  logFlow('Auth failure; no WS connection', { status: err.status });
2528
2855
  reporter.report('register.failed', { code: 'auth' });
2529
2856
  reporter.report('sdk.init_failed', { code: 'auth' });
2530
2857
  markInitSuccess(); // Clean exit, not a crash loop.
2858
+ // Policy-driven auth handling: "stop" (default, the shipped behavior) =
2859
+ // cease until the host restarts the SDK; "retry_slow" = come back on the
2860
+ // refusal-retry cadence.
2861
+ if (getConnectionPolicy().reregister.onAuthFailure === 'retry_slow') {
2862
+ logger.warn('Register auth failed; policy says retry_slow');
2863
+ scheduleReconnect(lifecycleOptions, 'auth_failure');
2864
+ }
2865
+ else {
2866
+ logger.warn('Register auth failed, stopping lifecycle');
2867
+ }
2531
2868
  return;
2532
2869
  }
2533
2870
  reporter.report('register.failed', { code: mapRegisterErrorCode(err), message: err.message });
@@ -2540,6 +2877,18 @@
2540
2877
  const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
2541
2878
  setRegistrationSettings(registrationSettings);
2542
2879
  applyRegistrationGuardrails(registrationSettings);
2880
+ // Connection policy applies on every outcome too — the server may tune retry
2881
+ // cadence even while refusing (design §2.1). Clamped + defaulted; an absent
2882
+ // block resolves to `served: false`, which keeps every legacy path.
2883
+ const appliedPolicy = applyConnectionPolicy(registrationSettings?.connection, 'register');
2884
+ if (appliedPolicy.changed.length > 0) {
2885
+ logger.info('[Register] Connection policy applied', {
2886
+ source: appliedPolicy.source,
2887
+ changed: appliedPolicy.changed
2888
+ });
2889
+ }
2890
+ // TODO(global-types): emit ws.policy_applied once available in the shared
2891
+ // event vocabulary (data: {source: 'register', v, changed}).
2543
2892
  if (registrationSettings) {
2544
2893
  logger.info('[Register] Registration settings received', registrationSettings);
2545
2894
  }
@@ -2554,10 +2903,11 @@
2554
2903
  setStatus('error');
2555
2904
  setLifecycleStatus('error');
2556
2905
  markInitSuccess(); // Clean exit, not a crash loop.
2557
- scheduleReregistration(lifecycleOptions);
2906
+ scheduleReconnect(lifecycleOptions, 'refusal');
2558
2907
  return;
2559
2908
  }
2560
2909
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
2910
+ markRegisterSuccess();
2561
2911
  reporter.setSessionKey(registerResponse.sessionKey);
2562
2912
  logger.info('Register response received:', {
2563
2913
  deviceId: registerResponse.deviceId,
@@ -2881,9 +3231,27 @@
2881
3231
  models: helloSlmConfig
2882
3232
  });
2883
3233
  reporter.report('ws.connect_started');
3234
+ const connectionPolicy = getConnectionPolicy();
2884
3235
  const client = new WebSocketClient({
2885
3236
  url: registerResponse.wsUrl,
2886
3237
  hello,
3238
+ // App-level keepalive only when the server served a policy (legacy = no
3239
+ // heartbeat at all). The DO answers the bare-text `ping` with `pong` and
3240
+ // refreshes lastSeen, keeping idle browser devices dispatchable.
3241
+ pingIntervalSeconds: connectionPolicy.served
3242
+ ? connectionPolicy.keepAlive.pingIntervalSeconds
3243
+ : 0,
3244
+ onPingTick: () => {
3245
+ // max_staleness safety net, piggybacked on the keepalive tick: a lost
3246
+ // `reregister` push (DO restart, dropped message) must not strand this
3247
+ // device on stale config forever.
3248
+ if (isShutdown() || getWebSocket() !== client)
3249
+ return;
3250
+ if (isRegistrationStale()) {
3251
+ logger.warn('[WS] Registration exceeded max_staleness; refreshing');
3252
+ triggerFullReregister(lifecycleOptions, 'max_staleness');
3253
+ }
3254
+ },
2887
3255
  onOpen: () => reporter.report('ws.connected'),
2888
3256
  onMessage: (message) => {
2889
3257
  if ('requests' in message && Array.isArray(message.requests)) {
@@ -2898,6 +3266,41 @@
2898
3266
  });
2899
3267
  setStatus(ack.status === 'error' ? 'error' : 'idle');
2900
3268
  }
3269
+ else if ('type' in message && message.type === 'policy_update') {
3270
+ // Mid-session policy push — same clamps and precedence as the
3271
+ // register-time block; applied atomically (one resolved object swap +
3272
+ // a live ping-timer retune). Unknown fields are ignored by the
3273
+ // resolver.
3274
+ const update = message;
3275
+ const applied = applyConnectionPolicy(update.connection, 'ws');
3276
+ if (getWebSocket() === client) {
3277
+ client.setPingIntervalSeconds(applied.policy.served ? applied.policy.keepAlive.pingIntervalSeconds : 0);
3278
+ }
3279
+ logger.info('[WS] Connection policy updated', {
3280
+ source: applied.source,
3281
+ v: update.v,
3282
+ changed: applied.changed
3283
+ });
3284
+ // TODO(global-types): emit ws.policy_applied once available in the
3285
+ // shared event vocabulary (data: {source: 'ws', v, changed}).
3286
+ }
3287
+ else if ('type' in message && message.type === 'reregister') {
3288
+ // Server-initiated refresh: wait uniform(0..delay_jitter_ms) so a
3289
+ // fleet-wide push doesn't become a register stampede, then run the
3290
+ // full lifecycle restart. Uses the single re-register timer so
3291
+ // shutdown clears it.
3292
+ const directive = message;
3293
+ if (isShutdown() || getWebSocket() !== client)
3294
+ return;
3295
+ const delayMs = computeReregisterDirectiveDelayMs(directive.delay_jitter_ms);
3296
+ const reason = typeof directive.reason === 'string' && directive.reason.length > 0
3297
+ ? `reregister:${directive.reason}`
3298
+ : 'reregister';
3299
+ logger.info('[WS] Server requested re-register', { reason, delayMs });
3300
+ setReregisterTimer(() => {
3301
+ triggerFullReregister(lifecycleOptions, reason);
3302
+ }, delayMs);
3303
+ }
2901
3304
  else {
2902
3305
  logger.debug('[WS] Unhandled message', message);
2903
3306
  }
@@ -2914,7 +3317,7 @@
2914
3317
  data: { wasClean: event.wasClean }
2915
3318
  });
2916
3319
  setStatus('error');
2917
- scheduleReregistration(lifecycleOptions);
3320
+ scheduleReconnect(lifecycleOptions, 'socket_closed');
2918
3321
  },
2919
3322
  onError: () => {
2920
3323
  logger.error('[WS] Connection error');
@@ -2937,7 +3340,9 @@
2937
3340
  taskType: primaryModel.taskType
2938
3341
  });
2939
3342
  // Reached a stable point (model loaded, WebSocket connected) — this load was
2940
- // not a crash loop, so clear the attempt counter.
3343
+ // not a crash loop, so clear the attempt counter. A successful
3344
+ // register+connect also resets the reconnect backoff curve.
3345
+ resetReconnectAttempts();
2941
3346
  markInitSuccess();
2942
3347
  };
2943
3348
  const mapCacheInvalidCode = (errorMessage) => {
@@ -3206,7 +3611,7 @@
3206
3611
  }
3207
3612
  catch (error) {
3208
3613
  transformersRuntimePromise = null;
3209
- console.error('[ZeroGPU][SLM] Failed to import Transformers runtime', {
3614
+ logger.error('[SLM] Failed to import Transformers runtime', {
3210
3615
  runtimeUrl: TRANSFORMERS_CDN,
3211
3616
  error: serializeError$5(error)
3212
3617
  });
@@ -3316,7 +3721,7 @@
3316
3721
  }
3317
3722
  }
3318
3723
  if (sawNonWasmPayloadAtBase) {
3319
- console.warn('[ZeroGPU][SLM] ONNX wasm probe got non-wasm payload', {
3724
+ getLogger().warn('[SLM] ONNX wasm probe got non-wasm payload', {
3320
3725
  wasmBase: baseWithSlash
3321
3726
  });
3322
3727
  }
@@ -3447,7 +3852,7 @@
3447
3852
  return await originalFetch(url, init);
3448
3853
  }
3449
3854
  catch (error) {
3450
- console.error('[ZeroGPU][SLM][fetch] non-model wasm/ort request failed', {
3855
+ logger.error('[SLM][fetch] non-model wasm/ort request failed', {
3451
3856
  modelId,
3452
3857
  requestUrl: originalRequestUrl,
3453
3858
  error: serializeError$4(error)
@@ -3498,7 +3903,19 @@
3498
3903
  return new Response('required_file_not_found', { status: 404, statusText: 'Not Found' });
3499
3904
  }
3500
3905
  catch (err) {
3501
- logger.warn(`[ZeroGPU] Failed to fetch ${relative}:`, err);
3906
+ // NOTE: this 502 is synthesised HERE — no gateway was involved. The
3907
+ // caller (transformers.js) reports it against the URL *it* built, which
3908
+ // still carries the huggingface.co prefix this fetch was installed to
3909
+ // replace, so the resulting message reads
3910
+ // "Bad gateway ... https://huggingface.co/https://models.zerogpu.ai/...".
3911
+ // That string means "every candidate URL threw", i.e. a network/abort
3912
+ // failure against the real model host — not an upstream 502 and not a
3913
+ // malformed URL actually being requested.
3914
+ logger.warn(`[SLM] Model file fetch failed for ${relative}`, {
3915
+ modelId,
3916
+ candidates: requestUrls,
3917
+ error: serializeError$4(err)
3918
+ });
3502
3919
  return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
3503
3920
  }
3504
3921
  };
@@ -3879,9 +4296,9 @@
3879
4296
  catch (error) {
3880
4297
  const message = error instanceof Error ? error.message : String(error);
3881
4298
  if (message.includes("Unexpected token '<'")) {
3882
- console.error('[ZeroGPU][SLM][loadOnnxAdapter] Parse error suggests HTML returned where JSON expected', { modelId: slm.modelId, modelUrl: slm.modelUrl });
4299
+ logger.error('[SLM][loadOnnxAdapter] Parse error suggests HTML returned where JSON expected', { modelId: slm.modelId, modelUrl: slm.modelUrl });
3883
4300
  }
3884
- console.error('[ZeroGPU][SLM][loadOnnxAdapter] failed', {
4301
+ logger.error('[SLM][loadOnnxAdapter] failed', {
3885
4302
  modelId: slm.modelId,
3886
4303
  modelVersion: slm.modelVersion,
3887
4304
  modelRepoId: slm.modelRepoId,
@@ -3889,7 +4306,6 @@
3889
4306
  requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
3890
4307
  error: serializeError$3(error)
3891
4308
  });
3892
- logger.error('ONNX adapter load failed', error);
3893
4309
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
3894
4310
  return { error: error, metrics: {} };
3895
4311
  }
@@ -4172,14 +4588,13 @@
4172
4588
  return { adapter, metrics };
4173
4589
  }
4174
4590
  catch (error) {
4175
- console.error('[ZeroGPU][Transformers][load] failed', {
4591
+ logger.error('Transformers adapter load failed', {
4176
4592
  modelId: slm.modelId,
4177
4593
  modelVersion: slm.modelVersion,
4178
4594
  modelRepoId: slm.modelRepoId,
4179
4595
  modelUrl: slm.modelUrl,
4180
4596
  error: serializeError$2(error)
4181
4597
  });
4182
- logger.error('Transformers adapter load failed', error);
4183
4598
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4184
4599
  return { error: error, metrics: {} };
4185
4600
  }
@@ -4219,7 +4634,7 @@
4219
4634
  }
4220
4635
  catch (error) {
4221
4636
  wllamaRuntimePromise = null;
4222
- console.error('[ZeroGPU][GGUF] Failed to import wllama runtime', {
4637
+ getLogger().error('[GGUF] Failed to import wllama runtime', {
4223
4638
  runtimeUrl: WLLAMA_CDN,
4224
4639
  error: serializeError$1(error)
4225
4640
  });
@@ -4438,13 +4853,12 @@
4438
4853
  return { adapter, metrics };
4439
4854
  }
4440
4855
  catch (error) {
4441
- console.error('[ZeroGPU][GGUF][load] failed', {
4856
+ logger.error('GGUF adapter load failed', {
4442
4857
  modelId: slm.modelId,
4443
4858
  modelVersion: slm.modelVersion,
4444
4859
  modelUrl: slm.modelUrl,
4445
4860
  error: serializeError(error)
4446
4861
  });
4447
- logger.error('GGUF adapter load failed', error);
4448
4862
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4449
4863
  return { error: error, metrics: {} };
4450
4864
  }
@@ -4616,7 +5030,13 @@
4616
5030
  options.overrides = { telemetry };
4617
5031
  }
4618
5032
  void initZeroGpuSdk(options).catch((error) => {
4619
- console.error('[ZeroGpuSdk] Auto-init failed', error);
5033
+ // The logger singleton may not exist yet when init fails before config
5034
+ // resolution, so honour the script-tag attribute directly. Silent unless
5035
+ // the integrator asked for logs — the failure is reported as an
5036
+ // `sdk.init_failed` device event regardless.
5037
+ if (enableConsoleLogs) {
5038
+ console.error('[ZeroGpuSdk] Auto-init failed', error);
5039
+ }
4620
5040
  });
4621
5041
  };
4622
5042
 
@@ -4625,4 +5045,4 @@
4625
5045
  exports.initZeroGpuSdk = initZeroGpuSdk;
4626
5046
 
4627
5047
  }));
4628
- //# sourceMappingURL=zerogpu-browser-sdk.af4825958dcb.umd.js.map
5048
+ //# sourceMappingURL=zerogpu-browser-sdk.71504e330923.umd.js.map