@zerogpu/browser-extension-sdk 0.5.0 → 0.6.0-dev.202612031336.gae43e53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -41
- package/bin/browser-extension-sdk.mjs +23 -0
- package/bin/cli.mjs +781 -0
- package/bin/herogpu.mjs +6 -0
- package/bin/zerogpu.mjs +6 -585
- package/dist/assets/herogpu-assets.json +21 -0
- package/dist/assets/herogpu-worker.js +1 -0
- package/dist/assets/zerogpu-assets.json +3 -3
- package/dist/assets/zerogpu-worker.js +1 -1
- package/dist/extension/herogpu-background.js +1 -0
- package/dist/extension/herogpu-offscreen.js +1 -0
- package/dist/extension/herogpu-settings-link.js +1 -0
- package/dist/extension/zerogpu-background.js +1 -1
- package/dist/extension/zerogpu-offscreen.js +1 -1
- package/dist/extension/zerogpu-settings-link.js +1 -1
- package/dist/herogpu-browser-sdk.cjs +1 -0
- package/dist/herogpu-browser-sdk.esm.js +1 -0
- package/dist/herogpu-browser-sdk.umd.js +1 -0
- package/dist/herogpu-worker.js +1 -0
- package/dist/loader.js +1 -1
- package/dist/manifest.json +6 -6
- package/dist/types/appinference/store.d.ts +18 -6
- package/dist/types/appinference/types.d.ts +29 -10
- package/dist/types/branding.d.ts +27 -0
- package/dist/types/config/types.d.ts +1 -1
- package/dist/types/extension/background.d.ts +68 -19
- package/dist/types/extension/consent.d.ts +61 -10
- package/dist/types/extension/offscreen.d.ts +64 -23
- package/dist/types/extension/settings-link.d.ts +12 -1
- package/dist/types/inference/runtime-locator.d.ts +1 -1
- package/dist/types/inference/worker-host.d.ts +1 -1
- package/dist/types/loader.d.ts +15 -3
- package/dist/types/public-api.d.ts +16 -10
- package/dist/types/runtime/app-identity.d.ts +2 -2
- package/dist/types/runtime/app-inference.d.ts +1 -1
- package/dist/types/runtime/custom-params.d.ts +1 -1
- package/dist/types/runtime/host-api.d.ts +2 -1
- package/dist/types/runtime/init-guard.d.ts +4 -1
- package/dist/types/runtime/tracking-script.d.ts +1 -1
- package/dist/types/storage/adopted-key.d.ts +23 -0
- package/dist/types/storage/cached-model.d.ts +4 -1
- package/dist/types/storage/model-store.d.ts +6 -0
- package/dist/types/transport/protocol.d.ts +1 -1
- package/dist/v/herogpu-browser-sdk.33541d5a9aa7.umd.js +1 -0
- package/dist/v/zerogpu-browser-sdk.33541d5a9aa7.umd.js +1 -0
- package/dist/zerogpu-browser-sdk.cjs +1 -1
- package/dist/zerogpu-browser-sdk.esm.js +1 -1
- package/dist/zerogpu-browser-sdk.umd.js +1 -1
- package/dist/zerogpu-worker.js +1 -1
- package/docs/app-side-inference.md +60 -46
- package/docs/auto-update-loader.md +33 -19
- package/docs/extension-developer-guide.md +158 -75
- package/docs/multi-model-support.md +14 -14
- package/package.json +13 -10
- package/dist/v/zerogpu-browser-sdk.5f140942519b.umd.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={sdkVersion:"0.5.0+36fc495",orchestrator:{baseUrl:"https://devices.zerogpu.ai",registerPath:"/register",eventsPath:"/events"},telemetry:{enableConsoleLogs:!1,locationData:!1,events:!0},inference:{worker:!0}},t=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),r=(e,o)=>{const n=Array.isArray(e)?[...e]:{...e};for(const e of Object.keys(o)){const s=o[e];if(void 0===s)continue;const i=n[e];t(s)&&t(i)?n[e]=r(i,s):n[e]=s}return n},o=(e,t)=>"string"==typeof e&&e.length>0?e:t,n=(e,t)=>"boolean"==typeof e?e:t,s=200,i=/(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i,a=new Set(["url","wsurl","baseurl","modelurl","modelrepourl","runtimeurl","requesturl","endpoint","endpointurl","manifesturl","bundleurl","orchestrator"]),d=new Set(["message","errormessage","error","reason"]),l=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"]),c=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e,m=e=>{if(e instanceof Error)return c(`${e.name}: ${e.message}`,s);if("string"==typeof e)return c(e,s);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 c(`${t}: ${r}`,s)}return"object"==typeof e?`[${e.constructor?.name??"object"}]`:c(String(e),s)},u=e=>Array.isArray(e)?`[array:${e.length}]`:e&&"object"==typeof e?`[object:${Object.keys(e).length} keys]`:`[${typeof e}]`,f=(e,t)=>{const r=e.toLowerCase();return a.has(r)?(e=>{try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid-url]"}})(t):d.has(r)?c(t,s):l.has(r)?c(t,256):`[string:${t.length}]`},p=(e,t)=>i.test(e)?"[redacted]":null==t||"boolean"==typeof t?t:"number"==typeof t?Number.isFinite(t)?t:String(t):"string"==typeof t?f(e,t):t instanceof Error?m(t):u(t),g=e=>"string"==typeof e?c(e,s):"[invalid log message]";class h{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,g(r),o):void 0===o?t("[ZeroGPU]",g(r)):t("[ZeroGPU]",g(r),(e=>{if(e instanceof Error)return{error:m(e)};if(!e||"object"!=typeof e||Array.isArray(e))return{detail:p("detail",e)};const t={};for(const[r,o]of Object.entries(e))Array.isArray(o)?i.test(r)?t[r]="[redacted]":o.every(e=>null===e||"object"!=typeof e)?t[r]=o.slice(0,20).map(e=>p(r,e)):t[r]=u(o):t[r]=p(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 y=null;const w=(e,t)=>(y=new h(e,t),y),k=()=>(y||(y=new h({enableConsoleLogs:!1,locationData:!1,events:!0})),y),b="zerogpu_device_id",I=()=>{try{return window.localStorage.getItem(b)}catch{return null}},v=e=>{try{window.localStorage.setItem(b,e)}catch{}},_=()=>"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)}),M=()=>{const e=I();if(e)return e;const t=_();return v(t),t},x=()=>navigator,S=()=>{if("undefined"!=typeof window)return window.Telegram?.WebApp},T=()=>{const e=navigator.userAgent.toLowerCase(),t=S();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"},A=()=>{const e=navigator.userAgent??"",t=x().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"},$=()=>{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=x().getBattery;if(e){const t=await e.call(navigator);return{level:t.level,charging:t.charging}}}catch{}},U=()=>{const e=x(),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})})},E=()=>{const e=S(),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 q extends Error{constructor(e,t){super(`Register failed: ${e} ${t??""}`.trim()),this.status=e,this.body=t}}const V=async e=>{try{return await e.clone().json()}catch{return null}},R=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},B=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 L extends Error{constructor(e,t){super(`Eligible models failed: ${e} ${t??""}`.trim()),this.status=e,this.body=t}}const O=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 j{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:O(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:O(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,N={status:"idle",phase:"idle"},F=(e,t)=>{N.adaptersByModelId||(N.adaptersByModelId={}),t?N.adaptersByModelId[e]=t:delete N.adaptersByModelId[e]},W=e=>N.adaptersByModelId?.[e],K=e=>{N.adaptersByModelId=e??{}},D=e=>{N.cachedModelId=e??null},G=e=>{N.ws=e,N.sessionAcked=!1},J=()=>!0===N.sessionAcked,H=()=>N.ws,X=e=>{N.status=e},Z=()=>{if(!N.config||!N.deviceId||!N.deviceInfo)throw new Error("SDK state not initialized");return N},Q=()=>N.config&&N.deviceId&&N.deviceInfo?N:null,Y=(e,t)=>{N.phase=e,N.declinedReason="declined"===e?t??null:null},ee=()=>N.declinedReason??null,te=()=>N.lifecycleOptions,re="sequence_classification",oe="seq2seq_generation",ne="zero_shot_classification",se="decoder_generation",ie="token_classification",ae="question_answering",de="text_embedding",le="fill_mask",ce=e=>{if("string"!=typeof e)return;const t=e.trim().toLowerCase();return t.length>0?t:void 0},me=[],ue=e=>{me.push(e)},fe=(e,t)=>e.inferenceFramework.toLowerCase()===t.toLowerCase(),pe=(e,t,r)=>{if(!e)return;const o=ce(r);if(o){const t=me.find(t=>t.capabilities.some(t=>((e,t,r)=>"string"==typeof e.inferenceKind&&fe(e,t)&&e.inferenceKind.toLowerCase()===r)(t,e,o)));if(t)return t}return t?me.find(r=>r.capabilities.some(r=>((e,t,r)=>"string"==typeof e.taskType&&fe(e,t)&&e.taskType.toLowerCase()===r.toLowerCase())(r,e,t))):void 0},ge={"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"},he=new Set(["ok","idle","ready"]),ye=(e,t)=>"ws.hello_ack"===e&&t&&!he.has(t)?"error":ge[e]??"info",we="zerogpu_event_buffer",ke=()=>{const e=(e=>{try{return window.localStorage.getItem(e)}catch{return null}})(we);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}},be=e=>{const t=e.length>100?e.slice(-100):e;((e,t)=>{try{window.localStorage.setItem(e,t)}catch{}})(we,JSON.stringify(t))},Ie=e=>{0!==e.length&&be([...ke(),...e])},ve=_(),_e=new Set(["guardrail.shutdown","guardrail.degraded","sdk.shutdown","sdk.crash_detected","ws.reconnect_scheduled"]);class Me{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(...ke()),(()=>{try{window.localStorage.removeItem(we)}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(_e.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:ve,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:_(),type:t,ts:(new Date).toISOString(),seq:this.seq++,severity:ye(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(()=>Ie(t))}catch{Ie(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||Ie(t)}).catch(()=>Ie(t))}catch{Ie(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 xe=null;const Se=new Me({enabled:!1,endpointUrl:"",operatorKey:"",deviceId:"",sdkVersion:"",platform:""}),Te=()=>xe??Se,Ae={onnx:2,transformersjs:2.5,transformers:2.5,gguf:1.4},$e=.7,Pe=.85,Ue=.95,Ce=1e4,Ee=.6,qe=6e4;let Ve={},Re=Le(null);function Be(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}function Le(e){const t=e?.watchdog??{},r=Object.fromEntries(Object.entries(e?.frameworkMultipliers??{}).filter(([,e])=>void 0!==Be(e)));return{memoryBudgetFraction:Be(Ve.memoryBudgetFraction)??Be(e?.memoryBudgetFraction)??.3,frameworkMultipliers:{...Ae,...r},minBatteryLevel:Be(e?.minBatteryLevel)??.2,storageHeadroom:Be(e?.storageHeadroom)??1.2,unknownMemoryGb:Be(e?.unknownMemoryGb)??2,watchdog:{warnPct:Be(t.warnPct)??$e,degradePct:Be(t.degradePct)??Pe,shutdownPct:Be(t.shutdownPct)??Ue,sampleMs:Be(t.sampleMs)??Ce,recoverPct:Be(t.recoverPct)??Ee,recoverHoldMs:Be(t.recoverHoldMs)??qe},maxMemoryBudgetMb:Be(e?.maxMemoryBudgetMb)??0,maxInputTokens:Be(e?.maxInputTokens)??0,sampleLatencyBudgetMs:Be(e?.sampleLatencyBudgetMs)??0,maxCachedModels:"number"==typeof Ve.maxCachedModels&&Number.isFinite(Ve.maxCachedModels)&&Ve.maxCachedModels>=0?Math.floor(Ve.maxCachedModels):"number"==typeof e?.maxCachedModels&&Number.isFinite(e.maxCachedModels)&&e.maxCachedModels>=0?Math.floor(e.maxCachedModels):3,wasm:{maxThreads:Be(e?.wasm?.maxThreads)??4,proxyWorker:!0===e?.wasm?.proxyWorker}}}const Oe=()=>Ve,je=()=>Re,ze=e=>"number"!=typeof e||!Number.isFinite(e)||e<=0?0:e<1e6?1024*e*1024:e,Ne=e=>Math.ceil(e.length/4),Fe=(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=Re.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}};let We="starting";const Ke={degraded:new Set,recovered:new Set,shutdown:new Set,activeModelChanged:new Set,modelChoiceRefused:new Set};let De=!1;const Ge=e=>{De=e},Je=()=>De,He=()=>We,Xe=e=>{"shutdown"!==We&&(We=e)},Ze=()=>"shutdown"===We,Qe=(e,t)=>(Ke[e]?.add(t),()=>Ke[e]?.delete(t)),Ye=(e,t={})=>{for(const r of Ke[e]??[])try{r(t)}catch{}try{"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent(`zerogpu:${e}`,{detail:t}))}catch{}},et="zerogpu_init_state",tt=3e5,rt=new Set(["downloading","loading","sampling"]),ot=()=>{try{const e=window.localStorage.getItem(et);if(!e)return null;const t=JSON.parse(e);return"number"!=typeof t?.attempts||"number"!=typeof t?.windowStart?null:t}catch{return null}},nt=e=>{try{window.localStorage.setItem(et,JSON.stringify(e))}catch{}},st=(e,t)=>`${e}@${t??"1"}`,it=e=>({modelCrashes:e?.modelCrashes,blocklist:e?.blocklist,lastShutdown:e?.lastShutdown}),at=(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};const s=rt.has(n);let i;if(s&&e?.modelId){const n=st(e.modelId,e.modelVersion),s=r?.[n],a=s&&t-s.firstAt<864e5,d=a?s.count+1:1;r={...r??{},[n]:{count:d,firstAt:a?s.firstAt:t}},d>=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}},dt=()=>{const e=ot();nt({attempts:0,windowStart:Date.now(),phase:e?.phase,modelId:e?.modelId,modelVersion:e?.modelVersion,...it(e)})},lt=(e,t,r)=>{const o=ot();nt({attempts:o?.attempts??0,windowStart:o?.windowStart??Date.now(),cooldownUntil:o?.cooldownUntil,phase:e,modelId:t,modelVersion:r,...it(o)})},ct=()=>{const e=ot();nt({attempts:e?.attempts??0,windowStart:e?.windowStart??Date.now(),cooldownUntil:e?.cooldownUntil,...it(e)})},mt=(e,t)=>{const r=ot(),o=r?.blocklist?.[st(e,t)];return Boolean(o&&o.until>Date.now())};let ut=null;const ft=()=>null!==ut,pt=(e,t)=>{gt(),ut=setTimeout(()=>{ut=null,e()},t)},gt=()=>{null!==ut&&(clearTimeout(ut),ut=null)};let ht=null;const yt=e=>!!ht&&(ht(e),!0),wt=e=>{try{const t=Z(),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{}},kt=[6e4,3e5,9e5,18e5];let bt=0,It=0;const vt=async({reason:e,guardrail:t=!1})=>{if("shutdown"===He())return;if(t&&Je())return;const r=k();r.warn("[Shutdown] Running shutdown sequence",{reason:e,guardrail:t}),t?(Ge(!0),Xe("error")):Xe("shutdown"),gt();try{t&&wt("error")}catch{}try{H()?.close(t?4002:1e3,e)}catch{}try{G(void 0),X("error"),Y("idle")}catch{}const o=Te();o.report(t?"guardrail.shutdown":"sdk.shutdown",{code:e});try{o.flush({beacon:!0})}catch{}try{const{adaptersByModelId:e,modelInfosByModelId:t}=Z(),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{}K({})}catch{}if((e=>{const t=ot();nt({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 Ye("shutdown",{code:e});const n=((e=Date.now())=>{It>0&&e-It>18e5&&(bt=0);const t=kt[Math.min(bt,kt.length-1)];return bt+=1,It=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}),Ye("shutdown",{code:e,restartInMs:n}),pt(()=>{Ge(!1),yt(`guardrail_restart:${e}`)||r.warn("[Shutdown] No lifecycle to restart")},n)};class _t{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 Mt=null;const xt=()=>{const e=globalThis.performance,t=e?.memory?.usedJSHeapSize;return"number"==typeof t&&t>0?t:null},St=()=>{if(null!==Mt||Oe().disableGuardrails)return;if(null===xt())return void k().debug("[Watchdog] performance.memory unavailable; watchdog inactive");const e=je();let t=e.unknownMemoryGb;try{const e=Z().deviceInfo?.memoryGb;"number"==typeof e&&e>0&&(t=e)}catch{}const r=e.memoryBudgetFraction*t*1024*1024*1024,o=new _t(e.watchdog,r);Mt=setInterval(()=>{try{if("shutdown"===He())return void Tt();if("undefined"!=typeof document&&"hidden"===document.visibilityState)return;const e=xt();if(null===e)return;((e,t)=>{const r=t?e.transition(t):null;if(!r)return;const o=Te();switch(r){case"warn":o.report("guardrail.pressure_warning",{code:"memory_pressure"});break;case"degrade":Xe("degraded"),wt("error"),o.report("guardrail.degraded",{code:"memory_pressure"}),Ye("degraded",{code:"memory_pressure"});break;case"recover":Xe("running"),wt("idle"),Ye("recovered",{});break;case"shutdown":Tt(),vt({reason:"memory_pressure",guardrail:!0})}})(o,o.onSample(e,Date.now()))}catch{}},e.watchdog.sampleMs)},Tt=()=>{null!==Mt&&(clearInterval(Mt),Mt=null)},At=e=>{Tt(),vt({reason:"oom",guardrail:!0}),k().error("[Watchdog] Allocation failure — emergency shutdown",{message:e})},$t=new Set,Pt=(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,$t.delete(o)),r(e))};try{n=setTimeout(()=>i("timeout"),t),o=new Image,o.onload=()=>i("fired"),o.onerror=()=>i("fired"),$t.add(o),o.src=e}catch{i("skipped")}});let Ut=null,Ct=null,Et=null,qt=0;const Vt=(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),Rt=async(e,t=3e3)=>{try{const r=await(Et||(Et=new Promise(e=>{if(!Ut||!Ct||"undefined"==typeof document||"undefined"==typeof window)return void e(null);let t,r=!1;const o=t=>{r||(r=!0,window.removeEventListener("message",n),e(t))},n=e=>{t&&e.origin===Ct&&e.source===t.contentWindow&&"zerogpu:runner:ready"===e.data?.type&&o(t.contentWindow)};try{window.addEventListener("message",n),t=document.createElement("iframe"),t.setAttribute("aria-hidden","true"),t.style.display="none",t.src=Ut,(document.body??document.documentElement).appendChild(t),setTimeout(()=>o(null),2e3)}catch{o(null)}}),Et));if(r){const o=await((e,t,r)=>new Promise(o=>{const n="zgpu-"+ ++qt;let s,i=!1;const a=e=>{i||(i=!0,void 0!==s&&clearTimeout(s),window.removeEventListener("message",d),o(e))},d=t=>{const r=t.data;t.origin===Ct&&t.source===e&&"zerogpu:tag:result"===r?.type&&r.id===n&&a("skipped"===r.status?"skipped":"fired")};try{window.addEventListener("message",d),s=setTimeout(()=>a("timeout"),r),e.postMessage({type:"zerogpu:tag:fire",id:n,url:t},Ct)}catch{a("skipped")}}))(r,e,t);if("skipped"!==o)return o}}catch{}const r=await Vt(e,t);return null!==r?r:((e,t)=>"function"!=typeof fetch?Pt(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)},Bt=["cust_param1","cust_param2","cust_param3"],Lt=/^[A-Za-z0-9._-]+$/,Ot=/[^\s@]+@[^\s@]+\.[^\s@]+/,jt=e=>Bt.includes(e);let zt=!1;const Nt=(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(Ot.test(r))console.warn(`[ZeroGPU] customParams.${e} looks like an email address and was dropped. Slots must not carry personal data.`);else{if(Lt.test(r))return r.length>128&&(zt||(zt=!0,k().warn("[CustomParams] Value truncated",{name:e,length:r.length,maxLength:128})),r=r.slice(0,128)),r;console.warn(`[ZeroGPU] customParams.${e} was dropped. A slot takes just a value (letters, digits, "." "_" "-"), not a nested parameter such as "user-id=123".`)}};let Ft={};const Wt=e=>{Ft=(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=Nt(e,o);void 0!==n&&(t[e]=n)}return t})(e)},Kt=()=>({...Ft});let Dt=!1,Gt=0,Jt=!1;const Ht=[],Xt=()=>Dt?new Promise(e=>{Ht.push(()=>{Dt=!0,e()})}):(Dt=!0,Promise.resolve()),Zt=()=>{Dt=!1;const e=Ht.shift();e&&e()},Qt=e=>{Jt=e},Yt=async e=>{const t=k(),r=performance.now(),o={cust_param1:Ft.cust_param1??"",cust_param2:Ft.cust_param2??"",cust_param3:Ft.cust_param3??""},{adaptersByModelId:n}=Z();let s=n?.[e.modelId];if(s||(s=await(async e=>{const t=k(),{modelInfosByModelId:r}=Z(),o=r?.[e];if(!o)return;const n=pe(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 F(e,i.adapter),i.adapter;t.warn("Lazy adapter load failed",{modelId:e,error:i.error?.message})})(e.modelId)),!s)return Te().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=Re.maxInputTokens)=>t>0&&Ne(e)>t)(i))return Te().report("task.rejected",{code:"not_ready",modelId:e.modelId,data:{reason:"input_too_large",estimatedTokens:Ne(i),maxInputTokens:je().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?Pt(e.trackingPixel).then(e=>{a=e}):e.trackingScript&&Rt(e.trackingScript).then(e=>{a=e});const d=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 d(),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 Te().report("task.failed",{code:s?"oom":"adapter_error",modelId:e.modelId,durationMs:Math.round(performance.now()-r),message:n}),s&&At(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 d()}}}},er=async e=>{const{ws:t,sessionKey:r,deviceId:o}=Z(),n=k(),s=e=>{const n={requests:e,deviceId:o,sessionKey:r};t?.send(n)};if(0!==e.requests.length){if("degraded"===We||"shutdown"===We||De)return Te().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(Jt||Dt||Gt>0)return Te().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}})));Dt=!0,X("busy");try{const t=[];for(const r of e.requests){const e=await Yt(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{Zt(),X("idle")}}},tr=30,rr="exponential",or=1e3,nr=2,sr=3e4,ir=500,ar=0,dr=86400,lr=600,cr="stop",mr=0,ur={min:15,max:120},fr={min:250,max:6e4},pr={min:1,max:4},gr={min:5e3,max:36e5},hr={min:0,max:3e4},yr={min:3600,max:604800},wr={min:60,max:86400},kr=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,br=(e,t,r)=>{const o=kr(e);return void 0===o||o<=0?r:Math.min(Math.max(o,t.min),t.max)},Ir=(e,t,r)=>{const o=kr(e);return void 0===o||o<0?r:Math.min(Math.max(o,t.min),t.max)},vr=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),_r=e=>{const t=vr(e),r=t?e:{},o=vr(r.keep_alive)?r.keep_alive:{},n=vr(r.reconnect)?r.reconnect:{},s=vr(r.reregister)?r.reregister:{},i=vr(r.socket)?r.socket:{},a=kr(n.give_up_after_attempts);return{served:t,keepAlive:{pingIntervalSeconds:br(o.ping_interval_seconds,ur,tr)},reconnect:{strategy:"fixed"===n.strategy?"fixed":rr,initialDelayMs:br(n.initial_delay_ms,fr,or),multiplier:br(n.multiplier,pr,nr),maxDelayMs:br(n.max_delay_ms,gr,sr),jitterMs:Ir(n.jitter_ms,hr,ir),giveUpAfterAttempts:void 0!==a&&a>=0&&Number.isInteger(a)?a:ar},reregister:{maxStalenessSeconds:br(s.max_staleness_seconds,yr,dr),onRefusalRetrySeconds:br(s.on_refusal_retry_seconds,wr,lr),onAuthFailure:"retry_slow"===s.on_auth_failure?"retry_slow":cr},socket:{idleTimeoutSeconds:Ir(i.idle_timeout_seconds,{min:0,max:Number.MAX_SAFE_INTEGER},mr)}}};let Mr=_r(void 0),xr=0,Sr=null;const Tr=(e,t)=>{const r=_r(e),o=((e,t)=>{const r=[],o=(e,t,n)=>{if(vr(e)&&vr(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})(Mr,r);return Mr=r,{policy:r,source:t,changed:o}},Ar=()=>Mr,$r="models";class Pr extends Error{constructor(e,t){const r=Ur(t),o=Cr(t);super(`model_store_${e}_failed:${r}${o?`:${o}`:""}`),this.name="ModelStoreError",this.operation=e,this.causeName=r}}const Ur=e=>e&&"object"==typeof e&&"string"==typeof e.name?e.name:null==e?"UnknownError":typeof e,Cr=e=>e&&"object"==typeof e&&"string"==typeof e.message?e.message.slice(0,200):"",Er=async(e,t)=>{const r=await new Promise((e,t)=>{if("undefined"==typeof indexedDB)return void t(new Pr("open",{name:"IndexedDBUnavailable",message:"indexedDB is not defined"}));let r;try{r=indexedDB.open("zerogpu-slm-cache",1)}catch(e){return void t(new Pr("open",e))}r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains($r)||e.createObjectStore($r,{keyPath:"key"})},r.onsuccess=()=>e(r.result),r.onerror=()=>t(new Pr("open",r.error))}),o="readonly"===e?"read":"write";return new Promise((n,s)=>{let i,a,d=!1;const l=(e,t=!1)=>{if(!d){d=!0;try{r.close()}catch{}t?s(e instanceof Pr?e:new Pr(o,e)):n(a)}};let c,m;try{c=r.transaction($r,e)}catch(e){return void l(e,!0)}c.oncomplete=()=>l(),c.onerror=e=>{const t=e?.target;i=i??t?.error??c.error},c.onabort=()=>l(i??c.error,!0);try{m=c.objectStore($r)}catch(e){return void l(e,!0)}t(m).then(e=>{a=e}).catch(e=>{i=i??e;try{c.abort()}catch{l(e,!0)}})})},qr=(e,t)=>`${e}:${t}`,Vr=async(e,t)=>{const r=qr(e,t);return Er("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)}))},Rr=async(e,t)=>{await Er("readwrite",async r=>{r.delete(qr(e,t))})},Br="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";let Lr={...{transformersUrl:Br}};const Or=()=>Lr,jr=()=>globalThis,zr=e=>{e&&(e.useBrowserCache=!1)},Nr="transformers-cache";let Fr=null;const Wr=()=>{const e=jr();if(e.TransformersPipeline)return Promise.resolve();if(!Fr){const t=k(),r=Or().transformersUrl;Fr=(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,zr(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 Fr=null,t.error("[SLM] Failed to import Transformers runtime",{runtimeUrl:r,error:m(e)}),e}})()}return Fr},Kr=e=>e.replace(/\/$/,""),Dr=e=>/^https?:\/\//i.test(e.trim()),Gr=e=>{const t=(e=>{const t=e.trim();if(!t)return"";if(Dr(t))try{return new URL(t).pathname.replace(/^\/+|\/+$/g,"")}catch{return""}return t.replace(/^\/+|\/+$/g,"")})(e);return t?Kr(`https://huggingface.co/${t}/resolve/main`):""},Jr=(e,t)=>{const r=(e||"").trim();if(Dr(r))return Kr(r);const o=Gr(t||r);return o||Kr(r)},Hr=e=>e.replace(/^\/+/,"").replace(/^resolve\/main\//,"").split("?")[0],Xr=(e,t)=>`${e}/${Hr(t)}`,Zr=()=>{const e=Or().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}},Qr=[0,97,115,109],Yr=["ort-wasm-simd-threaded.wasm","ort-wasm-simd.wasm","ort-wasm-threaded.wasm","ort-wasm.wasm"],eo=e=>e.endsWith("/")?e:`${e}/`,to=()=>{try{const e=new URL(Br),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/"}},ro=e=>e.length>=Qr.length&&Qr.every((t,r)=>e[r]===t);let oo=null;const no=e=>(oo||(oo=(async e=>{const t=[Or().wasmPaths,Zr(),to(),"https://unpkg.com/@xenova/transformers@2.17.2/dist/"].filter(e=>"string"==typeof e&&e.length>0).map(eo).filter((e,t,r)=>r.indexOf(e)===t);for(const r of t){let t=!1;for(const o of Yr){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(ro(s))return r;t=!0;break}catch{}}t&&k().warn("[SLM] ONNX wasm probe got non-wasm payload",{url:r})}return null})(e)),oo);let so=Promise.resolve();const io=async e=>{const t=so;let r=()=>{};so=new Promise(e=>{r=e}),await t;try{return await e()}finally{r()}},ao=(e,t)=>`zerogpu_cache_persist_failed:${e}@${t||"1"}`,lo=new Map,co=new Set,mo=(e,t)=>{const r=ao(e,t);lo.delete(r);try{window.localStorage.removeItem(r)}catch{}},uo=(e,t)=>((e,t)=>{const r=ao(e,t);let o=lo.get(r)??null;try{const e=window.localStorage.getItem(r);e&&(o=JSON.parse(e))}catch{}return o&&"number"==typeof o.failures?Date.now()-(o.lastFailureAt??0)>6048e5?(mo(e,t),null):o:null})(e,t)?.failures??0,fo=(e,t)=>uo(e,t)>0,po=(e,t,r,o,n)=>{const s=`${e}:${t}@${r}`;co.has(s)||(co.add(s),Te().report("model.cache_invalid",{code:"persist"===e?"cache_persist_failed":"cache_read_failed",message:m(o),modelId:t,modelVersion:r,data:{phase:e,errorName:go(o),...n}}))},go=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},ho=async(e,t)=>{try{return await Vr(e,t)}catch(r){return k().warn("[Cache] Model cache read failed; treating as a cache miss",{modelId:e,modelVersion:t,error:m(r)}),po("read",e,t,r,{}),null}},yo=async(e,t,r,o)=>{const n=k(),s=uo(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 Er("readwrite",async r=>{const s={key:qr(e,t),metadata:n,files:o};r.put(s)})})(e,t,r,o),s>0&&mo(e,t),"persisted"}catch(o){const i=s+1;return((e,t,r)=>{const o=ao(e,t);lo.set(o,r);try{window.localStorage.setItem(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)}),po("persist",e,t,o,{attempt:i,retryOnNextStart:i<2,sizeBytes:r.sizeBytes}),"failed"}},wo="zerogpu_cached_models",ko="zerogpu_cached_model_id",bo=e=>{try{return window.localStorage.getItem(e)}catch{return null}},Io=e=>{try{window.localStorage.removeItem(e)}catch{}},vo=e=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.modelId&&e.modelId.length>0,_o=()=>{const e=bo(wo);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(vo):[]}catch{return[]}},Mo=e=>{0===e.length?Io(wo):((e,t)=>{try{window.localStorage.setItem(e,t)}catch{}})(wo,JSON.stringify(e))},xo=(e,t)=>(t.lastUsedAt??0)-(e.lastUsedAt??0),So=()=>_o().sort(xo),To=(e,t=Date.now())=>{const r=_o().filter(t=>t.modelId!==e.modelId);Mo([{...e,lastUsedAt:t},...r])},Ao=e=>{const t=_o(),r=t.find(t=>t.modelId===e)??null;return r&&Mo(t.filter(t=>t.modelId!==e)),Io(e),bo(ko)===e&&Io(ko),r},$o=async(e,t,r)=>{try{if(Oe().disableGuardrails)return null;const o=je(),n=ze(e.sizeBytes);if(n>0){const s=Oe().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 Re.frameworkMultipliers[t]??2})(e.inferenceFramework),a=n*i,d="number"==typeof r?.memoryGb&&r.memoryGb>0?r.memoryGb:o.unknownMemoryGb,l=o.memoryBudgetFraction*d*1073741824,c=o.maxMemoryBudgetMb>0?1024*o.maxMemoryBudgetMb*1024:1/0,m=Math.min(l,c);if(a>m)return{code:"model_too_large_for_memory",message:`estimated runtime ${Math.round(a)} B > budget ${Math.round(m)} B (fraction=${o.memoryBudgetFraction}, maxBudgetMb=${o.maxMemoryBudgetMb||"none"}, multiplier=${i}, memoryGb=${d})`};const u=globalThis.performance,f=u?.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&&(!!S()||(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 Po={};const Uo=e=>{if("string"!=typeof e)return;return e.trim()||void 0},Co=()=>{const e={};Po.appId&&(e.app_id=Po.appId),Po.appName&&(e.app_name=Po.appName);const t=Po.externalAppId??(()=>{try{return"undefined"!=typeof chrome?Uo(chrome?.runtime?.id):void 0}catch{return}})();return t&&(e.external_app_id=t),e},Eo="__ZGPU_WORKER_SOURCE__",qo=["__ZGPU_WORKER","SOURCE__"].join("_"),Vo=()=>Eo!==qo?Eo:null;class Ro extends Error{constructor(e,t){super(t?`${e}:${t}`:e),this.name="InferenceWorkerError",this.code=e}}class Bo{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 Ro("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 Ro("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 Ro("worker_boot_timeout",`${n}ms`)),n);e.onerror=e=>{const t="string"==typeof e?.message?e.message:void 0;this.booted?this.crash(new Ro("worker_crashed",t)):s(new Ro("worker_boot_failed",t))},e.onmessageerror=()=>{this.booted||s(new Ro("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 Ro("worker_protocol_mismatch",String(t.protocol))):void this.request({type:"init",config:this.options.bootConfig()}).then(i,e=>s(new Ro("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 Ro("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 Ro("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 Lo="zerogpu-inference",Oo={worker:!0};let jo={...Oo},zo=null,No=!1,Fo=null;const Wo=e=>{jo={...Oo,...e??{}}},Ko=()=>jo.workerUrl??Or().workerUrl,Do=()=>{const e=Ko();if(e)return new Worker(e,{type:"module",name:Lo});const t=Vo();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:Lo})}finally{URL.revokeObjectURL(r)}},Go=()=>{const e=Or(),t=e.pageOrigin??("undefined"!=typeof location&&location?location.origin:void 0);return{protocol:1,logging:{enabled:k().isEnabled()},runtime:{...e,pageOrigin:t}}},Jo=(e,t,r)=>{zo||(zo={code:e,message:t});const o=Fo;Fo=null,o?.terminate(),k().warn("[Worker] Inference worker unavailable; models run on the main thread",{code:e,message:t}),r&&!No&&(No=!0,Te().report("guardrail.pressure_warning",{code:"inference_worker_unavailable",message:`${e}:${t}`.slice(0,256),data:{reason:e,fallback:"main_thread"}}))},Ho=(e,t)=>async(r,o,n,s)=>{if(!jo.worker||zo)return t(r,o,n,s);const i="function"!=typeof globalThis.Worker?{code:"worker_api_unavailable",message:"Worker is not defined",report:!0}:Ko()||Vo()?null:{code:"worker_source_unavailable",message:"no worker script in this build",report:!1};if(i)return Jo(i.code,i.message,i.report),t(r,o,n,s);const a=(Fo||(Fo=new Bo({spawn:Do,bootConfig:Go,onCrash:(e,t)=>{for(const e of t)F(e,void 0);Jo(e.code,e.message,!0)}})),Fo);try{const{executor:t,downloadedFiles:i}=await a.load(e,r,o,s?.wasm??je().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 Ro||e instanceof Error&&"transformers_runtime_load_failed"===e.code)(e))throw e;return Jo((e=>{if(e instanceof Ro)return e.code;const t=e?.code;return"string"==typeof t?t:"worker_error"})(e),m(e),!0),t(r,o,n,s)}},Xo="zerogpu_app_inference_chosen_model",Zo="zerogpu_app_inference_unfit_models",Qo=new Map,Yo=e=>{try{const t=window.localStorage.getItem(e);if(null!==t)return t}catch{}return Qo.get(e)??null},en=(e,t)=>{Qo.set(e,t);try{window.localStorage.setItem(e,t)}catch{}},tn=e=>{Qo.delete(e);try{window.localStorage.removeItem(e)}catch{}},rn=()=>{const e=Yo(Xo)?.trim();return e||null},on=()=>{tn(Xo)},nn=()=>{const e=Yo(Zo);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[]}},sn=e=>{const t=[...e].sort((e,t)=>e.at-t.at).slice(-16);0===t.length?tn(Zo):en(Zo,JSON.stringify(t))},an=e=>(e=>nn().filter(t=>t.sdkVersion===e))(e).map(e=>({modelId:e.modelId,modelVersion:e.modelVersion,reason:e.reason}));class dn extends Error{constructor(e,t,r){super(t),this.name="ZeroGpuError",this.code=e,void 0!==r&&(this.cause=r)}}class ln extends dn{constructor(e,t){super(`not_contributing_${e}`,`not contributing: ${e}${t?` (${t})`:""}`),this.name="NotContributingError",this.state=e,t&&(this.registryReason=t)}}class cn extends dn{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 dn{constructor(e,t){super("inference_failed",e,t),this.name="LocalInferenceFailedError"}}const un=e=>{if(e instanceof ln)return{code:e.code,message:e.message,name:e.name,state:e.state,...e.registryReason?{registryReason:e.registryReason}:{}};if(e instanceof cn)return{code:e.code,message:e.message,name:e.name,modelId:e.modelId,reason:e.reason};if(e instanceof dn)return{code:e.code,message:e.message,name:e.name};const t=e instanceof Error?e.message:String(e);return{code:"string"==typeof e?.code?e.code:"error",message:t,name:e instanceof Error?e.name:"Error"}},fn="[App]";let pn=null,gn=!1,hn=null,yn=null;const wn=()=>{const e=Q(),t=e?.modelInfo?.modelId;return t&&W(t)?t:null},kn=()=>{if(Ze()||Je()||!te())return"stopped";if(gn)return"switching";if("degraded"===He())return"degraded";const e=N.phase??"idle";if("declined"===e)return"declined";if("preparing"===e)return"preparing";if("running"===e){const e=Q();if(H()?.isActive()&&"error"!==e?.status&&wn())return J()?"contributing":"preparing"}return"registering"},bn=async()=>{const e=te(),t=Q();if(!e?.edgeOperatorKey||!t)throw new ln("stopped");const r=await(async e=>({...e,battery:await P()??e.battery,connection:U()??e.connection}))(t.deviceInfo),o={deviceId:t.deviceId,sdkVersion:t.config.sdkVersion,cachedModels:So().map(e=>({modelId:e.modelId,modelVersion:e.modelVersion||"1"})),device:r,unfitModels:an(t.config.sdkVersion),...Kt()};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 d=await fetch(s,{method:"POST",headers:i,body:JSON.stringify(t)}),l=await V(d),c=R(l);if(!d.ok&&!c){const e="string"==typeof l?l:JSON.stringify(l??"");throw o.warn("Eligible models request failed",{status:d.status,message:e.slice(0,200)}),new L(d.status,e)}const m=l&&"object"==typeof l?l:{},u=Array.isArray(m.models)?m.models:[];return o.info("Eligible models received",{lines:u.length,eligible:u.filter(e=>!0===e?.eligible).length,refusalReason:c??void 0}),{deviceId:"string"==typeof m.deviceId?m.deviceId:t.deviceId,edgeSdkType:"string"==typeof m.edgeSdkType?m.edgeSdkType:"unknown",guardMode:"string"==typeof m.guardMode?m.guardMode:void 0,models:u,...c?{refusalReason:c}:{}}})(t.config,o,{edgeOperatorKey:e.edgeOperatorKey})}catch(e){throw new dn((e=>{if(e instanceof L)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 ln("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,So(),wn());return hn=s,k().info(`${fn} Eligible models`,{lines:s.length,eligible:s.filter(e=>e.eligible).length}),s},In=(e,t)=>{rn()===e&&on(),pn?.modelId===e&&(pn.refusalReason=t),k().info(`${fn} Chosen model not kept`,{modelId:e,reason:t}),Ye("modelChoiceRefused",{modelId:e,reason:t})},vn=e=>{gn=!1;const t=pn;t&&(pn=null,t.reject(e))};let _n=0,Mn=!1;const xn=()=>{const e=(N.registrationSettings??null)?.device_timeout_interval_seconds;return"number"==typeof e&&Number.isFinite(e)&&e>0?e:600},Sn=(e,t)=>{const r=k();if(ft())return void r.info("[WS] Re-registration already scheduled; skipping",{reason:t});if(Ze())return void r.debug("[WS] SDK is shut down; not scheduling re-registration");const o=Ar();let n,s;if(o.served)if("socket_closed"===t){s=xr;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),xr+=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*xn();Te().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&&Y("registering"),pt(()=>{H()?.isActive()?r.info("[WS] Active WebSocket present; skipping re-registration"):(r.info("[WS] Re-registration timer fired; restarting lifecycle"),Tn(e,t))},n)},Tn=(e,t)=>{const r=k();r.info("[Lifecycle] Running",{reason:t}),$n(e).catch(o=>{r.error("[Lifecycle] Attempt failed; will retry",{reason:t,error:m(o)}),vn(new dn(Vn(o),`switch failed: ${m(o)}`,o)),Sn(e,"socket_closed")})};ht=e=>{const t=Q()?.lifecycleOptions;t&&Tn(t,e)};const An=(e,t)=>{const r=k();if(Ze())return void r.debug("[WS] SDK is shut down; ignoring re-register trigger");r.info("[WS] Running full re-register",{reason:t});const o=H();G(void 0);try{o?.close(1e3,t)}catch{}Tn(e,t)},$n=async e=>{const{config:t,appUserId:r,edgeOperatorKey:o,deviceId:n}=e;w(t.telemetry);const s=k();if(Ze())return void s.warn("[Init] SDK is shut down; refusing to start lifecycle");Xe("starting"),(e=>{N.config=e})(t),Wo(t.inference),gt();const i={config:t,appUserId:r,edgeOperatorKey:o,deviceId:n};if((e=>{N.lifecycleOptions=e})(i),Y("registering"),(e=>{if(!Mn&&"undefined"!=typeof window&&"function"==typeof window.addEventListener){Mn=!0;try{window.addEventListener("online",()=>{Ze()||H()?.isActive()||!ft()||(k().info("[WS] Network is back; re-registering now"),gt(),Tn(e,"online"))})}catch{}}})(i),!o)throw new Error("Missing required header: x-edge-operator-key");const a=((e=Date.now())=>{const t=ot(),{crash:r,modelCrashes:o,blocklist:n}=at(t,e),s={modelCrashes:o,blocklist:n,lastShutdown:t?.lastShutdown};if(t?.cooldownUntil&&t.cooldownUntil>e)return nt({...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 nt({attempts:1,windowStart:e,...s}),{allowed:!0,attempts:1,crash:r};const i=t.attempts+1;return i>=3?(nt({attempts:i,windowStart:t.windowStart,cooldownUntil:e+tt,...s}),{allowed:!1,cooldownRemainingMs:tt,attempts:i,crash:r}):(nt({attempts:i,windowStart:t.windowStart,...s}),{allowed:!0,attempts:i,crash:r})})();if(!a.allowed){X("error"),Xe("error"),s.warn("Init skipped: crash-loop guard active",{attempts:a.attempts,cooldownRemainingMs:a.cooldownRemainingMs}),Te().report("sdk.init_failed",{code:"crash_loop"}),vn(new ln("stopped"));const e=Math.max(1e3,(a.cooldownRemainingMs??0)+1e3);return void pt(()=>Tn(i,"crash_loop_cooldown"),e)}const d=performance.now(),l=n?null:I(),c=!n&&!l,m=n??l??M();n&&(e=>{v(e)})(n),s.info("[Init] Starting lifecycle",{sdkVersion:t.sdkVersion,deviceId:m,isFreshDevice:c,providedDeviceId:Boolean(n),orchestrator:t.orchestrator?.baseUrl});const u=await(async(e,t,r)=>{const o=window.screen||{width:null,height:null},n=S(),s=E(),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??M(),platform:T(),deviceType:A(),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:x().deviceMemory,gpuRenderer:$(),webglFingerprint:$(),screen:{width:o?.width??null,height:o?.height??null,pixelRatio:window.devicePixelRatio??null},battery:await P(),connection:U(),pageUrl:window.location?.href,referrer:document.referrer,location:e.locationData?await C():void 0}})(t.telemetry,r,m);((e,t)=>{N.deviceId=e,N.deviceInfo=t})(m,u),(e=>{xe&&xe.matches(e.deviceId,e.enabled)||(xe?.flush(),xe?.dispose(),xe=new Me(e))})({enabled:t.telemetry.events,endpointUrl:`${t.orchestrator.baseUrl}${t.orchestrator.eventsPath}`,operatorKey:o,deviceId:m,sdkVersion:t.sdkVersion,platform:u.platform});const f=Te();f.report("sdk.init_started",{data:{sdkVersion:t.sdkVersion}}),Ln(a.crash),s.info("[Init] Device info collected",{platform:u.platform,deviceType:u.deviceType,gpuRenderer:u.gpuRenderer});const p=(e,t)=>{s.info(`[Flow] ${e}`,t??{})};(()=>{const e=bo(ko);if(!e)return;const t=bo(e);if(t){try{const e=JSON.parse(t);vo(e)&&!_o().some(t=>t.modelId===e.modelId)&&To(e,Date.now()-1)}catch{}Io(e)}Io(ko)})(),await Gn(p);const g=c?[]:await qn(p);c?p("Fresh device detected; skip cache checks"):p("Cache verified",{cachedModels:g.map(e=>e.modelId)}),D(g[0]?.modelId??null);const h=rn(),y=an(t.sdkVersion),b={deviceId:m,sdkVersion:t.sdkVersion,cachedModels:g,device:u,...Kt(),...Co(),...y.length>0?{unfitModels:y}:{},...h?{requestedModelId:h}:{}};let _,L=[];const O={},z={},K={};s.info("[Register] Sending register request",{deviceId:m,cachedModels:b.cachedModels.map(e=>e.modelId),unfitModels:y.map(e=>e.modelId),requestedModelId:h??void 0,sdkVersion:t.sdkVersion}),f.report("register.started");const J=performance.now();try{_=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 d=await fetch(s,{method:"POST",headers:i,body:JSON.stringify(t)});o.info("Register request sent",{url:s,status:d.status,bodyBytes:JSON.stringify(t).length});const l=await V(d),c=R(l);if(!d.ok&&!c){const e="string"==typeof l?l:JSON.stringify(l??"");throw o.error("Register request failed",{status:d.status,message:e}),new q(d.status,e)}if(l&&"object"==typeof l&&!c){const e=l;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=l&&"object"==typeof l?l:{},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:B(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 q(d.status,"Register response body is not valid JSON")})(t,b,{edgeOperatorKey:o})}catch(e){if(e instanceof q&&(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"}),dt(),vn(new dn(`http_${e.status}`,"register refused the operator key",e)),void("retry_slow"===Ar().reregister.onAuthFailure?(s.warn("Register auth failed; policy says retry_slow"),Sn(i,"auth_failure")):(s.warn("Register auth failed, stopping lifecycle"),Y("idle")));throw f.report("register.failed",{code:Vn(e),message:e.message}),f.report("sdk.init_failed",{code:Vn(e)}),dt(),e}const Z=(e=>{if(!e||"object"!=typeof e)return null;for(const t of Object.values(e))if(t&&"object"==typeof t)return t;return null})(_.configSettings);var ee;ee=Z,N.registrationSettings=ee??null,(e=>{Re=Le(e?.guardrails??null)})(Z);const te=Tr(Z?.connection,"register");te.changed.length>0&&s.info("[Register] Connection policy applied",{source:te.source,changed:te.changed}),Z&&s.info("[Register] Registration settings received",{keys:Object.keys(Z)});const re=_.requestedModel;if(re&&!re.granted&&In(re.modelId,re.reason??_.refusalReason??"refused"),_.refusalReason)return f.report("register.rejected",{code:_.refusalReason}),s.warn("[Register] Registration refused by server",{reason:_.refusalReason}),X("error"),Xe("error"),Y("declined",_.refusalReason),dt(),vn(new ln("declined",_.refusalReason)),void Sn(i,"refusal");if(f.report("register.succeeded",{durationMs:Math.round(performance.now()-J)}),((e=Date.now())=>{Sr=e})(),f.setSessionKey(_.sessionKey),s.info("Register response received",{deviceId:_.deviceId,wsUrl:_.wsUrl}),!_.wsUrl)return dt(),Y("idle"),void vn(new dn("no_session","register opened no session"));L=On(_.slmConfig);const oe=L[0];oe&&f.report("model.assigned",{modelId:oe.modelId,modelVersion:oe.modelVersion,bytes:oe.sizeBytes}),s.info("[Register] Models assigned",{count:L.length,models:L.map(e=>e.modelId),totalBytes:L.reduce((e,t)=>e+(t.sizeBytes??0),0)});for(const e of L)K[zn(e)]="idle",z[e.modelId]=e;if(!oe)return dt(),Y("idle"),void vn(new dn("no_model","the registry assigned no model"));var ne,se,ie,ae;ne=_.sessionKey,N.sessionKey=ne,se=z,N.modelInfosByModelId=se??{},ie=oe,N.modelInfo=ie,N.taskType=ie?.taskType,N.modelInfosByModelId||(N.modelInfosByModelId={}),ie?.modelId&&(N.modelInfosByModelId[ie.modelId]=ie),ae=oe.sample,N.sample=ae,s.info("Runtime globals updated from register response",{taskType:oe.taskType,hasSample:Boolean(oe.sample)}),Y("preparing");const de=oe.modelVersion??"1",le=W(oe.modelId),ce=le&&le.config.modelVersion===de?le:void 0;for(const[e,t]of Object.entries(Q()?.adaptersByModelId??{}))if(e!==oe.modelId||!ce){try{await(t.dispose?.())}catch{}F(e,void 0)}let me=ce;if(ce)p("Model still loaded; reusing it",{modelId:oe.modelId}),O[oe.modelId]=ce,Cn(oe);else{const e=g.some(e=>e.modelId===oe.modelId&&e.modelVersion===de);p(e?"Loading the assigned model from the cache":"Loading the assigned model",{modelId:oe.modelId,cached:e});const r=await Un(oe);if("unfit"===r.kind)return Pn(i,oe,r.reason);if("transient"===r.kind)throw X("error"),await Jn({wsUrl:_.wsUrl,hello:{type:"hello",deviceId:_.deviceId,sessionKey:_.sessionKey,sdkVersion:t.sdkVersion,slmConfig:L.map(e=>({modelId:e.modelId,modelVersion:e.modelVersion??"1",status:e.modelId===oe.modelId?"error":K[zn(e)]||"idle"}))},ack:{type:"hello_ack",deviceId:_.deviceId,sdkVersion:t.sdkVersion,sessionKey:_.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}),ct(),s.error("Primary model failed to load; aborting lifecycle before WebSocket connect",{modelId:oe.modelId,modelVersion:oe.modelVersion,taskType:oe.taskType,reason:r.reason}),new Error(`primary_model_load_failed:${r.reason}`);if(me=r.adapter,O[oe.modelId]=me,F(oe.modelId,me),oe.sample?.text){s.info("[Sample] Running post-register sample inference",{taskType:oe.taskType}),lt("sampling",oe.modelId,oe.modelVersion);const e=await me.runSample(oe.sample),t={taskType:oe.taskType,ok:e.ok,error:e.error,errorMessage:e.errorMessage,processingTimeMs:e.processingTimeMs},r=je().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(me.dispose?.())}catch{}return F(oe.modelId,void 0),Pn(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)}Cn(oe),await En(oe.modelId)}for(const e of L){if(e.modelId===oe.modelId)continue;const t=Nn(e),r=pe(t.inferenceFramework,t.taskType,t.inferenceKind);if(!r){K[zn(e)]="error",s.warn("No adapter factory for secondary model",{modelId:e.modelId,framework:t.inferenceFramework,taskType:t.taskType});continue}const o=await Bn(e);if(o){K[zn(e)]="error",f.report("guardrail.preflight_blocked",{code:o.code,modelId:e.modelId,modelVersion:e.modelVersion,message:o.message});continue}lt("loading",e.modelId,e.modelVersion);const n=await r.load(t);n.adapter?(O[e.modelId]=n.adapter,F(e.modelId,n.adapter)):(K[zn(e)]="error",s.warn("Failed to load secondary model",{modelId:e.modelId,taskType:e.taskType,error:n.error?.message}))}const ue=_.deviceId,fe=L.map(e=>({modelId:e.modelId,modelVersion:e.modelVersion??"1",status:K[zn(e)]||"idle"})),ge={type:"hello",deviceId:ue,sessionKey:_.sessionKey,sdkVersion:t.sdkVersion,slmConfig:fe};s.info("[WS] Connecting WebSocket",{wsUrl:_.wsUrl,models:fe.map(e=>`${e.modelId}:${e.status}`)}),f.report("ws.connect_started");const he=Ar();let ye=null;const we=()=>{null!==ye&&(clearTimeout(ye),ye=null),(e=>{gn=!1;const t=pn;if(!t)return;pn=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)},ke=new j({url:_.wsUrl,hello:ge,pingIntervalSeconds:he.served?he.keepAlive.pingIntervalSeconds:0,onPingTick:()=>{Ze()||H()!==ke||((e=Date.now())=>Mr.served&&null!==Sr&&e-Sr>1e3*Mr.reregister.maxStalenessSeconds)()&&(s.warn("[WS] Registration exceeded max_staleness; refreshing"),An(i,"max_staleness"))},onOpen:()=>f.report("ws.connected"),onMessage:e=>{if("requests"in e&&Array.isArray(e.requests))er(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}),X("error"===r.status?"error":"idle"),H()===ke&&(t=!0,N.sessionAcked=t,we())}else if("type"in e&&"policy_update"===e.type){const t=e,r=Tr(t.connection,"ws");H()===ke&&ke.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(Ze()||H()!==ke)return;const r=((e,t=Math.random)=>{const r=kr(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}),pt(()=>{An(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=H()===ke;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}}),X("error"),Sn(i,"socket_closed"))},onError:()=>{s.error("[WS] Connection error"),f.report("ws.error"),H()===ke&&X("error")}});var be;G(ke),X("idle"),lt("running",oe.modelId,oe.modelVersion),Xe("running"),Y("running"),St(),f.report("sdk.init_succeeded",{durationMs:Math.round(performance.now()-d)}),s.info("[Init] SDK ready",{deviceId:m,primaryModelId:oe.modelId,taskType:oe.taskType}),xr=0,dt(),_n=0,be=oe.modelId,yn!==be&&(yn=be,Ye("activeModelChanged",{modelId:be})),null!==pn&&(ye=setTimeout(we,15e3))},Pn=async(e,t,r)=>{const o=k(),n=Te(),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 Rr(t.modelId,s).catch(()=>{}),Ao(t.modelId),await Kn(t.modelUrl).catch(()=>{}),((e,t,r,o,n=Date.now())=>{const s=nn().filter(t=>t.modelId!==e);sn([...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}),rn()===t.modelId&&In(t.modelId,r),ct(),dt(),F(t.modelId,void 0),D(So()[0]?.modelId??null),_n<4)return _n+=1,Y("registering"),$n(e);o.warn("[Model] Too many unfit models in a row; retrying on the slow cadence",{attempts:_n}),X("error"),Xe("error"),vn(new dn("unfit_models_exhausted","every assigned model failed on this device")),Sn(e,"refusal")},Un=async e=>{const t=k(),r=Te(),o=Nn(e),n=pe(o.inferenceFramework,o.taskType,o.inferenceKind),s=await Bn(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}),"low_battery"===s.code?{kind:"transient",reason:`preflight_blocked:${s.code}`}:{kind:"unfit",reason:`preflight:${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}),lt("loading",e.modelId,e.modelVersion);const i=performance.now(),a=await n.load(o),d=Math.round(performance.now()-i);if(a.adapter)return r.report("model.load_succeeded",{modelId:e.modelId,modelVersion:e.modelVersion,durationMs:d,bytes:a.metrics?.sizeBytes}),t.info("[Model] Primary model loaded",{modelId:e.modelId,ms:d,sizeBytes:a.metrics?.sizeBytes}),{kind:"adapter",adapter:a.adapter};const l=a.error?.message??"init_error";return r.report("model.load_failed",{code:Rn(l),modelId:e.modelId,modelVersion:e.modelVersion,durationMs:d,message:l}),t.error("[Model] Primary model load failed",{modelId:e.modelId,framework:o.inferenceFramework,taskType:o.taskType,ms:d,error:l}),(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))(l)?{kind:"transient",reason:l}:{kind:"unfit",reason:`load_failed:${Rn(l)}:${l.slice(0,48)}`}},Cn=e=>{const t=e.modelVersion??"1",r=(e=>{const t=_o().find(t=>t.modelId===e);if(t)return t;const r=bo(e);if(!r)return null;try{const e=JSON.parse(r);return vo(e)?e:null}catch{return null}})(e.modelId);r&&(r.modelVersion||"1")!==t&&(Rr(e.modelId,r.modelVersion||"1").catch(()=>{}),Te().report("model.evicted",{code:"version_changed",modelId:e.modelId,modelVersion:r.modelVersion})),To({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}),D(e.modelId)},En=async e=>{const t=je().maxCachedModels,r=((e,t)=>{if(!Number.isFinite(e)||e<=0)return[];const r=So(),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){Mo(r);for(const e of o)Io(e.modelId)}return o})(t,e);for(const e of r){await Rr(e.modelId,e.modelVersion||"1").catch(()=>{}),await Kn(e.modelUrl).catch(()=>{});const r=W(e.modelId);if(r){try{await(r.dispose?.())}catch{}F(e.modelId,void 0)}Te().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})}},qn=async e=>{const t=Te(),r=[];for(const o of So()){const n=o.modelVersion||"1";if(mt(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(fo(o.modelId,n)){e("Cached model was never persisted (browser storage refused); not claimed",{modelId:o.modelId,failures:uo(o.modelId,n)});continue}const s=Boolean(o.modelUrl&&o.taskType&&Array.isArray(o.requiredFiles)&&o.sample?.text),i=s?await Fn(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 Rr(o.modelId,n).catch(()=>{}),Ao(o.modelId),t.report("model.cache_purged",{modelId:o.modelId,modelVersion:n}))}return r},Vn=e=>{if(e instanceof q)return`http_${e.status}`;return/timeout/i.test(e?.message??"")?"timeout":"network"},Rn=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",Bn=async e=>{if(mt(e.modelId,e.modelVersion))return{code:"model_blocklisted",message:"blocklisted after repeated crashes during load"};let t;try{t=Z().deviceInfo}catch{t=void 0}return $o({modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:e.sizeBytes,inferenceFramework:e.inferenceFramework},"download",t)},Ln=e=>{if(!e)return;const t=Te();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})},On=e=>{if(!Array.isArray(e))return[];const t=[];for(const r of e){if(!r?.modelId||!r?.modelVersion||!r?.modelUrl)continue;const e=jn(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},jn=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},zn=e=>`${e.modelId}@${e.modelVersion??"1"}`,Nn=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}),Fn=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=Wn(e.requiredFiles);if(!t.length)return{ok:!1,missing:["<no required files>"],stored:0};try{const r=await Vr(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}}},Wn=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),Kn=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(Nr));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)}},Dn="zerogpu_transformers_cache_purged",Gn=async e=>{if("undefined"!=typeof caches){try{if(window.localStorage.getItem(Dn))return}catch{}try{const t=(await caches.keys()).filter(e=>e.includes(Nr));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(Dn,(new Date).toISOString())}catch{}}catch{}}},Jn=async e=>{await new Promise(t=>{let r=!1;const o=()=>{r||(r=!0,t())},n=window.setTimeout(o,1500);try{new j({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 Hn{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 Xn=async(e,t,r)=>{const o=k(),n=performance.now(),s={};try{const o=await ho(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},d=o?{downloadMs:o.metadata.downloadMs,loadModelMs:o.metadata.loadModelMs,sizeBytes:o.metadata.sizeBytes}:{},l=await r.loadExecutor(e,i,a),c={...d,loadModelMs:l.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 yo(e.modelId,e.modelVersion,{modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:r,downloadMs:o?0:a,loadModelMs:l.loadModelMs},t),c.sizeBytes=r,o||(c.downloadMs=a)}return{adapter:new Hn(e,r.capability(e),l,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 Rr(e.modelId,e.modelVersion).catch(()=>{}),{error:t,metrics:{}}}},Zn=async e=>{const t=performance.now();return{result:await e(),ms:Math.round(performance.now()-t)}},Qn={},Yn=(e,t,r,o,n,s)=>{const i=n.map(e=>Hr(e.trim())).filter(e=>e.length>0),a=new Set(i),d=k(),l=(()=>{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 Hr(e)}if(!l)return null;const n=l.pathname.replace(/\/$/,"");if(!t.startsWith(`${n}/`))return null;const s=t.slice(n.length+1);return Hr(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 d.error("[SLM][fetch] non-model wasm/ort request failed",{modelId:e,requestUrl:c,error:m(t)}),t}}const f=(e=>{const t=Hr(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 d.warn("[SLM] Unexpected model file request; falling back to original fetch",{file:u,modelId:e}),s(n,i);const p=(e=>{const r=Hr(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=Hr(f),h=Xr(e,g);let y=Qn[h]||r[h]||Qn[g]||r[g]||r[`onnx/${g}`]||Qn[`onnx/${g}`];if(!y&&g.startsWith("onnx/")){const t=g.replace("onnx/","");y=r[t]||Qn[t]||r[Xr(e,t)]||Qn[Xr(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 Qn[h]=e,o&&o(h,e),new Response(e)}}return new Response("required_file_not_found",{status:404,statusText:"Not Found"})}catch(t){return d.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"})}}},es="zgScoreRecorder",ts=e=>({[es]:e}),rs=(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)},os=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?.[es];if(s)for(const e of o)e[es]=s;return o},t.runBeam=async e=>{const r=await o.call(t,e),n=e[es];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:rs(t.data,r,o)}})(n,r.logits),r},t.updateBeam=(e,r)=>{const o=n.call(t,e,r),s=e[es];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)},ns=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)},ss=(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),is=e=>"number"==typeof e&&Number.isFinite(e)&&e>0&&e<1e6?Math.floor(e):void 0,as=e=>{const t=new BigInt64Array(e.length);return e.forEach((e,r)=>{t[r]=BigInt(e)}),t},ds=(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=[is(e.max_position_embeddings),is(e.n_positions),is(t.model_max_length)].filter(e=>void 0!==e);return r.length>0?Math.min(...r):512})(o,t),a=t.encode(""),d=a.length>0?a[a.length-1]:void 0,l=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),m=((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,d),u=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",as(t),r);else if("attention_mask"===s)o[s]=new e.Tensor("int64",as(t.map(()=>1)),r);else{if("token_type_ids"!==s)throw new Error(`sequence_classification_unsupported_input:${s}`);o[s]=new e.Tensor("int64",as(t.map(()=>0)),r)}return o})(m)),f=u[l];if(!f||!f.data||0===f.data.length)throw new Error("sequence_classification_empty_logits");const p=ss(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}}},ls={summary:"summarization",iab_classify:"text-classification",classification:"zero-shot-classification",text_generation:"text2text-generation"},cs=new Set([re,oe,ne,ie,ae,de,le]),ms={[oe]:"text2text-generation",[ne]:"zero-shot-classification",[ie]:"token-classification",[ae]:"question-answering",[de]:"feature-extraction",[le]:"fill-mask"},us=e=>{const t=ce(e.inferenceKind);return t&&cs.has(t)?t:"task"},fs=8192,ps=/\[MASK\]|<mask>/g,gs=e=>"number"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,hs=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("input_text_required");return e},ys=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""},ws=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]},ks=(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}},Is=(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,d="number"==typeof e?.index?e.index:i+1,l=r.startsWith("##")&&d===i+1,c=l?r.slice(2):r;if(i=d,o.push({token:r,label:t,score:Number(n.toFixed(6))}),l&&s){s.pieces[s.pieces.length-1]+=c,s.scores.push(n);continue}const{prefix:m,label:u}=bs(t);"O"!==t&&c?s&&"B"!==m&&s.label===u?(s.pieces.push(c),s.scores.push(n)):(a(),s={label:u,pieces:[c],scores:[n]}):a()}return a(),{entities:n,tokens:o}},vs=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):[]},_s=async(e,t,r)=>{const{pipeline:o,pipelineTask:n}=e,{result:s,ms:i}=await Zn(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}},Ms=async(e,t,r)=>{try{return await _s(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 _s(e,n,r)}};class xs{constructor(e,t){this.config=e,this.state=t,this.loadModelMs=t.loadModelMs}async runInference(e){const t=us(this.config);if(t===re)return this.runSequenceClassification(e);if(t===oe)return this.runSeq2Seq(e);if(t===ne)return this.runZeroShot(e,!0);if(t===ie)return this.runTokenClassification(e);if(t===ae)return this.runQuestionAnswering(e);if(t===de)return this.runTextEmbedding(e);if(t===le)return this.runFillMask(e);const r=this.config.taskType,o=ks(e.text,"summarize this text");if("classification"===r)return this.runZeroShot(e);if("iab_classify"===r){const{raw:e,ms:t}=await Ms(this.state,o);return{output:e,inferenceMs:t}}if("summary"===r){const{raw:t,ms:r}=await Ms(this.state,o,{maxNewTokens:e.maxNewTokens});return{output:{text:ys(t)},inferenceMs:r}}if("text_generation"===r){const{raw:t,ms:r}=await Ms(this.state,o,{maxNewTokens:e.maxNewTokens});return{output:{text:ys(t)},inferenceMs:r}}const{raw:n,ms:s}=await Ms(this.state,o);return{output:n,inferenceMs:s}}async runZeroShot(e,t=!1){const r=t?hs(e.text).slice(0,fs):ks(e.text,"summarize this text"),o=ws(e.categories)??ws(e.category),{raw:n,ms:s}=await Ms(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=hs(e.text),o=e.topK??e.top_k,{result:n,ms:s}=await Zn(()=>t.classify(r,"number"==typeof o?o:void 0));return{output:n,inferenceMs:s}}async runSeq2Seq(e){const t=hs(e.text).slice(0,8192),r=gs(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 Zn(()=>o(t,{max_new_tokens:r,do_sample:!1,num_beams:1,...s?ts(s):{}})),d=ys(i).trim(),l=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:d,score:l},inferenceMs:a}}async runTokenClassification(e){const t=hs(e.text).slice(0,fs),{result:r,ms:o}=await Zn(()=>this.state.pipeline(t,{ignore_labels:[]}));return{output:Is(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:hs(e.text)).slice(0,fs),o=this.state.pipeline,{result:n,ms:s}=await Zn(()=>o(t,r,{topk:1})),i=Array.isArray(n)?n[0]:n,a="string"==typeof i?.answer?i.answer.trim():"",d="number"==typeof i?.score?i.score:0,l=a?r.indexOf(a):-1;return{output:{answer:a,score:d,start:l,end:l>=0?l+a.length:-1},inferenceMs:s}}async runTextEmbedding(e){const t=hs(e.text).slice(0,fs),{result:r,ms:o}=await Zn(()=>this.state.pipeline(t,{pooling:"mean",normalize:!0}));return{output:{embedding:vs(r)},inferenceMs:o}}async runFillMask(e){const t=this.state.pipeline.tokenizer?.mask_token,r=((e,t)=>!t||e.includes(t)?e:e.replace(ps,t))(hs(e.text).slice(0,fs),"string"==typeof t?t:void 0),o=(e=>gs(e.topK)??gs(e.top_k))(e)??5,{result:n,ms:s}=await Zn(()=>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})),d=i[0];return{output:{predictions:a,text:"string"==typeof d?.sequence?d.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 Ss=async(e,t,r,o)=>{const n=us(e),s=k();try{await Wr()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const i=Kr(Jr(e.modelUrl,e.modelRepoId)),a=(e=>{const t=us(e);return ms[t]??ls[e.taskType]??e.taskType})(e),d=Dr(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!d)throw new Error("[SLM] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const l=await io(async()=>{const l=jr(),c=l.TransformersEnv||{};c.allowRemoteModels=!0,c.allowLocalModels=!0,zr(c),c.backends||(c.backends={}),c.backends.onnx||(c.backends.onnx={}),c.backends.onnx.wasm||(c.backends.onnx.wasm={});const m=s.isEnabled()?"error":"fatal";c?.backends?.onnx?.env&&(c.backends.onnx.env.logLevel=m);const u=Fe(void 0,o?.wasm);c.backends.onnx.wasm.proxy=u.proxy,c.backends.onnx.wasm.numThreads=Or().forceSingleThread?1:u.numThreads;const f=globalThis.fetch.bind(globalThis),p=await no(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=m);const g=globalThis.ort;g?.env&&(g.env.logLevel=m),c.fetch=Yn(e.modelId,i,t,r,(e.requiredFiles??[]).map(e=>e.name),f),l.TransformersEnv=c,globalThis.fetch=c.fetch;const h={device:"wasm",quantized:e.quantized,progress_callback:()=>{}},y=()=>Zn(async()=>{if(n===re){const e=(()=>{const e=jr().TransformersLib;if(!e)throw new Error("transformers_lib_unavailable");return e})(),[t,r]=await Promise.all([e.AutoTokenizer.from_pretrained(d,h),e.PreTrainedModel.from_pretrained(d,h)]);return{classifier:ds(e,t,r)}}const e=l.TransformersPipeline;if(!e)throw new Error("transformers_pipeline_unavailable");return{pipeline:await e(a,d,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:m}=l;if(c.classifier){return{pipeline:()=>Promise.reject(new Error("pipeline_not_loaded")),pipelineTask:n,loadModelMs:m,classifier:c.classifier}}const u=c.pipeline,f={pipeline:u,pipelineTask:a,loadModelMs:m};if(n===oe){const t=u.model;f.defaultMaxNewTokens=gs(t?.generation_config?.max_new_tokens)??48,os(t)?f.scoring={eosTokenIds:ns(t)}:k().warn("[SLM] seq2seq score hooks unavailable; score defaults to 0.5",{modelId:e.modelId})}return f},Ts=async(e,t,r,o)=>{const n=await Ss(e,t,r,o);return new xs(e,n)},As={capabilities:[{inferenceFramework:"ONNX",inferenceKind:re},{inferenceFramework:"ONNX",inferenceKind:oe},{inferenceFramework:"ONNX",inferenceKind:ne},{inferenceFramework:"ONNX",inferenceKind:ie},{inferenceFramework:"ONNX",inferenceKind:ae},{inferenceFramework:"ONNX",inferenceKind:de},{inferenceFramework:"ONNX",inferenceKind:le},{inferenceFramework:"ONNX",taskType:"summary"},{inferenceFramework:"ONNX",taskType:"iab_classify"},{inferenceFramework:"ONNX",taskType:"classification"},{inferenceFramework:"ONNX",taskType:"text_generation"}],load:(e,t)=>((e,t)=>Xn(e,t,{logLabel:"[SLM][loadOnnxAdapter]",capability:e=>({inferenceFramework:"ONNX",taskType:e.taskType,inferenceKind:e.inferenceKind,modelType:e.modelType}),loadExecutor:Ho("ONNX",Ts),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)};ue(As);class $s{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 Zn(async()=>this.state.pipeline(t));var i,a;const d=((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),l=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()))})(d,l);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})(d,l??[]);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 Ps=async(e,t,r)=>{const o=k();try{await Wr()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const n=Kr(Jr(e.modelUrl,e.modelRepoId)),s=Dr(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 io(async()=>{const i=jr(),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 d=globalThis.fetch.bind(globalThis),l=await no(d);l&&(a.backends.onnx.wasm.wasmPaths=l),a.fetch=Yn(e.modelId,n,t,r,(e.requiredFiles??[]).map(e=>e.name),d),i.TransformersEnv=a,globalThis.fetch=a.fetch;try{return await Zn(()=>{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=d}}),{result:a,ms:d}=i;return{pipeline:a,loadModelMs:d}},Us=async(e,t,r)=>{const o=await Ps(e,t,r);return new $s(o)},Cs={capabilities:[{inferenceFramework:"Transformers",taskType:"gliner"},{inferenceFramework:"Transformers",taskType:"gliner2"}],load:(e,t)=>((e,t)=>Xn(e,t,{logLabel:"Transformers adapter load",capability:e=>({inferenceFramework:"Transformers",taskType:e.taskType,modelType:e.modelType}),loadExecutor:Ho("Transformers",Us)}))(e,t)};ue(Cs);const Es="https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js";let qs=null;const Vs=Es.replace(/\/esm\/index\.js$/,"/esm");class Rs{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 Zn(async()=>this.state.wllama.createCompletion(t,{nPredict:r}));return{output:{text:"string"==typeof o?o:Bs(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 Bs=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)}},Ls=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):(qs||(qs=(async()=>{try{const e=await import(Es);if(!e?.Wllama)throw new Error("Wllama runtime missing Wllama export");return window.WllamaModule=e,e}catch(e){throw qs=null,k().error("[GGUF] Failed to import wllama runtime",{runtimeUrl:Es,error:m(e)}),e}})()),qs)),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),d=a?a[1]:i,l=[`${d}/resolve/${a?a[2]:"main"}/${t}`,`${d}/${t}`],c=[];for(const e of l)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":`${Vs}/single-thread/wllama.wasm`,"multi-thread/wllama.wasm":`${Vs}/multi-thread/wllama.wasm`},a=new n.Wllama(i),{ms:d}=await Zn(async()=>{await a.loadModel([s],{n_ctx:e.maxInputTokens&&e.maxInputTokens>0?e.maxInputTokens:2048})});return{wllama:a,loadModelMs:d}},Os={capabilities:[{inferenceFramework:"GGUF",inferenceKind:se},{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 ho(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}:{},d=await Ls(e,s,i),l={...a,loadModelMs:d.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 yo(e.modelId,e.modelVersion,{modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:i,downloadMs:r?0:a,loadModelMs:d.loadModelMs},t),l.sizeBytes=i,r||(l.downloadMs=a)}return{adapter:new Rs(e,d,l),metrics:l}}catch(t){return r.error("GGUF adapter load failed",{modelId:e.modelId,modelVersion:e.modelVersion,modelUrl:e.modelUrl,error:m(t)}),await Rr(e.modelId,e.modelVersion).catch(()=>{}),{error:t,metrics:{}}}})(e,t)};ue(Os);let js=!1;const zs={get status(){return He()},on:Qe,shutdown:()=>vt({reason:"host_stop"}),get contributionState(){return kn()},get activeModelId(){return wn()},get deviceId(){return Q()?.deviceId??null},eligibleModels:bn,switchModel:async e=>{const t="string"==typeof e?e.trim():"";if(!t)throw new dn("invalid_model_id","modelId is blank");if(Ze()||!te())throw new ln("stopped");let r=hn??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 cn(t,"not_offered");if(!o.eligible)throw new cn(t,o.reason??"not_eligible");if((e=>{en(Xo,e.trim())})(t),wn()===t&&"contributing"===kn())return{requestedModelId:t,activeModelId:t,granted:!0};if(Je())throw new ln("stopped");pn?.reject(new dn("switch_superseded","a newer switch replaced this one"));const n=new Promise((e,r)=>{pn={modelId:t,resolve:e,reject:r}});gn=!0,k().info(`${fn} Switching model`,{to:t,from:wn()??void 0}),Qt(!0);try{await(async()=>{await Xt(),Zt()})();const e=H();G(void 0);try{e?.close(1e3,"switching")}catch{}X("error"),gt(),await(async()=>{const e=Q()?.adaptersByModelId??{};for(const t of Object.values(e))try{await(t.dispose?.())}catch{}K({})})()}finally{Qt(!1)}return yt("switch")||vn(new ln("stopped")),n},runLocal:async e=>{const t=kn();if("contributing"!==t)throw new ln(t,"declined"===t?ee()??void 0:void 0);const r=Q(),o=wn(),n=o?W(o):void 0,s=o?r?.modelInfosByModelId?.[o]:void 0;if(!o||!n||!s)throw new ln("preparing");if(!e||"object"!=typeof e)throw new dn("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&&Ne(i)>a)throw new dn("input_too_large",`input of about ${Ne(i)} tokens exceeds the model's cap of ${a}`);const d=Te(),{value:l,queueWaitMs:c}=await(async e=>{Gt+=1;const t=performance.now();try{await Xt();const r=Math.round(performance.now()-t);try{return{value:await e(),queueWaitMs:r}}finally{Zt()}}finally{Gt-=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 d.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&&At(r),new mn(r||"inference failed",e)}});return{response:l.output.output,modelId:o,modelVersion:s.modelVersion??"1",location:"device",runtime:s.inferenceFramework?.trim().toLowerCase()||void 0,queueWaitMs:c,processingMs:"number"==typeof l.output.inferenceMs?l.output.inferenceMs:l.processingMs}},clearModelChoice:()=>on(),forgetUnfitModel:e=>(e=>{const t=nn(),r=t.filter(t=>t.modelId!==e);r.length!==t.length&&sn(r)})(e)},Ns=()=>zs,Fs=async t=>{if(js)return zs;js=!0,t?.resourcePolicy&&((e=>{Ve=e??{},Re=Le(null)})(t.resourcePolicy),t.resourcePolicy.disableGuardrails&&console.warn("[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only."));const s=(t=>{const s=e,i=r(s,t??{});return{sdkVersion:o(i.sdkVersion,s.sdkVersion),orchestrator:{baseUrl:o(i.orchestrator?.baseUrl,s.orchestrator.baseUrl),registerPath:o(i.orchestrator?.registerPath,s.orchestrator.registerPath),eventsPath:o(i.orchestrator?.eventsPath,s.orchestrator.eventsPath)},telemetry:{enableConsoleLogs:n(i.telemetry?.enableConsoleLogs,s.telemetry.enableConsoleLogs),locationData:n(i.telemetry?.locationData,s.telemetry.locationData),events:n(i.telemetry?.events,s.telemetry.events)},inference:{worker:n(i.inference?.worker,s.inference.worker),...o(i.inference?.workerUrl,"")?{workerUrl:o(i.inference?.workerUrl,"")}:{}}}})(t?.overrides);(e=>{Po={appId:Uo(e?.appId),appName:Uo(e?.appName),externalAppId:Uo(e?.externalAppId)}})(t),void 0!==t?.customParams&&(w(s.telemetry),Wt(t.customParams));try{await $n({config:s,appUserId:t?.appUserId,edgeOperatorKey:t?.edgeOperatorKey,deviceId:t?.deviceId})}catch(e){k().error("[Init] SDK initialization failed",{error:m(e)})}return zs},Ws=e=>{Wt(e)},Ks="zerogpu:consent",Ds={optedIn:!0,updatedAt:null,source:"default"},Gs=e=>{if(!e||"object"!=typeof e)return Ds;const t=e;return"boolean"!=typeof t.optedIn?Ds:{optedIn:t.optedIn,updatedAt:"string"==typeof t.updatedAt?t.updatedAt:null,source:"extension"===t.source||"settings-page"===t.source||"default"===t.source?t.source:"default"}},Js=async()=>{const e="undefined"!=typeof chrome?chrome?.storage?.local:void 0;if(!e)return Ds;try{const t=await e.get(Ks);return Gs(t?.[Ks])}catch{return Ds}};Promise.resolve();const Hs=e=>e.endsWith("/")?e:`${e}/`,Xs=e=>{(e=>{const t={...Lr};for(const[r,o]of Object.entries(e))void 0!==o&&(t[r]=o);Lr=t})({transformersUrl:`${e}transformers.min.js`,wasmPaths:e,forceSingleThread:!0,workerUrl:`${e}zerogpu-worker.js`})},Zs=e=>{const t={...e.overrides??{}};return"boolean"==typeof e.enableConsoleLogs&&(t.telemetry={...t.telemetry??{},enableConsoleLogs:e.enableConsoleLogs}),e.orchestratorBaseUrl&&(t.orchestrator={...t.orchestrator??{},baseUrl:e.orchestratorBaseUrl}),"boolean"==typeof e.inferenceWorker&&(t.inference={...t.inference??{},worker:e.inferenceWorker}),t};let Qs=null;const Ys=e=>{Qs||(Qs=(e=>{const t="undefined"!=typeof chrome?chrome?.storage?.onChanged:void 0;if(!t?.addListener)return()=>{};const r=(t,r)=>{if("local"!==r)return;const o=t?.[Ks];o&&e(Gs(o.newValue))};return t.addListener(r),()=>t.removeListener?.(r)})(t=>{t.optedIn&&ei(e)}))},ei=async(e={})=>{if(Ys(e),!(await Js()).optedIn)return;const t=(r=e.assetsBaseUrl)?Hs(r):"undefined"!=typeof chrome&&chrome?.runtime?.getURL?Hs(chrome.runtime.getURL("vendor/zerogpu/")):"vendor/zerogpu/";var r;(e=>{const t="string"==typeof e?e.trim():"";if(Ut=t||null,Ct=null,Ut)try{Ct=new URL(Ut).origin}catch{Ut=null}Et=null})((e=>!1===e?null:"string"==typeof e&&e.trim()?e:"https://zerogpu-browser-sdk.pages.dev/tag-runner.html")(e.trackingRunnerUrl)),e.enableConsoleLogs||(()=>{const e=window;if(e.__zgpuConsoleSilenced)return;e.__zgpuConsoleSilenced=!0;const t=()=>{};console.log=t,console.info=t,console.debug=t,console.warn=t,console.error=t})(),Xs(t);try{await(async e=>{if(window.WllamaModule)return;const t=await import(`${e}wllama/index.js`);if(!t?.Wllama)throw new Error("wllama/index.js is missing the Wllama export");window.WllamaModule=t,window.WllamaWasmPaths={"single-thread/wllama.wasm":`${e}wllama/single-thread/wllama.wasm`,"multi-thread/wllama.wasm":`${e}wllama/multi-thread/wllama.wasm`}})(t)}catch(e){console.warn("[ZeroGPU][offscreen] wllama runtime unavailable; GGUF models will be skipped.",e)}ai(e),await Fs({edgeOperatorKey:e.edgeOperatorKey,appUserId:e.appUserId,deviceId:e.deviceId,customParams:e.customParams,appId:e.appId,appName:e.appName,externalAppId:e.externalAppId,overrides:Zs(e)})},ti={forceInit:"zerogpu:forceInit",getStatus:"zerogpu:getStatus",disable:"zerogpu:disable",setCustomParams:"zerogpu:setCustomParams",getContribution:"zerogpu:getContribution",eligibleModels:"zerogpu:eligibleModels",switchModel:"zerogpu:switchModel",runLocal:"zerogpu:runLocal",clearModelChoice:"zerogpu:clearModelChoice",forgetUnfitModel:"zerogpu:forgetUnfitModel"},ri="zerogpu:event",oi=["activeModelChanged","modelChoiceRefused","degraded","recovered","shutdown"];let ni=!1;const si=(e,t)=>(Promise.resolve().then(t).then(t=>e({ok:!0,result:t}),t=>e({ok:!1,error:un(t)})),!0);let ii=null;const ai=(e={})=>{if(ii)return ii;const t={status:"idle",initialized:!1,lastAttemptAt:null,lastSuccessAt:null,lastErrorAt:null,lastErrorMessage:"",orchestratorBaseUrl:e.orchestratorBaseUrl},r="undefined"!=typeof chrome?chrome?.runtime:void 0;if(!r?.onMessage?.addListener)return console.warn("[ZeroGPU][offscreen] chrome.runtime.onMessage unavailable; messaging not registered."),t;ii=t;return(()=>{if(!ni){ni=!0;for(const e of oi)Qe(e,t=>{try{("undefined"!=typeof chrome?chrome?.runtime:void 0)?.sendMessage?.({type:ri,event:e,detail:t})?.catch?.(()=>{})}catch{}})}})(),r.onMessage.addListener((r,o,n)=>{if(!r||"object"!=typeof r)return;const s=r;if(s.type===ti.getStatus){const e=Ns();return void n({ok:!0,state:{...t,contributionState:e.contributionState,activeModelId:e.activeModelId}})}if(s.type===ti.getContribution){const e=Ns();return void n({ok:!0,result:{contributionState:e.contributionState,activeModelId:e.activeModelId,status:e.status,deviceId:e.deviceId}})}return s.type===ti.eligibleModels?si(n,()=>Ns().eligibleModels()):s.type===ti.switchModel?si(n,()=>Ns().switchModel(String(s.modelId??""))):s.type===ti.runLocal?si(n,()=>Ns().runLocal(s.input&&"object"==typeof s.input?s.input:{})):s.type===ti.clearModelChoice?si(n,()=>(Ns().clearModelChoice(),!0)):s.type===ti.forgetUnfitModel?si(n,()=>(Ns().forgetUnfitModel(String(s.modelId??"")),!0)):s.type===ti.forceInit?((async r=>{t.status="initializing",t.lastAttemptAt=(new Date).toISOString();try{await ei({...e,...r??{}}),t.status="running",t.initialized=!0,t.lastSuccessAt=(new Date).toISOString(),t.lastErrorMessage=""}catch(e){throw t.status="error",t.initialized=!1,t.lastErrorAt=(new Date).toISOString(),t.lastErrorMessage=e instanceof Error?e.message:String(e),e}})(s.config||void 0).then(()=>n({ok:!0,state:t})).catch(e=>n({ok:!1,state:t,error:e instanceof Error?e.message:String(e)})),!0):s.type===ti.setCustomParams?(Ws(s.customParams??{}),void n({ok:!0})):void(s.type===ti.disable&&vt({reason:"host_stop"}))}),t},di=()=>{ii=null,ni=!1};export{ri as ZEROGPU_EVENT_MESSAGE,ti as ZEROGPU_OFFSCREEN_MESSAGES,di as __resetOffscreenMessaging,Ns as getZeroGpuSdk,ei as initZeroGpuOffscreen,ai as registerZeroGpuOffscreenMessaging,Ws as setCustomParams};
|
|
1
|
+
const e={sdkVersion:"0.6.0-dev.202612031336.gae43e53+ae43e53",orchestrator:{baseUrl:"https://devices.herogpu.com",registerPath:"/register",eventsPath:"/events"},telemetry:{enableConsoleLogs:!1,locationData:!1,events:!0},inference:{worker:!0}},t=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),r=(e,o)=>{const n=Array.isArray(e)?[...e]:{...e};for(const e of Object.keys(o)){const s=o[e];if(void 0===s)continue;const i=n[e];t(s)&&t(i)?n[e]=r(i,s):n[e]=s}return n},o=(e,t)=>"string"==typeof e&&e.length>0?e:t,n=(e,t)=>"boolean"==typeof e?e:t,s=200,i=/(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i,a=new Set(["url","wsurl","baseurl","modelurl","modelrepourl","runtimeurl","requesturl","endpoint","endpointurl","manifesturl","bundleurl","orchestrator"]),d=new Set(["message","errormessage","error","reason"]),l=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"]),c=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e,m=e=>{if(e instanceof Error)return c(`${e.name}: ${e.message}`,s);if("string"==typeof e)return c(e,s);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 c(`${t}: ${r}`,s)}return"object"==typeof e?`[${e.constructor?.name??"object"}]`:c(String(e),s)},u=e=>Array.isArray(e)?`[array:${e.length}]`:e&&"object"==typeof e?`[object:${Object.keys(e).length} keys]`:`[${typeof e}]`,f=(e,t)=>{const r=e.toLowerCase();return a.has(r)?(e=>{try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid-url]"}})(t):d.has(r)?c(t,s):l.has(r)?c(t,256):`[string:${t.length}]`},p=(e,t)=>i.test(e)?"[redacted]":null==t||"boolean"==typeof t?t:"number"==typeof t?Number.isFinite(t)?t:String(t):"string"==typeof t?f(e,t):t instanceof Error?m(t):u(t),g=e=>"string"==typeof e?c(e,s):"[invalid log message]";class h{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,g(r),o):void 0===o?t("[herogpu]",g(r)):t("[herogpu]",g(r),(e=>{if(e instanceof Error)return{error:m(e)};if(!e||"object"!=typeof e||Array.isArray(e))return{detail:p("detail",e)};const t={};for(const[r,o]of Object.entries(e))Array.isArray(o)?i.test(r)?t[r]="[redacted]":o.every(e=>null===e||"object"!=typeof e)?t[r]=o.slice(0,20).map(e=>p(r,e)):t[r]=u(o):t[r]=p(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 y=(e,t)=>(w=new h(e,t),w),k=()=>(w||(w=new h({enableConsoleLogs:!1,locationData:!1,events:!0})),w),b=e=>{const t=(e=>`zerogpu_${e}`)(e);try{if(null!==window.localStorage.getItem(t))return t}catch{}return(e=>`herogpu_${e}`)(e)},I="device_id",v=()=>{try{return window.localStorage.getItem(b(I))}catch{return null}},_=e=>{try{window.localStorage.setItem(b(I),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)}),x=()=>{const e=v();if(e)return e;const t=M();return _(t),t},S=()=>navigator,T=()=>{if("undefined"!=typeof window)return window.Telegram?.WebApp},$=()=>{const e=navigator.userAgent.toLowerCase(),t=T();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"},A=()=>{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"},C=()=>{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}},U=async()=>{try{const e=S().getBattery;if(e){const t=await e.call(navigator);return{level:t.level,charging:t.charging}}}catch{}},E=()=>{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}},P=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})})},V=()=>{const e=T(),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 q extends Error{constructor(e,t){super(`Register failed: ${e} ${t??""}`.trim()),this.status=e,this.body=t}}const B=async e=>{try{return await e.clone().json()}catch{return null}},R=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},L=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 j extends Error{constructor(e,t){super(`Eligible models failed: ${e} ${t??""}`.trim()),this.status=e,this.body=t}}const O=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 N{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:O(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=F(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=F(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:O(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 F=e=>"number"==typeof e&&Number.isFinite(e)&&e>0?Math.round(1e3*e):0,z={status:"idle",phase:"idle"},W=(e,t)=>{z.adaptersByModelId||(z.adaptersByModelId={}),t?z.adaptersByModelId[e]=t:delete z.adaptersByModelId[e]},K=e=>z.adaptersByModelId?.[e],D=e=>{z.adaptersByModelId=e??{}},G=e=>{z.cachedModelId=e??null},J=e=>{z.ws=e,z.sessionAcked=!1},H=()=>!0===z.sessionAcked,X=()=>z.ws,Z=e=>{z.status=e},Q=()=>{if(!z.config||!z.deviceId||!z.deviceInfo)throw new Error("SDK state not initialized");return z},Y=()=>z.config&&z.deviceId&&z.deviceInfo?z:null,ee=(e,t)=>{z.phase=e,z.declinedReason="declined"===e?t??null:null},te=()=>z.declinedReason??null,re=()=>z.lifecycleOptions,oe="sequence_classification",ne="seq2seq_generation",se="zero_shot_classification",ie="decoder_generation",ae="token_classification",de="question_answering",le="text_embedding",ce="fill_mask",me=e=>{if("string"!=typeof e)return;const t=e.trim().toLowerCase();return t.length>0?t:void 0},ue=[],fe=e=>{ue.push(e)},pe=(e,t)=>e.inferenceFramework.toLowerCase()===t.toLowerCase(),ge=(e,t,r)=>{if(!e)return;const o=me(r);if(o){const t=ue.find(t=>t.capabilities.some(t=>((e,t,r)=>"string"==typeof e.inferenceKind&&pe(e,t)&&e.inferenceKind.toLowerCase()===r)(t,e,o)));if(t)return t}return t?ue.find(r=>r.capabilities.some(r=>((e,t,r)=>"string"==typeof e.taskType&&pe(e,t)&&e.taskType.toLowerCase()===r.toLowerCase())(r,e,t))):void 0},he={"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"]),ye=(e,t)=>"ws.hello_ack"===e&&t&&!we.has(t)?"error":he[e]??"info",ke=()=>b("event_buffer"),be=()=>{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[]}},Ie=e=>{const t=e.length>100?e.slice(-100):e;((e,t)=>{try{window.localStorage.setItem(e,t)}catch{}})(ke(),JSON.stringify(t))},ve=e=>{0!==e.length&&Ie([...be(),...e])},_e=M(),Me=new Set(["guardrail.shutdown","guardrail.degraded","sdk.shutdown","sdk.crash_detected","ws.reconnect_scheduled"]);class xe{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(...be()),(()=>{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:_e,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:ye(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(()=>ve(t))}catch{ve(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||ve(t)}).catch(()=>ve(t))}catch{ve(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 Te=new xe({enabled:!1,endpointUrl:"",operatorKey:"",deviceId:"",sdkVersion:"",platform:""}),$e=()=>Se??Te,Ae={onnx:2,transformersjs:2.5,transformers:2.5,gguf:1.4},Ce=.7,Ue=.85,Ee=.95,Pe=1e4,Ve=.6,qe=6e4;let Be={},Re=je(null);function Le(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}function je(e){const t=e?.watchdog??{},r=Object.fromEntries(Object.entries(e?.frameworkMultipliers??{}).filter(([,e])=>void 0!==Le(e)));return{memoryBudgetFraction:Le(Be.memoryBudgetFraction)??Le(e?.memoryBudgetFraction)??.3,frameworkMultipliers:{...Ae,...r},minBatteryLevel:Le(e?.minBatteryLevel)??.2,storageHeadroom:Le(e?.storageHeadroom)??1.2,unknownMemoryGb:Le(e?.unknownMemoryGb)??2,watchdog:{warnPct:Le(t.warnPct)??Ce,degradePct:Le(t.degradePct)??Ue,shutdownPct:Le(t.shutdownPct)??Ee,sampleMs:Le(t.sampleMs)??Pe,recoverPct:Le(t.recoverPct)??Ve,recoverHoldMs:Le(t.recoverHoldMs)??qe},maxMemoryBudgetMb:Le(e?.maxMemoryBudgetMb)??0,maxInputTokens:Le(e?.maxInputTokens)??0,sampleLatencyBudgetMs:Le(e?.sampleLatencyBudgetMs)??0,maxCachedModels:"number"==typeof Be.maxCachedModels&&Number.isFinite(Be.maxCachedModels)&&Be.maxCachedModels>=0?Math.floor(Be.maxCachedModels):"number"==typeof e?.maxCachedModels&&Number.isFinite(e.maxCachedModels)&&e.maxCachedModels>=0?Math.floor(e.maxCachedModels):3,wasm:{maxThreads:Le(e?.wasm?.maxThreads)??4,proxyWorker:!0===e?.wasm?.proxyWorker}}}const Oe=()=>Be,Ne=()=>Re,Fe=e=>"number"!=typeof e||!Number.isFinite(e)||e<=0?0:e<1e6?1024*e*1024:e,ze=e=>Math.ceil(e.length/4),We=(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=Re.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}},Ke="herogpu",De="zerogpu",Ge=`${Ke}:`,Je=`${De}:`,He=e=>`${Ke}:${e}`,Xe=e=>`${De}:${e}`,Ze=e=>{if("string"==typeof e)return e.startsWith(Je)?`${Ge}${e.slice(Je.length)}`: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)=>(Ye[e]?.add(t),()=>Ye[e]?.delete(t)),at=(e,t={})=>{for(const r of Ye[e]??[])try{r(t)}catch{}try{"undefined"!=typeof window&&(window.dispatchEvent(new CustomEvent(He(e),{detail:t})),window.dispatchEvent(new CustomEvent(Xe(e),{detail:t})))}catch{}},dt=()=>b("init_state");let lt=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;const ct=3e5,mt=new Set(["downloading","loading","sampling"]),ut=()=>{try{const e=window.localStorage.getItem(dt());if(!e)return null;const t=JSON.parse(e);return"number"!=typeof t?.attempts||"number"!=typeof t?.windowStart?null:t}catch{return null}},ft=e=>{try{window.localStorage.setItem(dt(),JSON.stringify(e))}catch{}},pt=(e,t)=>`${e}@${t??"1"}`,gt=e=>({modelCrashes:e?.modelCrashes,blocklist:e?.blocklist,lastShutdown:e?.lastShutdown}),ht=(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=mt.has(n);let i;if(s&&e?.modelId){const n=pt(e.modelId,e.modelVersion),s=r?.[n],a=s&&t-s.firstAt<864e5,d=a?s.count+1:1;r={...r??{},[n]:{count:d,firstAt:a?s.firstAt:t}},d>=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}},wt=()=>{const e=ut();ft({attempts:0,windowStart:Date.now(),phase:e?.phase,modelId:e?.modelId,modelVersion:e?.modelVersion,pageToken:e?.pageToken,...gt(e)})},yt=(e,t,r)=>{const o=ut();ft({attempts:o?.attempts??0,windowStart:o?.windowStart??Date.now(),cooldownUntil:o?.cooldownUntil,phase:e,modelId:t,modelVersion:r,pageToken:lt,...gt(o)})},kt=()=>{const e=ut();ft({attempts:e?.attempts??0,windowStart:e?.windowStart??Date.now(),cooldownUntil:e?.cooldownUntil,...gt(e)})},bt=(e,t)=>{const r=ut(),o=r?.blocklist?.[pt(e,t)];return Boolean(o&&o.until>Date.now())};let It=null;const vt=()=>null!==It,_t=(e,t)=>{Mt(),It=setTimeout(()=>{It=null,e()},t)},Mt=()=>{null!==It&&(clearTimeout(It),It=null)};let xt=null;const St=e=>!!xt&&(xt(e),!0),Tt=e=>{try{const t=Q(),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{}},$t=[6e4,3e5,9e5,18e5];let At=0,Ct=0;const Ut=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"),Mt();try{t&&Tt("error")}catch{}try{X()?.close(t?4002:1e3,e)}catch{}try{J(void 0),Z("error"),ee("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}=Q(),r=Object.entries(e??{}).sort(([e],[r])=>Fe(t?.[r]?.sizeBytes)-Fe(t?.[e]?.sizeBytes));for(const[,e]of r)try{await(e.dispose?.())}catch{}D({})}catch{}if((e=>{const t=ut();ft({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 at("shutdown",{code:e});const n=((e=Date.now())=>{Ct>0&&e-Ct>18e5&&(At=0);const t=$t[Math.min(At,$t.length-1)];return At+=1,Ct=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}),at("shutdown",{code:e,restartInMs:n}),_t(()=>{tt(!1),St(`guardrail_restart:${e}`)||r.warn("[Shutdown] No lifecycle to restart")},n)};class Et{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 Vt=()=>{const e=globalThis.performance,t=e?.memory?.usedJSHeapSize;return"number"==typeof t&&t>0?t:null},qt=()=>{if(null!==Pt||Oe().disableGuardrails)return;if(null===Vt())return void k().debug("[Watchdog] performance.memory unavailable; watchdog inactive");const e=Ne();let t=e.unknownMemoryGb;try{const e=Q().deviceInfo?.memoryGb;"number"==typeof e&&e>0&&(t=e)}catch{}const r=e.memoryBudgetFraction*t*1024*1024*1024,o=new Et(e.watchdog,r);Pt=setInterval(()=>{try{if("shutdown"===ot())return void Bt();if("undefined"!=typeof document&&"hidden"===document.visibilityState)return;const e=Vt();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"}),at("degraded",{code:"memory_pressure"});break;case"recover":nt("running"),Tt("idle"),at("recovered",{});break;case"shutdown":Bt(),Ut({reason:"memory_pressure",guardrail:!0})}})(o,o.onSample(e,Date.now()))}catch{}},e.watchdog.sampleMs)},Bt=()=>{null!==Pt&&(clearInterval(Pt),Pt=null)},Rt=e=>{Bt(),Ut({reason:"oom",guardrail:!0}),k().error("[Watchdog] Allocation failure — emergency shutdown",{message:e})},Lt=new Set,jt=(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,Lt.delete(o)),r(e))};try{n=setTimeout(()=>i("timeout"),t),o=new Image,o.onload=()=>i("fired"),o.onerror=()=>i("fired"),Lt.add(o),o.src=e}catch{i("skipped")}}),Ot=He("runner:ready"),Nt="tag:fire",Ft=He("tag:result");let zt=null,Wt=null,Kt=null,Dt=!1,Gt=0;const Jt=()=>Kt||(Kt=new Promise(e=>{if(!zt||!Wt||"undefined"==typeof document||"undefined"==typeof window)return void e(null);let t,r=!1;const o=t=>{r||(r=!0,window.removeEventListener("message",n),e(t))},n=e=>{const r=e.data?.type;t&&e.origin===Wt&&e.source===t.contentWindow&&Ze(r)===Ot&&(Dt=(e=>"string"==typeof e&&e.startsWith(Je))(r),o(t.contentWindow))};try{window.addEventListener("message",n),t=document.createElement("iframe"),t.setAttribute("aria-hidden","true"),t.style.display="none",t.src=zt,(document.body??document.documentElement).appendChild(t),setTimeout(()=>o(null),2e3)}catch{o(null)}}),Kt),Ht=(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),Xt=async(e,t=3e3)=>{try{const r=await Jt();if(r){const o=await((e,t,r)=>new Promise(o=>{const n="zgpu-"+ ++Gt;let s,i=!1;const a=e=>{i||(i=!0,void 0!==s&&clearTimeout(s),window.removeEventListener("message",d),o(e))},d=t=>{const r=t.data;t.origin===Wt&&t.source===e&&Ze(r?.type)===Ft&&r?.id===n&&a("skipped"===r.status?"skipped":"fired")};try{window.addEventListener("message",d),s=setTimeout(()=>a("timeout"),r);const o=Dt?Xe(Nt):He(Nt);e.postMessage({type:o,id:n,url:t},Wt)}catch{a("skipped")}}))(r,e,t);if("skipped"!==o)return o}}catch{}const r=await Ht(e,t);return null!==r?r:((e,t)=>"function"!=typeof fetch?jt(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)},Zt=["cust_param1","cust_param2","cust_param3"],Qt=/^[A-Za-z0-9._-]+$/,Yt=/[^\s@]+@[^\s@]+\.[^\s@]+/,er=e=>Zt.includes(e);let tr=!1;const rr=(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(Yt.test(r))console.warn(`[herogpu] customParams.${e} looks like an email address and was dropped. Slots must not carry personal data.`);else{if(Qt.test(r))return r.length>128&&(tr||(tr=!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 or={};const nr=e=>{or=(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(!er(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=rr(e,o);void 0!==n&&(t[e]=n)}return t})(e)},sr=()=>({...or});let ir=!1,ar=0,dr=!1;const lr=[],cr=()=>ir?new Promise(e=>{lr.push(()=>{ir=!0,e()})}):(ir=!0,Promise.resolve()),mr=()=>{ir=!1;const e=lr.shift();e&&e()},ur=e=>{dr=e},fr=async e=>{const t=k(),r=performance.now(),o={cust_param1:or.cust_param1??"",cust_param2:or.cust_param2??"",cust_param3:or.cust_param3??""},{adaptersByModelId:n}=Q();let s=n?.[e.modelId];if(s||(s=await(async e=>{const t=k(),{modelInfosByModelId:r}=Q(),o=r?.[e];if(!o)return;const n=ge(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 W(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=Re.maxInputTokens)=>t>0&&ze(e)>t)(i))return $e().report("task.rejected",{code:"not_ready",modelId:e.modelId,data:{reason:"input_too_large",estimatedTokens:ze(i),maxInputTokens:Ne().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?jt(e.trackingPixel).then(e=>{a=e}):e.trackingScript&&Xt(e.trackingScript).then(e=>{a=e});const d=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 d(),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&&Rt(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 d()}}}},pr=async e=>{const{ws:t,sessionKey:r,deviceId:o}=Q(),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(dr||ir||ar>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}})));ir=!0,Z("busy");try{const t=[];for(const r of e.requests){const e=await fr(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{mr(),Z("idle")}}},gr=30,hr="exponential",wr=1e3,yr=2,kr=3e4,br=500,Ir=0,vr=86400,_r=600,Mr="stop",xr=0,Sr={min:15,max:120},Tr={min:250,max:6e4},$r={min:1,max:4},Ar={min:5e3,max:36e5},Cr={min:0,max:3e4},Ur={min:3600,max:604800},Er={min:60,max:86400},Pr=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Vr=(e,t,r)=>{const o=Pr(e);return void 0===o||o<=0?r:Math.min(Math.max(o,t.min),t.max)},qr=(e,t,r)=>{const o=Pr(e);return void 0===o||o<0?r:Math.min(Math.max(o,t.min),t.max)},Br=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Rr=e=>{const t=Br(e),r=t?e:{},o=Br(r.keep_alive)?r.keep_alive:{},n=Br(r.reconnect)?r.reconnect:{},s=Br(r.reregister)?r.reregister:{},i=Br(r.socket)?r.socket:{},a=Pr(n.give_up_after_attempts);return{served:t,keepAlive:{pingIntervalSeconds:Vr(o.ping_interval_seconds,Sr,gr)},reconnect:{strategy:"fixed"===n.strategy?"fixed":hr,initialDelayMs:Vr(n.initial_delay_ms,Tr,wr),multiplier:Vr(n.multiplier,$r,yr),maxDelayMs:Vr(n.max_delay_ms,Ar,kr),jitterMs:qr(n.jitter_ms,Cr,br),giveUpAfterAttempts:void 0!==a&&a>=0&&Number.isInteger(a)?a:Ir},reregister:{maxStalenessSeconds:Vr(s.max_staleness_seconds,Ur,vr),onRefusalRetrySeconds:Vr(s.on_refusal_retry_seconds,Er,_r),onAuthFailure:"retry_slow"===s.on_auth_failure?"retry_slow":Mr},socket:{idleTimeoutSeconds:qr(i.idle_timeout_seconds,{min:0,max:Number.MAX_SAFE_INTEGER},xr)}}};let Lr=Rr(void 0),jr=0,Or=null;const Nr=(e,t)=>{const r=Rr(e),o=((e,t)=>{const r=[],o=(e,t,n)=>{if(Br(e)&&Br(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}},Fr=()=>Lr,zr="zerogpu-slm-cache",Wr="models";class Kr extends Error{constructor(e,t){const r=Dr(t),o=Gr(t);super(`model_store_${e}_failed:${r}${o?`:${o}`:""}`),this.name="ModelStoreError",this.operation=e,this.causeName=r}}const Dr=e=>e&&"object"==typeof e&&"string"==typeof e.name?e.name:null==e?"UnknownError":typeof e,Gr=e=>e&&"object"==typeof e&&"string"==typeof e.message?e.message.slice(0,200):"";let Jr=null;const Hr=()=>(Jr||(Jr=(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)})})(zr).then(e=>!1===e?"herogpu-slm-cache":zr,()=>zr)),Jr),Xr=async(e,t)=>{const r=await(async()=>{if("undefined"==typeof indexedDB)throw new Kr("open",{name:"IndexedDBUnavailable",message:"indexedDB is not defined"});const e=await Hr();return new Promise((t,r)=>{let o;try{o=indexedDB.open(e,1)}catch(e){return void r(new Kr("open",e))}o.onupgradeneeded=()=>{const e=o.result;e.objectStoreNames.contains(Wr)||e.createObjectStore(Wr,{keyPath:"key"})},o.onsuccess=()=>t(o.result),o.onerror=()=>r(new Kr("open",o.error))})})(),o="readonly"===e?"read":"write";return new Promise((n,s)=>{let i,a,d=!1;const l=(e,t=!1)=>{if(!d){d=!0;try{r.close()}catch{}t?s(e instanceof Kr?e:new Kr(o,e)):n(a)}};let c,m;try{c=r.transaction(Wr,e)}catch(e){return void l(e,!0)}c.oncomplete=()=>l(),c.onerror=e=>{const t=e?.target;i=i??t?.error??c.error},c.onabort=()=>l(i??c.error,!0);try{m=c.objectStore(Wr)}catch(e){return void l(e,!0)}t(m).then(e=>{a=e}).catch(e=>{i=i??e;try{c.abort()}catch{l(e,!0)}})})},Zr=(e,t)=>`${e}:${t}`,Qr=async(e,t)=>{const r=Zr(e,t);return Xr("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)}))},Yr=async(e,t)=>{await Xr("readwrite",async r=>{r.delete(Zr(e,t))})},eo="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";let to={...{transformersUrl:eo}};const ro=()=>to,oo=()=>globalThis,no=e=>{e&&(e.useBrowserCache=!1)},so="transformers-cache";let io=null;const ao=()=>{const e=oo();if(e.TransformersPipeline)return Promise.resolve();if(!io){const t=k(),r=ro().transformersUrl;io=(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,no(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 io=null,t.error("[SLM] Failed to import Transformers runtime",{runtimeUrl:r,error:m(e)}),e}})()}return io},lo=e=>e.replace(/\/$/,""),co=e=>/^https?:\/\//i.test(e.trim()),mo=e=>{const t=(e=>{const t=e.trim();if(!t)return"";if(co(t))try{return new URL(t).pathname.replace(/^\/+|\/+$/g,"")}catch{return""}return t.replace(/^\/+|\/+$/g,"")})(e);return t?lo(`https://huggingface.co/${t}/resolve/main`):""},uo=(e,t)=>{const r=(e||"").trim();if(co(r))return lo(r);const o=mo(t||r);return o||lo(r)},fo=e=>e.replace(/^\/+/,"").replace(/^resolve\/main\//,"").split("?")[0],po=(e,t)=>`${e}/${fo(t)}`,go=()=>{const e=ro().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}},ho=[0,97,115,109],wo=["ort-wasm-simd-threaded.wasm","ort-wasm-simd.wasm","ort-wasm-threaded.wasm","ort-wasm.wasm"],yo=e=>e.endsWith("/")?e:`${e}/`,ko=()=>{try{const e=new URL(eo),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/"}},bo=e=>e.length>=ho.length&&ho.every((t,r)=>e[r]===t);let Io=null;const vo=e=>(Io||(Io=(async e=>{const t=[ro().wasmPaths,go(),ko(),"https://unpkg.com/@xenova/transformers@2.17.2/dist/"].filter(e=>"string"==typeof e&&e.length>0).map(yo).filter((e,t,r)=>r.indexOf(e)===t);for(const r of t){let t=!1;for(const o of wo){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(bo(s))return r;t=!0;break}catch{}}t&&k().warn("[SLM] ONNX wasm probe got non-wasm payload",{url:r})}return null})(e)),Io);let _o=Promise.resolve();const Mo=async e=>{const t=_o;let r=()=>{};_o=new Promise(e=>{r=e}),await t;try{return await e()}finally{r()}},xo=(e,t)=>`cache_persist_failed:${e}@${t||"1"}`,So=e=>b(e),To=new Map,$o=new Set,Ao=(e,t)=>{const r=xo(e,t);To.delete(r);try{window.localStorage.removeItem(So(r))}catch{}},Co=(e,t)=>((e,t)=>{const r=xo(e,t);let o=To.get(r)??null;try{const e=window.localStorage.getItem(So(r));e&&(o=JSON.parse(e))}catch{}return o&&"number"==typeof o.failures?Date.now()-(o.lastFailureAt??0)>6048e5?(Ao(e,t),null):o:null})(e,t)?.failures??0,Uo=(e,t)=>Co(e,t)>0,Eo=(e,t,r,o,n)=>{const s=`${e}:${t}@${r}`;$o.has(s)||($o.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:Po(o),...n}}))},Po=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},Vo=async(e,t)=>{try{return await Qr(e,t)}catch(r){return k().warn("[Cache] Model cache read failed; treating as a cache miss",{modelId:e,modelVersion:t,error:m(r)}),Eo("read",e,t,r,{}),null}},qo=async(e,t,r,o)=>{const n=k(),s=Co(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 Xr("readwrite",async r=>{const s={key:Zr(e,t),metadata:n,files:o};r.put(s)})})(e,t,r,o),s>0&&Ao(e,t),"persisted"}catch(o){const i=s+1;return((e,t,r)=>{const o=xo(e,t);To.set(o,r);try{window.localStorage.setItem(So(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)}),Eo("persist",e,t,o,{attempt:i,retryOnNextStart:i<2,sizeBytes:r.sizeBytes}),"failed"}},Bo=()=>b("cached_models"),Ro="zerogpu_cached_model_id",Lo=e=>{try{return window.localStorage.getItem(e)}catch{return null}},jo=e=>{try{window.localStorage.removeItem(e)}catch{}},Oo=e=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.modelId&&e.modelId.length>0,No=()=>{const e=Lo(Bo());if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(Oo):[]}catch{return[]}},Fo=e=>{const t=Bo();0===e.length?jo(t):((e,t)=>{try{window.localStorage.setItem(e,t)}catch{}})(t,JSON.stringify(e))},zo=(e,t)=>(t.lastUsedAt??0)-(e.lastUsedAt??0),Wo=()=>No().sort(zo),Ko=(e,t=Date.now())=>{const r=No().filter(t=>t.modelId!==e.modelId);Fo([{...e,lastUsedAt:t},...r])},Do=e=>{const t=No(),r=t.find(t=>t.modelId===e)??null;return r&&Fo(t.filter(t=>t.modelId!==e)),jo(e),Lo(Ro)===e&&jo(Ro),r},Go=async(e,t,r)=>{try{if(Oe().disableGuardrails)return null;const o=Ne(),n=Fe(e.sizeBytes);if(n>0){const s=Oe().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 Re.frameworkMultipliers[t]??2})(e.inferenceFramework),a=n*i,d="number"==typeof r?.memoryGb&&r.memoryGb>0?r.memoryGb:o.unknownMemoryGb,l=o.memoryBudgetFraction*d*1073741824,c=o.maxMemoryBudgetMb>0?1024*o.maxMemoryBudgetMb*1024:1/0,m=Math.min(l,c);if(a>m)return{code:"model_too_large_for_memory",message:`estimated runtime ${Math.round(a)} B > budget ${Math.round(m)} B (fraction=${o.memoryBudgetFraction}, maxBudgetMb=${o.maxMemoryBudgetMb||"none"}, multiplier=${i}, memoryGb=${d})`};const u=globalThis.performance,f=u?.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&&(!!T()||(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 Jo={};const Ho=e=>{if("string"!=typeof e)return;return e.trim()||void 0},Xo=()=>{const e={};Jo.appId&&(e.app_id=Jo.appId),Jo.appName&&(e.app_name=Jo.appName);const t=Jo.externalAppId??(()=>{try{return"undefined"!=typeof chrome?Ho(chrome?.runtime?.id):void 0}catch{return}})();return t&&(e.external_app_id=t),e},Zo="__ZGPU_WORKER_SOURCE__",Qo=["__ZGPU_WORKER","SOURCE__"].join("_"),Yo=()=>Zo!==Qo?Zo:null;class en extends Error{constructor(e,t){super(t?`${e}:${t}`:e),this.name="InferenceWorkerError",this.code=e}}class tn{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 en("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 en("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 en("worker_boot_timeout",`${n}ms`)),n);e.onerror=e=>{const t="string"==typeof e?.message?e.message:void 0;this.booted?this.crash(new en("worker_crashed",t)):s(new en("worker_boot_failed",t))},e.onmessageerror=()=>{this.booted||s(new en("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 en("worker_protocol_mismatch",String(t.protocol))):void this.request({type:"init",config:this.options.bootConfig()}).then(i,e=>s(new en("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 en("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 en("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 rn="herogpu-inference",on={worker:!0};let nn={...on},sn=null,an=!1,dn=null;const ln=e=>{nn={...on,...e??{}}},cn=()=>nn.workerUrl??ro().workerUrl,mn=()=>{const e=cn();if(e)return new Worker(e,{type:"module",name:rn});const t=Yo();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:rn})}finally{URL.revokeObjectURL(r)}},un=()=>{const e=ro(),t=e.pageOrigin??("undefined"!=typeof location&&location?location.origin:void 0);return{protocol:1,logging:{enabled:k().isEnabled()},runtime:{...e,pageOrigin:t}}},fn=(e,t,r)=>{sn||(sn={code:e,message:t});const o=dn;dn=null,o?.terminate(),k().warn("[Worker] Inference worker unavailable; models run on the main thread",{code:e,message:t}),r&&!an&&(an=!0,$e().report("guardrail.pressure_warning",{code:"inference_worker_unavailable",message:`${e}:${t}`.slice(0,256),data:{reason:e,fallback:"main_thread"}}))},pn=(e,t)=>async(r,o,n,s)=>{if(!nn.worker||sn)return t(r,o,n,s);const i="function"!=typeof globalThis.Worker?{code:"worker_api_unavailable",message:"Worker is not defined",report:!0}:cn()||Yo()?null:{code:"worker_source_unavailable",message:"no worker script in this build",report:!1};if(i)return fn(i.code,i.message,i.report),t(r,o,n,s);const a=(dn||(dn=new tn({spawn:mn,bootConfig:un,onCrash:(e,t)=>{for(const e of t)W(e,void 0);fn(e.code,e.message,!0)}})),dn);try{const{executor:t,downloadedFiles:i}=await a.load(e,r,o,s?.wasm??Ne().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 en||e instanceof Error&&"transformers_runtime_load_failed"===e.code)(e))throw e;return fn((e=>{if(e instanceof en)return e.code;const t=e?.code;return"string"==typeof t?t:"worker_error"})(e),m(e),!0),t(r,o,n,s)}},gn="app_inference_chosen_model",hn="app_inference_unfit_models",wn=new Map,yn=e=>{try{const t=window.localStorage.getItem(b(e));if(null!==t)return t}catch{}return wn.get(e)??null},kn=(e,t)=>{wn.set(e,t);try{window.localStorage.setItem(b(e),t)}catch{}},bn=e=>{wn.delete(e);try{window.localStorage.removeItem(b(e))}catch{}},In=()=>{const e=yn(gn)?.trim();return e||null},vn=()=>{bn(gn)},_n=()=>{const e=yn(hn);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[]}},Mn=e=>{const t=[...e].sort((e,t)=>e.at-t.at).slice(-16);0===t.length?bn(hn):kn(hn,JSON.stringify(t))},xn=(e,t=Date.now())=>((e,t=Date.now())=>_n().filter(r=>r.sdkVersion===e&&t-r.at<864e5))(e,t).map(e=>({modelId:e.modelId,modelVersion:e.modelVersion,reason:e.reason}));class Sn extends Error{constructor(e,t,r){super(t),this.name="ZeroGpuError",this.code=e,void 0!==r&&(this.cause=r)}}class Tn extends Sn{constructor(e,t){super(`not_contributing_${e}`,`not contributing: ${e}${t?` (${t})`:""}`),this.name="NotContributingError",this.state=e,t&&(this.registryReason=t)}}class $n extends Sn{constructor(e,t){super("model_not_eligible",`${e} is not eligible here: ${t}`),this.name="ModelNotEligibleError",this.modelId=e,this.reason=t}}class An extends Sn{constructor(e,t){super("inference_failed",e,t),this.name="LocalInferenceFailedError"}}const Cn=e=>{if(e instanceof Tn)return{code:e.code,message:e.message,name:e.name,state:e.state,...e.registryReason?{registryReason:e.registryReason}:{}};if(e instanceof $n)return{code:e.code,message:e.message,name:e.name,modelId:e.modelId,reason:e.reason};if(e instanceof Sn)return{code:e.code,message:e.message,name:e.name};const t=e instanceof Error?e.message:String(e);return{code:"string"==typeof e?.code?e.code:"error",message:t,name:e instanceof Error?e.name:"Error"}},Un="[App]";let En=null,Pn=!1,Vn=null,qn=null;const Bn=()=>{const e=Y(),t=e?.modelInfo?.modelId;return t&&K(t)?t:null},Rn=()=>{if(st()||rt()||!re())return"stopped";if(Pn)return"switching";if("degraded"===ot())return"degraded";const e=z.phase??"idle";if("declined"===e)return"declined";if("preparing"===e)return"preparing";if("running"===e){const e=Y();if(X()?.isActive()&&"error"!==e?.status&&Bn())return H()?"contributing":"preparing"}return"registering"},Ln=async()=>{const e=re(),t=Y();if(!e?.edgeOperatorKey||!t)throw new Tn("stopped");const r=await(async e=>({...e,battery:await U()??e.battery,connection:E()??e.connection}))(t.deviceInfo),o={deviceId:t.deviceId,sdkVersion:t.config.sdkVersion,cachedModels:Wo().map(e=>({modelId:e.modelId,modelVersion:e.modelVersion||"1"})),device:r,unfitModels:xn(t.config.sdkVersion),...sr()};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 d=await fetch(s,{method:"POST",headers:i,body:JSON.stringify(t)}),l=await B(d),c=R(l);if(!d.ok&&!c){const e="string"==typeof l?l:JSON.stringify(l??"");throw o.warn("Eligible models request failed",{status:d.status,message:e.slice(0,200)}),new j(d.status,e)}const m=l&&"object"==typeof l?l:{},u=Array.isArray(m.models)?m.models:[];return o.info("Eligible models received",{lines:u.length,eligible:u.filter(e=>!0===e?.eligible).length,refusalReason:c??void 0}),{deviceId:"string"==typeof m.deviceId?m.deviceId:t.deviceId,edgeSdkType:"string"==typeof m.edgeSdkType?m.edgeSdkType:"unknown",guardMode:"string"==typeof m.guardMode?m.guardMode:void 0,models:u,...c?{refusalReason:c}:{}}})(t.config,o,{edgeOperatorKey:e.edgeOperatorKey})}catch(e){throw new Sn((e=>{if(e instanceof j)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 Tn("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,Wo(),Bn());return Vn=s,k().info(`${Un} Eligible models`,{lines:s.length,eligible:s.filter(e=>e.eligible).length}),s},jn=(e,t)=>{In()===e&&vn(),En?.modelId===e&&(En.refusalReason=t),k().info(`${Un} Chosen model not kept`,{modelId:e,reason:t}),at("modelChoiceRefused",{modelId:e,reason:t})},On=e=>{Pn=!1;const t=En;t&&(En=null,t.reject(e))};let Nn=0,Fn=!1;const zn=()=>{const e=(z.registrationSettings??null)?.device_timeout_interval_seconds;return"number"==typeof e&&Number.isFinite(e)&&e>0?e:600},Wn=(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=Fr();let n,s;if(o.served)if("socket_closed"===t){s=jr;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),jr+=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*zn();$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&&ee("registering"),_t(()=>{X()?.isActive()?r.info("[WS] Active WebSocket present; skipping re-registration"):(r.info("[WS] Re-registration timer fired; restarting lifecycle"),Kn(e,t))},n)},Kn=(e,t)=>{const r=k();r.info("[Lifecycle] Running",{reason:t}),Gn(e).catch(o=>{r.error("[Lifecycle] Attempt failed; will retry",{reason:t,error:m(o)}),On(new Sn(Yn(o),`switch failed: ${m(o)}`,o)),Wn(e,"socket_closed")})};xt=e=>{const t=Y()?.lifecycleOptions;t&&Kn(t,e)};const Dn=(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=X();J(void 0);try{o?.close(1e3,t)}catch{}Kn(e,t)},Gn=async e=>{const{config:t,appUserId:r,edgeOperatorKey:o,deviceId:n}=e;y(t.telemetry);const s=k();if(st())return void s.warn("[Init] SDK is shut down; refusing to start lifecycle");nt("starting"),(e=>{z.config=e})(t),ln(t.inference),Mt();const i={config:t,appUserId:r,edgeOperatorKey:o,deviceId:n};if((e=>{z.lifecycleOptions=e})(i),ee("registering"),(e=>{if(!Fn&&"undefined"!=typeof window&&"function"==typeof window.addEventListener){Fn=!0;try{window.addEventListener("online",()=>{st()||X()?.isActive()||!vt()||(k().info("[WS] Network is back; re-registering now"),Mt(),Kn(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}=ht(t,e),s={modelCrashes:o,blocklist:n,lastShutdown:t?.lastShutdown};if(t?.cooldownUntil&&t.cooldownUntil>e)return ft({...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 ft({attempts:1,windowStart:e,...s}),{allowed:!0,attempts:1,crash:r};const i=t.attempts+1;return i>=3?(ft({attempts:i,windowStart:t.windowStart,cooldownUntil:e+ct,...s}),{allowed:!1,cooldownRemainingMs:ct,attempts:i,crash:r}):(ft({attempts:i,windowStart:t.windowStart,...s}),{allowed:!0,attempts:i,crash:r})})();if(!a.allowed){Z("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"}),On(new Tn("stopped"));const e=Math.max(1e3,(a.cooldownRemainingMs??0)+1e3);return void _t(()=>Kn(i,"crash_loop_cooldown"),e)}const d=performance.now(),l=n?null:v(),c=!n&&!l,m=n??l??x();n&&(e=>{_(e)})(n),s.info("[Init] Starting lifecycle",{sdkVersion:t.sdkVersion,deviceId:m,isFreshDevice:c,providedDeviceId:Boolean(n),orchestrator:t.orchestrator?.baseUrl});const u=await(async(e,t,r)=>{const o=window.screen||{width:null,height:null},n=T(),s=V(),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??x(),platform:$(),deviceType:A(),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:C(),webglFingerprint:C(),screen:{width:o?.width??null,height:o?.height??null,pixelRatio:window.devicePixelRatio??null},battery:await U(),connection:E(),pageUrl:window.location?.href,referrer:document.referrer,location:e.locationData?await P():void 0}})(t.telemetry,r,m);((e,t)=>{z.deviceId=e,z.deviceInfo=t})(m,u),(e=>{Se&&Se.matches(e.deviceId,e.enabled)||(Se?.flush(),Se?.dispose(),Se=new xe(e))})({enabled:t.telemetry.events,endpointUrl:`${t.orchestrator.baseUrl}${t.orchestrator.eventsPath}`,operatorKey:o,deviceId:m,sdkVersion:t.sdkVersion,platform:u.platform});const f=$e();f.report("sdk.init_started",{data:{sdkVersion:t.sdkVersion}}),rs(a.crash),s.info("[Init] Device info collected",{platform:u.platform,deviceType:u.deviceType,gpuRenderer:u.gpuRenderer});const p=(e,t)=>{s.info(`[Flow] ${e}`,t??{})};(()=>{const e=Lo(Ro);if(!e)return;const t=Lo(e);if(t){try{const e=JSON.parse(t);Oo(e)&&!No().some(t=>t.modelId===e.modelId)&&Ko(e,Date.now()-1)}catch{}jo(e)}jo(Ro)})(),await ms(p);const g=c?[]:await Qn(p);c?p("Fresh device detected; skip cache checks"):p("Cache verified",{cachedModels:g.map(e=>e.modelId)}),G(g[0]?.modelId??null);const h=In(),w=xn(t.sdkVersion),b={deviceId:m,sdkVersion:t.sdkVersion,cachedModels:g,device:u,...sr(),...Xo(),...w.length>0?{unfitModels:w}:{},...h?{requestedModelId:h}:{}};let I,M=[];const j={},O={},F={};s.info("[Register] Sending register request",{deviceId:m,cachedModels:b.cachedModels.map(e=>e.modelId),unfitModels:w.map(e=>e.modelId),requestedModelId:h??void 0,sdkVersion:t.sdkVersion}),f.report("register.started");const D=performance.now();try{I=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 d=await fetch(s,{method:"POST",headers:i,body:JSON.stringify(t)});o.info("Register request sent",{url:s,status:d.status,bodyBytes:JSON.stringify(t).length});const l=await B(d),c=R(l);if(!d.ok&&!c){const e="string"==typeof l?l:JSON.stringify(l??"");throw o.error("Register request failed",{status:d.status,message:e}),new q(d.status,e)}if(l&&"object"==typeof l&&!c){const e=l;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=l&&"object"==typeof l?l:{},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:L(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 q(d.status,"Register response body is not valid JSON")})(t,b,{edgeOperatorKey:o})}catch(e){if(e instanceof q&&(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"}),wt(),On(new Sn(`http_${e.status}`,"register refused the operator key",e)),void("retry_slow"===Fr().reregister.onAuthFailure?(s.warn("Register auth failed; policy says retry_slow"),Wn(i,"auth_failure")):(s.warn("Register auth failed, stopping lifecycle"),ee("idle")));throw f.report("register.failed",{code:Yn(e),message:e.message}),f.report("sdk.init_failed",{code:Yn(e)}),wt(),e}const H=(e=>{if(!e||"object"!=typeof e)return null;for(const t of Object.values(e))if(t&&"object"==typeof t)return t;return null})(I.configSettings);var Q;Q=H,z.registrationSettings=Q??null,(e=>{Re=je(e?.guardrails??null)})(H);const te=Nr(H?.connection,"register");te.changed.length>0&&s.info("[Register] Connection policy applied",{source:te.source,changed:te.changed}),H&&s.info("[Register] Registration settings received",{keys:Object.keys(H)});const re=I.requestedModel;if(re&&!re.granted&&jn(re.modelId,re.reason??I.refusalReason??"refused"),I.refusalReason)return f.report("register.rejected",{code:I.refusalReason}),s.warn("[Register] Registration refused by server",{reason:I.refusalReason}),Z("error"),nt("error"),ee("declined",I.refusalReason),wt(),On(new Tn("declined",I.refusalReason)),void Wn(i,"refusal");if(f.report("register.succeeded",{durationMs:Math.round(performance.now()-D)}),((e=Date.now())=>{Or=e})(),f.setSessionKey(I.sessionKey),s.info("Register response received",{deviceId:I.deviceId,wsUrl:I.wsUrl}),!I.wsUrl)return wt(),ee("idle"),void On(new Sn("no_session","register opened no session"));M=os(I.slmConfig);const oe=M[0];oe&&f.report("model.assigned",{modelId:oe.modelId,modelVersion:oe.modelVersion,bytes:oe.sizeBytes}),s.info("[Register] Models assigned",{count:M.length,models:M.map(e=>e.modelId),totalBytes:M.reduce((e,t)=>e+(t.sizeBytes??0),0)});for(const e of M)F[ss(e)]="idle",O[e.modelId]=e;if(!oe)return wt(),ee("idle"),void On(new Sn("no_model","the registry assigned no model"));var ne,se,ie,ae;ne=I.sessionKey,z.sessionKey=ne,se=O,z.modelInfosByModelId=se??{},ie=oe,z.modelInfo=ie,z.taskType=ie?.taskType,z.modelInfosByModelId||(z.modelInfosByModelId={}),ie?.modelId&&(z.modelInfosByModelId[ie.modelId]=ie),ae=oe.sample,z.sample=ae,s.info("Runtime globals updated from register response",{taskType:oe.taskType,hasSample:Boolean(oe.sample)}),ee("preparing");const de=oe.modelVersion??"1",le=K(oe.modelId),ce=le&&le.config.modelVersion===de?le:void 0;for(const[e,t]of Object.entries(Y()?.adaptersByModelId??{}))if(e!==oe.modelId||!ce){try{await(t.dispose?.())}catch{}W(e,void 0)}let me=ce;if(ce)p("Model still loaded; reusing it",{modelId:oe.modelId}),j[oe.modelId]=ce,Xn(oe);else{const e=g.some(e=>e.modelId===oe.modelId&&e.modelVersion===de);p(e?"Loading the assigned model from the cache":"Loading the assigned model",{modelId:oe.modelId,cached:e});const r=await Hn(oe);if("unfit"===r.kind)return Jn(i,oe,r.reason);if("transient"===r.kind){Z("error"),await us({wsUrl:I.wsUrl,hello:{type:"hello",deviceId:I.deviceId,sessionKey:I.sessionKey,sdkVersion:t.sdkVersion,slmConfig:M.map(e=>({modelId:e.modelId,modelVersion:e.modelVersion??"1",status:e.modelId===oe.modelId?"error":F[ss(e)]||"idle"}))},ack:{type:"hello_ack",deviceId:I.deviceId,sdkVersion:t.sdkVersion,sessionKey:I.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}),kt(),wt(),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 On(new Sn(Yn(e),`switch failed: ${e.message}`,e)),void Wn(i,"refusal")}if(me=r.adapter,j[oe.modelId]=me,W(oe.modelId,me),oe.sample?.text){s.info("[Sample] Running post-register sample inference",{taskType:oe.taskType}),yt("sampling",oe.modelId,oe.modelVersion);const e=await me.runSample(oe.sample),t={taskType:oe.taskType,ok:e.ok,error:e.error,errorMessage:e.errorMessage,processingTimeMs:e.processingTimeMs},r=Ne().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(me.dispose?.())}catch{}return W(oe.modelId,void 0),Jn(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)}Xn(oe),await Zn(oe.modelId)}for(const e of M){if(e.modelId===oe.modelId)continue;const t=is(e),r=ge(t.inferenceFramework,t.taskType,t.inferenceKind);if(!r){F[ss(e)]="error",s.warn("No adapter factory for secondary model",{modelId:e.modelId,framework:t.inferenceFramework,taskType:t.taskType});continue}const o=await ts(e);if(o){F[ss(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?(j[e.modelId]=n.adapter,W(e.modelId,n.adapter)):(F[ss(e)]="error",s.warn("Failed to load secondary model",{modelId:e.modelId,taskType:e.taskType,error:n.error?.message}))}const ue=I.deviceId,fe=M.map(e=>({modelId:e.modelId,modelVersion:e.modelVersion??"1",status:F[ss(e)]||"idle"})),pe={type:"hello",deviceId:ue,sessionKey:I.sessionKey,sdkVersion:t.sdkVersion,slmConfig:fe};s.info("[WS] Connecting WebSocket",{wsUrl:I.wsUrl,models:fe.map(e=>`${e.modelId}:${e.status}`)}),f.report("ws.connect_started");const he=Fr();let we=null;const ye=()=>{null!==we&&(clearTimeout(we),we=null),(e=>{Pn=!1;const t=En;if(!t)return;En=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)},ke=new N({url:I.wsUrl,hello:pe,pingIntervalSeconds:he.served?he.keepAlive.pingIntervalSeconds:0,onPingTick:()=>{st()||X()!==ke||((e=Date.now())=>Lr.served&&null!==Or&&e-Or>1e3*Lr.reregister.maxStalenessSeconds)()&&(s.warn("[WS] Registration exceeded max_staleness; refreshing"),Dn(i,"max_staleness"))},onOpen:()=>f.report("ws.connected"),onMessage:e=>{if("requests"in e&&Array.isArray(e.requests))pr(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}),Z("error"===r.status?"error":"idle"),X()===ke&&(t=!0,z.sessionAcked=t,ye())}else if("type"in e&&"policy_update"===e.type){const t=e,r=Nr(t.connection,"ws");X()===ke&&ke.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()||X()!==ke)return;const r=((e,t=Math.random)=>{const r=Pr(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(()=>{Dn(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=X()===ke;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}}),Z("error"),Wn(i,"socket_closed"))},onError:()=>{s.error("[WS] Connection error"),f.report("ws.error"),X()===ke&&Z("error")}});var be;J(ke),Z("idle"),yt("running",oe.modelId,oe.modelVersion),nt("running"),ee("running"),qt(),f.report("sdk.init_succeeded",{durationMs:Math.round(performance.now()-d)}),s.info("[Init] SDK ready",{deviceId:m,primaryModelId:oe.modelId,taskType:oe.taskType}),jr=0,wt(),Nn=0,be=oe.modelId,qn!==be&&(qn=be,at("activeModelChanged",{modelId:be})),null!==En&&(we=setTimeout(ye,15e3))},Jn=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 Yr(t.modelId,s).catch(()=>{}),Do(t.modelId),await ls(t.modelUrl).catch(()=>{}),((e,t,r,o,n=Date.now())=>{const s=_n().filter(t=>t.modelId!==e);Mn([...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}),In()===t.modelId&&jn(t.modelId,r),kt(),wt(),W(t.modelId,void 0),G(Wo()[0]?.modelId??null),Nn<4)return Nn+=1,ee("registering"),Gn(e);o.warn("[Model] Too many unfit models in a row; retrying on the slow cadence",{attempts:Nn}),Z("error"),nt("error"),On(new Sn("unfit_models_exhausted","every assigned model failed on this device")),Wn(e,"refusal")},Hn=async e=>{const t=k(),r=$e(),o=is(e),n=ge(o.inferenceFramework,o.taskType,o.inferenceKind),s=await ts(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),d=Math.round(performance.now()-i);if(a.adapter)return r.report("model.load_succeeded",{modelId:e.modelId,modelVersion:e.modelVersion,durationMs:d,bytes:a.metrics?.sizeBytes}),t.info("[Model] Primary model loaded",{modelId:e.modelId,ms:d,sizeBytes:a.metrics?.sizeBytes}),{kind:"adapter",adapter:a.adapter};const l=a.error?.message??"init_error";return r.report("model.load_failed",{code:es(l),modelId:e.modelId,modelVersion:e.modelVersion,durationMs:d,message:l}),t.error("[Model] Primary model load failed",{modelId:e.modelId,framework:o.inferenceFramework,taskType:o.taskType,ms:d,error:l}),(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))(l)?{kind:"transient",reason:l}:{kind:"unfit",reason:`load_failed:${es(l)}:${l.slice(0,48)}`}},Xn=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 Oo(e)?e:null}catch{return null}})(e.modelId);r&&(r.modelVersion||"1")!==t&&(Yr(e.modelId,r.modelVersion||"1").catch(()=>{}),$e().report("model.evicted",{code:"version_changed",modelId:e.modelId,modelVersion:r.modelVersion})),Ko({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}),G(e.modelId)},Zn=async e=>{const t=Ne().maxCachedModels,r=((e,t)=>{if(!Number.isFinite(e)||e<=0)return[];const r=Wo(),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){Fo(r);for(const e of o)jo(e.modelId)}return o})(t,e);for(const e of r){await Yr(e.modelId,e.modelVersion||"1").catch(()=>{}),await ls(e.modelUrl).catch(()=>{});const r=K(e.modelId);if(r){try{await(r.dispose?.())}catch{}W(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})}},Qn=async e=>{const t=$e(),r=[];for(const o of Wo()){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(Uo(o.modelId,n)){e("Cached model was never persisted (browser storage refused); not claimed",{modelId:o.modelId,failures:Co(o.modelId,n)});continue}const s=Boolean(o.modelUrl&&o.taskType&&Array.isArray(o.requiredFiles)&&o.sample?.text),i=s?await as(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 Yr(o.modelId,n).catch(()=>{}),Do(o.modelId),t.report("model.cache_purged",{modelId:o.modelId,modelVersion:n}))}return r},Yn=e=>{if(e instanceof q)return`http_${e.status}`;return/timeout/i.test(e?.message??"")?"timeout":"network"},es=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",ts=async e=>{if(bt(e.modelId,e.modelVersion))return{code:"model_blocklisted",message:"blocklisted after repeated crashes during load"};let t;try{t=Q().deviceInfo}catch{t=void 0}return Go({modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:e.sizeBytes,inferenceFramework:e.inferenceFramework},"download",t)},rs=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})},os=e=>{if(!Array.isArray(e))return[];const t=[];for(const r of e){if(!r?.modelId||!r?.modelVersion||!r?.modelUrl)continue;const e=ns(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},ns=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},ss=e=>`${e.modelId}@${e.modelVersion??"1"}`,is=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}),as=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=ds(e.requiredFiles);if(!t.length)return{ok:!1,missing:["<no required files>"],stored:0};try{const r=await Qr(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}}},ds=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),ls=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(so));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)}},cs=()=>b("transformers_cache_purged"),ms=async e=>{if("undefined"!=typeof caches){try{if(window.localStorage.getItem(cs()))return}catch{}try{const t=(await caches.keys()).filter(e=>e.includes(so));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(cs(),(new Date).toISOString())}catch{}}catch{}}},us=async e=>{await new Promise(t=>{let r=!1;const o=()=>{r||(r=!0,t())},n=window.setTimeout(o,1500);try{new N({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 fs{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 ps=async(e,t,r)=>{const o=k(),n=performance.now(),s={};try{const o=await Vo(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},d=o?{downloadMs:o.metadata.downloadMs,loadModelMs:o.metadata.loadModelMs,sizeBytes:o.metadata.sizeBytes}:{},l=await r.loadExecutor(e,i,a),c={...d,loadModelMs:l.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 qo(e.modelId,e.modelVersion,{modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:r,downloadMs:o?0:a,loadModelMs:l.loadModelMs},t),c.sizeBytes=r,o||(c.downloadMs=a)}return{adapter:new fs(e,r.capability(e),l,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 Yr(e.modelId,e.modelVersion).catch(()=>{}),{error:t,metrics:{}}}},gs=async e=>{const t=performance.now();return{result:await e(),ms:Math.round(performance.now()-t)}},hs={},ws=(e,t,r,o,n,s)=>{const i=n.map(e=>fo(e.trim())).filter(e=>e.length>0),a=new Set(i),d=k(),l=(()=>{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 fo(e)}if(!l)return null;const n=l.pathname.replace(/\/$/,"");if(!t.startsWith(`${n}/`))return null;const s=t.slice(n.length+1);return fo(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 d.error("[SLM][fetch] non-model wasm/ort request failed",{modelId:e,requestUrl:c,error:m(t)}),t}}const f=(e=>{const t=fo(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 d.warn("[SLM] Unexpected model file request; falling back to original fetch",{file:u,modelId:e}),s(n,i);const p=(e=>{const r=fo(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=fo(f),h=po(e,g);let w=hs[h]||r[h]||hs[g]||r[g]||r[`onnx/${g}`]||hs[`onnx/${g}`];if(!w&&g.startsWith("onnx/")){const t=g.replace("onnx/","");w=r[t]||hs[t]||r[po(e,t)]||hs[po(e,t)]}if(w)return new Response(w);try{for(const e of p){const t=await s(e,i);if(t.ok){const e=await t.blob();return hs[h]=e,o&&o(h,e),new Response(e)}}return new Response("required_file_not_found",{status:404,statusText:"Not Found"})}catch(t){return d.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"})}}},ys="zgScoreRecorder",ks=e=>({[ys]:e}),bs=(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)},Is=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?.[ys];if(s)for(const e of o)e[ys]=s;return o},t.runBeam=async e=>{const r=await o.call(t,e),n=e[ys];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:bs(t.data,r,o)}})(n,r.logits),r},t.updateBeam=(e,r)=>{const o=n.call(t,e,r),s=e[ys];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)},vs=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)},_s=(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),Ms=e=>"number"==typeof e&&Number.isFinite(e)&&e>0&&e<1e6?Math.floor(e):void 0,xs=e=>{const t=new BigInt64Array(e.length);return e.forEach((e,r)=>{t[r]=BigInt(e)}),t},Ss=(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=[Ms(e.max_position_embeddings),Ms(e.n_positions),Ms(t.model_max_length)].filter(e=>void 0!==e);return r.length>0?Math.min(...r):512})(o,t),a=t.encode(""),d=a.length>0?a[a.length-1]:void 0,l=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),m=((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,d),u=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",xs(t),r);else if("attention_mask"===s)o[s]=new e.Tensor("int64",xs(t.map(()=>1)),r);else{if("token_type_ids"!==s)throw new Error(`sequence_classification_unsupported_input:${s}`);o[s]=new e.Tensor("int64",xs(t.map(()=>0)),r)}return o})(m)),f=u[l];if(!f||!f.data||0===f.data.length)throw new Error("sequence_classification_empty_logits");const p=_s(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}}},Ts={summary:"summarization",iab_classify:"text-classification",classification:"zero-shot-classification",text_generation:"text2text-generation"},$s=new Set([oe,ne,se,ae,de,le,ce]),As={[ne]:"text2text-generation",[se]:"zero-shot-classification",[ae]:"token-classification",[de]:"question-answering",[le]:"feature-extraction",[ce]:"fill-mask"},Cs=e=>{const t=me(e.inferenceKind);return t&&$s.has(t)?t:"task"},Us=8192,Es=/\[MASK\]|<mask>/g,Ps=e=>"number"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,Vs=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("input_text_required");return e},qs=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""},Bs=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]},Rs=(e,t)=>{const r=(e??"").trim();return r?r.slice(0,1024):t},Ls=e=>{const t=/^([BI])-(.+)$/.exec(e);return t?{prefix:t[1],label:t[2]}:{prefix:null,label:e}},js=(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,d="number"==typeof e?.index?e.index:i+1,l=r.startsWith("##")&&d===i+1,c=l?r.slice(2):r;if(i=d,o.push({token:r,label:t,score:Number(n.toFixed(6))}),l&&s){s.pieces[s.pieces.length-1]+=c,s.scores.push(n);continue}const{prefix:m,label:u}=Ls(t);"O"!==t&&c?s&&"B"!==m&&s.label===u?(s.pieces.push(c),s.scores.push(n)):(a(),s={label:u,pieces:[c],scores:[n]}):a()}return a(),{entities:n,tokens:o}},Os=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):[]},Ns=async(e,t,r)=>{const{pipeline:o,pipelineTask:n}=e,{result:s,ms:i}=await gs(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}},Fs=async(e,t,r)=>{try{return await Ns(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 Ns(e,n,r)}};class zs{constructor(e,t){this.config=e,this.state=t,this.loadModelMs=t.loadModelMs}async runInference(e){const t=Cs(this.config);if(t===oe)return this.runSequenceClassification(e);if(t===ne)return this.runSeq2Seq(e);if(t===se)return this.runZeroShot(e,!0);if(t===ae)return this.runTokenClassification(e);if(t===de)return this.runQuestionAnswering(e);if(t===le)return this.runTextEmbedding(e);if(t===ce)return this.runFillMask(e);const r=this.config.taskType,o=Rs(e.text,"summarize this text");if("classification"===r)return this.runZeroShot(e);if("iab_classify"===r){const{raw:e,ms:t}=await Fs(this.state,o);return{output:e,inferenceMs:t}}if("summary"===r){const{raw:t,ms:r}=await Fs(this.state,o,{maxNewTokens:e.maxNewTokens});return{output:{text:qs(t)},inferenceMs:r}}if("text_generation"===r){const{raw:t,ms:r}=await Fs(this.state,o,{maxNewTokens:e.maxNewTokens});return{output:{text:qs(t)},inferenceMs:r}}const{raw:n,ms:s}=await Fs(this.state,o);return{output:n,inferenceMs:s}}async runZeroShot(e,t=!1){const r=t?Vs(e.text).slice(0,Us):Rs(e.text,"summarize this text"),o=Bs(e.categories)??Bs(e.category),{raw:n,ms:s}=await Fs(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=Vs(e.text),o=e.topK??e.top_k,{result:n,ms:s}=await gs(()=>t.classify(r,"number"==typeof o?o:void 0));return{output:n,inferenceMs:s}}async runSeq2Seq(e){const t=Vs(e.text).slice(0,8192),r=Ps(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 gs(()=>o(t,{max_new_tokens:r,do_sample:!1,num_beams:1,...s?ks(s):{}})),d=qs(i).trim(),l=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:d,score:l},inferenceMs:a}}async runTokenClassification(e){const t=Vs(e.text).slice(0,Us),{result:r,ms:o}=await gs(()=>this.state.pipeline(t,{ignore_labels:[]}));return{output:js(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:Vs(e.text)).slice(0,Us),o=this.state.pipeline,{result:n,ms:s}=await gs(()=>o(t,r,{topk:1})),i=Array.isArray(n)?n[0]:n,a="string"==typeof i?.answer?i.answer.trim():"",d="number"==typeof i?.score?i.score:0,l=a?r.indexOf(a):-1;return{output:{answer:a,score:d,start:l,end:l>=0?l+a.length:-1},inferenceMs:s}}async runTextEmbedding(e){const t=Vs(e.text).slice(0,Us),{result:r,ms:o}=await gs(()=>this.state.pipeline(t,{pooling:"mean",normalize:!0}));return{output:{embedding:Os(r)},inferenceMs:o}}async runFillMask(e){const t=this.state.pipeline.tokenizer?.mask_token,r=((e,t)=>!t||e.includes(t)?e:e.replace(Es,t))(Vs(e.text).slice(0,Us),"string"==typeof t?t:void 0),o=(e=>Ps(e.topK)??Ps(e.top_k))(e)??5,{result:n,ms:s}=await gs(()=>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})),d=i[0];return{output:{predictions:a,text:"string"==typeof d?.sequence?d.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 Ws=async(e,t,r,o)=>{const n=Cs(e),s=k();try{await ao()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const i=lo(uo(e.modelUrl,e.modelRepoId)),a=(e=>{const t=Cs(e);return As[t]??Ts[e.taskType]??e.taskType})(e),d=co(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!d)throw new Error("[SLM] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const l=await Mo(async()=>{const l=oo(),c=l.TransformersEnv||{};c.allowRemoteModels=!0,c.allowLocalModels=!0,no(c),c.backends||(c.backends={}),c.backends.onnx||(c.backends.onnx={}),c.backends.onnx.wasm||(c.backends.onnx.wasm={});const m=s.isEnabled()?"error":"fatal";c?.backends?.onnx?.env&&(c.backends.onnx.env.logLevel=m);const u=We(void 0,o?.wasm);c.backends.onnx.wasm.proxy=u.proxy,c.backends.onnx.wasm.numThreads=ro().forceSingleThread?1:u.numThreads;const f=globalThis.fetch.bind(globalThis),p=await vo(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=m);const g=globalThis.ort;g?.env&&(g.env.logLevel=m),c.fetch=ws(e.modelId,i,t,r,(e.requiredFiles??[]).map(e=>e.name),f),l.TransformersEnv=c,globalThis.fetch=c.fetch;const h={device:"wasm",quantized:e.quantized,progress_callback:()=>{}},w=()=>gs(async()=>{if(n===oe){const e=(()=>{const e=oo().TransformersLib;if(!e)throw new Error("transformers_lib_unavailable");return e})(),[t,r]=await Promise.all([e.AutoTokenizer.from_pretrained(d,h),e.PreTrainedModel.from_pretrained(d,h)]);return{classifier:Ss(e,t,r)}}const e=l.TransformersPipeline;if(!e)throw new Error("transformers_pipeline_unavailable");return{pipeline:await e(a,d,h)}});try{return await w()}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 w()}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 w()}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:m}=l;if(c.classifier){return{pipeline:()=>Promise.reject(new Error("pipeline_not_loaded")),pipelineTask:n,loadModelMs:m,classifier:c.classifier}}const u=c.pipeline,f={pipeline:u,pipelineTask:a,loadModelMs:m};if(n===ne){const t=u.model;f.defaultMaxNewTokens=Ps(t?.generation_config?.max_new_tokens)??48,Is(t)?f.scoring={eosTokenIds:vs(t)}:k().warn("[SLM] seq2seq score hooks unavailable; score defaults to 0.5",{modelId:e.modelId})}return f},Ks=async(e,t,r,o)=>{const n=await Ws(e,t,r,o);return new zs(e,n)},Ds={capabilities:[{inferenceFramework:"ONNX",inferenceKind:oe},{inferenceFramework:"ONNX",inferenceKind:ne},{inferenceFramework:"ONNX",inferenceKind:se},{inferenceFramework:"ONNX",inferenceKind:ae},{inferenceFramework:"ONNX",inferenceKind:de},{inferenceFramework:"ONNX",inferenceKind:le},{inferenceFramework:"ONNX",inferenceKind:ce},{inferenceFramework:"ONNX",taskType:"summary"},{inferenceFramework:"ONNX",taskType:"iab_classify"},{inferenceFramework:"ONNX",taskType:"classification"},{inferenceFramework:"ONNX",taskType:"text_generation"}],load:(e,t)=>((e,t)=>ps(e,t,{logLabel:"[SLM][loadOnnxAdapter]",capability:e=>({inferenceFramework:"ONNX",taskType:e.taskType,inferenceKind:e.inferenceKind,modelType:e.modelType}),loadExecutor:pn("ONNX",Ks),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)};fe(Ds);class Gs{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 gs(async()=>this.state.pipeline(t));var i,a;const d=((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),l=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()))})(d,l);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})(d,l??[]);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 Js=async(e,t,r)=>{const o=k();try{await ao()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const n=lo(uo(e.modelUrl,e.modelRepoId)),s=co(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 Mo(async()=>{const i=oo(),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 d=globalThis.fetch.bind(globalThis),l=await vo(d);l&&(a.backends.onnx.wasm.wasmPaths=l),a.fetch=ws(e.modelId,n,t,r,(e.requiredFiles??[]).map(e=>e.name),d),i.TransformersEnv=a,globalThis.fetch=a.fetch;try{return await gs(()=>{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=d}}),{result:a,ms:d}=i;return{pipeline:a,loadModelMs:d}},Hs=async(e,t,r)=>{const o=await Js(e,t,r);return new Gs(o)},Xs={capabilities:[{inferenceFramework:"Transformers",taskType:"gliner"},{inferenceFramework:"Transformers",taskType:"gliner2"}],load:(e,t)=>((e,t)=>ps(e,t,{logLabel:"Transformers adapter load",capability:e=>({inferenceFramework:"Transformers",taskType:e.taskType,modelType:e.modelType}),loadExecutor:pn("Transformers",Hs)}))(e,t)};fe(Xs);const Zs="https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js";let Qs=null;const Ys=Zs.replace(/\/esm\/index\.js$/,"/esm");class ei{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 gs(async()=>this.state.wllama.createCompletion(t,{nPredict:r}));return{output:{text:"string"==typeof o?o:ti(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 ti=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)}},ri=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):(Qs||(Qs=(async()=>{try{const e=await import(Zs);if(!e?.Wllama)throw new Error("Wllama runtime missing Wllama export");return window.WllamaModule=e,e}catch(e){throw Qs=null,k().error("[GGUF] Failed to import wllama runtime",{runtimeUrl:Zs,error:m(e)}),e}})()),Qs)),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),d=a?a[1]:i,l=[`${d}/resolve/${a?a[2]:"main"}/${t}`,`${d}/${t}`],c=[];for(const e of l)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":`${Ys}/single-thread/wllama.wasm`,"multi-thread/wllama.wasm":`${Ys}/multi-thread/wllama.wasm`},a=new n.Wllama(i),{ms:d}=await gs(async()=>{await a.loadModel([s],{n_ctx:e.maxInputTokens&&e.maxInputTokens>0?e.maxInputTokens:2048})});return{wllama:a,loadModelMs:d}},oi={capabilities:[{inferenceFramework:"GGUF",inferenceKind:ie},{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 Vo(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}:{},d=await ri(e,s,i),l={...a,loadModelMs:d.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 qo(e.modelId,e.modelVersion,{modelId:e.modelId,modelVersion:e.modelVersion,sizeBytes:i,downloadMs:r?0:a,loadModelMs:d.loadModelMs},t),l.sizeBytes=i,r||(l.downloadMs=a)}return{adapter:new ei(e,d,l),metrics:l}}catch(t){return r.error("GGUF adapter load failed",{modelId:e.modelId,modelVersion:e.modelVersion,modelUrl:e.modelUrl,error:m(t)}),await Yr(e.modelId,e.modelVersion).catch(()=>{}),{error:t,metrics:{}}}})(e,t)};fe(oi);let ni=!1;const si={get status(){return ot()},on:it,shutdown:()=>Ut({reason:"host_stop"}),get contributionState(){return Rn()},get activeModelId(){return Bn()},get deviceId(){return Y()?.deviceId??null},eligibleModels:Ln,switchModel:async e=>{const t="string"==typeof e?e.trim():"";if(!t)throw new Sn("invalid_model_id","modelId is blank");if(st()||!re())throw new Tn("stopped");let r=Vn??await Ln(),o=r.find(e=>e.modelId===t);if(o&&o.eligible||(r=await Ln(),o=r.find(e=>e.modelId===t)),!o)throw new $n(t,"not_offered");if(!o.eligible)throw new $n(t,o.reason??"not_eligible");if((e=>{kn(gn,e.trim())})(t),Bn()===t&&"contributing"===Rn())return{requestedModelId:t,activeModelId:t,granted:!0};if(rt())throw new Tn("stopped");En?.reject(new Sn("switch_superseded","a newer switch replaced this one"));const n=new Promise((e,r)=>{En={modelId:t,resolve:e,reject:r}});Pn=!0,k().info(`${Un} Switching model`,{to:t,from:Bn()??void 0}),ur(!0);try{await(async()=>{await cr(),mr()})();const e=X();J(void 0);try{e?.close(1e3,"switching")}catch{}Z("error"),Mt(),await(async()=>{const e=Y()?.adaptersByModelId??{};for(const t of Object.values(e))try{await(t.dispose?.())}catch{}D({})})()}finally{ur(!1)}return St("switch")||On(new Tn("stopped")),n},runLocal:async e=>{const t=Rn();if("contributing"!==t)throw new Tn(t,"declined"===t?te()??void 0:void 0);const r=Y(),o=Bn(),n=o?K(o):void 0,s=o?r?.modelInfosByModelId?.[o]:void 0;if(!o||!n||!s)throw new Tn("preparing");if(!e||"object"!=typeof e)throw new Sn("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&&ze(i)>a)throw new Sn("input_too_large",`input of about ${ze(i)} tokens exceeds the model's cap of ${a}`);const d=$e(),{value:l,queueWaitMs:c}=await(async e=>{ar+=1;const t=performance.now();try{await cr();const r=Math.round(performance.now()-t);try{return{value:await e(),queueWaitMs:r}}finally{mr()}}finally{ar-=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 d.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&&Rt(r),new An(r||"inference failed",e)}});return{response:l.output.output,modelId:o,modelVersion:s.modelVersion??"1",location:"device",runtime:s.inferenceFramework?.trim().toLowerCase()||void 0,queueWaitMs:c,processingMs:"number"==typeof l.output.inferenceMs?l.output.inferenceMs:l.processingMs}},clearModelChoice:()=>vn(),forgetUnfitModel:e=>(e=>{const t=_n(),r=t.filter(t=>t.modelId!==e);r.length!==t.length&&Mn(r)})(e)},ii=()=>si,ai=ii,di=async t=>{if(ni)return si;ni=!0,t?.resourcePolicy&&((e=>{Be=e??{},Re=je(null)})(t.resourcePolicy),t.resourcePolicy.disableGuardrails&&console.warn("[herogpu] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only."));const s=(t=>{const s=e,i=r(s,t??{});return{sdkVersion:o(i.sdkVersion,s.sdkVersion),orchestrator:{baseUrl:o(i.orchestrator?.baseUrl,s.orchestrator.baseUrl),registerPath:o(i.orchestrator?.registerPath,s.orchestrator.registerPath),eventsPath:o(i.orchestrator?.eventsPath,s.orchestrator.eventsPath)},telemetry:{enableConsoleLogs:n(i.telemetry?.enableConsoleLogs,s.telemetry.enableConsoleLogs),locationData:n(i.telemetry?.locationData,s.telemetry.locationData),events:n(i.telemetry?.events,s.telemetry.events)},inference:{worker:n(i.inference?.worker,s.inference.worker),...o(i.inference?.workerUrl,"")?{workerUrl:o(i.inference?.workerUrl,"")}:{}}}})(t?.overrides);(e=>{Jo={appId:Ho(e?.appId),appName:Ho(e?.appName),externalAppId:Ho(e?.externalAppId)}})(t),void 0!==t?.customParams&&(y(s.telemetry),nr(t.customParams));try{await Gn({config:s,appUserId:t?.appUserId,edgeOperatorKey:t?.edgeOperatorKey,deviceId:t?.deviceId})}catch(e){k().error("[Init] SDK initialization failed",{error:m(e)})}return si},li=e=>{nr(e)},ci="herogpu:consent",mi="zerogpu:consent",ui={optedIn:!0,updatedAt:null,source:"default"},fi=e=>{if(!e||"object"!=typeof e)return ui;const t=e;return"boolean"!=typeof t.optedIn?ui:{optedIn:t.optedIn,updatedAt:"string"==typeof t.updatedAt?t.updatedAt:null,source:"extension"===t.source||"settings-page"===t.source||"default"===t.source?t.source:"default"}},pi=[mi,ci];let gi;const hi=async()=>{const e="undefined"!=typeof chrome?chrome?.storage?.local:void 0;if(!e)return ui;try{const t=await e.get(pi);return fi(t?.[(e=>(gi=void 0!==e?.[mi],gi?mi:ci))(t)])}catch{return ui}};Promise.resolve();const wi=e=>e.endsWith("/")?e:`${e}/`,yi=e=>{if(!e)return null;const t=e.split(/[?#]/)[0].split("/").pop();return"herogpu-offscreen.js"===t?"herogpu":"zerogpu-offscreen.js"===t?"zerogpu":null},ki=(e,t)=>{const r=`vendor/${e}/`,o="undefined"!=typeof chrome&&chrome?.runtime?.getURL?wi(chrome.runtime.getURL(r)):r;return{assetsBaseUrl:t?wi(t):o,workerFile:`${e}-worker.js`}},bi=async e=>{try{const t=await fetch(e);return t.body?.cancel?.()?.catch?.(()=>{}),t.ok}catch{return!1}},Ii=({assetsBaseUrl:e,workerFile:t})=>{(e=>{const t={...to};for(const[r,o]of Object.entries(e))void 0!==o&&(t[r]=o);to=t})({transformersUrl:`${e}transformers.min.js`,wasmPaths:e,forceSingleThread:!0,workerUrl:`${e}${t}`})},vi=e=>{const t={...e.overrides??{}};return"boolean"==typeof e.enableConsoleLogs&&(t.telemetry={...t.telemetry??{},enableConsoleLogs:e.enableConsoleLogs}),e.orchestratorBaseUrl&&(t.orchestrator={...t.orchestrator??{},baseUrl:e.orchestratorBaseUrl}),"boolean"==typeof e.inferenceWorker&&(t.inference={...t.inference??{},worker:e.inferenceWorker}),t};let _i=null;const Mi=e=>{_i||(_i=(e=>{const t="undefined"!=typeof chrome?chrome?.storage?.onChanged:void 0;if(!t?.addListener)return()=>{};const r=(t,r)=>{if("local"!==r)return;const o=t?.[mi],n=t?.[ci];(o||n)&&(o&&(gi=void 0!==o.newValue),o&&gi?e(fi(o.newValue)):n&&!1===gi?e(fi(n.newValue)):hi().then(e,()=>{}))};return t.addListener(r),()=>t.removeListener?.(r)})(t=>{t.optedIn&&xi(e)}))},xi=async(e={})=>{if(Mi(e),!(await hi()).optedIn)return;const t=await(async e=>{const t=yi((()=>{try{return import.meta.url}catch{return}})());if(t)return ki(t,e);const r=ki("zerogpu",e);if("function"!=typeof fetch||"undefined"==typeof chrome||!chrome?.runtime?.getURL)return r;if(await bi(`${r.assetsBaseUrl}${r.workerFile}`))return r;const o=ki("herogpu",e);return await bi(`${o.assetsBaseUrl}${o.workerFile}`)?o:r})(e.assetsBaseUrl),{assetsBaseUrl:r}=t;var o;(e=>{const t="string"==typeof e?e.trim():"";if(zt=t||null,Wt=null,zt)try{Wt=new URL(zt).origin}catch{zt=null}Kt=null,Dt=!1})(!1===(o=e.trackingRunnerUrl)?null:"string"==typeof o&&o.trim()?o:"https://zerogpu-browser-sdk.pages.dev/tag-runner.html"),e.enableConsoleLogs||(()=>{const e=window;if(e.__zgpuConsoleSilenced)return;e.__zgpuConsoleSilenced=!0;const t=()=>{};console.log=t,console.info=t,console.debug=t,console.warn=t,console.error=t})(),Ii(t);try{await(async e=>{if(window.WllamaModule)return;const t=await import(`${e}wllama/index.js`);if(!t?.Wllama)throw new Error("wllama/index.js is missing the Wllama export");window.WllamaModule=t,window.WllamaWasmPaths={"single-thread/wllama.wasm":`${e}wllama/single-thread/wllama.wasm`,"multi-thread/wllama.wasm":`${e}wllama/multi-thread/wllama.wasm`}})(r)}catch(e){console.warn("[herogpu][offscreen] wllama runtime unavailable; GGUF models will be skipped.",e)}Bi(e),await di({edgeOperatorKey:e.edgeOperatorKey,appUserId:e.appUserId,deviceId:e.deviceId,customParams:e.customParams,appId:e.appId,appName:e.appName,externalAppId:e.externalAppId,overrides:vi(e)})},Si=xi,Ti={forceInit:He("forceInit"),getStatus:He("getStatus"),disable:He("disable"),setCustomParams:He("setCustomParams"),getContribution:He("getContribution"),eligibleModels:He("eligibleModels"),switchModel:He("switchModel"),runLocal:He("runLocal"),clearModelChoice:He("clearModelChoice"),forgetUnfitModel:He("forgetUnfitModel")},$i={forceInit:Xe("forceInit"),getStatus:Xe("getStatus"),disable:Xe("disable"),setCustomParams:Xe("setCustomParams"),getContribution:Xe("getContribution"),eligibleModels:Xe("eligibleModels"),switchModel:Xe("switchModel"),runLocal:Xe("runLocal"),clearModelChoice:Xe("clearModelChoice"),forgetUnfitModel:Xe("forgetUnfitModel")},Ai=He("event"),Ci=Xe("event"),Ui=["activeModelChanged","modelChoiceRefused","degraded","recovered","shutdown"];let Ei=!1;const Pi=()=>"undefined"!=typeof chrome?chrome?.runtime:void 0,Vi=(e,t)=>(Promise.resolve().then(t).then(t=>e({ok:!0,result:t}),t=>e({ok:!1,error:Cn(t)})),!0);let qi=null;const Bi=(e={})=>{if(qi)return qi;const t={status:"idle",initialized:!1,lastAttemptAt:null,lastSuccessAt:null,lastErrorAt:null,lastErrorMessage:"",orchestratorBaseUrl:e.orchestratorBaseUrl},r="undefined"!=typeof chrome?chrome?.runtime:void 0;if(!r?.onMessage?.addListener)return console.warn("[herogpu][offscreen] chrome.runtime.onMessage unavailable; messaging not registered."),t;qi=t;return(()=>{if(!Ei){Ei=!0;for(const e of Ui)it(e,t=>{for(const r of[Ai,Ci])try{Pi()?.sendMessage?.({type:r,event:e,detail:t})?.catch?.(()=>{})}catch{}})}})(),r.onMessage.addListener((r,o,n)=>{if(!r||"object"!=typeof r)return;const s=r,i=Ze(s.type);if(i===Ti.getStatus){const e=ii();return void n({ok:!0,state:{...t,contributionState:e.contributionState,activeModelId:e.activeModelId}})}if(i===Ti.getContribution){const e=ii();return void n({ok:!0,result:{contributionState:e.contributionState,activeModelId:e.activeModelId,status:e.status,deviceId:e.deviceId}})}return i===Ti.eligibleModels?Vi(n,()=>ii().eligibleModels()):i===Ti.switchModel?Vi(n,()=>ii().switchModel(String(s.modelId??""))):i===Ti.runLocal?Vi(n,()=>ii().runLocal(s.input&&"object"==typeof s.input?s.input:{})):i===Ti.clearModelChoice?Vi(n,()=>(ii().clearModelChoice(),!0)):i===Ti.forgetUnfitModel?Vi(n,()=>(ii().forgetUnfitModel(String(s.modelId??"")),!0)):i===Ti.forceInit?((async r=>{t.status="initializing",t.lastAttemptAt=(new Date).toISOString();try{await xi({...e,...r??{}}),t.status="running",t.initialized=!0,t.lastSuccessAt=(new Date).toISOString(),t.lastErrorMessage=""}catch(e){throw t.status="error",t.initialized=!1,t.lastErrorAt=(new Date).toISOString(),t.lastErrorMessage=e instanceof Error?e.message:String(e),e}})(s.config||void 0).then(()=>n({ok:!0,state:t})).catch(e=>n({ok:!1,state:t,error:e instanceof Error?e.message:String(e)})),!0):i===Ti.setCustomParams?(li(s.customParams??{}),void n({ok:!0})):void(i===Ti.disable&&Ut({reason:"host_stop"}))}),t},Ri=Bi,Li=()=>{qi=null,Ei=!1};export{Ai as HEROGPU_EVENT_MESSAGE,Ti as HEROGPU_OFFSCREEN_MESSAGES,Ci as ZEROGPU_EVENT_MESSAGE,$i as ZEROGPU_OFFSCREEN_MESSAGES,Li as __resetOffscreenMessaging,ii as getHeroGpuSdk,ai as getZeroGpuSdk,xi as initHeroGpuOffscreen,Si as initZeroGpuOffscreen,Bi as registerHeroGpuOffscreenMessaging,Ri as registerZeroGpuOffscreenMessaging,li as setCustomParams,yi as vendoredLayoutFromModuleUrl};
|