@zerogpu/browser-extension-sdk 0.1.7 → 0.2.0-dev.202607221142.g1c6b982

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.
Files changed (31) hide show
  1. package/README.md +7 -0
  2. package/dist/assets/zerogpu-assets.json +3 -2
  3. package/dist/extension/zerogpu-offscreen.js +1000 -141
  4. package/dist/extension/zerogpu-offscreen.js.map +1 -1
  5. package/dist/manifest.json +6 -5
  6. package/dist/types/config/types.d.ts +18 -0
  7. package/dist/types/public-api.d.ts +29 -1
  8. package/dist/types/runtime/guardrails.d.ts +36 -0
  9. package/dist/types/runtime/host-api.d.ts +22 -0
  10. package/dist/types/runtime/init-guard.d.ts +38 -15
  11. package/dist/types/runtime/lifecycle.d.ts +2 -0
  12. package/dist/types/runtime/reregister.d.ts +10 -0
  13. package/dist/types/runtime/resource-gate.d.ts +23 -0
  14. package/dist/types/runtime/shutdown.d.ts +22 -0
  15. package/dist/types/runtime/tracking-pixel.d.ts +27 -0
  16. package/dist/types/runtime/watchdog.d.ts +35 -0
  17. package/dist/types/transport/http.d.ts +13 -0
  18. package/dist/types/transport/protocol.d.ts +8 -0
  19. package/dist/types/transport/websocket.d.ts +1 -1
  20. package/dist/v/{zerogpu-browser-sdk.eb450ff5aa47.umd.js → zerogpu-browser-sdk.beb83655dbd2.umd.js} +997 -138
  21. package/dist/v/zerogpu-browser-sdk.beb83655dbd2.umd.js.map +1 -0
  22. package/dist/zerogpu-browser-sdk.cjs +996 -137
  23. package/dist/zerogpu-browser-sdk.cjs.map +1 -1
  24. package/dist/zerogpu-browser-sdk.esm.js +996 -137
  25. package/dist/zerogpu-browser-sdk.esm.js.map +1 -1
  26. package/dist/zerogpu-browser-sdk.umd.js +996 -137
  27. package/dist/zerogpu-browser-sdk.umd.js.map +1 -1
  28. package/docs/auto-update-loader.md +6 -0
  29. package/docs/extension-developer-guide.md +7 -0
  30. package/package.json +4 -3
  31. package/dist/v/zerogpu-browser-sdk.eb450ff5aa47.umd.js.map +0 -1
@@ -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.202607221142.g1c6b982+1c6b982" === 'string' && "0.2.0-dev.202607221142.g1c6b982+1c6b982".length > 0
2
+ ? "0.2.0-dev.202607221142.g1c6b982+1c6b982"
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,656 @@ 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
+
1590
+ /**
1591
+ * Fires ad-measurement pixels from the device.
1592
+ *
1593
+ * The point of running these here rather than server-side is that the ad server
1594
+ * sees the end user's real IP, User-Agent and cookies; fired from a datacenter
1595
+ * they are filtered or flagged as fraud.
1596
+ */
1597
+ const DEFAULT_TIMEOUT_MS = 3000;
1598
+ // Holds in-flight images so the GC cannot collect one mid-request, which would
1599
+ // cancel the beacon before it reaches the ad server.
1600
+ const inFlight = new Set();
1601
+ /**
1602
+ * Loads `url` as an image and resolves once the request has left the device.
1603
+ *
1604
+ * Both `load` and `error` resolve to 'fired', by design. Measurement endpoints
1605
+ * answer with 204s, redirect chains and non-image bodies, so `error` is the
1606
+ * normal outcome for a perfectly successful pixel — treating it as a failure
1607
+ * would report a ~100% failure rate. Only the timeout is genuinely unknown.
1608
+ *
1609
+ * Never rejects: a pixel is best-effort and must not affect inference.
1610
+ */
1611
+ const fireTrackingPixel = (url, timeoutMs = DEFAULT_TIMEOUT_MS) => {
1612
+ // Non-DOM hosts (e.g. a worker) cannot fire a beacon.
1613
+ if (typeof Image === 'undefined')
1614
+ return Promise.resolve('skipped');
1615
+ return new Promise((resolve) => {
1616
+ let settled = false;
1617
+ let img;
1618
+ let timer;
1619
+ const settle = (status) => {
1620
+ if (settled)
1621
+ return;
1622
+ settled = true;
1623
+ if (timer !== undefined)
1624
+ clearTimeout(timer);
1625
+ if (img) {
1626
+ img.onload = null;
1627
+ img.onerror = null;
1628
+ inFlight.delete(img);
1629
+ }
1630
+ resolve(status);
1631
+ };
1632
+ // Everything here is best-effort: a host that blocks image construction or
1633
+ // src assignment must degrade to 'skipped', never throw into the caller and
1634
+ // never take inference down with it.
1635
+ try {
1636
+ timer = setTimeout(() => settle('timeout'), timeoutMs);
1637
+ img = new Image();
1638
+ img.onload = () => settle('fired');
1639
+ img.onerror = () => settle('fired');
1640
+ inFlight.add(img);
1641
+ img.src = url;
1642
+ }
1643
+ catch {
1644
+ settle('skipped');
1645
+ }
1646
+ });
1647
+ };
1648
+
975
1649
  let executing = false;
