@zerogpu/browser-extension-sdk 0.5.1 → 0.6.0

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 (55) hide show
  1. package/README.md +99 -41
  2. package/bin/browser-extension-sdk.mjs +23 -0
  3. package/bin/cli.mjs +781 -0
  4. package/bin/herogpu.mjs +6 -0
  5. package/bin/zerogpu.mjs +6 -585
  6. package/dist/assets/herogpu-assets.json +21 -0
  7. package/dist/assets/herogpu-worker.js +1 -0
  8. package/dist/assets/zerogpu-assets.json +2 -2
  9. package/dist/assets/zerogpu-worker.js +1 -1
  10. package/dist/extension/herogpu-background.js +1 -0
  11. package/dist/extension/herogpu-offscreen.js +1 -0
  12. package/dist/extension/herogpu-settings-link.js +1 -0
  13. package/dist/extension/zerogpu-background.js +1 -1
  14. package/dist/extension/zerogpu-offscreen.js +1 -1
  15. package/dist/extension/zerogpu-settings-link.js +1 -1
  16. package/dist/herogpu-browser-sdk.cjs +1 -0
  17. package/dist/herogpu-browser-sdk.esm.js +1 -0
  18. package/dist/herogpu-browser-sdk.umd.js +1 -0
  19. package/dist/herogpu-worker.js +1 -0
  20. package/dist/loader.js +1 -1
  21. package/dist/manifest.json +5 -5
  22. package/dist/types/appinference/store.d.ts +6 -2
  23. package/dist/types/appinference/types.d.ts +29 -10
  24. package/dist/types/branding.d.ts +27 -0
  25. package/dist/types/config/types.d.ts +1 -1
  26. package/dist/types/extension/background.d.ts +68 -19
  27. package/dist/types/extension/consent.d.ts +61 -10
  28. package/dist/types/extension/offscreen.d.ts +64 -23
  29. package/dist/types/extension/settings-link.d.ts +12 -1
  30. package/dist/types/inference/runtime-locator.d.ts +1 -1
  31. package/dist/types/inference/worker-host.d.ts +1 -1
  32. package/dist/types/loader.d.ts +15 -3
  33. package/dist/types/public-api.d.ts +16 -10
  34. package/dist/types/runtime/app-identity.d.ts +2 -2
  35. package/dist/types/runtime/app-inference.d.ts +1 -1
  36. package/dist/types/runtime/custom-params.d.ts +1 -1
  37. package/dist/types/runtime/host-api.d.ts +2 -1
  38. package/dist/types/runtime/init-guard.d.ts +2 -1
  39. package/dist/types/runtime/tracking-script.d.ts +1 -1
  40. package/dist/types/storage/adopted-key.d.ts +23 -0
  41. package/dist/types/storage/cached-model.d.ts +4 -1
  42. package/dist/types/storage/model-store.d.ts +6 -0
  43. package/dist/types/transport/protocol.d.ts +1 -1
  44. package/dist/v/herogpu-browser-sdk.a957716b164a.umd.js +1 -0
  45. package/dist/v/zerogpu-browser-sdk.a957716b164a.umd.js +1 -0
  46. package/dist/zerogpu-browser-sdk.cjs +1 -1
  47. package/dist/zerogpu-browser-sdk.esm.js +1 -1
  48. package/dist/zerogpu-browser-sdk.umd.js +1 -1
  49. package/dist/zerogpu-worker.js +1 -1
  50. package/docs/app-side-inference.md +55 -45
  51. package/docs/auto-update-loader.md +33 -19
  52. package/docs/extension-developer-guide.md +158 -75
  53. package/docs/multi-model-support.md +14 -14
  54. package/package.json +13 -10
  55. package/dist/v/zerogpu-browser-sdk.686affbdf19f.umd.js +0 -1
