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