976
1650
  const buildInferenceInput = (request) => {
977
1651
  const input = request.input ?? {};
@@ -1042,6 +1716,29 @@ const executeSingleRequest = async (request) => {
1042
1716
  }
1043
1717
  };
1044
1718
  }
1719
+ // Kicked off only once the adapter is confirmed: a model_not_ready return
1720
+ // above sends the request to cloud instead, and firing then would count an
1721
+ // impression this device never served. Deliberately not awaited so a slow ad
1722
+ // server cannot add latency to inference; whatever has settled by the time
1723
+ // inference finishes is what gets reported.
1724
+ let pixelStatus = 'pending';
1725
+ if (request.trackingPixel) {
1726
+ void fireTrackingPixel(request.trackingPixel).then((status) => {
1727
+ pixelStatus = status;
1728
+ });
1729
+ }
1730
+ const pixelMetadata = async () => {
1731
+ if (!request.trackingPixel)
1732
+ return {};
1733
+ // Yield one turn before snapshotting. The beacon's load/error is a
1734
+ // macrotask, and it cannot run while synchronous inference holds the
1735
+ // thread — so by the time inference resolves, a request that finished long
1736
+ // ago is still sitting unprocessed in the queue and would be reported as
1737
+ // 'pending'. This waits on nothing (a genuinely slow pixel still reports
1738
+ // 'pending'), it just stops discarding a result that already arrived.
1739
+ await new Promise((resolve) => setTimeout(resolve, 0));
1740
+ return { trackingPixel: pixelStatus };
1741
+ };
1045
1742
  try {
1046
1743
  const input = buildInferenceInput(request);
1047
1744
  const result = await adapter.runInference(input);
@@ -1053,18 +1750,26 @@ const executeSingleRequest = async (request) => {
1053
1750
  error: false,
1054
1751
  errorMessage: '',
1055
1752
  metadata: {
1056
- processingTime: Math.round(performance.now() - start)
1753
+ processingTime: Math.round(performance.now() - start),
1754
+ ...(await pixelMetadata())
1057
1755
  }
1058
1756
  };
1059
1757
  }
