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