@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,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const SDK_VERSION = typeof "0.1.7+371d38a" === 'string' && "0.1.7+371d38a".length > 0
4
- ? "0.1.7+371d38a"
3
+ const SDK_VERSION = typeof "0.2.0-dev.202607221142.g1c6b982+1c6b982" === 'string' && "0.2.0-dev.202607221142.g1c6b982+1c6b982".length > 0
4
+ ? "0.2.0-dev.202607221142.g1c6b982+1c6b982"
5
5
  : '0.0.0-dev';
6
6
 
7
7
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -387,18 +387,29 @@ const parseRegisterResponseBody = async (response) => {
387
387
  return null;
388
388
  }
389
389
  };
390
- const isEdgeSdkTypeNotAllowedResponse = (payload) => {
390
+ /**
391
+ * Detects the server's "polite refusal" envelope: HTTP 200, `status: 'ok'`,
392
+ * and a reason/code — used for `edge_sdk_type_not_allowed` and for every
393
+ * admission-guard refusal (`model_too_large_for_memory`, `low_battery`,
394
+ * `guardrail_blocked`, …). Returns the reason code, or null.
395
+ */
396
+ const detectSoftRefusal = (payload) => {
391
397
  if (!payload || typeof payload !== 'object') {
392
- return false;
398
+ return null;
393
399
  }
394
400
  const body = payload;
395
401
  const status = typeof body.status === 'string' ? body.status.toLowerCase() : '';
396
402
  if (status !== 'ok') {
397
- return false;
403
+ return null;
398
404
  }
399
405
  const nestedError = body.error;
400
406
  const candidateCodes = [body.code, body.errorCode, body.reason, nestedError?.code];
401
- return candidateCodes.some((value) => typeof value === 'string' && value.toLowerCase() === 'edge_sdk_type_not_allowed');
407
+ for (const value of candidateCodes) {
408
+ if (typeof value === 'string' && value.trim().length > 0) {
409
+ return value.trim().toLowerCase();
410
+ }
411
+ }
412
+ return null;
402
413
  };
403
414
  const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
404
415
  const buildCurl = (url, body, headers) => {
@@ -427,24 +438,27 @@ const registerDevice = async (config, payload, auth) => {
427
438
  logger.info('Register request sent:', { url, status: response.status });
428
439
  getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
429
440
  const registerResponseBody = await parseRegisterResponseBody(response);
430
- const edgeSdkTypeNotAllowed = isEdgeSdkTypeNotAllowedResponse(registerResponseBody);
431
- if (!response.ok && !edgeSdkTypeNotAllowed) {
441
+ const refusalReason = detectSoftRefusal(registerResponseBody);
442
+ if (!response.ok && !refusalReason) {
432
443
  const text = typeof registerResponseBody === 'string'
433
444
  ? registerResponseBody
434
445
  : JSON.stringify(registerResponseBody ?? '');
435
446
  logger.error('Register request failed:', { status: response.status, text });
436
447
  throw new RegisterError(response.status, text);
437
448
  }
438
- if (registerResponseBody && typeof registerResponseBody === 'object' && !edgeSdkTypeNotAllowed) {
449
+ if (registerResponseBody && typeof registerResponseBody === 'object' && !refusalReason) {
439
450
  const registerResponse = registerResponseBody;
440
451
  logger.info('Register response parsed:', registerResponse);
441
452
  return registerResponse;
442
453
  }
443
- if (edgeSdkTypeNotAllowed) {
454
+ if (refusalReason) {
455
+ // A refusal is still a conversation, not an error: synthesize an accepted
456
+ // response with no wsUrl and carry the reason so the lifecycle can exit
457
+ // cleanly (and pick up any configSettings the server included).
444
458
  const responseObject = registerResponseBody && typeof registerResponseBody === 'object'
445
459
  ? registerResponseBody
446
460
  : {};
447
- const acceptedResponse = {
461
+ const refusedResponse = {
448
462
  deviceId: typeof responseObject.deviceId === 'string' && responseObject.deviceId
449
463
  ? responseObject.deviceId
450
464
  : payload.deviceId,
@@ -452,14 +466,18 @@ const registerDevice = async (config, payload, auth) => {
452
466
  wsUrl: typeof responseObject.wsUrl === 'string' ? responseObject.wsUrl : '',
453
467
  active: typeof responseObject.active === 'boolean' ? responseObject.active : false,
454
468
  ttlSeconds: typeof responseObject.ttlSeconds === 'number' ? responseObject.ttlSeconds : 0,
469
+ refusalReason,
470
+ configSettings: responseObject.configSettings && typeof responseObject.configSettings === 'object'
471
+ ? responseObject.configSettings
472
+ : undefined,
455
473
  slmConfig: typeof responseObject.slmConfig !== 'undefined'
456
474
  ? responseObject.slmConfig
457
475
  : typeof responseObject.modelInfo !== 'undefined'
458
476
  ? [responseObject.modelInfo]
459
477
  : undefined
460
478
  };
461
- logger.info('Handled edge_sdk_type_not_allowed register response');
462
- return acceptedResponse;
479
+ logger.info('Register politely refused by server', { reason: refusalReason });
480
+ return refusedResponse;
463
481
  }
464
482
  throw new RegisterError(response.status, 'Register response body is not valid JSON');
465
483
  };
@@ -540,8 +558,14 @@ class WebSocketClient {
540
558
  this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
541
559
  this.socket.send(JSON.stringify(payload));
542
560
  }
543
- close() {
544
- this.socket.close();
561
+ close(code, reason) {
562
+ if (typeof code === 'number') {
563
+ // Close reasons are capped at 123 bytes by the WS protocol.
564
+ this.socket.close(code, (reason ?? '').slice(0, 120));
565
+ }
566
+ else {
567
+ this.socket.close();
568
+ }
545
569
  }
546
570
  }
547
571
 
@@ -974,6 +998,656 @@ const initEventReporter = (options) => {
974
998
  };
975
999
  const getEventReporter = () => singleton ?? NOOP;
976
1000
 
1001
+ /**
1002
+ * Host-facing lifecycle status and events. The SDK is a guest in someone
1003
+ * else's app: this module is how the host observes guardrail state (degraded /
1004
+ * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1005
+ * consumers get the same signals as `zerogpu:*` window events, matching the
1006
+ * existing `zerogpu:cameraPreview` pattern.
1007
+ */
1008
+ let lifecycleStatus = 'starting';
1009
+ const listeners = {
1010
+ degraded: new Set(),
1011
+ recovered: new Set(),
1012
+ shutdown: new Set()
1013
+ };
1014
+ const getLifecycleStatus = () => lifecycleStatus;
1015
+ const setLifecycleStatus = (status) => {
1016
+ // Shutdown is terminal (state machine B.3): recovery exists only from
1017
+ // warn/degrade, never from shutdown.
1018
+ if (lifecycleStatus === 'shutdown')
1019
+ return;
1020
+ lifecycleStatus = status;
1021
+ };
1022
+ const isShutdown = () => lifecycleStatus === 'shutdown';
1023
+ /** Degraded and shutting-down SDKs finish in-flight work but accept nothing new. */
1024
+ const isTaskGateActive = () => lifecycleStatus === 'degraded' || lifecycleStatus === 'shutdown';
1025
+ const onHostEvent = (name, listener) => {
1026
+ listeners[name]?.add(listener);
1027
+ return () => listeners[name]?.delete(listener);
1028
+ };
1029
+ const emitHostEvent = (name, detail = {}) => {
1030
+ for (const listener of listeners[name] ?? []) {
1031
+ try {
1032
+ listener(detail);
1033
+ }
1034
+ catch {
1035
+ // A host listener bug must never propagate into the SDK.
1036
+ }
1037
+ }
1038
+ try {
1039
+ if (typeof window !== 'undefined') {
1040
+ window.dispatchEvent(new CustomEvent(`zerogpu:${name}`, { detail }));
1041
+ }
1042
+ }
1043
+ catch {
1044
+ // ignore
1045
+ }
1046
+ };
1047
+
1048
+ const DEFAULT_FRAMEWORK_MULTIPLIERS = {
1049
+ onnx: 2.0,
1050
+ transformersjs: 2.5,
1051
+ transformers: 2.5,
1052
+ gguf: 1.4
1053
+ };
1054
+ const DEFAULT_FRAMEWORK_MULTIPLIER = 2.0;
1055
+ const DEFAULT_MEMORY_BUDGET_FRACTION = 0.3;
1056
+ /** Battery floor below which a discharging device defers model downloads. */
1057
+ const DEFAULT_MIN_BATTERY_LEVEL = 0.2;
1058
+ /** Downloads need headroom beyond the file size (IndexedDB overhead, temp copies). */
1059
+ const DEFAULT_STORAGE_HEADROOM = 1.2;
1060
+ /** Devices that report no memory are treated as modest 2 GB devices (same as the server). */
1061
+ const UNKNOWN_DEVICE_MEMORY_GB = 2;
1062
+ const DEFAULT_WATCHDOG = {
1063
+ warnPct: 0.7,
1064
+ degradePct: 0.85,
1065
+ shutdownPct: 0.95,
1066
+ sampleMs: 10000,
1067
+ recoverPct: 0.6,
1068
+ recoverHoldMs: 60000
1069
+ };
1070
+ let policy = {};
1071
+ let resolved = resolve(null);
1072
+ function positive(value) {
1073
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
1074
+ }
1075
+ function resolve(settings) {
1076
+ const watchdog = settings?.watchdog ?? {};
1077
+ // Non-positive served multipliers are treated as absent (same semantics as
1078
+ // the registry) so a bad settings edit cannot zero out the memory gate.
1079
+ const servedMultipliers = Object.fromEntries(Object.entries(settings?.frameworkMultipliers ?? {}).filter(([, v]) => positive(v) !== undefined));
1080
+ return {
1081
+ memoryBudgetFraction: positive(policy.memoryBudgetFraction) ??
1082
+ positive(settings?.memoryBudgetFraction) ??
1083
+ DEFAULT_MEMORY_BUDGET_FRACTION,
1084
+ frameworkMultipliers: {
1085
+ ...DEFAULT_FRAMEWORK_MULTIPLIERS,
1086
+ ...servedMultipliers
1087
+ },
1088
+ minBatteryLevel: positive(settings?.minBatteryLevel) ?? DEFAULT_MIN_BATTERY_LEVEL,
1089
+ storageHeadroom: positive(settings?.storageHeadroom) ?? DEFAULT_STORAGE_HEADROOM,
1090
+ unknownMemoryGb: positive(settings?.unknownMemoryGb) ?? UNKNOWN_DEVICE_MEMORY_GB,
1091
+ watchdog: {
1092
+ warnPct: positive(watchdog.warnPct) ?? DEFAULT_WATCHDOG.warnPct,
1093
+ degradePct: positive(watchdog.degradePct) ?? DEFAULT_WATCHDOG.degradePct,
1094
+ shutdownPct: positive(watchdog.shutdownPct) ?? DEFAULT_WATCHDOG.shutdownPct,
1095
+ sampleMs: positive(watchdog.sampleMs) ?? DEFAULT_WATCHDOG.sampleMs,
1096
+ recoverPct: positive(watchdog.recoverPct) ?? DEFAULT_WATCHDOG.recoverPct,
1097
+ recoverHoldMs: positive(watchdog.recoverHoldMs) ?? DEFAULT_WATCHDOG.recoverHoldMs
1098
+ }
1099
+ };
1100
+ }
1101
+ const setResourcePolicy = (next) => {
1102
+ policy = next ?? {};
1103
+ resolved = resolve(null);
1104
+ };
1105
+ const getResourcePolicy = () => policy;
1106
+ /** Called after every register with the server-tuned block (or null). */
1107
+ const applyRegistrationGuardrails = (settings) => {
1108
+ resolved = resolve(settings?.guardrails ?? null);
1109
+ };
1110
+ const getGuardrails = () => resolved;
1111
+ const multiplierFor = (framework) => {
1112
+ const key = framework?.trim().toLowerCase() ?? '';
1113
+ return resolved.frameworkMultipliers[key] ?? DEFAULT_FRAMEWORK_MULTIPLIER;
1114
+ };
1115
+ /**
1116
+ * The catalog's size column is megabytes but travels as `sizeBytes` unchanged
1117
+ * (deberta-v3-small -> 184). Values below 1e6 cannot be real byte counts for
1118
+ * an on-device model — interpret them as MB, identically to the registry.
1119
+ */
1120
+ const normalizeModelSizeBytes = (raw) => {
1121
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0)
1122
+ return 0;
1123
+ return raw < 1000000 ? raw * 1024 * 1024 : raw;
1124
+ };
1125
+
1126
+ /**
1127
+ * Crash-loop guard for SDK initialization, extended into the Layer 4 crash
1128
+ * marker + per-model breaker.
1129
+ *
1130
+ * On a brand-new device the lifecycle synchronously downloads and instantiates
1131
+ * a full model (and runs a sample inference) before connecting the WebSocket.
1132
+ * In a memory-constrained host such as a Telegram mini-app WebView this burst
1133
+ * can crash/OOM the view; the host reloads, the SDK repeats the same heavy
1134
+ * path, and the app "refreshes continuously".
1135
+ *
1136
+ * Two mechanisms share one persisted state (`zerogpu_init_state`):
1137
+ *
1138
+ * - the original attempt counter: several uncompleted attempts in a short
1139
+ * window trip a cool-down that skips heavy init entirely;
1140
+ * - the crash marker: a `phase` written before each dangerous step
1141
+ * (load/sample) and cleared on graceful shutdown. A phase surviving to the
1142
+ * next boot means the process died mid-step — that boot reports
1143
+ * `sdk.crash_detected`, and two deaths during one model's risky phases in
1144
+ * 24 h blocklist that model for 24 h so a single oversized model can't take
1145
+ * the host down repeatedly.
1146
+ */
1147
+ const INIT_STATE_KEY = 'zerogpu_init_state';
1148
+ /** Attempts that never completed are only counted within this rolling window. */
1149
+ const ATTEMPT_WINDOW_MS = 60000;
1150
+ /** Number of uncompleted attempts in the window that trips the cool-down. */
1151
+ const MAX_ATTEMPTS_IN_WINDOW = 3;
1152
+ /** How long to skip heavy init once a crash loop is detected. */
1153
+ const COOLDOWN_MS = 5 * 60000;
1154
+ /** Phases where a process death points at the model itself. */
1155
+ const RISKY_PHASES = new Set(['downloading', 'loading', 'sampling']);
1156
+ const CRASH_WINDOW_MS = 24 * 60 * 60 * 1000;
1157
+ const BLOCKLIST_MS = 24 * 60 * 60 * 1000;
1158
+ const CRASHES_TO_BLOCKLIST = 2;
1159
+ const readState = () => {
1160
+ try {
1161
+ const raw = window.localStorage.getItem(INIT_STATE_KEY);
1162
+ if (!raw)
1163
+ return null;
1164
+ const parsed = JSON.parse(raw);
1165
+ if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
1166
+ return null;
1167
+ }
1168
+ return parsed;
1169
+ }
1170
+ catch {
1171
+ return null;
1172
+ }
1173
+ };
1174
+ const writeState = (state) => {
1175
+ try {
1176
+ window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
1177
+ }
1178
+ catch {
1179
+ // Storage may be unavailable/partitioned; degrade silently.
1180
+ }
1181
+ };
1182
+ const modelKey = (modelId, modelVersion) => `${modelId}@${modelVersion ?? '1'}`;
1183
+ /** The breaker/marker fields that must survive attempt resets and successes. */
1184
+ const persistentFields = (state) => ({
1185
+ modelCrashes: state?.modelCrashes,
1186
+ blocklist: state?.blocklist,
1187
+ lastShutdown: state?.lastShutdown
1188
+ });
1189
+ const pruneBlocklist = (blocklist, now) => {
1190
+ if (!blocklist)
1191
+ return undefined;
1192
+ const live = Object.fromEntries(Object.entries(blocklist).filter(([, entry]) => entry.until > now));
1193
+ return Object.keys(live).length > 0 ? live : undefined;
1194
+ };
1195
+ /**
1196
+ * Extracts crash info from a surviving phase and applies the breaker rule.
1197
+ * Returns the mutated persistent fields plus the report for the caller.
1198
+ */
1199
+ const consumeCrashMarker = (state, now) => {
1200
+ let modelCrashes = state?.modelCrashes;
1201
+ let blocklist = pruneBlocklist(state?.blocklist, now);
1202
+ const phase = state?.phase;
1203
+ if (!phase)
1204
+ return { modelCrashes, blocklist };
1205
+ const risky = RISKY_PHASES.has(phase);
1206
+ let blocklistedModel;
1207
+ if (risky && state?.modelId) {
1208
+ const key = modelKey(state.modelId, state.modelVersion);
1209
+ const prior = modelCrashes?.[key];
1210
+ const inWindow = prior && now - prior.firstAt < CRASH_WINDOW_MS;
1211
+ const count = inWindow ? prior.count + 1 : 1;
1212
+ modelCrashes = { ...(modelCrashes ?? {}), [key]: { count, firstAt: inWindow ? prior.firstAt : now } };
1213
+ if (count >= CRASHES_TO_BLOCKLIST) {
1214
+ blocklist = { ...(blocklist ?? {}), [key]: { until: now + BLOCKLIST_MS } };
1215
+ blocklistedModel = key;
1216
+ }
1217
+ }
1218
+ return {
1219
+ crash: {
1220
+ code: risky ? 'oom_suspected' : 'unknown',
1221
+ phase,
1222
+ modelId: state?.modelId,
1223
+ modelVersion: state?.modelVersion,
1224
+ blocklistedModel
1225
+ },
1226
+ modelCrashes,
1227
+ blocklist
1228
+ };
1229
+ };
1230
+ /**
1231
+ * Records the start of an init attempt and decides whether heavy init may
1232
+ * proceed. Must be called once, before any heavy work, on every lifecycle start.
1233
+ */
1234
+ const beginInitAttempt = (now = Date.now()) => {
1235
+ const state = readState();
1236
+ // A surviving phase means the last process died mid-step; consume it first
1237
+ // so the crash is attributed exactly once.
1238
+ const { crash, modelCrashes, blocklist } = consumeCrashMarker(state, now);
1239
+ const persistent = {
1240
+ modelCrashes,
1241
+ blocklist,
1242
+ lastShutdown: state?.lastShutdown
1243
+ };
1244
+ // Still inside an active cool-down from a previously detected crash loop.
1245
+ if (state?.cooldownUntil && state.cooldownUntil > now) {
1246
+ writeState({ ...state, phase: undefined, modelId: undefined, modelVersion: undefined, ...persistent });
1247
+ return {
1248
+ allowed: false,
1249
+ cooldownRemainingMs: state.cooldownUntil - now,
1250
+ attempts: state.attempts,
1251
+ crash
1252
+ };
1253
+ }
1254
+ // No prior state, or the previous window/cool-down has elapsed → start fresh.
1255
+ if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
1256
+ writeState({ attempts: 1, windowStart: now, ...persistent });
1257
+ return { allowed: true, attempts: 1, crash };
1258
+ }
1259
+ const attempts = state.attempts + 1;
1260
+ // Too many uncompleted attempts in the window → assume a crash loop and back
1261
+ // off so the host app stops reloading.
1262
+ if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
1263
+ writeState({
1264
+ attempts,
1265
+ windowStart: state.windowStart,
1266
+ cooldownUntil: now + COOLDOWN_MS,
1267
+ ...persistent
1268
+ });
1269
+ return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts, crash };
1270
+ }
1271
+ writeState({ attempts, windowStart: state.windowStart, ...persistent });
1272
+ return { allowed: true, attempts, crash };
1273
+ };
1274
+ /**
1275
+ * Clears crash-loop tracking. Call once init reaches a stable point (e.g. the
1276
+ * WebSocket is connected), so successful loads never accumulate toward a trip.
1277
+ * Breaker history and the current phase survive — only the attempt counter
1278
+ * resets.
1279
+ */
1280
+ const markInitSuccess = () => {
1281
+ const state = readState();
1282
+ writeState({
1283
+ attempts: 0,
1284
+ windowStart: Date.now(),
1285
+ phase: state?.phase,
1286
+ modelId: state?.modelId,
1287
+ modelVersion: state?.modelVersion,
1288
+ ...persistentFields(state)
1289
+ });
1290
+ };
1291
+ /** Written before every dangerous step so an unclean death is attributable. */
1292
+ const setInitPhase = (phase, modelId, modelVersion) => {
1293
+ const state = readState();
1294
+ writeState({
1295
+ attempts: state?.attempts ?? 0,
1296
+ windowStart: state?.windowStart ?? Date.now(),
1297
+ cooldownUntil: state?.cooldownUntil,
1298
+ phase,
1299
+ modelId,
1300
+ modelVersion,
1301
+ ...persistentFields(state)
1302
+ });
1303
+ };
1304
+ /** The graceful shutdown sequence ran — the next boot must not count a crash. */
1305
+ const markCleanShutdown = (code) => {
1306
+ const state = readState();
1307
+ writeState({
1308
+ attempts: state?.attempts ?? 0,
1309
+ windowStart: state?.windowStart ?? Date.now(),
1310
+ cooldownUntil: state?.cooldownUntil,
1311
+ modelCrashes: state?.modelCrashes,
1312
+ blocklist: state?.blocklist,
1313
+ lastShutdown: { code, ts: Date.now() }
1314
+ });
1315
+ };
1316
+ /** Blocklisted models are refused before any I/O (breaker, Layer 4). */
1317
+ const isModelBlocklisted = (modelId, modelVersion) => {
1318
+ const state = readState();
1319
+ const entry = state?.blocklist?.[modelKey(modelId, modelVersion)];
1320
+ return Boolean(entry && entry.until > Date.now());
1321
+ };
1322
+
1323
+ /**
1324
+ * The single pending re-registration timer, isolated so both the lifecycle
1325
+ * (which schedules it) and the shutdown sequence (which must kill it — §4.7:
1326
+ * a guardrail shutdown closes the socket, and without this the re-register
1327
+ * loop would resurrect the SDK into the same memory conditions) can reach it
1328
+ * without importing each other.
1329
+ */
1330
+ let reregisterTimerId = null;
1331
+ const hasReregisterTimer = () => reregisterTimerId !== null;
1332
+ const setReregisterTimer = (callback, delayMs) => {
1333
+ clearReregisterTimer();
1334
+ reregisterTimerId = setTimeout(() => {
1335
+ reregisterTimerId = null;
1336
+ callback();
1337
+ }, delayMs);
1338
+ };
1339
+ const clearReregisterTimer = () => {
1340
+ if (reregisterTimerId !== null) {
1341
+ clearTimeout(reregisterTimerId);
1342
+ reregisterTimerId = null;
1343
+ }
1344
+ };
1345
+
1346
+ /** Guardrail shutdown close code; the registry records it as `close_4002`. */
1347
+ const CLOSE_GUARDRAIL = 4002;
1348
+ const CLOSE_NORMAL = 1000;
1349
+ /**
1350
+ * Client→server status update on the live session. The registry's
1351
+ * DeviceSession accepts a hello_ack-shaped message from an authenticated
1352
+ * socket and flips the device `idle`/`error` — the degrade/recover wire
1353
+ * contract, no new message type needed.
1354
+ */
1355
+ const sendStatusUpdate = (status) => {
1356
+ try {
1357
+ const state = getState();
1358
+ const ws = state.ws;
1359
+ if (!ws?.isActive() || !state.sessionKey)
1360
+ return;
1361
+ ws.send({
1362
+ type: 'hello_ack',
1363
+ deviceId: state.deviceId,
1364
+ sdkVersion: state.config.sdkVersion,
1365
+ sessionKey: state.sessionKey,
1366
+ status,
1367
+ timestamp: Date.now()
1368
+ });
1369
+ }
1370
+ catch {
1371
+ // Best effort only.
1372
+ }
1373
+ };
1374
+ /**
1375
+ * The ordered shutdown sequence (GRACEFUL_SHUTDOWN_IMPLEMENTATION.md §5):
1376
+ * mark terminal + kill the re-register loop → gate input → tell the server →
1377
+ * report + beacon-flush → free memory largest-first → mark the exit clean →
1378
+ * notify the host. Every step individually guarded; target ≤ 1 s. Terminal:
1379
+ * `startLifecycle` refuses to run again until the page restarts the SDK.
1380
+ */
1381
+ const runShutdownSequence = async ({ reason, guardrail = false }) => {
1382
+ if (getLifecycleStatus() === 'shutdown')
1383
+ return;
1384
+ const logger = getLogger();
1385
+ logger.warn('[Shutdown] Running shutdown sequence', { reason, guardrail });
1386
+ // 0. Terminal state — gates the router, blocks startLifecycle, and stops the
1387
+ // re-register loop from resurrecting us into the same conditions (§4.7).
1388
+ setLifecycleStatus('shutdown');
1389
+ clearReregisterTimer();
1390
+ // 1–2. Tell the server (best effort), then close with the right code.
1391
+ try {
1392
+ if (guardrail)
1393
+ sendStatusUpdate('error');
1394
+ }
1395
+ catch {
1396
+ /* best effort */
1397
+ }
1398
+ try {
1399
+ getWebSocket()?.close(guardrail ? CLOSE_GUARDRAIL : CLOSE_NORMAL, reason);
1400
+ }
1401
+ catch {
1402
+ /* best effort */
1403
+ }
1404
+ try {
1405
+ setWebSocket(undefined);
1406
+ setStatus('error');
1407
+ }
1408
+ catch {
1409
+ /* state may not be initialized */
1410
+ }
1411
+ // 3. Report + flush before anything else can kill the page. Failure is fine:
1412
+ // the offline buffer drains next boot.
1413
+ const reporter = getEventReporter();
1414
+ reporter.report(guardrail ? 'guardrail.shutdown' : 'sdk.shutdown', { code: reason });
1415
+ try {
1416
+ reporter.flush({ beacon: true });
1417
+ }
1418
+ catch {
1419
+ /* offline buffer covers it */
1420
+ }
1421
+ // 4. Free memory largest-first; files stay on disk (re-download is the
1422
+ // expensive part, and the trigger here is memory, not storage).
1423
+ try {
1424
+ const { adaptersByModelId, modelInfosByModelId } = getState();
1425
+ const entries = Object.entries(adaptersByModelId ?? {}).sort(([a], [b]) => normalizeModelSizeBytes(modelInfosByModelId?.[b]?.sizeBytes) -
1426
+ normalizeModelSizeBytes(modelInfosByModelId?.[a]?.sizeBytes));
1427
+ for (const [, adapter] of entries) {
1428
+ try {
1429
+ await adapter.dispose?.();
1430
+ }
1431
+ catch {
1432
+ /* a failing dispose must not stop the sequence */
1433
+ }
1434
+ }
1435
+ setAdaptersByModelId({});
1436
+ }
1437
+ catch {
1438
+ /* state may not be initialized */
1439
+ }
1440
+ // 5. Mark the exit clean so the next boot isn't counted as a crash.
1441
+ markCleanShutdown(reason);
1442
+ // 6. Notify the host.
1443
+ emitHostEvent('shutdown', { code: reason });
1444
+ };
1445
+
1446
+ class WatchdogLadder {
1447
+ constructor(thresholds, budgetBytes) {
1448
+ this.thresholds = thresholds;
1449
+ this.budgetBytes = budgetBytes;
1450
+ this.belowRecoverSince = null;
1451
+ this.state = 'normal';
1452
+ }
1453
+ /** Maps a memory sample to the raw action the ladder calls for, if any. */
1454
+ onSample(usedBytes, now) {
1455
+ if (this.budgetBytes <= 0)
1456
+ return null;
1457
+ const used = usedBytes / this.budgetBytes;
1458
+ const t = this.thresholds;
1459
+ if (used > t.shutdownPct)
1460
+ return 'shutdown';
1461
+ if (used > t.degradePct)
1462
+ return 'degrade';
1463
+ if (used > t.warnPct)
1464
+ return 'warn';
1465
+ if (used < t.recoverPct && this.state !== 'normal') {
1466
+ if (this.belowRecoverSince === null)
1467
+ this.belowRecoverSince = now;
1468
+ return now - this.belowRecoverSince >= t.recoverHoldMs ? 'recover' : null;
1469
+ }
1470
+ this.belowRecoverSince = null;
1471
+ return null;
1472
+ }
1473
+ /** Applies an action; returns it only when it is a real state transition. */
1474
+ transition(action) {
1475
+ if (this.state === 'shutdown')
1476
+ return null;
1477
+ switch (action) {
1478
+ case 'shutdown':
1479
+ this.state = 'shutdown';
1480
+ return 'shutdown';
1481
+ case 'degrade':
1482
+ this.belowRecoverSince = null;
1483
+ if (this.state === 'degraded')
1484
+ return null;
1485
+ this.state = 'degraded';
1486
+ return 'degrade';
1487
+ case 'warn':
1488
+ this.belowRecoverSince = null;
1489
+ // Warn never downgrades an active degrade.
1490
+ if (this.state !== 'normal')
1491
+ return null;
1492
+ this.state = 'warn';
1493
+ return 'warn';
1494
+ case 'recover':
1495
+ this.belowRecoverSince = null;
1496
+ if (this.state === 'normal')
1497
+ return null;
1498
+ this.state = 'normal';
1499
+ return 'recover';
1500
+ }
1501
+ }
1502
+ }
1503
+ let timerId = null;
1504
+ const readHeapUsedBytes = () => {
1505
+ const perf = globalThis.performance;
1506
+ const used = perf?.memory?.usedJSHeapSize;
1507
+ return typeof used === 'number' && used > 0 ? used : null;
1508
+ };
1509
+ const act = (ladder, action) => {
1510
+ const transition = action ? ladder.transition(action) : null;
1511
+ if (!transition)
1512
+ return;
1513
+ const reporter = getEventReporter();
1514
+ switch (transition) {
1515
+ case 'warn':
1516
+ reporter.report('guardrail.pressure_warning', { code: 'memory_pressure' });
1517
+ break;
1518
+ case 'degrade':
1519
+ // Finish in-flight, accept nothing new; the DO takes us out of rotation.
1520
+ setLifecycleStatus('degraded');
1521
+ sendStatusUpdate('error');
1522
+ reporter.report('guardrail.degraded', { code: 'memory_pressure' });
1523
+ emitHostEvent('degraded', { code: 'memory_pressure' });
1524
+ break;
1525
+ case 'recover':
1526
+ setLifecycleStatus('running');
1527
+ sendStatusUpdate('idle');
1528
+ emitHostEvent('recovered', {});
1529
+ break;
1530
+ case 'shutdown':
1531
+ stopWatchdog();
1532
+ void runShutdownSequence({ reason: 'memory_pressure', guardrail: true });
1533
+ break;
1534
+ }
1535
+ };
1536
+ const startWatchdog = () => {
1537
+ if (timerId !== null || getResourcePolicy().disableGuardrails)
1538
+ return;
1539
+ if (readHeapUsedBytes() === null) {
1540
+ getLogger().debug('[Watchdog] performance.memory unavailable; watchdog inactive');
1541
+ return;
1542
+ }
1543
+ const guardrails = getGuardrails();
1544
+ let memoryGb = guardrails.unknownMemoryGb;
1545
+ try {
1546
+ const reported = getState().deviceInfo?.memoryGb;
1547
+ if (typeof reported === 'number' && reported > 0)
1548
+ memoryGb = reported;
1549
+ }
1550
+ catch {
1551
+ /* state not initialized yet */
1552
+ }
1553
+ const budgetBytes = guardrails.memoryBudgetFraction * memoryGb * 1024 * 1024 * 1024;
1554
+ const ladder = new WatchdogLadder(guardrails.watchdog, budgetBytes);
1555
+ timerId = setInterval(() => {
1556
+ try {
1557
+ if (getLifecycleStatus() === 'shutdown') {
1558
+ stopWatchdog();
1559
+ return;
1560
+ }
1561
+ // Hidden pages get throttled timers and misleading heap numbers; the
1562
+ // terminal-flush path owns backgrounding.
1563
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden')
1564
+ return;
1565
+ const used = readHeapUsedBytes();
1566
+ if (used === null)
1567
+ return;
1568
+ act(ladder, ladder.onSample(used, Date.now()));
1569
+ }
1570
+ catch {
1571
+ // The watchdog must never crash the host.
1572
+ }
1573
+ }, guardrails.watchdog.sampleMs);
1574
+ };
1575
+ const stopWatchdog = () => {
1576
+ if (timerId !== null) {
1577
+ clearInterval(timerId);
1578
+ timerId = null;
1579
+ }
1580
+ };
1581
+ /**
1582
+ * Allocation-failure boundary (Layer 5): adapters that catch a RangeError /
1583
+ * wasm abort route here instead of propagating — we may be one allocation from
1584
+ * the OOM kill, so run the emergency variant immediately.
1585
+ */
1586
+ const onAllocationFailure = (message) => {
1587
+ stopWatchdog();
1588
+ void runShutdownSequence({ reason: 'oom', guardrail: true });
1589
+ getLogger().error('[Watchdog] Allocation failure — emergency shutdown', { message });
1590
+ };
1591
+
1592
+ /**
1593
+ * Fires ad-measurement pixels from the device.
1594
+ *
1595
+ * The point of running these here rather than server-side is that the ad server
1596
+ * sees the end user's real IP, User-Agent and cookies; fired from a datacenter
1597
+ * they are filtered or flagged as fraud.
1598
+ */
1599
+ const DEFAULT_TIMEOUT_MS = 3000;
1600
+ // Holds in-flight images so the GC cannot collect one mid-request, which would
1601
+ // cancel the beacon before it reaches the ad server.
1602
+ const inFlight = new Set();
1603
+ /**
1604
+ * Loads `url` as an image and resolves once the request has left the device.
1605
+ *
1606
+ * Both `load` and `error` resolve to 'fired', by design. Measurement endpoints
1607
+ * answer with 204s, redirect chains and non-image bodies, so `error` is the
1608
+ * normal outcome for a perfectly successful pixel — treating it as a failure
1609
+ * would report a ~100% failure rate. Only the timeout is genuinely unknown.
1610
+ *
1611
+ * Never rejects: a pixel is best-effort and must not affect inference.
1612
+ */
1613
+ const fireTrackingPixel = (url, timeoutMs = DEFAULT_TIMEOUT_MS) => {
1614
+ // Non-DOM hosts (e.g. a worker) cannot fire a beacon.
1615
+ if (typeof Image === 'undefined')
1616
+ return Promise.resolve('skipped');
1617
+ return new Promise((resolve) => {
1618
+ let settled = false;
1619
+ let img;
1620
+ let timer;
1621
+ const settle = (status) => {
1622
+ if (settled)
1623
+ return;
1624
+ settled = true;
1625
+ if (timer !== undefined)
1626
+ clearTimeout(timer);
1627
+ if (img) {
1628
+ img.onload = null;
1629
+ img.onerror = null;
1630
+ inFlight.delete(img);
1631
+ }
1632
+ resolve(status);
1633
+ };
1634
+ // Everything here is best-effort: a host that blocks image construction or
1635
+ // src assignment must degrade to 'skipped', never throw into the caller and
1636
+ // never take inference down with it.
1637
+ try {
1638
+ timer = setTimeout(() => settle('timeout'), timeoutMs);
1639
+ img = new Image();
1640
+ img.onload = () => settle('fired');
1641
+ img.onerror = () => settle('fired');
1642
+ inFlight.add(img);
1643
+ img.src = url;
1644
+ }
1645
+ catch {
1646
+ settle('skipped');
1647
+ }
1648
+ });
1649
+ };
1650
+
977
1651
  let executing = false;
978
1652
  const buildInferenceInput = (request) => {
979
1653
  const input = request.input ?? {};
@@ -1044,6 +1718,29 @@ const executeSingleRequest = async (request) => {
1044
1718
  }
1045
1719
  };
1046
1720
  }
1721
+ // Kicked off only once the adapter is confirmed: a model_not_ready return
1722
+ // above sends the request to cloud instead, and firing then would count an
1723
+ // impression this device never served. Deliberately not awaited so a slow ad
1724
+ // server cannot add latency to inference; whatever has settled by the time
1725
+ // inference finishes is what gets reported.
1726
+ let pixelStatus = 'pending';
1727
+ if (request.trackingPixel) {
1728
+ void fireTrackingPixel(request.trackingPixel).then((status) => {
1729
+ pixelStatus = status;
1730
+ });
1731
+ }
1732
+ const pixelMetadata = async () => {
1733
+ if (!request.trackingPixel)
1734
+ return {};
1735
+ // Yield one turn before snapshotting. The beacon's load/error is a
1736
+ // macrotask, and it cannot run while synchronous inference holds the
1737
+ // thread — so by the time inference resolves, a request that finished long
1738
+ // ago is still sitting unprocessed in the queue and would be reported as
1739
+ // 'pending'. This waits on nothing (a genuinely slow pixel still reports
1740
+ // 'pending'), it just stops discarding a result that already arrived.
1741
+ await new Promise((resolve) => setTimeout(resolve, 0));
1742
+ return { trackingPixel: pixelStatus };
1743
+ };
1047
1744
  try {
1048
1745
  const input = buildInferenceInput(request);
1049
1746
  const result = await adapter.runInference(input);
@@ -1055,18 +1752,26 @@ const executeSingleRequest = async (request) => {
1055
1752
  error: false,
1056
1753
  errorMessage: '',
1057
1754
  metadata: {
1058
- processingTime: Math.round(performance.now() - start)
1755
+ processingTime: Math.round(performance.now() - start),
1756
+ ...(await pixelMetadata())
1059
1757
  }
1060
1758
  };
1061
1759
  }
1062
1760
  catch (error) {
1063
1761
  logger.error('Task failed', error);
1762
+ const message = error.message ?? '';
1763
+ const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
1064
1764
  getEventReporter().report('task.failed', {
1065
- code: 'adapter_error',
1765
+ code: isAllocationFailure ? 'oom' : 'adapter_error',
1066
1766
  modelId: request.modelId,
1067
1767
  durationMs: Math.round(performance.now() - start),
1068
- message: error.message
1768
+ message
1069
1769
  });
1770
+ if (isAllocationFailure) {
1771
+ // We may be one allocation from the OOM kill — emergency shutdown
1772
+ // (Layer 5 boundary); the error envelope below still goes out first.
1773
+ onAllocationFailure(message);
1774
+ }
1070
1775
  return {
1071
1776
  requestId: request.requestId,
1072
1777
  modelId: request.modelId,
@@ -1075,7 +1780,11 @@ const executeSingleRequest = async (request) => {
1075
1780
  error: true,
1076
1781
  errorMessage: error.message,
1077
1782
  metadata: {
1078
- processingTime: Math.round(performance.now() - start)
1783
+ processingTime: Math.round(performance.now() - start),
1784
+ // The beacon is fired before inference runs, so a failed task can still
1785
+ // have delivered its impression. Reporting it only on success would
1786
+ // under-count the fire rate.
1787
+ ...(await pixelMetadata())
1079
1788
  }
1080
1789
  };
1081
1790
  }
@@ -1094,6 +1803,21 @@ const handleIncomingMessage = async (msg) => {
1094
1803
  if (msg.requests.length === 0) {
1095
1804
  return;
1096
1805
  }
1806
+ // Degraded/shutting-down: finish in-flight work, accept nothing new — the
1807
+ // standard error envelope tells the server to route elsewhere immediately.
1808
+ if (isTaskGateActive()) {
1809
+ getEventReporter().report('task.rejected', { code: 'degraded' });
1810
+ sendBatchResponse(msg.requests.map((request) => ({
1811
+ requestId: request.requestId,
1812
+ modelId: request.modelId,
1813
+ modelVersion: request.modelVersion,
1814
+ response: { text: '' },
1815
+ error: true,
1816
+ errorMessage: 'degraded',
1817
+ metadata: { processingTime: 0 }
1818
+ })));
1819
+ return;
1820
+ }
1097
1821
  if (executing) {
1098
1822
  getEventReporter().report('task.rejected', { code: 'busy' });
1099
1823
  sendBatchResponse(msg.requests.map((request) => ({
@@ -1249,115 +1973,95 @@ const clearCachedModelInfo = (modelId) => {
1249
1973
  safeRemoveItem(CACHED_MODEL_ID_KEY);
1250
1974
  };
1251
1975
 
1252
- /**
1253
- * Crash-loop guard for SDK initialization.
1254
- *
1255
- * On a brand-new device the lifecycle synchronously downloads and instantiates a
1256
- * full model (and runs a sample inference) before connecting the WebSocket. In a
1257
- * memory-constrained host such as a Telegram mini-app WebView this burst can
1258
- * crash/OOM the view. The host then reloads the mini-app, the SDK runs the same
1259
- * heavy first-run path again, crashes again, and the app appears to "refresh
1260
- * continuously".
1261
- *
1262
- * Nothing in the previous flow recorded a *failed* attempt: the cache pointer is
1263
- * only written after a fully successful load, so every reload looked like a fresh
1264
- * first run. This guard persists a small attempt counter *before* the heavy work
1265
- * and clears it only once init reaches a stable point. If we see several attempts
1266
- * in a short window that never completed, we assume a crash loop and skip the
1267
- * heavy init for a cool-down period, which breaks the refresh cycle and lets the
1268
- * host app stay up.
1269
- */
1270
- const INIT_STATE_KEY = 'zerogpu_init_state';
1271
- /** Attempts that never completed are only counted within this rolling window. */
1272
- const ATTEMPT_WINDOW_MS = 60000;
1273
- /** Number of uncompleted attempts in the window that trips the cool-down. */
1274
- const MAX_ATTEMPTS_IN_WINDOW = 3;
1275
- /** How long to skip heavy init once a crash loop is detected. */
1276
- const COOLDOWN_MS = 5 * 60000;
1277
- const readState = () => {
1976
+ const BYTES_PER_GB = 1024 * 1024 * 1024;
1977
+ const evaluateResourceGate = async (model, stage, deviceInfo) => {
1278
1978
  try {
1279
- const raw = window.localStorage.getItem(INIT_STATE_KEY);
1280
- if (!raw)
1281
- return null;
1282
- const parsed = JSON.parse(raw);
1283
- if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
1979
+ if (getResourcePolicy().disableGuardrails)
1284
1980
  return null;
1981
+ const guardrails = getGuardrails();
1982
+ const sizeBytes = normalizeModelSizeBytes(model.sizeBytes);
1983
+ if (sizeBytes > 0) {
1984
+ const maxModelBytes = getResourcePolicy().maxModelBytes;
1985
+ if (typeof maxModelBytes === 'number' && sizeBytes > maxModelBytes) {
1986
+ return {
1987
+ code: 'model_too_large_for_memory',
1988
+ message: `model ${sizeBytes} B exceeds host maxModelBytes ${maxModelBytes}`
1989
+ };
1990
+ }
1991
+ const multiplier = multiplierFor(model.inferenceFramework);
1992
+ const estimatedRuntimeBytes = sizeBytes * multiplier;
1993
+ const memoryGb = typeof deviceInfo?.memoryGb === 'number' && deviceInfo.memoryGb > 0
1994
+ ? deviceInfo.memoryGb
1995
+ : guardrails.unknownMemoryGb;
1996
+ const budgetBytes = guardrails.memoryBudgetFraction * memoryGb * BYTES_PER_GB;
1997
+ if (estimatedRuntimeBytes > budgetBytes) {
1998
+ return {
1999
+ code: 'model_too_large_for_memory',
2000
+ message: `estimated runtime ${Math.round(estimatedRuntimeBytes)} B > budget ${Math.round(budgetBytes)} B ` +
2001
+ `(fraction=${guardrails.memoryBudgetFraction}, multiplier=${multiplier}, memoryGb=${memoryGb})`
2002
+ };
2003
+ }
2004
+ // Heap headroom — Chromium only; other engines expose nothing and the
2005
+ // preflight above stays the only pre-load signal there.
2006
+ const perf = globalThis.performance;
2007
+ const heap = perf?.memory;
2008
+ if (heap && heap.jsHeapSizeLimit > 0 && heap.usedJSHeapSize + estimatedRuntimeBytes > heap.jsHeapSizeLimit) {
2009
+ return {
2010
+ code: 'model_too_large_for_memory',
2011
+ message: `heap used ${heap.usedJSHeapSize} + runtime ${Math.round(estimatedRuntimeBytes)} exceeds limit ${heap.jsHeapSizeLimit}`
2012
+ };
2013
+ }
2014
+ if (stage === 'download') {
2015
+ try {
2016
+ const estimate = await navigator.storage?.estimate?.();
2017
+ if (estimate && typeof estimate.quota === 'number' && typeof estimate.usage === 'number') {
2018
+ const free = estimate.quota - estimate.usage;
2019
+ if (sizeBytes * guardrails.storageHeadroom > free) {
2020
+ return {
2021
+ code: 'storage_quota_exceeded',
2022
+ message: `need ${Math.round(sizeBytes * guardrails.storageHeadroom)} B, quota headroom ${free} B`
2023
+ };
2024
+ }
2025
+ }
2026
+ }
2027
+ catch {
2028
+ // Storage estimate unavailable — skip the check.
2029
+ }
2030
+ }
2031
+ }
2032
+ if (stage === 'download') {
2033
+ const battery = deviceInfo?.battery;
2034
+ if (battery &&
2035
+ typeof battery.level === 'number' &&
2036
+ battery.level < guardrails.minBatteryLevel &&
2037
+ battery.charging !== true) {
2038
+ return {
2039
+ code: 'low_battery',
2040
+ message: `battery ${battery.level} below ${guardrails.minBatteryLevel} and not charging`
2041
+ };
2042
+ }
1285
2043
  }
1286
- return parsed;
1287
- }
1288
- catch {
1289
2044
  return null;
1290
2045
  }
1291
- };
1292
- const writeState = (state) => {
1293
- try {
1294
- window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
1295
- }
1296
- catch {
1297
- // Storage may be unavailable/partitioned; degrade silently.
1298
- }
1299
- };
1300
- const clearState = () => {
1301
- try {
1302
- window.localStorage.removeItem(INIT_STATE_KEY);
1303
- }
1304
2046
  catch {
1305
- // ignore
1306
- }
1307
- };
1308
- /**
1309
- * Records the start of an init attempt and decides whether heavy init may
1310
- * proceed. Must be called once, before any heavy work, on every lifecycle start.
1311
- */
1312
- const beginInitAttempt = (now = Date.now()) => {
1313
- const state = readState();
1314
- // Still inside an active cool-down from a previously detected crash loop.
1315
- if (state?.cooldownUntil && state.cooldownUntil > now) {
1316
- return {
1317
- allowed: false,
1318
- cooldownRemainingMs: state.cooldownUntil - now,
1319
- attempts: state.attempts
1320
- };
1321
- }
1322
- // No prior state, or the previous window/cool-down has elapsed → start fresh.
1323
- if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
1324
- writeState({ attempts: 1, windowStart: now });
1325
- return { allowed: true, attempts: 1 };
1326
- }
1327
- const attempts = state.attempts + 1;
1328
- // Too many uncompleted attempts in the window → assume a crash loop and back
1329
- // off so the host app stops reloading.
1330
- if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
1331
- writeState({
1332
- attempts,
1333
- windowStart: state.windowStart,
1334
- cooldownUntil: now + COOLDOWN_MS
1335
- });
1336
- return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts };
2047
+ // The gate itself must never break init.
2048
+ return null;
1337
2049
  }
1338
- writeState({ attempts, windowStart: state.windowStart });
1339
- return { allowed: true, attempts };
1340
- };
1341
- /**
1342
- * Clears crash tracking. Call once init reaches a stable point (e.g. the
1343
- * WebSocket is connected), so successful loads never accumulate toward a trip.
1344
- */
1345
- const markInitSuccess = () => {
1346
- clearState();
1347
2050
  };
1348
2051
 
2052
+ // "Ready" must be proven: a model may only announce `idle` in the hello after
2053
+ // its local warm-up inference completed successfully. Both failure shapes count
2054
+ // — an errored sample AND a completed-but-not-ok one (previously only the
2055
+ // former demoted the model, so an unproven device could claim readiness).
2056
+ function warmUpFailed(sample) {
2057
+ return Boolean(sample.error) || !sample.ok;
2058
+ }
1349
2059
  // Re-registration loop: when the server idle-closes the WebSocket (or it drops
1350
2060
  // for any reason), wait device_timeout_interval_seconds and run the full
1351
2061
  // lifecycle again — re-registering refreshes device metrics and yields a new
1352
- // session key + WS URL. A single pending timer at a time; before reconnecting
1353
- // we check no socket is already live (infinite-loop guard).
1354
- let reregisterTimerId = null;
1355
- const clearReregisterTimer = () => {
1356
- if (reregisterTimerId !== null) {
1357
- clearTimeout(reregisterTimerId);
1358
- reregisterTimerId = null;
1359
- }
1360
- };
2062
+ // session key + WS URL. The single pending timer lives in ./reregister so the
2063
+ // shutdown sequence can kill it (§4.7); before reconnecting we check no socket
2064
+ // is already live (infinite-loop guard).
1361
2065
  const resolveReregisterDelaySeconds = () => {
1362
2066
  const value = getRegistrationSettings()?.device_timeout_interval_seconds;
1363
2067
  return typeof value === 'number' && Number.isFinite(value) && value > 0
@@ -1366,14 +2070,17 @@ const resolveReregisterDelaySeconds = () => {
1366
2070
  };
1367
2071
  const scheduleReregistration = (options) => {
1368
2072
  const logger = getLogger();
1369
- if (reregisterTimerId !== null) {
2073
+ if (hasReregisterTimer()) {
1370
2074
  logger.debug('[WS] Re-registration already scheduled; skipping');
1371
2075
  return;
1372
2076
  }
2077
+ if (isShutdown()) {
2078
+ logger.debug('[WS] SDK is shut down; not scheduling re-registration');
2079
+ return;
2080
+ }
1373
2081
  const delaySeconds = resolveReregisterDelaySeconds();
1374
2082
  logger.info('[WS] Scheduling re-registration', { delaySeconds });
1375
- reregisterTimerId = setTimeout(() => {
1376
- reregisterTimerId = null;
2083
+ setReregisterTimer(() => {
1377
2084
  if (getWebSocket()?.isActive()) {
1378
2085
  logger.info('[WS] Active WebSocket present; skipping re-registration');
1379
2086
  return;
@@ -1402,6 +2109,13 @@ const extractRegistrationSettings = (configSettings) => {
1402
2109
  const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
1403
2110
  initLogger(config.telemetry);
1404
2111
  const logger = getLogger();
2112
+ // Shutdown is terminal until the host restarts the SDK (page reload): a
2113
+ // stray timer or caller must not resurrect us into the same conditions.
2114
+ if (isShutdown()) {
2115
+ logger.warn('[Init] SDK is shut down; refusing to start lifecycle');
2116
+ return;
2117
+ }
2118
+ setLifecycleStatus('starting');
1405
2119
  setConfig(config);
1406
2120
  // A fresh (manual or scheduled) start supersedes any pending reconnect timer.
1407
2121
  clearReregisterTimer();
@@ -1424,10 +2138,14 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1424
2138
  const guard = beginInitAttempt();
1425
2139
  if (!guard.allowed) {
1426
2140
  setStatus('error');
2141
+ setLifecycleStatus('error');
1427
2142
  logger.warn('Init skipped: crash-loop guard active', {
1428
2143
  attempts: guard.attempts,
1429
2144
  cooldownRemainingMs: guard.cooldownRemainingMs
1430
2145
  });
2146
+ // Reporter may exist from an earlier run on this page; best-effort only —
2147
+ // on a cold page the offline buffer picks the story up next boot.
2148
+ getEventReporter().report('sdk.init_failed', { code: 'crash_loop' });
1431
2149
  return;
1432
2150
  }
1433
2151
  const bootStartedAt = performance.now();
@@ -1457,6 +2175,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1457
2175
  });
1458
2176
  const reporter = getEventReporter();
1459
2177
  reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2178
+ reportCrashFromPreviousSession(guard.crash);
1460
2179
  logger.info('[Init] Device info collected', {
1461
2180
  platform: sanitizedDeviceInfo.platform,
1462
2181
  deviceType: sanitizedDeviceInfo.deviceType,
@@ -1479,6 +2198,20 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1479
2198
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
1480
2199
  setCachedModelId(cachedModelId);
1481
2200
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
2201
+ // Breaker short-circuit: a blocklisted model must not be validation-loaded
2202
+ // (that load is the exact thing that killed the host) and must not be
2203
+ // advertised in cachedModels. Files stay on disk; the entry lapses in 24 h.
2204
+ if (cachedInfo && isModelBlocklisted(cachedInfo.modelId, cachedInfo.modelVersion)) {
2205
+ reporter.report('guardrail.preflight_blocked', {
2206
+ code: 'model_blocklisted',
2207
+ modelId: cachedInfo.modelId,
2208
+ modelVersion: cachedInfo.modelVersion
2209
+ });
2210
+ logger.warn('[Guard] Cached model is blocklisted; skipping cache validation', {
2211
+ modelId: cachedInfo.modelId
2212
+ });
2213
+ cachedInfo = null;
2214
+ }
1482
2215
  if (!isFreshDevice) {
1483
2216
  logger.info('Cache lookup', {
1484
2217
  cachedModelId,
@@ -1552,6 +2285,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1552
2285
  });
1553
2286
  }
1554
2287
  else {
2288
+ setInitPhase('loading', cachedInfo.modelId, cachedInfo.modelVersion);
1555
2289
  const loadResult = await factory.load(slmConfig, { allowDownload: hasCachedFiles });
1556
2290
  if (!loadResult.adapter || loadResult.error) {
1557
2291
  cacheInvalid = true;
@@ -1571,6 +2305,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1571
2305
  cachedAdapter = loadResult.adapter;
1572
2306
  setAdapter(cachedInfo.modelId, cachedAdapter);
1573
2307
  const sample = cachedInfo.sample;
2308
+ setInitPhase('sampling', cachedInfo.modelId, cachedInfo.modelVersion);
1574
2309
  const sampleResult = await cachedAdapter.runSample(sample);
1575
2310
  cachedSampleMetrics = {
1576
2311
  taskType: cachedInfo.taskType,
@@ -1668,17 +2403,34 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1668
2403
  markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
1669
2404
  throw err;
1670
2405
  }
2406
+ // Settings (incl. server-tuned guardrails) apply on every outcome — a
2407
+ // refusal can still carry the tunables and the re-register interval.
2408
+ const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
2409
+ setRegistrationSettings(registrationSettings);
2410
+ applyRegistrationGuardrails(registrationSettings);
2411
+ if (registrationSettings) {
2412
+ logger.info('[Register] Registration settings received', registrationSettings);
2413
+ }
2414
+ if (registerResponse.refusalReason) {
2415
+ // The server deliberately declined this device (admission rules) — the
2416
+ // opposite of a failure. Exit cleanly, come back on the slow re-register
2417
+ // interval: battery/connection refusals are transient conditions.
2418
+ reporter.report('register.rejected', { code: registerResponse.refusalReason });
2419
+ logger.warn('[Register] Registration refused by server', {
2420
+ reason: registerResponse.refusalReason
2421
+ });
2422
+ setStatus('error');
2423
+ setLifecycleStatus('error');
2424
+ markInitSuccess(); // Clean exit, not a crash loop.
2425
+ scheduleReregistration(lifecycleOptions);
2426
+ return;
2427
+ }
1671
2428
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
1672
2429
  reporter.setSessionKey(registerResponse.sessionKey);
1673
2430
  logger.info('Register response received:', {
1674
2431
  deviceId: registerResponse.deviceId,
1675
2432
  wsUrl: registerResponse.wsUrl
1676
2433
  });
1677
- const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
1678
- setRegistrationSettings(registrationSettings);
1679
- if (registrationSettings) {
1680
- logger.info('[Register] Registration settings received', registrationSettings);
1681
- }
1682
2434
  if (!registerResponse.wsUrl) {
1683
2435
  markInitSuccess(); // Clean exit, not a crash loop.
1684
2436
  return;
@@ -1737,7 +2489,26 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1737
2489
  setAdaptersByModelId({});
1738
2490
  const slmConfig = buildSlmConfigFromAssigned(primaryModel);
1739
2491
  const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
1740
- if (!factory) {
2492
+ // Layer 2/4 preflight: blocklisted or won't-fit models are refused before
2493
+ // any download/allocation. The model is reported `error` in the hello so
2494
+ // the device stays registered and auditable; the host stays alive.
2495
+ const preflightBlock = await preflightAssignedModel(primaryModel);
2496
+ if (preflightBlock) {
2497
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
2498
+ loadErrorMessage = `preflight_blocked:${preflightBlock.code}`;
2499
+ reporter.report('guardrail.preflight_blocked', {
2500
+ code: preflightBlock.code,
2501
+ modelId: primaryModel.modelId,
2502
+ modelVersion: primaryModel.modelVersion,
2503
+ message: preflightBlock.message
2504
+ });
2505
+ logger.warn('[Guard] Primary model blocked by preflight', {
2506
+ modelId: primaryModel.modelId,
2507
+ code: preflightBlock.code,
2508
+ message: preflightBlock.message
2509
+ });
2510
+ }
2511
+ else if (!factory) {
1741
2512
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1742
2513
  loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
1743
2514
  reporter.report('model.load_failed', {
@@ -1761,6 +2532,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1761
2532
  modelRepoId: primaryModel.modelRepoId
1762
2533
  });
1763
2534
  reporter.report('model.load_started', { modelId: primaryModel.modelId, modelVersion: primaryModel.modelVersion });
2535
+ setInitPhase('loading', primaryModel.modelId, primaryModel.modelVersion);
1764
2536
  const primaryLoadStart = performance.now();
1765
2537
  const loadResult = await factory.load(slmConfig);
1766
2538
  const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
@@ -1847,6 +2619,18 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1847
2619
  });
1848
2620
  continue;
1849
2621
  }
2622
+ const secondaryBlock = await preflightAssignedModel(model);
2623
+ if (secondaryBlock) {
2624
+ modelStatuses[getModelStatusKey(model)] = 'error';
2625
+ reporter.report('guardrail.preflight_blocked', {
2626
+ code: secondaryBlock.code,
2627
+ modelId: model.modelId,
2628
+ modelVersion: model.modelVersion,
2629
+ message: secondaryBlock.message
2630
+ });
2631
+ continue;
2632
+ }
2633
+ setInitPhase('loading', model.modelId, model.modelVersion);
1850
2634
  const loadResult = await factory.load(slmConfig);
1851
2635
  if (loadResult.adapter) {
1852
2636
  adaptersByModelId[model.modelId] = loadResult.adapter;
@@ -1904,6 +2688,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1904
2688
  logger.info('[Sample] Running post-register sample inference', {
1905
2689
  taskType: primaryModel.taskType
1906
2690
  });
2691
+ setInitPhase('sampling', primaryModel.modelId, primaryModel.modelVersion);
1907
2692
  postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1908
2693
  const sampleLog = {
1909
2694
  taskType: primaryModel.taskType,
@@ -1912,7 +2697,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1912
2697
  errorMessage: postRegisterSample.errorMessage,
1913
2698
  processingTimeMs: postRegisterSample.processingTimeMs
1914
2699
  };
1915
- if (postRegisterSample.error || !postRegisterSample.ok) {
2700
+ if (warmUpFailed(postRegisterSample)) {
1916
2701
  reporter.report('model.sample_failed', {
1917
2702
  modelId: primaryModel.modelId,
1918
2703
  durationMs: postRegisterSample.processingTimeMs,
@@ -1920,6 +2705,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1920
2705
  data: { phase: 'post_register' }
1921
2706
  });
1922
2707
  logger.error('[Sample] Post-register sample failed', sampleLog);
2708
+ // "Ready" must be proven: any warm-up that did not complete successfully
2709
+ // (errored OR merely not-ok) demotes the model to error in the hello, so
2710
+ // the registry never lists an unproven device for dispatch.
2711
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1923
2712
  }
1924
2713
  else {
1925
2714
  reporter.report('model.sample_succeeded', {
@@ -1929,9 +2718,6 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1929
2718
  });
1930
2719
  logger.info('[Sample] Post-register sample ok', sampleLog);
1931
2720
  }
1932
- if (postRegisterSample.error) {
1933
- modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1934
- }
1935
2721
  }
1936
2722
  const helloDeviceId = registerResponse.deviceId;
1937
2723
  const helloSlmConfig = assignedModels.map((model) => ({
@@ -1996,6 +2782,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
1996
2782
  });
1997
2783
  setWebSocket(client);
1998
2784
  setStatus('idle');
2785
+ // Model phases are behind us; a death from here on is not model-attributed.
2786
+ setInitPhase('running', primaryModel.modelId, primaryModel.modelVersion);
2787
+ setLifecycleStatus('running');
2788
+ startWatchdog();
1999
2789
  reporter.report('sdk.init_succeeded', { durationMs: Math.round(performance.now() - bootStartedAt) });
2000
2790
  logger.info('[Init] SDK ready', {
2001
2791
  deviceId,
@@ -2024,6 +2814,8 @@ const mapRegisterErrorCode = (err) => {
2024
2814
  const mapModelLoadErrorCode = (message) => {
2025
2815
  if (!message)
2026
2816
  return 'init_error';
2817
+ if (/preflight_blocked/.test(message))
2818
+ return 'guardrail_blocked';
2027
2819
  if (/no_adapter_factory/.test(message))
2028
2820
  return 'no_adapter_factory';
2029
2821
  if (/oom|out of memory|RangeError/i.test(message))
@@ -2032,6 +2824,44 @@ const mapModelLoadErrorCode = (message) => {
2032
2824
  return 'wasm_abort';
2033
2825
  return 'init_error';
2034
2826
  };
2827
+ /** Blocklist short-circuit, then the ResourceGate — before any I/O for a model. */
2828
+ const preflightAssignedModel = async (model) => {
2829
+ if (isModelBlocklisted(model.modelId, model.modelVersion)) {
2830
+ return { code: 'model_blocklisted', message: 'blocklisted after repeated crashes during load' };
2831
+ }
2832
+ let deviceInfo;
2833
+ try {
2834
+ deviceInfo = getState().deviceInfo;
2835
+ }
2836
+ catch {
2837
+ deviceInfo = undefined;
2838
+ }
2839
+ return evaluateResourceGate({
2840
+ modelId: model.modelId,
2841
+ modelVersion: model.modelVersion,
2842
+ sizeBytes: model.sizeBytes,
2843
+ inferenceFramework: model.inferenceFramework
2844
+ }, 'download', deviceInfo);
2845
+ };
2846
+ /** The previous process died mid-phase — attribute it now that the reporter is live. */
2847
+ const reportCrashFromPreviousSession = (crash) => {
2848
+ if (!crash)
2849
+ return;
2850
+ const reporter = getEventReporter();
2851
+ reporter.report('sdk.crash_detected', {
2852
+ code: crash.code,
2853
+ modelId: crash.modelId,
2854
+ modelVersion: crash.modelVersion,
2855
+ data: { phase: crash.phase }
2856
+ });
2857
+ if (crash.blocklistedModel) {
2858
+ reporter.report('guardrail.model_blocklisted', {
2859
+ modelId: crash.modelId,
2860
+ modelVersion: crash.modelVersion,
2861
+ message: crash.blocklistedModel
2862
+ });
2863
+ }
2864
+ };
2035
2865
  const normalizeAssignedModels = (slmConfig) => {
2036
2866
  if (!Array.isArray(slmConfig))
2037
2867
  return [];
@@ -3482,18 +4312,47 @@ const factory = {
3482
4312
  registerAdapter(factory);
3483
4313
 
3484
4314
  let initialized = false;
4315
+ const handle = {
4316
+ get status() {
4317
+ return getLifecycleStatus();
4318
+ },
4319
+ on: onHostEvent,
4320
+ shutdown: () => runShutdownSequence({ reason: 'host_stop' })
4321
+ };
4322
+ /**
4323
+ * Never rejects: the SDK is a guest in someone else's app, and a failed init
4324
+ * must degrade to "SDK not running" — observable via `handle.status` and the
4325
+ * reported `sdk.init_failed` events — never to an unhandled rejection in the
4326
+ * host. Existing `await initZeroGpuSdk(...)` callers are unaffected (the
4327
+ * returned handle is additive).
4328
+ */
3485
4329
  const initZeroGpuSdk = async (options) => {
3486
4330
  if (initialized) {
3487
- return;
4331
+ return handle;
3488
4332
  }
3489
- const config = resolveConfig(options?.overrides);
3490
- await startLifecycle({
3491
- config,
3492
- appUserId: options?.appUserId,
3493
- edgeOperatorKey: options?.edgeOperatorKey,
3494
- deviceId: options?.deviceId
3495
- });
3496
4333
  initialized = true;
4334
+ if (options?.resourcePolicy) {
4335
+ setResourcePolicy(options.resourcePolicy);
4336
+ if (options.resourcePolicy.disableGuardrails) {
4337
+ // Loud by design: a host running without guardrails should know it.
4338
+ console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
4339
+ }
4340
+ }
4341
+ const config = resolveConfig(options?.overrides);
4342
+ try {
4343
+ await startLifecycle({
4344
+ config,
4345
+ appUserId: options?.appUserId,
4346
+ edgeOperatorKey: options?.edgeOperatorKey,
4347
+ deviceId: options?.deviceId
4348
+ });
4349
+ }
4350
+ catch (err) {
4351
+ // Already reported inside the lifecycle (register.failed / sdk.init_failed
4352
+ // / init-failure hello); surface for the host without throwing into it.
4353
+ getLogger().error('[Init] SDK initialization failed', err);
4354
+ }
4355
+ return handle;
3497
4356
  };
3498
4357
 
3499
4358
  const readAttr = (script, names) => {