1060
1758
  catch (error) {
1061
1759
  logger.error('Task failed', error);
1760
+ const message = error.message ?? '';
1761
+ const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
1062
1762
  getEventReporter().report('task.failed', {
1063
- code: 'adapter_error',
1763
+ code: isAllocationFailure ? 'oom' : 'adapter_error',
1064
1764
  modelId: request.modelId,
1065
1765
  durationMs: Math.round(performance.now() - start),
1066
- message: error.message
1766
+ message
1067
1767
  });
1768
+ if (isAllocationFailure) {
1769
+ // We may be one allocation from the OOM kill — emergency shutdown
1770
+ // (Layer 5 boundary); the error envelope below still goes out first.
1771
+ onAllocationFailure(message);
1772
+ }
1068
1773
  return {
1069
1774
  requestId: request.requestId,
1070
1775
  modelId: request.modelId,
@@ -1073,7 +1778,11 @@ const executeSingleRequest = async (request) => {
1073
1778
  error: true,
1074
1779
  errorMessage: error.message,
1075
1780
  metadata: {
1076
- processingTime: Math.round(performance.now() - start)
1781
+ processingTime: Math.round(performance.now() - start),
1782
+ // The beacon is fired before inference runs, so a failed task can still
1783
+ // have delivered its impression. Reporting it only on success would
1784
+ // under-count the fire rate.
1785
+ ...(await pixelMetadata())
1077
1786
  }
1078
1787
  };
1079
1788
  }
@@ -1092,6 +1801,21 @@ const handleIncomingMessage = async (msg) => {
1092
1801
  if (msg.requests.length === 0) {
1093
1802
  return;
1094
1803
  }
1804
+ // Degraded/shutting-down: finish in-flight work, accept nothing new — the
1805
+ // standard error envelope tells the server to route elsewhere immediately.
1806
+ if (isTaskGateActive()) {
1807
+ getEventReporter().report('task.rejected', { code: 'degraded' });
1808
+ sendBatchResponse(msg.requests.map((request) => ({
1809
+ requestId: request.requestId,
1810
+ modelId: request.modelId,
1811
+ modelVersion: request.modelVersion,
1812
+ response: { text: '' },
1813
+ error: true,
1814
+ errorMessage: 'degraded',
1815
+ metadata: { processingTime: 0 }
1816
+ })));
1817
+ return;
1818
+ }
1095
1819
  if (executing) {
1096
1820
  getEventReporter().report('task.rejected', { code: 'busy' });
1097
1821
  sendBatchResponse(msg.requests.map((request) => ({
@@ -1247,115 +1971,95 @@ const clearCachedModelInfo = (modelId) => {
1247
1971
  safeRemoveItem(CACHED_MODEL_ID_KEY);
1248
1972
  };
1249
1973
 
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 = () => {
1974
+ const BYTES_PER_GB = 1024 * 1024 * 1024;
1975
+ const evaluateResourceGate = async (model, stage, deviceInfo) => {
1276
1976
  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') {
1977
+ if (getResourcePolicy().disableGuardrails)
1282
1978
  return null;
1979
+ const guardrails = getGuardrails();
1980
+ const sizeBytes = normalizeModelSizeBytes(model.sizeBytes);
1981
+ if (sizeBytes > 0) {
1982
+ const maxModelBytes = getResourcePolicy().maxModelBytes;
1983
+ if (typeof maxModelBytes === 'number' && sizeBytes > maxModelBytes) {
1984
+ return {
1985
+ code: 'model_too_large_for_memory',
1986
+ message: `model ${sizeBytes} B exceeds host maxModelBytes ${maxModelBytes}`
1987
+ };
1988
+ }
1989
+ const multiplier = multiplierFor(model.inferenceFramework);
1990
+ const estimatedRuntimeBytes = sizeBytes * multiplier;
1991
+ const memoryGb = typeof deviceInfo?.memoryGb === 'number' && deviceInfo.memoryGb > 0
1992
+ ? deviceInfo.memoryGb
1993
+ : guardrails.unknownMemoryGb;
1994
+ const budgetBytes = guardrails.memoryBudgetFraction * memoryGb * BYTES_PER_GB;
1995
+ if (estimatedRuntimeBytes > budgetBytes) {
1996
+ return {
1997
+ code: 'model_too_large_for_memory',
1998
+ message: `estimated runtime ${Math.round(estimatedRuntimeBytes)} B > budget ${Math.round(budgetBytes)} B ` +
1999
+ `(fraction=${guardrails.memoryBudgetFraction}, multiplier=${multiplier}, memoryGb=${memoryGb})`
2000
+ };
2001
+ }
2002
+ // Heap headroom — Chromium only; other engines expose nothing and the
2003
+ // preflight above stays the only pre-load signal there.
2004
+ const perf = globalThis.performance;
2005
+ const heap = perf?.memory;
2006
+ if (heap && heap.jsHeapSizeLimit > 0 && heap.usedJSHeapSize + estimatedRuntimeBytes > heap.jsHeapSizeLimit) {
2007
+ return {
2008
+ code: 'model_too_large_for_memory',
2009
+ message: `heap used ${heap.usedJSHeapSize} + runtime ${Math.round(estimatedRuntimeBytes)} exceeds limit ${heap.jsHeapSizeLimit}`
2010
+ };
2011
+ }
2012
+ if (stage === 'download') {
2013
+ try {
2014
+ const estimate = await navigator.storage?.estimate?.();
2015
+ if (estimate && typeof estimate.quota === 'number' && typeof estimate.usage === 'number') {
2016
+ const free = estimate.quota - estimate.usage;
2017
+ if (sizeBytes * guardrails.storageHeadroom > free) {
2018
+ return {
2019
+ code: 'storage_quota_exceeded',
2020
+ message: `need ${Math.round(sizeBytes * guardrails.storageHeadroom)} B, quota headroom ${free} B`
2021
+ };
2022
+ }
2023
+ }
2024
+ }
2025
+ catch {
2026
+ // Storage estimate unavailable — skip the check.
2027
+ }
2028
+ }
2029
+ }
2030
+ if (stage === 'download') {
2031
+ const battery = deviceInfo?.battery;
2032
+ if (battery &&
2033
+ typeof battery.level === 'number' &&
2034
+ battery.level < guardrails.minBatteryLevel &&
2035
+ battery.charging !== true) {
2036
+ return {
2037
+ code: 'low_battery',
2038
+ message: `battery ${battery.level} below ${guardrails.minBatteryLevel} and not charging`
2039
+ };
2040
+ }
1283
2041
  }
1284
- return parsed;
1285
- }
1286
- catch {
1287
2042
  return null;
1288
2043
  }
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
2044
  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 };
2045
+ // The gate itself must never break init.
2046
+ return null;
1335
2047
  }
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
2048
  };
1346
2049
 
2050
+ // "Ready" must be proven: a model may only announce `idle` in the hello after
2051
+ // its local warm-up inference completed successfully. Both failure shapes count
2052
+ // — an errored sample AND a completed-but-not-ok one (previously only the
2053
+ // former demoted the model, so an unproven device could claim readiness).
2054
+ function warmUpFailed(sample) {
2055
+ return Boolean(sample.error) || !sample.ok;
2056
+ }
1347
2057
  // Re-registration loop: when the server idle-closes the WebSocket (or it drops
1348
2058
  // for any reason), wait device_timeout_interval_seconds and run the full
1349
2059
  // 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
- };
2060
+ // session key + WS URL. The single pending timer lives in ./reregister so the
2061
+ // shutdown sequence can kill it (§4.7); before reconnecting we check no socket
2062
+ // is already live (infinite-loop guard).
1359
2063
  const resolveReregisterDelaySeconds = () => {
1360
2064
  const value = getRegistrationSettings()?.device_timeout_interval_seconds;
1361
2065
  return typeof value === 'number' && Number.isFinite(value) && value > 0
@@ -1364,14 +2068,17 @@ const resolveReregisterDelaySeconds = () => {
1364
2068
  };
1365
2069
  const scheduleReregistration = (options) => {
1366
2070
  const logger = getLogger();
1367
- if (reregisterTimerId !== null) {
2071
+ if (hasReregisterTimer()) {
1368
2072
  logger.debug('[WS] Re-registration already scheduled; skipping');
1369
2073
  return;
1370
2074
  }
2075
+ if (isShutdown()) {
2076
+ logger.debug('[WS] SDK is shut down; not scheduling re-registration');
2077
+ return;
2078
+ }
1371
2079
  const delaySeconds = resolveReregisterDelaySeconds();
1372
2080
  logger.info('[WS] Scheduling re-registration', { delaySeconds });
1373
- reregisterTimerId = setTimeout(() => {
1374
- reregisterTimerId = null;
2081
+ setReregisterTimer(() => {
1375
2082
  if (getWebSocket()?.isActive()) {
1376
2083
  logger.info('[WS] Active WebSocket present; skipping re-registration');
1377
2084
  return;
@@ -1400,6 +2107,13 @@ const extractRegistrationSettings = (configSettings) => {
1400
2107
  const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
1401
2108
  initLogger(config.telemetry);
1402
2109
  const logger = getLogger();
2110
+ // Shutdown is terminal until the host restarts the SDK (page reload): a
2111
+ // stray timer or caller must not resurrect us into the same conditions.
2112
+ if (isShutdown()) {
2113
+ logger.warn('[Init] SDK is shut down; refusing to start lifecycle');
2114
+ return;
2115
+ }
2116
+ setLifecycleStatus('starting');
1403
2117
  setConfig(config);
1404
2118
  // A fresh (manual or scheduled) start supersedes any pending reconnect timer.
1405
2119
  clearReregisterTimer();
@@ -1422,10 +2136,14 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1422
2136
  const guard = beginInitAttempt();
1423
2137
  if (!guard.allowed) {
1424
2138
  setStatus('error');
2139
+ setLifecycleStatus('error');
1425
2140
  logger.warn('Init skipped: crash-loop guard active', {
1426
2141
  attempts: guard.attempts,
1427
2142
  cooldownRemainingMs: guard.cooldownRemainingMs
1428
2143
  });
2144
+ // Reporter may exist from an earlier run on this page; best-effort only —
2145
+ // on a cold page the offline buffer picks the story up next boot.
2146
+ getEventReporter().report('sdk.init_failed', { code: 'crash_loop' });
1429
2147
  return;
1430
2148
  }
1431
2149
  const bootStartedAt = performance.now();
@@ -1455,6 +2173,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1455
2173
  });
1456
2174
  const reporter = getEventReporter();
1457
2175
  reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2176
+ reportCrashFromPreviousSession(guard.crash);
1458
2177
  logger.info('[Init] Device info collected', {
1459
2178
  platform: sanitizedDeviceInfo.platform,
1460
2179
  deviceType: sanitizedDeviceInfo.deviceType,
@@ -1477,6 +2196,20 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1477
2196
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
1478
2197
  setCachedModelId(cachedModelId);
1479
2198
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
2199
+ // Breaker short-circuit: a blocklisted model must not be validation-loaded
2200
+ // (that load is the exact thing that killed the host) and must not be
2201
+ // advertised in cachedModels. Files stay on disk; the entry lapses in 24 h.
2202
+ if (cachedInfo && isModelBlocklisted(cachedInfo.modelId, cachedInfo.modelVersion)) {
2203
+ reporter.report('guardrail.preflight_blocked', {
2204
+ code: 'model_blocklisted',
2205
+ modelId: cachedInfo.modelId,
2206
+ modelVersion: cachedInfo.modelVersion
2207
+ });
2208
+ logger.warn('[Guard] Cached model is blocklisted; skipping cache validation', {
2209
+ modelId: cachedInfo.modelId
2210
+ });
2211
+ cachedInfo = null;
2212
+ }
1480
2213
  if (!isFreshDevice) {
1481
2214
  logger.info('Cache lookup', {
1482
2215
  cachedModelId,
@@ -1550,6 +2283,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1550
2283
  });
1551
2284
  }
1552
2285
  else {
2286
+ setInitPhase('loading', cachedInfo.modelId, cachedInfo.modelVersion);
1553
2287
  const loadResult = await factory.load(slmConfig, { allowDownload: hasCachedFiles });
1554
2288
  if (!loadResult.adapter || loadResult.error) {
1555
2289
  cacheInvalid = true;
@@ -1569,6 +2303,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1569
2303
  cachedAdapter = loadResult.adapter;
1570
2304
  setAdapter(cachedInfo.modelId, cachedAdapter);
1571
2305
  const sample = cachedInfo.sample;
2306
+ setInitPhase('sampling', cachedInfo.modelId, cachedInfo.modelVersion);
1572
2307
  const sampleResult = await cachedAdapter.runSample(sample);
1573
2308
  cachedSampleMetrics = {
1574
2309
  taskType: cachedInfo.taskType,
@@ -1666,17 +2401,34 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1666
2401
  markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
1667
2402
  throw err;
1668
2403
  }
2404
+ // Settings (incl. server-tuned guardrails) apply on every outcome — a
2405
+ // refusal can still carry the tunables and the re-register interval.
2406
+ const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
2407
+ setRegistrationSettings(registrationSettings);
2408
+ applyRegistrationGuardrails(registrationSettings);
2409
+ if (registrationSettings) {
2410
+ logger.info('[Register] Registration settings received', registrationSettings);
2411
+ }
2412
+ if (registerResponse.refusalReason) {
2413
+ // The server deliberately declined this device (admission rules) — the
2414
+ // opposite of a failure. Exit cleanly, come back on the slow re-register
2415
+ // interval: battery/connection refusals are transient conditions.
2416
+ reporter.report('register.rejected', { code: registerResponse.refusalReason });
2417
+ logger.warn('[Register] Registration refused by server', {
2418
+ reason: registerResponse.refusalReason
2419
+ });
2420
+ setStatus('error');
2421
+ setLifecycleStatus('error');
2422
+ markInitSuccess(); // Clean exit, not a crash loop.
2423
+ scheduleReregistration(lifecycleOptions);
2424
+ return;
2425
+ }
1669
2426
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
1670
2427
  reporter.setSessionKey(registerResponse.sessionKey);
1671
2428
  logger.info('Register response received:', {
1672
2429
  deviceId: registerResponse.deviceId,
1673
2430
  wsUrl: registerResponse.wsUrl
1674
2431
  });
1675
- const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
1676
- setRegistrationSettings(registrationSettings);
1677
- if (registrationSettings) {
1678
- logger.info('[Register] Registration settings received', registrationSettings);
1679
- }
1680
2432
  if (!registerResponse.wsUrl) {
1681
2433
  markInitSuccess(); // Clean exit, not a crash loop.
1682
2434
  return;
@@ -1735,7 +2487,26 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1735
2487
  setAdaptersByModelId({});
1736
2488
  const slmConfig = buildSlmConfigFromAssigned(primaryModel);
1737
2489
  const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
1738
- if (!factory) {
2490
+ // Layer 2/4 preflight: blocklisted or won't-fit models are refused before
2491
+ // any download/allocation. The model is reported `error` in the hello so
2492
+ // the device stays registered and auditable; the host stays alive.
2493
+ const preflightBlock = await preflightAssignedModel(primaryModel);
2494
+ if (preflightBlock) {
2495
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
2496
+ loadErrorMessage = `preflight_blocked:${preflightBlock.code}`;
2497
+ reporter.report('guardrail.preflight_blocked', {
2498
+ code: preflightBlock.code,
2499
+ modelId: primaryModel.modelId,
2500
+ modelVersion: primaryModel.modelVersion,
2501
+ message: preflightBlock.message
2502
+ });
2503
+ logger.warn('[Guard] Primary model blocked by preflight', {
2504
+ modelId: primaryModel.modelId,
2505
+ code: preflightBlock.code,
2506
+ message: preflightBlock.message
2507
+ });
2508
+ }
2509
+ else if (!factory) {
1739
2510
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1740
2511
  loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
1741
2512
  reporter.report('model.load_failed', {
@@ -1759,6 +2530,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1759
2530
  modelRepoId: primaryModel.modelRepoId
1760
2531
  });
1761
2532
  reporter.report('model.load_started', { modelId: primaryModel.modelId, modelVersion: primaryModel.modelVersion });
2533
+ setInitPhase('loading', primaryModel.modelId, primaryModel.modelVersion);
1762
2534
  const primaryLoadStart = performance.now();
1763
2535
  const loadResult = await factory.load(slmConfig);
1764
2536
  const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
@@ -1845,6 +2617,18 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1845
2617
  });
1846
2618
  continue;
1847
2619
  }
2620
+ const secondaryBlock = await preflightAssignedModel(model);
2621
+ if (secondaryBlock) {
2622
+ modelStatuses[getModelStatusKey(model)] = 'error';
2623
+ reporter.report('guardrail.preflight_blocked', {
2624
+ code: secondaryBlock.code,
2625
+ modelId: model.modelId,
2626
+ modelVersion: model.modelVersion,
2627
+ message: secondaryBlock.message
2628
+ });
2629
+ continue;
2630
+ }
2631
+ setInitPhase('loading', model.modelId, model.modelVersion);
1848
2632
  const loadResult = await factory.load(slmConfig);
1849
2633
  if (loadResult.adapter) {
1850
2634
  adaptersByModelId[model.modelId] = loadResult.adapter;
@@ -1902,6 +2686,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1902
2686
  logger.info('[Sample] Running post-register sample inference', {
1903
2687
  taskType: primaryModel.taskType
1904
2688
  });
2689
+ setInitPhase('sampling', primaryModel.modelId, primaryModel.modelVersion);
1905
2690
  postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1906
2691
  const sampleLog = {
1907
2692
  taskType: primaryModel.taskType,
@@ -1910,7 +2695,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1910
2695
  errorMessage: postRegisterSample.errorMessage,
1911
2696
  processingTimeMs: postRegisterSample.processingTimeMs
1912
2697
  };
1913
- if (postRegisterSample.error || !postRegisterSample.ok) {
2698
+ if (warmUpFailed(postRegisterSample)) {
1914
2699
  reporter.report('model.sample_failed', {
1915
2700
  modelId: primaryModel.modelId,
1916
2701
  durationMs: postRegisterSample.processingTimeMs,
@@ -1918,6 +2703,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1918
2703
  data: { phase: 'post_register' }
1919
2704
  });
1920
2705
  logger.error('[Sample] Post-register sample failed', sampleLog);
2706
+ // "Ready" must be proven: any warm-up that did not complete successfully
2707
+ // (errored OR merely not-ok) demotes the model to error in the hello, so
2708
+ // the registry never lists an unproven device for dispatch.
2709
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1921
2710
  }
1922
2711
  else {
1923
2712
  reporter.report('model.sample_succeeded', {
@@ -1927,9 +2716,6 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1927
2716
  });
1928
2717
  logger.info('[Sample] Post-register sample ok', sampleLog);
1929
2718
  }
1930
- if (postRegisterSample.error) {
1931
- modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1932
- }
1933
2719
  }
1934
2720
  const helloDeviceId = registerResponse.deviceId;
1935
2721
  const helloSlmConfig = assignedModels.map((model) => ({
@@ -1994,6 +2780,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1994
2780
  });
1995
2781
  setWebSocket(client);
1996
2782
  setStatus('idle');
2783
+ // Model phases are behind us; a death from here on is not model-attributed.
2784
+ setInitPhase('running', primaryModel.modelId, primaryModel.modelVersion);
2785
+ setLifecycleStatus('running');
2786
+ startWatchdog();
1997
2787
  reporter.report('sdk.init_succeeded', { durationMs: Math.round(performance.now() - bootStartedAt) });
1998
2788
  logger.info('[Init] SDK ready', {
1999
2789
  deviceId,
@@ -2022,6 +2812,8 @@ const mapRegisterErrorCode = (err) => {
2022
2812
  const mapModelLoadErrorCode = (message) => {
2023
2813
  if (!message)
2024
2814
  return 'init_error';
2815
+ if (/preflight_blocked/.test(message))
2816
+ return 'guardrail_blocked';
2025
2817
  if (/no_adapter_factory/.test(message))
2026
2818
  return 'no_adapter_factory';
2027
2819
  if (/oom|out of memory|RangeError/i.test(message))
@@ -2030,6 +2822,44 @@ const mapModelLoadErrorCode = (message) => {
2030
2822
  return 'wasm_abort';
2031
2823
  return 'init_error';
2032
2824
  };
2825
+ /** Blocklist short-circuit, then the ResourceGate — before any I/O for a model. */
2826
+ const preflightAssignedModel = async (model) => {
2827
+ if (isModelBlocklisted(model.modelId, model.modelVersion)) {
2828
+ return { code: 'model_blocklisted', message: 'blocklisted after repeated crashes during load' };
2829
+ }
2830
+ let deviceInfo;
2831
+ try {
2832
+ deviceInfo = getState().deviceInfo;
2833
+ }
2834
+ catch {
2835
+ deviceInfo = undefined;
2836
+ }
2837
+ return evaluateResourceGate({
2838
+ modelId: model.modelId,
2839
+ modelVersion: model.modelVersion,
2840
+ sizeBytes: model.sizeBytes,
2841
+ inferenceFramework: model.inferenceFramework
2842
+ }, 'download', deviceInfo);
2843
+ };
2844
+ /** The previous process died mid-phase — attribute it now that the reporter is live. */
2845
+ const reportCrashFromPreviousSession = (crash) => {
2846
+ if (!crash)
2847
+ return;
2848
+ const reporter = getEventReporter();
2849
+ reporter.report('sdk.crash_detected', {
2850
+ code: crash.code,
2851
+ modelId: crash.modelId,
2852
+ modelVersion: crash.modelVersion,
2853
+ data: { phase: crash.phase }
2854
+ });
2855
+ if (crash.blocklistedModel) {
2856
+ reporter.report('guardrail.model_blocklisted', {
2857
+ modelId: crash.modelId,
2858
+ modelVersion: crash.modelVersion,
2859
+ message: crash.blocklistedModel
2860
+ });
2861
+ }
2862
+ };
2033
2863
  const normalizeAssignedModels = (slmConfig) => {
2034
2864
  if (!Array.isArray(slmConfig))
2035
2865
  return [];
@@ -3480,18 +4310,47 @@ const factory = {
3480
4310
  registerAdapter(factory);
3481
4311
 
3482
4312
  let initialized = false;
4313
+ const handle = {
4314
+ get status() {
4315
+ return getLifecycleStatus();
4316
+ },
4317
+ on: onHostEvent,
4318
+ shutdown: () => runShutdownSequence({ reason: 'host_stop' })
4319
+ };
4320
+ /**
4321
+ * Never rejects: the SDK is a guest in someone else's app, and a failed init
4322
+ * must degrade to "SDK not running" — observable via `handle.status` and the
4323
+ * reported `sdk.init_failed` events — never to an unhandled rejection in the
4324
+ * host. Existing `await initZeroGpuSdk(...)` callers are unaffected (the
4325
+ * returned handle is additive).
4326
+ */
3483
4327
  const initZeroGpuSdk = async (options) => {
3484
4328
  if (initialized) {
3485
- return;
4329
+ return handle;
3486
4330
  }
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
4331
  initialized = true;
4332
+ if (options?.resourcePolicy) {
4333
+ setResourcePolicy(options.resourcePolicy);
4334
+ if (options.resourcePolicy.disableGuardrails) {
4335
+ // Loud by design: a host running without guardrails should know it.
4336
+ console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
4337
+ }
4338
+ }
4339
+ const config = resolveConfig(options?.overrides);
4340
+ try {
4341
+ await startLifecycle({
4342
+ config,
4343
+ appUserId: options?.appUserId,
4344
+ edgeOperatorKey: options?.edgeOperatorKey,
4345
+ deviceId: options?.deviceId
4346
+ });
4347
+ }
4348
+ catch (err) {
4349
+ // Already reported inside the lifecycle (register.failed / sdk.init_failed
4350
+ // / init-failure hello); surface for the host without throwing into it.
4351
+ getLogger().error('[Init] SDK initialization failed', err);
4352
+ }
4353
+ return handle;
3495
4354
  };
3496
4355
 
3497
4356
  const readAttr = (script, names) => {