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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  {
2
- "sdkVersion": "0.2.0-dev.202607221142.g1c6b982+1c6b982",
2
+ "sdkVersion": "0.2.0-dev.202607231429.gf080a5e+f080a5e",
3
3
  "channel": "development",
4
4
  "transformersVersion": "2.17.2",
5
5
  "wllamaVersion": "2.3.5",
@@ -14,5 +14,5 @@
14
14
  "wllama/single-thread/wllama.wasm",
15
15
  "wllama/multi-thread/wllama.wasm"
16
16
  ],
17
- "builtAt": "2026-07-22T11:44:17.730Z"
17
+ "builtAt": "2026-07-23T14:31:11.440Z"
18
18
  }
@@ -1,5 +1,5 @@
1
- const SDK_VERSION = typeof "0.2.0-dev.202607221142.g1c6b982+1c6b982" === 'string' && "0.2.0-dev.202607221142.g1c6b982+1c6b982".length > 0
2
- ? "0.2.0-dev.202607221142.g1c6b982+1c6b982"
1
+ const SDK_VERSION = typeof "0.2.0-dev.202607231429.gf080a5e+f080a5e" === 'string' && "0.2.0-dev.202607231429.gf080a5e+f080a5e".length > 0
2
+ ? "0.2.0-dev.202607231429.gf080a5e+f080a5e"
3
3
  : '0.0.0-dev';
4
4
 
5
5
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -996,53 +996,6 @@ const initEventReporter = (options) => {
996
996
  };
997
997
  const getEventReporter = () => singleton ?? NOOP;
998
998
 
999
- /**
1000
- * Host-facing lifecycle status and events. The SDK is a guest in someone
1001
- * else's app: this module is how the host observes guardrail state (degraded /
1002
- * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1003
- * consumers get the same signals as `zerogpu:*` window events, matching the
1004
- * existing `zerogpu:cameraPreview` pattern.
1005
- */
1006
- let lifecycleStatus = 'starting';
1007
- const listeners = {
1008
- degraded: new Set(),
1009
- recovered: new Set(),
1010
- shutdown: new Set()
1011
- };
1012
- const getLifecycleStatus = () => lifecycleStatus;
1013
- const setLifecycleStatus = (status) => {
1014
- // Shutdown is terminal (state machine B.3): recovery exists only from
1015
- // warn/degrade, never from shutdown.
1016
- if (lifecycleStatus === 'shutdown')
1017
- return;
1018
- lifecycleStatus = status;
1019
- };
1020
- const isShutdown = () => lifecycleStatus === 'shutdown';
1021
- /** Degraded and shutting-down SDKs finish in-flight work but accept nothing new. */
1022
- const isTaskGateActive = () => lifecycleStatus === 'degraded' || lifecycleStatus === 'shutdown';
1023
- const onHostEvent = (name, listener) => {
1024
- listeners[name]?.add(listener);
1025
- return () => listeners[name]?.delete(listener);
1026
- };
1027
- const emitHostEvent = (name, detail = {}) => {
1028
- for (const listener of listeners[name] ?? []) {
1029
- try {
1030
- listener(detail);
1031
- }
1032
- catch {
1033
- // A host listener bug must never propagate into the SDK.
1034
- }
1035
- }
1036
- try {
1037
- if (typeof window !== 'undefined') {
1038
- window.dispatchEvent(new CustomEvent(`zerogpu:${name}`, { detail }));
1039
- }
1040
- }
1041
- catch {
1042
- // ignore
1043
- }
1044
- };
1045
-
1046
999
  const DEFAULT_FRAMEWORK_MULTIPLIERS = {
1047
1000
  onnx: 2.0,
1048
1001
  transformersjs: 2.5,
@@ -1065,6 +1018,18 @@ const DEFAULT_WATCHDOG = {
1065
1018
  recoverPct: 0.6,
1066
1019
  recoverHoldMs: 60000
1067
1020
  };
1021
+ /**
1022
+ * Ceiling on wasm threads when the environment allows them at all
1023
+ * (cross-origin isolated). Diminishing returns above ~4 on the matmul kernels,
1024
+ * and leaving cores free keeps the host page/app responsive. Rows can raise it
1025
+ * via `guardrails.wasm.maxThreads`.
1026
+ */
1027
+ const DEFAULT_WASM_MAX_THREADS = 4;
1028
+ /**
1029
+ * Same chars-per-token heuristic the registry's dispatch input guard uses —
1030
+ * both sides only need the order of magnitude to agree.
1031
+ */
1032
+ const CHARS_PER_TOKEN = 4;
1068
1033
  let policy = {};
1069
1034
  let resolved = resolve(null);
1070
1035
  function positive(value) {
@@ -1093,6 +1058,15 @@ function resolve(settings) {
1093
1058
  sampleMs: positive(watchdog.sampleMs) ?? DEFAULT_WATCHDOG.sampleMs,
1094
1059
  recoverPct: positive(watchdog.recoverPct) ?? DEFAULT_WATCHDOG.recoverPct,
1095
1060
  recoverHoldMs: positive(watchdog.recoverHoldMs) ?? DEFAULT_WATCHDOG.recoverHoldMs
1061
+ },
1062
+ // 0 = feature off — all three gates are additive and inert unless the
1063
+ // registry serves a value for this surface (backward compatible).
1064
+ maxMemoryBudgetMb: positive(settings?.maxMemoryBudgetMb) ?? 0,
1065
+ maxInputTokens: positive(settings?.maxInputTokens) ?? 0,
1066
+ sampleLatencyBudgetMs: positive(settings?.sampleLatencyBudgetMs) ?? 0,
1067
+ wasm: {
1068
+ maxThreads: positive(settings?.wasm?.maxThreads) ?? DEFAULT_WASM_MAX_THREADS,
1069
+ proxyWorker: settings?.wasm?.proxyWorker === true
1096
1070
  }
1097
1071
  };
1098
1072
  }
