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