@zerogpu/browser-extension-sdk 0.1.7 → 0.2.0-dev.202607211328.gc9a2a62

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.1.7+371d38a" === 'string' && "0.1.7+371d38a".length > 0
8
- ? "0.1.7+371d38a"
7
+ const SDK_VERSION = typeof "0.2.0-dev.202607211328.gc9a2a62+c9a2a62" === 'string' && "0.2.0-dev.202607211328.gc9a2a62+c9a2a62".length > 0
8
+ ? "0.2.0-dev.202607211328.gc9a2a62+c9a2a62"
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
@@ -391,18 +391,29 @@
391
391
  return null;
392
392
  }
393
393
  };
394
- const isEdgeSdkTypeNotAllowedResponse = (payload) => {
394
+ /**
395
+ * Detects the server's "polite refusal" envelope: HTTP 200, `status: 'ok'`,
396
+ * and a reason/code — used for `edge_sdk_type_not_allowed` and for every
397
+ * admission-guard refusal (`model_too_large_for_memory`, `low_battery`,
398
+ * `guardrail_blocked`, …). Returns the reason code, or null.
399
+ */
400
+ const detectSoftRefusal = (payload) => {
395
401
  if (!payload || typeof payload !== 'object') {
396
- return false;
402
+ return null;
397
403
  }
398
404
  const body = payload;
399
405
  const status = typeof body.status === 'string' ? body.status.toLowerCase() : '';
400
406
  if (status !== 'ok') {
401
- return false;
407
+ return null;
402
408
  }
403
409
  const nestedError = body.error;
404
410
  const candidateCodes = [body.code, body.errorCode, body.reason, nestedError?.code];
405
- return candidateCodes.some((value) => typeof value === 'string' && value.toLowerCase() === 'edge_sdk_type_not_allowed');
411
+ for (const value of candidateCodes) {
412
+ if (typeof value === 'string' && value.trim().length > 0) {
413
+ return value.trim().toLowerCase();
414
+ }
415
+ }
416
+ return null;
406
417
  };
407
418
  const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
408
419
  const buildCurl = (url, body, headers) => {
@@ -431,24 +442,27 @@
431
442
  logger.info('Register request sent:', { url, status: response.status });
432
443
  getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
433
444
  const registerResponseBody = await parseRegisterResponseBody(response);
434
- const edgeSdkTypeNotAllowed = isEdgeSdkTypeNotAllowedResponse(registerResponseBody);
435
- if (!response.ok && !edgeSdkTypeNotAllowed) {
445
+ const refusalReason = detectSoftRefusal(registerResponseBody);
446
+ if (!response.ok && !refusalReason) {
436
447
  const text = typeof registerResponseBody === 'string'
437
448
  ? registerResponseBody
438
449
  : JSON.stringify(registerResponseBody ?? '');
439
450
  logger.error('Register request failed:', { status: response.status, text });
440
451
  throw new RegisterError(response.status, text);
441
452
  }
442
- if (registerResponseBody && typeof registerResponseBody === 'object' && !edgeSdkTypeNotAllowed) {
453
+ if (registerResponseBody && typeof registerResponseBody === 'object' && !refusalReason) {
443
454
  const registerResponse = registerResponseBody;
444
455
  logger.info('Register response parsed:', registerResponse);
445
456
  return registerResponse;
446
457
  }
447
- if (edgeSdkTypeNotAllowed) {
458
+ if (refusalReason) {
459
+ // A refusal is still a conversation, not an error: synthesize an accepted
460
+ // response with no wsUrl and carry the reason so the lifecycle can exit
461
+ // cleanly (and pick up any configSettings the server included).
448
462
  const responseObject = registerResponseBody && typeof registerResponseBody === 'object'
449
463
  ? registerResponseBody
450
464
  : {};
451
- const acceptedResponse = {
465
+ const refusedResponse = {
452
466
  deviceId: typeof responseObject.deviceId === 'string' && responseObject.deviceId
453
467
  ? responseObject.deviceId
454
468
  : payload.deviceId,
@@ -456,14 +470,18 @@
456
470
  wsUrl: typeof responseObject.wsUrl === 'string' ? responseObject.wsUrl : '',
457
471
  active: typeof responseObject.active === 'boolean' ? responseObject.active : false,
458
472
  ttlSeconds: typeof responseObject.ttlSeconds === 'number' ? responseObject.ttlSeconds : 0,
473
+ refusalReason,
474
+ configSettings: responseObject.configSettings && typeof responseObject.configSettings === 'object'
475
+ ? responseObject.configSettings
476
+ : undefined,
459
477
  slmConfig: typeof responseObject.slmConfig !== 'undefined'
460
478
  ? responseObject.slmConfig
461
479
  : typeof responseObject.modelInfo !== 'undefined'
462
480
  ? [responseObject.modelInfo]
463
481
  : undefined
464
482
  };
465
- logger.info('Handled edge_sdk_type_not_allowed register response');
466
- return acceptedResponse;
483
+ logger.info('Register politely refused by server', { reason: refusalReason });
484
+ return refusedResponse;
467
485
  }
468
486
  throw new RegisterError(response.status, 'Register response body is not valid JSON');
469
487
  };
@@ -544,8 +562,14 @@
544
562
  this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
545
563
  this.socket.send(JSON.stringify(payload));
546
564
  }
547
- close() {
548
- this.socket.close();
565
+ close(code, reason) {
566
+ if (typeof code === 'number') {
567
+ // Close reasons are capped at 123 bytes by the WS protocol.
568
+ this.socket.close(code, (reason ?? '').slice(0, 120));
569
+ }
570
+ else {
571
+ this.socket.close();
572
+ }
549
573
  }
550
574
  }
551
575
 
@@ -978,6 +1002,597 @@
978
1002
  };
979
1003
  const getEventReporter = () => singleton ?? NOOP;
980
1004
 
1005
+ /**
1006
+ * Host-facing lifecycle status and events. The SDK is a guest in someone
1007
+ * else's app: this module is how the host observes guardrail state (degraded /
1008
+ * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1009
+ * consumers get the same signals as `zerogpu:*` window events, matching the
1010
+ * existing `zerogpu:cameraPreview` pattern.
1011
+ */
1012
+ let lifecycleStatus = 'starting';
1013
+ const listeners = {
1014
+ degraded: new Set(),
1015
+ recovered: new Set(),
1016
+ shutdown: new Set()
1017
+ };
1018
+ const getLifecycleStatus = () => lifecycleStatus;
1019
+ const setLifecycleStatus = (status) => {
1020
+ // Shutdown is terminal (state machine B.3): recovery exists only from
1021
+ // warn/degrade, never from shutdown.
1022
+ if (lifecycleStatus === 'shutdown')
1023
+ return;
1024
+ lifecycleStatus = status;
1025
+ };
1026
+ const isShutdown = () => lifecycleStatus === 'shutdown';
1027
+ /** Degraded and shutting-down SDKs finish in-flight work but accept nothing new. */
1028
+ const isTaskGateActive = () => lifecycleStatus === 'degraded' || lifecycleStatus === 'shutdown';
1029
+ const onHostEvent = (name, listener) => {
1030
+ listeners[name]?.add(listener);
1031
+ return () => listeners[name]?.delete(listener);
1032
+ };
1033
+ const emitHostEvent = (name, detail = {}) => {
1034
+ for (const listener of listeners[name] ?? []) {
1035
+ try {
1036
+ listener(detail);
1037
+ }
1038
+ catch {
1039
+ // A host listener bug must never propagate into the SDK.
1040
+ }
1041
+ }
1042
+ try {
1043
+ if (typeof window !== 'undefined') {
1044
+ window.dispatchEvent(new CustomEvent(`zerogpu:${name}`, { detail }));
1045
+ }
1046
+ }
1047
+ catch {
1048
+ // ignore
1049
+ }
1050
+ };
1051
+
1052
+ const DEFAULT_FRAMEWORK_MULTIPLIERS = {
1053
+ onnx: 2.0,
1054
+ transformersjs: 2.5,
1055
+ transformers: 2.5,
1056
+ gguf: 1.4
1057
+ };
1058
+ const DEFAULT_FRAMEWORK_MULTIPLIER = 2.0;
1059
+ const DEFAULT_MEMORY_BUDGET_FRACTION = 0.3;
1060
+ /** Battery floor below which a discharging device defers model downloads. */
1061
+ const DEFAULT_MIN_BATTERY_LEVEL = 0.2;
1062
+ /** Downloads need headroom beyond the file size (IndexedDB overhead, temp copies). */
1063
+ const DEFAULT_STORAGE_HEADROOM = 1.2;
1064
+ /** Devices that report no memory are treated as modest 2 GB devices (same as the server). */
1065
+ const UNKNOWN_DEVICE_MEMORY_GB = 2;
1066
+ const DEFAULT_WATCHDOG = {
1067
+ warnPct: 0.7,
1068
+ degradePct: 0.85,
1069
+ shutdownPct: 0.95,
1070
+ sampleMs: 10000,
1071
+ recoverPct: 0.6,
1072
+ recoverHoldMs: 60000
1073
+ };
1074
+ let policy = {};
1075
+ let resolved = resolve(null);
1076
+ function positive(value) {
1077
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
1078
+ }
1079
+ function resolve(settings) {
1080
+ const watchdog = settings?.watchdog ?? {};
1081
+ // Non-positive served multipliers are treated as absent (same semantics as
1082
+ // the registry) so a bad settings edit cannot zero out the memory gate.
1083
+ const servedMultipliers = Object.fromEntries(Object.entries(settings?.frameworkMultipliers ?? {}).filter(([, v]) => positive(v) !== undefined));
1084
+ return {
1085
+ memoryBudgetFraction: positive(policy.memoryBudgetFraction) ??
1086
+ positive(settings?.memoryBudgetFraction) ??
1087
+ DEFAULT_MEMORY_BUDGET_FRACTION,
1088
+ frameworkMultipliers: {
1089
+ ...DEFAULT_FRAMEWORK_MULTIPLIERS,
1090
+ ...servedMultipliers
1091
+ },
1092
+ minBatteryLevel: positive(settings?.minBatteryLevel) ?? DEFAULT_MIN_BATTERY_LEVEL,
1093
+ storageHeadroom: positive(settings?.storageHeadroom) ?? DEFAULT_STORAGE_HEADROOM,
1094
+ unknownMemoryGb: positive(settings?.unknownMemoryGb) ?? UNKNOWN_DEVICE_MEMORY_GB,
1095
+ watchdog: {
1096
+ warnPct: positive(watchdog.warnPct) ?? DEFAULT_WATCHDOG.warnPct,
1097
+ degradePct: positive(watchdog.degradePct) ?? DEFAULT_WATCHDOG.degradePct,
1098
+ shutdownPct: positive(watchdog.shutdownPct) ?? DEFAULT_WATCHDOG.shutdownPct,
1099
+ sampleMs: positive(watchdog.sampleMs) ?? DEFAULT_WATCHDOG.sampleMs,
1100
+ recoverPct: positive(watchdog.recoverPct) ?? DEFAULT_WATCHDOG.recoverPct,
1101
+ recoverHoldMs: positive(watchdog.recoverHoldMs) ?? DEFAULT_WATCHDOG.recoverHoldMs
1102
+ }
1103
+ };
1104
+ }
1105
+ const setResourcePolicy = (next) => {
1106
+ policy = next ?? {};
1107
+ resolved = resolve(null);
1108
+ };
1109
+ const getResourcePolicy = () => policy;
1110
+ /** Called after every register with the server-tuned block (or null). */
1111
+ const applyRegistrationGuardrails = (settings) => {
1112
+ resolved = resolve(settings?.guardrails ?? null);
1113
+ };
1114
+ const getGuardrails = () => resolved;
1115
+ const multiplierFor = (framework) => {
1116
+ const key = framework?.trim().toLowerCase() ?? '';
1117
+ return resolved.frameworkMultipliers[key] ?? DEFAULT_FRAMEWORK_MULTIPLIER;
1118
+ };
1119
+ /**
1120
+ * The catalog's size column is megabytes but travels as `sizeBytes` unchanged
1121
+ * (deberta-v3-small -> 184). Values below 1e6 cannot be real byte counts for
1122
+ * an on-device model — interpret them as MB, identically to the registry.
1123
+ */
1124
+ const normalizeModelSizeBytes = (raw) => {
1125
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0)
1126
+ return 0;
1127
+ return raw < 1000000 ? raw * 1024 * 1024 : raw;
1128
+ };
1129
+
1130
+ /**
1131
+ * Crash-loop guard for SDK initialization, extended into the Layer 4 crash
1132
+ * marker + per-model breaker.
1133
+ *
1134
+ * On a brand-new device the lifecycle synchronously downloads and instantiates
1135
+ * a full model (and runs a sample inference) before connecting the WebSocket.
1136
+ * In a memory-constrained host such as a Telegram mini-app WebView this burst
1137
+ * can crash/OOM the view; the host reloads, the SDK repeats the same heavy
1138
+ * path, and the app "refreshes continuously".
1139
+ *
1140
+ * Two mechanisms share one persisted state (`zerogpu_init_state`):
1141
+ *
1142
+ * - the original attempt counter: several uncompleted attempts in a short
1143
+ * window trip a cool-down that skips heavy init entirely;
1144
+ * - the crash marker: a `phase` written before each dangerous step
1145
+ * (load/sample) and cleared on graceful shutdown. A phase surviving to the
1146
+ * next boot means the process died mid-step — that boot reports
1147
+ * `sdk.crash_detected`, and two deaths during one model's risky phases in
1148
+ * 24 h blocklist that model for 24 h so a single oversized model can't take
1149
+ * the host down repeatedly.
1150
+ */
1151
+ const INIT_STATE_KEY = 'zerogpu_init_state';
1152
+ /** Attempts that never completed are only counted within this rolling window. */
1153
+ const ATTEMPT_WINDOW_MS = 60000;
1154
+ /** Number of uncompleted attempts in the window that trips the cool-down. */
1155
+ const MAX_ATTEMPTS_IN_WINDOW = 3;
1156
+ /** How long to skip heavy init once a crash loop is detected. */
1157
+ const COOLDOWN_MS = 5 * 60000;
1158
+ /** Phases where a process death points at the model itself. */
1159
+ const RISKY_PHASES = new Set(['downloading', 'loading', 'sampling']);
1160
+ const CRASH_WINDOW_MS = 24 * 60 * 60 * 1000;
1161
+ const BLOCKLIST_MS = 24 * 60 * 60 * 1000;
1162
+ const CRASHES_TO_BLOCKLIST = 2;
1163
+ const readState = () => {
1164
+ try {
1165
+ const raw = window.localStorage.getItem(INIT_STATE_KEY);
1166
+ if (!raw)
1167
+ return null;
1168
+ const parsed = JSON.parse(raw);
1169
+ if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
1170
+ return null;
1171
+ }
1172
+ return parsed;
1173
+ }
1174
+ catch {
1175
+ return null;
1176
+ }
1177
+ };
1178
+ const writeState = (state) => {
1179
+ try {
1180
+ window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
1181
+ }
1182
+ catch {
1183
+ // Storage may be unavailable/partitioned; degrade silently.
1184
+ }
1185
+ };
1186
+ const modelKey = (modelId, modelVersion) => `${modelId}@${modelVersion ?? '1'}`;
1187
+ /** The breaker/marker fields that must survive attempt resets and successes. */
1188
+ const persistentFields = (state) => ({
1189
+ modelCrashes: state?.modelCrashes,
1190
+ blocklist: state?.blocklist,
1191
+ lastShutdown: state?.lastShutdown
1192
+ });
1193
+ const pruneBlocklist = (blocklist, now) => {
1194
+ if (!blocklist)
1195
+ return undefined;
1196
+ const live = Object.fromEntries(Object.entries(blocklist).filter(([, entry]) => entry.until > now));
1197
+ return Object.keys(live).length > 0 ? live : undefined;
1198
+ };
1199
+ /**
1200
+ * Extracts crash info from a surviving phase and applies the breaker rule.
1201
+ * Returns the mutated persistent fields plus the report for the caller.
1202
+ */
1203
+ const consumeCrashMarker = (state, now) => {
1204
+ let modelCrashes = state?.modelCrashes;
1205
+ let blocklist = pruneBlocklist(state?.blocklist, now);
1206
+ const phase = state?.phase;
1207
+ if (!phase)
1208
+ return { modelCrashes, blocklist };
1209
+ const risky = RISKY_PHASES.has(phase);
1210
+ let blocklistedModel;
1211
+ if (risky && state?.modelId) {
1212
+ const key = modelKey(state.modelId, state.modelVersion);
1213
+ const prior = modelCrashes?.[key];
1214
+ const inWindow = prior && now - prior.firstAt < CRASH_WINDOW_MS;
1215
+ const count = inWindow ? prior.count + 1 : 1;
1216
+ modelCrashes = { ...(modelCrashes ?? {}), [key]: { count, firstAt: inWindow ? prior.firstAt : now } };
1217
+ if (count >= CRASHES_TO_BLOCKLIST) {
1218
+ blocklist = { ...(blocklist ?? {}), [key]: { until: now + BLOCKLIST_MS } };
1219
+ blocklistedModel = key;
1220
+ }
1221
+ }
1222
+ return {
1223
+ crash: {
1224
+ code: risky ? 'oom_suspected' : 'unknown',
1225
+ phase,
1226
+ modelId: state?.modelId,
1227
+ modelVersion: state?.modelVersion,
1228
+ blocklistedModel
1229
+ },
1230
+ modelCrashes,
1231
+ blocklist
1232
+ };
1233
+ };
1234
+ /**
1235
+ * Records the start of an init attempt and decides whether heavy init may
1236
+ * proceed. Must be called once, before any heavy work, on every lifecycle start.
1237
+ */
1238
+ const beginInitAttempt = (now = Date.now()) => {
1239
+ const state = readState();
1240
+ // A surviving phase means the last process died mid-step; consume it first
1241
+ // so the crash is attributed exactly once.
1242
+ const { crash, modelCrashes, blocklist } = consumeCrashMarker(state, now);
1243
+ const persistent = {
1244
+ modelCrashes,
1245
+ blocklist,
1246
+ lastShutdown: state?.lastShutdown
1247
+ };
1248
+ // Still inside an active cool-down from a previously detected crash loop.
1249
+ if (state?.cooldownUntil && state.cooldownUntil > now) {
1250
+ writeState({ ...state, phase: undefined, modelId: undefined, modelVersion: undefined, ...persistent });
1251
+ return {
1252
+ allowed: false,
1253
+ cooldownRemainingMs: state.cooldownUntil - now,
1254
+ attempts: state.attempts,
1255
+ crash
1256
+ };
1257
+ }
1258
+ // No prior state, or the previous window/cool-down has elapsed → start fresh.
1259
+ if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
1260
+ writeState({ attempts: 1, windowStart: now, ...persistent });
1261
+ return { allowed: true, attempts: 1, crash };
1262
+ }
1263
+ const attempts = state.attempts + 1;
1264
+ // Too many uncompleted attempts in the window → assume a crash loop and back
1265
+ // off so the host app stops reloading.
1266
+ if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
1267
+ writeState({
1268
+ attempts,
1269
+ windowStart: state.windowStart,
1270
+ cooldownUntil: now + COOLDOWN_MS,
1271
+ ...persistent
1272
+ });
1273
+ return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts, crash };
1274
+ }
1275
+ writeState({ attempts, windowStart: state.windowStart, ...persistent });
1276
+ return { allowed: true, attempts, crash };
1277
+ };
1278
+ /**
1279
+ * Clears crash-loop tracking. Call once init reaches a stable point (e.g. the
1280
+ * WebSocket is connected), so successful loads never accumulate toward a trip.
1281
+ * Breaker history and the current phase survive — only the attempt counter
1282
+ * resets.
1283
+ */
1284
+ const markInitSuccess = () => {
1285
+ const state = readState();
1286
+ writeState({
1287
+ attempts: 0,
1288
+ windowStart: Date.now(),
1289
+ phase: state?.phase,
1290
+ modelId: state?.modelId,
1291
+ modelVersion: state?.modelVersion,
1292
+ ...persistentFields(state)
1293
+ });
1294
+ };
1295
+ /** Written before every dangerous step so an unclean death is attributable. */
1296
+ const setInitPhase = (phase, modelId, modelVersion) => {
1297
+ const state = readState();
1298
+ writeState({
1299
+ attempts: state?.attempts ?? 0,
1300
+ windowStart: state?.windowStart ?? Date.now(),
1301
+ cooldownUntil: state?.cooldownUntil,
1302
+ phase,
1303
+ modelId,
1304
+ modelVersion,
1305
+ ...persistentFields(state)
1306
+ });
1307
+ };
1308
+ /** The graceful shutdown sequence ran — the next boot must not count a crash. */
1309
+ const markCleanShutdown = (code) => {
1310
+ const state = readState();
1311
+ writeState({
1312
+ attempts: state?.attempts ?? 0,
1313
+ windowStart: state?.windowStart ?? Date.now(),
1314
+ cooldownUntil: state?.cooldownUntil,
1315
+ modelCrashes: state?.modelCrashes,
1316
+ blocklist: state?.blocklist,
1317
+ lastShutdown: { code, ts: Date.now() }
1318
+ });
1319
+ };
1320
+ /** Blocklisted models are refused before any I/O (breaker, Layer 4). */
1321
+ const isModelBlocklisted = (modelId, modelVersion) => {
1322
+ const state = readState();
1323
+ const entry = state?.blocklist?.[modelKey(modelId, modelVersion)];
1324
+ return Boolean(entry && entry.until > Date.now());
1325
+ };
1326
+
1327
+ /**
1328
+ * The single pending re-registration timer, isolated so both the lifecycle
1329
+ * (which schedules it) and the shutdown sequence (which must kill it — §4.7:
1330
+ * a guardrail shutdown closes the socket, and without this the re-register
1331
+ * loop would resurrect the SDK into the same memory conditions) can reach it
1332
+ * without importing each other.
1333
+ */
1334
+ let reregisterTimerId = null;
1335
+ const hasReregisterTimer = () => reregisterTimerId !== null;
1336
+ const setReregisterTimer = (callback, delayMs) => {
1337
+ clearReregisterTimer();
1338
+ reregisterTimerId = setTimeout(() => {
1339
+ reregisterTimerId = null;
1340
+ callback();
1341
+ }, delayMs);
1342
+ };
1343
+ const clearReregisterTimer = () => {
1344
+ if (reregisterTimerId !== null) {
1345
+ clearTimeout(reregisterTimerId);
1346
+ reregisterTimerId = null;
1347
+ }
1348
+ };
1349
+
1350
+ /** Guardrail shutdown close code; the registry records it as `close_4002`. */
1351
+ const CLOSE_GUARDRAIL = 4002;
1352
+ const CLOSE_NORMAL = 1000;
1353
+ /**
1354
+ * Client→server status update on the live session. The registry's
1355
+ * DeviceSession accepts a hello_ack-shaped message from an authenticated
1356
+ * socket and flips the device `idle`/`error` — the degrade/recover wire
1357
+ * contract, no new message type needed.
1358
+ */
1359
+ const sendStatusUpdate = (status) => {
1360
+ try {
1361
+ const state = getState();
1362
+ const ws = state.ws;
1363
+ if (!ws?.isActive() || !state.sessionKey)
1364
+ return;
1365
+ ws.send({
1366
+ type: 'hello_ack',
1367
+ deviceId: state.deviceId,
1368
+ sdkVersion: state.config.sdkVersion,
1369
+ sessionKey: state.sessionKey,
1370
+ status,
1371
+ timestamp: Date.now()
1372
+ });
1373
+ }
1374
+ catch {
1375
+ // Best effort only.
1376
+ }
1377
+ };
1378
+ /**
1379
+ * The ordered shutdown sequence (GRACEFUL_SHUTDOWN_IMPLEMENTATION.md §5):
1380
+ * mark terminal + kill the re-register loop → gate input → tell the server →
1381
+ * report + beacon-flush → free memory largest-first → mark the exit clean →
1382
+ * notify the host. Every step individually guarded; target ≤ 1 s. Terminal:
1383
+ * `startLifecycle` refuses to run again until the page restarts the SDK.
1384
+ */
1385
+ const runShutdownSequence = async ({ reason, guardrail = false }) => {
1386
+ if (getLifecycleStatus() === 'shutdown')
1387
+ return;
1388
+ const logger = getLogger();
1389
+ logger.warn('[Shutdown] Running shutdown sequence', { reason, guardrail });
1390
+ // 0. Terminal state — gates the router, blocks startLifecycle, and stops the
1391
+ // re-register loop from resurrecting us into the same conditions (§4.7).
1392
+ setLifecycleStatus('shutdown');
1393
+ clearReregisterTimer();
1394
+ // 1–2. Tell the server (best effort), then close with the right code.
1395
+ try {
1396
+ if (guardrail)
1397
+ sendStatusUpdate('error');
1398
+ }
1399
+ catch {
1400
+ /* best effort */
1401
+ }
1402
+ try {
1403
+ getWebSocket()?.close(guardrail ? CLOSE_GUARDRAIL : CLOSE_NORMAL, reason);
1404
+ }
1405
+ catch {
1406
+ /* best effort */
1407
+ }
1408
+ try {
1409
+ setWebSocket(undefined);
1410
+ setStatus('error');
1411
+ }
1412
+ catch {
1413
+ /* state may not be initialized */
1414
+ }
1415
+ // 3. Report + flush before anything else can kill the page. Failure is fine:
1416
+ // the offline buffer drains next boot.
1417
+ const reporter = getEventReporter();
1418
+ reporter.report(guardrail ? 'guardrail.shutdown' : 'sdk.shutdown', { code: reason });
1419
+ try {
1420
+ reporter.flush({ beacon: true });
1421
+ }
1422
+ catch {
1423
+ /* offline buffer covers it */
1424
+ }
1425
+ // 4. Free memory largest-first; files stay on disk (re-download is the
1426
+ // expensive part, and the trigger here is memory, not storage).
1427
+ try {
1428
+ const { adaptersByModelId, modelInfosByModelId } = getState();
1429
+ const entries = Object.entries(adaptersByModelId ?? {}).sort(([a], [b]) => normalizeModelSizeBytes(modelInfosByModelId?.[b]?.sizeBytes) -
1430
+ normalizeModelSizeBytes(modelInfosByModelId?.[a]?.sizeBytes));
1431
+ for (const [, adapter] of entries) {
1432
+ try {
1433
+ await adapter.dispose?.();
1434
+ }
1435
+ catch {
1436
+ /* a failing dispose must not stop the sequence */
1437
+ }
1438
+ }
1439
+ setAdaptersByModelId({});
1440
+ }
1441
+ catch {
1442
+ /* state may not be initialized */
1443
+ }
1444
+ // 5. Mark the exit clean so the next boot isn't counted as a crash.
1445
+ markCleanShutdown(reason);
1446
+ // 6. Notify the host.
1447
+ emitHostEvent('shutdown', { code: reason });
1448
+ };
1449
+
1450
+ class WatchdogLadder {
1451
+ constructor(thresholds, budgetBytes) {
1452
+ this.thresholds = thresholds;
1453
+ this.budgetBytes = budgetBytes;
1454
+ this.belowRecoverSince = null;
1455
+ this.state = 'normal';
1456
+ }
1457
+ /** Maps a memory sample to the raw action the ladder calls for, if any. */
1458
+ onSample(usedBytes, now) {
1459
+ if (this.budgetBytes <= 0)
1460
+ return null;
1461
+ const used = usedBytes / this.budgetBytes;
1462
+ const t = this.thresholds;
1463
+ if (used > t.shutdownPct)
1464
+ return 'shutdown';
1465
+ if (used > t.degradePct)
1466
+ return 'degrade';
1467
+ if (used > t.warnPct)
1468
+ return 'warn';
1469
+ if (used < t.recoverPct && this.state !== 'normal') {
1470
+ if (this.belowRecoverSince === null)
1471
+ this.belowRecoverSince = now;
1472
+ return now - this.belowRecoverSince >= t.recoverHoldMs ? 'recover' : null;
1473
+ }
1474
+ this.belowRecoverSince = null;
1475
+ return null;
1476
+ }
1477
+ /** Applies an action; returns it only when it is a real state transition. */
1478
+ transition(action) {
1479
+ if (this.state === 'shutdown')
1480
+ return null;
1481
+ switch (action) {
1482
+ case 'shutdown':
1483
+ this.state = 'shutdown';
1484
+ return 'shutdown';
1485
+ case 'degrade':
1486
+ this.belowRecoverSince = null;
1487
+ if (this.state === 'degraded')
1488
+ return null;
1489
+ this.state = 'degraded';
1490
+ return 'degrade';
1491
+ case 'warn':
1492
+ this.belowRecoverSince = null;
1493
+ // Warn never downgrades an active degrade.
1494
+ if (this.state !== 'normal')
1495
+ return null;
1496
+ this.state = 'warn';
1497
+ return 'warn';
1498
+ case 'recover':
1499
+ this.belowRecoverSince = null;
1500
+ if (this.state === 'normal')
1501
+ return null;
1502
+ this.state = 'normal';
1503
+ return 'recover';
1504
+ }
1505
+ }
1506
+ }
1507
+ let timerId = null;
1508
+ const readHeapUsedBytes = () => {
1509
+ const perf = globalThis.performance;
1510
+ const used = perf?.memory?.usedJSHeapSize;
1511
+ return typeof used === 'number' && used > 0 ? used : null;
1512
+ };
1513
+ const act = (ladder, action) => {
1514
+ const transition = action ? ladder.transition(action) : null;
1515
+ if (!transition)
1516
+ return;
1517
+ const reporter = getEventReporter();
1518
+ switch (transition) {
1519
+ case 'warn':
1520
+ reporter.report('guardrail.pressure_warning', { code: 'memory_pressure' });
1521
+ break;
1522
+ case 'degrade':
1523
+ // Finish in-flight, accept nothing new; the DO takes us out of rotation.
1524
+ setLifecycleStatus('degraded');
1525
+ sendStatusUpdate('error');
1526
+ reporter.report('guardrail.degraded', { code: 'memory_pressure' });
1527
+ emitHostEvent('degraded', { code: 'memory_pressure' });
1528
+ break;
1529
+ case 'recover':
1530
+ setLifecycleStatus('running');
1531
+ sendStatusUpdate('idle');
1532
+ emitHostEvent('recovered', {});
1533
+ break;
1534
+ case 'shutdown':
1535
+ stopWatchdog();
1536
+ void runShutdownSequence({ reason: 'memory_pressure', guardrail: true });
1537
+ break;
1538
+ }
1539
+ };
1540
+ const startWatchdog = () => {
1541
+ if (timerId !== null || getResourcePolicy().disableGuardrails)
1542
+ return;
1543
+ if (readHeapUsedBytes() === null) {
1544
+ getLogger().debug('[Watchdog] performance.memory unavailable; watchdog inactive');
1545
+ return;
1546
+ }
1547
+ const guardrails = getGuardrails();
1548
+ let memoryGb = guardrails.unknownMemoryGb;
1549
+ try {
1550
+ const reported = getState().deviceInfo?.memoryGb;
1551
+ if (typeof reported === 'number' && reported > 0)
1552
+ memoryGb = reported;
1553
+ }
1554
+ catch {
1555
+ /* state not initialized yet */
1556
+ }
1557
+ const budgetBytes = guardrails.memoryBudgetFraction * memoryGb * 1024 * 1024 * 1024;
1558
+ const ladder = new WatchdogLadder(guardrails.watchdog, budgetBytes);
1559
+ timerId = setInterval(() => {
1560
+ try {
1561
+ if (getLifecycleStatus() === 'shutdown') {
1562
+ stopWatchdog();
1563
+ return;
1564
+ }
1565
+ // Hidden pages get throttled timers and misleading heap numbers; the
1566
+ // terminal-flush path owns backgrounding.
1567
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden')
1568
+ return;
1569
+ const used = readHeapUsedBytes();
1570
+ if (used === null)
1571
+ return;
1572
+ act(ladder, ladder.onSample(used, Date.now()));
1573
+ }
1574
+ catch {
1575
+ // The watchdog must never crash the host.
1576
+ }
1577
+ }, guardrails.watchdog.sampleMs);
1578
+ };
1579
+ const stopWatchdog = () => {
1580
+ if (timerId !== null) {
1581
+ clearInterval(timerId);
1582
+ timerId = null;
1583
+ }
1584
+ };
1585
+ /**
1586
+ * Allocation-failure boundary (Layer 5): adapters that catch a RangeError /
1587
+ * wasm abort route here instead of propagating — we may be one allocation from
1588
+ * the OOM kill, so run the emergency variant immediately.
1589
+ */
1590
+ const onAllocationFailure = (message) => {
1591
+ stopWatchdog();
1592
+ void runShutdownSequence({ reason: 'oom', guardrail: true });
1593
+ getLogger().error('[Watchdog] Allocation failure — emergency shutdown', { message });
1594
+ };
1595
+
981
1596
  let executing = false;