@@ -1120,6 +1094,81 @@ const normalizeModelSizeBytes = (raw) => {
1120
1094
  return 0;
1121
1095
  return raw < 1000000 ? raw * 1024 * 1024 : raw;
1122
1096
  };
1097
+ /** Rough token count of an input — same heuristic as the registry guard. */
1098
+ const estimateInputTokens = (text) => Math.ceil(text.length / CHARS_PER_TOKEN);
1099
+ /** True when a served cap exists and the input exceeds it (0/absent cap = no gate). */
1100
+ const inputExceedsTokenCap = (text, capTokens = resolved.maxInputTokens) => capTokens > 0 && estimateInputTokens(text) > capTokens;
1101
+ const probeWasmEnvironment = () => ({
1102
+ isolated: typeof globalThis.crossOriginIsolated === 'boolean' &&
1103
+ globalThis.crossOriginIsolated &&
1104
+ typeof globalThis.SharedArrayBuffer === 'function',
1105
+ cores: typeof navigator !== 'undefined' && typeof navigator.hardwareConcurrency === 'number'
1106
+ ? navigator.hardwareConcurrency
1107
+ : 1,
1108
+ workerAvailable: typeof globalThis.Worker === 'function'
1109
+ });
1110
+ /**
1111
+ * ONNX wasm execution settings for this environment + served config:
1112
+ * - threads: multi-threaded wasm needs SharedArrayBuffer, which exists only on
1113
+ * cross-origin-isolated pages (COOP/COEP on the loader). When available, use
1114
+ * min(hardwareConcurrency − 1, served maxThreads) — one core is left for the
1115
+ * page. Not isolated → 1, exactly the long-standing behavior.
1116
+ * - proxy: worker execution is opt-in via `guardrails.wasm.proxyWorker` (per
1117
+ * surface, after verifying the target WebView), and only where Worker exists.
1118
+ */
1119
+ const resolveWasmSettings = (probe = probeWasmEnvironment()) => {
1120
+ const cores = Number.isFinite(probe.cores) && probe.cores > 0 ? Math.floor(probe.cores) : 1;
1121
+ const numThreads = probe.isolated ? Math.max(1, Math.min(cores - 1, resolved.wasm.maxThreads)) : 1;
1122
+ const proxy = resolved.wasm.proxyWorker && probe.workerAvailable;
1123
+ return { numThreads, proxy };
1124
+ };
1125
+
1126
+ /**
1127
+ * Host-facing lifecycle status and events. The SDK is a guest in someone
1128
+ * else's app: this module is how the host observes guardrail state (degraded /
1129
+ * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1130
+ * consumers get the same signals as `zerogpu:*` window events, matching the
1131
+ * existing `zerogpu:cameraPreview` pattern.
1132
+ */
1133
+ let lifecycleStatus = 'starting';
1134
+ const listeners = {
1135
+ degraded: new Set(),
1136
+ recovered: new Set(),
1137
+ shutdown: new Set()
1138
+ };
1139
+ const getLifecycleStatus = () => lifecycleStatus;
1140
+ const setLifecycleStatus = (status) => {
1141
+ // Shutdown is terminal (state machine B.3): recovery exists only from
1142
+ // warn/degrade, never from shutdown.
1143
+ if (lifecycleStatus === 'shutdown')
1144
+ return;
1145
+ lifecycleStatus = status;
1146
+ };
1147
+ const isShutdown = () => lifecycleStatus === 'shutdown';
1148
+ /** Degraded and shutting-down SDKs finish in-flight work but accept nothing new. */
1149
+ const isTaskGateActive = () => lifecycleStatus === 'degraded' || lifecycleStatus === 'shutdown';
1150
+ const onHostEvent = (name, listener) => {
1151
+ listeners[name]?.add(listener);
1152
+ return () => listeners[name]?.delete(listener);
1153
+ };
1154
+ const emitHostEvent = (name, detail = {}) => {
1155
+ for (const listener of listeners[name] ?? []) {
1156
+ try {
1157
+ listener(detail);
1158
+ }
1159
+ catch {
1160
+ // A host listener bug must never propagate into the SDK.
1161
+ }
1162
+ }
1163
+ try {
1164
+ if (typeof window !== 'undefined') {
1165
+ window.dispatchEvent(new CustomEvent(`zerogpu:${name}`, { detail }));
1166
+ }
1167
+ }
1168
+ catch {
1169
+ // ignore
1170
+ }
1171
+ };
1123
1172
 
