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

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.
package/README.md CHANGED
@@ -123,12 +123,13 @@ to the stable `dist/zerogpu-browser-sdk.umd.js` bundle.
123
123
  > works but pins the app to whatever build is live at load time — prefer the
124
124
  > loader so updates are automatic.
125
125
 
126
- **Release channels:** `js-sdk.zerogpu.ai` serves **official releases only** — the
127
- production deploy is gated on a `v<version>` git tag matching a plain `X.Y.Z`
128
- package version, so an auto-updating embed can never receive a development
129
- build. Development builds live on the separate `dev-js-sdk.zerogpu.ai` /
130
- `staging-js-sdk.zerogpu.ai` domains (deployed from the `dev`/`main` branches) —
131
- point a test page at those to try unreleased builds.
126
+ **Release channels:** `js-sdk.zerogpu.ai` serves **tagged releases only** — the
127
+ production deploy is gated on a `v*` git tag (release tags may carry a
128
+ prerelease suffix, e.g. `v2.1.8-alpha`), so an auto-updating embed can never
129
+ receive an untagged branch build. Development builds live on the separate
130
+ `dev-js-sdk.zerogpu.ai` / `staging-js-sdk.zerogpu.ai` domains (deployed from
131
+ the `dev`/`main` branches) — point a test page at those to try unreleased
132
+ builds.
132
133
 
133
134
  ## Configuration Options
