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