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