134
135
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "sdkVersion": "0.2.0-dev.202607221142.g1c6b982+1c6b982",
2
+ "sdkVersion": "0.2.0-dev.202607241630.gdb7f26a+db7f26a",
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-24T16:32:19.095Z"
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.202607241630.gdb7f26a+db7f26a" === 'string' && "0.2.0-dev.202607241630.gdb7f26a+db7f26a".length > 0
2
+ ? "0.2.0-dev.202607241630.gdb7f26a+db7f26a"
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
@@ -2012,7 +2097,15 @@ const evaluateResourceGate = async (model, stage, deviceInfo) => {
2012
2097
  if (stage === 'download') {
2013
2098
  try {
2014
2099
  const estimate = await navigator.storage?.estimate?.();
2015
- if (estimate && typeof estimate.quota === 'number' && typeof estimate.usage === 'number') {
2100
+ // quota > 0 is required for the numbers to mean anything: embedded
2101
+ // WebViews (Telegram's iOS WKWebView above all) implement estimate()
2102
+ // but answer quota=0 — "no space promised", not "no space". Writes
2103
+ // there routinely succeed anyway, and a genuinely full origin always
2104
+ // reports quota > 0 with usage ≈ quota, so zero carries no signal:
2105
+ // treat it like an absent API and let the download itself decide.
2106
+ // (2026-07-24 prod: quota=0 fail-closed kept every iOS mini-app
2107
+ // device in a register → preflight_blocked → inactive loop.)
2108
+ if (estimate && typeof estimate.quota === 'number' && typeof estimate.usage === 'number' && estimate.quota > 0) {
2016
2109
  const free = estimate.quota - estimate.usage;
2017
2110
  if (sizeBytes * guardrails.storageHeadroom > free) {
2018
2111
  return {
@@ -2051,8 +2144,19 @@ const evaluateResourceGate = async (model, stage, deviceInfo) => {
2051
2144
  // its local warm-up inference completed successfully. Both failure shapes count
2052
2145
  // — an errored sample AND a completed-but-not-ok one (previously only the
2053
2146
  // former demoted the model, so an unproven device could claim readiness).
2054
- function warmUpFailed(sample) {
2055
- return Boolean(sample.error) || !sample.ok;
2147
+ // With a served `guardrails.sampleLatencyBudgetMs`, "proven" also means
2148
+ // "proven fast enough": a sample that completed but blew the budget demotes
2149
+ // the model too — a device that needs 5–10 s for a representative sample
2150
+ // cannot serve a real request inside the dispatch budget, and letting it claim
2151
+ // idle only buys it a timeout + quarantine (and, on WebView surfaces, a
2152
+ // mid-generation OOM kill). 0/absent budget → success-only gating (unchanged).
2153
+ function warmUpFailed(sample, latencyBudgetMs = 0) {
2154
+ if (Boolean(sample.error) || !sample.ok)
2155
+ return true;
2156
+ return (latencyBudgetMs > 0 &&
2157
+ typeof sample.processingTimeMs === 'number' &&
2158
+ Number.isFinite(sample.processingTimeMs) &&
2159
+ sample.processingTimeMs > latencyBudgetMs);
2056
2160
  }
2057
2161
  // Re-registration loop: when the server idle-closes the WebSocket (or it drops
2058
2162
  // for any reason), wait device_timeout_interval_seconds and run the full
@@ -2555,6 +2659,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2555
2659
  modelVersion: primaryModel.modelVersion ?? '1',
2556
2660
  modelUrl: primaryModel.modelUrl,
2557
2661
  modelRepoId: primaryModel.modelRepoId,
2662
+ // inferenceFramework/modelType were historically NOT persisted, so
2663
+ // every boot's cached-path getAdapterFactory(undefined, taskType)
2664
+ // returned nothing → model.cache_invalid `no_adapter_factory` →
2665
+ // cache purged → full reload, every single session. Persisting them
2666
+ // is what makes the cache actually survive a restart.
2667
+ inferenceFramework: primaryModel.inferenceFramework,
2668
+ modelType: primaryModel.modelType,
2558
2669
  maxInputTokens: primaryModel.maxTokens,
2559
2670
  quantized: primaryModel.quantized,
2560
2671
  quantization: primaryModel.quantization,
@@ -2695,17 +2806,22 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2695
2806
  errorMessage: postRegisterSample.errorMessage,
2696
2807
  processingTimeMs: postRegisterSample.processingTimeMs
2697
2808
  };
2698
- if (warmUpFailed(postRegisterSample)) {
2809
+ const sampleLatencyBudgetMs = getGuardrails().sampleLatencyBudgetMs;
2810
+ if (warmUpFailed(postRegisterSample, sampleLatencyBudgetMs)) {
2811
+ const tooSlow = !postRegisterSample.error && postRegisterSample.ok && sampleLatencyBudgetMs > 0;
2699
2812
  reporter.report('model.sample_failed', {
2700
2813
  modelId: primaryModel.modelId,
2701
2814
  durationMs: postRegisterSample.processingTimeMs,
2702
- message: postRegisterSample.errorMessage,
2815
+ message: tooSlow
2816
+ ? `sample_too_slow:${postRegisterSample.processingTimeMs}ms>budget:${sampleLatencyBudgetMs}ms`
2817
+ : postRegisterSample.errorMessage,
2703
2818
  data: { phase: 'post_register' }
2704
2819
  });
2705
- logger.error('[Sample] Post-register sample failed', sampleLog);
2820
+ logger.error('[Sample] Post-register sample failed', { ...sampleLog, sampleLatencyBudgetMs });
2706
2821
  // "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.
2822
+ // (errored, merely not-ok, OR over the served latency budget) demotes the
2823
+ // model to error in the hello, so the registry never lists a device for
2824
+ // dispatches it cannot serve in time.
2709
2825
  modelStatuses[getModelStatusKey(primaryModel)] = 'error';
2710
2826
  }
2711
2827
  else {
@@ -3602,8 +3718,13 @@ const instantiatePipeline = async (slm, cachedFiles, onFileDownloaded) => {
3602
3718
  if (env?.backends?.onnx?.env) {
3603
3719
  env.backends.onnx.env.logLevel = transformersLogLevel;
3604
3720
  }
3605
- env.backends.onnx.wasm.proxy = false;
3606
- env.backends.onnx.wasm.numThreads = 1;
3721
+ // Environment- and settings-driven (guardrails.wasm): threads activate only
3722
+ // on cross-origin-isolated pages (SharedArrayBuffer), proxy only when the
3723
+ // surface's settings opt in — everywhere else this resolves to the
3724
+ // long-standing single-threaded main-thread configuration.
3725
+ const wasmSettings = resolveWasmSettings();
3726
+ env.backends.onnx.wasm.proxy = wasmSettings.proxy;
3727
+ env.backends.onnx.wasm.numThreads = wasmSettings.numThreads;
3607
3728
  const originalFetch = window.fetch.bind(window);
3608
3729
  const wasmOverridePath = await getUsableOnnxWasmOverridePath(originalFetch);
3609
3730
  if (wasmOverridePath) {