982
1597
  const buildInferenceInput = (request) => {
983
1598
  const input = request.input ?? {};
@@ -1065,12 +1680,19 @@
1065
1680
  }
1066
1681
  catch (error) {
1067
1682
  logger.error('Task failed', error);
1683
+ const message = error.message ?? '';
1684
+ const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
1068
1685
  getEventReporter().report('task.failed', {
1069
- code: 'adapter_error',
1686
+ code: isAllocationFailure ? 'oom' : 'adapter_error',
1070
1687
  modelId: request.modelId,
1071
1688
  durationMs: Math.round(performance.now() - start),
1072
- message: error.message
1689
+ message
1073
1690
  });
1691
+ if (isAllocationFailure) {
1692
+ // We may be one allocation from the OOM kill — emergency shutdown
1693
+ // (Layer 5 boundary); the error envelope below still goes out first.
1694
+ onAllocationFailure(message);
1695
+ }
1074
1696
  return {
1075
1697
  requestId: request.requestId,
1076
1698
  modelId: request.modelId,
@@ -1098,6 +1720,21 @@
1098
1720
  if (msg.requests.length === 0) {
1099
1721
  return;
1100
1722
  }
1723
+ // Degraded/shutting-down: finish in-flight work, accept nothing new — the
1724
+ // standard error envelope tells the server to route elsewhere immediately.
1725
+ if (isTaskGateActive()) {
1726
+ getEventReporter().report('task.rejected', { code: 'degraded' });
1727
+ sendBatchResponse(msg.requests.map((request) => ({
1728
+ requestId: request.requestId,
1729
+ modelId: request.modelId,
1730
+ modelVersion: request.modelVersion,
1731
+ response: { text: '' },
1732
+ error: true,
1733
+ errorMessage: 'degraded',
1734
+ metadata: { processingTime: 0 }
1735
+ })));
1736
+ return;
1737
+ }
1101
1738
  if (executing) {
1102
1739
  getEventReporter().report('task.rejected', { code: 'busy' });
1103
1740
  sendBatchResponse(msg.requests.map((request) => ({
@@ -1253,115 +1890,88 @@
1253
1890
  safeRemoveItem(CACHED_MODEL_ID_KEY);
1254
1891
  };
1255
1892
 
1256
- /**
1257
- * Crash-loop guard for SDK initialization.
1258
- *
1259
- * On a brand-new device the lifecycle synchronously downloads and instantiates a
1260
- * full model (and runs a sample inference) before connecting the WebSocket. In a
1261
- * memory-constrained host such as a Telegram mini-app WebView this burst can
1262
- * crash/OOM the view. The host then reloads the mini-app, the SDK runs the same
1263
- * heavy first-run path again, crashes again, and the app appears to "refresh
1264
- * continuously".
1265
- *
1266
- * Nothing in the previous flow recorded a *failed* attempt: the cache pointer is
1267
- * only written after a fully successful load, so every reload looked like a fresh
1268
- * first run. This guard persists a small attempt counter *before* the heavy work
1269
- * and clears it only once init reaches a stable point. If we see several attempts
1270
- * in a short window that never completed, we assume a crash loop and skip the
1271
- * heavy init for a cool-down period, which breaks the refresh cycle and lets the
1272
- * host app stay up.
1273
- */
1274
- const INIT_STATE_KEY = 'zerogpu_init_state';
1275
- /** Attempts that never completed are only counted within this rolling window. */
1276
- const ATTEMPT_WINDOW_MS = 60000;
1277
- /** Number of uncompleted attempts in the window that trips the cool-down. */
1278
- const MAX_ATTEMPTS_IN_WINDOW = 3;
1279
- /** How long to skip heavy init once a crash loop is detected. */
1280
- const COOLDOWN_MS = 5 * 60000;
1281
- const readState = () => {
1893
+ const BYTES_PER_GB = 1024 * 1024 * 1024;
1894
+ const evaluateResourceGate = async (model, stage, deviceInfo) => {
1282
1895
  try {
1283
- const raw = window.localStorage.getItem(INIT_STATE_KEY);
1284
- if (!raw)
1285
- return null;
1286
- const parsed = JSON.parse(raw);
1287
- if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
1896
+ if (getResourcePolicy().disableGuardrails)
1288
1897
  return null;
1898
+ const guardrails = getGuardrails();
1899
+ const sizeBytes = normalizeModelSizeBytes(model.sizeBytes);
1900
+ if (sizeBytes > 0) {
1901
+ const maxModelBytes = getResourcePolicy().maxModelBytes;
1902
+ if (typeof maxModelBytes === 'number' && sizeBytes > maxModelBytes) {
1903
+ return {
1904
+ code: 'model_too_large_for_memory',
1905
+ message: `model ${sizeBytes} B exceeds host maxModelBytes ${maxModelBytes}`
1906
+ };
1907
+ }
1908
+ const multiplier = multiplierFor(model.inferenceFramework);
1909
+ const estimatedRuntimeBytes = sizeBytes * multiplier;
1910
+ const memoryGb = typeof deviceInfo?.memoryGb === 'number' && deviceInfo.memoryGb > 0
1911
+ ? deviceInfo.memoryGb
1912
+ : guardrails.unknownMemoryGb;
1913
+ const budgetBytes = guardrails.memoryBudgetFraction * memoryGb * BYTES_PER_GB;
1914
+ if (estimatedRuntimeBytes > budgetBytes) {
1915
+ return {
1916
+ code: 'model_too_large_for_memory',
1917
+ message: `estimated runtime ${Math.round(estimatedRuntimeBytes)} B > budget ${Math.round(budgetBytes)} B ` +
1918
+ `(fraction=${guardrails.memoryBudgetFraction}, multiplier=${multiplier}, memoryGb=${memoryGb})`
1919
+ };
1920
+ }
1921
+ // Heap headroom — Chromium only; other engines expose nothing and the
1922
+ // preflight above stays the only pre-load signal there.
1923
+ const perf = globalThis.performance;
1924
+ const heap = perf?.memory;
1925
+ if (heap && heap.jsHeapSizeLimit > 0 && heap.usedJSHeapSize + estimatedRuntimeBytes > heap.jsHeapSizeLimit) {
1926
+ return {
1927
+ code: 'model_too_large_for_memory',
1928
+ message: `heap used ${heap.usedJSHeapSize} + runtime ${Math.round(estimatedRuntimeBytes)} exceeds limit ${heap.jsHeapSizeLimit}`
1929
+ };
1930
+ }
1931
+ if (stage === 'download') {
1932
+ try {
1933
+ const estimate = await navigator.storage?.estimate?.();
1934
+ if (estimate && typeof estimate.quota === 'number' && typeof estimate.usage === 'number') {
1935
+ const free = estimate.quota - estimate.usage;
1936
+ if (sizeBytes * guardrails.storageHeadroom > free) {
1937
+ return {
1938
+ code: 'storage_quota_exceeded',
1939
+ message: `need ${Math.round(sizeBytes * guardrails.storageHeadroom)} B, quota headroom ${free} B`
1940
+ };
1941
+ }
1942
+ }
1943
+ }
1944
+ catch {
1945
+ // Storage estimate unavailable — skip the check.
1946
+ }
1947
+ }
1948
+ }
1949
+ if (stage === 'download') {
1950
+ const battery = deviceInfo?.battery;
1951
+ if (battery &&
1952
+ typeof battery.level === 'number' &&
1953
+ battery.level < guardrails.minBatteryLevel &&
1954
+ battery.charging !== true) {
1955
+ return {
1956
+ code: 'low_battery',
1957
+ message: `battery ${battery.level} below ${guardrails.minBatteryLevel} and not charging`
1958
+ };
1959
+ }
1289
1960
  }
1290
- return parsed;
1291
- }
1292
- catch {
1293
1961
  return null;
1294
1962
  }
1295
- };
1296
- const writeState = (state) => {
1297
- try {
1298
- window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
1299
- }
1300
- catch {
1301
- // Storage may be unavailable/partitioned; degrade silently.
1302
- }
1303
- };
1304
- const clearState = () => {
1305
- try {
1306
- window.localStorage.removeItem(INIT_STATE_KEY);
1307
- }
1308
1963
  catch {
1309
- // ignore
1310
- }
1311
- };
1312
- /**
1313
- * Records the start of an init attempt and decides whether heavy init may
1314
- * proceed. Must be called once, before any heavy work, on every lifecycle start.
1315
- */
1316
- const beginInitAttempt = (now = Date.now()) => {
1317
- const state = readState();
1318
- // Still inside an active cool-down from a previously detected crash loop.
1319
- if (state?.cooldownUntil && state.cooldownUntil > now) {
1320
- return {
1321
- allowed: false,
1322
- cooldownRemainingMs: state.cooldownUntil - now,
1323
- attempts: state.attempts
1324
- };
1325
- }
1326
- // No prior state, or the previous window/cool-down has elapsed → start fresh.
1327
- if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
1328
- writeState({ attempts: 1, windowStart: now });
1329
- return { allowed: true, attempts: 1 };
1330
- }
1331
- const attempts = state.attempts + 1;
1332
- // Too many uncompleted attempts in the window → assume a crash loop and back
1333
- // off so the host app stops reloading.
1334
- if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
1335
- writeState({
1336
- attempts,
1337
- windowStart: state.windowStart,
1338
- cooldownUntil: now + COOLDOWN_MS
1339
- });
1340
- return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts };
1964
+ // The gate itself must never break init.
1965
+ return null;
1341
1966
  }
1342
- writeState({ attempts, windowStart: state.windowStart });
1343
- return { allowed: true, attempts };
1344
- };
1345
- /**
1346
- * Clears crash tracking. Call once init reaches a stable point (e.g. the
1347
- * WebSocket is connected), so successful loads never accumulate toward a trip.
1348
- */
1349
- const markInitSuccess = () => {
1350
- clearState();
1351
1967
  };
1352
1968
 
1353
1969
  // Re-registration loop: when the server idle-closes the WebSocket (or it drops
1354
1970
  // for any reason), wait device_timeout_interval_seconds and run the full
1355
1971
  // lifecycle again — re-registering refreshes device metrics and yields a new
1356
- // session key + WS URL. A single pending timer at a time; before reconnecting
1357
- // we check no socket is already live (infinite-loop guard).
1358
- let reregisterTimerId = null;
1359
- const clearReregisterTimer = () => {
1360
- if (reregisterTimerId !== null) {
1361
- clearTimeout(reregisterTimerId);
1362
- reregisterTimerId = null;
1363
- }
1364
- };
1972
+ // session key + WS URL. The single pending timer lives in ./reregister so the
1973
+ // shutdown sequence can kill it (§4.7); before reconnecting we check no socket
1974
+ // is already live (infinite-loop guard).
1365
1975
  const resolveReregisterDelaySeconds = () => {
1366
1976
  const value = getRegistrationSettings()?.device_timeout_interval_seconds;
1367
1977
  return typeof value === 'number' && Number.isFinite(value) && value > 0
@@ -1370,14 +1980,17 @@
1370
1980
  };
1371
1981
  const scheduleReregistration = (options) => {
1372
1982
  const logger = getLogger();
1373
- if (reregisterTimerId !== null) {
1983
+ if (hasReregisterTimer()) {
1374
1984
  logger.debug('[WS] Re-registration already scheduled; skipping');
1375
1985
  return;
1376
1986
  }
1987
+ if (isShutdown()) {
1988
+ logger.debug('[WS] SDK is shut down; not scheduling re-registration');
1989
+ return;
1990
+ }
1377
1991
  const delaySeconds = resolveReregisterDelaySeconds();
1378
1992
  logger.info('[WS] Scheduling re-registration', { delaySeconds });
1379
- reregisterTimerId = setTimeout(() => {
1380
- reregisterTimerId = null;
1993
+ setReregisterTimer(() => {
1381
1994
  if (getWebSocket()?.isActive()) {
1382
1995
  logger.info('[WS] Active WebSocket present; skipping re-registration');
1383
1996
  return;
@@ -1406,6 +2019,13 @@
1406
2019
  const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
1407
2020
  initLogger(config.telemetry);
1408
2021
  const logger = getLogger();
2022
+ // Shutdown is terminal until the host restarts the SDK (page reload): a
2023
+ // stray timer or caller must not resurrect us into the same conditions.
2024
+ if (isShutdown()) {
2025
+ logger.warn('[Init] SDK is shut down; refusing to start lifecycle');
2026
+ return;
2027
+ }
2028
+ setLifecycleStatus('starting');
1409
2029
  setConfig(config);
1410
2030
  // A fresh (manual or scheduled) start supersedes any pending reconnect timer.
1411
2031
  clearReregisterTimer();
@@ -1428,10 +2048,14 @@
1428
2048
  const guard = beginInitAttempt();
1429
2049
  if (!guard.allowed) {
1430
2050
  setStatus('error');
2051
+ setLifecycleStatus('error');
1431
2052
  logger.warn('Init skipped: crash-loop guard active', {
1432
2053
  attempts: guard.attempts,
1433
2054
  cooldownRemainingMs: guard.cooldownRemainingMs
1434
2055
  });
2056
+ // Reporter may exist from an earlier run on this page; best-effort only —
2057
+ // on a cold page the offline buffer picks the story up next boot.
2058
+ getEventReporter().report('sdk.init_failed', { code: 'crash_loop' });
1435
2059
  return;
1436
2060
  }
1437
2061
  const bootStartedAt = performance.now();
@@ -1461,6 +2085,7 @@
1461
2085
  });
1462
2086
  const reporter = getEventReporter();
1463
2087
  reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2088
+ reportCrashFromPreviousSession(guard.crash);
1464
2089
  logger.info('[Init] Device info collected', {
1465
2090
  platform: sanitizedDeviceInfo.platform,
1466
2091
  deviceType: sanitizedDeviceInfo.deviceType,
@@ -1483,6 +2108,20 @@
1483
2108
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
1484
2109
  setCachedModelId(cachedModelId);
1485
2110
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
2111
+ // Breaker short-circuit: a blocklisted model must not be validation-loaded
2112
+ // (that load is the exact thing that killed the host) and must not be
2113
+ // advertised in cachedModels. Files stay on disk; the entry lapses in 24 h.
2114
+ if (cachedInfo && isModelBlocklisted(cachedInfo.modelId, cachedInfo.modelVersion)) {
2115
+ reporter.report('guardrail.preflight_blocked', {
2116
+ code: 'model_blocklisted',
2117
+ modelId: cachedInfo.modelId,
2118
+ modelVersion: cachedInfo.modelVersion
2119
+ });
2120
+ logger.warn('[Guard] Cached model is blocklisted; skipping cache validation', {
2121
+ modelId: cachedInfo.modelId
2122
+ });
2123
+ cachedInfo = null;
2124
+ }
1486
2125
  if (!isFreshDevice) {
1487
2126
  logger.info('Cache lookup', {
1488
2127
  cachedModelId,
@@ -1556,6 +2195,7 @@
1556
2195
  });
1557
2196
  }
1558
2197
  else {
2198
+ setInitPhase('loading', cachedInfo.modelId, cachedInfo.modelVersion);
1559
2199
  const loadResult = await factory.load(slmConfig, { allowDownload: hasCachedFiles });
1560
2200
  if (!loadResult.adapter || loadResult.error) {
1561
2201
  cacheInvalid = true;
@@ -1575,6 +2215,7 @@
1575
2215
  cachedAdapter = loadResult.adapter;
1576
2216
  setAdapter(cachedInfo.modelId, cachedAdapter);
1577
2217
  const sample = cachedInfo.sample;
2218
+ setInitPhase('sampling', cachedInfo.modelId, cachedInfo.modelVersion);
1578
2219
  const sampleResult = await cachedAdapter.runSample(sample);
1579
2220
  cachedSampleMetrics = {
1580
2221
  taskType: cachedInfo.taskType,
@@ -1672,17 +2313,34 @@
1672
2313
  markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
1673
2314
  throw err;
1674
2315
  }
2316
+ // Settings (incl. server-tuned guardrails) apply on every outcome — a
2317
+ // refusal can still carry the tunables and the re-register interval.
2318
+ const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
2319
+ setRegistrationSettings(registrationSettings);
2320
+ applyRegistrationGuardrails(registrationSettings);
2321
+ if (registrationSettings) {
2322
+ logger.info('[Register] Registration settings received', registrationSettings);
2323
+ }
2324
+ if (registerResponse.refusalReason) {
2325
+ // The server deliberately declined this device (admission rules) — the
2326
+ // opposite of a failure. Exit cleanly, come back on the slow re-register
2327
+ // interval: battery/connection refusals are transient conditions.
2328
+ reporter.report('register.rejected', { code: registerResponse.refusalReason });
2329
+ logger.warn('[Register] Registration refused by server', {
2330
+ reason: registerResponse.refusalReason
2331
+ });
2332
+ setStatus('error');
2333
+ setLifecycleStatus('error');
2334
+ markInitSuccess(); // Clean exit, not a crash loop.
2335
+ scheduleReregistration(lifecycleOptions);
2336
+ return;
2337
+ }
1675
2338
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
1676
2339
  reporter.setSessionKey(registerResponse.sessionKey);
1677
2340
  logger.info('Register response received:', {
1678
2341
  deviceId: registerResponse.deviceId,
1679
2342
  wsUrl: registerResponse.wsUrl
1680
2343
  });
1681
- const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
1682
- setRegistrationSettings(registrationSettings);
1683
- if (registrationSettings) {
1684
- logger.info('[Register] Registration settings received', registrationSettings);
1685
- }
1686
2344
  if (!registerResponse.wsUrl) {
1687
2345
  markInitSuccess(); // Clean exit, not a crash loop.
1688
2346
  return;
@@ -1741,7 +2399,26 @@
1741
2399
  setAdaptersByModelId({});
1742
2400
  const slmConfig = buildSlmConfigFromAssigned(primaryModel);
1743
2401
  const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
1744
- if (!factory) {
2402
+ // Layer 2/4 preflight: blocklisted or won't-fit models are refused before
2403
+ // any download/allocation. The model is reported `error` in the hello so
2404
+ // the device stays registered and auditable; the host stays alive.
2405
+ const preflightBlock = await preflightAssignedModel(primaryModel);
2406
+ if (preflightBlock) {
2407
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
2408
+ loadErrorMessage = `preflight_blocked:${preflightBlock.code}`;
2409
+ reporter.report('guardrail.preflight_blocked', {
2410
+ code: preflightBlock.code,
2411
+ modelId: primaryModel.modelId,
2412
+ modelVersion: primaryModel.modelVersion,
2413
+ message: preflightBlock.message
2414
+ });
2415
+ logger.warn('[Guard] Primary model blocked by preflight', {
2416
+ modelId: primaryModel.modelId,
2417
+ code: preflightBlock.code,
2418
+ message: preflightBlock.message
2419
+ });
2420
+ }
2421
+ else if (!factory) {
1745
2422
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1746
2423
  loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
1747
2424
  reporter.report('model.load_failed', {
@@ -1765,6 +2442,7 @@
1765
2442
  modelRepoId: primaryModel.modelRepoId
1766
2443
  });
1767
2444
  reporter.report('model.load_started', { modelId: primaryModel.modelId, modelVersion: primaryModel.modelVersion });
2445
+ setInitPhase('loading', primaryModel.modelId, primaryModel.modelVersion);
1768
2446
  const primaryLoadStart = performance.now();
1769
2447
  const loadResult = await factory.load(slmConfig);
1770
2448
  const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
@@ -1851,6 +2529,18 @@
1851
2529
  });
1852
2530
  continue;
1853
2531
  }
2532
+ const secondaryBlock = await preflightAssignedModel(model);
2533
+ if (secondaryBlock) {
2534
+ modelStatuses[getModelStatusKey(model)] = 'error';
2535
+ reporter.report('guardrail.preflight_blocked', {
2536
+ code: secondaryBlock.code,
2537
+ modelId: model.modelId,
2538
+ modelVersion: model.modelVersion,
2539
+ message: secondaryBlock.message
2540
+ });
2541
+ continue;
2542
+ }
2543
+ setInitPhase('loading', model.modelId, model.modelVersion);
1854
2544
  const loadResult = await factory.load(slmConfig);
1855
2545
  if (loadResult.adapter) {
1856
2546
  adaptersByModelId[model.modelId] = loadResult.adapter;
@@ -1908,6 +2598,7 @@
1908
2598
  logger.info('[Sample] Running post-register sample inference', {
1909
2599
  taskType: primaryModel.taskType
1910
2600
  });
2601
+ setInitPhase('sampling', primaryModel.modelId, primaryModel.modelVersion);
1911
2602
  postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1912
2603
  const sampleLog = {
1913
2604
  taskType: primaryModel.taskType,
@@ -2000,6 +2691,10 @@
2000
2691
  });
2001
2692
  setWebSocket(client);
2002
2693
  setStatus('idle');
2694
+ // Model phases are behind us; a death from here on is not model-attributed.
2695
+ setInitPhase('running', primaryModel.modelId, primaryModel.modelVersion);
2696
+ setLifecycleStatus('running');
2697
+ startWatchdog();
2003
2698
  reporter.report('sdk.init_succeeded', { durationMs: Math.round(performance.now() - bootStartedAt) });
2004
2699
  logger.info('[Init] SDK ready', {
2005
2700
  deviceId,
@@ -2028,6 +2723,8 @@
2028
2723
  const mapModelLoadErrorCode = (message) => {
2029
2724
  if (!message)
2030
2725
  return 'init_error';
2726
+ if (/preflight_blocked/.test(message))
2727
+ return 'guardrail_blocked';
2031
2728
  if (/no_adapter_factory/.test(message))
2032
2729
  return 'no_adapter_factory';
2033
2730
  if (/oom|out of memory|RangeError/i.test(message))
@@ -2036,6 +2733,44 @@
2036
2733
  return 'wasm_abort';
2037
2734
  return 'init_error';
2038
2735
  };
2736
+ /** Blocklist short-circuit, then the ResourceGate — before any I/O for a model. */
2737
+ const preflightAssignedModel = async (model) => {
2738
+ if (isModelBlocklisted(model.modelId, model.modelVersion)) {
2739
+ return { code: 'model_blocklisted', message: 'blocklisted after repeated crashes during load' };
2740
+ }
2741
+ let deviceInfo;
2742
+ try {
2743
+ deviceInfo = getState().deviceInfo;
2744
+ }
2745
+ catch {
2746
+ deviceInfo = undefined;
2747
+ }
2748
+ return evaluateResourceGate({
2749
+ modelId: model.modelId,
2750
+ modelVersion: model.modelVersion,
2751
+ sizeBytes: model.sizeBytes,
2752
+ inferenceFramework: model.inferenceFramework
2753
+ }, 'download', deviceInfo);
2754
+ };
2755
+ /** The previous process died mid-phase — attribute it now that the reporter is live. */
2756
+ const reportCrashFromPreviousSession = (crash) => {
2757
+ if (!crash)
2758
+ return;
2759
+ const reporter = getEventReporter();
2760
+ reporter.report('sdk.crash_detected', {
2761
+ code: crash.code,
2762
+ modelId: crash.modelId,
2763
+ modelVersion: crash.modelVersion,
2764
+ data: { phase: crash.phase }
2765
+ });
2766
+ if (crash.blocklistedModel) {
2767
+ reporter.report('guardrail.model_blocklisted', {
2768
+ modelId: crash.modelId,
2769
+ modelVersion: crash.modelVersion,
2770
+ message: crash.blocklistedModel
2771
+ });
2772
+ }
2773
+ };
2039
2774
  const normalizeAssignedModels = (slmConfig) => {
2040
2775
  if (!Array.isArray(slmConfig))
2041
2776
  return [];
@@ -3486,18 +4221,47 @@
3486
4221
  registerAdapter(factory);
3487
4222
 
3488
4223
  let initialized = false;
4224
+ const handle = {
4225
+ get status() {
4226
+ return getLifecycleStatus();
4227
+ },
4228
+ on: onHostEvent,
4229
+ shutdown: () => runShutdownSequence({ reason: 'host_stop' })
4230
+ };
4231
+ /**
4232
+ * Never rejects: the SDK is a guest in someone else's app, and a failed init
4233
+ * must degrade to "SDK not running" — observable via `handle.status` and the
4234
+ * reported `sdk.init_failed` events — never to an unhandled rejection in the
4235
+ * host. Existing `await initZeroGpuSdk(...)` callers are unaffected (the
4236
+ * returned handle is additive).
4237
+ */
3489
4238
  const initZeroGpuSdk = async (options) => {
3490
4239
  if (initialized) {
3491
- return;
4240
+ return handle;
3492
4241
  }
3493
- const config = resolveConfig(options?.overrides);
3494
- await startLifecycle({
3495
- config,
3496
- appUserId: options?.appUserId,
3497
- edgeOperatorKey: options?.edgeOperatorKey,
3498
- deviceId: options?.deviceId
3499
- });
3500
4242
  initialized = true;
4243
+ if (options?.resourcePolicy) {
4244
+ setResourcePolicy(options.resourcePolicy);
4245
+ if (options.resourcePolicy.disableGuardrails) {
4246
+ // Loud by design: a host running without guardrails should know it.
4247
+ console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
4248
+ }
4249
+ }
4250
+ const config = resolveConfig(options?.overrides);
4251
+ try {
4252
+ await startLifecycle({
4253
+ config,
4254
+ appUserId: options?.appUserId,
4255
+ edgeOperatorKey: options?.edgeOperatorKey,
4256
+ deviceId: options?.deviceId
4257
+ });
4258
+ }
4259
+ catch (err) {
4260
+ // Already reported inside the lifecycle (register.failed / sdk.init_failed
4261
+ // / init-failure hello); surface for the host without throwing into it.
4262
+ getLogger().error('[Init] SDK initialization failed', err);
4263
+ }
4264
+ return handle;
3501
4265
  };
3502
4266
 
3503
4267
  const readAttr = (script, names) => {
@@ -3621,4 +4385,4 @@
3621
4385
  exports.initZeroGpuSdk = initZeroGpuSdk;
3622
4386
 
3623
4387
  }));
3624
- //# sourceMappingURL=zerogpu-browser-sdk.eb450ff5aa47.umd.js.map
4388
+ //# sourceMappingURL=zerogpu-browser-sdk.de2e6d71813f.umd.js.map