1124
1173
  /**
1125
1174
  * Crash-loop guard for SDK initialization, extended into the Layer 4 crash
@@ -1716,6 +1765,35 @@ const executeSingleRequest = async (request) => {
1716
1765
  }
1717
1766
  };
1718
1767
  }
1768
+ // Input-size gate (served `guardrails.maxInputTokens`, 0/absent = off): an
1769
+ // over-cap input cannot finish inside the dispatch budget on this surface —
1770
+ // and on WebView surfaces the attempt can OOM-kill the renderer
1771
+ // mid-generation. Refuse with the standard error envelope immediately so the
1772
+ // server routes to the next candidate/cloud in milliseconds. The registry
1773
+ // enforces the same cap pre-dispatch, so this is the belt to its suspenders.
1774
+ const inputText = typeof request.input?.text === 'string' ? request.input.text : '';
1775
+ if (inputExceedsTokenCap(inputText)) {
1776
+ getEventReporter().report('task.rejected', {
1777
+ code: 'not_ready',
1778
+ modelId: request.modelId,
1779
+ data: {
1780
+ reason: 'input_too_large',
1781
+ estimatedTokens: estimateInputTokens(inputText),
1782
+ maxInputTokens: getGuardrails().maxInputTokens
1783
+ }
1784
+ });
1785
+ return {
1786
+ requestId: request.requestId,
1787
+ modelId: request.modelId,
1788
+ modelVersion: request.modelVersion,
1789
+ response: { text: '' },
1790
+ error: true,
1791
+ errorMessage: 'input_too_large',
1792
+ metadata: {
1793
+ processingTime: Math.round(performance.now() - start)
1794
+ }
1795
+ };
1796
+ }
1719
1797
  // Kicked off only once the adapter is confirmed: a model_not_ready return
1720
1798
  // above sends the request to cloud instead, and firing then would count an
1721
1799
  // impression this device never served. Deliberately not awaited so a slow ad
@@ -1991,12 +2069,19 @@ const evaluateResourceGate = async (model, stage, deviceInfo) => {
1991
2069
  const memoryGb = typeof deviceInfo?.memoryGb === 'number' && deviceInfo.memoryGb > 0
1992
2070
  ? deviceInfo.memoryGb
1993
2071
  : guardrails.unknownMemoryGb;
1994
- const budgetBytes = guardrails.memoryBudgetFraction * memoryGb * BYTES_PER_GB;
2072
+ // min(fraction × RAM, served absolute cap): the same arithmetic the
2073
+ // registry's admission guard applies. On embedded-WebView surfaces the
2074
+ // absolute cap models the renderer's real process budget, which
2075
+ // fraction-of-device-RAM wildly overestimates.
2076
+ const fractionBudgetBytes = guardrails.memoryBudgetFraction * memoryGb * BYTES_PER_GB;
2077
+ const absoluteBudgetBytes = guardrails.maxMemoryBudgetMb > 0 ? guardrails.maxMemoryBudgetMb * 1024 * 1024 : Infinity;
2078
+ const budgetBytes = Math.min(fractionBudgetBytes, absoluteBudgetBytes);
1995
2079
  if (estimatedRuntimeBytes > budgetBytes) {
1996
2080
  return {
1997
2081
  code: 'model_too_large_for_memory',
1998
2082
  message: `estimated runtime ${Math.round(estimatedRuntimeBytes)} B > budget ${Math.round(budgetBytes)} B ` +
1999
- `(fraction=${guardrails.memoryBudgetFraction}, multiplier=${multiplier}, memoryGb=${memoryGb})`
2083
+ `(fraction=${guardrails.memoryBudgetFraction}, maxBudgetMb=${guardrails.maxMemoryBudgetMb || 'none'}, ` +
2084
+ `multiplier=${multiplier}, memoryGb=${memoryGb})`
2000
2085
  };
2001
2086
  }
2002
2087
  // Heap headroom — Chromium only; other engines expose nothing and the
@@ -2051,8 +2136,19 @@ const evaluateResourceGate = async (model, stage, deviceInfo) => {
2051
2136
  // its local warm-up inference completed successfully. Both failure shapes count
2052
2137
  // — an errored sample AND a completed-but-not-ok one (previously only the
2053
2138
  // former demoted the model, so an unproven device could claim readiness).
2054
- function warmUpFailed(sample) {
2055
- return Boolean(sample.error) || !sample.ok;
2139
+ // With a served `guardrails.sampleLatencyBudgetMs`, "proven" also means
2140
+ // "proven fast enough": a sample that completed but blew the budget demotes
2141
+ // the model too — a device that needs 5–10 s for a representative sample
2142
+ // cannot serve a real request inside the dispatch budget, and letting it claim
2143
+ // idle only buys it a timeout + quarantine (and, on WebView surfaces, a
2144
+ // mid-generation OOM kill). 0/absent budget → success-only gating (unchanged).
2145
+ function warmUpFailed(sample, latencyBudgetMs = 0) {
2146
+ if (Boolean(sample.error) || !sample.ok)
2147
+ return true;
2148
+ return (latencyBudgetMs > 0 &&
2149
+ typeof sample.processingTimeMs === 'number' &&
2150
+ Number.isFinite(sample.processingTimeMs) &&
2151
+ sample.processingTimeMs > latencyBudgetMs);
2056
2152
  }
2057
2153
  // Re-registration loop: when the server idle-closes the WebSocket (or it drops
2058
2154
  // for any reason), wait device_timeout_interval_seconds and run the full
@@ -2555,6 +2651,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2555
2651
  modelVersion: primaryModel.modelVersion ?? '1',
2556
2652
  modelUrl: primaryModel.modelUrl,
2557
2653
  modelRepoId: primaryModel.modelRepoId,
2654
+ // inferenceFramework/modelType were historically NOT persisted, so
2655
+ // every boot's cached-path getAdapterFactory(undefined, taskType)
2656
+ // returned nothing → model.cache_invalid `no_adapter_factory` →
2657
+ // cache purged → full reload, every single session. Persisting them
2658
+ // is what makes the cache actually survive a restart.
2659
+ inferenceFramework: primaryModel.inferenceFramework,
2660
+ modelType: primaryModel.modelType,
2558
2661
  maxInputTokens: primaryModel.maxTokens,
2559
2662
  quantized: primaryModel.quantized,
2560
2663
  quantization: primaryModel.quantization,
@@ -2695,17 +2798,22 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2695
2798
  errorMessage: postRegisterSample.errorMessage,
2696
2799
  processingTimeMs: postRegisterSample.processingTimeMs
2697
2800
  };
2698
- if (warmUpFailed(postRegisterSample)) {
2801
+ const sampleLatencyBudgetMs = getGuardrails().sampleLatencyBudgetMs;
2802
+ if (warmUpFailed(postRegisterSample, sampleLatencyBudgetMs)) {
2803
+ const tooSlow = !postRegisterSample.error && postRegisterSample.ok && sampleLatencyBudgetMs > 0;
2699
2804
  reporter.report('model.sample_failed', {
2700
2805
  modelId: primaryModel.modelId,
2701
2806
  durationMs: postRegisterSample.processingTimeMs,
2702
- message: postRegisterSample.errorMessage,
2807
+ message: tooSlow
2808
+ ? `sample_too_slow:${postRegisterSample.processingTimeMs}ms>budget:${sampleLatencyBudgetMs}ms`
2809
+ : postRegisterSample.errorMessage,
2703
2810
  data: { phase: 'post_register' }
2704
2811
  });
2705
- logger.error('[Sample] Post-register sample failed', sampleLog);
2812
+ logger.error('[Sample] Post-register sample failed', { ...sampleLog, sampleLatencyBudgetMs });
2706
2813
  // "Ready" must be proven: any warm-up that did not complete successfully
2707
- // (errored OR merely not-ok) demotes the model to error in the hello, so
2708
- // the registry never lists an unproven device for dispatch.
2814
+ // (errored, merely not-ok, OR over the served latency budget) demotes the
2815
+ // model to error in the hello, so the registry never lists a device for
2816
+ // dispatches it cannot serve in time.
2709
2817
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
2710
2818
  }
2711
2819
  else {
@@ -3602,8 +3710,13 @@ const instantiatePipeline = async (slm, cachedFiles, onFileDownloaded) => {
3602
3710
  if (env?.backends?.onnx?.env) {
3603
3711
  env.backends.onnx.env.logLevel = transformersLogLevel;
3604
3712
  }
3605
- env.backends.onnx.wasm.proxy = false;
3606
- env.backends.onnx.wasm.numThreads = 1;
3713
+ // Environment- and settings-driven (guardrails.wasm): threads activate only
3714
+ // on cross-origin-isolated pages (SharedArrayBuffer), proxy only when the
3715
+ // surface's settings opt in — everywhere else this resolves to the
3716
+ // long-standing single-threaded main-thread configuration.
3717
+ const wasmSettings = resolveWasmSettings();
3718
+ env.backends.onnx.wasm.proxy = wasmSettings.proxy;
3719
+ env.backends.onnx.wasm.numThreads = wasmSettings.numThreads;
3607
3720
  const originalFetch = window.fetch.bind(window);
3608
3721
  const wasmOverridePath = await getUsableOnnxWasmOverridePath(originalFetch);
3609
3722
  if (wasmOverridePath) {