@@ -22,7 +22,7 @@ export interface InitOptions extends AppIdentity {
22
22
  resourcePolicy?: ResourcePolicy;
23
23
  /**
24
24
  * Operator macros (`cust_param1`..`cust_param3`) attached to every request
25
- * this device serves. Opaque to ZeroGPU and reported back only to you; must
25
+ * this device serves. Opaque to herogpu and reported back only to you; must
26
26
  * not carry personal data. Change them later with `setCustomParams`.
27
27
  */
28
28
  customParams?: CustomParams;
@@ -34,12 +34,12 @@ export interface InitOptions extends AppIdentity {
34
34
  * `activeModelChanged` / `modelChoiceRefused`; `shutdown()` runs the ordered
35
35
  * graceful shutdown (terminal until the page restarts the SDK).
36
36
  *
37
- * App-side inference (0.5.0): the model this device holds for the ZeroGPU
37
+ * App-side inference (0.5.0): the model this device holds for the herogpu
38
38
  * network can also serve the host page, and the page may choose which
39
39
  * eligible model that is. `eligibleModels`, `switchModel` and `runLocal`
40
40
  * work only while `contributionState` is `contributing`.
41
41
  */
42
- export interface ZeroGpuSdkHandle {
42
+ export interface HeroGpuSdkHandle {
43
43
  readonly status: SdkLifecycleStatus;
44
44
  on(event: HostEventName, listener: (detail: HostEventDetail) => void): () => void;
45
45
  shutdown(): Promise<void>;
@@ -60,20 +60,26 @@ export interface ZeroGpuSdkHandle {
60
60
  /** Let a model that failed its warm-up here be tried again. */
61
61
  forgetUnfitModel(modelId: string): void;
62
62
  }
63
+ /** @deprecated Use {@link HeroGpuSdkHandle}. */
64
+ export type ZeroGpuSdkHandle = HeroGpuSdkHandle;
63
65
  /**
64
- * The handle without holding the one `initZeroGpuSdk` returned — for pages
66
+ * The handle without holding the one `initHeroGpuSdk` returned — for pages
65
67
  * that let the script tag start the SDK (`data-edge-operator-key`). Before
66
- * `initZeroGpuSdk` ran, the app-side calls answer `not_contributing_stopped`.
68
+ * `initHeroGpuSdk` ran, the app-side calls answer `not_contributing_stopped`.
67
69
  */
68
- export declare const getZeroGpuSdk: () => ZeroGpuSdkHandle;
70
+ export declare const getHeroGpuSdk: () => HeroGpuSdkHandle;
71
+ /** @deprecated Use {@link getHeroGpuSdk}. Same function, earlier name. */
72
+ export declare const getZeroGpuSdk: () => HeroGpuSdkHandle;
69
73
  /**
70
74
  * Never rejects: the SDK is a guest in someone else's app, and a failed init
71
75
  * must degrade to "SDK not running" — observable via `handle.status` and the
72
76
  * reported `sdk.init_failed` events — never to an unhandled rejection in the
73
- * host. Existing `await initZeroGpuSdk(...)` callers are unaffected (the
77
+ * host. Existing `await initHeroGpuSdk(...)` callers are unaffected (the
74
78
  * returned handle is additive).
75
79
  */
76
- export declare const initZeroGpuSdk: (options?: InitOptions) => Promise<ZeroGpuSdkHandle>;
80
+ export declare const initHeroGpuSdk: (options?: InitOptions) => Promise<HeroGpuSdkHandle>;
81
+ /** @deprecated Use {@link initHeroGpuSdk}. Same function, earlier name. */
82
+ export declare const initZeroGpuSdk: (options?: InitOptions) => Promise<HeroGpuSdkHandle>;
77
83
  /**
78
84
  * Replaces the operator macros: slots omitted here become unset, and
79
85
  * `setCustomParams({})` clears them all. Applies from the next request the
@@ -84,6 +90,6 @@ export type { CustomParams, CustParamSlot } from './runtime/custom-params';
84
90
  export type { HostEventName, HostEventDetail, SdkLifecycleStatus } from './runtime/host-api';
85
91
  export type { ResourcePolicy } from './runtime/guardrails';
86
92
  export type { InferenceInput } from './adapters/types';
87
- export type { ContributionState, EligibleModel, LocalInferenceResult, SwitchOutcome, SerializedZeroGpuError } from './appinference/types';
88
- export { CONTRIBUTION_STATES, LocalInferenceFailedError, ModelNotEligibleError, NotContributingError, ZeroGpuError, isZeroGpuError } from './appinference/types';
93
+ export type { ContributionState, EligibleModel, LocalInferenceResult, SwitchOutcome, SerializedHeroGpuError, SerializedZeroGpuError } from './appinference/types';
94
+ export { CONTRIBUTION_STATES, LocalInferenceFailedError, ModelNotEligibleError, NotContributingError, HeroGpuError, isHeroGpuError, ZeroGpuError, isZeroGpuError } from './appinference/types';
89
95
  export type { AppIdentity } from './runtime/app-identity';
@@ -1,10 +1,10 @@
1
1
  /**
2
- * The host application's ZeroGPU identity, sent at register so the inference
2
+ * The host application's herogpu identity, sent at register so the inference
3
3
  * this device serves is attributed to the app. Optional throughout: an unset
4
4
  * value is simply left off the register body.
5
5
  */
6
6
  export interface AppIdentity {
7
- /** The app's ZeroGPU app ID, from the ZeroGPU dashboard. */
7
+ /** The app's herogpu app ID, from the herogpu dashboard. */
8
8
  appId?: string;
9
9
  appName?: string;
10
10
  /**
@@ -43,7 +43,7 @@ export declare const forgetUnfitModel: (modelId: string) => void;
43
43
  * of the queue: an in-flight network task finishes first, network tasks
44
44
  * arriving meanwhile are answered busy, and this runs next.
45
45
  *
46
- * Throws `NotContributingError` outside `contributing`, `ZeroGpuError`
46
+ * Throws `NotContributingError` outside `contributing`, `HeroGpuError`
47
47
  * (`input_too_large`) when the text exceeds the model's catalog cap, and
48
48
  * `LocalInferenceFailedError` when the model fails on the input.
49
49
  */
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Operator macros: three opaque slots an app attaches to every request its
3
- * devices serve. ZeroGPU stores and counts them, never interprets them, and
3
+ * devices serve. herogpu stores and counts them, never interprets them, and
4
4
  * reports them back only to the operator that owns the SDK key.
5
5
  */
6
6
  export declare const CUST_PARAM_SLOTS: readonly ["cust_param1", "cust_param2", "cust_param3"];
@@ -2,7 +2,8 @@
2
2
  * Host-facing lifecycle status and events. The SDK is a guest in someone
3
3
  * else's app: this module is how the host observes guardrail state (degraded /
4
4
  * recovered / shutdown) without the SDK ever throwing into it. Script-tag
5
- * consumers get the same signals as `zerogpu:*` window events.
5
+ * consumers get the same signals as `herogpu:*` window events (and under the
6
+ * `zerogpu:*` names 0.5.1 and earlier used).
6
7
  */
7
8
  export type SdkLifecycleStatus = 'starting' | 'running' | 'degraded' | 'shutdown' | 'error';
8
9
  export type HostEventName = 'degraded' | 'recovered' | 'shutdown'
@@ -8,7 +8,8 @@
8
8
  * can crash/OOM the view; the host reloads, the SDK repeats the same heavy
9
9
  * path, and the app "refreshes continuously".
10
10
  *
11
- * Two mechanisms share one persisted state (`zerogpu_init_state`):
11
+ * Two mechanisms share one persisted state (`herogpu_init_state`, or
12
+ * `zerogpu_init_state` on a device that already has it):
12
13
  *
13
14
  * - the original attempt counter: several uncompleted attempts in a short
14
15
  * window trip a cool-down that skips heavy init entirely;
@@ -7,7 +7,7 @@
7
7
  * remotely-hosted code on extension pages outright.
8
8
  *
9
9
  * So the tag is executed off the extension origin, in a small runner page served
10
- * from ZeroGPU's own https origin under a permissive CSP. The offscreen document
10
+ * from herogpu's own https origin under a permissive CSP. The offscreen document
11
11
  * frames that runner and drives it over postMessage; the tag's JS runs there, not
12
12
  * in the extension. This needs no files in — and no manifest changes to — the host
13
13
  * extension (framing an external https page is allowed by the default MV3 CSP).
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Where the SDK keeps its localStorage state: "adopt what exists".
3
+ *
4
+ * Until 0.5.1 every key was named `zerogpu_<name>`. A device that already has
5
+ * such a key keeps using it in place, for reads and for writes, so its device
6
+ * id, its cached-model list and everything else survive the upgrade, and a
7
+ * downgrade to an earlier release still finds its data where it left it. Only
8
+ * a device that has no `zerogpu_<name>` key gets `herogpu_<name>`.
9
+ *
10
+ * The rule is applied per key and on every access, never by moving, copying or
11
+ * deleting stored data.
12
+ */
13
+ /** `herogpu_<name>`: the key a device with no earlier state uses. */
14
+ export declare const brandStorageKey: (name: string) => string;
15
+ /** `zerogpu_<name>`: the key 0.5.1 and earlier used. */
16
+ export declare const legacyStorageKey: (name: string) => string;
17
+ /**
18
+ * The localStorage key this device's `<name>` state lives under: the
19
+ * `zerogpu_` one when it exists, the `herogpu_` one otherwise. A blocked
20
+ * storage answers with the `herogpu_` key; the caller's own try/catch then
21
+ * handles the access that follows.
22
+ */
23
+ export declare const adoptedStorageKey: (name: string) => string;
@@ -38,7 +38,10 @@ export interface CachedModelInfo {
38
38
  /** Epoch ms of the last load; the eviction order. */
39
39
  lastUsedAt?: number;
40
40
  }
41
- export declare const CACHED_MODELS_KEY = "zerogpu_cached_models";
41
+ /** The list's key on a device with no earlier state. */
42
+ export declare const CACHED_MODELS_KEY: string;
43
+ /** The list's key until 0.5.1; a device that has it keeps using it. */
44
+ export declare const LEGACY_CACHED_MODELS_KEY: string;
42
45
  /** Every remembered model, most recently used first. */
43
46
  export declare const listCachedModels: () => CachedModelInfo[];
44
47
  export declare const getCachedModelInfo: (modelId: string) => CachedModelInfo | null;
@@ -1,4 +1,8 @@
1
1
  import { ModelMetadata, StoredModel } from './types';
2
+ /** The model cache of a device with no earlier state. */
3
+ export declare const MODEL_DB_NAME = "herogpu-slm-cache";
4
+ /** The model cache until 0.5.1. A device that has it keeps using it in place. */
5
+ export declare const LEGACY_MODEL_DB_NAME = "zerogpu-slm-cache";
2
6
  /**
3
7
  * Error raised by the model store. `cause` keeps the browser's own error name
4
8
  * (e.g. `QuotaExceededError`, WebKit's `UnknownError` for Blobs it cannot
@@ -10,6 +14,8 @@ export declare class ModelStoreError extends Error {
10
14
  readonly causeName: string;
11
15
  constructor(operation: string, cause: unknown);
12
16
  }
17
+ /** Test hook: decide the database name again on the next open. */
18
+ export declare const __resetModelStoreDbName: () => void;
13
19
  export declare const markModelDownloading: (modelId: string, version: string, sizeBytes: number) => Promise<void>;
14
20
  export declare const putModelComplete: (modelId: string, version: string, metadata: Omit<ModelMetadata, "status" | "updatedAt"> & {
15
21
  downloadMs?: number;
@@ -37,7 +37,7 @@ export interface ServerTaskRequest {
37
37
  trackingPixel?: string;
38
38
  /**
39
39
  * Ad-measurement JavaScript-tag URL for this device to fire. Executed in the
40
- * ZeroGPU-hosted runner page (framed by the offscreen document) so the tag's
40
+ * herogpu-hosted runner page (framed by the offscreen document) so the tag's
41
41
  * JS actually runs, otherwise fired as a credentialed request beacon. Mutually
42
42
  * exclusive with `trackingPixel` (the orchestrator sets at most one; the pixel
43
43
  * wins). Sibling of `input` for the same reason as `trackingPixel`.
@@ -0,0 +1 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).HeroGpuBrowserSdk={})}(this,function(e){"use strict";const t={sdkVersion:"0.6.0+17c3989",orchestrator:{baseUrl:"https://devices.herogpu.com",registerPath:"/register",eventsPath:"/events"},telemetry:{enableConsoleLogs:!1,locationData:!1,events:!0},inference:{worker:!0}},r=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),o=(e,t)=>{const n=Array.isArray(e)?[...e]:{...e};for(const e of Object.keys(t)){const s=t[e];if(void 0===s)continue;const i=n[e];r(s)&&r(i)?n[e]=o(i,s):n[e]=s}return n},n=(e,t)=>"string"==typeof e&&e.length>0?e:t,s=(e,t)=>"boolean"==typeof e?e:t,i=200,a=/(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i,l=new Set(["url","wsurl","baseurl","modelurl","modelrepourl","runtimeurl","requesturl","endpoint","endpointurl","manifesturl","bundleurl","orchestrator"]),d=new Set(["message","errormessage","error","reason"]),c=new Set(["requestid","modelid","modelversion","modelrepoid","modeltype","deviceid","sdkversion","tasktype","framework","inferenceframework","quantization","code","status","type","phase","flow","event","source","name","platform","devicetype","gpurenderer","mime","mode","file","files","requiredfiles","models","cachedmodels","keys","changed","cachedmodelid","assignedmodelid","primarymodelid"]),u=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e,m=e=>{if(e instanceof Error)return u(`${e.name}: ${e.message}`,i);if("string"==typeof e)return u(e,i);if(null==e)return String(e);if("object"==typeof e&&"string"==typeof e.name&&"string"==typeof e.message){const{name:t,message:r}=e;return u(`${t}: ${r}`,i)}return"object"==typeof e?`[${e.constructor?.name??"object"}]`:u(String(e),i)},f=e=>Array.isArray(e)?`[array:${e.length}]`:e&&"object"==typeof e?`[object:${Object.keys(e).length} keys]`:`[${typeof e}]`,p=(e,t)=>{const r=e.toLowerCase();return l.has(r)?(e=>{try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid-url]"}})(t):d.has(r)?u(t,i):c.has(r)?u(t,256):`[string:${t.length}]`},g=(e,t)=>a.test(e)?"[redacted]":null==t||"boolean"==typeof t?t:"number"==typeof t?Number.isFinite(t)?t:String(t):"string"==typeof t?p(e,t):t instanceof Error?m(t):f(t),h=e=>"string"==typeof e?u(e,i):"[invalid log message]";class y{constructor(e,t){this.enabled=e.enableConsoleLogs,this.sink=t}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}emit(e,t,r,o){this.enabled&&(this.sink?this.sink(e,h(r),o):void 0===o?t("[herogpu]",h(r)):t("[herogpu]",h(r),(e=>{if(e instanceof Error)return{error:m(e)};if(!e||"object"!=typeof e||Array.isArray(e))return{detail:g("detail",e)};const t={};for(const[r,o]of Object.entries(e))Array.isArray(o)?a.test(r)?t[r]="[redacted]":o.every(e=>null===e||"object"!=typeof e)?t[r]=o.slice(0,20).map(e=>g(r,e)):t[r]=f(o):t[r]=g(r,o);return t})(o)))}debug(e,t){this.emit("debug",console.debug,e,t)}info(e,t){this.emit("info",console.debug,e,t)}warn(e,t){this.emit("warn",console.warn,e,t)}error(e,t){this.emit("error",console.error,e,t)}}let w=null;const b=(e,t)=>(w=new y(e,t),w),k=()=>(w||(w=new y({enableConsoleLogs:!1,locationData:!1,events:!0})),w),v=e=>{const t=(e=>`zerogpu_${e}`)(e);try{if(null!==window.localStorage.getItem(t))return t}catch{}return(e=>`herogpu_${e}`)(e)},_="device_id",x=()=>{try{return window.localStorage.getItem(v(_))}catch{return null}},I=e=>{try{window.localStorage.setItem(v(_),e)}catch{}},M=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=15&crypto.getRandomValues(new Uint8Array(1))[0];return("x"===e?t:3&t|8).toString(16)}),T=()=>{const e=x();if(e)return e;const t=M();return I(t),t},S=()=>navigator,A=()=>{if("undefined"!=typeof window)return window.Telegram?.WebApp},$=()=>{const e=navigator.userAgent.toLowerCase(),t=A();return t?.platform?t.platform:t?"telegram-webapp":e.includes("android")?"android-web":e.includes("iphone")||e.includes("ipad")?"ios-web":e.includes("mac os")?"macos-web":e.includes("windows")?"windows-web":"web"},E=()=>{const e=navigator.userAgent??"",t=S().userAgentData;if(!0===t?.mobile)return"mobile";if(/iPad|Tablet|PlayBook|Silk/i.test(e)||navigator.maxTouchPoints>1&&window.innerWidth>=768)return"tablet";return/Mobi|Android|iPhone|iPod/i.test(e)?"mobile":"desktop"},q=()=>{try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return;const r=t.getExtension("WEBGL_debug_renderer_info");return r?t.getParameter(r.UNMASKED_RENDERER_WEBGL):t.getParameter(t.RENDERER)}catch{return}},P=async()=>{try{const e=S().getBattery;if(e){const t=await e.call(navigator);return{level:t.level,charging:t.charging}}}catch{}},L=()=>{const e=S(),t=e.connection||e.mozConnection||e.webkitConnection;if(t)return{type:t.effectiveType||"unknown",downlink:t.downlink||0,rtt:t.rtt||0}},C=async()=>{if(navigator.geolocation)return new Promise(e=>{navigator.geolocation.getCurrentPosition(t=>{e({lat:t.coords.latitude,lon:t.coords.longitude,accuracy:t.coords.accuracy})},()=>e(void 0),{timeout:5e3,maximumAge:6e4})})},B=()=>{const e=A(),t=e?.initDataUnsafe?.user;return t||(()=>{try{const e=window.location?.hash||"";if(!e.includes("tgWebAppData"))return;const t=new URLSearchParams(e.startsWith("#")?e.substring(1):e).get("tgWebAppData");if(!t)return;const r=decodeURIComponent(t),o=new URLSearchParams(r).get("user");if(!o)return;return JSON.parse(o)}catch{return}})()};class N extends Error{constructor(e,t){super(`Register failed: ${e} ${t??""}`.trim()),this.status=e,this.body=t}}const R=async e=>{try{return await e.clone().json()}catch{return null}},U=e=>{if(!e||"object"!=typeof e)return null;const t=e;if("ok"!==("string"==typeof t.status?t.status.toLowerCase():""))return null;const r=t.error,o=[t.code,t.errorCode,t.reason,r?.code];for(const e of o)if("string"==typeof e&&e.trim().length>0)return e.trim().toLowerCase();return null},j=e=>{const t=e?.requestedModel;if(!t||"object"!=typeof t)return;const r=t;return"string"==typeof r.modelId&&"boolean"==typeof r.granted?{modelId:r.modelId,granted:r.granted,..."string"==typeof r.reason?{reason:r.reason}:{},..."string"==typeof r.rule?{rule:r.rule}:{},...r.detail&&"object"==typeof r.detail?{detail:r.detail}:{}}:void 0};class O extends Error{constructor(e,t){super(`Eligible models failed: ${e} ${t??""}`.trim()),this.status=e,this.body=t}}const V=e=>{if(e&&"object"==typeof e){const t=e.type;if("string"==typeof t&&t.length>0)return t;if(Array.isArray(e.requests))return"task_batch"}return"unknown"};class F{constructor(e){this.options=e,this.logger=k(),this.pingTimer=null,this.handleOpen=()=>{if(this.logger.info("WebSocket connection opened"),this.options.onOpen?.(),this.send(this.options.hello),this.startPing(),this.options.ack&&(this.send(this.options.ack),this.options.closeAfterAck)){const e=this.options.closeCode??4e3,t=(this.options.closeReason??"").slice(0,120);this.logger.warn("Closing WebSocket after ack",{code:e,reason:t}),window.setTimeout(()=>{this.socket.close(e,t)},50)}},this.handleMessage=e=>{const t=e.data;if("string"==typeof t){const e=t.trim();if("pong"===e)return;if(e.length>0&&"{"!==e[0]&&"["!==e[0])return void this.logger.debug("[WS IN] ignoring non-JSON frame",{bytes:e.length})}try{const e=JSON.parse(t);this.logger.debug("[WS IN] frame",{type:V(e),requests:Array.isArray(e.requests)?e.requests.length:void 0,bytes:"string"==typeof t?t.length:void 0}),this.options.onMessage(e)}catch(e){this.logger.error("Failed to parse WS message",{error:m(e)})}},this.handleError=e=>{this.stopPing();const t=e.target;this.logger.error("WebSocket error",{url:t.url,readyState:t.readyState,event:e.type}),this.options.onError(e)},this.handleClose=e=>{this.stopPing();const t=e.target;this.logger.warn("WebSocket closed",{url:t.url,code:e.code,reason:e.reason||"No reason provided",wasClean:e.wasClean}),this.options.onClose(e)},this.pingIntervalMs=z(e.pingIntervalSeconds),this.logger.info("Creating WebSocket connection",{url:e.url}),this.socket=new WebSocket(e.url),this.socket.onopen=this.handleOpen,this.socket.onmessage=this.handleMessage,this.socket.onerror=this.handleError,this.socket.onclose=this.handleClose}setPingIntervalSeconds(e){this.pingIntervalMs=z(e),this.socket.readyState===WebSocket.OPEN?this.startPing():this.stopPing()}startPing(){this.stopPing(),this.pingIntervalMs<=0||(this.pingTimer=setInterval(()=>{if(this.socket.readyState===WebSocket.OPEN){try{this.socket.send("ping")}catch(e){this.logger.debug("Keepalive ping failed",{error:m(e)})}try{this.options.onPingTick?.()}catch{}}else this.stopPing()},this.pingIntervalMs))}stopPing(){null!==this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null)}isActive(){return this.socket.readyState===WebSocket.OPEN||this.socket.readyState===WebSocket.CONNECTING}send(e){const t=JSON.stringify(e);this.logger.debug("[WS OUT] frame",{type:V(e),requests:Array.isArray(e.requests)?e.requests.length:void 0,bytes:t.length}),this.socket.send(t)}close(e,t){this.stopPing(),"number"==typeof e?this.socket.close(e,(t??"").slice(0,120)):this.socket.close()}}const z=e=>"number"==typeof e&&Number.isFinite(e)&&e>0?Math.round(1e3*e):0,W={status:"idle",phase:"idle"},K=(e,t)=>{W.adaptersByModelId||(W.adaptersByModelId={}),t?W.adaptersByModelId[e]=t:delete W.adaptersByModelId[e]},D=e=>W.adaptersByModelId?.[e],G=e=>{W.adaptersByModelId=e??{}},H=e=>{W.cachedModelId=e??null},J=e=>{W.ws=e,W.sessionAcked=!1},X=()=>!0===W.sessionAcked,Z=()=>W.ws,Q=e=>{W.status=e},Y=()=>{if(!W.config||!W.deviceId||!W.deviceInfo)throw new Error("SDK state not initialized");return W},ee=()=>W.config&&W.deviceId&&W.deviceInfo?W:null,te=(e,t)=>{W.phase=e,W.declinedReason="declined"===e?t??null:null},re=()=>W.declinedReason??null,oe=()=>W.lifecycleOptions,ne="sequence_classification",se="seq2seq_generation",ie="zero_shot_classification",ae="decoder_generation",le="token_classification",de="question_answering",ce="text_embedding",ue="fill_mask",me=e=>{if("string"!=typeof e)return;const t=e.trim().toLowerCase();return t.length>0?t:void 0},fe=[],pe=e=>{fe.push(e)},ge=(e,t)=>e.inferenceFramework.toLowerCase()===t.toLowerCase(),he=(e,t,r)=>{if(!e)return;const o=me(r);if(o){const t=fe.find(t=>t.capabilities.some(t=>((e,t,r)=>"string"==typeof e.inferenceKind&&ge(e,t)&&e.inferenceKind.toLowerCase()===r)(t,e,o)));if(t)return t}return t?fe.find(r=>r.capabilities.some(r=>((e,t,r)=>"string"==typeof e.taskType&&ge(e,t)&&e.taskType.toLowerCase()===r.toLowerCase())(r,e,t))):void 0},ye={"sdk.init_started":"info","sdk.init_succeeded":"info","sdk.init_failed":"error","sdk.shutdown":"info","sdk.crash_detected":"fatal","host.foreground":"info","host.background":"info","register.started":"info","register.succeeded":"info","register.failed":"error","register.rejected":"warning","model.assigned":"info","model.cache_hit":"info","model.cache_invalid":"warning","model.cache_purged":"info","model.download_started":"info","model.download_succeeded":"info","model.download_failed":"error","model.load_started":"info","model.load_succeeded":"info","model.load_failed":"error","model.sample_succeeded":"info","model.sample_failed":"error","model.evicted":"warning","ws.connect_started":"info","ws.connected":"info","ws.hello_ack":"info","ws.closed":"warning","ws.error":"error","ws.reconnect_scheduled":"info","ws.init_failure_reported":"error","task.failed":"error","task.rejected":"warning","task.slow":"warning","guardrail.preflight_blocked":"warning","guardrail.pressure_warning":"warning","guardrail.degraded":"warning","guardrail.shutdown":"fatal","guardrail.model_blocklisted":"warning","ws.session_opened":"info","ws.session_authenticated":"info","ws.session_rejected":"warning","ws.session_superseded":"info","ws.session_closed":"info","dispatch.sent":"info","dispatch.completed":"info","dispatch.timeout":"error","dispatch.failed_offline":"warning","registry.status_changed":"info"},we=new Set(["ok","idle","ready"]),be=(e,t)=>"ws.hello_ack"===e&&t&&!we.has(t)?"error":ye[e]??"info",ke=()=>v("event_buffer"),ve=()=>{const e=(e=>{try{return window.localStorage.getItem(e)}catch{return null}})(ke());if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}},_e=e=>{const t=e.length>100?e.slice(-100):e;((e,t)=>{try{window.localStorage.setItem(e,t)}catch{}})(ke(),JSON.stringify(t))},xe=e=>{0!==e.length&&_e([...ve(),...e])},Ie=M(),Me=new Set(["guardrail.shutdown","guardrail.degraded","sdk.shutdown","sdk.crash_detected","ws.reconnect_scheduled"]);class Te{constructor(e){this.options=e,this.queue=[],this.seq=0,this.emittedCount=0,this.capped=!1,this.criticalOverflow=0,this.timer=null,this.lastByTypeCode=new Map,this.listenersBound=!1,this.boundPageHide=null,this.boundVisibilityChange=null,e.enabled&&(this.queue.push(...ve()),(()=>{try{window.localStorage.removeItem(ke())}catch{}})(),this.bindTerminalFlush(),this.timer=setInterval(()=>this.flush(),1e4))}setSessionKey(e){this.sessionKey=e}matches(e,t){return this.options.enabled===t&&this.options.deviceId===e}dispose(){null!==this.timer&&(clearInterval(this.timer),this.timer=null),"undefined"!=typeof window&&(this.boundPageHide&&window.removeEventListener("pagehide",this.boundPageHide),this.boundVisibilityChange&&window.removeEventListener("visibilitychange",this.boundVisibilityChange)),this.boundPageHide=null,this.boundVisibilityChange=null,this.listenersBound=!1}report(e,t={}){try{if(!this.options.enabled)return;if(this.emittedCount>=200)return this.capped||(this.capped=!0,this.enqueue({type:"sdk.shutdown",fields:{code:"unknown",data:{capped:!0}}}),this.flush()),void(Me.has(e)&&this.criticalOverflow<10&&(this.criticalOverflow+=1,this.enqueue({type:e,fields:{...t,data:{...t.data??{},pastCap:!0}}}),this.flush()));const r=Date.now(),o=`${e}:${t.code??""}`,n=this.lastByTypeCode.get(o);if(n&&r-n.at<3e4){const e=(Number(n.event.data?.repeat)||1)+1;return n.event.data={...n.event.data??{},repeat:e},void(n.at=r)}const s=this.enqueue({type:e,fields:t});this.lastByTypeCode.set(o,{event:s,at:r});const i=s.severity;(this.queue.length>=20||"error"===i||"fatal"===i)&&Promise.resolve().then(()=>this.flush())}catch{}}flush(e={}){try{if(!this.options.enabled||0===this.queue.length)return;const t=this.queue.slice(0,20);this.queue=this.queue.slice(20);const r=new Set(t);for(const[e,t]of this.lastByTypeCode)r.has(t.event)&&this.lastByTypeCode.delete(e);const o={v:1,deviceId:this.options.deviceId,sessionId:Ie,sdkVersion:this.options.sdkVersion,edgeSdkType:this.options.edgeSdkType,platform:this.options.platform,...this.sessionKey?{sessionKey:this.sessionKey}:{},events:t};if(e.beacon)return void this.sendBeacon(o,t);this.sendFetch(o,t)}catch{}}enqueue(e){const{type:t,fields:r}=e,o={eventId:M(),type:t,ts:(new Date).toISOString(),seq:this.seq++,severity:be(t,r.code),code:r.code,message:r.message?r.message.slice(0,256):void 0,modelId:r.modelId,modelVersion:r.modelVersion,taskType:r.taskType,durationMs:r.durationMs,bytes:r.bytes,data:r.data};return this.queue.push(o),this.emittedCount+=1,o}sendBeacon(e,t){const r=JSON.stringify({...e,edgeOperatorKey:this.options.operatorKey});let o=!1;try{"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&(o=navigator.sendBeacon(this.options.endpointUrl,new Blob([r],{type:"application/json"})))}catch{o=!1}if(!o)try{fetch(this.options.endpointUrl,{method:"POST",keepalive:!0,headers:{"content-type":"application/json","x-edge-operator-key":this.options.operatorKey},body:r}).catch(()=>xe(t))}catch{xe(t)}}sendFetch(e,t){try{fetch(this.options.endpointUrl,{method:"POST",keepalive:!0,headers:{"content-type":"application/json","x-edge-operator-key":this.options.operatorKey},body:JSON.stringify(e)}).then(e=>{e.ok||xe(t)}).catch(()=>xe(t))}catch{xe(t)}}bindTerminalFlush(){if(!this.listenersBound&&"undefined"!=typeof window){this.listenersBound=!0;try{this.boundPageHide=()=>this.flush({beacon:!0}),this.boundVisibilityChange=()=>{"undefined"!=typeof document&&"hidden"===document.visibilityState&&this.flush({beacon:!0})},window.addEventListener("pagehide",this.boundPageHide),window.addEventListener("visibilitychange",this.boundVisibilityChange)}catch{}}}}let Se=null;const Ae=new Te({enabled:!1,endpointUrl:"",operatorKey:"",deviceId:"",sdkVersion:"",platform:""}),$e=()=>Se??Ae,Ee={onnx:2,transformersjs:2.5,transformers:2.5,gguf:1.4},qe=.7,Pe=.85,Le=.95,Ce=1e4,Be=.6,Ne=6e4;let Re={},Ue=Oe(null);function je(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}function Oe(e){const t=e?.watchdog??{},r=Object.fromEntries(Object.entries(e?.frameworkMultipliers??{}).filter(([,e])=>void 0!==je(e)));return{memoryBudgetFraction:je(Re.memoryBudgetFraction)??je(e?.memoryBudgetFraction)??.3,frameworkMultipliers:{...Ee,...r},minBatteryLevel:je(e?.minBatteryLevel)??.2,storageHeadroom:je(e?.storageHeadroom)??1.2,unknownMemoryGb:je(e?.unknownMemoryGb)??2,watchdog:{warnPct:je(t.warnPct)??qe,degradePct:je(t.degradePct)??Pe,shutdownPct:je(t.shutdownPct)??Le,sampleMs:je(t.sampleMs)??Ce,recoverPct:je(t.recoverPct)??Be,recoverHoldMs:je(t.recoverHoldMs)??Ne},maxMemoryBudgetMb:je(e?.maxMemoryBudgetMb)??0,maxInputTokens:je(e?.maxInputTokens)??0,sampleLatencyBudgetMs:je(e?.sampleLatencyBudgetMs)??0,maxCachedModels:"number"==typeof Re.maxCachedModels&&Number.isFinite(Re.maxCachedModels)&&Re.maxCachedModels>=0?Math.floor(Re.maxCachedModels):"number"==typeof e?.maxCachedModels&&Number.isFinite(e.maxCachedModels)&&e.maxCachedModels>=0?Math.floor(e.maxCachedModels):3,wasm:{maxThreads:je(e?.wasm?.maxThreads)??4,proxyWorker:!0===e?.wasm?.proxyWorker}}}const Ve=()=>Re,Fe=()=>Ue,ze=e=>"number"!=typeof e||!Number.isFinite(e)||e<=0?0:e<1e6?1024*e*1024:e,We=e=>Math.ceil(e.length/4),Ke=(e=(()=>({isolated:"boolean"==typeof globalThis.crossOriginIsolated&&globalThis.crossOriginIsolated&&"function"==typeof globalThis.SharedArrayBuffer,cores:"undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:1,workerAvailable:"function"==typeof globalThis.Worker,inDocument:"undefined"!=typeof document}))(),t=Ue.wasm)=>{const r=Number.isFinite(e.cores)&&e.cores>0?Math.floor(e.cores):1;return{numThreads:e.isolated?Math.max(1,Math.min(r-1,t.maxThreads)):1,proxy:t.proxyWorker&&e.workerAvailable&&!1!==e.inDocument}},De="herogpu",Ge="zerogpu",He=`${De}:`,Je=`${Ge}:`,Xe=e=>`${De}:${e}`,Ze=e=>`${Ge}:${e}`;let Qe="starting";const Ye={degraded:new Set,recovered:new Set,shutdown:new Set,activeModelChanged:new Set,modelChoiceRefused:new Set};let et=!1;const tt=e=>{et=e},rt=()=>et,ot=()=>Qe,nt=e=>{"shutdown"!==Qe&&(Qe=e)},st=()=>"shutdown"===Qe,it=(e,t={})=>{for(const r of Ye[e]??[])try{r(t)}catch{}try{"undefined"!=typeof window&&(window.dispatchEvent(new CustomEvent(Xe(e),{detail:t})),window.dispatchEvent(new CustomEvent(Ze(e),{detail:t})))}catch{}},at=()=>v("init_state");let lt=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;const dt=3e5,ct=new Set(["downloading","loading","sampling"]),ut=()=>{try{const e=window.localStorage.getItem(at());if(!e)return null;const t=JSON.parse(e);return"number"!=typeof t?.attempts||"number"!=typeof t?.windowStart?null:t}catch{return null}},mt=e=>{try{window.localStorage.setItem(at(),JSON.stringify(e))}catch{}},ft=(e,t)=>`${e}@${t??"1"}`,pt=e=>({modelCrashes:e?.modelCrashes,blocklist:e?.blocklist,lastShutdown:e?.lastShutdown}),gt=(e,t)=>{let r=e?.modelCrashes,o=((e,t)=>{if(!e)return;const r=Object.fromEntries(Object.entries(e).filter(([,e])=>e.until>t));return Object.keys(r).length>0?r:void 0})(e?.blocklist,t);const n=e?.phase;if(!n)return{modelCrashes:r,blocklist:o};if(e?.pageToken===lt)return{modelCrashes:r,blocklist:o};const s=ct.has(n);let i;if(s&&e?.modelId){const n=ft(e.modelId,e.modelVersion),s=r?.[n],a=s&&t-s.firstAt<864e5,l=a?s.count+1:1;r={...r??{},[n]:{count:l,firstAt:a?s.firstAt:t}},l>=2&&(o={...o??{},[n]:{until:t+864e5}},i=n)}return{crash:{code:s?"oom_suspected":"unknown",phase:n,modelId:e?.modelId,modelVersion:e?.modelVersion,blocklistedModel:i},modelCrashes:r,blocklist:o}},ht=()=>{const e=ut();mt({attempts:0,windowStart:Date.now(),phase:e?.phase,modelId:e?.modelId,modelVersion:e?.modelVersion,pageToken:e?.pageToken,...pt(e)})},yt=(e,t,r)=>{const o=ut();mt({attempts:o?.attempts??0,windowStart:o?.windowStart??Date.now(),cooldownUntil:o?.cooldownUntil,phase:e,modelId:t,modelVersion:r,pageToken:lt,...pt(o)})},wt=()=>{const e=ut();mt({attempts:e?.attempts??0,windowStart:e?.windowStart??Date.now(),cooldownUntil:e?.cooldownUntil,...pt(e)})},bt=(e,t)=>{const r=ut(),o=r?.blocklist?.[ft(e,t)];return Boolean(o&&o.until>Date.now())};let kt=null;const vt=()=>null!==kt,_t=(e,t)=>{xt(),kt=setTimeout(()=>{kt=null,e()},t)},xt=()=>{null!==kt&&(clearTimeout(kt),kt=null)};let It=null;const Mt=e=>!!It&&(It(e),!0),Tt=e=>{try{const t=Y(),r=t.ws;if(!r?.isActive()||!t.sessionKey)return;r.send({type:"hello_ack",deviceId:t.deviceId,sdkVersion:t.config.sdkVersion,sessionKey:t.sessionKey,status:e,timestamp:Date.now()})}catch{}},St=[6e4,3e5,9e5,18e5];let At=0,$t=0;const Et=async({reason:e,guardrail:t=!1})=>{if("shutdown"===ot())return;if(t&&rt())return;const r=k();r.warn("[Shutdown] Running shutdown sequence",{reason:e,guardrail:t}),t?(tt(!0),nt("error")):nt("shutdown"),xt();try{t&&Tt("error")}catch{}try{Z()?.close(t?4002:1e3,e)}catch{}try{J(void 0),Q("error"),te("idle")}catch{}const o=$e();o.report(t?"guardrail.shutdown":"sdk.shutdown",{code:e});try{o.flush({beacon:!0})}catch{}try{const{adaptersByModelId:e,modelInfosByModelId:t}=Y(),r=Object.entries(e??{}).sort(([e],[r])=>ze(t?.[r]?.sizeBytes)-ze(t?.[e]?.sizeBytes));for(const[,e]of r)try{await(e.dispose?.())}catch{}G({})}catch{}if((e=>{const t=ut();mt({attempts:t?.attempts??0,windowStart:t?.windowStart??Date.now(),cooldownUntil:t?.cooldownUntil,modelCrashes:t?.modelCrashes,blocklist:t?.blocklist,lastShutdown:{code:e,ts:Date.now()}})})(e),!t)return void it("shutdown",{code:e});const n=((e=Date.now())=>{$t>0&&e-$t>18e5&&(At=0);const t=St[Math.min(At,St.length-1)];return At+=1,$t=e,t})();o.report("ws.reconnect_scheduled",{code:"guardrail_restart",durationMs:n,data:{reason:e}}),r.warn("[Shutdown] Guardrail stop; restarting with a fresh runtime later",{reason:e,restartInMs:n}),it("shutdown",{code:e,restartInMs:n}),_t(()=>{tt(!1),Mt(`guardrail_restart:${e}`)||r.warn("[Shutdown] No lifecycle to restart")},n)};class qt{constructor(e,t){this.thresholds=e,this.budgetBytes=t,this.belowRecoverSince=null,this.state="normal"}onSample(e,t){if(this.budgetBytes<=0)return null;const r=e/this.budgetBytes,o=this.thresholds;return r>o.shutdownPct?"shutdown":r>o.degradePct?"degrade":r>o.warnPct?"warn":r<o.recoverPct&&"normal"!==this.state?(null===this.belowRecoverSince&&(this.belowRecoverSince=t),t-this.belowRecoverSince>=o.recoverHoldMs?"recover":null):(this.belowRecoverSince=null,null)}transition(e){if("shutdown"===this.state)return null;switch(e){case"shutdown":return this.state="shutdown","shutdown";case"degrade":return this.belowRecoverSince=null,"degraded"===this.state?null:(this.state="degraded","degrade");case"warn":return this.belowRecoverSince=null,"normal"!==this.state?null:(this.state="warn","warn");case"recover":return this.belowRecoverSince=null,"normal"===this.state?null:(this.state="normal","recover")}}}let Pt=null;const Lt=()=>{const e=globalThis.performance,t=e?.memory?.usedJSHeapSize;return"number"==typeof t&&t>0?t:null},Ct=()=>{if(null!==Pt||Ve().disableGuardrails)return;if(null===Lt())return void k().debug("[Watchdog] performance.memory unavailable; watchdog inactive");const e=Fe();let t=e.unknownMemoryGb;try{const e=Y().deviceInfo?.memoryGb;"number"==typeof e&&e>0&&(t=e)}catch{}const r=e.memoryBudgetFraction*t*1024*1024*1024,o=new qt(e.watchdog,r);Pt=setInterval(()=>{try{if("shutdown"===ot())return void Bt();if("undefined"!=typeof document&&"hidden"===document.visibilityState)return;const e=Lt();if(null===e)return;((e,t)=>{const r=t?e.transition(t):null;if(!r)return;const o=$e();switch(r){case"warn":o.report("guardrail.pressure_warning",{code:"memory_pressure"});break;case"degrade":nt("degraded"),Tt("error"),o.report("guardrail.degraded",{code:"memory_pressure"}),it("degraded",{code:"memory_pressure"});break;case"recover":nt("running"),Tt("idle"),it("recovered",{});break;case"shutdown":Bt(),Et({reason:"memory_pressure",guardrail:!0})}})(o,o.onSample(e,Date.now()))}catch{}},e.watchdog.sampleMs)},Bt=()=>{null!==Pt&&(clearInterval(Pt),Pt=null)},Nt=e=>{Bt(),Et({reason:"oom",guardrail:!0}),k().error("[Watchdog] Allocation failure — emergency shutdown",{message:e})},Rt=new Set,Ut=(e,t=3e3)=>"undefined"==typeof Image?Promise.resolve("skipped"):new Promise(r=>{let o,n,s=!1;const i=e=>{s||(s=!0,void 0!==n&&clearTimeout(n),o&&(o.onload=null,o.onerror=null,Rt.delete(o)),r(e))};try{n=setTimeout(()=>i("timeout"),t),o=new Image,o.onload=()=>i("fired"),o.onerror=()=>i("fired"),Rt.add(o),o.src=e}catch{i("skipped")}}),jt="tag:fire",Ot=Xe("tag:result");let Vt=null,Ft=0;const zt=(e,t,r)=>new Promise(o=>{const n="zgpu-"+ ++Ft;let s,i=!1;const a=e=>{i||(i=!0,void 0!==s&&clearTimeout(s),window.removeEventListener("message",l),o(e))},l=t=>{const r=t.data;null===t.origin&&t.source===e&&(e=>{if("string"==typeof e)return e.startsWith(Je)?`${He}${e.slice(Je.length)}`:e})(r?.type)===Ot&&r?.id===n&&a("skipped"===r.status?"skipped":"fired")};try{window.addEventListener("message",l),s=setTimeout(()=>a("timeout"),r);const o=Xe(jt);e.postMessage({type:o,id:n,url:t},null)}catch{a("skipped")}}),Wt=(e,t)=>"undefined"!=typeof document&&(e=>{try{return"https:"===new URL(e).protocol}catch{return!1}})(e)?new Promise(r=>{let o,n,s=!1;const i=e=>{s||(s=!0,void 0!==n&&clearTimeout(n),o&&(o.onload=null,o.onerror=null,o.remove()),r(e))};try{n=setTimeout(()=>i("timeout"),t),o=document.createElement("script"),o.async=!0,o.onload=()=>i("fired"),o.onerror=()=>i(null),o.src=e,(document.head??document.documentElement).appendChild(o)}catch{i(null)}}):Promise.resolve(null),Kt=async(e,t=3e3)=>{try{const r=await(Vt||(Vt=new Promise(e=>{e(null)}),Vt));if(r){const o=await zt(r,e,t);if("skipped"!==o)return o}}catch{}const r=await Wt(e,t);return null!==r?r:((e,t)=>"function"!=typeof fetch?Ut(e,t):new Promise(r=>{let o,n=!1;const s=e=>{n||(n=!0,void 0!==o&&clearTimeout(o),r(e))};try{o=setTimeout(()=>s("timeout"),t),fetch(e,{mode:"no-cors",credentials:"include",keepalive:!0}).then(()=>s("fired")).catch(()=>s("fired"))}catch{s("skipped")}}))(e,t)},Dt=["cust_param1","cust_param2","cust_param3"],Gt=/^[A-Za-z0-9._-]+$/,Ht=/[^\s@]+@[^\s@]+\.[^\s@]+/,Jt=e=>Dt.includes(e);let Xt=!1;const Zt=(e,t)=>{if(null==t)return;let r;if("string"==typeof t)r=t;else{if(!("number"==typeof t&&Number.isFinite(t)||"boolean"==typeof t))return void k().warn("[CustomParams] Dropped a value that is not a string, number or boolean",{name:e,type:typeof t});r=String(t)}if(r=Array.from(r).filter(e=>{return!((t=e.codePointAt(0)??0)<=31||t>=127&&t<=159);var t}).join("").trim(),r)if(Ht.test(r))console.warn(`[herogpu] customParams.${e} looks like an email address and was dropped. Slots must not carry personal data.`);else{if(Gt.test(r))return r.length>128&&(Xt||(Xt=!0,k().warn("[CustomParams] Value truncated",{name:e,length:r.length,maxLength:128})),r=r.slice(0,128)),r;console.warn(`[herogpu] customParams.${e} was dropped. A slot takes just a value (letters, digits, "." "_" "-"), not a nested parameter such as "user-id=123".`)}};let Qt={};const Yt=e=>{Qt=(e=>{const t={};if(null==e)return t;if("object"!=typeof e||Array.isArray(e))return k().warn("[CustomParams] Ignored: expected an object of cust_param1..3",{type:Array.isArray(e)?"array":typeof e}),t;const r=e;let o;try{o=Object.keys(r)}catch{return k().warn("[CustomParams] Ignored: the object could not be read"),t}for(const e of o){if(!Jt(e)){k().warn("[CustomParams] Ignored an unknown key; only cust_param1..3 are accepted",{name:e});continue}let o;try{o=r[e]}catch{k().warn("[CustomParams] Dropped a value that could not be read",{name:e});continue}const n=Zt(e,o);void 0!==n&&(t[e]=n)}return t})(e)},er=()=>({...Qt});let tr=!1,rr=0,or=!1;const nr=[],sr=()=>tr?new Promise(e=>{nr.push(()=>{tr=!0,e()})}):(tr=!0,Promise.resolve()),ir=()=>{tr=!1;const e=nr.shift();e&&e()},ar=e=>{or=e},lr=async e=>{const t=k(),r=performance.now(),o={cust_param1:Qt.cust_param1??"",cust_param2:Qt.cust_param2??"",cust_param3:Qt.cust_param3??""},{adaptersByModelId:n}=Y();let s=n?.[e.modelId];if(s||(s=await(async e=>{const t=k(),{modelInfosByModelId:r}=Y(),o=r?.[e];if(!o)return;const n=he(o.inferenceFramework,o.taskType,o.inferenceKind);if(!n)return void t.warn("No adapter factory registered for assigned model",{modelId:e,inferenceFramework:o.inferenceFramework,inferenceKind:o.inferenceKind,taskType:o.taskType});const s={modelId:o.modelId,modelVersion:o.modelVersion??"",modelUrl:o.modelUrl,modelRepoId:o.modelRepoId,modelType:o.modelType,inferenceFramework:o.inferenceFramework,inferenceKind:o.inferenceKind,requiredFiles:o.requiredFiles,quantized:o.quantized??!1,quantization:o.quantization,taskType:o.taskType,maxInputTokens:o.maxTokens},i=await n.load(s);if(i.adapter)return K(e,i.adapter),i.adapter;t.warn("Lazy adapter load failed",{modelId:e,error:i.error?.message})})(e.modelId)),!s)return $e().report("task.rejected",{code:"not_ready",modelId:e.modelId}),{requestId:e.requestId,modelId:e.modelId,modelVersion:e.modelVersion,response:{text:""},error:!0,errorMessage:"model_not_ready",metadata:{processingTime:Math.round(performance.now()-r)}};const i="string"==typeof e.input?.text?e.input.text:"";if(((e,t=Ue.maxInputTokens)=>t>0&&We(e)>t)(i))return $e().report("task.rejected",{code:"not_ready",modelId:e.modelId,data:{reason:"input_too_large",estimatedTokens:We(i),maxInputTokens:Fe().maxInputTokens}}),{requestId:e.requestId,modelId:e.modelId,modelVersion:e.modelVersion,response:{text:""},error:!0,errorMessage:"input_too_large",metadata:{processingTime:Math.round(performance.now()-r)}};let a="pending";e.trackingPixel?Ut(e.trackingPixel).then(e=>{a=e}):e.trackingScript&&Kt(e.trackingScript).then(e=>{a=e});const l=async()=>e.trackingPixel||e.trackingScript?(await new Promise(e=>setTimeout(e,0)),{trackingPixel:a}):{};try{const t=(e=>{const t=e.input??{};return{...t,text:"string"==typeof t.text?t.text:"",usecase:"string"==typeof t.usecase?t.usecase:void 0}})(e),n=await s.runInference(t);return{requestId:e.requestId,modelId:e.modelId,modelVersion:e.modelVersion,response:n.output,error:!1,errorMessage:"",metadata:{processingTime:Math.round(performance.now()-r),...await l(),customParams:o}}}catch(o){t.error("Task failed",{error:m(o)});const n=o.message??"",s=o instanceof RangeError||/out of memory|oom|wasm.*abort|allocation failed/i.test(n);return $e().report("task.failed",{code:s?"oom":"adapter_error",modelId:e.modelId,durationMs:Math.round(performance.now()-r),message:n}),s&&Nt(n),{requestId:e.requestId,modelId:e.modelId,modelVersion:e.modelVersion,response:{text:""},error:!0,errorMessage:o.message,metadata:{processingTime:Math.round(performance.now()-r),...await l()}}}},dr=async e=>{const{ws:t,sessionKey:r,deviceId:o}=Y(),n=k(),s=e=>{const n={requests:e,deviceId:o,sessionKey:r};t?.send(n)};if(0!==e.requests.length){if("degraded"===Qe||"shutdown"===Qe||et)return $e().report("task.rejected",{code:"degraded"}),void s(e.requests.map(e=>({requestId:e.requestId,modelId:e.modelId,modelVersion:e.modelVersion,response:{text:""},error:!0,errorMessage:"degraded",metadata:{processingTime:0}})));if(or||tr||rr>0)return $e().report("task.rejected",{code:"busy"}),void s(e.requests.map(e=>({requestId:e.requestId,modelId:e.modelId,modelVersion:e.modelVersion,response:{text:""},error:!0,errorMessage:"device_busy",metadata:{processingTime:0}})));tr=!0,Q("busy");try{const t=[];for(const r of e.requests){const e=await lr(r);n.info("[WS OUT] task result",{requestId:e.requestId,modelId:e.modelId,responseBytes:JSON.stringify(e.response??null).length,processingTimeMs:e.metadata.processingTime,error:e.error,errorMessage:e.errorMessage||void 0}),t.push(e)}s(t)}finally{ir(),Q("idle")}}},cr=30,ur="exponential",mr=1e3,fr=2,pr=3e4,gr=500,hr=0,yr=86400,wr=600,br="stop",kr=0,vr={min:15,max:120},_r={min:250,max:6e4},xr={min:1,max:4},Ir={min:5e3,max:36e5},Mr={min:0,max:3e4},Tr={min:3600,max:604800},Sr={min:60,max:86400},Ar=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,$r=(e,t,r)=>{const o=Ar(e);return void 0===o||o<=0?r:Math.min(Math.max(o,t.min),t.max)},Er=(e,t,r)=>{const o=Ar(e);return void 0===o||o<0?r:Math.min(Math.max(o,t.min),t.max)},qr=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Pr=e=>{const t=qr(e),r=t?e:{},o=qr(r.keep_alive)?r.keep_alive:{},n=qr(r.reconnect)?r.reconnect:{},s=qr(r.reregister)?r.reregister:{},i=qr(r.socket)?r.socket:{},a=Ar(n.give_up_after_attempts);return{served:t,keepAlive:{pingIntervalSeconds:$r(o.ping_interval_seconds,vr,cr)},reconnect:{strategy:"fixed"===n.strategy?"fixed":ur,initialDelayMs:$r(n.initial_delay_ms,_r,mr),multiplier:$r(n.multiplier,xr,fr),maxDelayMs:$r(n.max_delay_ms,Ir,pr),jitterMs:Er(n.jitter_ms,Mr,gr),giveUpAfterAttempts:void 0!==a&&a>=0&&Number.isInteger(a)?a:hr},reregister:{maxStalenessSeconds:$r(s.max_staleness_seconds,Tr,yr),onRefusalRetrySeconds:$r(s.on_refusal_retry_seconds,Sr,wr),onAuthFailure:"retry_slow"===s.on_auth_failure?"retry_slow":br},socket:{idleTimeoutSeconds:Er(i.idle_timeout_seconds,{min:0,max:Number.MAX_SAFE_INTEGER},kr)}}};let Lr=Pr(void 0),Cr=0,Br=null;const Nr=(e,t)=>{const r=Pr(e),o=((e,t)=>{const r=[],o=(e,t,n)=>{if(qr(e)&&qr(t))for(const r of Object.keys(t))o(e[r],t[r],n?`${n}.${r}`:r);else e!==t&&r.push(n)};return o(e,t,""),r})(Lr,r);return Lr=r,{policy:r,source:t,changed:o}},Rr=()=>Lr,Ur="zerogpu-slm-cache",jr="models";class Or extends Error{constructor(e,t){const r=Vr(t),o=Fr(t);super(`model_store_${e}_failed:${r}${o?`:${o}`:""}`),this.name="ModelStoreError",this.operation=e,this.causeName=r}}const Vr=e=>e&&"object"==typeof e&&"string"==typeof e.name?e.name:null==e?"UnknownError":typeof e,Fr=e=>e&&"object"==typeof e&&"string"==typeof e.message?e.message.slice(0,200):"";let zr=null;const Wr=()=>(zr||(zr=(async e=>{const t=indexedDB;if("function"==typeof t.databases)try{const r=await t.databases();if(Array.isArray(r))return r.some(t=>t?.name===e)}catch{}return new Promise(t=>{let r,o=!1;try{r=indexedDB.open(e)}catch{return void t(void 0)}r.onupgradeneeded=e=>{if(0===e.oldVersion){o=!0;try{r.transaction?.abort()}catch{}}},r.onsuccess=()=>{try{r.result.close()}catch{}if(o){try{indexedDB.deleteDatabase(e)}catch{}t(!1)}else t(!0)},r.onerror=e=>{e?.preventDefault?.(),t(!o&&void 0)},r.onblocked=()=>t(void 0)})})(Ur).then(e=>!1===e?"herogpu-slm-cache":Ur,()=>Ur)),zr),Kr=async(e,t)=>{const r=await(async()=>{if("undefined"==typeof indexedDB)throw new Or("open",{name:"IndexedDBUnavailable",message:"indexedDB is not defined"});const e=await Wr();return new Promise((t,r)=>{let o;try{o=indexedDB.open(e,1)}catch(e){return void r(new Or("open",e))}o.onupgradeneeded=()=>{const e=o.result;e.objectStoreNames.contains(jr)||e.createObjectStore(jr,{keyPath:"key"})},o.onsuccess=()=>t(o.result),o.onerror=()=>r(new Or("open",o.error))})})(),o="readonly"===e?"read":"write";return new Promise((n,s)=>{let i,a,l=!1;const d=(e,t=!1)=>{if(!l){l=!0;try{r.close()}catch{}t?s(e instanceof Or?e:new Or(o,e)):n(a)}};let c,u;try{c=r.transaction(jr,e)}catch(e){return void d(e,!0)}c.oncomplete=()=>d(),c.onerror=e=>{const t=e?.target;i=i??t?.error??c.error},c.onabort=()=>d(i??c.error,!0);try{u=c.objectStore(jr)}catch(e){return void d(e,!0)}t(u).then(e=>{a=e}).catch(e=>{i=i??e;try{c.abort()}catch{d(e,!0)}})})},Dr=(e,t)=>`${e}:${t}`,Gr=async(e,t)=>{const r=Dr(e,t);return Kr("readonly",async e=>new Promise((t,o)=>{const n=e.get(r);n.onsuccess=()=>{const e=n.result;e&&"complete"===e.metadata.status?t({metadata:e.metadata,files:e.files}):t(null)},n.onerror=()=>o(n.error)}))},Hr=async(e,t)=>{await Kr("readwrite",async r=>{r.delete(Dr(e,t))})},Jr="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";let Xr={...{transformersUrl:Jr}};const Zr=()=>Xr,Qr=()=>globalThis,Yr=e=>{e&&(e.useBrowserCache=!1)},eo="transformers-cache";let to=null;const ro=()=>{const e=Qr();if(e.TransformersPipeline)return Promise.resolve();if(!to){const t=k(),r=Zr().transformersUrl;to=(async()=>{try{t.info("[Runtime] Importing Transformers runtime",{runtimeUrl:r});const o=performance.now(),n=await import(r),s=n?.pipeline,i=n?.env;if("function"!=typeof s||!i)throw new Error("Transformers runtime missing pipeline/env exports");t.info("[Runtime] Transformers runtime ready",{ms:Math.round(performance.now()-o)}),i.allowLocalModels=!0,i.allowRemoteModels=!0,Yr(i),i?.backends?.onnx?.env&&(i.backends.onnx.env.logLevel="warning"),"logLevel"in i&&(i.logLevel="warning"),e.TransformersPipeline=s,e.TransformersEnv=i,e.TransformersLib=(e=>{if(!e||"object"!=typeof e)return;const t=e,{AutoTokenizer:r,PreTrainedModel:o,Tensor:n}=t,s=e=>Boolean(e)&&"function"==typeof e.from_pretrained;return s(r)&&s(o)&&"function"==typeof n?{AutoTokenizer:r,PreTrainedModel:o,Tensor:n}:void 0})(n)}catch(e){throw to=null,t.error("[SLM] Failed to import Transformers runtime",{runtimeUrl:r,error:m(e)}),e}})()}return to},oo=e=>e.replace(/\/$/,""),no=e=>/^https?:\/\//i.test(e.trim()),so=e=>{const t=(e=>{const t=e.trim();if(!t)return"";if(no(t))try{return new URL(t).pathname.replace(/^\/+|\/+$/g,"")}catch{return""}return t.replace(/^\/+|\/+$/g,"")})(e);return t?oo(`https://huggingface.co/${t}/resolve/main`):""},io=(e,t)=>{const r=(e||"").trim();if(no(r))return oo(r);const o=so(t||r);return o||oo(r)},ao=e=>e.replace(/^\/+/,"").replace(/^resolve\/main\//,"").split("?")[0],lo=(e,t)=>`${e}/${ao(t)}`,co=()=>{const e=Zr().pageOrigin??("undefined"!=typeof location&&location?location.origin:void 0);if(!e||"null"===e)return null;try{return new URL("/onnx-wasm/",e).toString()}catch{return null}},uo=[0,97,115,109],mo=["ort-wasm-simd-threaded.wasm","ort-wasm-simd.wasm","ort-wasm-threaded.wasm","ort-wasm.wasm"],fo=e=>e.endsWith("/")?e:`${e}/`,po=()=>{try{const e=new URL(Jr),t=e.pathname,r=t.lastIndexOf("/"),o=r>=0?t.slice(0,r+1):"/";return`${e.origin}${o}`}catch{return"https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/"}},go=e=>e.length>=uo.length&&uo.every((t,r)=>e[r]===t);let ho=null;const yo=e=>(ho||(ho=(async e=>{const t=[Zr().wasmPaths,co(),po(),"https://unpkg.com/@xenova/transformers@2.17.2/dist/"].filter(e=>"string"==typeof e&&e.length>0).map(fo).filter((e,t,r)=>r.indexOf(e)===t);for(const r of t){let t=!1;for(const o of mo){const n=(()=>{try{return new URL(o,r).toString()}catch{return`${r}${o}`}})();try{const o=await e(n,{cache:"no-store"});if(!o.ok)continue;const s=new Uint8Array(await o.arrayBuffer());if(go(s))return r;t=!0;break}catch{}}t&&k().warn("[SLM] ONNX wasm probe got non-wasm payload",{url:r})}return null})(e)),ho);let wo=Promise.resolve();const bo=async e=>{const t=wo;let r=()=>{};wo=new Promise(e=>{r=e}),await t;try{return await e()}finally{r()}},ko=(e,t)=>`cache_persist_failed:${e}@${t||"1"}`,vo=e=>v(e),_o=new Map,xo=new Set,Io=(e,t)=>{const r=ko(e,t);_o.delete(r);try{window.localStorage.removeItem(vo(r))}catch{}},Mo=(e,t)=>((e,t)=>{const r=ko(e,t);let o=_o.get(r)??null;try{const e=window.localStorage.getItem(vo(r));e&&(o=JSON.parse(e))}catch{}return o&&"number"==typeof o.failures?Date.now()-(o.lastFailureAt??0)>6048e5?(Io(e,t),null):o:null})(e,t)?.failures??0,To=(e,t)=>Mo(e,t)>0,So=(e,t,r,o,n)=>{const s=`${e}:${t}@${r}`;xo.has(s)||(xo.add(s),$e().report("model.cache_invalid",{code:"persist"===e?"cache_persist_failed":"cache_read_failed",message:m(o),modelId:t,modelVersion:r,data:{phase:e,errorName:Ao(o),...n}}))},Ao=e=>{if(e&&"object"==typeof e){const t=e.causeName;if("string"==typeof t)return t;const r=e.name;if("string"==typeof r)return r}return typeof e},$o=async(e,t)=>{try{return await Gr(e,t)}catch(r){return k().warn("[Cache] Model cache read failed; treating as a cache miss",{modelId:e,modelVersion:t,error:m(r)}),So("read",e,t,r,{}),null}},Eo=async(e,t,r,o)=>{const n=k(),s=Mo(e,t);if(s>=2)return n.info("[Cache] Skipping model cache write (earlier attempts failed); serving from memory",{modelId:e,modelVersion:t,failures:s}),"skipped";try{return await(async(e,t,r,o)=>{const n={...r,modelId:e,modelVersion:t,status:"complete",updatedAt:Date.now(),sizeBytes:r.sizeBytes};await Kr("readwrite",async r=>{const s={key:Dr(e,t),metadata:n,files:o};r.put(s)})})(e,t,r,o),s>0&&Io(e,t),"persisted"}catch(o){const i=s+1;return((e,t,r)=>{const o=ko(e,t);_o.set(o,r);try{window.localStorage.setItem(vo(o),JSON.stringify(r))}catch{}})(e,t,{failures:i,lastFailureAt:Date.now(),lastError:m(o)}),n.warn("[Cache] Model cache write failed; serving from memory",{modelId:e,modelVersion:t,attempt:i,retryOnNextStart:i<2,error:m(o)}),So("persist",e,t,o,{attempt:i,retryOnNextStart:i<2,sizeBytes:r.sizeBytes}),"failed"}},qo=()=>v("cached_models"),Po="zerogpu_cached_model_id",Lo=e=>{try{return window.localStorage.getItem(e)}catch{return null}},Co=e=>{try{window.localStorage.removeItem(e)}catch{}},Bo=e=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.modelId&&e.modelId.length>0,No=()=>{const e=Lo(qo());if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(Bo):[]}catch{return[]}},Ro=e=>{const t=qo();0===e.length?Co(t):((e,t)=>{try{window.localStorage.setItem(e,t)}catch{}})(t,JSON.stringify(e))},Uo=(e,t)=>(t.lastUsedAt??0)-(e.lastUsedAt??0),jo=()=>No().sort(Uo),Oo=(e,t=Date.now())=>{const r=No().filter(t=>t.modelId!==e.modelId);Ro([{...e,lastUsedAt:t},...r])},Vo=e=>{const t=No(),r=t.find(t=>t.modelId===e)??null;return r&&Ro(t.filter(t=>t.modelId!==e)),Co(e),Lo(Po)===e&&Co(Po),r},Fo=async(e,t,r)=>{try{if(Ve().disableGuardrails)return null;const o=Fe(),n=ze(e.sizeBytes);if(n>0){const s=Ve().maxModelBytes;if("number"==typeof s&&n>s)return{code:"model_too_large_for_memory",message:`model ${n} B exceeds host maxModelBytes ${s}`};const i=(e=>{const t=e?.trim().toLowerCase()??"";return Ue.frameworkMultipliers[t]??2})(e.inferenceFramework),a=n*i,l="number"==typeof r?.memoryGb&&r.memoryGb>0?r.memoryGb:o.unknownMemoryGb,d=o.memoryBudgetFraction*l*1073741824,c=o.maxMemoryBudgetMb>0?1024*o.maxMemoryBudgetMb*1024:1/0,u=Math.min(d,c);if(a>u)return{code:"model_too_large_for_memory",message:`estimated runtime ${Math.round(a)} B > budget ${Math.round(u)} B (fraction=${o.memoryBudgetFraction}, maxBudgetMb=${o.maxMemoryBudgetMb||"none"}, multiplier=${i}, memoryGb=${l})`};const m=globalThis.performance,f=m?.memory;if(f&&f.jsHeapSizeLimit>0&&f.usedJSHeapSize+a>f.jsHeapSizeLimit)return{code:"model_too_large_for_memory",message:`heap used ${f.usedJSHeapSize} + runtime ${Math.round(a)} exceeds limit ${f.jsHeapSizeLimit}`};if("download"===t)try{const e=await(navigator.storage?.estimate?.());if(e&&"number"==typeof e.quota&&"number"==typeof e.usage&&e.quota>0&&!(()=>{try{return"undefined"!=typeof window&&(!!A()||(window.location?.hash||"").includes("tgWebAppData"))}catch{return!1}})()){const t=e.quota-e.usage;if(n*o.storageHeadroom>t)return{code:"storage_quota_exceeded",message:`need ${Math.round(n*o.storageHeadroom)} B, quota headroom ${t} B (quota ${e.quota} B, usage ${e.usage} B)`}}}catch{}}if("download"===t){const e=r?.battery;if(e&&"number"==typeof e.level&&e.level<o.minBatteryLevel&&!0!==e.charging)return{code:"low_battery",message:`battery ${e.level} below ${o.minBatteryLevel} and not charging`}}return null}catch{return null}};let zo={};const Wo=e=>{if("string"!=typeof e)return;return e.trim()||void 0},Ko=()=>{const e={};zo.appId&&(e.app_id=zo.appId),zo.appName&&(e.app_name=zo.appName);const t=zo.externalAppId??(()=>{try{return"undefined"!=typeof chrome?Wo(chrome?.runtime?.id):void 0}catch{return}})();return t&&(e.external_app_id=t),e},Do='const e={onnx:2,transformersjs:2.5,transformers:2.5,gguf:1.4},t=.7,r=.85,n=.95,o=1e4,s=.6,a=6e4;let i={},l=function(l){const u={},f=Object.fromEntries(Object.entries({}).filter(([,e])=>void 0!==c(e)));return{memoryBudgetFraction:c(i.memoryBudgetFraction)??c(l?.memoryBudgetFraction)??.3,frameworkMultipliers:{...e,...f},minBatteryLevel:c(l?.minBatteryLevel)??.2,storageHeadroom:c(l?.storageHeadroom)??1.2,unknownMemoryGb:c(l?.unknownMemoryGb)??2,watchdog:{warnPct:c(u.warnPct)??t,degradePct:c(u.degradePct)??r,shutdownPct:c(u.shutdownPct)??n,sampleMs:c(u.sampleMs)??o,recoverPct:c(u.recoverPct)??s,recoverHoldMs:c(u.recoverHoldMs)??a},maxMemoryBudgetMb:c(l?.maxMemoryBudgetMb)??0,maxInputTokens:c(l?.maxInputTokens)??0,sampleLatencyBudgetMs:c(l?.sampleLatencyBudgetMs)??0,maxCachedModels:"number"==typeof i.maxCachedModels&&Number.isFinite(i.maxCachedModels)&&i.maxCachedModels>=0?Math.floor(i.maxCachedModels):3,wasm:{maxThreads:c(l?.wasm?.maxThreads)??4,proxyWorker:!0===l?.wasm?.proxyWorker}}}(null);function c(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}const u=(e=(()=>({isolated:"boolean"==typeof globalThis.crossOriginIsolated&&globalThis.crossOriginIsolated&&"function"==typeof globalThis.SharedArrayBuffer,cores:"undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:1,workerAvailable:"function"==typeof globalThis.Worker,inDocument:"undefined"!=typeof document}))(),t=l.wasm)=>{const r=Number.isFinite(e.cores)&&e.cores>0?Math.floor(e.cores):1;return{numThreads:e.isolated?Math.max(1,Math.min(r-1,t.maxThreads)):1,proxy:t.proxyWorker&&e.workerAvailable&&!1!==e.inDocument}},f="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";let m={...{transformersUrl:f}};const d=()=>m,p=200,g=/(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i,h=new Set(["url","wsurl","baseurl","modelurl","modelrepourl","runtimeurl","requesturl","endpoint","endpointurl","manifesturl","bundleurl","orchestrator"]),y=new Set(["message","errormessage","error","reason"]),w=new Set(["requestid","modelid","modelversion","modelrepoid","modeltype","deviceid","sdkversion","tasktype","framework","inferenceframework","quantization","code","status","type","phase","flow","event","source","name","platform","devicetype","gpurenderer","mime","mode","file","files","requiredfiles","models","cachedmodels","keys","changed","cachedmodelid","assignedmodelid","primarymodelid"]),b=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e,x=e=>{if(e instanceof Error)return b(`${e.name}: ${e.message}`,p);if("string"==typeof e)return b(e,p);if(null==e)return String(e);if("object"==typeof e&&"string"==typeof e.name&&"string"==typeof e.message){const{name:t,message:r}=e;return b(`${t}: ${r}`,p)}return"object"==typeof e?`[${e.constructor?.name??"object"}]`:b(String(e),p)},k=e=>Array.isArray(e)?`[array:${e.length}]`:e&&"object"==typeof e?`[object:${Object.keys(e).length} keys]`:`[${typeof e}]`,_=(e,t)=>{const r=e.toLowerCase();return h.has(r)?(e=>{try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid-url]"}})(t):y.has(r)?b(t,p):w.has(r)?b(t,256):`[string:${t.length}]`},M=(e,t)=>g.test(e)?"[redacted]":null==t||"boolean"==typeof t?t:"number"==typeof t?Number.isFinite(t)?t:String(t):"string"==typeof t?_(e,t):t instanceof Error?x(t):k(t),v=e=>"string"==typeof e?b(e,p):"[invalid log message]";class T{constructor(e,t){this.enabled=e.enableConsoleLogs,this.sink=t}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}emit(e,t,r,n){this.enabled&&(this.sink?this.sink(e,v(r),n):void 0===n?t("[herogpu]",v(r)):t("[herogpu]",v(r),(e=>{if(e instanceof Error)return{error:x(e)};if(!e||"object"!=typeof e||Array.isArray(e))return{detail:M("detail",e)};const t={};for(const[r,n]of Object.entries(e))Array.isArray(n)?g.test(r)?t[r]="[redacted]":n.every(e=>null===e||"object"!=typeof e)?t[r]=n.slice(0,20).map(e=>M(r,e)):t[r]=k(n):t[r]=M(r,n);return t})(n)))}debug(e,t){this.emit("debug",console.debug,e,t)}info(e,t){this.emit("info",console.debug,e,t)}warn(e,t){this.emit("warn",console.warn,e,t)}error(e,t){this.emit("error",console.error,e,t)}}let S=null;const E=()=>(S||(S=new T({enableConsoleLogs:!1,locationData:!1,events:!0})),S),A=async e=>{const t=performance.now();return{result:await e(),ms:Math.round(performance.now()-t)}},L="sequence_classification",$="seq2seq_generation",q="zero_shot_classification",P="token_classification",j="question_answering",I="text_embedding",B="fill_mask",R=()=>globalThis,z=e=>{e&&(e.useBrowserCache=!1)};let N=null;const U=()=>{const e=R();if(e.TransformersPipeline)return Promise.resolve();if(!N){const t=E(),r=d().transformersUrl;N=(async()=>{try{t.info("[Runtime] Importing Transformers runtime",{runtimeUrl:r});const n=performance.now(),o=await import(r),s=o?.pipeline,a=o?.env;if("function"!=typeof s||!a)throw new Error("Transformers runtime missing pipeline/env exports");t.info("[Runtime] Transformers runtime ready",{ms:Math.round(performance.now()-n)}),a.allowLocalModels=!0,a.allowRemoteModels=!0,z(a),a?.backends?.onnx?.env&&(a.backends.onnx.env.logLevel="warning"),"logLevel"in a&&(a.logLevel="warning"),e.TransformersPipeline=s,e.TransformersEnv=a,e.TransformersLib=(e=>{if(!e||"object"!=typeof e)return;const t=e,{AutoTokenizer:r,PreTrainedModel:n,Tensor:o}=t,s=e=>Boolean(e)&&"function"==typeof e.from_pretrained;return s(r)&&s(n)&&"function"==typeof o?{AutoTokenizer:r,PreTrainedModel:n,Tensor:o}:void 0})(o)}catch(e){throw N=null,t.error("[SLM] Failed to import Transformers runtime",{runtimeUrl:r,error:x(e)}),e}})()}return N},C=e=>e.replace(/\\/$/,""),O=e=>/^https?:\\/\\//i.test(e.trim()),F=e=>{const t=(e=>{const t=e.trim();if(!t)return"";if(O(t))try{return new URL(t).pathname.replace(/^\\/+|\\/+$/g,"")}catch{return""}return t.replace(/^\\/+|\\/+$/g,"")})(e);return t?C(`https://huggingface.co/${t}/resolve/main`):""},W=(e,t)=>{const r=(e||"").trim();if(O(r))return C(r);const n=F(t||r);return n||C(r)},H=e=>e.replace(/^\\/+/,"").replace(/^resolve\\/main\\//,"").split("?")[0],D=(e,t)=>`${e}/${H(t)}`,K=()=>{const e=d().pageOrigin??("undefined"!=typeof location&&location?location.origin:void 0);if(!e||"null"===e)return null;try{return new URL("/onnx-wasm/",e).toString()}catch{return null}},G=[0,97,115,109],Z=["ort-wasm-simd-threaded.wasm","ort-wasm-simd.wasm","ort-wasm-threaded.wasm","ort-wasm.wasm"],J=e=>e.endsWith("/")?e:`${e}/`,Q=()=>{try{const e=new URL(f),t=e.pathname,r=t.lastIndexOf("/"),n=r>=0?t.slice(0,r+1):"/";return`${e.origin}${n}`}catch{return"https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/"}},X=e=>e.length>=G.length&&G.every((t,r)=>e[r]===t);let V=null;const Y=e=>(V||(V=(async e=>{const t=[d().wasmPaths,K(),Q(),"https://unpkg.com/@xenova/transformers@2.17.2/dist/"].filter(e=>"string"==typeof e&&e.length>0).map(J).filter((e,t,r)=>r.indexOf(e)===t);for(const r of t){let t=!1;for(const n of Z){const o=(()=>{try{return new URL(n,r).toString()}catch{return`${r}${n}`}})();try{const n=await e(o,{cache:"no-store"});if(!n.ok)continue;const s=new Uint8Array(await n.arrayBuffer());if(X(s))return r;t=!0;break}catch{}}t&&E().warn("[SLM] ONNX wasm probe got non-wasm payload",{url:r})}return null})(e)),V);let ee=Promise.resolve();const te=async e=>{const t=ee;let r=()=>{};ee=new Promise(e=>{r=e}),await t;try{return await e()}finally{r()}},re={},ne=(e,t,r,n,o,s)=>{const a=o.map(e=>H(e.trim())).filter(e=>e.length>0),i=new Set(a),l=E(),c=(()=>{try{return new URL(t)}catch{return null}})();return async(o,a)=>{const u="string"==typeof o?o:o instanceof URL?o.toString():o.url,f=(e=>{const t=(()=>{try{return new URL(e).pathname}catch{return e.split("?")[0]||""}})(),r="/resolve/main/",n=t.indexOf(r);if(n>=0){const e=t.slice(n+14);return H(e)}if(!c)return null;const o=c.pathname.replace(/\\/$/,"");if(!t.startsWith(`${o}/`))return null;const s=t.slice(o.length+1);return H(s)})(u);if(!f){if(!(/\\.wasm(?:\\?|$)/i.test(u)||/onnxruntime|ort-wasm/i.test(u)))return s(o,a);try{return await s(o,a)}catch(t){throw l.error("[SLM][fetch] non-model wasm/ort request failed",{modelId:e,requestUrl:u,error:x(t)}),t}}const m=(e=>{const t=H(e);if(!t)return null;if(0===i.size||i.has(t))return t;if(t.startsWith("onnx/")&&t.endsWith(".onnx")&&!t.endsWith("_quantized.onnx")){const e=t.replace(/\\.onnx$/,"_quantized.onnx");if(i.has(e))return e}return null})(f);if(!m)return l.warn("[SLM] Unexpected model file request; falling back to original fetch",{file:f,modelId:e}),s(o,a);const d=(e=>{const r=H(e),n=[],o=e=>{n.includes(e)||n.push(e)};try{const e=new URL(t),n=e.toString().endsWith("/")?e.toString():`${e.toString()}/`;t.endsWith("/resolve/main")?o(new URL(r,n).toString()):(o(new URL(r,n).toString()),o(new URL(`resolve/main/${r}`,n).toString()))}catch{t.endsWith("/resolve/main")?o(`${t}/${r}`):(o(`${t}/${r}`),o(`${t}/resolve/main/${r}`))}return n})(m),p=H(m),g=D(e,p);let h=re[g]||r[g]||re[p]||r[p]||r[`onnx/${p}`]||re[`onnx/${p}`];if(!h&&p.startsWith("onnx/")){const t=p.replace("onnx/","");h=r[t]||re[t]||r[D(e,t)]||re[D(e,t)]}if(h)return new Response(h);try{for(const e of d){const t=await s(e,a);if(t.ok){const e=await t.blob();return re[g]=e,n&&n(g,e),new Response(e)}}return new Response("required_file_not_found",{status:404,statusText:"Not Found"})}catch(t){return l.warn("[SLM] Model file fetch failed",{modelId:e,file:m,candidateCount:d.length,error:x(t)}),new Response("model_file_fetch_failed",{status:502,statusText:"Bad Gateway"})}}},oe="zgScoreRecorder",se=e=>({[oe]:e}),ae=(e,t,r)=>{let n=-1/0;for(let o=0;o<r;o+=1)n=Math.max(n,e[t+o]);let o=0;for(let s=0;s<r;s+=1)o+=Math.exp(e[t+s]-n);return n+Math.log(o)},ie=e=>{const t=e;if(!t||t.__zgScoreHooks)return Boolean(t?.__zgScoreHooks);const{getStartBeams:r,runBeam:n,updateBeam:o}=t;return"function"==typeof r&&"function"==typeof n&&"function"==typeof o&&(t.getStartBeams=(...e)=>{const n=r.apply(t,e),o=e[1],s=o?.[oe];if(s)for(const e of n)e[oe]=s;return n},t.runBeam=async e=>{const r=await n.call(t,e),o=e[oe];return o&&r?.logits&&((e,t)=>{const{offset:r,size:n}=(e=>{const t=e.dims,r=t[t.length-1];return{offset:((t.length>=2?t[t.length-2]:1)-1)*r,size:r}})(t);e.pending={row:t.data,offset:r,size:n,logSumExp:ae(t.data,r,n)}})(o,r.logits),r},t.updateBeam=(e,r)=>{const n=o.call(t,e,r),s=e[oe];return s&&((e,t)=>{const r=e.pending;if(e.pending=void 0,!r||e.sawEos)return;if(e.eosTokenIds.includes(t))return void(e.sawEos=!0);const n=Math.exp(r.row[r.offset+t]-r.logSumExp);e.logProbs.push(Math.log(Math.max(n,1e-9)))})(s,r),n},t.__zgScoreHooks=!0,!0)},le=e=>{const t=e,r=t?.generation_config?.eos_token_id??t?.config?.eos_token_id;return(Array.isArray(r)?r:[r]).filter(e=>"number"==typeof e)},ce=(e,t)=>"sigmoid"===e?(e=>Array.from(e,e=>1/(1+Math.exp(-e))))(t):(e=>{const t=Array.from(e);if(0===t.length)return[];const r=Math.max(...t),n=t.map(e=>Math.exp(e-r)),o=n.reduce((e,t)=>e+t,0);return n.map(e=>e/o)})(t),ue=e=>"number"==typeof e&&Number.isFinite(e)&&e>0&&e<1e6?Math.floor(e):void 0,fe=e=>{const t=new BigInt64Array(e.length);return e.forEach((e,r)=>{t[r]=BigInt(e)}),t},me=(e,t,r)=>{const n=r.config??{},o=r.session,s="multi_label_classification"===n.problem_type?"sigmoid":"softmax";const a=((e,t)=>{const r=[ue(e.max_position_embeddings),ue(e.n_positions),ue(t.model_max_length)].filter(e=>void 0!==e);return r.length>0?Math.min(...r):512})(n,t),i=t.encode(""),l=i.length>0?i[i.length-1]:void 0,c=o.outputNames.includes("logits")?"logits":o.outputNames[0],u=n.id2label&&"object"==typeof n.id2label?Object.keys(n.id2label).length:0;return{labelCount:u,maxLength:a,activation:s,async classify(r,i){const u=r.slice(0,16*a),f=((e,t,r)=>{if(e.length<=t)return e;const n=e[e.length-1];return void 0!==r&&n===r&&t>=2?[...e.slice(0,t-1),n]:e.slice(0,t)})(t.encode(u),a,l),m=await o.run((t=>{const r=[1,t.length],n={};for(const s of o.inputNames)if("input_ids"===s)n[s]=new e.Tensor("int64",fe(t),r);else if("attention_mask"===s)n[s]=new e.Tensor("int64",fe(t.map(()=>1)),r);else{if("token_type_ids"!==s)throw new Error(`sequence_classification_unsupported_input:${s}`);n[s]=new e.Tensor("int64",fe(t.map(()=>0)),r)}return n})(f)),d=m[c];if(!d||!d.data||0===d.data.length)throw new Error("sequence_classification_empty_logits");const p=ce(s,d.data),g=((e,t)=>{const r=e.id2label,n=r&&"object"==typeof r?r:{};return Array.from({length:t},(e,t)=>{const r=n[String(t)];return"string"==typeof r&&r.length>0?r:`LABEL_${t}`})})(n,p.length);return((e,t,r)=>{const n=Math.max(1,Math.min(Math.floor(r),e.length)),o=e.map((e,t)=>({score:e,index:t})).sort((e,t)=>t.score-e.score).slice(0,n),s={};for(const{score:e,index:r}of o)s[t[r]??`LABEL_${r}`]=e;return s})(p,g,"number"==typeof(h=i)&&Number.isFinite(h)&&h>=1?Math.floor(h):50);var h}}},de={summary:"summarization",iab_classify:"text-classification",classification:"zero-shot-classification",text_generation:"text2text-generation"},pe=new Set([L,$,q,P,j,I,B]),ge={[$]:"text2text-generation",[q]:"zero-shot-classification",[P]:"token-classification",[j]:"question-answering",[I]:"feature-extraction",[B]:"fill-mask"},he=e=>{const t=(e=>{if("string"!=typeof e)return;const t=e.trim().toLowerCase();return t.length>0?t:void 0})(e.inferenceKind);return t&&pe.has(t)?t:"task"},ye=8192,we=/\\[MASK\\]|<mask>/g,be=e=>"number"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,xe=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("input_text_required");return e},ke=e=>{if("string"==typeof e)return e;if(Array.isArray(e)&&e.length){const t=e[0];if(t&&"string"==typeof t.summary_text)return t.summary_text;if(t&&"string"==typeof t.generated_text)return t.generated_text;if(t&&"string"==typeof t.label)return t.label;try{return JSON.stringify(t)}catch{return String(t??"")}}if(e&&"object"==typeof e){const t=e;if("string"==typeof t.summary_text)return t.summary_text;if("string"==typeof t.generated_text)return t.generated_text;if("string"==typeof t.label)return t.label;try{return JSON.stringify(t)}catch{return String(t)}}return""},_e=e=>{if(Array.isArray(e)){const t=e.filter(e=>"string"==typeof e);return t.length>0?t:void 0}if("string"==typeof e&&e.length>0)return[e]},Me=(e,t)=>{const r=(e??"").trim();return r?r.slice(0,1024):t},ve=e=>{const t=/^([BI])-(.+)$/.exec(e);return t?{prefix:t[1],label:t[2]}:{prefix:null,label:e}},Te=(e,t)=>{const r=Array.isArray(t)?t:[],n=[],o=[];let s=null,a=-2;const i=()=>{if(!s)return;const t=s.pieces.join(" "),r=o[o.length-1],{start:n,end:a}=((e,t,r)=>{const n=e.indexOf(t,r);if(n>=0)return{start:n,end:n+t.length};const o=t.split(/\\s+/).filter(Boolean).map(e=>e.replace(/[.*+?^${}()|[\\]\\\\]/g,"\\\\$&")).join("\\\\s*");if(!o)return{start:-1,end:-1};const s=new RegExp(o).exec(e.slice(r));return s?{start:r+s.index,end:r+s.index+s[0].length}:{start:-1,end:-1}})(e,t,r&&r.end>=0?r.end:0),i=s.scores.reduce((e,t)=>e+t,0)/Math.max(1,s.scores.length);o.push({label:s.label,text:t,start:n,end:a,score:Number(i.toFixed(6))}),s=null};for(const e of r){const t="string"==typeof e?.entity?e.entity:"O",r="string"==typeof e?.word?e.word:"",o="number"==typeof e?.score?e.score:0,l="number"==typeof e?.index?e.index:a+1,c=r.startsWith("##")&&l===a+1,u=c?r.slice(2):r;if(a=l,n.push({token:r,label:t,score:Number(o.toFixed(6))}),c&&s){s.pieces[s.pieces.length-1]+=u,s.scores.push(o);continue}const{prefix:f,label:m}=ve(t);"O"!==t&&u?s&&"B"!==f&&s.label===m?(s.pieces.push(u),s.scores.push(o)):(i(),s={label:m,pieces:[u],scores:[o]}):i()}return i(),{entities:o,tokens:n}},Se=e=>{if(Array.isArray(e)){return e.flat(1/0).filter(e=>"number"==typeof e)}const t=e?.data;return t&&"number"==typeof t.length?Array.from(t):[]},Ee=async(e,t,r)=>{const{pipeline:n,pipelineTask:o}=e,{result:s,ms:a}=await A(async()=>{if("zero-shot-classification"===o){if(!r?.categories||0===r.categories.length)throw new Error("classification_categories_required");return n(t,r.categories)}return"summarization"===o?n(t,{max_new_tokens:r?.maxNewTokens??64,min_length:1,do_sample:!1}):"text2text-generation"===o?n(t,{max_new_tokens:r?.maxNewTokens??128,do_sample:!1}):n(t)});return{raw:s,ms:a}},Ae=async(e,t,r)=>{try{return await Ee(e,t,r)}catch(n){if(!(e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("invalid array length"))(n)||t.length<=256)throw n;const o=t.slice(0,256);return await Ee(e,o,r)}};class Le{constructor(e,t){this.config=e,this.state=t,this.loadModelMs=t.loadModelMs}async runInference(e){const t=he(this.config);if(t===L)return this.runSequenceClassification(e);if(t===$)return this.runSeq2Seq(e);if(t===q)return this.runZeroShot(e,!0);if(t===P)return this.runTokenClassification(e);if(t===j)return this.runQuestionAnswering(e);if(t===I)return this.runTextEmbedding(e);if(t===B)return this.runFillMask(e);const r=this.config.taskType,n=Me(e.text,"summarize this text");if("classification"===r)return this.runZeroShot(e);if("iab_classify"===r){const{raw:e,ms:t}=await Ae(this.state,n);return{output:e,inferenceMs:t}}if("summary"===r){const{raw:t,ms:r}=await Ae(this.state,n,{maxNewTokens:e.maxNewTokens});return{output:{text:ke(t)},inferenceMs:r}}if("text_generation"===r){const{raw:t,ms:r}=await Ae(this.state,n,{maxNewTokens:e.maxNewTokens});return{output:{text:ke(t)},inferenceMs:r}}const{raw:o,ms:s}=await Ae(this.state,n);return{output:o,inferenceMs:s}}async runZeroShot(e,t=!1){const r=t?xe(e.text).slice(0,ye):Me(e.text,"summarize this text"),n=_e(e.categories)??_e(e.category),{raw:o,ms:s}=await Ae(this.state,r,{categories:n});if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return Array.isArray(t.labels)&&Array.isArray(t.scores)})(o)){return{output:(e=>{const t=e.labels,r=e.scores;if(!Array.isArray(t)||!Array.isArray(r))return null;const n=t.flatMap((e,t)=>{const n=r[t];return"string"==typeof e&&"number"==typeof n?[[e,n]]:[]});return n.length>0?Object.fromEntries(n):null})(o)??o,inferenceMs:s}}return{output:o,inferenceMs:s}}async runSequenceClassification(e){const t=this.state.classifier;if(!t)throw new Error("sequence_classifier_not_loaded");const r=xe(e.text),n=e.topK??e.top_k,{result:o,ms:s}=await A(()=>t.classify(r,"number"==typeof n?n:void 0));return{output:o,inferenceMs:s}}async runSeq2Seq(e){const t=xe(e.text).slice(0,8192),r=be(e.maxNewTokens)??this.state.defaultMaxNewTokens??48,{pipeline:n,scoring:o}=this.state,s=o?{eosTokenIds:o.eosTokenIds,logProbs:[],sawEos:!1}:void 0;const{result:a,ms:i}=await A(()=>n(t,{max_new_tokens:r,do_sample:!1,num_beams:1,...s?se(s):{}})),l=ke(a).trim(),c=s?(e=>{const t=e.logProbs.length;return 0===t?.5:Math.exp(e.logProbs.reduce((e,t)=>e+t,0)/t)})(s):.5;return{output:{text:l,score:c},inferenceMs:i}}async runTokenClassification(e){const t=xe(e.text).slice(0,ye),{result:r,ms:n}=await A(()=>this.state.pipeline(t,{ignore_labels:[]}));return{output:Te(t,r),inferenceMs:n}}async runQuestionAnswering(e){const t="string"==typeof e.question?e.question.trim():"";if(!t)throw new Error("input_question_required");const r=("string"==typeof e.context&&e.context.trim().length>0?e.context:xe(e.text)).slice(0,ye),n=this.state.pipeline,{result:o,ms:s}=await A(()=>n(t,r,{topk:1})),a=Array.isArray(o)?o[0]:o,i="string"==typeof a?.answer?a.answer.trim():"",l="number"==typeof a?.score?a.score:0,c=i?r.indexOf(i):-1;return{output:{answer:i,score:l,start:c,end:c>=0?c+i.length:-1},inferenceMs:s}}async runTextEmbedding(e){const t=xe(e.text).slice(0,ye),{result:r,ms:n}=await A(()=>this.state.pipeline(t,{pooling:"mean",normalize:!0}));return{output:{embedding:Se(r)},inferenceMs:n}}async runFillMask(e){const t=this.state.pipeline.tokenizer?.mask_token,r=((e,t)=>!t||e.includes(t)?e:e.replace(we,t))(xe(e.text).slice(0,ye),"string"==typeof t?t:void 0),n=(e=>be(e.topK)??be(e.top_k))(e)??5,{result:o,ms:s}=await A(()=>this.state.pipeline(r,{topk:n})),a=Array.isArray(o)?o:[],i=a.map(e=>({token:"string"==typeof e?.token_str?e.token_str.trim():"",tokenId:"number"==typeof e?.token?e.token:-1,score:"number"==typeof e?.score?e.score:0})),l=a[0];return{output:{predictions:i,text:"string"==typeof l?.sequence?l.sequence:r},inferenceMs:s}}async runSample(e){const t=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:"response from processing sample"};try{const n=await this.runInference({...e,text:e.text}),o=Math.round(performance.now()-t);return null!=(r=n.output)&&("string"==typeof r?r.trim().length>0:Array.isArray(r)?r.length>0:"object"!=typeof r||Object.keys(r).length>0)?{ok:!0,processingTimeMs:o,error:!1}:{ok:!1,processingTimeMs:o,error:!0,errorMessage:"response from processing sample"}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}var r}}const $e=async(e,t,r,n)=>{const o=he(e),s=E();try{await U()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const a=C(W(e.modelUrl,e.modelRepoId)),i=(e=>{const t=he(e);return ge[t]??de[e.taskType]??e.taskType})(e),l=O(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!l)throw new Error("[SLM] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const c=await te(async()=>{const c=R(),f=c.TransformersEnv||{};f.allowRemoteModels=!0,f.allowLocalModels=!0,z(f),f.backends||(f.backends={}),f.backends.onnx||(f.backends.onnx={}),f.backends.onnx.wasm||(f.backends.onnx.wasm={});const m=s.isEnabled()?"error":"fatal";f?.backends?.onnx?.env&&(f.backends.onnx.env.logLevel=m);const p=u(void 0,n?.wasm);f.backends.onnx.wasm.proxy=p.proxy,f.backends.onnx.wasm.numThreads=d().forceSingleThread?1:p.numThreads;const g=globalThis.fetch.bind(globalThis),h=await Y(g);if(h)f.backends.onnx.wasm.wasmPaths=h;else try{delete f.backends.onnx.wasm.wasmPaths}catch{f.backends.onnx.wasm.wasmPaths=void 0}"logLevel"in f&&(f.logLevel=m);const y=globalThis.ort;y?.env&&(y.env.logLevel=m),f.fetch=ne(e.modelId,a,t,r,(e.requiredFiles??[]).map(e=>e.name),g),c.TransformersEnv=f,globalThis.fetch=f.fetch;const w={device:"wasm",quantized:e.quantized,progress_callback:()=>{}},b=()=>A(async()=>{if(o===L){const e=(()=>{const e=R().TransformersLib;if(!e)throw new Error("transformers_lib_unavailable");return e})(),[t,r]=await Promise.all([e.AutoTokenizer.from_pretrained(l,w),e.PreTrainedModel.from_pretrained(l,w)]);return{classifier:me(e,t,r)}}const e=c.TransformersPipeline;if(!e)throw new Error("transformers_pipeline_unavailable");return{pipeline:await e(i,l,w)}});try{return await b()}catch(e){const t=f?.backends?.onnx?.wasm,r=Boolean(t&&"wasmPaths"in t&&t.wasmPaths);let n=e;if(t){const e=t.simd,r=t.numThreads,o=t.proxy;t.simd=!1,t.numThreads=1,t.proxy=!1;try{return await b()}catch(s){n=s,t.simd=e,t.numThreads=r,t.proxy=o}}if(!r||!t){const e=n instanceof Error?n.message:String(n);throw new Error(`pipeline_load_failed:${e}`)}const o=t.wasmPaths;try{delete t.wasmPaths}catch{t.wasmPaths=void 0}try{return await b()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`pipeline_load_failed:${t}`)}finally{t.wasmPaths=o}}finally{globalThis.fetch=g}}),{result:f,ms:m}=c;if(f.classifier){return{pipeline:()=>Promise.reject(new Error("pipeline_not_loaded")),pipelineTask:o,loadModelMs:m,classifier:f.classifier}}const p=f.pipeline,g={pipeline:p,pipelineTask:i,loadModelMs:m};if(o===$){const t=p.model;g.defaultMaxNewTokens=be(t?.generation_config?.max_new_tokens)??48,ie(t)?g.scoring={eosTokenIds:le(t)}:E().warn("[SLM] seq2seq score hooks unavailable; score defaults to 0.5",{modelId:e.modelId})}return g};class qe{constructor(e){this.state=e,this.loadModelMs=e.loadModelMs}async runInference(e){const t=(e.text??"").trim();if(!t)return{output:{entities:[]},inferenceMs:0};const r="number"==typeof e.threshold&&Number.isFinite(e.threshold)?e.threshold:.4,n=(e.usecase??"ner").toLowerCase(),{result:o,ms:s}=await A(async()=>this.state.pipeline(t));var a,i;const l=((e,t)=>e.filter(e=>e.score>=t))((a=o,i=t,Array.isArray(a)?a.flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e,r="string"==typeof t.entity_group?t.entity_group:"string"==typeof t.entity?t.entity:"string"==typeof t.label?t.label:null;if(!r)return[];const n="number"==typeof t.score?t.score:0,o="number"==typeof t.start?t.start:-1,s="number"==typeof t.end?t.end:-1,a="string"==typeof t.word?t.word:"string"==typeof t.text?t.text:o>=0&&s>o?i.slice(o,s):"";return a?[{text:a,label:r,score:n,start:o,end:s}]:[]}):[]),r),c=Array.isArray(e.labels)?e.labels:void 0,u=((e,t)=>{if(!t||0===t.length)return e;const r=new Set(t.map(e=>e.toLowerCase()));return e.filter(e=>r.has(e.label.toLowerCase()))})(l,c);if("redact"===n){const r="string"==typeof e.mask&&e.mask.length>0?e.mask:"[REDACTED]",n=((e,t,r)=>{if(0===t.length)return e;const n=[...t].sort((e,t)=>t.start-e.start);let o=e;for(const e of n){if(e.start<0||e.end<=e.start)continue;const t=r.includes("LABEL")?r.replace("LABEL",e.label):r;o=o.slice(0,e.start)+t+o.slice(e.end)}return o})(t,u,r);return{output:{text:n,entities:u},inferenceMs:s}}if("json"===n){const t=((e,t)=>{if(!e||"object"!=typeof e)return{};const r={};for(const[n,o]of Object.entries(e)){const e=Array.isArray(o)?o:[],s={};for(const r of e){if("string"!=typeof r)continue;const e=r.split("::")[0],n=t.find(t=>t.label.toLowerCase()===e.toLowerCase());n&&(s[e]=n.text)}r[n]=s}return r})(e.schema,u);return{output:t,inferenceMs:s}}if("classification"===n){const e=((e,t)=>{const r={};for(const n of t){const t=e.filter(e=>e.label.toLowerCase()===n.toLowerCase()).reduce((e,t)=>Math.max(e,t.score),0);r[n]=t}return r})(l,c??[]);return{output:e,inferenceMs:s}}return{output:{entities:u},inferenceMs:s}}async runSample(e){const t=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:"response from processing sample"};try{return await this.runInference({text:e.text,labels:e.labels,threshold:e.threshold,usecase:e.usecase??"ner",schema:e.schema,mask:e.mask,categories:e.categories}),{ok:!0,processingTimeMs:Math.round(performance.now()-t),error:!1,errorMessage:void 0}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}}}const Pe=async(e,t,r)=>{const n=E();try{await U()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const o=C(W(e.modelUrl,e.modelRepoId)),s=O(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!s)throw new Error("[Transformers] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const a=await te(async()=>{const a=R(),i=a.TransformersEnv||{};i.allowRemoteModels=!0,i.allowLocalModels=!0,i.backends||(i.backends={}),i.backends.onnx||(i.backends.onnx={}),i.backends.onnx.wasm||(i.backends.onnx.wasm={}),i.backends.onnx.wasm.proxy=!1,i.backends.onnx.wasm.numThreads=1;const l=globalThis.fetch.bind(globalThis),c=await Y(l);c&&(i.backends.onnx.wasm.wasmPaths=c),i.fetch=ne(e.modelId,o,t,r,(e.requiredFiles??[]).map(e=>e.name),l),a.TransformersEnv=i,globalThis.fetch=i.fetch;try{return await A(()=>{const t=a.TransformersPipeline;if(!t)throw new Error("transformers_pipeline_unavailable");return t("token-classification",s,{device:"wasm",quantized:e.quantized,aggregation_strategy:"simple",progress_callback:()=>{}})})}catch(e){const t=e instanceof Error?e.message:String(e);throw n.warn("[Transformers] token-classification pipeline load failed",{message:t}),new Error(`transformers_pipeline_load_failed:${t}`)}finally{globalThis.fetch=l}}),{result:i,ms:l}=a;return{pipeline:i,loadModelMs:l}},je="transformers_runtime_load_failed",Ie=e=>{if(void 0===e)return;if(e instanceof Error)return{error:x(e)};const t={};for(const[r,n]of Object.entries(e))t[r]=n instanceof Error?x(n):n;return t},Be=e=>{const t=e instanceof Error?e.name:"Error",r=e instanceof Error?e.message:String(e),n={name:t,message:r},o=e?.code;return"string"==typeof o?n.code=o:r.startsWith(je)&&(n.code=je),n};((e,t)=>{const r=new Map,n=t=>e.postMessage(t),o=e=>{const t=r.get(e);if(!t)throw new Error("worker_model_not_loaded");return t},s=async e=>{switch(e.type){case"init":{const{config:t}=e;return((e,t)=>{S=new T(e,t)})({enableConsoleLogs:t.logging.enabled,locationData:!1,events:!1},(e,t,r)=>n({type:"log",level:e,message:t,fields:Ie(r)})),t.logging.enabled||"undefined"!=typeof document||(()=>{const e=()=>{};console.log=e,console.info=e,console.debug=e,console.warn=e,console.error=e})(),(e=>{const t={...m};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);m=t})(t.runtime),{protocol:1}}case"load":{const n=t[e.framework];if(!n)throw new Error(`worker_framework_unsupported:${e.framework}`);const o={},s=await n(e.slm,e.cachedFiles??{},(e,t)=>{o[e]=t},{wasm:e.wasm});r.set(e.handle,s);return{loadModelMs:s.loadModelMs,downloadedFiles:o}}case"infer":return o(e.handle).runInference(e.input);case"sample":return o(e.handle).runSample(e.sample);case"dispose":{const t=r.get(e.handle);return r.delete(e.handle),await(t?.dispose?.()),!0}default:throw new Error("worker_unknown_message")}};e.onmessage=e=>{const t=e?.data;t&&"object"==typeof t&&"number"==typeof t.id&&s(t).then(e=>n({type:"result",id:t.id,ok:!0,value:e}),e=>n({type:"result",id:t.id,ok:!1,error:Be(e)}))},n({type:"ready",protocol:1})})(self,{ONNX:async(e,t,r,n)=>{const o=await $e(e,t,r,n);return new Le(e,o)},Transformers:async(e,t,r)=>{const n=await Pe(e,t,r);return new qe(n)}});\n',Go=["__ZGPU_WORKER","SOURCE__"].join("_"),Ho=()=>Do!==Go?Do:null;class Jo extends Error{constructor(e,t){super(t?`${e}:${t}`:e),this.name="InferenceWorkerError",this.code=e}}class Xo{constructor(e){this.options=e,this.worker=null,this.ready=null,this.booted=!1,this.dead=null,this.nextId=1,this.handleSeq=0,this.pending=new Map,this.loaded=new Map}isAlive(){return null!==this.worker&&null===this.dead}loadedCount(){return this.loaded.size}async load(e,t,r,o){await this.boot();const n="m"+ ++this.handleSeq,s=await this.request({type:"load",handle:n,framework:e,slm:t,cachedFiles:r,wasm:o});this.loaded.set(n,t.modelId);return{executor:{loadModelMs:s.loadModelMs,runInference:e=>this.request({type:"infer",handle:n,input:e}),runSample:e=>this.request({type:"sample",handle:n,sample:e}),dispose:async()=>{this.loaded.delete(n);try{await this.request({type:"dispose",handle:n})}catch{}0===this.loaded.size&&this.terminate()}},downloadedFiles:s.downloadedFiles??{}}}terminate(e=new Jo("worker_terminated")){const t=this.worker;if(this.worker=null,this.ready=null,this.booted=!1,this.loaded.clear(),t){try{t.terminate()}catch{}k().info("[Worker] Inference worker terminated",{code:e.code,pending:this.pending.size})}this.rejectAll(e)}boot(){if(this.dead)return Promise.reject(this.dead);if(this.ready)return this.ready;let e;try{e=this.options.spawn()}catch(e){return Promise.reject(new Jo("worker_spawn_failed",m(e)))}return this.worker=e,this.ready=new Promise((t,r)=>{let o=!1;const n=this.options.bootTimeoutMs??2e4,s=t=>{if(!o){o=!0,clearTimeout(a),this.worker=null,this.ready=null;try{e.terminate()}catch{}r(t)}},i=()=>{o||(o=!0,clearTimeout(a),this.booted=!0,t())},a=setTimeout(()=>s(new Jo("worker_boot_timeout",`${n}ms`)),n);e.onerror=e=>{const t="string"==typeof e?.message?e.message:void 0;this.booted?this.crash(new Jo("worker_crashed",t)):s(new Jo("worker_boot_failed",t))},e.onmessageerror=()=>{this.booted||s(new Jo("worker_boot_failed","messageerror"))},e.onmessage=e=>{const t=e?.data;if(t&&"object"==typeof t)return"ready"===t.type?1!==t.protocol?void s(new Jo("worker_protocol_mismatch",String(t.protocol))):void this.request({type:"init",config:this.options.bootConfig()}).then(i,e=>s(new Jo("worker_boot_failed",m(e)))):void this.dispatch(t)}}),this.ready}request(e){if(this.dead)return Promise.reject(this.dead);const t=this.worker;if(!t)return Promise.reject(new Jo("worker_unavailable"));const r=this.nextId++;return new Promise((o,n)=>{this.pending.set(r,{resolve:o,reject:n});try{t.postMessage({...e,id:r})}catch(e){this.pending.delete(r),n(new Jo("worker_post_failed",m(e)))}})}dispatch(e){if("result"===e.type){const t=this.pending.get(e.id);if(!t)return;return this.pending.delete(e.id),void(e.ok?t.resolve(e.value):t.reject((e=>{const t="RangeError"===e.name?new RangeError(e.message):new Error(e.message);return e.name&&"RangeError"!==e.name&&(t.name=e.name),e.code&&(t.code=e.code),t})(e.error)))}if("log"===e.type){const t=k(),r="string"==typeof e.message?e.message:"[worker log]";switch(e.level){case"error":t.error(r,e.fields);break;case"warn":t.warn(r,e.fields);break;case"debug":t.debug(r,e.fields);break;default:t.info(r,e.fields)}}}crash(e){if(this.dead)return;this.dead=e;const t=[...this.loaded.values()];this.terminate(e),this.options.onCrash?.(e,t)}rejectAll(e){const t=[...this.pending.values()];this.pending.clear();for(const r of t)r.reject(e)}}const Zo="herogpu-inference",Qo={worker:!0};let Yo={...Qo},en=null,tn=!1,rn=null;const on=e=>{Yo={...Qo,...e??{}}},nn=()=>Yo.workerUrl??Zr().workerUrl,sn=()=>{const e=nn();if(e)return new Worker(e,{type:"module",name:Zo});const t=Ho();if(!t)throw new Error("worker_source_unavailable");const r=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));try{return new Worker(r,{type:"module",name:Zo})}finally{URL.revokeObjectURL(r)}},an=()=>{const e=Zr(),t=e.pageOrigin??("undefined"!=typeof location&&location?location.origin:void 0);return{protocol:1,logging:{enabled:k().isEnabled()},runtime:{...e,pageOrigin:t}}},ln=(e,t,r)=>{en||(en={code:e,message:t});const o=rn;rn=null,o?.terminate(),k().warn("[Worker] Inference worker unavailable; models run on the main thread",{code:e,message:t}),r&&!tn&&(tn=!0,$e().report("guardrail.pressure_warning",{code:"inference_worker_unavailable",message:`${e}:${t}`.slice(0,256),data:{reason:e,fallback:"main_thread"}}))},dn=(e,t)=>async(r,o,n,s)=>{if(!Yo.worker||en)return t(r,o,n,s);const i="function"!=typeof globalThis.Worker?{code:"worker_api_unavailable",message:"Worker is not defined",report:!0}:nn()||Ho()?null:{code:"worker_source_unavailable",message:"no worker script in this build",report:!1};if(i)return ln(i.code,i.message,i.report),t(r,o,n,s);const a=(rn||(rn=new Xo({spawn:sn,bootConfig:an,onCrash:(e,t)=>{for(const e of t)K(e,void 0);ln(e.code,e.message,!0)}})),rn);try{const{executor:t,downloadedFiles:i}=await a.load(e,r,o,s?.wasm??Fe().wasm);for(const[e,t]of Object.entries(i))n(e,t);return k().info("[Worker] Model loaded off the main thread",{modelId:r.modelId,framework:e,loadModelMs:t.loadModelMs,downloadedFiles:Object.keys(i).length}),t}catch(e){if(!(e=>e instanceof Jo||e instanceof Error&&"transformers_runtime_load_failed"===e.code)(e))throw e;return ln((e=>{if(e instanceof Jo)return e.code;const t=e?.code;return"string"==typeof t?t:"worker_error"})(e),m(e),!0),t(r,o,n,s)}},cn="app_inference_chosen_model",un="app_inference_unfit_models",mn=new Map,fn=e=>{try{const t=window.localStorage.getItem(v(e));if(null!==t)return t}catch{}return mn.get(e)??null},pn=(e,t)=>{mn.set(e,t);try{window.localStorage.setItem(v(e),t)}catch{}},gn=e=>{mn.delete(e);try{window.localStorage.removeItem(v(e))}catch{}},hn=()=>{const e=fn(cn)?.trim();return e||null},yn=()=>{gn(cn)},wn=()=>{const e=fn(un);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.modelId&&"string"==typeof e.modelVersion&&"string"==typeof e.reason&&"string"==typeof e.sdkVersion&&"number"==typeof e.at).slice(0,16):[]}catch{return[]}},bn=e=>{const t=[...e].sort((e,t)=>e.at-t.at).slice(-16);0===t.length?gn(un):pn(un,JSON.stringify(t))},kn=(e,t=Date.now())=>((e,t=Date.now())=>wn().filter(r=>r.sdkVersion===e&&t-r.at<864e5))(e,t).map(e=>({modelId:e.modelId,modelVersion:e.modelVersion,reason:e.reason}));class vn extends Error{constructor(e,t,r){super(t),this.name="ZeroGpuError",this.code=e,void 0!==r&&(this.cause=r)}}const _n=vn;class xn extends vn{constructor(e,t){super(`not_contributing_${e}`,`not contributing: ${e}${t?` (${t})`:""}`),this.name="NotContributingError",this.state=e,t&&(this.registryReason=t)}}class In extends vn{constructor(e,t){super("model_not_eligible",`${e} is not eligible here: ${t}`),this.name="ModelNotEligibleError",this.modelId=e,this.reason=t}}class Mn extends vn{constructor(e,t){super("inference_failed",e,t),this.name="LocalInferenceFailedError"}}const Tn=e=>e instanceof vn||e instanceof Error&&"string"==typeof e.code,Sn=Tn,An="[App]";let $n=null,En=!1,qn=null,Pn=null;const Ln=()=>{const e=ee(),t=e?.modelInfo?.modelId;return t&&D(t)?t:null},Cn=()=>{if(st()||rt()||!oe())return"stopped";if(En)return"switching";if("degraded"===ot())return"degraded";const e=W.phase??"idle";if("declined"===e)return"declined";if("preparing"===e)return"preparing";if("running"===e){const e=ee();if(Z()?.isActive()&&"error"!==e?.status&&Ln())return X()?"contributing":"preparing"}return"registering"},Bn=async()=>{const e=oe(),t=ee();if(!e?.edgeOperatorKey||!t)throw new xn("stopped");const r=await(async e=>({...e,battery:await P()??e.battery,connection:L()??e.connection}))(t.deviceInfo),o={deviceId:t.deviceId,sdkVersion:t.config.sdkVersion,cachedModels:jo().map(e=>({modelId:e.modelId,modelVersion:e.modelVersion||"1"})),device:r,unfitModels:kn(t.config.sdkVersion),...er()};let n;try{n=await(async(e,t,r)=>{const o=k(),n=e?.orchestrator;if(!n?.baseUrl)throw new Error("Invalid SDK config: orchestrator.baseUrl is required");const s=`${n.baseUrl}/models/eligible`,i={"Content-Type":"application/json"},a=r?.edgeOperatorKey?.trim();a&&(i["x-edge-operator-key"]=a);const l=await fetch(s,{method:"POST",headers:i,body:JSON.stringify(t)}),d=await R(l),c=U(d);if(!l.ok&&!c){const e="string"==typeof d?d:JSON.stringify(d??"");throw o.warn("Eligible models request failed",{status:l.status,message:e.slice(0,200)}),new O(l.status,e)}const u=d&&"object"==typeof d?d:{},m=Array.isArray(u.models)?u.models:[];return o.info("Eligible models received",{lines:m.length,eligible:m.filter(e=>!0===e?.eligible).length,refusalReason:c??void 0}),{deviceId:"string"==typeof u.deviceId?u.deviceId:t.deviceId,edgeSdkType:"string"==typeof u.edgeSdkType?u.edgeSdkType:"unknown",guardMode:"string"==typeof u.guardMode?u.guardMode:void 0,models:m,...c?{refusalReason:c}:{}}})(t.config,o,{edgeOperatorKey:e.edgeOperatorKey})}catch(e){throw new vn((e=>{if(e instanceof O)return`http_${e.status}`;const t=e instanceof Error?e.message:String(e);return/timeout/i.test(t)?"timeout":"network"})(e),`eligible models: ${m(e)}`,e)}if(n.refusalReason)throw new xn("declined",n.refusalReason);const s=((e,t,r)=>{const o=new Set(t.map(e=>`${e.modelId}|${e.modelVersion||"1"}`));return e.filter(e=>"string"==typeof e?.modelId&&e.modelId.length>0).map(e=>{const t="string"==typeof e.modelVersion&&e.modelVersion?e.modelVersion:"1",n={};for(const[t,r]of Object.entries(e.detail??{}))n[t]="string"==typeof r?r:JSON.stringify(r);return{modelId:e.modelId,modelVersion:t,displayName:e.modelDisplayName,taskType:e.taskType,inferenceKind:e.inferenceKind,inferenceFramework:e.inferenceFramework,sizeBytes:e.sizeBytes,maxTokens:e.maxTokens,eligible:!0===e.eligible,reason:e.reason,rule:e.rule,detail:n,downloaded:o.has(`${e.modelId}|${t}`),active:null!==r&&r===e.modelId}})})(n.models,jo(),Ln());return qn=s,k().info(`${An} Eligible models`,{lines:s.length,eligible:s.filter(e=>e.eligible).length}),s},Nn=(e,t)=>{hn()===e&&yn(),$n?.modelId===e&&($n.refusalReason=t),k().info(`${An} Chosen model not kept`,{modelId:e,reason:t}),it("modelChoiceRefused",{modelId:e,reason:t})},Rn=e=>{En=!1;const t=$n;t&&($n=null,t.reject(e))};let Un=0,jn=!1;const On=()=>{const e=(W.registrationSettings??null)?.device_timeout_interval_seconds;return"number"==typeof e&&Number.isFinite(e)&&e>0?e:600},Vn=(e,t)=>{const r=k();if(vt())return void r.info("[WS] Re-registration already scheduled; skipping",{reason:t});if(st())return void r.debug("[WS] SDK is shut down; not scheduling re-registration");const o=Rr();let n,s;if(o.served)if("socket_closed"===t){s=Cr;const e=o.reconnect.giveUpAfterAttempts;if(e>0&&s>=e)return void r.warn("[WS] Reconnect give-up threshold reached; not rescheduling",{attempt:s,giveUpAfter:e});n=((e,t,r=Math.random)=>{const o=Number.isFinite(t)&&t>0?t:0,n="fixed"===e.strategy?e.initialDelayMs:e.initialDelayMs*Math.pow(e.multiplier,o),s=Math.min(n,e.maxDelayMs),i=e.jitterMs>0?r()*e.jitterMs:0;return Math.round(s+i)})(o.reconnect,s),Cr+=1}else n=((e,t,r=Math.random)=>Math.round(1e3*e+(t>0?r()*t:0)))(o.reregister.onRefusalRetrySeconds,o.reconnect.jitterMs);else n=1e3*On();$e().report("ws.reconnect_scheduled",{code:t,durationMs:n,data:void 0!==s?{attempt:s}:void 0}),r.info("[WS] Scheduling re-registration",{reason:t,delayMs:n,attempt:s}),"refusal"!==t&&te("registering"),_t(()=>{Z()?.isActive()?r.info("[WS] Active WebSocket present; skipping re-registration"):(r.info("[WS] Re-registration timer fired; restarting lifecycle"),Fn(e,t))},n)},Fn=(e,t)=>{const r=k();r.info("[Lifecycle] Running",{reason:t}),Wn(e).catch(o=>{r.error("[Lifecycle] Attempt failed; will retry",{reason:t,error:m(o)}),Rn(new vn(Xn(o),`switch failed: ${m(o)}`,o)),Vn(e,"socket_closed")})};It=e=>{const t=ee()?.lifecycleOptions;t&&Fn(t,e)};const zn=(e,t)=>{const r=k();if(st())return void r.debug("[WS] SDK is shut down; ignoring re-register trigger");r.info("[WS] Running full re-register",{reason:t});const o=Z();J(void 0);try{o?.close(1e3,t)}catch{}Fn(e,t)},Wn=async e=>{const{config:t,appUserId:r,edgeOperatorKey:o,deviceId:n}=e;b(t.telemetry);const s=k();if(st())return void s.warn("[Init] SDK is shut down; refusing to start lifecycle");nt("starting"),(e=>{W.config=e})(t),on(t.inference),xt();const i={config:t,appUserId:r,edgeOperatorKey:o,deviceId:n};if((e=>{W.lifecycleOptions=e})(i),te("registering"),(e=>{if(!jn&&"undefined"!=typeof window&&"function"==typeof window.addEventListener){jn=!0;try{window.addEventListener("online",()=>{st()||Z()?.isActive()||!vt()||(k().info("[WS] Network is back; re-registering now"),xt(),Fn(e,"online"))})}catch{}}})(i),!o)throw new Error("Missing required header: x-edge-operator-key");const a=((e=Date.now())=>{const t=ut(),{crash:r,modelCrashes:o,blocklist:n}=gt(t,e),s={modelCrashes:o,blocklist:n,lastShutdown:t?.lastShutdown};if(t?.cooldownUntil&&t.cooldownUntil>e)return mt({...t,phase:void 0,modelId:void 0,modelVersion:void 0,...s}),{allowed:!1,cooldownRemainingMs:t.cooldownUntil-e,attempts:t.attempts,crash:r};if(!t||e-t.windowStart>6e4)return mt({attempts:1,windowStart:e,...s}),{allowed:!0,attempts:1,crash:r};const i=t.attempts+1;return i>=3?(mt({attempts:i,windowStart:t.windowStart,cooldownUntil:e+dt,...s}),{allowed:!1,cooldownRemainingMs:dt,attempts:i,crash:r}):(mt({attempts:i,windowStart:t.windowStart,...s}),{allowed:!0,attempts:i,crash:r})})();if(!a.allowed){Q("error"),nt("error"),s.warn("Init skipped: crash-loop guard active",{attempts:a.attempts,cooldownRemainingMs:a.cooldownRemainingMs}),$e().report("sdk.init_failed",{code:"crash_loop"}),Rn(new xn("stopped"));const e=Math.max(1e3,(a.cooldownRemainingMs??0)+1e3);return void _t(()=>Fn(i,"crash_loop_cooldown"),e)}const l=performance.now(),d=n?null:x(),c=!n&&!d,u=n??d??T();n&&(e=>{I(e)})(n),s.info("[Init] Starting lifecycle",{sdkVersion:t.sdkVersion,deviceId:u,isFreshDevice:c,providedDeviceId:Boolean(n),orchestrator:t.orchestrator?.baseUrl});const m=await(async(e,t,r)=>{const o=window.screen||{width:null,height:null},n=A(),s=B(),i=s?.first_name||s?.last_name?[s?.first_name,s?.last_name].filter(Boolean).join(" "):void 0;return{appUserId:s?.id?.toString()||t,appUsername:s?.username,appFirstName:s?.first_name,appLastName:s?.last_name,appFullName:i,sdkDeviceId:r??T(),platform:$(),deviceType:E(),userAgent:navigator.userAgent,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,appPlatform:n?.platform,appVersion:n?.version,appLanguage:s?.language_code,themeParams:n?.themeParams,cpuCores:navigator.hardwareConcurrency||1,memoryGb:S().deviceMemory,gpuRenderer:q(),webglFingerprint:q(),screen:{width:o?.width??null,height:o?.height??null,pixelRatio:window.devicePixelRatio??null},battery:await P(),connection:L(),pageUrl:window.location?.href,referrer:document.referrer,location:e.locationData?await C():void 0}})(t.telemetry,r,u);((e,t)=>{W.deviceId=e,W.deviceInfo=t})(u,m),(e=>{Se&&Se.matches(e.deviceId,e.enabled)||(Se?.flush(),Se?.dispose(),Se=new Te(e))})({enabled:t.telemetry.events,endpointUrl:`${t.orchestrator.baseUrl}${t.orchestrator.eventsPath}`,operatorKey:o,deviceId:u,sdkVersion:t.sdkVersion,platform:m.platform});const f=$e();f.report("sdk.init_started",{data:{sdkVersion:t.sdkVersion}}),Yn(a.crash),s.info("[Init] Device info collected",{platform:m.platform,deviceType:m.deviceType,gpuRenderer:m.gpuRenderer});const p=(e,t)=>{s.info(`[Flow] ${e}`,t??{})};(()=>{const e=Lo(Po);if(!e)return;const t=Lo(e);if(t){try{const e=JSON.parse(t);Bo(e)&&!No().some(t=>t.modelId===e.modelId)&&Oo(e,Date.now()-1)}catch{}Co(e)}Co(Po)})(),await ls(p);const g=c?[]:await Jn(p);c?p("Fresh device detected; skip cache checks"):p("Cache verified",{cachedModels:g.map(e=>e.modelId)}),H(g[0]?.modelId??null);const h=hn(),y=kn(t.sdkVersion),w={deviceId:u,sdkVersion:t.sdkVersion,cachedModels:g,device:m,...er(),...Ko(),...y.length>0?{unfitModels:y}:{},...h?{requestedModelId:h}:{}};let v,_=[];const M={},O={},V={};s.info("[Register] Sending register request",{deviceId:u,cachedModels:w.cachedModels.map(e=>e.modelId),unfitModels:y.map(e=>e.modelId),requestedModelId:h??void 0,sdkVersion:t.sdkVersion}),f.report("register.started");const z=performance.now();try{v=await(async(e,t,r)=>{const o=k(),n=e?.orchestrator;if(!n?.baseUrl||!n?.registerPath)throw new Error("Invalid SDK config: orchestrator.baseUrl and orchestrator.registerPath are required");const s=`${n.baseUrl}${n.registerPath}`,i={"Content-Type":"application/json"},a=r?.edgeOperatorKey?.trim();a&&(i["x-edge-operator-key"]=a);const l=await fetch(s,{method:"POST",headers:i,body:JSON.stringify(t)});o.info("Register request sent",{url:s,status:l.status,bodyBytes:JSON.stringify(t).length});const d=await R(l),c=U(d);if(!l.ok&&!c){const e="string"==typeof d?d:JSON.stringify(d??"");throw o.error("Register request failed",{status:l.status,message:e}),new N(l.status,e)}if(d&&"object"==typeof d&&!c){const e=d;return o.info("Register response parsed",{deviceId:e.deviceId,hasWsUrl:Boolean(e.wsUrl),models:e.slmConfig?.length??0,ttlSeconds:e.ttlSeconds,requestedModel:e.requestedModel?`${e.requestedModel.modelId}:${e.requestedModel.granted?"granted":e.requestedModel.reason??"refused"}`:void 0}),e}if(c){const e=d&&"object"==typeof d?d:{},r={deviceId:"string"==typeof e.deviceId&&e.deviceId?e.deviceId:t.deviceId,sessionKey:"string"==typeof e.sessionKey?e.sessionKey:"",wsUrl:"string"==typeof e.wsUrl?e.wsUrl:"",active:"boolean"==typeof e.active&&e.active,ttlSeconds:"number"==typeof e.ttlSeconds?e.ttlSeconds:0,refusalReason:c,requestedModel:j(e),configSettings:e.configSettings&&"object"==typeof e.configSettings?e.configSettings:void 0,slmConfig:void 0!==e.slmConfig?e.slmConfig:void 0!==e.modelInfo?[e.modelInfo]:void 0};return o.info("Register politely refused by server",{reason:c}),r}throw new N(l.status,"Register response body is not valid JSON")})(t,w,{edgeOperatorKey:o})}catch(e){if(e instanceof N&&(401===e.status||403===e.status))return p("Auth failure; no WS connection",{status:e.status}),f.report("register.failed",{code:"auth"}),f.report("sdk.init_failed",{code:"auth"}),ht(),Rn(new vn(`http_${e.status}`,"register refused the operator key",e)),void("retry_slow"===Rr().reregister.onAuthFailure?(s.warn("Register auth failed; policy says retry_slow"),Vn(i,"auth_failure")):(s.warn("Register auth failed, stopping lifecycle"),te("idle")));throw f.report("register.failed",{code:Xn(e),message:e.message}),f.report("sdk.init_failed",{code:Xn(e)}),ht(),e}const G=(e=>{if(!e||"object"!=typeof e)return null;for(const t of Object.values(e))if(t&&"object"==typeof t)return t;return null})(v.configSettings);var X;X=G,W.registrationSettings=X??null,(e=>{Ue=Oe(e?.guardrails??null)})(G);const Y=Nr(G?.connection,"register");Y.changed.length>0&&s.info("[Register] Connection policy applied",{source:Y.source,changed:Y.changed}),G&&s.info("[Register] Registration settings received",{keys:Object.keys(G)});const re=v.requestedModel;if(re&&!re.granted&&Nn(re.modelId,re.reason??v.refusalReason??"refused"),v.refusalReason)return f.report("register.rejected",{code:v.refusalReason}),s.warn("[Register] Registration refused by server",{reason:v.refusalReason}),Q("error"),nt("error"),te("declined",v.refusalReason),ht(),Rn(new xn("declined",v.refusalReason)),void Vn(i,"refusal");if(f.report("register.succeeded",{durationMs:Math.round(performance.now()-z)}),((e=Date.now())=>{Br=e})(),f.setSessionKey(v.sessionKey),s.info("Register response received",{deviceId:v.deviceId,wsUrl:v.wsUrl}),!v.wsUrl)return ht(),te("idle"),void Rn(new vn("no_session","register opened no session"));_=es(v.slmConfig);const oe=_[0];oe&&f.report("model.assigned",{modelId:oe.modelId,modelVersion:oe.modelVersion,bytes:oe.sizeBytes}),s.info("[Register] Models assigned",{count:_.length,models:_.map(e=>e.modelId),totalBytes:_.reduce((e,t)=>e+(t.sizeBytes??0),0)});for(const e of _)V[rs(e)]="idle",O[e.modelId]=e;if(!oe)return ht(),te("idle"),void Rn(new vn("no_model","the registry assigned no model"));var ne,se,ie,ae;ne=v.sessionKey,W.sessionKey=ne,se=O,W.modelInfosByModelId=se??{},ie=oe,W.modelInfo=ie,W.taskType=ie?.taskType,W.modelInfosByModelId||(W.modelInfosByModelId={}),ie?.modelId&&(W.modelInfosByModelId[ie.modelId]=ie),ae=oe.sample,W.sample=ae,s.info("Runtime globals updated from register response",{taskType:oe.taskType,hasSample:Boolean(oe.sample)}),te("preparing");const le=oe.modelVersion??"1",de=D(oe.modelId),ce=de&&de.config.modelVersion===le?de:void 0;for(const[e,t]of Object.entries(ee()?.adaptersByModelId??{}))if(e!==oe.modelId||!ce){try{await(t.dispose?.())}catch{}K(e,void 0)}let ue=ce;if(ce)p("Model still loaded; reusing it",{modelId:oe.modelId}),M[oe.modelId]=ce,Gn(oe);else{const e=g.some(e=>e.modelId===oe.modelId&&e.modelVersion===le);p(e?"Loading the assigned model from the cache":"Loading the assigned model",{modelId:oe.modelId,cached:e});const r=await Dn(oe);if("unfit"===r.kind)return Kn(i,oe,r.reason);if("transient"===r.kind){Q("error"),await ds({wsUrl:v.wsUrl,hello:{type:"hello",deviceId:v.deviceId,sessionKey:v.sessionKey,sdkVersion:t.sdkVersion,slmConfig:_.map(e=>({modelId:e.modelId,modelVersion:e.modelVersion??"1",status:e.modelId===oe.modelId?"error":V[rs(e)]||"idle"}))},ack:{type:"hello_ack",deviceId:v.deviceId,sdkVersion:t.sdkVersion,sessionKey:v.sessionKey,status:"error",timestamp:Date.now(),errorMessage:`primary_model_load_failed:${r.reason}`}}).catch(()=>{}),f.report("ws.init_failure_reported",{code:"primary_model_load_failed",message:r.reason}),f.report("sdk.init_failed",{code:"primary_model_load_failed",message:r.reason}),wt(),ht(),s.error("Primary model failed to load; retrying on the refusal cadence",{modelId:oe.modelId,modelVersion:oe.modelVersion,taskType:oe.taskType,reason:r.reason});const e=new Error(`primary_model_load_failed:${r.reason}`);return Rn(new vn(Xn(e),`switch failed: ${e.message}`,e)),void Vn(i,"refusal")}if(ue=r.adapter,M[oe.modelId]=ue,K(oe.modelId,ue),oe.sample?.text){s.info("[Sample] Running post-register sample inference",{taskType:oe.taskType}),yt("sampling",oe.modelId,oe.modelVersion);const e=await ue.runSample(oe.sample),t={taskType:oe.taskType,ok:e.ok,error:e.error,errorMessage:e.errorMessage,processingTimeMs:e.processingTimeMs},r=Fe().sampleLatencyBudgetMs;if(function(e,t=0){return!(!Boolean(e.error)&&e.ok)||t>0&&"number"==typeof e.processingTimeMs&&Number.isFinite(e.processingTimeMs)&&e.processingTimeMs>t}(e,r)){const o=!e.error&&e.ok&&r>0?`sample_too_slow:${e.processingTimeMs}ms>budget:${r}ms`:e.errorMessage??"sample_failed";f.report("model.sample_failed",{modelId:oe.modelId,durationMs:e.processingTimeMs,message:o,data:{phase:"post_register"}}),s.error("[Sample] Post-register sample failed",{...t,sampleLatencyBudgetMs:r});try{await(ue.dispose?.())}catch{}return K(oe.modelId,void 0),Kn(i,oe,`warmup_failed:${o}`)}f.report("model.sample_succeeded",{modelId:oe.modelId,durationMs:e.processingTimeMs,data:{phase:"post_register"}}),s.info("[Sample] Post-register sample ok",t)}Gn(oe),await Hn(oe.modelId)}for(const e of _){if(e.modelId===oe.modelId)continue;const t=os(e),r=he(t.inferenceFramework,t.taskType,t.inferenceKind);if(!r){V[rs(e)]="error",s.warn("No adapter factory for secondary model",{modelId:e.modelId,framework:t.inferenceFramework,taskType:t.taskType});continue}const o=await Qn(e);if(o){V[rs(e)]="error",f.report("guardrail.preflight_blocked",{code:o.code,modelId:e.modelId,modelVersion:e.modelVersion,message:o.message});continue}yt("loading",e.modelId,e.modelVersion);const n=await r.load(t);n.adapter?(M[e.modelId]=n.adapter,K(e.modelId,n.adapter)):(V[rs(e)]="error",s.warn("Failed to load secondary model",{modelId:e.modelId,taskType:e.taskType,error:n.error?.message}))}const me=v.deviceId,fe=_.map(e=>({modelId:e.modelId,modelVersion:e.modelVersion??"1",status:V[rs(e)]||"idle"})),pe={type:"hello",deviceId:me,sessionKey:v.sessionKey,sdkVersion:t.sdkVersion,slmConfig:fe};s.info("[WS] Connecting WebSocket",{wsUrl:v.wsUrl,models:fe.map(e=>`${e.modelId}:${e.status}`)}),f.report("ws.connect_started");const ge=Rr();let ye=null;const we=()=>{null!==ye&&(clearTimeout(ye),ye=null),(e=>{En=!1;const t=$n;if(!t)return;$n=null;const r=null!==e&&e===t.modelId;t.resolve({requestedModelId:t.modelId,activeModelId:e,granted:r,...r?{}:{reason:t.refusalReason??"not_assigned"}})})(oe.modelId)},be=new F({url:v.wsUrl,hello:pe,pingIntervalSeconds:ge.served?ge.keepAlive.pingIntervalSeconds:0,onPingTick:()=>{st()||Z()!==be||((e=Date.now())=>Lr.served&&null!==Br&&e-Br>1e3*Lr.reregister.maxStalenessSeconds)()&&(s.warn("[WS] Registration exceeded max_staleness; refreshing"),zn(i,"max_staleness"))},onOpen:()=>f.report("ws.connected"),onMessage:e=>{if("requests"in e&&Array.isArray(e.requests))dr(e);else if("type"in e&&"hello_ack"===e.type){const r=e;s.info("[WS] Received hello_ack",{status:r.status,deviceId:r.deviceId,errorMessage:r.errorMessage}),f.report("ws.hello_ack",{code:r.status,message:r.errorMessage}),Q("error"===r.status?"error":"idle"),Z()===be&&(t=!0,W.sessionAcked=t,we())}else if("type"in e&&"policy_update"===e.type){const t=e,r=Nr(t.connection,"ws");Z()===be&&be.setPingIntervalSeconds(r.policy.served?r.policy.keepAlive.pingIntervalSeconds:0),s.info("[WS] Connection policy updated",{source:r.source,v:t.v,changed:r.changed})}else if("type"in e&&"reregister"===e.type){const t=e;if(st()||Z()!==be)return;const r=((e,t=Math.random)=>{const r=Ar(e),o=void 0!==r&&r>=0?Math.min(r,36e5):6e4;return Math.round(t()*o)})(t.delay_jitter_ms),o="string"==typeof t.reason&&t.reason.length>0?`reregister:${t.reason}`:"reregister";s.info("[WS] Server requested re-register",{reason:o,delayMs:r}),_t(()=>{zn(i,o)},r)}else s.debug("[WS] Unhandled message",{type:"type"in e&&"string"==typeof e.type?e.type:"unknown"});var t},onClose:e=>{const t=Z()===be;s.warn("[WS] Connection closed",{code:e.code,reason:e.reason,current:t}),t&&(f.report("ws.closed",{code:`close_${e.code}`,data:{wasClean:e.wasClean}}),Q("error"),Vn(i,"socket_closed"))},onError:()=>{s.error("[WS] Connection error"),f.report("ws.error"),Z()===be&&Q("error")}});var ke;J(be),Q("idle"),yt("running",oe.modelId,oe.modelVersion),nt("running"),te("running"),Ct(),f.report("sdk.init_succeeded",{durationMs:Math.round(performance.now()-l)}),s.info("[Init] SDK ready",{deviceId:u,primaryModelId:oe.modelId,taskType:oe.taskType}),Cr=0,ht(),Un=0,ke=oe.modelId,Pn!==ke&&(Pn=ke,it("activeModelChanged",{modelId:ke})),null!==$n&&(ye=setTimeout(we,15e3))},Kn=async(e,t,r)=>{const o=k(),n=$e(),s=t.modelVersion??"1";if(o.warn("[Model] Model unfit on this device; dropping it and registering again",{modelId:t.modelId,modelVersion:s,reason:r}),await Hr(t.modelId,s).catch(()=>{}),Vo(t.modelId),await is(t.modelUrl).catch(()=>{}),((e,t,r,o,n=Date.now())=>{const s=wn().filter(t=>t.modelId!==e);bn([...s,{modelId:e,modelVersion:t||"1",reason:r.slice(0,64),sdkVersion:o,at:n}])})(t.modelId,s,r,e.config.sdkVersion),n.report("model.evicted",{code:"unfit",modelId:t.modelId,modelVersion:s,message:r}),hn()===t.modelId&&Nn(t.modelId,r),wt(),ht(),K(t.modelId,void 0),H(jo()[0]?.modelId??null),Un<4)return Un+=1,te("registering"),Wn(e);o.warn("[Model] Too many unfit models in a row; retrying on the slow cadence",{attempts:Un}),Q("error"),nt("error"),Rn(new vn("unfit_models_exhausted","every assigned model failed on this device")),Vn(e,"refusal")},Dn=async e=>{const t=k(),r=$e(),o=os(e),n=he(o.inferenceFramework,o.taskType,o.inferenceKind),s=await Qn(e);if(s)return r.report("guardrail.preflight_blocked",{code:s.code,modelId:e.modelId,modelVersion:e.modelVersion,message:s.message}),t.warn("[Guard] Primary model blocked by preflight",{modelId:e.modelId,code:s.code,message:s.message}),{kind:"transient",reason:`preflight_blocked:${s.code}`};if(!n)return r.report("model.load_failed",{code:"no_adapter_factory",modelId:e.modelId,modelVersion:e.modelVersion}),t.error("[Model] No adapter factory for primary model",{modelId:e.modelId,framework:o.inferenceFramework,taskType:o.taskType}),{kind:"unfit",reason:`no_adapter_factory:${o.inferenceFramework??"unknown"}:${o.taskType}`};t.info("[Model] Loading primary model",{modelId:e.modelId,framework:o.inferenceFramework,taskType:o.taskType,quantized:o.quantized,sizeBytes:e.sizeBytes,modelRepoId:e.modelRepoId}),r.report("model.load_started",{modelId:e.modelId,modelVersion:e.modelVersion}),yt("loading",e.modelId,e.modelVersion);const i=performance.now(),a=await n.load(o),l=Math.round(performance.now()-i);if(a.adapter)return r.report("model.load_succeeded",{modelId:e.modelId,modelVersion:e.modelVersion,durationMs:l,bytes:a.metrics?.sizeBytes}),t.info("[Model] Primary model loaded",{modelId:e.modelId,ms:l,sizeBytes:a.metrics?.sizeBytes}),{kind:"adapter",adapter:a.adapter};const d=a.error?.message??"init_error";return r.report("model.load_failed",{code:Zn(d),modelId:e.modelId,modelVersion:e.modelVersion,durationMs:l,message:d}),t.error("[Model] Primary model load failed",{modelId:e.modelId,framework:o.inferenceFramework,taskType:o.taskType,ms:l,error:d}),(e=>/network|fetch|timeout|timed out|econn|http 5\d\d|\b(429|502|503|504)\b|model_not_cached|runtime_load_failed|worker_/i.test(e)&&!/\b(403|404)\b/.test(e))(d)?{kind:"transient",reason:d}:{kind:"unfit",reason:`load_failed:${Zn(d)}:${d.slice(0,48)}`}},Gn=e=>{const t=e.modelVersion??"1",r=(e=>{const t=No().find(t=>t.modelId===e);if(t)return t;const r=Lo(e);if(!r)return null;try{const e=JSON.parse(r);return Bo(e)?e:null}catch{return null}})(e.modelId);r&&(r.modelVersion||"1")!==t&&(Hr(e.modelId,r.modelVersion||"1").catch(()=>{}),$e().report("model.evicted",{code:"version_changed",modelId:e.modelId,modelVersion:r.modelVersion})),Oo({modelId:e.modelId,modelVersion:t,modelUrl:e.modelUrl,modelRepoId:e.modelRepoId,inferenceFramework:e.inferenceFramework,inferenceKind:e.inferenceKind,modelType:e.modelType,maxInputTokens:e.maxTokens,quantized:e.quantized,quantization:e.quantization,taskType:e.taskType,sizeBytes:e.sizeBytes,sample:e.sample,requiredFiles:e.requiredFiles}),H(e.modelId)},Hn=async e=>{const t=Fe().maxCachedModels,r=((e,t)=>{if(!Number.isFinite(e)||e<=0)return[];const r=jo(),o=[];for(;r.length>e;){let e=-1;for(let o=r.length-1;o>=0;o-=1)if(r[o].modelId!==t){e=o;break}if(e<0)break;o.push(...r.splice(e,1))}if(o.length>0){Ro(r);for(const e of o)Co(e.modelId)}return o})(t,e);for(const e of r){await Hr(e.modelId,e.modelVersion||"1").catch(()=>{}),await is(e.modelUrl).catch(()=>{});const r=D(e.modelId);if(r){try{await(r.dispose?.())}catch{}K(e.modelId,void 0)}$e().report("model.evicted",{code:"cache_cap",modelId:e.modelId,modelVersion:e.modelVersion,bytes:e.sizeBytes}),k().info("[Cache] Evicted the least recently used model from the cache",{modelId:e.modelId,cap:t})}},Jn=async e=>{const t=$e(),r=[];for(const o of jo()){const n=o.modelVersion||"1";if(bt(o.modelId,n)){t.report("guardrail.preflight_blocked",{code:"model_blocklisted",modelId:o.modelId,modelVersion:n}),e("Cached model is blocklisted; not claimed",{modelId:o.modelId});continue}if(To(o.modelId,n)){e("Cached model was never persisted (browser storage refused); not claimed",{modelId:o.modelId,failures:Mo(o.modelId,n)});continue}const s=Boolean(o.modelUrl&&o.taskType&&Array.isArray(o.requiredFiles)&&o.sample?.text),i=s?await ns(o):{ok:!1,missing:[],stored:0};i.ok?r.push({modelId:o.modelId,modelVersion:n}):(t.report("model.cache_invalid",{code:s?"files_missing":"metadata_missing",modelId:o.modelId,modelVersion:n,data:{missing:i.missing.slice(0,8),stored:i.stored}}),e("Cached model invalid; dropping it",{modelId:o.modelId,complete:s,stored:i.stored,missing:i.missing.slice(0,8)}),await Hr(o.modelId,n).catch(()=>{}),Vo(o.modelId),t.report("model.cache_purged",{modelId:o.modelId,modelVersion:n}))}return r},Xn=e=>{if(e instanceof N)return`http_${e.status}`;return/timeout/i.test(e?.message??"")?"timeout":"network"},Zn=e=>e?/preflight_blocked/.test(e)?"guardrail_blocked":/no_adapter_factory/.test(e)?"no_adapter_factory":/oom|out of memory|RangeError/i.test(e)?"oom":/wasm|abort/i.test(e)?"wasm_abort":"init_error":"init_error",Qn=async e=>{if(bt(e.modelId,e.modelVersion))return{code:"model_blocklisted",message:"blocklisted after repeated crashes during load"};let t;try{t=Y().deviceInfo}catch{t=void 0}return Fo({modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:e.sizeBytes,inferenceFramework:e.inferenceFramework},"download",t)},Yn=e=>{if(!e)return;const t=$e();t.report("sdk.crash_detected",{code:e.code,modelId:e.modelId,modelVersion:e.modelVersion,data:{phase:e.phase}}),e.blocklistedModel&&t.report("guardrail.model_blocklisted",{modelId:e.modelId,modelVersion:e.modelVersion,message:e.blocklistedModel})},es=e=>{if(!Array.isArray(e))return[];const t=[];for(const r of e){if(!r?.modelId||!r?.modelVersion||!r?.modelUrl)continue;const e=ts(r);e&&t.push({modelId:r.modelId,modelType:r.modelType,modelVersion:r.modelVersion,modelUrl:r.modelUrl,modelRepoId:r.modelRepoId,maxTokens:r.maxTokens,requiredFiles:r.requiredFiles,inferenceFramework:r.inferenceFramework,inferenceKind:r.inferenceKind,quantized:Boolean(r.quantized),quantization:r.quantization,taskType:e,sizeBytes:r.sizeBytes,sample:r.sample})}return t},ts=e=>{const t=e.taskType;if("string"==typeof t&&t.length>0)return t;const r=e.inferenceKind;return"string"==typeof r&&r.trim().length>0?r.trim():null},rs=e=>`${e.modelId}@${e.modelVersion??"1"}`,os=e=>({modelId:e.modelId,modelVersion:e.modelVersion??"1",modelUrl:e.modelUrl,modelRepoId:e.modelRepoId,modelType:e.modelType,inferenceFramework:e.inferenceFramework,inferenceKind:e.inferenceKind,requiredFiles:e.requiredFiles,quantized:e.quantized??!1,quantization:e.quantization,taskType:e.taskType,maxInputTokens:e.maxTokens}),ns=async e=>{if(!Array.isArray(e.requiredFiles))return{ok:!1,missing:["<no required files>"],stored:0};if(0===e.requiredFiles.length)return{ok:!0,missing:[],stored:0};const t=ss(e.requiredFiles);if(!t.length)return{ok:!1,missing:["<no required files>"],stored:0};try{const r=await Gr(e.modelId,e.modelVersion||"1");if(!r?.files)return{ok:!1,missing:["<no record>"],stored:0};const o=new Set;for(const t of Object.keys(r.files)){const r=t.replace(/^\/+/,"").replace(/^resolve\/main\//,"");o.add(r);const n=`${e.modelId}/`;r.startsWith(n)&&o.add(r.slice(n.length))}const n=t.filter(e=>!o.has(e)&&(!o.has(`onnx/${e}`)&&(!e.startsWith("onnx/")||!o.has(e.slice(5)))));return{ok:0===n.length,missing:n,stored:Object.keys(r.files).length}}catch(e){return{ok:!1,missing:[`<read failed: ${m(e)}>`],stored:0}}},ss=e=>e.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.name).map(e=>e.name.trim().replace(/^\/+/,"")).filter(e=>"string"==typeof e&&e.length>0),is=async e=>{if("undefined"==typeof caches||!e)return;const t=e.trim().replace(/\/$/,"");if(!t)return;const r=(await caches.keys()).filter(e=>e.includes(eo));for(const e of r){const r=await caches.open(e);for(const e of await r.keys())e.url.includes(t)&&await r.delete(e)}},as=()=>v("transformers_cache_purged"),ls=async e=>{if("undefined"!=typeof caches){try{if(window.localStorage.getItem(as()))return}catch{}try{const t=(await caches.keys()).filter(e=>e.includes(eo));for(const e of t)await caches.delete(e);t.length>0&&e("Legacy transformers.js cache purged",{caches:t.length});try{window.localStorage.setItem(as(),(new Date).toISOString())}catch{}}catch{}}},ds=async e=>{await new Promise(t=>{let r=!1;const o=()=>{r||(r=!0,t())},n=window.setTimeout(o,1500);try{new F({url:e.wsUrl,hello:e.hello,ack:e.ack,closeAfterAck:!0,closeCode:4001,closeReason:"primary_model_load_failed",onMessage:()=>{},onClose:()=>{window.clearTimeout(n),o()},onError:()=>{window.clearTimeout(n),o()}})}catch{window.clearTimeout(n),o()}})};class cs{constructor(e,t,r,o){this.config=e,this.capability=t,this.executor=r,this.metrics=o}runInference(e){return this.executor.runInference(e)}runSample(e){return this.executor.runSample(e)}async dispose(){await(this.executor.dispose?.())}}const us=async(e,t,r)=>{const o=k(),n=performance.now(),s={};try{const o=await $o(e.modelId,e.modelVersion),i=o?.files||{};if(!o&&!1===t?.allowDownload)return{error:new Error("model_not_cached"),metrics:{}};const a=(e,t)=>{s[e]=t},l=o?{downloadMs:o.metadata.downloadMs,loadModelMs:o.metadata.loadModelMs,sizeBytes:o.metadata.sizeBytes}:{},d=await r.loadExecutor(e,i,a),c={...l,loadModelMs:d.loadModelMs};if(Object.keys(s).length>0){const t={...i,...s},r=Object.values(t).reduce((e,t)=>e+t.size,0),a=Math.round(performance.now()-n);await Eo(e.modelId,e.modelVersion,{modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:r,downloadMs:o?0:a,loadModelMs:d.loadModelMs},t),c.sizeBytes=r,o||(c.downloadMs=a)}return{adapter:new cs(e,r.capability(e),d,c),metrics:c}}catch(t){return r.onLoadError?.(t,e),o.error(`${r.logLabel} failed`,{modelId:e.modelId,modelVersion:e.modelVersion,modelRepoId:e.modelRepoId,modelUrl:e.modelUrl,requiredFiles:(e.requiredFiles??[]).map(e=>e.name),error:m(t)}),await Hr(e.modelId,e.modelVersion).catch(()=>{}),{error:t,metrics:{}}}},ms=async e=>{const t=performance.now();return{result:await e(),ms:Math.round(performance.now()-t)}},fs={},ps=(e,t,r,o,n,s)=>{const i=n.map(e=>ao(e.trim())).filter(e=>e.length>0),a=new Set(i),l=k(),d=(()=>{try{return new URL(t)}catch{return null}})();return async(n,i)=>{const c="string"==typeof n?n:n instanceof URL?n.toString():n.url,u=(e=>{const t=(()=>{try{return new URL(e).pathname}catch{return e.split("?")[0]||""}})(),r="/resolve/main/",o=t.indexOf(r);if(o>=0){const e=t.slice(o+14);return ao(e)}if(!d)return null;const n=d.pathname.replace(/\/$/,"");if(!t.startsWith(`${n}/`))return null;const s=t.slice(n.length+1);return ao(s)})(c);if(!u){if(!(/\.wasm(?:\?|$)/i.test(c)||/onnxruntime|ort-wasm/i.test(c)))return s(n,i);try{return await s(n,i)}catch(t){throw l.error("[SLM][fetch] non-model wasm/ort request failed",{modelId:e,requestUrl:c,error:m(t)}),t}}const f=(e=>{const t=ao(e);if(!t)return null;if(0===a.size||a.has(t))return t;if(t.startsWith("onnx/")&&t.endsWith(".onnx")&&!t.endsWith("_quantized.onnx")){const e=t.replace(/\.onnx$/,"_quantized.onnx");if(a.has(e))return e}return null})(u);if(!f)return l.warn("[SLM] Unexpected model file request; falling back to original fetch",{file:u,modelId:e}),s(n,i);const p=(e=>{const r=ao(e),o=[],n=e=>{o.includes(e)||o.push(e)};try{const e=new URL(t),o=e.toString().endsWith("/")?e.toString():`${e.toString()}/`;t.endsWith("/resolve/main")?n(new URL(r,o).toString()):(n(new URL(r,o).toString()),n(new URL(`resolve/main/${r}`,o).toString()))}catch{t.endsWith("/resolve/main")?n(`${t}/${r}`):(n(`${t}/${r}`),n(`${t}/resolve/main/${r}`))}return o})(f),g=ao(f),h=lo(e,g);let y=fs[h]||r[h]||fs[g]||r[g]||r[`onnx/${g}`]||fs[`onnx/${g}`];if(!y&&g.startsWith("onnx/")){const t=g.replace("onnx/","");y=r[t]||fs[t]||r[lo(e,t)]||fs[lo(e,t)]}if(y)return new Response(y);try{for(const e of p){const t=await s(e,i);if(t.ok){const e=await t.blob();return fs[h]=e,o&&o(h,e),new Response(e)}}return new Response("required_file_not_found",{status:404,statusText:"Not Found"})}catch(t){return l.warn("[SLM] Model file fetch failed",{modelId:e,file:f,candidateCount:p.length,error:m(t)}),new Response("model_file_fetch_failed",{status:502,statusText:"Bad Gateway"})}}},gs="zgScoreRecorder",hs=e=>({[gs]:e}),ys=(e,t,r)=>{let o=-1/0;for(let n=0;n<r;n+=1)o=Math.max(o,e[t+n]);let n=0;for(let s=0;s<r;s+=1)n+=Math.exp(e[t+s]-o);return o+Math.log(n)},ws=e=>{const t=e;if(!t||t.__zgScoreHooks)return Boolean(t?.__zgScoreHooks);const{getStartBeams:r,runBeam:o,updateBeam:n}=t;return"function"==typeof r&&"function"==typeof o&&"function"==typeof n&&(t.getStartBeams=(...e)=>{const o=r.apply(t,e),n=e[1],s=n?.[gs];if(s)for(const e of o)e[gs]=s;return o},t.runBeam=async e=>{const r=await o.call(t,e),n=e[gs];return n&&r?.logits&&((e,t)=>{const{offset:r,size:o}=(e=>{const t=e.dims,r=t[t.length-1];return{offset:((t.length>=2?t[t.length-2]:1)-1)*r,size:r}})(t);e.pending={row:t.data,offset:r,size:o,logSumExp:ys(t.data,r,o)}})(n,r.logits),r},t.updateBeam=(e,r)=>{const o=n.call(t,e,r),s=e[gs];return s&&((e,t)=>{const r=e.pending;if(e.pending=void 0,!r||e.sawEos)return;if(e.eosTokenIds.includes(t))return void(e.sawEos=!0);const o=Math.exp(r.row[r.offset+t]-r.logSumExp);e.logProbs.push(Math.log(Math.max(o,1e-9)))})(s,r),o},t.__zgScoreHooks=!0,!0)},bs=e=>{const t=e,r=t?.generation_config?.eos_token_id??t?.config?.eos_token_id;return(Array.isArray(r)?r:[r]).filter(e=>"number"==typeof e)},ks=(e,t)=>"sigmoid"===e?(e=>Array.from(e,e=>1/(1+Math.exp(-e))))(t):(e=>{const t=Array.from(e);if(0===t.length)return[];const r=Math.max(...t),o=t.map(e=>Math.exp(e-r)),n=o.reduce((e,t)=>e+t,0);return o.map(e=>e/n)})(t),vs=e=>"number"==typeof e&&Number.isFinite(e)&&e>0&&e<1e6?Math.floor(e):void 0,_s=e=>{const t=new BigInt64Array(e.length);return e.forEach((e,r)=>{t[r]=BigInt(e)}),t},xs=(e,t,r)=>{const o=r.config??{},n=r.session,s="multi_label_classification"===o.problem_type?"sigmoid":"softmax";const i=((e,t)=>{const r=[vs(e.max_position_embeddings),vs(e.n_positions),vs(t.model_max_length)].filter(e=>void 0!==e);return r.length>0?Math.min(...r):512})(o,t),a=t.encode(""),l=a.length>0?a[a.length-1]:void 0,d=n.outputNames.includes("logits")?"logits":n.outputNames[0],c=o.id2label&&"object"==typeof o.id2label?Object.keys(o.id2label).length:0;return{labelCount:c,maxLength:i,activation:s,async classify(r,a){const c=r.slice(0,16*i),u=((e,t,r)=>{if(e.length<=t)return e;const o=e[e.length-1];return void 0!==r&&o===r&&t>=2?[...e.slice(0,t-1),o]:e.slice(0,t)})(t.encode(c),i,l),m=await n.run((t=>{const r=[1,t.length],o={};for(const s of n.inputNames)if("input_ids"===s)o[s]=new e.Tensor("int64",_s(t),r);else if("attention_mask"===s)o[s]=new e.Tensor("int64",_s(t.map(()=>1)),r);else{if("token_type_ids"!==s)throw new Error(`sequence_classification_unsupported_input:${s}`);o[s]=new e.Tensor("int64",_s(t.map(()=>0)),r)}return o})(u)),f=m[d];if(!f||!f.data||0===f.data.length)throw new Error("sequence_classification_empty_logits");const p=ks(s,f.data),g=((e,t)=>{const r=e.id2label,o=r&&"object"==typeof r?r:{};return Array.from({length:t},(e,t)=>{const r=o[String(t)];return"string"==typeof r&&r.length>0?r:`LABEL_${t}`})})(o,p.length);return((e,t,r)=>{const o=Math.max(1,Math.min(Math.floor(r),e.length)),n=e.map((e,t)=>({score:e,index:t})).sort((e,t)=>t.score-e.score).slice(0,o),s={};for(const{score:e,index:r}of n)s[t[r]??`LABEL_${r}`]=e;return s})(p,g,"number"==typeof(h=a)&&Number.isFinite(h)&&h>=1?Math.floor(h):50);var h}}},Is={summary:"summarization",iab_classify:"text-classification",classification:"zero-shot-classification",text_generation:"text2text-generation"},Ms=new Set([ne,se,ie,le,de,ce,ue]),Ts={[se]:"text2text-generation",[ie]:"zero-shot-classification",[le]:"token-classification",[de]:"question-answering",[ce]:"feature-extraction",[ue]:"fill-mask"},Ss=e=>{const t=me(e.inferenceKind);return t&&Ms.has(t)?t:"task"},As=8192,$s=/\[MASK\]|<mask>/g,Es=e=>"number"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,qs=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("input_text_required");return e},Ps=e=>{if("string"==typeof e)return e;if(Array.isArray(e)&&e.length){const t=e[0];if(t&&"string"==typeof t.summary_text)return t.summary_text;if(t&&"string"==typeof t.generated_text)return t.generated_text;if(t&&"string"==typeof t.label)return t.label;try{return JSON.stringify(t)}catch{return String(t??"")}}if(e&&"object"==typeof e){const t=e;if("string"==typeof t.summary_text)return t.summary_text;if("string"==typeof t.generated_text)return t.generated_text;if("string"==typeof t.label)return t.label;try{return JSON.stringify(t)}catch{return String(t)}}return""},Ls=e=>{if(Array.isArray(e)){const t=e.filter(e=>"string"==typeof e);return t.length>0?t:void 0}if("string"==typeof e&&e.length>0)return[e]},Cs=(e,t)=>{const r=(e??"").trim();return r?r.slice(0,1024):t},Bs=e=>{const t=/^([BI])-(.+)$/.exec(e);return t?{prefix:t[1],label:t[2]}:{prefix:null,label:e}},Ns=(e,t)=>{const r=Array.isArray(t)?t:[],o=[],n=[];let s=null,i=-2;const a=()=>{if(!s)return;const t=s.pieces.join(" "),r=n[n.length-1],{start:o,end:i}=((e,t,r)=>{const o=e.indexOf(t,r);if(o>=0)return{start:o,end:o+t.length};const n=t.split(/\s+/).filter(Boolean).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s*");if(!n)return{start:-1,end:-1};const s=new RegExp(n).exec(e.slice(r));return s?{start:r+s.index,end:r+s.index+s[0].length}:{start:-1,end:-1}})(e,t,r&&r.end>=0?r.end:0),a=s.scores.reduce((e,t)=>e+t,0)/Math.max(1,s.scores.length);n.push({label:s.label,text:t,start:o,end:i,score:Number(a.toFixed(6))}),s=null};for(const e of r){const t="string"==typeof e?.entity?e.entity:"O",r="string"==typeof e?.word?e.word:"",n="number"==typeof e?.score?e.score:0,l="number"==typeof e?.index?e.index:i+1,d=r.startsWith("##")&&l===i+1,c=d?r.slice(2):r;if(i=l,o.push({token:r,label:t,score:Number(n.toFixed(6))}),d&&s){s.pieces[s.pieces.length-1]+=c,s.scores.push(n);continue}const{prefix:u,label:m}=Bs(t);"O"!==t&&c?s&&"B"!==u&&s.label===m?(s.pieces.push(c),s.scores.push(n)):(a(),s={label:m,pieces:[c],scores:[n]}):a()}return a(),{entities:n,tokens:o}},Rs=e=>{if(Array.isArray(e)){return e.flat(1/0).filter(e=>"number"==typeof e)}const t=e?.data;return t&&"number"==typeof t.length?Array.from(t):[]},Us=async(e,t,r)=>{const{pipeline:o,pipelineTask:n}=e,{result:s,ms:i}=await ms(async()=>{if("zero-shot-classification"===n){if(!r?.categories||0===r.categories.length)throw new Error("classification_categories_required");return o(t,r.categories)}return"summarization"===n?o(t,{max_new_tokens:r?.maxNewTokens??64,min_length:1,do_sample:!1}):"text2text-generation"===n?o(t,{max_new_tokens:r?.maxNewTokens??128,do_sample:!1}):o(t)});return{raw:s,ms:i}},js=async(e,t,r)=>{try{return await Us(e,t,r)}catch(o){if(!(e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("invalid array length"))(o)||t.length<=256)throw o;const n=t.slice(0,256);return await Us(e,n,r)}};class Os{constructor(e,t){this.config=e,this.state=t,this.loadModelMs=t.loadModelMs}async runInference(e){const t=Ss(this.config);if(t===ne)return this.runSequenceClassification(e);if(t===se)return this.runSeq2Seq(e);if(t===ie)return this.runZeroShot(e,!0);if(t===le)return this.runTokenClassification(e);if(t===de)return this.runQuestionAnswering(e);if(t===ce)return this.runTextEmbedding(e);if(t===ue)return this.runFillMask(e);const r=this.config.taskType,o=Cs(e.text,"summarize this text");if("classification"===r)return this.runZeroShot(e);if("iab_classify"===r){const{raw:e,ms:t}=await js(this.state,o);return{output:e,inferenceMs:t}}if("summary"===r){const{raw:t,ms:r}=await js(this.state,o,{maxNewTokens:e.maxNewTokens});return{output:{text:Ps(t)},inferenceMs:r}}if("text_generation"===r){const{raw:t,ms:r}=await js(this.state,o,{maxNewTokens:e.maxNewTokens});return{output:{text:Ps(t)},inferenceMs:r}}const{raw:n,ms:s}=await js(this.state,o);return{output:n,inferenceMs:s}}async runZeroShot(e,t=!1){const r=t?qs(e.text).slice(0,As):Cs(e.text,"summarize this text"),o=Ls(e.categories)??Ls(e.category),{raw:n,ms:s}=await js(this.state,r,{categories:o});if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return Array.isArray(t.labels)&&Array.isArray(t.scores)})(n)){return{output:(e=>{const t=e.labels,r=e.scores;if(!Array.isArray(t)||!Array.isArray(r))return null;const o=t.flatMap((e,t)=>{const o=r[t];return"string"==typeof e&&"number"==typeof o?[[e,o]]:[]});return o.length>0?Object.fromEntries(o):null})(n)??n,inferenceMs:s}}return{output:n,inferenceMs:s}}async runSequenceClassification(e){const t=this.state.classifier;if(!t)throw new Error("sequence_classifier_not_loaded");const r=qs(e.text),o=e.topK??e.top_k,{result:n,ms:s}=await ms(()=>t.classify(r,"number"==typeof o?o:void 0));return{output:n,inferenceMs:s}}async runSeq2Seq(e){const t=qs(e.text).slice(0,8192),r=Es(e.maxNewTokens)??this.state.defaultMaxNewTokens??48,{pipeline:o,scoring:n}=this.state,s=n?{eosTokenIds:n.eosTokenIds,logProbs:[],sawEos:!1}:void 0;const{result:i,ms:a}=await ms(()=>o(t,{max_new_tokens:r,do_sample:!1,num_beams:1,...s?hs(s):{}})),l=Ps(i).trim(),d=s?(e=>{const t=e.logProbs.length;return 0===t?.5:Math.exp(e.logProbs.reduce((e,t)=>e+t,0)/t)})(s):.5;return{output:{text:l,score:d},inferenceMs:a}}async runTokenClassification(e){const t=qs(e.text).slice(0,As),{result:r,ms:o}=await ms(()=>this.state.pipeline(t,{ignore_labels:[]}));return{output:Ns(t,r),inferenceMs:o}}async runQuestionAnswering(e){const t="string"==typeof e.question?e.question.trim():"";if(!t)throw new Error("input_question_required");const r=("string"==typeof e.context&&e.context.trim().length>0?e.context:qs(e.text)).slice(0,As),o=this.state.pipeline,{result:n,ms:s}=await ms(()=>o(t,r,{topk:1})),i=Array.isArray(n)?n[0]:n,a="string"==typeof i?.answer?i.answer.trim():"",l="number"==typeof i?.score?i.score:0,d=a?r.indexOf(a):-1;return{output:{answer:a,score:l,start:d,end:d>=0?d+a.length:-1},inferenceMs:s}}async runTextEmbedding(e){const t=qs(e.text).slice(0,As),{result:r,ms:o}=await ms(()=>this.state.pipeline(t,{pooling:"mean",normalize:!0}));return{output:{embedding:Rs(r)},inferenceMs:o}}async runFillMask(e){const t=this.state.pipeline.tokenizer?.mask_token,r=((e,t)=>!t||e.includes(t)?e:e.replace($s,t))(qs(e.text).slice(0,As),"string"==typeof t?t:void 0),o=(e=>Es(e.topK)??Es(e.top_k))(e)??5,{result:n,ms:s}=await ms(()=>this.state.pipeline(r,{topk:o})),i=Array.isArray(n)?n:[],a=i.map(e=>({token:"string"==typeof e?.token_str?e.token_str.trim():"",tokenId:"number"==typeof e?.token?e.token:-1,score:"number"==typeof e?.score?e.score:0})),l=i[0];return{output:{predictions:a,text:"string"==typeof l?.sequence?l.sequence:r},inferenceMs:s}}async runSample(e){const t=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:"response from processing sample"};try{const o=await this.runInference({...e,text:e.text}),n=Math.round(performance.now()-t);return null!=(r=o.output)&&("string"==typeof r?r.trim().length>0:Array.isArray(r)?r.length>0:"object"!=typeof r||Object.keys(r).length>0)?{ok:!0,processingTimeMs:n,error:!1}:{ok:!1,processingTimeMs:n,error:!0,errorMessage:"response from processing sample"}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}var r}}const Vs=async(e,t,r,o)=>{const n=Ss(e),s=k();try{await ro()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const i=oo(io(e.modelUrl,e.modelRepoId)),a=(e=>{const t=Ss(e);return Ts[t]??Is[e.taskType]??e.taskType})(e),l=no(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!l)throw new Error("[SLM] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const d=await bo(async()=>{const d=Qr(),c=d.TransformersEnv||{};c.allowRemoteModels=!0,c.allowLocalModels=!0,Yr(c),c.backends||(c.backends={}),c.backends.onnx||(c.backends.onnx={}),c.backends.onnx.wasm||(c.backends.onnx.wasm={});const u=s.isEnabled()?"error":"fatal";c?.backends?.onnx?.env&&(c.backends.onnx.env.logLevel=u);const m=Ke(void 0,o?.wasm);c.backends.onnx.wasm.proxy=m.proxy,c.backends.onnx.wasm.numThreads=Zr().forceSingleThread?1:m.numThreads;const f=globalThis.fetch.bind(globalThis),p=await yo(f);if(p)c.backends.onnx.wasm.wasmPaths=p;else try{delete c.backends.onnx.wasm.wasmPaths}catch{c.backends.onnx.wasm.wasmPaths=void 0}"logLevel"in c&&(c.logLevel=u);const g=globalThis.ort;g?.env&&(g.env.logLevel=u),c.fetch=ps(e.modelId,i,t,r,(e.requiredFiles??[]).map(e=>e.name),f),d.TransformersEnv=c,globalThis.fetch=c.fetch;const h={device:"wasm",quantized:e.quantized,progress_callback:()=>{}},y=()=>ms(async()=>{if(n===ne){const e=(()=>{const e=Qr().TransformersLib;if(!e)throw new Error("transformers_lib_unavailable");return e})(),[t,r]=await Promise.all([e.AutoTokenizer.from_pretrained(l,h),e.PreTrainedModel.from_pretrained(l,h)]);return{classifier:xs(e,t,r)}}const e=d.TransformersPipeline;if(!e)throw new Error("transformers_pipeline_unavailable");return{pipeline:await e(a,l,h)}});try{return await y()}catch(e){const t=c?.backends?.onnx?.wasm,r=Boolean(t&&"wasmPaths"in t&&t.wasmPaths);let o=e;if(t){const e=t.simd,r=t.numThreads,n=t.proxy;t.simd=!1,t.numThreads=1,t.proxy=!1;try{return await y()}catch(s){o=s,t.simd=e,t.numThreads=r,t.proxy=n}}if(!r||!t){const e=o instanceof Error?o.message:String(o);throw new Error(`pipeline_load_failed:${e}`)}const n=t.wasmPaths;try{delete t.wasmPaths}catch{t.wasmPaths=void 0}try{return await y()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`pipeline_load_failed:${t}`)}finally{t.wasmPaths=n}}finally{globalThis.fetch=f}}),{result:c,ms:u}=d;if(c.classifier){return{pipeline:()=>Promise.reject(new Error("pipeline_not_loaded")),pipelineTask:n,loadModelMs:u,classifier:c.classifier}}const m=c.pipeline,f={pipeline:m,pipelineTask:a,loadModelMs:u};if(n===se){const t=m.model;f.defaultMaxNewTokens=Es(t?.generation_config?.max_new_tokens)??48,ws(t)?f.scoring={eosTokenIds:bs(t)}:k().warn("[SLM] seq2seq score hooks unavailable; score defaults to 0.5",{modelId:e.modelId})}return f},Fs=async(e,t,r,o)=>{const n=await Vs(e,t,r,o);return new Os(e,n)},zs={capabilities:[{inferenceFramework:"ONNX",inferenceKind:ne},{inferenceFramework:"ONNX",inferenceKind:se},{inferenceFramework:"ONNX",inferenceKind:ie},{inferenceFramework:"ONNX",inferenceKind:le},{inferenceFramework:"ONNX",inferenceKind:de},{inferenceFramework:"ONNX",inferenceKind:ce},{inferenceFramework:"ONNX",inferenceKind:ue},{inferenceFramework:"ONNX",taskType:"summary"},{inferenceFramework:"ONNX",taskType:"iab_classify"},{inferenceFramework:"ONNX",taskType:"classification"},{inferenceFramework:"ONNX",taskType:"text_generation"}],load:(e,t)=>((e,t)=>us(e,t,{logLabel:"[SLM][loadOnnxAdapter]",capability:e=>({inferenceFramework:"ONNX",taskType:e.taskType,inferenceKind:e.inferenceKind,modelType:e.modelType}),loadExecutor:dn("ONNX",Fs),onLoadError:(e,t)=>{(e instanceof Error?e.message:String(e)).includes("Unexpected token '<'")&&k().error("[SLM][loadOnnxAdapter] Parse error suggests HTML returned where JSON expected",{modelId:t.modelId,modelUrl:t.modelUrl})}}))(e,t)};pe(zs);class Ws{constructor(e){this.state=e,this.loadModelMs=e.loadModelMs}async runInference(e){const t=(e.text??"").trim();if(!t)return{output:{entities:[]},inferenceMs:0};const r="number"==typeof e.threshold&&Number.isFinite(e.threshold)?e.threshold:.4,o=(e.usecase??"ner").toLowerCase(),{result:n,ms:s}=await ms(async()=>this.state.pipeline(t));var i,a;const l=((e,t)=>e.filter(e=>e.score>=t))((i=n,a=t,Array.isArray(i)?i.flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e,r="string"==typeof t.entity_group?t.entity_group:"string"==typeof t.entity?t.entity:"string"==typeof t.label?t.label:null;if(!r)return[];const o="number"==typeof t.score?t.score:0,n="number"==typeof t.start?t.start:-1,s="number"==typeof t.end?t.end:-1,i="string"==typeof t.word?t.word:"string"==typeof t.text?t.text:n>=0&&s>n?a.slice(n,s):"";return i?[{text:i,label:r,score:o,start:n,end:s}]:[]}):[]),r),d=Array.isArray(e.labels)?e.labels:void 0,c=((e,t)=>{if(!t||0===t.length)return e;const r=new Set(t.map(e=>e.toLowerCase()));return e.filter(e=>r.has(e.label.toLowerCase()))})(l,d);if("redact"===o){const r="string"==typeof e.mask&&e.mask.length>0?e.mask:"[REDACTED]",o=((e,t,r)=>{if(0===t.length)return e;const o=[...t].sort((e,t)=>t.start-e.start);let n=e;for(const e of o){if(e.start<0||e.end<=e.start)continue;const t=r.includes("LABEL")?r.replace("LABEL",e.label):r;n=n.slice(0,e.start)+t+n.slice(e.end)}return n})(t,c,r);return{output:{text:o,entities:c},inferenceMs:s}}if("json"===o){const t=((e,t)=>{if(!e||"object"!=typeof e)return{};const r={};for(const[o,n]of Object.entries(e)){const e=Array.isArray(n)?n:[],s={};for(const r of e){if("string"!=typeof r)continue;const e=r.split("::")[0],o=t.find(t=>t.label.toLowerCase()===e.toLowerCase());o&&(s[e]=o.text)}r[o]=s}return r})(e.schema,c);return{output:t,inferenceMs:s}}if("classification"===o){const e=((e,t)=>{const r={};for(const o of t){const t=e.filter(e=>e.label.toLowerCase()===o.toLowerCase()).reduce((e,t)=>Math.max(e,t.score),0);r[o]=t}return r})(l,d??[]);return{output:e,inferenceMs:s}}return{output:{entities:c},inferenceMs:s}}async runSample(e){const t=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:"response from processing sample"};try{return await this.runInference({text:e.text,labels:e.labels,threshold:e.threshold,usecase:e.usecase??"ner",schema:e.schema,mask:e.mask,categories:e.categories}),{ok:!0,processingTimeMs:Math.round(performance.now()-t),error:!1,errorMessage:void 0}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}}}const Ks=async(e,t,r)=>{const o=k();try{await ro()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const n=oo(io(e.modelUrl,e.modelRepoId)),s=no(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!s)throw new Error("[Transformers] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const i=await bo(async()=>{const i=Qr(),a=i.TransformersEnv||{};a.allowRemoteModels=!0,a.allowLocalModels=!0,a.backends||(a.backends={}),a.backends.onnx||(a.backends.onnx={}),a.backends.onnx.wasm||(a.backends.onnx.wasm={}),a.backends.onnx.wasm.proxy=!1,a.backends.onnx.wasm.numThreads=1;const l=globalThis.fetch.bind(globalThis),d=await yo(l);d&&(a.backends.onnx.wasm.wasmPaths=d),a.fetch=ps(e.modelId,n,t,r,(e.requiredFiles??[]).map(e=>e.name),l),i.TransformersEnv=a,globalThis.fetch=a.fetch;try{return await ms(()=>{const t=i.TransformersPipeline;if(!t)throw new Error("transformers_pipeline_unavailable");return t("token-classification",s,{device:"wasm",quantized:e.quantized,aggregation_strategy:"simple",progress_callback:()=>{}})})}catch(e){const t=e instanceof Error?e.message:String(e);throw o.warn("[Transformers] token-classification pipeline load failed",{message:t}),new Error(`transformers_pipeline_load_failed:${t}`)}finally{globalThis.fetch=l}}),{result:a,ms:l}=i;return{pipeline:a,loadModelMs:l}},Ds=async(e,t,r)=>{const o=await Ks(e,t,r);return new Ws(o)},Gs={capabilities:[{inferenceFramework:"Transformers",taskType:"gliner"},{inferenceFramework:"Transformers",taskType:"gliner2"}],load:(e,t)=>((e,t)=>us(e,t,{logLabel:"Transformers adapter load",capability:e=>({inferenceFramework:"Transformers",taskType:e.taskType,modelType:e.modelType}),loadExecutor:dn("Transformers",Ds)}))(e,t)};pe(Gs);const Hs="https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js";let Js=null;const Xs=Hs.replace(/\/esm\/index\.js$/,"/esm");class Zs{constructor(e,t,r){this.config=e,this.capability={inferenceFramework:"GGUF",taskType:e.taskType,inferenceKind:e.inferenceKind,modelType:e.modelType},this.state=t,this.metrics=r}async runInference(e){const t=((e,t)=>{const r=(e??"").trim();return r?t&&t.toLowerCase().includes("instruct")?`<|im_start|>user\n${r}<|im_end|>\n<|im_start|>assistant\n`:r:""})(e.text??"",this.config.modelType);if(!t)return{output:{text:""},inferenceMs:0};const r="number"==typeof e.maxNewTokens&&e.maxNewTokens>0?e.maxNewTokens:128,{result:o,ms:n}=await ms(async()=>this.state.wllama.createCompletion(t,{nPredict:r}));return{output:{text:"string"==typeof o?o:Qs(o)},inferenceMs:n}}async runSample(e){const t=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:"response from processing sample"};try{const r=(await this.runInference({text:e.text,maxNewTokens:32,usecase:e.usecase})).output;return("string"==typeof r?.text?r.text.trim():"")?{ok:!0,processingTimeMs:Math.round(performance.now()-t),error:!1}:{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:"response from processing sample"}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}}}const Qs=e=>{if(!e)return"";if("string"==typeof e)return e;if("object"==typeof e){const t=e;if("string"==typeof t.text)return t.text;if("string"==typeof t.content)return t.content;if("string"==typeof t.completion)return t.completion}try{return JSON.stringify(e)}catch{return String(e)}},Ys=async(e,t,r)=>{const o=(e=>{if(!Array.isArray(e)||0===e.length)return null;const t=e.find(e=>e?.name?.toLowerCase().endsWith(".gguf"));return t?.name??e[0]?.name??null})(e.requiredFiles);if(!o)throw new Error("gguf_required_file_missing");const n=await(window.WllamaModule?Promise.resolve(window.WllamaModule):(Js||(Js=(async()=>{try{const e=await import(Hs);if(!e?.Wllama)throw new Error("Wllama runtime missing Wllama export");return window.WllamaModule=e,e}catch(e){throw Js=null,k().error("[GGUF] Failed to import wllama runtime",{runtimeUrl:Hs,error:m(e)}),e}})()),Js)),s=await(async(e,t,r,o)=>{const n=`${e.modelId}/${t}`,s=r[n]||r[t];if(s)return s;const i=(e.modelUrl||"").replace(/\/$/,"");if(!i)throw new Error("gguf_model_url_missing");const a=i.match(/^(.*?\/huggingface\.co\/[^/]+\/[^/]+)\/(?:tree|blob)\/([^/]+)(?:\/.*)?$/i),l=a?a[1]:i,d=[`${l}/resolve/${a?a[2]:"main"}/${t}`,`${l}/${t}`],c=[];for(const e of d)try{const t=await fetch(e);if(t.ok){const e=await t.blob();return o(n,e),e}c.push(`${e} → HTTP ${t.status}`)}catch(t){c.push(`${e} → ${t instanceof Error?t.message:String(t)}`)}throw new Error(`gguf_file_fetch_failed: ${c.join("; ")}`)})(e,o,t,r),i=window.WllamaWasmPaths??{"single-thread/wllama.wasm":`${Xs}/single-thread/wllama.wasm`,"multi-thread/wllama.wasm":`${Xs}/multi-thread/wllama.wasm`},a=new n.Wllama(i),{ms:l}=await ms(async()=>{await a.loadModel([s],{n_ctx:e.maxInputTokens&&e.maxInputTokens>0?e.maxInputTokens:2048})});return{wllama:a,loadModelMs:l}},ei={capabilities:[{inferenceFramework:"GGUF",inferenceKind:ae},{inferenceFramework:"GGUF",taskType:"text_generation"},{inferenceFramework:"GGUF",taskType:"summary"}],load:(e,t)=>(async(e,t)=>{const r=k(),o=performance.now(),n={};try{const r=await $o(e.modelId,e.modelVersion),s=r?.files||{};if(!r&&!1===t?.allowDownload)return{error:new Error("model_not_cached"),metrics:{}};const i=(e,t)=>{n[e]=t},a=r?{downloadMs:r.metadata.downloadMs,loadModelMs:r.metadata.loadModelMs,sizeBytes:r.metadata.sizeBytes}:{},l=await Ys(e,s,i),d={...a,loadModelMs:l.loadModelMs};if(Object.keys(n).length>0){const t={...s,...n},i=Object.values(t).reduce((e,t)=>e+t.size,0),a=Math.round(performance.now()-o);await Eo(e.modelId,e.modelVersion,{modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:i,downloadMs:r?0:a,loadModelMs:l.loadModelMs},t),d.sizeBytes=i,r||(d.downloadMs=a)}return{adapter:new Zs(e,l,d),metrics:d}}catch(t){return r.error("GGUF adapter load failed",{modelId:e.modelId,modelVersion:e.modelVersion,modelUrl:e.modelUrl,error:m(t)}),await Hr(e.modelId,e.modelVersion).catch(()=>{}),{error:t,metrics:{}}}})(e,t)};pe(ei);let ti=!1;const ri={get status(){return ot()},on:(e,t)=>(Ye[e]?.add(t),()=>Ye[e]?.delete(t)),shutdown:()=>Et({reason:"host_stop"}),get contributionState(){return Cn()},get activeModelId(){return Ln()},get deviceId(){return ee()?.deviceId??null},eligibleModels:Bn,switchModel:async e=>{const t="string"==typeof e?e.trim():"";if(!t)throw new vn("invalid_model_id","modelId is blank");if(st()||!oe())throw new xn("stopped");let r=qn??await Bn(),o=r.find(e=>e.modelId===t);if(o&&o.eligible||(r=await Bn(),o=r.find(e=>e.modelId===t)),!o)throw new In(t,"not_offered");if(!o.eligible)throw new In(t,o.reason??"not_eligible");if((e=>{pn(cn,e.trim())})(t),Ln()===t&&"contributing"===Cn())return{requestedModelId:t,activeModelId:t,granted:!0};if(rt())throw new xn("stopped");$n?.reject(new vn("switch_superseded","a newer switch replaced this one"));const n=new Promise((e,r)=>{$n={modelId:t,resolve:e,reject:r}});En=!0,k().info(`${An} Switching model`,{to:t,from:Ln()??void 0}),ar(!0);try{await(async()=>{await sr(),ir()})();const e=Z();J(void 0);try{e?.close(1e3,"switching")}catch{}Q("error"),xt(),await(async()=>{const e=ee()?.adaptersByModelId??{};for(const t of Object.values(e))try{await(t.dispose?.())}catch{}G({})})()}finally{ar(!1)}return Mt("switch")||Rn(new xn("stopped")),n},runLocal:async e=>{const t=Cn();if("contributing"!==t)throw new xn(t,"declined"===t?re()??void 0:void 0);const r=ee(),o=Ln(),n=o?D(o):void 0,s=o?r?.modelInfosByModelId?.[o]:void 0;if(!o||!n||!s)throw new xn("preparing");if(!e||"object"!=typeof e)throw new vn("invalid_input","input must be an object");const i="string"==typeof e.text?e.text:"",a="number"==typeof s.maxTokens&&s.maxTokens>0?s.maxTokens:0;if(a>0&&We(i)>a)throw new vn("input_too_large",`input of about ${We(i)} tokens exceeds the model's cap of ${a}`);const l=$e(),{value:d,queueWaitMs:c}=await(async e=>{rr+=1;const t=performance.now();try{await sr();const r=Math.round(performance.now()-t);try{return{value:await e(),queueWaitMs:r}}finally{ir()}}finally{rr-=1}})(async()=>{const t=performance.now();try{return{output:await n.runInference(e),processingMs:Math.round(performance.now()-t)}}catch(e){const r=e instanceof Error?e.message:String(e),n=(e=>{const t=e instanceof Error?e.message:String(e??"");return e instanceof RangeError||/out of memory|oom|wasm.*abort|allocation failed/i.test(t)})(e);throw l.report("task.failed",{code:n?"oom":"app_adapter_error",modelId:o,modelVersion:s.modelVersion,taskType:s.taskType,durationMs:Math.round(performance.now()-t),message:r}),n&&Nt(r),new Mn(r||"inference failed",e)}});return{response:d.output.output,modelId:o,modelVersion:s.modelVersion??"1",location:"device",runtime:s.inferenceFramework?.trim().toLowerCase()||void 0,queueWaitMs:c,processingMs:"number"==typeof d.output.inferenceMs?d.output.inferenceMs:d.processingMs}},clearModelChoice:()=>yn(),forgetUnfitModel:e=>(e=>{const t=wn(),r=t.filter(t=>t.modelId!==e);r.length!==t.length&&bn(r)})(e)},oi=()=>ri,ni=oi,si=async e=>{if(ti)return ri;ti=!0,e?.resourcePolicy&&((e=>{Re=e??{},Ue=Oe(null)})(e.resourcePolicy),e.resourcePolicy.disableGuardrails&&console.warn("[herogpu] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only."));const r=(e=>{const r=t,i=o(r,e??{});return{sdkVersion:n(i.sdkVersion,r.sdkVersion),orchestrator:{baseUrl:n(i.orchestrator?.baseUrl,r.orchestrator.baseUrl),registerPath:n(i.orchestrator?.registerPath,r.orchestrator.registerPath),eventsPath:n(i.orchestrator?.eventsPath,r.orchestrator.eventsPath)},telemetry:{enableConsoleLogs:s(i.telemetry?.enableConsoleLogs,r.telemetry.enableConsoleLogs),locationData:s(i.telemetry?.locationData,r.telemetry.locationData),events:s(i.telemetry?.events,r.telemetry.events)},inference:{worker:s(i.inference?.worker,r.inference.worker),...n(i.inference?.workerUrl,"")?{workerUrl:n(i.inference?.workerUrl,"")}:{}}}})(e?.overrides);(e=>{zo={appId:Wo(e?.appId),appName:Wo(e?.appName),externalAppId:Wo(e?.externalAppId)}})(e),void 0!==e?.customParams&&(b(r.telemetry),Yt(e.customParams));try{await Wn({config:r,appUserId:e?.appUserId,edgeOperatorKey:e?.edgeOperatorKey,deviceId:e?.deviceId})}catch(e){k().error("[Init] SDK initialization failed",{error:m(e)})}return ri},ii=si,ai=(e,t)=>{for(const r of t){const t=e.getAttribute(r)?.trim();if(t)return t}},li=(e,t)=>{if(e)for(const r of t){const t=e.get(r)?.trim();if(t)return t}},di=(e,t)=>{for(const r of t){const t=e.getAttribute(r);if(null===t)continue;const o=t.trim().toLowerCase();if(""===o)return!0;if("true"===o||"1"===o)return!0;if("false"===o||"0"===o)return!1}};(()=>{const e="undefined"==typeof document?null:document.currentScript instanceof HTMLScriptElement?document.currentScript:null;if(!e)return;let t;const r=e.getAttribute("src")?.trim();if(r)try{const e=new URL(r,"undefined"!=typeof document?document.baseURI:void 0);t=e.searchParams}catch{t=void 0}const o=ai(e,["data-edge-operator-key","edgeOperatorKey"])??li(t,["edge-operator-key","edgeOperatorKey"]);if(!o)return;const n={appUserId:ai(e,["data-app-user-id","appUserId"])??li(t,["app-user-id","appUserId"]),deviceId:ai(e,["data-device-id","deviceId"])??li(t,["device-id","deviceId"]),appId:ai(e,["data-app-id","appId"])??li(t,["app-id","appId"]),appName:ai(e,["data-app-name","appName"])??li(t,["app-name","appName"]),externalAppId:ai(e,["data-external-app-id","externalAppId"])??li(t,["external-app-id","externalAppId"]),edgeOperatorKey:o},s={};for(const r of Dt){const o=r.slice(10),n=ai(e,[`data-cust-param${o}`,r])??li(t,[`cust-param${o}`,r]);void 0!==n&&(s[r]=n)}Object.keys(s).length>0&&(n.customParams=s);const i=di(e,["data-enable-console-logs","enableConsoleLogs"])??(()=>{const e=li(t,["enable-console-logs","enableConsoleLogs"]);if(void 0===e)return;const r=e.toLowerCase();return"true"===r||"1"===r||"false"!==r&&"0"!==r&&void 0})(),a=di(e,["data-herogpu-telemetry-events","herogpuTelemetryEvents","data-zerogpu-telemetry-events","zerogpuTelemetryEvents"])??(()=>{const e=li(t,["telemetry-events","herogpuTelemetryEvents","zerogpuTelemetryEvents"]);if(void 0===e)return;const r=e.toLowerCase();return"true"===r||"1"===r||"false"!==r&&"0"!==r&&void 0})();if(void 0!==i||void 0!==a){const e={};void 0!==i&&(e.enableConsoleLogs=i),void 0!==a&&(e.events=a),n.overrides={telemetry:e}}si(n).catch(e=>{i&&console.error("[herogpu] Auto-init failed",e instanceof Error?`${e.name}: ${e.message}`:String(e))})})(),e.CONTRIBUTION_STATES=["stopped","registering","declined","preparing","switching","degraded","contributing"],e.HeroGpuError=vn,e.LocalInferenceFailedError=Mn,e.ModelNotEligibleError=In,e.NotContributingError=xn,e.ZeroGpuError=_n,e.getHeroGpuSdk=oi,e.getZeroGpuSdk=ni,e.initHeroGpuSdk=si,e.initZeroGpuSdk=ii,e.isHeroGpuError=Tn,e.isZeroGpuError=Sn,e.setCustomParams=e=>{Yt(e)}}),function(e){e&&e.HeroGpuBrowserSdk&&(e.ZeroGpuBrowserSdk=e.HeroGpuBrowserSdk)}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:this);