@neuvybe/jarvis 0.50.4 → 0.50.5
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/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -347,7 +347,7 @@ ${n.map(a=>`[${a}]`).join(`
|
|
|
347
347
|
`)}var Lxe,Fxe,Uxe,Oxe,$xe,RW=D(()=>{"use strict";ai();ew();xS();Lxe=2e3,Fxe=3e4,Uxe=5,Oxe="the search could not be completed",$xe=re.object({spoken_preamble:re.string().describe("one short sentence spoken aloud while this runs; on a parallel batch the first call carries the whole announcement and later calls leave this empty"),query:re.string().min(1).describe("the web search query"),max_results:re.number().int().min(1).max(10).optional().describe("how many results to return (default 5, max 10)"),detach:re.boolean().optional().describe("search as a background job: the call returns at once and the results arrive when they land")})});import{mkdirSync as Hxe,readdirSync as Vxe,rmSync as MW,statSync as Gxe,writeFileSync as Yxe}from"node:fs";import{tmpdir as LW}from"node:os";import{join as tN}from"node:path";var FW,qxe,pu,rN=D(()=>{"use strict";FW="jarvis-session-",qxe=1440*60*1e3,pu=class{logger;dir;used=!1;counter=0;constructor(e,r,i=LW()){this.logger=r,this.dir=tN(i,`${FW}${e}`)}spill(e,r){try{Hxe(this.dir,{recursive:!0}),this.used=!0,this.counter+=1;let i=tN(this.dir,`${e}-${this.counter}.md`);return Yxe(i,r,"utf8"),i}catch(i){return this.logger.debug("session scratch write failed - spill skipped",{errorName:i instanceof Error?i.name:typeof i}),null}}dispose(){if(this.used)try{MW(this.dir,{recursive:!0,force:!0})}catch(e){this.logger.debug("session scratch cleanup failed - startup sweep will retire it",{errorName:e instanceof Error?e.name:typeof e})}}static sweepStale(e,r=LW(),i=qxe,n=Date.now()){let s;try{s=Vxe(r)}catch{return}for(let o of s){if(!o.startsWith(FW))continue;let a=tN(r,o);try{n-Gxe(a).mtimeMs>i&&(MW(a,{recursive:!0,force:!0}),e.debug("swept stale session scratch dir",{name:o}))}catch{}}}}});var GE,UW=D(()=>{"use strict";GE=class{hooks=[];add(e){this.hooks.push(e)}async preTool(e,r){for(let i of this.hooks){if(!i.preTool)continue;let n;try{n=await i.preTool(e,r)}catch(s){return r.logger.debug("tool hook preTool threw - call denied (fail closed)",{tool:e.name,errorName:s instanceof Error?s.name:typeof s}),{allow:!1,reason:"tool call refused: a tool hook failed while judging it"}}if(!("allow"in n)||!n.allow)return n}return{allow:!0}}async postTool(e,r,i){let n=r;for(let s of this.hooks){if(!s.postTool)continue;let o;try{o=await s.postTool(e,n,i)}catch(a){return i.logger.debug("tool hook postTool threw - result withheld (fail closed)",{tool:e.name,errorName:a instanceof Error?a.name:typeof a}),{failed:"tool result withheld: a result hook failed while judging it"}}if("fail"in o)return{failed:o.fail};"replace"in o&&(n=o.replace)}return{result:n}}}});function OW(t){return{name:"dismiss_notification",description:"Remove a queued notification from the session state by its id, without saying anything. Use it once the conversation shows the user got the news, or when it is not worth saying. Dismissal never deletes the underlying result from the conversation.",inputSchema:jxe,tier:"read",execute:e=>Promise.resolve(t.dismiss(e.id)?{ok:!0,content:`notification ${e.id} dismissed`}:{ok:!1,error:"no queued notification has that id"})}}var YE,jxe,$W=D(()=>{"use strict";ai();YE=class{seq=0;items=new Map;add(e,r){this.seq+=1;let i=`n${this.seq}`;return this.items.set(i,{id:i,priority:r,text:e,announce:{state:"none"}}),i}dismiss(e){return this.items.delete(e)}annotate(e,r){let i=this.items.get(e);i!==void 0&&(i.announce=r)}list(){return[...this.items.values()].map(e=>({...e}))}isEmpty(){return this.items.size===0}},jxe=re.object({id:re.string().min(1).describe("the queued notification id from the session state (e.g. n1)")})});var qE,PW=D(()=>{"use strict";ai();qE=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`tool '${e.name}' is already registered`);this.tools.set(e.name,e)}get(e){return this.tools.get(e)}list(){return[...this.tools.values()]}modelFacing(){return this.list().map(e=>({name:e.name,description:e.description,inputSchema:re.toJSONSchema(e.inputSchema)}))}}});import*as zE from"node:path";function Wxe(t){if(typeof t!="object"||t===null)return;let e=t.path;return typeof e=="string"?e:void 0}function HW(t){return(process.platform==="win32"?t.toLowerCase().replace(/\//g,"\\"):t).replace(/[\\/]+$/,"")}function Jxe(t){return t.split(/[\\/]+/).at(-1)??t}function Kxe(t){let e=t;for(let r of Zxe)e=e.replace(r,VW);return e.replace(Xxe,`$1${VW}@`)}var zxe,jE,VW,Zxe,Xxe,GW=D(()=>{"use strict";zxe="path refused: it matches the secrets denylist (.env*, .jarvis, id_*, *.pem) - secret files never enter the model context",jE=class{resolvedHomeDir;refusal=zxe;constructor(e){if(this.resolvedHomeDir=e,e.trim().length===0)throw new Error("SecretsGuard requires the resolved jarvis home directory")}isDenied(e){let r=e.toLowerCase().split(/[\\/]+/);if(r.includes(".jarvis"))return!0;let i=r.at(-1)??"";return i.startsWith(".env")||i.startsWith("id_")||i.endsWith(".pem")?!0:this.isUnderHome(e)}preTool(e){let r=Wxe(e.input);return r!==void 0&&this.matchesPatterns(r)?{allow:!1,reason:this.refusal}:{allow:!0}}postTool(e,r,i){if(!r.ok)return{pass:!0};let n=Kxe(this.maskDeniedSources(r.content,i.cwd));return n===r.content?{pass:!0}:{replace:{...r,content:n}}}maskDeniedSources(e,r){return e.split(`
|
|
348
348
|
`).map(i=>{let n=this.deniedPathPrefix(i,r);return n===null?i:`${n}:<redacted: matches denied file ${Jxe(n)}>`}).join(`
|
|
349
349
|
`)}deniedPathPrefix(e,r){let i=-1;for(let n=0;n<4;n+=1){if(i=e.indexOf(":",i+1),i<=0)return null;let s=e.slice(0,i);if(this.isDenied(s)||this.isDenied(zE.resolve(r,s)))return s}return null}matchesPatterns(e){let r=e.toLowerCase().split(/[\\/]+/);if(r.includes(".jarvis"))return!0;let i=r.at(-1)??"";return i.startsWith(".env")||i.startsWith("id_")||i.endsWith(".pem")}isUnderHome(e){let r=HW(this.resolvedHomeDir),i=HW(e);return i===r||i.startsWith(r+zE.sep)}};VW="<redacted: secret-shaped value>",Zxe=[/-----BEGIN [A-Z0-9 ]+-----[\s\S]*?-----END [A-Z0-9 ]+-----/g,/-----BEGIN [A-Z0-9 ]+-----[\s\S]*$/g,/\b(?:sk-[A-Za-z0-9_-]{8,}|AKIA[0-9A-Z]{12,}|gh[po]_[A-Za-z0-9]{16,}|xox[a-z]-[A-Za-z0-9-]{8,}|AIza[A-Za-z0-9_-]{20,})\b/g],Xxe=/(:\/\/[^/\s:@]+:)(\S+)@/g});var WE,YW=D(()=>{"use strict";WE=class{buffer=[];pending=null;closed=!1;push(e){if(this.closed)return;let r=this.pending;if(r){this.pending=null,r({value:e,done:!1});return}this.buffer.push(e)}close(){if(this.closed)return;this.closed=!0;let e=this.pending;e&&(this.pending=null,e({value:void 0,done:!0}))}async*drain(){for(;;){if(this.buffer.length>0){yield this.buffer.shift();continue}if(this.closed)return;let e=await new Promise(r=>{this.pending=r});if(e.done)return;yield e.value}}}});var ebe,tbe,qW,Nh,nN=D(()=>{"use strict";ebe=new Set([".","!","?"]),tbe=new Set([",",";",":"]),qW={minClauseLength:12},Nh=class{buffer="";minClauseLength;constructor(e=qW){this.minClauseLength=e.minClauseLength}push(e){this.buffer+=e;let r=[];for(let i=this.findBoundary();i!==-1;i=this.findBoundary()){let n=this.buffer.slice(0,i+1).trim();this.buffer=this.buffer.slice(i+1).replace(/^\s+/,""),n.length>0&&r.push(n)}return r}flush(){let e=this.buffer.trim();return this.buffer="",e.length>0?[e]:[]}findBoundary(){for(let e=0;e<this.buffer.length;e++){let r=this.buffer[e];if(r===`
|
|
350
|
-
`)return e;let i=e+1<this.buffer.length?this.buffer[e+1]:"";if(i!==""&&/\s/.test(i)&&(ebe.has(r)||tbe.has(r)&&e+1>=this.minClauseLength))return e}return-1}}});var JE,Ka,mu,rbe,jW,iN=D(()=>{JE=new Map,Ka=[],mu=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let i=JE.get(t);if(i===void 0)JE.set(t,{backend:e,priority:r});else{if(i.priority>r)return;if(i.priority===r&&i.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Ka.indexOf(t);n!==-1&&Ka.splice(n,1);for(let s=0;s<Ka.length;s++)if(JE.get(Ka[s]).priority<=r){Ka.splice(s,0,t);return}Ka.push(t)}return}throw new TypeError("not a valid backend")},rbe=async t=>{let e=JE.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(i){return r||(e.error=`${i}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},jW=async t=>{let e=t.executionProviders||[],r=e.map(c=>typeof c=="string"?c:c.name),i=r.length===0?Ka:r,n,s=[],o=new Set;for(let c of i){let l=await rbe(c);typeof l=="string"?s.push({name:c,err:l}):(n||(n=l),n===l&&o.add(c))}if(!n)throw new Error(`no available backend found. ERR: ${s.map(c=>`[${c.name}] ${c.err}`).join(", ")}`);for(let{name:c,err:l}of s)r.includes(c)&&console.warn(`removing requested execution provider "${c}" from session options because it is not available: ${l}`);let a=e.filter(c=>o.has(typeof c=="string"?c:c.name));return[n,new Proxy(t,{get:(c,l)=>l==="executionProviders"?a:Reflect.get(c,l)})]}});var zW=D(()=>{iN()});var WW,JW=D(()=>{WW="1.26.0"});var ZW,Rt,sN=D(()=>{JW();ZW="warning",Rt={wasm:{},webgl:{},webgpu:{},versions:{common:WW},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);ZW=t}},get logLevel(){return ZW}};Object.defineProperty(Rt,"logLevel",{enumerable:!0})});var Et,XW=D(()=>{sN();Et=Rt});var KW,e9,t9=D(()=>{KW=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let i=r.getContext("2d");if(i!=null){let n,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],s=t.dims[3]):(n=t.dims[3],s=t.dims[2]);let o=e?.format!==void 0?e.format:"RGB",a=e?.norm,c,l;a===void 0||a.mean===void 0?c=[255,255,255,255]:typeof a.mean=="number"?c=[a.mean,a.mean,a.mean,a.mean]:(c=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(c[3]=a.mean[3])),a===void 0||a.bias===void 0?l=[0,0,0,0]:typeof a.bias=="number"?l=[a.bias,a.bias,a.bias,a.bias]:(l=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(l[3]=a.bias[3]));let u=s*n,d=0,h=u,A=u*2,f=-1;o==="RGBA"?(d=0,h=u,A=u*2,f=u*3):o==="RGB"?(d=0,h=u,A=u*2):o==="RBG"&&(d=0,A=u,h=u*2);for(let m=0;m<s;m++)for(let E=0;E<n;E++){let I=(t.data[d++]-l[0])*c[0],y=(t.data[h++]-l[1])*c[1],Q=(t.data[A++]-l[2])*c[2],v=f===-1?255:(t.data[f++]-l[3])*c[3];i.fillStyle="rgba("+I+","+y+","+Q+","+v+")",i.fillRect(E,m,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},e9=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(r!=null){let n,s,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],s=t.dims[1],o=t.dims[3]):(n=t.dims[3],s=t.dims[2],o=t.dims[1]);let a=e!==void 0&&e.format!==void 0?e.format:"RGB",c=e?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean=="number"?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias=="number"?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=s*n;if(e!==void 0&&(e.format!==void 0&&o===4&&e.format!=="RGBA"||o===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,A=0,f=1,m=2,E=3,I=0,y=d,Q=d*2,v=-1;a==="RGBA"?(I=0,y=d,Q=d*2,v=d*3):a==="RGB"?(I=0,y=d,Q=d*2):a==="RBG"&&(I=0,Q=d,y=d*2),i=r.createImageData(n,s);for(let S=0;S<s*n;A+=h,f+=h,m+=h,E+=h,S++)i.data[A]=(t.data[I++]-u[0])*l[0],i.data[f]=(t.data[y++]-u[1])*l[1],i.data[m]=(t.data[Q++]-u[2])*l[2],i.data[E]=v===-1?255:(t.data[v++]-u[3])*l[3]}else throw new Error("Can not access image data");return i}});var oN,r9,n9,i9,s9,o9,a9=D(()=>{ZE();oN=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:i}=e,n=e.norm??{mean:255,bias:0},s,o;typeof n.mean=="number"?s=[n.mean,n.mean,n.mean,n.mean]:s=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let a=e.format!==void 0?e.format:"RGBA",c=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",l=r*i,u=c==="RGBA"?new Float32Array(l*4):new Float32Array(l*3),d=4,h=0,A=1,f=2,m=3,E=0,I=l,y=l*2,Q=-1;a==="RGB"&&(d=3,h=0,A=1,f=2,m=-1),c==="RGBA"?Q=l*3:c==="RBG"?(E=0,y=l,I=l*2):c==="BGR"&&(y=0,I=l,E=l*2);for(let S=0;S<l;S++,h+=d,f+=d,A+=d,m+=d)u[E++]=(t[h]+o[0])/s[0],u[I++]=(t[A]+o[1])/s[1],u[y++]=(t[f]+o[2])/s[2],Q!==-1&&m!==-1&&(u[Q++]=(t[m]+o[3])/s[3]);return c==="RGBA"?new Xt("float32",u,[1,4,r,i]):new Xt("float32",u,[1,3,r,i])},r9=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,i=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,s=typeof t=="string",o,a=e??{},c=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},l=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=c();u.width=t.width,u.height=t.height;let d=l(u);if(d!=null){let h=t.height,A=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,A=e.resizedWidth),e!==void 0){if(a=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=h,a.width=A}else a.tensorFormat="RGBA",a.height=h,a.width=A;d.drawImage(t,0,0),o=d.getImageData(0,0,A,h).data}else throw new Error("Can not access image data")}else if(i){let u,d;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,d=e.resizedWidth):(u=t.height,d=t.width),e!==void 0&&(a=e),a.format="RGBA",a.height=u,a.width=d,e!==void 0){let h=c();h.width=d,h.height=u;let A=l(h);if(A!=null)A.putImageData(t,0,0),o=A.getImageData(0,0,d,u).data;else throw new Error("Can not access image data")}else o=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=c();u.width=t.width,u.height=t.height;let d=l(u);if(d!=null){let h=t.height,A=t.width;return d.drawImage(t,0,0,A,h),o=d.getImageData(0,0,A,h).data,a.height=h,a.width=A,oN(o,a)}else throw new Error("Can not access image data")}else{if(s)return new Promise((u,d)=>{let h=c(),A=l(h);if(!t||!A)return d();let f=new Image;f.crossOrigin="Anonymous",f.src=t,f.onload=()=>{h.width=f.width,h.height=f.height,A.drawImage(f,0,0,h.width,h.height);let m=A.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,u(oN(m.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return oN(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},n9=(t,e)=>{let{width:r,height:i,download:n,dispose:s}=e,o=[1,i,r,4];return new Xt({location:"texture",type:"float32",texture:t,dims:o,download:n,dispose:s})},i9=(t,e)=>{let{dataType:r,dims:i,download:n,dispose:s}=e;return new Xt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:i,download:n,dispose:s})},s9=(t,e)=>{let{dataType:r,dims:i,download:n,dispose:s}=e;return new Xt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:i,download:n,dispose:s})},o9=(t,e,r)=>new Xt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})});var ec,Rh,c9,l9,u9=D(()=>{ec=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Rh=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),c9=!1,l9=()=>{if(!c9){c9=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,i=typeof r<"u"&&r.from;t&&(ec.set("int64",BigInt64Array),Rh.set(BigInt64Array,"int64")),e&&(ec.set("uint64",BigUint64Array),Rh.set(BigUint64Array,"uint64")),i?(ec.set("float16",r),Rh.set(r,"float16")):ec.set("float16",Uint16Array)}}});var A9,d9,h9=D(()=>{ZE();A9=t=>{let e=1;for(let r=0;r<t.length;r++){let i=t[r];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${r}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${i}`);e*=i}return e},d9=(t,e)=>{switch(t.location){case"cpu":return new Xt(t.type,t.data,e);case"cpu-pinned":return new Xt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Xt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Xt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Xt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}});var Xt,ZE=D(()=>{t9();a9();u9();h9();Xt=class{constructor(e,r,i){l9();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let a=ec.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,c;if(typeof e=="string")if(n=e,c=i,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");a=r}else{let l=ec.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?a=l.from(r,BigInt):a=l.from(r)}else if(r instanceof l)a=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")a=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(c=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")n="string",a=e;else if(l==="boolean")n="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(e);else{let l=Rh.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=l,a=e}if(c===void 0)c=[a.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");s=c,this.cpuData=a,this.dataLocation="cpu"}let o=A9(s);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=o}static async fromImage(e,r){return r9(e,r)}static fromTexture(e,r){return n9(e,r)}static fromGpuBuffer(e,r){return i9(e,r)}static fromMLTensor(e,r){return s9(e,r)}static fromPinnedBuffer(e,r,i){return o9(e,r,i)}toDataURL(e){return KW(this,e)}toImageData(e){return e9(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return d9(this,e)}}});var Dn,aN=D(()=>{ZE();Dn=Xt});var cN,f9,vo,So,Do,_o,lN=D(()=>{sN();cN=(t,e)=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||console.timeStamp(`${t}::ORT::${e}`)},f9=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let n=0;n<r.length;n++){if(i&&!r[n].includes("TRACE_FUNC")){let s=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(s+=`::${e}`),cN("CPU",s);return}r[n].includes("TRACE_FUNC")&&(i=!0)}},vo=t=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||f9("BEGIN",t)},So=t=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||f9("END",t)},Do=t=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||console.time(`ORT::${t}`)},_o=t=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||console.timeEnd(`ORT::${t}`)}});var XE,g9=D(()=>{iN();aN();lN();XE=class t{constructor(e){this.handler=e}async run(e,r,i){vo(),Do("InferenceSession.run");let n={},s={};if(typeof e!="object"||e===null||e instanceof Dn||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Dn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let l of r){if(typeof l!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(l)===-1)throw new RangeError(`'fetches' contains invalid output name: ${l}.`);n[l]=null}if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let l=!1,u=Object.getOwnPropertyNames(r);for(let d of this.outputNames)if(u.indexOf(d)!==-1){let h=r[d];(h===null||h instanceof Dn)&&(l=!0,o=!1,n[d]=h)}if(l){if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let l of this.inputNames)if(typeof e[l]>"u")throw new Error(`input '${l}' is missing in 'feeds'.`);if(o)for(let l of this.outputNames)n[l]=null;let a=await this.handler.run(e,n,s),c={};for(let l in a)if(Object.hasOwnProperty.call(a,l)){let u=a[l];u instanceof Dn?c[l]=u:c[l]=new Dn(u.type,u.data,u.dims)}return _o("InferenceSession.run"),So(),c}async release(){return this.handler.dispose()}static async create(e,r,i,n){vo(),Do("InferenceSession.create");let s,o={};if(typeof e=="string"){if(s=e,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,d=0,h=e.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(d=r,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(h=e.byteLength-d,typeof i=="number"){if(h=i,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||d+h>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-d}].`);if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(u,d,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,c]=await jW(o),l=await a.createInferenceSessionHandler(s,c);return _o("InferenceSession.create"),So(),new t(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}});var p9,m9=D(()=>{g9();p9=XE});var E9=D(()=>{});var I9=D(()=>{});var y9=D(()=>{});var C9=D(()=>{});var uN={};An(uN,{InferenceSession:()=>p9,TRACE:()=>cN,TRACE_EVENT_BEGIN:()=>Do,TRACE_EVENT_END:()=>_o,TRACE_FUNC_BEGIN:()=>vo,TRACE_FUNC_END:()=>So,Tensor:()=>Dn,env:()=>Et,registerBackend:()=>mu});var ko=D(()=>{zW();XW();m9();aN();E9();I9();lN();y9();C9()});var dJ={};An(dJ,{InferenceSession:()=>p9,TRACE:()=>cN,TRACE_EVENT_BEGIN:()=>Do,TRACE_EVENT_END:()=>_o,TRACE_FUNC_BEGIN:()=>vo,TRACE_FUNC_END:()=>So,Tensor:()=>Dn,default:()=>pbe,env:()=>Et,registerBackend:()=>mu});import{createRequire as nbe}from"module";var Eu,QN,ibe,sbe,obe,CN,_n,abe,cbe,lbe,Cu,wN,AN,B9,x9,gs,U9,dN,b9,Q9,w9,v9,hN,O9,$9,fN,KE,Mh,gN,S9,D9,_9,P9,ct,Lh,Wn,rI,rt,vN,H9,ube,k9,T9,N9,tc,R9,V9,Abe,Iu,tI,yu,G9,Y9,SN,DN,q9,j9,nI,z9,M9,W9,J9,rc,L9,pN,BN,Z9,X9,mN,K9,eJ,dbe,eI,EN,IN,tJ,rJ,nJ,iJ,sJ,oJ,aJ,cJ,yN,F9,lJ,hbe,uJ,xN,bN,AJ,fbe,gbe,pbe,hJ=D(()=>{ko();ko();ko();ko();ko();ko();ko();Eu=nbe(import.meta.url),QN=Object.defineProperty,ibe=Object.getOwnPropertyDescriptor,sbe=Object.getOwnPropertyNames,obe=Object.prototype.hasOwnProperty,CN=(t=>typeof Eu<"u"?Eu:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Eu<"u"?Eu:e)[r]}):t)(function(t){if(typeof Eu<"u")return Eu.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),_n=(t,e)=>()=>(t&&(e=t(t=0)),e),abe=(t,e)=>{for(var r in e)QN(t,r,{get:e[r],enumerable:!0})},cbe=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of sbe(e))!obe.call(t,n)&&n!==r&&QN(t,n,{get:()=>e[n],enumerable:!(i=ibe(e,n))||i.enumerable});return t},lbe=t=>cbe(QN({},"__esModule",{value:!0}),t),wN=_n(()=>{"use strict";Cu=!!(typeof process<"u"&&process.versions&&process.versions.node)}),$9=_n(()=>{"use strict";wN(),AN=Cu||typeof location>"u"?void 0:location.origin,B9=import.meta.url>"file:"&&import.meta.url<"file;",x9=()=>{if(!Cu){if(B9){let t=URL;return new URL(new t("ort.node.min.mjs",import.meta.url).href,AN).href}return import.meta.url}},gs=x9(),U9=()=>{if(gs&&!gs.startsWith("blob:"))return gs.substring(0,gs.lastIndexOf("/")+1)},dN=(t,e)=>{try{let r=e??gs;return(r?new URL(t,r):new URL(t)).origin===AN}catch{return!1}},b9=(t,e)=>{let r=e??gs;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},Q9=(t,e)=>`${e??"./"}${t}`,w9=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},v9=async t=>(await import(t)).default,hN=void 0,O9=async(t,e,r,i)=>{let n=hN&&!(t||e);if(n)if(gs)n=dN(gs)||i&&!r;else if(i&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,hN];{let s="ort-wasm-simd-threaded.mjs",o=t??b9(s,e),a=!Cu&&r&&o&&!dN(o,e),c=a?await w9(o):o??Q9(s,e);return[a?c:void 0,await v9(c)]}}}),Lh=_n(()=>{"use strict";$9(),KE=!1,Mh=!1,gN=!1,S9=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},D9=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},_9=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},P9=async t=>{if(KE)return Promise.resolve();if(Mh)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gN)throw new Error("previous call to 'initializeWebAssembly()' failed.");Mh=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!_9())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!D9())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=S9();r>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,s=typeof n=="string"?n:void 0,o=n?.mjs,a=o?.href??o,c=n?.wasm,l=c?.href??c,u=t.wasmBinary,[d,h]=await O9(a,s,r>1,!!u||!!l),A=!1,f=[];if(e>0&&f.push(new Promise(m=>{setTimeout(()=>{A=!0,m()},e)})),f.push(new Promise((m,E)=>{let I={numThreads:r};if(u)I.wasmBinary=u,I.locateFile=y=>y;else if(l||s)I.locateFile=y=>l??s+y;else if(a&&a.indexOf("blob:")!==0)I.locateFile=y=>new URL(y,a).href;else if(d){let y=U9();y&&(I.locateFile=Q=>y+Q)}h(I).then(y=>{Mh=!1,KE=!0,fN=y,m(),d&&URL.revokeObjectURL(d)},y=>{Mh=!1,gN=!0,E(y)})})),await Promise.race(f),A)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},ct=()=>{if(KE&&fN)return fN;throw new Error("WebAssembly is not initialized yet.")}}),vN=_n(()=>{"use strict";Lh(),Wn=(t,e)=>{let r=ct(),i=r.lengthBytesUTF8(t)+1,n=r._malloc(i);return r.stringToUTF8(t,n,i),e.push(n),n},rI=(t,e,r,i)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,s])=>{let o=e?e+n:n;if(typeof s=="object")rI(s,o+".",r,i);else if(typeof s=="string"||typeof s=="number")i(o,s.toString());else if(typeof s=="boolean")i(o,s?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof s}`)})},rt=t=>{let e=ct(),r=e.stackSave();try{let i=e.PTR_SIZE,n=e.stackAlloc(2*i);e._OrtGetLastError(n,n+i);let s=Number(e.getValue(n,i===4?"i32":"i64")),o=e.getValue(n+i,"*"),a=o?e.UTF8ToString(o):"";throw new Error(`${t} ERROR_CODE: ${s}, ERROR_MESSAGE: ${a}`)}finally{e.stackRestore(r)}}}),ube=_n(()=>{"use strict";Lh(),vN(),H9=t=>{let e=ct(),r=0,i=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let s=0;return t?.tag!==void 0&&(s=Wn(t.tag,i)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&rt("Can't create run options."),t?.extra!==void 0&&rI(t.extra,"",new WeakSet,(o,a)=>{let c=Wn(o,i),l=Wn(a,i);e._OrtAddRunConfigEntry(r,c,l)!==0&&rt(`Can't set a run config entry: ${o} - ${a}.`)}),[r,i]}catch(s){throw r!==0&&e._OrtReleaseRunOptions(r),i.forEach(o=>e._free(o)),s}}}),Abe=_n(()=>{"use strict";Lh(),vN(),k9=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},T9=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},N9=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},tc=(t,e,r,i)=>{let n=Wn(e,i),s=Wn(r,i);ct()._OrtAddSessionConfigEntry(t,n,s)!==0&&rt(`Can't set a session config entry: ${e} - ${r}.`)},R9=async(t,e,r)=>{let i=e.executionProviders;for(let n of i){let s=typeof n=="string"?n:n.name,o=[];switch(s){case"webnn":if(s="WEBNN",tc(t,"session.disable_quant_qdq","1",r),tc(t,"session.disable_qdq_constant_folding","1",r),typeof n!="string"){let d=n?.deviceType;d&&tc(t,"deviceType",d,r)}break;case"webgpu":if(s="JS",typeof n!="string"){let d=n;if(d?.preferredLayout){if(d.preferredLayout!=="NCHW"&&d.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${d.preferredLayout}`);tc(t,"preferredLayout",d.preferredLayout,r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Wn(s,r),c=o.length,l=0,u=0;if(c>0){l=ct()._malloc(c*ct().PTR_SIZE),r.push(l),u=ct()._malloc(c*ct().PTR_SIZE),r.push(u);for(let d=0;d<c;d++)ct().setValue(l+d*ct().PTR_SIZE,o[d][0],"*"),ct().setValue(u+d*ct().PTR_SIZE,o[d][1],"*")}await ct()._OrtAppendExecutionProvider(t,a,l,u,c)!==0&&rt(`Can't append execution provider: ${s}.`)}},V9=async t=>{let e=ct(),r=0,i=[],n=t||{};N9(n);try{let s=k9(n.graphOptimizationLevel??"all"),o=T9(n.executionMode??"sequential"),a=typeof n.logId=="string"?Wn(n.logId,i):0,c=n.logSeverityLevel??2;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log severity level is not valid: ${c}`);let l=n.logVerbosityLevel??0;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log verbosity level is not valid: ${l}`);let u=typeof n.optimizedModelFilePath=="string"?Wn(n.optimizedModelFilePath,i):0;if(r=e._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,a,c,l,u),r===0&&rt("Can't create session options."),n.executionProviders&&await R9(r,n,i),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);tc(r,"enableGraphCapture",n.enableGraphCapture.toString(),i)}if(n.freeDimensionOverrides)for(let[d,h]of Object.entries(n.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let A=Wn(d,i);e._OrtAddFreeDimensionOverride(r,A,h)!==0&&rt(`Can't set a free dimension override: ${d} - ${h}.`)}return n.extra!==void 0&&rI(n.extra,"",new WeakSet,(d,h)=>{tc(r,d,h,i)}),[r,i]}catch(s){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&rt("Can't release session options."),i.forEach(o=>e._free(o)),s}}}),j9=_n(()=>{"use strict";Iu=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},tI=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},yu=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],i=typeof e=="number"?e:e.reduce((n,s)=>n*s,1);return r>0?Math.ceil(i*r):void 0},G9=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Y9=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},SN=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",DN=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",q9=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),z9=_n(()=>{"use strict";wN(),nI=async t=>{if(typeof t=="string")if(Cu)try{let{readFile:e}=CN("node:fs/promises");return new Uint8Array(await e(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let{createReadStream:r}=CN("node:fs"),i=r(t),n=[];for await(let s of i)n.push(s);return new Uint8Array(Buffer.concat(n))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),i=r?parseInt(r,10):0;if(i<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),s;try{s=new ArrayBuffer(i)}catch(a){if(a instanceof RangeError){let c=Math.ceil(i/65536);s=new WebAssembly.Memory({initial:c,maximum:c}).buffer}else throw a}let o=0;for(;;){let{done:a,value:c}=await n.read();if(a)break;let l=c.byteLength;new Uint8Array(s,o,l).set(c),o+=l}return new Uint8Array(s,0,i)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),dbe=_n(()=>{"use strict";ube(),Abe(),j9(),Lh(),vN(),z9(),M9=(t,e)=>{ct()._OrtInit(t,e)!==0&&rt("Can't initialize onnxruntime.")},W9=async t=>{M9(t.wasm.numThreads,Y9(t.logLevel))},J9=async(t,e)=>{ct().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=t.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},rc=new Map,L9=t=>{let e=ct(),r=e.stackSave();try{let i=e.PTR_SIZE,n=e.stackAlloc(2*i);e._OrtGetInputOutputCount(t,n,n+i)!==0&&rt("Can't get session input/output count.");let s=i===4?"i32":"i64";return[Number(e.getValue(n,s)),Number(e.getValue(n+i,s))]}finally{e.stackRestore(r)}},pN=(t,e)=>{let r=ct(),i=r.stackSave(),n=0;try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputMetadata(t,e,o,o+s)!==0&&rt("Can't get session input/output metadata.");let a=Number(r.getValue(o,"*"));n=Number(r.getValue(o+s,"*"));let c=r.HEAP32[n/4];if(c===0)return[a,0];let l=r.HEAPU32[n/4+1],u=[];for(let d=0;d<l;d++){let h=Number(r.getValue(n+8+d*s,"*"));u.push(h!==0?r.UTF8ToString(h):Number(r.getValue(n+8+(d+l)*s,"*")))}return[a,c,u]}finally{r.stackRestore(i),n!==0&&r._OrtFree(n)}},BN=t=>{let e=ct(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Z9=async(t,e)=>{let r,i,n=ct();Array.isArray(t)?[r,i]=t:t.buffer===n.HEAPU8.buffer?[r,i]=[t.byteOffset,t.byteLength]:[r,i]=BN(t);let s=0,o=0,a=0,c=[],l=[],u=[];try{if([o,c]=await V9(e),e?.externalData&&n.mountExternalData){let Q=[];for(let v of e.externalData){let S=typeof v=="string"?v:v.path;Q.push(nI(typeof v=="string"?v:v.data).then(F=>{n.mountExternalData(S,F)}))}await Promise.all(Q)}for(let Q of e?.executionProviders??[])if((typeof Q=="string"?Q:Q.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof Q!="string"){let v=Q,S=v?.context,F=v?.gpuDevice,M=v?.deviceType,$=v?.powerPreference;S?n.currentContext=S:F?n.currentContext=await n.webnnCreateMLContext(F):n.currentContext=await n.webnnCreateMLContext({deviceType:M,powerPreference:$})}else n.currentContext=await n.webnnCreateMLContext();break}s=await n._OrtCreateSession(r,i,o),n.webgpuOnCreateSession?.(s),s===0&&rt("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(s,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[d,h]=L9(s),A=!!e?.enableGraphCapture,f=[],m=[],E=[],I=[],y=[];for(let Q=0;Q<d;Q++){let[v,S,F]=pN(s,Q);v===0&&rt("Can't get an input name."),l.push(v);let M=n.UTF8ToString(v);f.push(M),E.push(S===0?{name:M,isTensor:!1}:{name:M,isTensor:!0,type:tI(S),shape:F})}for(let Q=0;Q<h;Q++){let[v,S,F]=pN(s,Q+d);v===0&&rt("Can't get an output name."),u.push(v);let M=n.UTF8ToString(v);m.push(M),I.push(S===0?{name:M,isTensor:!1}:{name:M,isTensor:!0,type:tI(S),shape:F})}return rc.set(s,[s,l,u,null,A,!1]),[s,f,m,E,I]}catch(d){throw l.forEach(h=>n._OrtFree(h)),u.forEach(h=>n._OrtFree(h)),a!==0&&n._OrtReleaseBinding(a)!==0&&rt("Can't release IO binding."),s!==0&&n._OrtReleaseSession(s)!==0&&rt("Can't release session."),d}finally{n._free(r),o!==0&&n._OrtReleaseSessionOptions(o)!==0&&rt("Can't release session options."),c.forEach(d=>n._free(d)),n.unmountExternalData?.()}},X9=t=>{let e=ct(),r=rc.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[i,n,s,o,a]=r;o&&(a&&e._OrtClearBoundOutputs(o.handle)!==0&&rt("Can't clear bound outputs."),e._OrtReleaseBinding(o.handle)!==0&&rt("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(c=>e._OrtFree(c)),s.forEach(c=>e._OrtFree(c)),e._OrtReleaseSession(i)!==0&&rt("Can't release session."),rc.delete(t)},mN=async(t,e,r,i,n,s,o=!1)=>{if(!t){e.push(0);return}let a=ct(),c=a.PTR_SIZE,l=t[0],u=t[1],d=t[3],h=d,A,f;if(l==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let I=t[2].gpuBuffer;f=yu(Iu(l),u);{let y=a.jsepRegisterBuffer;if(!y)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=y(i,s,I,f)}}else if(d==="ml-tensor"){let I=t[2].mlTensor;f=yu(Iu(l),u);let y=a.webnnRegisterMLTensor;if(!y)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=y(i,I,Iu(l),u)}else{let I=t[2];if(Array.isArray(I)){f=c*I.length,A=a._malloc(f),r.push(A);for(let y=0;y<I.length;y++){if(typeof I[y]!="string")throw new TypeError(`tensor data at index ${y} is not a string`);a.setValue(A+y*c,Wn(I[y],r),"*")}}else{let y=a.webnnIsGraphInput,Q=a.webnnIsGraphOutput;if(l!=="string"&&y&&Q){let v=a.UTF8ToString(n);if(y(i,v)||Q(i,v)){let S=Iu(l);f=yu(S,u),h="ml-tensor";let F=a.webnnCreateTemporaryTensor,M=a.webnnUploadTensor;if(!F||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let $=await F(i,S,u);M($,new Uint8Array(I.buffer,I.byteOffset,I.byteLength)),A=$}else f=I.byteLength,A=a._malloc(f),r.push(A),a.HEAPU8.set(new Uint8Array(I.buffer,I.byteOffset,f),A)}else f=I.byteLength,A=a._malloc(f),r.push(A),a.HEAPU8.set(new Uint8Array(I.buffer,I.byteOffset,f),A)}}let m=a.stackSave(),E=a.stackAlloc(4*u.length);try{u.forEach((y,Q)=>a.setValue(E+Q*c,y,c===4?"i32":"i64"));let I=a._OrtCreateTensor(Iu(l),A,f,E,u.length,q9(h));I===0&&rt(`Can't create tensor for input/output. session=${i}, index=${s}.`),e.push(I)}finally{a.stackRestore(m)}},K9=async(t,e,r,i,n,s)=>{let o=ct(),a=o.PTR_SIZE,c=rc.get(t);if(!c)throw new Error(`cannot run inference. invalid session id: ${t}`);let l=c[0],u=c[1],d=c[2],h=c[3],A=c[4],f=c[5],m=e.length,E=i.length,I=0,y=[],Q=[],v=[],S=[],F=[],M=o.stackSave(),$=o.stackAlloc(m*a),L=o.stackAlloc(m*a),se=o.stackAlloc(E*a),_=o.stackAlloc(E*a);try{[I,y]=H9(s),Do("wasm prepareInputOutputTensor");for(let P=0;P<m;P++)await mN(r[P],Q,S,t,u[e[P]],e[P],A);for(let P=0;P<E;P++)await mN(n[P],v,S,t,d[i[P]],m+i[P],A);_o("wasm prepareInputOutputTensor");for(let P=0;P<m;P++)o.setValue($+P*a,Q[P],"*"),o.setValue(L+P*a,u[e[P]],"*");for(let P=0;P<E;P++)o.setValue(se+P*a,v[P],"*"),o.setValue(_+P*a,d[i[P]],"*");o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let fe;fe=await o._OrtRun(l,L,$,m,_,E,se,I),fe!==0&&rt("failed to call OrtRun().");let Qe=[],x=[];Do("wasm ProcessOutputTensor");for(let P=0;P<E;P++){let _e=Number(o.getValue(se+P*a,"*"));if(_e===v[P]||F.includes(v[P])){Qe.push(n[P]),_e!==v[P]&&o._OrtReleaseTensor(_e)!==0&&rt("Can't release tensor.");continue}let dt=o.stackSave(),Je=o.stackAlloc(4*a),Rn=!1,Ce,Ht=0;try{o._OrtGetTensorData(_e,Je,Je+a,Je+2*a,Je+3*a)!==0&&rt(`Can't access output tensor data on index ${P}.`);let bs=a===4?"i32":"i64",Qs=Number(o.getValue(Je,bs));Ht=o.getValue(Je+a,"*");let q=o.getValue(Je+a*2,"*"),Zn=Number(o.getValue(Je+a*3,bs)),tr=[];for(let St=0;St<Zn;St++)tr.push(Number(o.getValue(q+St*a,bs)));o._OrtFree(q)!==0&&rt("Can't free memory for tensor dims.");let $r=tr.reduce((St,it)=>St*it,1);Ce=tI(Qs);let De=h?.outputPreferredLocations[i[P]];if(Ce==="string"){if(De==="gpu-buffer"||De==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let St=[];for(let it=0;it<$r;it++){let an=o.getValue(Ht+it*a,"*"),Xn=o.getValue(Ht+(it+1)*a,"*"),fy=it===$r-1?void 0:Xn-an;St.push(o.UTF8ToString(an,fy))}Qe.push([Ce,tr,St,"cpu"])}else if(De==="gpu-buffer"&&$r>0){let St=o.jsepGetBuffer;if(!St)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let it=St(Ht),an=yu(Qs,$r);if(an===void 0||!SN(Ce))throw new Error(`Unsupported data type: ${Ce}`);Rn=!0,Qe.push([Ce,tr,{gpuBuffer:it,download:o.jsepCreateDownloader(it,an,Ce),dispose:()=>{o._OrtReleaseTensor(_e)!==0&&rt("Can't release tensor.")}},"gpu-buffer"])}else if(De==="ml-tensor"&&$r>0){let St=o.webnnEnsureTensor,it=o.webnnIsGraphInputOutputTypeSupported;if(!St||!it)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(yu(Qs,$r)===void 0||!DN(Ce))throw new Error(`Unsupported data type: ${Ce}`);if(!it(t,Ce,!1))throw new Error(`preferredLocation "ml-tensor" for ${Ce} output is not supported by current WebNN Context.`);let an=await St(t,Ht,Qs,tr,!1);Rn=!0,Qe.push([Ce,tr,{mlTensor:an,download:o.webnnCreateMLTensorDownloader(Ht,Ce),dispose:()=>{o.webnnReleaseTensorId(Ht),o._OrtReleaseTensor(_e)}},"ml-tensor"])}else if(De==="ml-tensor-cpu-output"&&$r>0){let St=o.webnnCreateMLTensorDownloader(Ht,Ce)(),it=Qe.length;Rn=!0,x.push((async()=>{let an=[it,await St];return o.webnnReleaseTensorId(Ht),o._OrtReleaseTensor(_e),an})()),Qe.push([Ce,tr,[],"cpu"])}else{let St=G9(Ce),it=new St($r);new Uint8Array(it.buffer,it.byteOffset,it.byteLength).set(o.HEAPU8.subarray(Ht,Ht+it.byteLength)),Qe.push([Ce,tr,it,"cpu"])}}finally{o.stackRestore(dt),Ce==="string"&&Ht&&o._free(Ht),Rn||o._OrtReleaseTensor(_e)}}h&&!A&&(o._OrtClearBoundOutputs(h.handle)!==0&&rt("Can't clear bound outputs."),rc.set(t,[l,u,d,h,A,!1]));for(let[P,_e]of await Promise.all(x))Qe[P][2]=_e;return _o("wasm ProcessOutputTensor"),Qe}finally{o.webnnOnRunEnd?.(l),o.stackRestore(M),Q.forEach(fe=>o._OrtReleaseTensor(fe)),v.forEach(fe=>o._OrtReleaseTensor(fe)),S.forEach(fe=>o._free(fe)),I!==0&&o._OrtReleaseRunOptions(I),y.forEach(fe=>o._free(fe))}},eJ=t=>{let e=ct(),r=rc.get(t);if(!r)throw new Error("invalid session id");let i=r[0],n=e._OrtEndProfiling(i);n===0&&rt("Can't get an profile file name."),e._OrtFree(n)}}),cJ=_n(()=>{"use strict";dbe(),Lh(),$9(),eI=!1,EN=!1,IN=!1,tJ=async()=>{if(!EN){if(eI)throw new Error("multiple calls to 'initWasm()' detected.");if(IN)throw new Error("previous call to 'initWasm()' failed.");eI=!0;try{await P9(Et.wasm),await W9(Et),EN=!0}catch(t){throw IN=!0,t}finally{eI=!1}}},rJ=async t=>{await J9(Et,t)},nJ=async t=>BN(t),iJ=async(t,e)=>Z9(t,e),sJ=async t=>{X9(t)},oJ=async(t,e,r,i,n,s)=>K9(t,e,r,i,n,s),aJ=async t=>{eJ(t)}}),hbe=_n(()=>{"use strict";cJ(),j9(),wN(),z9(),yN=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},F9=t=>{switch(t[3]){case"cpu":return new Dn(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!SN(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:i,dispose:n}=t[2];return Dn.fromGpuBuffer(r,{dataType:e,dims:t[1],download:i,dispose:n})}case"ml-tensor":{let e=t[0];if(!DN(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:i,dispose:n}=t[2];return Dn.fromMLTensor(r,{dataType:e,dims:t[1],download:i,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},lJ=class{async fetchModelAndCopyToWasmMemory(t){return nJ(await nI(t))}async loadModel(t,e){vo();let r;typeof t=="string"?Cu?r=await nI(t):r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await iJ(r,e),So()}async dispose(){return sJ(this.sessionId)}async run(t,e,r){vo();let i=[],n=[];Object.entries(t).forEach(d=>{let h=d[0],A=d[1],f=this.inputNames.indexOf(h);if(f===-1)throw new Error(`invalid input '${h}'`);i.push(A),n.push(f)});let s=[],o=[];Object.entries(e).forEach(d=>{let h=d[0],A=d[1],f=this.outputNames.indexOf(h);if(f===-1)throw new Error(`invalid output '${h}'`);s.push(A),o.push(f)});let a=i.map((d,h)=>yN(d,()=>`input "${this.inputNames[n[h]]}"`)),c=s.map((d,h)=>d?yN(d,()=>`output "${this.outputNames[o[h]]}"`):null),l=await oJ(this.sessionId,n,a,o,c,r),u={};for(let d=0;d<l.length;d++)u[this.outputNames[o[d]]]=s[d]??F9(l[d]);return So(),u}startProfiling(){}endProfiling(){aJ(this.sessionId)}}}),uJ={};abe(uJ,{OnnxruntimeWebAssemblyBackend:()=>bN,initializeFlags:()=>xN,wasmBackend:()=>AJ});fbe=_n(()=>{"use strict";cJ(),hbe(),xN=()=>{(typeof Et.wasm.initTimeout!="number"||Et.wasm.initTimeout<0)&&(Et.wasm.initTimeout=0);let t=Et.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Et.wasm.simd=!1),typeof Et.wasm.proxy!="boolean"&&(Et.wasm.proxy=!1),typeof Et.wasm.trace!="boolean"&&(Et.wasm.trace=!1),typeof Et.wasm.numThreads!="number"||!Number.isInteger(Et.wasm.numThreads)||Et.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Et.wasm.numThreads=1;else{let e=typeof navigator>"u"?CN("node:os").cpus().length:navigator.hardwareConcurrency;Et.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},bN=class{async init(t){xN(),await tJ(),await rJ(t)}async createInferenceSessionHandler(t,e){let r=new lJ;return await r.loadModel(t,e),r}},AJ=new bN}),gbe="1.26.0",pbe=uN;{let t=(fbe(),lbe(uJ)).wasmBackend;mu("cpu",t,10),mu("wasm",t,10)}Object.defineProperty(Et.versions,"web",{value:gbe,enumerable:!0})});import{existsSync as mbe}from"node:fs";import{createRequire as Ebe}from"node:module";import{dirname as Ibe,join as ybe,sep as fJ}from"node:path";import{fileURLToPath as Cbe,pathToFileURL as Bbe}from"node:url";async function iI(){let t=await Promise.resolve().then(()=>(hJ(),dJ));return t.default??t}function sI(t,e){t.env.wasm.numThreads=1,t.env.wasm.wasmPaths=bbe(e)}function xbe(t){return[new URL("./",t),new URL("../",t)].map(e=>Cbe(e))}function bbe(t=import.meta.url){let e=xbe(t);try{e.push(Ibe(Ebe(t).resolve("onnxruntime-web")))}catch{}let r=null;for(let i of e){let n=gJ.filter(s=>!mbe(ybe(i,s)));if(n.length===0)return Qbe(i);n.length<gJ.length&&r===null&&(r={dir:i,missing:n})}throw r!==null?new Error(`ort-web WASM runtime at '${r.dir}' is missing '${r.missing.join("', '")}' - the .wasm and its .mjs glue must be copied together`):new Error(`ort-web WASM runtime ('${pJ}' + '${mJ}') not found beside the bundle or in node_modules`)}function Qbe(t){return Bbe(t.endsWith(fJ)?t:t+fJ).href}var pJ,mJ,gJ,_N=D(()=>{"use strict";pJ="ort-wasm-simd-threaded.wasm",mJ="ort-wasm-simd-threaded.mjs",gJ=[pJ,mJ]});import{existsSync as wbe}from"node:fs";import{fileURLToPath as vbe}from"node:url";function kN(t,e){return[new URL(`../../assets/${t}`,e),new URL(`./assets/${t}`,e),new URL(`../assets/${t}`,e)].map(r=>vbe(r))}function oI(t,e,r,i={}){let n=i.baseUrl??r,s=i.exists??wbe,o="envPath"in i?i.envPath:process.env[e];if(o&&s(o))return o;let a=kN(t,n);for(let c of a)if(s(c))return c;throw new Error(`model '${t}' not found. Tried: ${a.join(", ")}. Set ${e} to override.`)}var TN=D(()=>{"use strict"});function NN(t={}){return oI(EJ,IJ,import.meta.url,t)}var EJ,IJ,RN=D(()=>{"use strict";TN();EJ="silero_vad.onnx",IJ="JARVIS_SILERO_VAD_MODEL_PATH"});var Bu,Fh,yJ,nc,MN=D(()=>{"use strict";_N();RN();Bu=512,Fh=64,yJ=256,nc=class{modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;pending=new Int16Array(Bu);pendingLen=0;state=new Float32Array(yJ);context=new Float32Array(Fh);chain=Promise.resolve();constructor(e={}){this.modelPath=e.modelPath}process(e){if(this.disposed)return Promise.reject(new Error("SileroVadRunner is disposed"));let r=this.chain.then(()=>this.runWindows(e));return this.chain=r.then(()=>{},()=>{}),r}reset(){this.chain=this.chain.then(()=>{this.pendingLen=0,this.state=new Float32Array(yJ),this.context.fill(0)})}load(){return this.disposed?Promise.reject(new Error("SileroVadRunner is disposed")):this.ensureSession().then(()=>{})}prewarm(){this.disposed||this.ensureSession().catch(()=>{})}async dispose(){this.disposed=!0,this.pendingLen=0;let e=this.session;this.session=null,this.sessionPromise=null,this.ort=null,e&&await e.release()}async runWindows(e){if(this.disposed)throw new Error("SileroVadRunner is disposed");if(e.length===0)return[];let r=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let n=[],s=0;for(;;){let o=Math.min(Bu-this.pendingLen,e.length-s);if(o>0&&(this.pending.set(e.subarray(s,s+o),this.pendingLen),this.pendingLen+=o,s+=o),this.pendingLen<Bu)break;this.pendingLen=0,n.push(await this.inferWindow(r,i))}return n}async inferWindow(e,r){let i=new Float32Array(Fh+Bu);i.set(this.context,0);for(let a=0;a<Bu;a++)i[Fh+a]=this.pending[a]/32768;let n=await e.run({input:new r.Tensor("float32",i,[1,i.length]),state:new r.Tensor("float32",this.state,[2,1,128]),sr:new r.Tensor("int64",BigInt64Array.from([16000n]),[])});if(this.disposed)throw new Error("SileroVadRunner is disposed");let s=n[e.outputNames[0]].data;this.state=n[e.outputNames[1]].data,this.context.set(i.subarray(i.length-Fh));let o=s[0];if(!Number.isFinite(o))throw new Error("silero vad produced a non-finite output");return o<0?0:o>1?1:o}ensureSession(){return this.sessionPromise?this.sessionPromise:(this.sessionPromise=this.loadSession(),this.sessionPromise)}async loadSession(){let e=await iI();this.ort=e,sI(e);let r=this.modelPath??NN(),i=await e.InferenceSession.create(r,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SileroVadRunner is disposed");return this.session=i,i}}});function Sbe(t){let e=1;for(;e<t;)e<<=1;return e}var LN,aI,CJ=D(()=>{"use strict";LN=class{size;rev;cos;sin;constructor(e){if(e<2||(e&e-1)!==0)throw new Error(`Radix2Fft size must be a power of two >= 2, got ${e}`);this.size=e;let r=Math.log2(e);this.rev=new Uint32Array(e);for(let n=0;n<e;n++){let s=0;for(let o=0;o<r;o++)s|=(n>>o&1)<<r-1-o;this.rev[n]=s}let i=e>>1;this.cos=new Float64Array(i),this.sin=new Float64Array(i);for(let n=0;n<i;n++){let s=2*Math.PI*n/e;this.cos[n]=Math.cos(s),this.sin[n]=Math.sin(s)}}transform(e,r,i){let n=this.size,s=this.rev;for(let o=0;o<n;o++){let a=s[o];if(a>o){let c=e[o];e[o]=e[a],e[a]=c;let l=r[o];r[o]=r[a],r[a]=l}}for(let o=2;o<=n;o<<=1){let a=o>>1,c=n/o;for(let l=0;l<n;l+=o)for(let u=0;u<a;u++){let d=u*c,h=this.cos[d],A=i?this.sin[d]:-this.sin[d],f=l+u,m=f+a,E=e[m]*h-r[m]*A,I=e[m]*A+r[m]*h;e[m]=e[f]-E,r[m]=r[f]-I,e[f]+=E,r[f]+=I}}if(i){let o=1/n;for(let a=0;a<n;a++)e[a]*=o,r[a]*=o}}};aI=class{n;bins;m;fft;chirpCos;chirpSin;bRe;bIm;aRe;aIm;constructor(e){if(e<2)throw new Error(`PowerSpectrum length must be >= 2, got ${e}`);this.n=e,this.bins=(e>>1)+1,this.m=Sbe(2*e-1),this.fft=new LN(this.m),this.chirpCos=new Float64Array(e),this.chirpSin=new Float64Array(e);for(let r=0;r<e;r++){let i=r*r%(2*e),n=Math.PI*i/e;this.chirpCos[r]=Math.cos(n),this.chirpSin[r]=Math.sin(n)}this.bRe=new Float64Array(this.m),this.bIm=new Float64Array(this.m);for(let r=0;r<e;r++){let i=this.chirpCos[r],n=this.chirpSin[r];this.bRe[r]=i,this.bIm[r]=n,r!==0&&(this.bRe[this.m-r]=i,this.bIm[this.m-r]=n)}this.fft.transform(this.bRe,this.bIm,!1),this.aRe=new Float64Array(this.m),this.aIm=new Float64Array(this.m)}computePower(e,r){let{n:i,m:n,aRe:s,aIm:o}=this;s.fill(0),o.fill(0);for(let a=0;a<i;a++){let c=e[a];s[a]=c*this.chirpCos[a],o[a]=-c*this.chirpSin[a]}this.fft.transform(s,o,!1);for(let a=0;a<n;a++){let c=s[a],l=o[a],u=this.bRe[a],d=this.bIm[a];s[a]=c*u-l*d,o[a]=c*d+l*u}this.fft.transform(s,o,!0);for(let a=0;a<this.bins;a++){let c=s[a],l=o[a];r[a]=c*c+l*l}}}});function bJ(t){let i=27/Math.log(6.4);return t>=1e3?15+Math.log(t/1e3)*i:3*t/200}function kbe(t){let i=Math.log(6.4)/27;return t>=15?1e3*Math.exp(i*(t-15)):200*t/3}function QJ(t,e,r){let i=new Float64Array(r),n=r>1?(e-t)/(r-1):0;for(let s=0;s<r;s++)i[s]=t+s*n;return r>1&&(i[r-1]=e),i}function Tbe(){let t=bJ(0),e=bJ(FN/2),r=QJ(t,e,ps+2),i=new Float64Array(ps+2);for(let a=0;a<r.length;a++)i[a]=kbe(r[a]);let n=QJ(0,FN/2,Uh),s=new Float64Array(ps+1);for(let a=0;a<ps+1;a++)s[a]=i[a+1]-i[a];let o=[];for(let a=0;a<ps;a++){let c=2/(i[a+2]-i[a]),l=new Float64Array(Uh),u=Uh,d=0;for(let h=0;h<Uh;h++){let A=-(i[a]-n[h])/s[a],f=(i[a+2]-n[h])/s[a+1],m=Math.max(0,Math.min(A,f))*c;l[h]=m,m>0&&(h<u&&(u=h),d=h+1)}u>d&&(u=d=0),o.push({lo:u,hi:d,weights:l.slice(u,d)})}return o}function Nbe(){let t=new Float64Array(Jn);for(let e=0;e<Jn;e++)t[e]=.5-.5*Math.cos(2*Math.PI*e/Jn);return t}var FN,Jn,Dbe,ps,Uh,BJ,_be,xJ,Or,ic,UN,Oh,cI=D(()=>{"use strict";CJ();FN=16e3,Jn=400,Dbe=160,ps=80,Uh=(Jn>>1)+1,BJ=1e-10,_be=1e-7,xJ=32768,Or=FN*8,ic=800,UN=ps;Oh=class{hann=Nbe();filters=Tbe();spectrum=new aI(Jn);padded=new Float64Array(Or+Jn);frame=new Float64Array(Jn);power=new Float64Array(Uh);logBuf=new Float64Array(ps*ic);fromPcm16(e){return this.window(e),this.normalize(),this.reflectPad(),this.melSpectrogram()}window(e){let r=this.padded,i=Jn/2,n=e.length;if(n>=Or){let s=n-Or;for(let o=0;o<Or;o++)r[i+o]=e[s+o]/xJ}else{let s=Or-n;for(let o=0;o<s;o++)r[i+o]=0;for(let o=0;o<n;o++)r[i+s+o]=e[o]/xJ}}normalize(){let e=this.padded,r=Jn/2,i=Or,n=0;for(let a=0;a<i;a++)n+=e[r+a];n/=i;let s=0;for(let a=0;a<i;a++){let c=e[r+a]-n;s+=c*c}s/=i;let o=1/Math.sqrt(s+_be);for(let a=0;a<i;a++)e[r+a]=(e[r+a]-n)*o}reflectPad(){let e=this.padded,r=Jn/2,i=Or;for(let n=0;n<r;n++)e[n]=e[r+(r-n)],e[r+i+n]=e[r+(i-2-n)]}melSpectrogram(){let{padded:e,frame:r,power:i,hann:n,filters:s,logBuf:o}=this;for(let u=0;u<ic;u++){let d=u*Dbe;for(let h=0;h<Jn;h++)r[h]=e[d+h]*n[h];this.spectrum.computePower(r,i);for(let h=0;h<ps;h++){let{lo:A,hi:f,weights:m}=s[h],E=0;for(let I=A;I<f;I++)E+=m[I-A]*i[I];o[h*ic+u]=Math.log10(E<BJ?BJ:E)}}let a=-1/0;for(let u of o)u>a&&(a=u);let c=a-8,l=new Float32Array(ps*ic);for(let u=0;u<o.length;u++){let d=o[u]<c?c:o[u];l[u]=(d+4)/4}return l}}});function Rbe(t){return t.toLowerCase().replace(/[.,!?;:]+$/g,"").trim()}function lI(t,e){return e.some(r=>vJ(t,r))}function vJ(t,e){if(!t.endsWith(e))return!1;let r=t.length-e.length-1;return r<0||t[r]===" "}function Mbe(t,e){let r=Lbe(t);return r===""?null:e.find(i=>Fbe(r,i))??null}function Lbe(t){let e=/^.*[.!?\u3002\uFF01\uFF1F]\s+/s.exec(t);return(e?t.slice(e[0].length):t).trim()}function Fbe(t,e){for(let r=t.indexOf(e);r!==-1;r=t.indexOf(e,r+1)){let i=r===0||!wJ(t[r-1]),n=r+e.length===t.length||!wJ(t[r+e.length]);if(i&&n)return!0}return!1}function wJ(t){return/[a-z0-9']/.test(t)}var uI,ON,$h,$N=D(()=>{"use strict";na();na();uI={silenceEnergyThreshold:zs,shortSilenceMs:500,longSilenceMs:1400,reopenGraceMs:400,stopSecsMs:3e4,heldBudgetLadderMs:[4e3,8e3],heldCeilingMs:12e4,strongHoldCues:["hold on","hang on","give me a sec","give me a second","one moment","one sec","one second","let me think","let me see","let me look"],weakHoldCues:["actually","wait"],commitCues:["that's it","go ahead","what do you think"]},ON="semantic",$h=class{clock;config;classifier;telemetry=null;phase="listening";inSilence=!1;silenceStartedAt=null;firstSpeechAt=null;budgetOwner="baseline";armedBudgetMs=null;lastRawPartial="";lastNormPartial="";strongHoldCue=null;partialStability="stable";pendingVetoClear=!1;held=!1;heldLadderStep=0;heldCeilingDeadlineAtMs=null;commitCb;silenceTimer=null;graceTimer=null;stopTimer=null;ceilingTimer=null;constructor(e,r={},i){this.clock=e,this.config={...uI,...r},this.classifier=i??new $A(this.config.silenceEnergyThreshold)}onAudioFrame(e){this.phase==="committed"||this.phase==="disposed"||this.classifier.classify(e,this.applyVerdict)}applyVerdict=e=>{this.phase==="committed"||this.phase==="disposed"||(e?this.handleSpeech():this.handleSilence())};onPartial(e){if(this.phase==="committed"||this.phase==="disposed")return;if(this.lastRawPartial=e.trim(),this.lastNormPartial=Rbe(e),lI(this.lastNormPartial,this.config.commitCues)){this.commit("lexical");return}let r=this.strongHoldCue,i=Mbe(this.lastNormPartial,this.config.strongHoldCues);if(i===null&&r!==null&&this.partialStability==="redecode"&&!this.pendingVetoClear){this.pendingVetoClear=!0,this.telemetry?.strongHoldClearDebounced?.(r),lI(this.lastNormPartial,this.config.weakHoldCues)&&(this.held||this.holdFloor());return}if(this.pendingVetoClear=!1,this.strongHoldCue=i,this.strongHoldCue!==null){if(this.strongHoldCue!==r){this.telemetry?.strongHoldRecognized(this.strongHoldCue),this.held||this.enterHeld(this.strongHoldCue);return}if(this.held)return;if(vJ(this.lastNormPartial,this.strongHoldCue)){this.enterHeld(this.strongHoldCue);return}this.holdFloor();return}if(lI(this.lastNormPartial,this.config.weakHoldCues)){if(this.held)return;this.holdFloor()}}onCommit(e){this.commitCb=e}attachTelemetry(e){this.telemetry=e}setPartialStability(e){this.partialStability=e}dispose(){this.phase="disposed",this.clearAllTimers()}holdFloor(){this.clearSilenceTimer(),this.phase==="tentative"&&(this.clearGraceTimer(),this.phase="listening"),this.inSilence=!1}handleSpeech(){this.held?(this.inSilence&&(this.exitHeld("speech"),this.clearStopTimer(),this.stopTimer=this.clock.setTimer(this.config.stopSecsMs,()=>this.commit("stop_cap"))),this.firstSpeechAt??=this.clock.now()):this.firstSpeechAt===null&&(this.firstSpeechAt=this.clock.now(),this.stopTimer=this.clock.setTimer(this.config.stopSecsMs,()=>this.commit("stop_cap"))),this.clearSilenceTimer(),this.phase==="tentative"&&(this.clearGraceTimer(),this.phase="listening"),this.inSilence=!1}handleSilence(){this.firstSpeechAt===null||this.phase!=="listening"||this.inSilence||(this.inSilence=!0,this.silenceStartedAt=this.clock.now(),this.budgetOwner="baseline",this.armedBudgetMs=this.held?this.heldLadderBudgetMs():this.silenceBudgetMs(),this.silenceTimer=this.clock.setTimer(this.armedBudgetMs,()=>this.onSilenceBudgetElapsed()),this.onSilenceDetected())}silenceBudgetMs(){return this.isCompleteSounding()?this.config.shortSilenceMs:this.config.longSilenceMs}onSilenceDetected(){}canRefineBudget(){return this.phase==="listening"&&this.inSilence}canApplySemanticVerdict(){return(this.phase==="listening"||this.phase==="tentative")&&this.inSilence}isHeld(){return this.held}heldAllowanceExhausted(){return this.heldCeilingDeadlineAtMs!==null&&this.heldCeilingDeadlineAtMs-this.clock.now()<=0}livePartial(){return this.lastRawPartial}rearmSilence(e,r="smart_turn"){if(!this.inSilence||this.silenceStartedAt===null||this.phase!=="listening"&&this.phase!=="tentative"||this.held)return;let i=e-(this.clock.now()-this.silenceStartedAt);if(this.phase==="tentative"){if(i<=0)return;this.clearGraceTimer(),this.phase="listening"}e!==this.armedBudgetMs&&(this.budgetOwner=r),this.armedBudgetMs=e,this.clearSilenceTimer(),i<=0?this.onSilenceBudgetElapsed():this.silenceTimer=this.clock.setTimer(i,()=>this.onSilenceBudgetElapsed())}onSilenceBudgetElapsed(){if(this.silenceTimer=null,this.phase==="listening"){if(this.held){this.heldLadderStep+=1;let e=this.heldLadderBudgetMs();this.armedBudgetMs=e,this.silenceTimer=this.clock.setTimer(e,()=>this.onSilenceBudgetElapsed()),this.telemetry?.heldLadderRearmed(e);return}this.phase="tentative",this.graceTimer=this.clock.setTimer(this.config.reopenGraceMs,()=>{this.graceTimer=null,this.commit(this.budgetOwner)})}}isCompleteSounding(){return this.strongHoldCue!==null?!1:/[.!?\u3002\uFF01\uFF1F]$/.test(this.lastRawPartial)?!0:lI(this.lastNormPartial,this.config.commitCues)}enterHeld(e){if(this.held)return;let r=this.clock.now();this.heldCeilingDeadlineAtMs??=r+this.config.heldCeilingMs;let i=this.heldCeilingDeadlineAtMs-r;if(!(i<=0&&e===ON)){if(this.held=!0,this.heldLadderStep=0,this.clearStopTimer(),this.telemetry?.heldEntered(e),i<=0){this.commit("held_ceiling");return}this.ceilingTimer=this.clock.setTimer(i,()=>this.commit("held_ceiling")),this.holdFloor()}}resumeHeldSilence(){!this.held||this.phase!=="listening"||this.inSilence||this.firstSpeechAt===null||this.silenceStartedAt===null||(this.inSilence=!0,this.budgetOwner="baseline",this.armedBudgetMs=this.heldLadderBudgetMs(),this.silenceTimer=this.clock.setTimer(this.armedBudgetMs,()=>this.onSilenceBudgetElapsed()))}exitHeld(e){this.held=!1,this.clearCeilingTimer(),this.telemetry?.heldExited(e)}heldLadderBudgetMs(){let e=this.config.heldBudgetLadderMs;return e[Math.min(this.heldLadderStep,e.length-1)]??this.config.longSilenceMs}commit(e){this.phase==="committed"||this.phase==="disposed"||(this.held&&this.exitHeld(e==="held_ceiling"?"ceiling":"commit_cue"),this.phase="committed",this.clearAllTimers(),this.telemetry?.endpointerCommitted(e,this.inSilence?this.silenceStartedAt:null),this.commitCb?.())}clearSilenceTimer(){this.silenceTimer!==null&&(this.clock.clearTimer(this.silenceTimer),this.silenceTimer=null)}clearGraceTimer(){this.graceTimer!==null&&(this.clock.clearTimer(this.graceTimer),this.graceTimer=null)}clearStopTimer(){this.stopTimer!==null&&(this.clock.clearTimer(this.stopTimer),this.stopTimer=null)}clearCeilingTimer(){this.ceilingTimer!==null&&(this.clock.clearTimer(this.ceilingTimer),this.ceilingTimer=null)}clearAllTimers(){this.clearSilenceTimer(),this.clearGraceTimer(),this.clearStopTimer(),this.clearCeilingTimer()}}});var SJ,Ph,PN=D(()=>{"use strict";cI();$N();SJ={...uI,commitThreshold:.65,holdThreshold:.35},Ph=class extends $h{smartConfig;inference;buffer=new Int16Array(Or*2);bufferLen=0;silenceEpoch=0;degraded=!1;smartDisposed=!1;semantics;evaluatedEpoch=0;evaluationAbort=new AbortController;constructor(e,r,i={},n,s){super(e,i,n),this.smartConfig={...SJ,...i},this.inference=r,s&&(this.semantics=s)}onAudioFrame(e){this.appendToBuffer(e),super.onAudioFrame(e)}dispose(){this.smartDisposed=!0,this.bufferLen=0,this.evaluationAbort.abort(),super.dispose()}onSilenceDetected(){if(this.silenceEpoch+=1,this.degraded||this.smartDisposed)return;let e=this.silenceEpoch,r=this.snapshotBuffer();this.runInference(r,e)}async runInference(e,r){let i=this.clock.now(),n;try{n=await this.inference.infer(e)}catch(o){let a=this.degraded;this.degraded=!0,!a&&!this.smartDisposed&&this.telemetry?.smartTurnDegraded(this.clock.now()-i,o);return}let s=this.clock.now()-i;if(this.smartDisposed||r!==this.silenceEpoch||!this.canRefineBudget()){this.telemetry?.smartTurnResolved(n,s,"stale");return}n>=this.smartConfig.commitThreshold?(this.telemetry?.smartTurnResolved(n,s,"shorten"),this.rearmSilence(this.smartConfig.shortSilenceMs),this.maybeEvaluateTurn(r,"shorten")):n<=this.smartConfig.holdThreshold?(this.telemetry?.smartTurnResolved(n,s,"extend"),this.rearmSilence(this.smartConfig.longSilenceMs)):(this.telemetry?.smartTurnResolved(n,s,"inconclusive"),this.maybeEvaluateTurn(r,"inconclusive"))}maybeEvaluateTurn(e,r){if(!this.semantics||this.evaluatedEpoch===e||this.isHeld())return;let i=this.livePartial();i!==""&&(this.evaluatedEpoch=e,this.runEvaluation(this.semantics,i,e,r))}async runEvaluation(e,r,i,n){this.telemetry?.evaluatorFired?.(n);let s=this.clock.now(),o;try{o=await e.evaluator.evaluate({recentTurns:e.recentTurns(),livePartial:r},this.evaluationAbort.signal)}catch(c){this.smartDisposed||this.telemetry?.evaluatorFailed?.(this.clock.now()-s,c);return}let a=this.clock.now()-s;if(this.smartDisposed||i!==this.silenceEpoch||!this.canApplySemanticVerdict()){this.telemetry?.evaluatorResolved?.(o.verdict,o.confidence,a,"stale");return}if(this.telemetry?.evaluatorResolved?.(o.verdict,o.confidence,a,"applied"),o.verdict==="done")this.rearmSilence(this.smartConfig.shortSilenceMs,"semantic");else if(o.verdict==="mid_thought")this.rearmSilence(this.smartConfig.longSilenceMs,"semantic");else{if(this.heldAllowanceExhausted())return;this.enterHeld(ON),this.resumeHeldSilence()}}appendToBuffer(e){let r=e.byteLength>>1;if(r===0)return;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),n=r>Or?r-Or:0,s=r-n;if(this.bufferLen+s>this.buffer.length){let o=Math.min(this.bufferLen,Or);this.buffer.copyWithin(0,this.bufferLen-o,this.bufferLen),this.bufferLen=o}for(let o=n;o<r;o++)this.buffer[this.bufferLen++]=i.getInt16(o*2,!0)}snapshotBuffer(){let e=Math.max(0,this.bufferLen-Or);return this.buffer.slice(e,this.bufferLen)}}});function HN(t={}){return oI(DJ,_J,import.meta.url,t)}var DJ,_J,VN=D(()=>{"use strict";TN();DJ="smart-turn-v3.1-cpu.onnx",_J="JARVIS_SMART_TURN_MODEL_PATH"});var Hh,GN=D(()=>{"use strict";cI();_N();VN();Hh=class{logMel;modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;constructor(e={}){this.logMel=e.logMel??new Oh,this.modelPath=e.modelPath}async infer(e){if(this.disposed)throw new Error("SmartTurnRunner is disposed");let r=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let n=this.logMel.fromPcm16(e),s=new i.Tensor("float32",n,[1,UN,ic]),o=await r.run({input_features:s});if(this.disposed)throw new Error("SmartTurnRunner is disposed");let a=r.outputNames[0],l=o[a].data[0];if(!Number.isFinite(l))throw new Error("smart-turn produced a non-finite output");return l<0?0:l>1?1:l}prewarm(){this.disposed||this.ensureSession().catch(()=>{})}async dispose(){this.disposed=!0;let e=this.session;this.session=null,this.sessionPromise=null,this.ort=null,e&&await e.release()}ensureSession(){return this.sessionPromise?this.sessionPromise:(this.sessionPromise=this.load(),this.sessionPromise)}async load(){let e=await iI();this.ort=e,sI(e);let r=this.modelPath??HN(),i=await e.InferenceSession.create(r,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SmartTurnRunner is disposed");return this.session=i,i}}});function qbe(t){let e=[];if(t.recentTurns.length>0){e.push("Recent conversation:");for(let r of t.recentTurns)e.push(`${r.role==="assistant"?"Assistant":"User"}: ${r.text}`)}else e.push("Recent conversation: (none)");return e.push(""),e.push("Live partial transcript (the user is speaking right now):"),e.push(JSON.stringify(t.livePartial)),e.join(`
|
|
350
|
+
`)return e;let i=e+1<this.buffer.length?this.buffer[e+1]:"";if(i!==""&&/\s/.test(i)&&(ebe.has(r)||tbe.has(r)&&e+1>=this.minClauseLength))return e}return-1}}});var JE,Ka,mu,rbe,jW,iN=D(()=>{JE=new Map,Ka=[],mu=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let i=JE.get(t);if(i===void 0)JE.set(t,{backend:e,priority:r});else{if(i.priority>r)return;if(i.priority===r&&i.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Ka.indexOf(t);n!==-1&&Ka.splice(n,1);for(let s=0;s<Ka.length;s++)if(JE.get(Ka[s]).priority<=r){Ka.splice(s,0,t);return}Ka.push(t)}return}throw new TypeError("not a valid backend")},rbe=async t=>{let e=JE.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(i){return r||(e.error=`${i}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},jW=async t=>{let e=t.executionProviders||[],r=e.map(c=>typeof c=="string"?c:c.name),i=r.length===0?Ka:r,n,s=[],o=new Set;for(let c of i){let l=await rbe(c);typeof l=="string"?s.push({name:c,err:l}):(n||(n=l),n===l&&o.add(c))}if(!n)throw new Error(`no available backend found. ERR: ${s.map(c=>`[${c.name}] ${c.err}`).join(", ")}`);for(let{name:c,err:l}of s)r.includes(c)&&console.warn(`removing requested execution provider "${c}" from session options because it is not available: ${l}`);let a=e.filter(c=>o.has(typeof c=="string"?c:c.name));return[n,new Proxy(t,{get:(c,l)=>l==="executionProviders"?a:Reflect.get(c,l)})]}});var zW=D(()=>{iN()});var WW,JW=D(()=>{WW="1.26.0"});var ZW,Rt,sN=D(()=>{JW();ZW="warning",Rt={wasm:{},webgl:{},webgpu:{},versions:{common:WW},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);ZW=t}},get logLevel(){return ZW}};Object.defineProperty(Rt,"logLevel",{enumerable:!0})});var Et,XW=D(()=>{sN();Et=Rt});var KW,e9,t9=D(()=>{KW=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let i=r.getContext("2d");if(i!=null){let n,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],s=t.dims[3]):(n=t.dims[3],s=t.dims[2]);let o=e?.format!==void 0?e.format:"RGB",a=e?.norm,c,l;a===void 0||a.mean===void 0?c=[255,255,255,255]:typeof a.mean=="number"?c=[a.mean,a.mean,a.mean,a.mean]:(c=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(c[3]=a.mean[3])),a===void 0||a.bias===void 0?l=[0,0,0,0]:typeof a.bias=="number"?l=[a.bias,a.bias,a.bias,a.bias]:(l=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(l[3]=a.bias[3]));let u=s*n,d=0,h=u,A=u*2,f=-1;o==="RGBA"?(d=0,h=u,A=u*2,f=u*3):o==="RGB"?(d=0,h=u,A=u*2):o==="RBG"&&(d=0,A=u,h=u*2);for(let m=0;m<s;m++)for(let E=0;E<n;E++){let I=(t.data[d++]-l[0])*c[0],y=(t.data[h++]-l[1])*c[1],Q=(t.data[A++]-l[2])*c[2],v=f===-1?255:(t.data[f++]-l[3])*c[3];i.fillStyle="rgba("+I+","+y+","+Q+","+v+")",i.fillRect(E,m,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},e9=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(r!=null){let n,s,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],s=t.dims[1],o=t.dims[3]):(n=t.dims[3],s=t.dims[2],o=t.dims[1]);let a=e!==void 0&&e.format!==void 0?e.format:"RGB",c=e?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean=="number"?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias=="number"?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=s*n;if(e!==void 0&&(e.format!==void 0&&o===4&&e.format!=="RGBA"||o===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,A=0,f=1,m=2,E=3,I=0,y=d,Q=d*2,v=-1;a==="RGBA"?(I=0,y=d,Q=d*2,v=d*3):a==="RGB"?(I=0,y=d,Q=d*2):a==="RBG"&&(I=0,Q=d,y=d*2),i=r.createImageData(n,s);for(let S=0;S<s*n;A+=h,f+=h,m+=h,E+=h,S++)i.data[A]=(t.data[I++]-u[0])*l[0],i.data[f]=(t.data[y++]-u[1])*l[1],i.data[m]=(t.data[Q++]-u[2])*l[2],i.data[E]=v===-1?255:(t.data[v++]-u[3])*l[3]}else throw new Error("Can not access image data");return i}});var oN,r9,n9,i9,s9,o9,a9=D(()=>{ZE();oN=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:i}=e,n=e.norm??{mean:255,bias:0},s,o;typeof n.mean=="number"?s=[n.mean,n.mean,n.mean,n.mean]:s=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let a=e.format!==void 0?e.format:"RGBA",c=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",l=r*i,u=c==="RGBA"?new Float32Array(l*4):new Float32Array(l*3),d=4,h=0,A=1,f=2,m=3,E=0,I=l,y=l*2,Q=-1;a==="RGB"&&(d=3,h=0,A=1,f=2,m=-1),c==="RGBA"?Q=l*3:c==="RBG"?(E=0,y=l,I=l*2):c==="BGR"&&(y=0,I=l,E=l*2);for(let S=0;S<l;S++,h+=d,f+=d,A+=d,m+=d)u[E++]=(t[h]+o[0])/s[0],u[I++]=(t[A]+o[1])/s[1],u[y++]=(t[f]+o[2])/s[2],Q!==-1&&m!==-1&&(u[Q++]=(t[m]+o[3])/s[3]);return c==="RGBA"?new Xt("float32",u,[1,4,r,i]):new Xt("float32",u,[1,3,r,i])},r9=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,i=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,s=typeof t=="string",o,a=e??{},c=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},l=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=c();u.width=t.width,u.height=t.height;let d=l(u);if(d!=null){let h=t.height,A=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,A=e.resizedWidth),e!==void 0){if(a=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=h,a.width=A}else a.tensorFormat="RGBA",a.height=h,a.width=A;d.drawImage(t,0,0),o=d.getImageData(0,0,A,h).data}else throw new Error("Can not access image data")}else if(i){let u,d;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,d=e.resizedWidth):(u=t.height,d=t.width),e!==void 0&&(a=e),a.format="RGBA",a.height=u,a.width=d,e!==void 0){let h=c();h.width=d,h.height=u;let A=l(h);if(A!=null)A.putImageData(t,0,0),o=A.getImageData(0,0,d,u).data;else throw new Error("Can not access image data")}else o=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=c();u.width=t.width,u.height=t.height;let d=l(u);if(d!=null){let h=t.height,A=t.width;return d.drawImage(t,0,0,A,h),o=d.getImageData(0,0,A,h).data,a.height=h,a.width=A,oN(o,a)}else throw new Error("Can not access image data")}else{if(s)return new Promise((u,d)=>{let h=c(),A=l(h);if(!t||!A)return d();let f=new Image;f.crossOrigin="Anonymous",f.src=t,f.onload=()=>{h.width=f.width,h.height=f.height,A.drawImage(f,0,0,h.width,h.height);let m=A.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,u(oN(m.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return oN(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},n9=(t,e)=>{let{width:r,height:i,download:n,dispose:s}=e,o=[1,i,r,4];return new Xt({location:"texture",type:"float32",texture:t,dims:o,download:n,dispose:s})},i9=(t,e)=>{let{dataType:r,dims:i,download:n,dispose:s}=e;return new Xt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:i,download:n,dispose:s})},s9=(t,e)=>{let{dataType:r,dims:i,download:n,dispose:s}=e;return new Xt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:i,download:n,dispose:s})},o9=(t,e,r)=>new Xt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})});var ec,Rh,c9,l9,u9=D(()=>{ec=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Rh=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),c9=!1,l9=()=>{if(!c9){c9=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,i=typeof r<"u"&&r.from;t&&(ec.set("int64",BigInt64Array),Rh.set(BigInt64Array,"int64")),e&&(ec.set("uint64",BigUint64Array),Rh.set(BigUint64Array,"uint64")),i?(ec.set("float16",r),Rh.set(r,"float16")):ec.set("float16",Uint16Array)}}});var A9,d9,h9=D(()=>{ZE();A9=t=>{let e=1;for(let r=0;r<t.length;r++){let i=t[r];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${r}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${i}`);e*=i}return e},d9=(t,e)=>{switch(t.location){case"cpu":return new Xt(t.type,t.data,e);case"cpu-pinned":return new Xt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Xt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Xt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Xt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}});var Xt,ZE=D(()=>{t9();a9();u9();h9();Xt=class{constructor(e,r,i){l9();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let a=ec.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,c;if(typeof e=="string")if(n=e,c=i,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");a=r}else{let l=ec.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?a=l.from(r,BigInt):a=l.from(r)}else if(r instanceof l)a=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")a=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(c=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")n="string",a=e;else if(l==="boolean")n="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(e);else{let l=Rh.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=l,a=e}if(c===void 0)c=[a.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");s=c,this.cpuData=a,this.dataLocation="cpu"}let o=A9(s);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=o}static async fromImage(e,r){return r9(e,r)}static fromTexture(e,r){return n9(e,r)}static fromGpuBuffer(e,r){return i9(e,r)}static fromMLTensor(e,r){return s9(e,r)}static fromPinnedBuffer(e,r,i){return o9(e,r,i)}toDataURL(e){return KW(this,e)}toImageData(e){return e9(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return d9(this,e)}}});var Dn,aN=D(()=>{ZE();Dn=Xt});var cN,f9,vo,So,Do,_o,lN=D(()=>{sN();cN=(t,e)=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||console.timeStamp(`${t}::ORT::${e}`)},f9=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let n=0;n<r.length;n++){if(i&&!r[n].includes("TRACE_FUNC")){let s=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(s+=`::${e}`),cN("CPU",s);return}r[n].includes("TRACE_FUNC")&&(i=!0)}},vo=t=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||f9("BEGIN",t)},So=t=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||f9("END",t)},Do=t=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||console.time(`ORT::${t}`)},_o=t=>{(typeof Rt.trace>"u"?!Rt.wasm.trace:!Rt.trace)||console.timeEnd(`ORT::${t}`)}});var XE,g9=D(()=>{iN();aN();lN();XE=class t{constructor(e){this.handler=e}async run(e,r,i){vo(),Do("InferenceSession.run");let n={},s={};if(typeof e!="object"||e===null||e instanceof Dn||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Dn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let l of r){if(typeof l!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(l)===-1)throw new RangeError(`'fetches' contains invalid output name: ${l}.`);n[l]=null}if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let l=!1,u=Object.getOwnPropertyNames(r);for(let d of this.outputNames)if(u.indexOf(d)!==-1){let h=r[d];(h===null||h instanceof Dn)&&(l=!0,o=!1,n[d]=h)}if(l){if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let l of this.inputNames)if(typeof e[l]>"u")throw new Error(`input '${l}' is missing in 'feeds'.`);if(o)for(let l of this.outputNames)n[l]=null;let a=await this.handler.run(e,n,s),c={};for(let l in a)if(Object.hasOwnProperty.call(a,l)){let u=a[l];u instanceof Dn?c[l]=u:c[l]=new Dn(u.type,u.data,u.dims)}return _o("InferenceSession.run"),So(),c}async release(){return this.handler.dispose()}static async create(e,r,i,n){vo(),Do("InferenceSession.create");let s,o={};if(typeof e=="string"){if(s=e,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,d=0,h=e.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(d=r,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(h=e.byteLength-d,typeof i=="number"){if(h=i,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||d+h>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-d}].`);if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(u,d,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,c]=await jW(o),l=await a.createInferenceSessionHandler(s,c);return _o("InferenceSession.create"),So(),new t(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}});var p9,m9=D(()=>{g9();p9=XE});var E9=D(()=>{});var I9=D(()=>{});var y9=D(()=>{});var C9=D(()=>{});var uN={};An(uN,{InferenceSession:()=>p9,TRACE:()=>cN,TRACE_EVENT_BEGIN:()=>Do,TRACE_EVENT_END:()=>_o,TRACE_FUNC_BEGIN:()=>vo,TRACE_FUNC_END:()=>So,Tensor:()=>Dn,env:()=>Et,registerBackend:()=>mu});var ko=D(()=>{zW();XW();m9();aN();E9();I9();lN();y9();C9()});var dJ={};An(dJ,{InferenceSession:()=>p9,TRACE:()=>cN,TRACE_EVENT_BEGIN:()=>Do,TRACE_EVENT_END:()=>_o,TRACE_FUNC_BEGIN:()=>vo,TRACE_FUNC_END:()=>So,Tensor:()=>Dn,default:()=>pbe,env:()=>Et,registerBackend:()=>mu});import{createRequire as nbe}from"module";var Eu,QN,ibe,sbe,obe,CN,_n,abe,cbe,lbe,Cu,wN,AN,B9,x9,gs,U9,dN,b9,Q9,w9,v9,hN,O9,$9,fN,KE,Mh,gN,S9,D9,_9,P9,ct,Lh,Wn,rI,rt,vN,H9,ube,k9,T9,N9,tc,R9,V9,Abe,Iu,tI,yu,G9,Y9,SN,DN,q9,j9,nI,z9,M9,W9,J9,rc,L9,pN,BN,Z9,X9,mN,K9,eJ,dbe,eI,EN,IN,tJ,rJ,nJ,iJ,sJ,oJ,aJ,cJ,yN,F9,lJ,hbe,uJ,xN,bN,AJ,fbe,gbe,pbe,hJ=D(()=>{ko();ko();ko();ko();ko();ko();ko();Eu=nbe(import.meta.url),QN=Object.defineProperty,ibe=Object.getOwnPropertyDescriptor,sbe=Object.getOwnPropertyNames,obe=Object.prototype.hasOwnProperty,CN=(t=>typeof Eu<"u"?Eu:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Eu<"u"?Eu:e)[r]}):t)(function(t){if(typeof Eu<"u")return Eu.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),_n=(t,e)=>()=>(t&&(e=t(t=0)),e),abe=(t,e)=>{for(var r in e)QN(t,r,{get:e[r],enumerable:!0})},cbe=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of sbe(e))!obe.call(t,n)&&n!==r&&QN(t,n,{get:()=>e[n],enumerable:!(i=ibe(e,n))||i.enumerable});return t},lbe=t=>cbe(QN({},"__esModule",{value:!0}),t),wN=_n(()=>{"use strict";Cu=!!(typeof process<"u"&&process.versions&&process.versions.node)}),$9=_n(()=>{"use strict";wN(),AN=Cu||typeof location>"u"?void 0:location.origin,B9=import.meta.url>"file:"&&import.meta.url<"file;",x9=()=>{if(!Cu){if(B9){let t=URL;return new URL(new t("ort.node.min.mjs",import.meta.url).href,AN).href}return import.meta.url}},gs=x9(),U9=()=>{if(gs&&!gs.startsWith("blob:"))return gs.substring(0,gs.lastIndexOf("/")+1)},dN=(t,e)=>{try{let r=e??gs;return(r?new URL(t,r):new URL(t)).origin===AN}catch{return!1}},b9=(t,e)=>{let r=e??gs;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},Q9=(t,e)=>`${e??"./"}${t}`,w9=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},v9=async t=>(await import(t)).default,hN=void 0,O9=async(t,e,r,i)=>{let n=hN&&!(t||e);if(n)if(gs)n=dN(gs)||i&&!r;else if(i&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,hN];{let s="ort-wasm-simd-threaded.mjs",o=t??b9(s,e),a=!Cu&&r&&o&&!dN(o,e),c=a?await w9(o):o??Q9(s,e);return[a?c:void 0,await v9(c)]}}}),Lh=_n(()=>{"use strict";$9(),KE=!1,Mh=!1,gN=!1,S9=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},D9=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},_9=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},P9=async t=>{if(KE)return Promise.resolve();if(Mh)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(gN)throw new Error("previous call to 'initializeWebAssembly()' failed.");Mh=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!_9())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!D9())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=S9();r>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,s=typeof n=="string"?n:void 0,o=n?.mjs,a=o?.href??o,c=n?.wasm,l=c?.href??c,u=t.wasmBinary,[d,h]=await O9(a,s,r>1,!!u||!!l),A=!1,f=[];if(e>0&&f.push(new Promise(m=>{setTimeout(()=>{A=!0,m()},e)})),f.push(new Promise((m,E)=>{let I={numThreads:r};if(u)I.wasmBinary=u,I.locateFile=y=>y;else if(l||s)I.locateFile=y=>l??s+y;else if(a&&a.indexOf("blob:")!==0)I.locateFile=y=>new URL(y,a).href;else if(d){let y=U9();y&&(I.locateFile=Q=>y+Q)}h(I).then(y=>{Mh=!1,KE=!0,fN=y,m(),d&&URL.revokeObjectURL(d)},y=>{Mh=!1,gN=!0,E(y)})})),await Promise.race(f),A)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},ct=()=>{if(KE&&fN)return fN;throw new Error("WebAssembly is not initialized yet.")}}),vN=_n(()=>{"use strict";Lh(),Wn=(t,e)=>{let r=ct(),i=r.lengthBytesUTF8(t)+1,n=r._malloc(i);return r.stringToUTF8(t,n,i),e.push(n),n},rI=(t,e,r,i)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,s])=>{let o=e?e+n:n;if(typeof s=="object")rI(s,o+".",r,i);else if(typeof s=="string"||typeof s=="number")i(o,s.toString());else if(typeof s=="boolean")i(o,s?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof s}`)})},rt=t=>{let e=ct(),r=e.stackSave();try{let i=e.PTR_SIZE,n=e.stackAlloc(2*i);e._OrtGetLastError(n,n+i);let s=Number(e.getValue(n,i===4?"i32":"i64")),o=e.getValue(n+i,"*"),a=o?e.UTF8ToString(o):"";throw new Error(`${t} ERROR_CODE: ${s}, ERROR_MESSAGE: ${a}`)}finally{e.stackRestore(r)}}}),ube=_n(()=>{"use strict";Lh(),vN(),H9=t=>{let e=ct(),r=0,i=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let s=0;return t?.tag!==void 0&&(s=Wn(t.tag,i)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&rt("Can't create run options."),t?.extra!==void 0&&rI(t.extra,"",new WeakSet,(o,a)=>{let c=Wn(o,i),l=Wn(a,i);e._OrtAddRunConfigEntry(r,c,l)!==0&&rt(`Can't set a run config entry: ${o} - ${a}.`)}),[r,i]}catch(s){throw r!==0&&e._OrtReleaseRunOptions(r),i.forEach(o=>e._free(o)),s}}}),Abe=_n(()=>{"use strict";Lh(),vN(),k9=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},T9=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},N9=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},tc=(t,e,r,i)=>{let n=Wn(e,i),s=Wn(r,i);ct()._OrtAddSessionConfigEntry(t,n,s)!==0&&rt(`Can't set a session config entry: ${e} - ${r}.`)},R9=async(t,e,r)=>{let i=e.executionProviders;for(let n of i){let s=typeof n=="string"?n:n.name,o=[];switch(s){case"webnn":if(s="WEBNN",tc(t,"session.disable_quant_qdq","1",r),tc(t,"session.disable_qdq_constant_folding","1",r),typeof n!="string"){let d=n?.deviceType;d&&tc(t,"deviceType",d,r)}break;case"webgpu":if(s="JS",typeof n!="string"){let d=n;if(d?.preferredLayout){if(d.preferredLayout!=="NCHW"&&d.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${d.preferredLayout}`);tc(t,"preferredLayout",d.preferredLayout,r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Wn(s,r),c=o.length,l=0,u=0;if(c>0){l=ct()._malloc(c*ct().PTR_SIZE),r.push(l),u=ct()._malloc(c*ct().PTR_SIZE),r.push(u);for(let d=0;d<c;d++)ct().setValue(l+d*ct().PTR_SIZE,o[d][0],"*"),ct().setValue(u+d*ct().PTR_SIZE,o[d][1],"*")}await ct()._OrtAppendExecutionProvider(t,a,l,u,c)!==0&&rt(`Can't append execution provider: ${s}.`)}},V9=async t=>{let e=ct(),r=0,i=[],n=t||{};N9(n);try{let s=k9(n.graphOptimizationLevel??"all"),o=T9(n.executionMode??"sequential"),a=typeof n.logId=="string"?Wn(n.logId,i):0,c=n.logSeverityLevel??2;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log severity level is not valid: ${c}`);let l=n.logVerbosityLevel??0;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log verbosity level is not valid: ${l}`);let u=typeof n.optimizedModelFilePath=="string"?Wn(n.optimizedModelFilePath,i):0;if(r=e._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,a,c,l,u),r===0&&rt("Can't create session options."),n.executionProviders&&await R9(r,n,i),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);tc(r,"enableGraphCapture",n.enableGraphCapture.toString(),i)}if(n.freeDimensionOverrides)for(let[d,h]of Object.entries(n.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let A=Wn(d,i);e._OrtAddFreeDimensionOverride(r,A,h)!==0&&rt(`Can't set a free dimension override: ${d} - ${h}.`)}return n.extra!==void 0&&rI(n.extra,"",new WeakSet,(d,h)=>{tc(r,d,h,i)}),[r,i]}catch(s){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&rt("Can't release session options."),i.forEach(o=>e._free(o)),s}}}),j9=_n(()=>{"use strict";Iu=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},tI=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},yu=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],i=typeof e=="number"?e:e.reduce((n,s)=>n*s,1);return r>0?Math.ceil(i*r):void 0},G9=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Y9=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},SN=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",DN=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",q9=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),z9=_n(()=>{"use strict";wN(),nI=async t=>{if(typeof t=="string")if(Cu)try{let{readFile:e}=CN("node:fs/promises");return new Uint8Array(await e(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let{createReadStream:r}=CN("node:fs"),i=r(t),n=[];for await(let s of i)n.push(s);return new Uint8Array(Buffer.concat(n))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),i=r?parseInt(r,10):0;if(i<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),s;try{s=new ArrayBuffer(i)}catch(a){if(a instanceof RangeError){let c=Math.ceil(i/65536);s=new WebAssembly.Memory({initial:c,maximum:c}).buffer}else throw a}let o=0;for(;;){let{done:a,value:c}=await n.read();if(a)break;let l=c.byteLength;new Uint8Array(s,o,l).set(c),o+=l}return new Uint8Array(s,0,i)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),dbe=_n(()=>{"use strict";ube(),Abe(),j9(),Lh(),vN(),z9(),M9=(t,e)=>{ct()._OrtInit(t,e)!==0&&rt("Can't initialize onnxruntime.")},W9=async t=>{M9(t.wasm.numThreads,Y9(t.logLevel))},J9=async(t,e)=>{ct().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=t.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},rc=new Map,L9=t=>{let e=ct(),r=e.stackSave();try{let i=e.PTR_SIZE,n=e.stackAlloc(2*i);e._OrtGetInputOutputCount(t,n,n+i)!==0&&rt("Can't get session input/output count.");let s=i===4?"i32":"i64";return[Number(e.getValue(n,s)),Number(e.getValue(n+i,s))]}finally{e.stackRestore(r)}},pN=(t,e)=>{let r=ct(),i=r.stackSave(),n=0;try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputMetadata(t,e,o,o+s)!==0&&rt("Can't get session input/output metadata.");let a=Number(r.getValue(o,"*"));n=Number(r.getValue(o+s,"*"));let c=r.HEAP32[n/4];if(c===0)return[a,0];let l=r.HEAPU32[n/4+1],u=[];for(let d=0;d<l;d++){let h=Number(r.getValue(n+8+d*s,"*"));u.push(h!==0?r.UTF8ToString(h):Number(r.getValue(n+8+(d+l)*s,"*")))}return[a,c,u]}finally{r.stackRestore(i),n!==0&&r._OrtFree(n)}},BN=t=>{let e=ct(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Z9=async(t,e)=>{let r,i,n=ct();Array.isArray(t)?[r,i]=t:t.buffer===n.HEAPU8.buffer?[r,i]=[t.byteOffset,t.byteLength]:[r,i]=BN(t);let s=0,o=0,a=0,c=[],l=[],u=[];try{if([o,c]=await V9(e),e?.externalData&&n.mountExternalData){let Q=[];for(let v of e.externalData){let S=typeof v=="string"?v:v.path;Q.push(nI(typeof v=="string"?v:v.data).then(F=>{n.mountExternalData(S,F)}))}await Promise.all(Q)}for(let Q of e?.executionProviders??[])if((typeof Q=="string"?Q:Q.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof Q!="string"){let v=Q,S=v?.context,F=v?.gpuDevice,M=v?.deviceType,$=v?.powerPreference;S?n.currentContext=S:F?n.currentContext=await n.webnnCreateMLContext(F):n.currentContext=await n.webnnCreateMLContext({deviceType:M,powerPreference:$})}else n.currentContext=await n.webnnCreateMLContext();break}s=await n._OrtCreateSession(r,i,o),n.webgpuOnCreateSession?.(s),s===0&&rt("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(s,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[d,h]=L9(s),A=!!e?.enableGraphCapture,f=[],m=[],E=[],I=[],y=[];for(let Q=0;Q<d;Q++){let[v,S,F]=pN(s,Q);v===0&&rt("Can't get an input name."),l.push(v);let M=n.UTF8ToString(v);f.push(M),E.push(S===0?{name:M,isTensor:!1}:{name:M,isTensor:!0,type:tI(S),shape:F})}for(let Q=0;Q<h;Q++){let[v,S,F]=pN(s,Q+d);v===0&&rt("Can't get an output name."),u.push(v);let M=n.UTF8ToString(v);m.push(M),I.push(S===0?{name:M,isTensor:!1}:{name:M,isTensor:!0,type:tI(S),shape:F})}return rc.set(s,[s,l,u,null,A,!1]),[s,f,m,E,I]}catch(d){throw l.forEach(h=>n._OrtFree(h)),u.forEach(h=>n._OrtFree(h)),a!==0&&n._OrtReleaseBinding(a)!==0&&rt("Can't release IO binding."),s!==0&&n._OrtReleaseSession(s)!==0&&rt("Can't release session."),d}finally{n._free(r),o!==0&&n._OrtReleaseSessionOptions(o)!==0&&rt("Can't release session options."),c.forEach(d=>n._free(d)),n.unmountExternalData?.()}},X9=t=>{let e=ct(),r=rc.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[i,n,s,o,a]=r;o&&(a&&e._OrtClearBoundOutputs(o.handle)!==0&&rt("Can't clear bound outputs."),e._OrtReleaseBinding(o.handle)!==0&&rt("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(c=>e._OrtFree(c)),s.forEach(c=>e._OrtFree(c)),e._OrtReleaseSession(i)!==0&&rt("Can't release session."),rc.delete(t)},mN=async(t,e,r,i,n,s,o=!1)=>{if(!t){e.push(0);return}let a=ct(),c=a.PTR_SIZE,l=t[0],u=t[1],d=t[3],h=d,A,f;if(l==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let I=t[2].gpuBuffer;f=yu(Iu(l),u);{let y=a.jsepRegisterBuffer;if(!y)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=y(i,s,I,f)}}else if(d==="ml-tensor"){let I=t[2].mlTensor;f=yu(Iu(l),u);let y=a.webnnRegisterMLTensor;if(!y)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=y(i,I,Iu(l),u)}else{let I=t[2];if(Array.isArray(I)){f=c*I.length,A=a._malloc(f),r.push(A);for(let y=0;y<I.length;y++){if(typeof I[y]!="string")throw new TypeError(`tensor data at index ${y} is not a string`);a.setValue(A+y*c,Wn(I[y],r),"*")}}else{let y=a.webnnIsGraphInput,Q=a.webnnIsGraphOutput;if(l!=="string"&&y&&Q){let v=a.UTF8ToString(n);if(y(i,v)||Q(i,v)){let S=Iu(l);f=yu(S,u),h="ml-tensor";let F=a.webnnCreateTemporaryTensor,M=a.webnnUploadTensor;if(!F||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let $=await F(i,S,u);M($,new Uint8Array(I.buffer,I.byteOffset,I.byteLength)),A=$}else f=I.byteLength,A=a._malloc(f),r.push(A),a.HEAPU8.set(new Uint8Array(I.buffer,I.byteOffset,f),A)}else f=I.byteLength,A=a._malloc(f),r.push(A),a.HEAPU8.set(new Uint8Array(I.buffer,I.byteOffset,f),A)}}let m=a.stackSave(),E=a.stackAlloc(4*u.length);try{u.forEach((y,Q)=>a.setValue(E+Q*c,y,c===4?"i32":"i64"));let I=a._OrtCreateTensor(Iu(l),A,f,E,u.length,q9(h));I===0&&rt(`Can't create tensor for input/output. session=${i}, index=${s}.`),e.push(I)}finally{a.stackRestore(m)}},K9=async(t,e,r,i,n,s)=>{let o=ct(),a=o.PTR_SIZE,c=rc.get(t);if(!c)throw new Error(`cannot run inference. invalid session id: ${t}`);let l=c[0],u=c[1],d=c[2],h=c[3],A=c[4],f=c[5],m=e.length,E=i.length,I=0,y=[],Q=[],v=[],S=[],F=[],M=o.stackSave(),$=o.stackAlloc(m*a),L=o.stackAlloc(m*a),se=o.stackAlloc(E*a),_=o.stackAlloc(E*a);try{[I,y]=H9(s),Do("wasm prepareInputOutputTensor");for(let P=0;P<m;P++)await mN(r[P],Q,S,t,u[e[P]],e[P],A);for(let P=0;P<E;P++)await mN(n[P],v,S,t,d[i[P]],m+i[P],A);_o("wasm prepareInputOutputTensor");for(let P=0;P<m;P++)o.setValue($+P*a,Q[P],"*"),o.setValue(L+P*a,u[e[P]],"*");for(let P=0;P<E;P++)o.setValue(se+P*a,v[P],"*"),o.setValue(_+P*a,d[i[P]],"*");o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let fe;fe=await o._OrtRun(l,L,$,m,_,E,se,I),fe!==0&&rt("failed to call OrtRun().");let Qe=[],x=[];Do("wasm ProcessOutputTensor");for(let P=0;P<E;P++){let _e=Number(o.getValue(se+P*a,"*"));if(_e===v[P]||F.includes(v[P])){Qe.push(n[P]),_e!==v[P]&&o._OrtReleaseTensor(_e)!==0&&rt("Can't release tensor.");continue}let dt=o.stackSave(),Je=o.stackAlloc(4*a),Rn=!1,Ce,Ht=0;try{o._OrtGetTensorData(_e,Je,Je+a,Je+2*a,Je+3*a)!==0&&rt(`Can't access output tensor data on index ${P}.`);let bs=a===4?"i32":"i64",Qs=Number(o.getValue(Je,bs));Ht=o.getValue(Je+a,"*");let q=o.getValue(Je+a*2,"*"),Zn=Number(o.getValue(Je+a*3,bs)),tr=[];for(let St=0;St<Zn;St++)tr.push(Number(o.getValue(q+St*a,bs)));o._OrtFree(q)!==0&&rt("Can't free memory for tensor dims.");let $r=tr.reduce((St,it)=>St*it,1);Ce=tI(Qs);let De=h?.outputPreferredLocations[i[P]];if(Ce==="string"){if(De==="gpu-buffer"||De==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let St=[];for(let it=0;it<$r;it++){let an=o.getValue(Ht+it*a,"*"),Xn=o.getValue(Ht+(it+1)*a,"*"),fy=it===$r-1?void 0:Xn-an;St.push(o.UTF8ToString(an,fy))}Qe.push([Ce,tr,St,"cpu"])}else if(De==="gpu-buffer"&&$r>0){let St=o.jsepGetBuffer;if(!St)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let it=St(Ht),an=yu(Qs,$r);if(an===void 0||!SN(Ce))throw new Error(`Unsupported data type: ${Ce}`);Rn=!0,Qe.push([Ce,tr,{gpuBuffer:it,download:o.jsepCreateDownloader(it,an,Ce),dispose:()=>{o._OrtReleaseTensor(_e)!==0&&rt("Can't release tensor.")}},"gpu-buffer"])}else if(De==="ml-tensor"&&$r>0){let St=o.webnnEnsureTensor,it=o.webnnIsGraphInputOutputTypeSupported;if(!St||!it)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(yu(Qs,$r)===void 0||!DN(Ce))throw new Error(`Unsupported data type: ${Ce}`);if(!it(t,Ce,!1))throw new Error(`preferredLocation "ml-tensor" for ${Ce} output is not supported by current WebNN Context.`);let an=await St(t,Ht,Qs,tr,!1);Rn=!0,Qe.push([Ce,tr,{mlTensor:an,download:o.webnnCreateMLTensorDownloader(Ht,Ce),dispose:()=>{o.webnnReleaseTensorId(Ht),o._OrtReleaseTensor(_e)}},"ml-tensor"])}else if(De==="ml-tensor-cpu-output"&&$r>0){let St=o.webnnCreateMLTensorDownloader(Ht,Ce)(),it=Qe.length;Rn=!0,x.push((async()=>{let an=[it,await St];return o.webnnReleaseTensorId(Ht),o._OrtReleaseTensor(_e),an})()),Qe.push([Ce,tr,[],"cpu"])}else{let St=G9(Ce),it=new St($r);new Uint8Array(it.buffer,it.byteOffset,it.byteLength).set(o.HEAPU8.subarray(Ht,Ht+it.byteLength)),Qe.push([Ce,tr,it,"cpu"])}}finally{o.stackRestore(dt),Ce==="string"&&Ht&&o._free(Ht),Rn||o._OrtReleaseTensor(_e)}}h&&!A&&(o._OrtClearBoundOutputs(h.handle)!==0&&rt("Can't clear bound outputs."),rc.set(t,[l,u,d,h,A,!1]));for(let[P,_e]of await Promise.all(x))Qe[P][2]=_e;return _o("wasm ProcessOutputTensor"),Qe}finally{o.webnnOnRunEnd?.(l),o.stackRestore(M),Q.forEach(fe=>o._OrtReleaseTensor(fe)),v.forEach(fe=>o._OrtReleaseTensor(fe)),S.forEach(fe=>o._free(fe)),I!==0&&o._OrtReleaseRunOptions(I),y.forEach(fe=>o._free(fe))}},eJ=t=>{let e=ct(),r=rc.get(t);if(!r)throw new Error("invalid session id");let i=r[0],n=e._OrtEndProfiling(i);n===0&&rt("Can't get an profile file name."),e._OrtFree(n)}}),cJ=_n(()=>{"use strict";dbe(),Lh(),$9(),eI=!1,EN=!1,IN=!1,tJ=async()=>{if(!EN){if(eI)throw new Error("multiple calls to 'initWasm()' detected.");if(IN)throw new Error("previous call to 'initWasm()' failed.");eI=!0;try{await P9(Et.wasm),await W9(Et),EN=!0}catch(t){throw IN=!0,t}finally{eI=!1}}},rJ=async t=>{await J9(Et,t)},nJ=async t=>BN(t),iJ=async(t,e)=>Z9(t,e),sJ=async t=>{X9(t)},oJ=async(t,e,r,i,n,s)=>K9(t,e,r,i,n,s),aJ=async t=>{eJ(t)}}),hbe=_n(()=>{"use strict";cJ(),j9(),wN(),z9(),yN=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},F9=t=>{switch(t[3]){case"cpu":return new Dn(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!SN(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:i,dispose:n}=t[2];return Dn.fromGpuBuffer(r,{dataType:e,dims:t[1],download:i,dispose:n})}case"ml-tensor":{let e=t[0];if(!DN(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:i,dispose:n}=t[2];return Dn.fromMLTensor(r,{dataType:e,dims:t[1],download:i,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},lJ=class{async fetchModelAndCopyToWasmMemory(t){return nJ(await nI(t))}async loadModel(t,e){vo();let r;typeof t=="string"?Cu?r=await nI(t):r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await iJ(r,e),So()}async dispose(){return sJ(this.sessionId)}async run(t,e,r){vo();let i=[],n=[];Object.entries(t).forEach(d=>{let h=d[0],A=d[1],f=this.inputNames.indexOf(h);if(f===-1)throw new Error(`invalid input '${h}'`);i.push(A),n.push(f)});let s=[],o=[];Object.entries(e).forEach(d=>{let h=d[0],A=d[1],f=this.outputNames.indexOf(h);if(f===-1)throw new Error(`invalid output '${h}'`);s.push(A),o.push(f)});let a=i.map((d,h)=>yN(d,()=>`input "${this.inputNames[n[h]]}"`)),c=s.map((d,h)=>d?yN(d,()=>`output "${this.outputNames[o[h]]}"`):null),l=await oJ(this.sessionId,n,a,o,c,r),u={};for(let d=0;d<l.length;d++)u[this.outputNames[o[d]]]=s[d]??F9(l[d]);return So(),u}startProfiling(){}endProfiling(){aJ(this.sessionId)}}}),uJ={};abe(uJ,{OnnxruntimeWebAssemblyBackend:()=>bN,initializeFlags:()=>xN,wasmBackend:()=>AJ});fbe=_n(()=>{"use strict";cJ(),hbe(),xN=()=>{(typeof Et.wasm.initTimeout!="number"||Et.wasm.initTimeout<0)&&(Et.wasm.initTimeout=0);let t=Et.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Et.wasm.simd=!1),typeof Et.wasm.proxy!="boolean"&&(Et.wasm.proxy=!1),typeof Et.wasm.trace!="boolean"&&(Et.wasm.trace=!1),typeof Et.wasm.numThreads!="number"||!Number.isInteger(Et.wasm.numThreads)||Et.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Et.wasm.numThreads=1;else{let e=typeof navigator>"u"?CN("node:os").cpus().length:navigator.hardwareConcurrency;Et.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},bN=class{async init(t){xN(),await tJ(),await rJ(t)}async createInferenceSessionHandler(t,e){let r=new lJ;return await r.loadModel(t,e),r}},AJ=new bN}),gbe="1.26.0",pbe=uN;{let t=(fbe(),lbe(uJ)).wasmBackend;mu("cpu",t,10),mu("wasm",t,10)}Object.defineProperty(Et.versions,"web",{value:gbe,enumerable:!0})});import{existsSync as mbe}from"node:fs";import{createRequire as Ebe}from"node:module";import{dirname as Ibe,join as ybe,sep as fJ}from"node:path";import{fileURLToPath as Cbe,pathToFileURL as Bbe}from"node:url";async function iI(){let t=await Promise.resolve().then(()=>(hJ(),dJ));return t.default??t}function sI(t,e){t.env.wasm.numThreads=1,t.env.wasm.wasmPaths=bbe(e)}function xbe(t){return[new URL("./",t),new URL("../",t)].map(e=>Cbe(e))}function bbe(t=import.meta.url){let e=xbe(t);try{e.push(Ibe(Ebe(t).resolve("onnxruntime-web")))}catch{}let r=null;for(let i of e){let n=gJ.filter(s=>!mbe(ybe(i,s)));if(n.length===0)return Qbe(i);n.length<gJ.length&&r===null&&(r={dir:i,missing:n})}throw r!==null?new Error(`ort-web WASM runtime at '${r.dir}' is missing '${r.missing.join("', '")}' - the .wasm and its .mjs glue must be copied together`):new Error(`ort-web WASM runtime ('${pJ}' + '${mJ}') not found beside the bundle or in node_modules`)}function Qbe(t){return Bbe(t.endsWith(fJ)?t:t+fJ).href}var pJ,mJ,gJ,_N=D(()=>{"use strict";pJ="ort-wasm-simd-threaded.wasm",mJ="ort-wasm-simd-threaded.mjs",gJ=[pJ,mJ]});import{existsSync as wbe}from"node:fs";import{fileURLToPath as vbe}from"node:url";function kN(t,e){return[new URL(`../../assets/${t}`,e),new URL(`./assets/${t}`,e),new URL(`../assets/${t}`,e)].map(r=>vbe(r))}function oI(t,e,r,i={}){let n=i.baseUrl??r,s=i.exists??wbe,o="envPath"in i?i.envPath:process.env[e];if(o&&s(o))return o;let a=kN(t,n);for(let c of a)if(s(c))return c;throw new Error(`model '${t}' not found. Tried: ${a.join(", ")}. Set ${e} to override.`)}var TN=D(()=>{"use strict"});function NN(t={}){return oI(EJ,IJ,import.meta.url,t)}var EJ,IJ,RN=D(()=>{"use strict";TN();EJ="silero_vad.onnx",IJ="JARVIS_SILERO_VAD_MODEL_PATH"});var Bu,Fh,yJ,nc,MN=D(()=>{"use strict";_N();RN();Bu=512,Fh=64,yJ=256,nc=class{modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;pending=new Int16Array(Bu);pendingLen=0;state=new Float32Array(yJ);context=new Float32Array(Fh);chain=Promise.resolve();constructor(e={}){this.modelPath=e.modelPath}process(e){if(this.disposed)return Promise.reject(new Error("SileroVadRunner is disposed"));let r=this.chain.then(()=>this.runWindows(e));return this.chain=r.then(()=>{},()=>{}),r}reset(){this.chain=this.chain.then(()=>{this.pendingLen=0,this.state=new Float32Array(yJ),this.context.fill(0)})}load(){return this.disposed?Promise.reject(new Error("SileroVadRunner is disposed")):this.ensureSession().then(()=>{})}prewarm(){this.disposed||this.ensureSession().catch(()=>{})}async dispose(){this.disposed=!0,this.pendingLen=0;let e=this.session;this.session=null,this.sessionPromise=null,this.ort=null,e&&await e.release()}async runWindows(e){if(this.disposed)throw new Error("SileroVadRunner is disposed");if(e.length===0)return[];let r=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let n=[],s=0;for(;;){let o=Math.min(Bu-this.pendingLen,e.length-s);if(o>0&&(this.pending.set(e.subarray(s,s+o),this.pendingLen),this.pendingLen+=o,s+=o),this.pendingLen<Bu)break;this.pendingLen=0,n.push(await this.inferWindow(r,i))}return n}async inferWindow(e,r){let i=new Float32Array(Fh+Bu);i.set(this.context,0);for(let a=0;a<Bu;a++)i[Fh+a]=this.pending[a]/32768;let n=await e.run({input:new r.Tensor("float32",i,[1,i.length]),state:new r.Tensor("float32",this.state,[2,1,128]),sr:new r.Tensor("int64",BigInt64Array.from([16000n]),[])});if(this.disposed)throw new Error("SileroVadRunner is disposed");let s=n[e.outputNames[0]].data;this.state=n[e.outputNames[1]].data,this.context.set(i.subarray(i.length-Fh));let o=s[0];if(!Number.isFinite(o))throw new Error("silero vad produced a non-finite output");return o<0?0:o>1?1:o}ensureSession(){return this.sessionPromise?this.sessionPromise:(this.sessionPromise=this.loadSession(),this.sessionPromise)}async loadSession(){let e=await iI();this.ort=e,sI(e);let r=this.modelPath??NN(),i=await e.InferenceSession.create(r,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SileroVadRunner is disposed");return this.session=i,i}}});function Sbe(t){let e=1;for(;e<t;)e<<=1;return e}var LN,aI,CJ=D(()=>{"use strict";LN=class{size;rev;cos;sin;constructor(e){if(e<2||(e&e-1)!==0)throw new Error(`Radix2Fft size must be a power of two >= 2, got ${e}`);this.size=e;let r=Math.log2(e);this.rev=new Uint32Array(e);for(let n=0;n<e;n++){let s=0;for(let o=0;o<r;o++)s|=(n>>o&1)<<r-1-o;this.rev[n]=s}let i=e>>1;this.cos=new Float64Array(i),this.sin=new Float64Array(i);for(let n=0;n<i;n++){let s=2*Math.PI*n/e;this.cos[n]=Math.cos(s),this.sin[n]=Math.sin(s)}}transform(e,r,i){let n=this.size,s=this.rev;for(let o=0;o<n;o++){let a=s[o];if(a>o){let c=e[o];e[o]=e[a],e[a]=c;let l=r[o];r[o]=r[a],r[a]=l}}for(let o=2;o<=n;o<<=1){let a=o>>1,c=n/o;for(let l=0;l<n;l+=o)for(let u=0;u<a;u++){let d=u*c,h=this.cos[d],A=i?this.sin[d]:-this.sin[d],f=l+u,m=f+a,E=e[m]*h-r[m]*A,I=e[m]*A+r[m]*h;e[m]=e[f]-E,r[m]=r[f]-I,e[f]+=E,r[f]+=I}}if(i){let o=1/n;for(let a=0;a<n;a++)e[a]*=o,r[a]*=o}}};aI=class{n;bins;m;fft;chirpCos;chirpSin;bRe;bIm;aRe;aIm;constructor(e){if(e<2)throw new Error(`PowerSpectrum length must be >= 2, got ${e}`);this.n=e,this.bins=(e>>1)+1,this.m=Sbe(2*e-1),this.fft=new LN(this.m),this.chirpCos=new Float64Array(e),this.chirpSin=new Float64Array(e);for(let r=0;r<e;r++){let i=r*r%(2*e),n=Math.PI*i/e;this.chirpCos[r]=Math.cos(n),this.chirpSin[r]=Math.sin(n)}this.bRe=new Float64Array(this.m),this.bIm=new Float64Array(this.m);for(let r=0;r<e;r++){let i=this.chirpCos[r],n=this.chirpSin[r];this.bRe[r]=i,this.bIm[r]=n,r!==0&&(this.bRe[this.m-r]=i,this.bIm[this.m-r]=n)}this.fft.transform(this.bRe,this.bIm,!1),this.aRe=new Float64Array(this.m),this.aIm=new Float64Array(this.m)}computePower(e,r){let{n:i,m:n,aRe:s,aIm:o}=this;s.fill(0),o.fill(0);for(let a=0;a<i;a++){let c=e[a];s[a]=c*this.chirpCos[a],o[a]=-c*this.chirpSin[a]}this.fft.transform(s,o,!1);for(let a=0;a<n;a++){let c=s[a],l=o[a],u=this.bRe[a],d=this.bIm[a];s[a]=c*u-l*d,o[a]=c*d+l*u}this.fft.transform(s,o,!0);for(let a=0;a<this.bins;a++){let c=s[a],l=o[a];r[a]=c*c+l*l}}}});function bJ(t){let i=27/Math.log(6.4);return t>=1e3?15+Math.log(t/1e3)*i:3*t/200}function kbe(t){let i=Math.log(6.4)/27;return t>=15?1e3*Math.exp(i*(t-15)):200*t/3}function QJ(t,e,r){let i=new Float64Array(r),n=r>1?(e-t)/(r-1):0;for(let s=0;s<r;s++)i[s]=t+s*n;return r>1&&(i[r-1]=e),i}function Tbe(){let t=bJ(0),e=bJ(FN/2),r=QJ(t,e,ps+2),i=new Float64Array(ps+2);for(let a=0;a<r.length;a++)i[a]=kbe(r[a]);let n=QJ(0,FN/2,Uh),s=new Float64Array(ps+1);for(let a=0;a<ps+1;a++)s[a]=i[a+1]-i[a];let o=[];for(let a=0;a<ps;a++){let c=2/(i[a+2]-i[a]),l=new Float64Array(Uh),u=Uh,d=0;for(let h=0;h<Uh;h++){let A=-(i[a]-n[h])/s[a],f=(i[a+2]-n[h])/s[a+1],m=Math.max(0,Math.min(A,f))*c;l[h]=m,m>0&&(h<u&&(u=h),d=h+1)}u>d&&(u=d=0),o.push({lo:u,hi:d,weights:l.slice(u,d)})}return o}function Nbe(){let t=new Float64Array(Jn);for(let e=0;e<Jn;e++)t[e]=.5-.5*Math.cos(2*Math.PI*e/Jn);return t}var FN,Jn,Dbe,ps,Uh,BJ,_be,xJ,Or,ic,UN,Oh,cI=D(()=>{"use strict";CJ();FN=16e3,Jn=400,Dbe=160,ps=80,Uh=(Jn>>1)+1,BJ=1e-10,_be=1e-7,xJ=32768,Or=FN*8,ic=800,UN=ps;Oh=class{hann=Nbe();filters=Tbe();spectrum=new aI(Jn);padded=new Float64Array(Or+Jn);frame=new Float64Array(Jn);power=new Float64Array(Uh);logBuf=new Float64Array(ps*ic);fromPcm16(e){return this.window(e),this.normalize(),this.reflectPad(),this.melSpectrogram()}window(e){let r=this.padded,i=Jn/2,n=e.length;if(n>=Or){let s=n-Or;for(let o=0;o<Or;o++)r[i+o]=e[s+o]/xJ}else{let s=Or-n;for(let o=0;o<s;o++)r[i+o]=0;for(let o=0;o<n;o++)r[i+s+o]=e[o]/xJ}}normalize(){let e=this.padded,r=Jn/2,i=Or,n=0;for(let a=0;a<i;a++)n+=e[r+a];n/=i;let s=0;for(let a=0;a<i;a++){let c=e[r+a]-n;s+=c*c}s/=i;let o=1/Math.sqrt(s+_be);for(let a=0;a<i;a++)e[r+a]=(e[r+a]-n)*o}reflectPad(){let e=this.padded,r=Jn/2,i=Or;for(let n=0;n<r;n++)e[n]=e[r+(r-n)],e[r+i+n]=e[r+(i-2-n)]}melSpectrogram(){let{padded:e,frame:r,power:i,hann:n,filters:s,logBuf:o}=this;for(let u=0;u<ic;u++){let d=u*Dbe;for(let h=0;h<Jn;h++)r[h]=e[d+h]*n[h];this.spectrum.computePower(r,i);for(let h=0;h<ps;h++){let{lo:A,hi:f,weights:m}=s[h],E=0;for(let I=A;I<f;I++)E+=m[I-A]*i[I];o[h*ic+u]=Math.log10(E<BJ?BJ:E)}}let a=-1/0;for(let u of o)u>a&&(a=u);let c=a-8,l=new Float32Array(ps*ic);for(let u=0;u<o.length;u++){let d=o[u]<c?c:o[u];l[u]=(d+4)/4}return l}}});function Rbe(t){return t.toLowerCase().replace(/[.,!?;:]+$/g,"").trim()}function lI(t,e){return e.some(r=>vJ(t,r))}function vJ(t,e){if(!t.endsWith(e))return!1;let r=t.length-e.length-1;return r<0||t[r]===" "}function Mbe(t,e){let r=Lbe(t);return r===""?null:e.find(i=>Fbe(r,i))??null}function Lbe(t){let e=/^.*[.!?\u3002\uFF01\uFF1F]\s+/s.exec(t);return(e?t.slice(e[0].length):t).trim()}function Fbe(t,e){for(let r=t.indexOf(e);r!==-1;r=t.indexOf(e,r+1)){let i=r===0||!wJ(t[r-1]),n=r+e.length===t.length||!wJ(t[r+e.length]);if(i&&n)return!0}return!1}function wJ(t){return/[a-z0-9']/.test(t)}var uI,ON,$h,$N=D(()=>{"use strict";na();na();uI={silenceEnergyThreshold:zs,shortSilenceMs:500,longSilenceMs:1400,reopenGraceMs:400,stopSecsMs:3e4,heldBudgetLadderMs:[4e3,8e3],heldCeilingMs:12e4,heldStableTopRungs:1,strongHoldCues:["hold on","hang on","give me a sec","give me a second","one moment","one sec","one second","let me think","let me see","let me look"],weakHoldCues:["actually","wait"],commitCues:["that's it","go ahead","what do you think"]},ON="semantic",$h=class{clock;config;classifier;telemetry=null;phase="listening";inSilence=!1;silenceStartedAt=null;firstSpeechAt=null;budgetOwner="baseline";armedBudgetMs=null;lastRawPartial="";lastNormPartial="";strongHoldCue=null;partialStability="stable";pendingVetoClear=!1;held=!1;heldLadderStep=0;heldStablePartial="";heldStableTopRungElapses=0;heldCeilingDeadlineAtMs=null;commitCb;silenceTimer=null;graceTimer=null;stopTimer=null;ceilingTimer=null;constructor(e,r={},i){this.clock=e,this.config={...uI,...r},this.classifier=i??new $A(this.config.silenceEnergyThreshold)}onAudioFrame(e){this.phase==="committed"||this.phase==="disposed"||this.classifier.classify(e,this.applyVerdict)}applyVerdict=e=>{this.phase==="committed"||this.phase==="disposed"||(e?this.handleSpeech():this.handleSilence())};onPartial(e){if(this.phase==="committed"||this.phase==="disposed")return;if(this.lastRawPartial=e.trim(),this.lastNormPartial=Rbe(e),lI(this.lastNormPartial,this.config.commitCues)){this.commit("lexical");return}this.held&&this.lastNormPartial!==this.heldStablePartial&&(this.heldStablePartial=this.lastNormPartial,this.heldStableTopRungElapses=0);let r=this.strongHoldCue,i=Mbe(this.lastNormPartial,this.config.strongHoldCues);if(i===null&&r!==null&&this.partialStability==="redecode"&&!this.pendingVetoClear){this.pendingVetoClear=!0,this.telemetry?.strongHoldClearDebounced?.(r),lI(this.lastNormPartial,this.config.weakHoldCues)&&(this.held||this.holdFloor());return}if(this.pendingVetoClear=!1,this.strongHoldCue=i,this.strongHoldCue!==null){if(this.strongHoldCue!==r){this.telemetry?.strongHoldRecognized(this.strongHoldCue),this.held||this.enterHeld(this.strongHoldCue);return}if(this.held)return;if(vJ(this.lastNormPartial,this.strongHoldCue)){this.enterHeld(this.strongHoldCue);return}this.holdFloor();return}if(lI(this.lastNormPartial,this.config.weakHoldCues)){if(this.held)return;this.holdFloor()}}onCommit(e){this.commitCb=e}attachTelemetry(e){this.telemetry=e}setPartialStability(e){this.partialStability=e}dispose(){this.phase="disposed",this.clearAllTimers()}holdFloor(){this.clearSilenceTimer(),this.phase==="tentative"&&(this.clearGraceTimer(),this.phase="listening"),this.inSilence=!1}handleSpeech(){this.held?(this.inSilence&&(this.exitHeld("speech"),this.clearStopTimer(),this.stopTimer=this.clock.setTimer(this.config.stopSecsMs,()=>this.commit("stop_cap"))),this.firstSpeechAt??=this.clock.now()):this.firstSpeechAt===null&&(this.firstSpeechAt=this.clock.now(),this.stopTimer=this.clock.setTimer(this.config.stopSecsMs,()=>this.commit("stop_cap"))),this.clearSilenceTimer(),this.phase==="tentative"&&(this.clearGraceTimer(),this.phase="listening"),this.inSilence=!1}handleSilence(){this.firstSpeechAt===null||this.phase!=="listening"||this.inSilence||(this.inSilence=!0,this.silenceStartedAt=this.clock.now(),this.budgetOwner="baseline",this.armedBudgetMs=this.held?this.heldLadderBudgetMs():this.silenceBudgetMs(),this.silenceTimer=this.clock.setTimer(this.armedBudgetMs,()=>this.onSilenceBudgetElapsed()),this.onSilenceDetected())}silenceBudgetMs(){return this.isCompleteSounding()?this.config.shortSilenceMs:this.config.longSilenceMs}onSilenceDetected(){}canRefineBudget(){return this.phase==="listening"&&this.inSilence}canApplySemanticVerdict(){return(this.phase==="listening"||this.phase==="tentative")&&this.inSilence}isHeld(){return this.held}heldAllowanceExhausted(){return this.heldCeilingDeadlineAtMs!==null&&this.heldCeilingDeadlineAtMs-this.clock.now()<=0}livePartial(){return this.lastRawPartial}rearmSilence(e,r="smart_turn"){if(!this.inSilence||this.silenceStartedAt===null||this.phase!=="listening"&&this.phase!=="tentative"||this.held)return;let i=e-(this.clock.now()-this.silenceStartedAt);if(this.phase==="tentative"){if(i<=0)return;this.clearGraceTimer(),this.phase="listening"}e!==this.armedBudgetMs&&(this.budgetOwner=r),this.armedBudgetMs=e,this.clearSilenceTimer(),i<=0?this.onSilenceBudgetElapsed():this.silenceTimer=this.clock.setTimer(i,()=>this.onSilenceBudgetElapsed())}onSilenceBudgetElapsed(){if(this.silenceTimer=null,this.phase==="listening"){if(this.held){let e=this.heldLadderStep>=this.config.heldBudgetLadderMs.length-1;if(this.heldLadderStep+=1,e&&(this.heldStableTopRungElapses+=1,this.heldStableTopRungElapses>this.config.heldStableTopRungs)){this.commit("held_stable");return}let r=this.heldLadderBudgetMs();this.armedBudgetMs=r,this.silenceTimer=this.clock.setTimer(r,()=>this.onSilenceBudgetElapsed()),this.telemetry?.heldLadderRearmed(r);return}this.phase="tentative",this.graceTimer=this.clock.setTimer(this.config.reopenGraceMs,()=>{this.graceTimer=null,this.commit(this.budgetOwner)})}}isCompleteSounding(){return this.strongHoldCue!==null?!1:/[.!?\u3002\uFF01\uFF1F]$/.test(this.lastRawPartial)?!0:lI(this.lastNormPartial,this.config.commitCues)}enterHeld(e){if(this.held)return;let r=this.clock.now();this.heldCeilingDeadlineAtMs??=r+this.config.heldCeilingMs;let i=this.heldCeilingDeadlineAtMs-r;if(!(i<=0&&e===ON)){if(this.held=!0,this.heldLadderStep=0,this.heldStablePartial=this.lastNormPartial,this.heldStableTopRungElapses=0,this.clearStopTimer(),this.telemetry?.heldEntered(e),i<=0){this.commit("held_ceiling");return}this.ceilingTimer=this.clock.setTimer(i,()=>this.commit("held_ceiling")),this.holdFloor()}}resumeHeldSilence(){!this.held||this.phase!=="listening"||this.inSilence||this.firstSpeechAt===null||this.silenceStartedAt===null||(this.inSilence=!0,this.budgetOwner="baseline",this.armedBudgetMs=this.heldLadderBudgetMs(),this.silenceTimer=this.clock.setTimer(this.armedBudgetMs,()=>this.onSilenceBudgetElapsed()))}exitHeld(e){this.held=!1,this.clearCeilingTimer(),this.telemetry?.heldExited(e)}heldLadderBudgetMs(){let e=this.config.heldBudgetLadderMs;return e[Math.min(this.heldLadderStep,e.length-1)]??this.config.longSilenceMs}commit(e){if(!(this.phase==="committed"||this.phase==="disposed")){if(this.held){let r=e==="held_ceiling"?"ceiling":e==="held_stable"?"stable":"commit_cue";this.exitHeld(r)}this.phase="committed",this.clearAllTimers(),this.telemetry?.endpointerCommitted(e,this.inSilence?this.silenceStartedAt:null),this.commitCb?.()}}clearSilenceTimer(){this.silenceTimer!==null&&(this.clock.clearTimer(this.silenceTimer),this.silenceTimer=null)}clearGraceTimer(){this.graceTimer!==null&&(this.clock.clearTimer(this.graceTimer),this.graceTimer=null)}clearStopTimer(){this.stopTimer!==null&&(this.clock.clearTimer(this.stopTimer),this.stopTimer=null)}clearCeilingTimer(){this.ceilingTimer!==null&&(this.clock.clearTimer(this.ceilingTimer),this.ceilingTimer=null)}clearAllTimers(){this.clearSilenceTimer(),this.clearGraceTimer(),this.clearStopTimer(),this.clearCeilingTimer()}}});var SJ,Ph,PN=D(()=>{"use strict";cI();$N();SJ={...uI,commitThreshold:.65,holdThreshold:.35},Ph=class extends $h{smartConfig;inference;buffer=new Int16Array(Or*2);bufferLen=0;silenceEpoch=0;degraded=!1;smartDisposed=!1;semantics;evaluatedEpoch=0;evaluationAbort=new AbortController;constructor(e,r,i={},n,s){super(e,i,n),this.smartConfig={...SJ,...i},this.inference=r,s&&(this.semantics=s)}onAudioFrame(e){this.appendToBuffer(e),super.onAudioFrame(e)}dispose(){this.smartDisposed=!0,this.bufferLen=0,this.evaluationAbort.abort(),super.dispose()}onSilenceDetected(){if(this.silenceEpoch+=1,this.degraded||this.smartDisposed)return;let e=this.silenceEpoch,r=this.snapshotBuffer();this.runInference(r,e)}async runInference(e,r){let i=this.clock.now(),n;try{n=await this.inference.infer(e)}catch(o){let a=this.degraded;this.degraded=!0,!a&&!this.smartDisposed&&this.telemetry?.smartTurnDegraded(this.clock.now()-i,o);return}let s=this.clock.now()-i;if(this.smartDisposed||r!==this.silenceEpoch||!this.canRefineBudget()){this.telemetry?.smartTurnResolved(n,s,"stale");return}n>=this.smartConfig.commitThreshold?(this.telemetry?.smartTurnResolved(n,s,"shorten"),this.rearmSilence(this.smartConfig.shortSilenceMs),this.maybeEvaluateTurn(r,"shorten")):n<=this.smartConfig.holdThreshold?(this.telemetry?.smartTurnResolved(n,s,"extend"),this.rearmSilence(this.smartConfig.longSilenceMs)):(this.telemetry?.smartTurnResolved(n,s,"inconclusive"),this.maybeEvaluateTurn(r,"inconclusive"))}maybeEvaluateTurn(e,r){if(!this.semantics||this.evaluatedEpoch===e||this.isHeld())return;let i=this.livePartial();i!==""&&(this.evaluatedEpoch=e,this.runEvaluation(this.semantics,i,e,r))}async runEvaluation(e,r,i,n){this.telemetry?.evaluatorFired?.(n);let s=this.clock.now(),o;try{o=await e.evaluator.evaluate({recentTurns:e.recentTurns(),livePartial:r},this.evaluationAbort.signal)}catch(c){this.smartDisposed||this.telemetry?.evaluatorFailed?.(this.clock.now()-s,c);return}let a=this.clock.now()-s;if(this.smartDisposed||i!==this.silenceEpoch||!this.canApplySemanticVerdict()){this.telemetry?.evaluatorResolved?.(o.verdict,o.confidence,a,"stale");return}if(this.telemetry?.evaluatorResolved?.(o.verdict,o.confidence,a,"applied"),o.verdict==="done")this.rearmSilence(this.smartConfig.shortSilenceMs,"semantic");else if(o.verdict==="mid_thought")this.rearmSilence(this.smartConfig.longSilenceMs,"semantic");else{if(this.heldAllowanceExhausted())return;this.enterHeld(ON),this.resumeHeldSilence()}}appendToBuffer(e){let r=e.byteLength>>1;if(r===0)return;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),n=r>Or?r-Or:0,s=r-n;if(this.bufferLen+s>this.buffer.length){let o=Math.min(this.bufferLen,Or);this.buffer.copyWithin(0,this.bufferLen-o,this.bufferLen),this.bufferLen=o}for(let o=n;o<r;o++)this.buffer[this.bufferLen++]=i.getInt16(o*2,!0)}snapshotBuffer(){let e=Math.max(0,this.bufferLen-Or);return this.buffer.slice(e,this.bufferLen)}}});function HN(t={}){return oI(DJ,_J,import.meta.url,t)}var DJ,_J,VN=D(()=>{"use strict";TN();DJ="smart-turn-v3.1-cpu.onnx",_J="JARVIS_SMART_TURN_MODEL_PATH"});var Hh,GN=D(()=>{"use strict";cI();_N();VN();Hh=class{logMel;modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;constructor(e={}){this.logMel=e.logMel??new Oh,this.modelPath=e.modelPath}async infer(e){if(this.disposed)throw new Error("SmartTurnRunner is disposed");let r=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let n=this.logMel.fromPcm16(e),s=new i.Tensor("float32",n,[1,UN,ic]),o=await r.run({input_features:s});if(this.disposed)throw new Error("SmartTurnRunner is disposed");let a=r.outputNames[0],l=o[a].data[0];if(!Number.isFinite(l))throw new Error("smart-turn produced a non-finite output");return l<0?0:l>1?1:l}prewarm(){this.disposed||this.ensureSession().catch(()=>{})}async dispose(){this.disposed=!0;let e=this.session;this.session=null,this.sessionPromise=null,this.ort=null,e&&await e.release()}ensureSession(){return this.sessionPromise?this.sessionPromise:(this.sessionPromise=this.load(),this.sessionPromise)}async load(){let e=await iI();this.ort=e,sI(e);let r=this.modelPath??HN(),i=await e.InferenceSession.create(r,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SmartTurnRunner is disposed");return this.session=i,i}}});function qbe(t){let e=[];if(t.recentTurns.length>0){e.push("Recent conversation:");for(let r of t.recentTurns)e.push(`${r.role==="assistant"?"Assistant":"User"}: ${r.text}`)}else e.push("Recent conversation: (none)");return e.push(""),e.push("Live partial transcript (the user is speaking right now):"),e.push(JSON.stringify(t.livePartial)),e.join(`
|
|
351
351
|
`)}function jbe(t){let e=YN(t)?.content,r=(Array.isArray(e)?e:[]).map(u=>YN(u)).filter(u=>u?.type==="text").map(u=>typeof u?.text=="string"?u.text:"").join(""),i=kJ+r;i.includes("}")||(i+="}");let n=i.indexOf("{"),s=i.lastIndexOf("}");if(n===-1||s<=n)throw new ms("turn evaluator reply carried no JSON object");let o;try{o=JSON.parse(i.slice(n,s+1))}catch{throw new ms("turn evaluator reply was not valid JSON")}let a=YN(o),c=a?.verdict;if(typeof c!="string"||!Gbe.includes(c))throw new ms("turn evaluator reply carried an unknown verdict");let l=a?.confidence;if(typeof l!="number"||!Number.isFinite(l)||l<0||l>1)throw new ms("turn evaluator confidence missing or out of range");return{verdict:c,confidence:l}}function YN(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}var Ube,Obe,$be,Pbe,Hbe,kJ,Vbe,Gbe,Ybe,ms,xu,qN=D(()=>{"use strict";$i();Ube="claude-haiku-4-5-20251001",Obe=2e3,$be="https://api.anthropic.com/v1/messages",Pbe="2023-06-01",Hbe=64,kJ='{"verdict":"',Vbe=["}"],Gbe=["done","mid_thought","hold_floor"],Ybe=`You are the semantic turn evaluator inside a real-time voice assistant's
|
|
352
352
|
turn-taking system. The user is speaking; a streaming ASR produces a live
|
|
353
353
|
partial transcript. Your only job is to judge whether the user's turn reads
|