@neuvybe/jarvis 0.50.4 → 0.50.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. 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
@@ -389,7 +389,7 @@ Rules:
389
389
  Output exactly one line of strict JSON and nothing else:
390
390
  {"verdict":"done"|"mid_thought"|"hold_floor","confidence":<number 0..1>}
391
391
  confidence is your certainty in the verdict.
392
- `,ms=class extends Error{status;constructor(e,r){super(e),this.status=r,this.name="TurnEvaluatorError"}},xu=class{key;fetchImpl;timeoutMs;constructor(e,r=fetch,i=Obe){this.key=e,this.fetchImpl=r,this.timeoutMs=i}async evaluate(e,r){let i={model:Ube,max_tokens:Hbe,temperature:0,stop_sequences:Vbe,system:Ybe,messages:[{role:"user",content:qbe(e)},{role:"assistant",content:kJ}]},n;try{n=await this.fetchImpl($be,{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":Pbe,"content-type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.any([r,AbortSignal.timeout(this.timeoutMs)])})}catch(o){throw o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")?o:new ms(qt(o,this.key))}if(!n.ok)throw new ms(`turn evaluator request failed (HTTP ${n.status})`,n.status);let s;try{s=await n.json()}catch{throw new ms("turn evaluator response body was not JSON")}return jbe(s)}}});function jN(t){return t===void 0?AI:{id:AI.id,engineVoice:{...AI.engineVoice,"elevenlabs-flash":{kind:"preset",voiceId:t},"elevenlabs-v3":{kind:"preset",voiceId:t}}}}var Vh,AI,zN=D(()=>{"use strict";Vh="21m00Tcm4TlvDq8ikWAM",AI={id:"jarvis-primary",engineVoice:{"elevenlabs-flash":{kind:"preset",voiceId:Vh},"elevenlabs-v3":{kind:"preset",voiceId:Vh}}}});var dI,TJ=D(()=>{"use strict";Tt();dI=class{turnId;openedAtMs;log;terminal=!1;heldOpen=!1;asideCommit=!1;silenceReason=null;dispatched=!1;acts={};commandStarted=!1;wordlessCuts=0;parkedAtMs=null;decider=null;silenceOnsetAtMs=null;commitAtMs=null;asrFinalAtMs=null;transcriptLength=null;firstDeltaAtMs=null;firstAudioAtMs=null;constructor(e,r,i=ee){this.turnId=e,this.openedAtMs=r,this.log=i}endpointerCommitted(e,r){this.decider===null&&(this.decider=e,this.silenceOnsetAtMs=r)}smartTurnResolved(e,r,i){this.log.debug("smart-turn P(complete)",{turnId:this.turnId,probability:e,inferenceMs:r,outcome:i})}smartTurnDegraded(e,r){this.log.debug("smart-turn DEGRADED to baseline - inference failed; this turn endpoints on baseline timers only",{turnId:this.turnId,inferenceMs:e,error:r instanceof Error?r.message:String(r)})}strongHoldRecognized(e){this.log.debug("lexical STRONG hold recognized - completeness vetoed, silence budget biases long",{turnId:this.turnId,cue:e})}strongHoldClearDebounced(e){this.log.debug("strong hold clear debounced - cue absent from one re-decode partial; veto holds pending a second",{turnId:this.turnId,cue:e})}heldEntered(e){this.heldOpen=!0,this.log.debug("floor-held mode entered - silence budgets escalate, stop cap suspended",{turnId:this.turnId,cue:e})}heldLadderRearmed(e){this.log.debug("held silence budget re-armed at the next ladder step",{turnId:this.turnId,budgetMs:e})}heldExited(e){this.heldOpen=!1,this.log.debug("floor-held mode exited",{turnId:this.turnId,reason:e})}evaluatorFired(e){this.log.debug("semantic evaluator fired - smart-turn resolved in a gated band during a live silence episode",{turnId:this.turnId,band:e})}evaluatorResolved(e,r,i,n){this.log.debug("semantic evaluator resolved",{turnId:this.turnId,verdict:e,confidence:r,latencyMs:i,outcome:n})}evaluatorFailed(e,r){this.log.debug("semantic evaluator failed - no signal; this episode endpoints as armed",{turnId:this.turnId,latencyMs:e,error:r instanceof Error?r.message:String(r)})}committed(e,r){this.commitAtMs===null&&(r==="ptt"&&this.heldOpen&&this.heldExited("ptt"),this.commitAtMs=e,r==="ptt"&&(this.decider??="ptt"))}asrFinalResolved(e,r){this.asrFinalAtMs===null&&(this.asrFinalAtMs=e,this.transcriptLength=r)}firstReasonerDelta(e){this.firstDeltaAtMs??=e}firstTtsAudio(e){this.firstAudioAtMs??=e}markAsideCommit(){this.asideCommit=!0}silence(e){this.silenceReason=e}asideWakeword(){this.log.debug("aside wakeword - the lexical gate opened; the utterance dispatches for the model's judgment",{turnId:this.turnId})}markDispatched(){this.dispatched=!0}actSettled(e){this.acts[e]=(this.acts[e]??0)+1}toolStarted(){this.commandStarted=!0}parked(e){this.parkedAtMs=e,this.log.debug("voice turn parked - audio cut; the reply waits for the barging utterance's first word or its blank verdict",{turnId:this.turnId})}resumed(e,r){this.wordlessCuts+=1;let i=this.parkedAtMs===null?null:e-this.parkedAtMs;this.parkedAtMs=null,this.log.debug("voice turn resumed - the barge carried no words; the reply continues",{turnId:this.turnId,verdict:r,parkedMs:i})}actCounts(){return{...this.acts}}completed(e,r,i=!1){if(this.terminal||(this.terminal=!0,!this.dispatched))return null;let n=this.firstDeltaAtMs===null?"lost":"completed";return i?this.hold(e,n,{},r):(this.summary(e,n,{},r),n)}cancelled(e,r,i=!1,n=!1){if(this.terminal||(this.terminal=!0,!this.dispatched||r==="client_shutdown"))return null;let s=n?"detached":this.firstAudioAtMs!==null||this.commandStarted?"barged":"superseded";return i?this.hold(e,s,{},void 0,n):(this.summary(e,s,{}),s)}failed(e,r,i=!1){return this.terminal||(this.terminal=!0,!this.dispatched)?null:i?this.hold(e,"failed",{reason:r}):(this.summary(e,"failed",{reason:r}),"failed")}hold(e,r,i,n,s=!1){let o=!1;return{fallback:r,commandStarted:this.commandStarted,detachedJob:s,acts:this.actCounts(),emit:(a,c)=>{o||(o=!0,this.summary(e,a,i,n,c))}}}summary(e,r,i,n,s){this.log.debug("voice turn summary",{turnId:this.turnId,outcome:r,...i,decider:this.decider,disposition:"dispatched",...this.asideCommit&&{floor:"aside"},...this.silenceReason!==null&&{silence:this.silenceReason},...Object.keys(this.acts).length>0&&{acts:{...this.acts}},...this.wordlessCuts>0&&{wordlessCuts:this.wordlessCuts},...s!==void 0&&{playedMs:s.playedMs,spokenCharacters:s.spokenCharacters,characters:s.characters},silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),finalToFirstDeltaMs:this.spanMs(this.asrFinalAtMs,this.firstDeltaAtMs),firstDeltaToFirstAudioMs:this.spanMs(this.firstDeltaAtMs,this.firstAudioAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength,...n!==void 0&&n.rounds>0&&{toolRounds:n.rounds,toolMs:n.totalMs}})}asideAbsorbed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn absorbed in the aside - no reply spoken",{turnId:this.turnId,decider:this.decider,disposition:"absorbed",floor:"aside",silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}blank(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn blank - terminated silently (no transcribed speech)",{turnId:this.turnId,decider:this.decider,silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}spanMs(e,r){return e===null||r===null?null:r-e}}});function Zbe(t){return Jbe.test(t)}function MJ(t){return t instanceof Ji?"channel_violation":"turn_failed"}var WN,NJ,RJ,zbe,Wbe,Jbe,hI,LJ=D(()=>{"use strict";cw();nm();HA();TJ();WN=16e3,NJ="pcm_s16le",RJ=WN*2/1e3,zbe="en",Wbe=["Jarvis"],Jbe=/\bjarvis\b/i;hI=class{deps;asrStream;ttsStream=null;reasonAbort=new AbortController;recordStartupFailure;phase="capturing";settled=!1;finalizing=!1;lastFrameAtMs;timeline;speech=[];openSpeech=null;openSeeded=!1;charsPushed=0;audioBytes=0;sawFirstAudio=!1;running=null;dispatched=!1;parked=!1;wakeParked=null;heldDelta=null;loopDone=!1;cutActId=null;cuts=[];portion={acts:0,charsPushed:0,audioBytes:0};partialWordsReported=!1;constructor(e){this.deps=e,this.lastFrameAtMs=e.startMs,this.timeline=new dI(e.turnId,e.clock.now()),e.controller.attachTelemetry?.(this.timeline),e.controller.setPartialStability?.(e.asrEngine.partialStability??"stable"),this.asrStream=e.asrEngine.open({sampleRate:WN,encoding:NJ,language:zbe,biasTerms:Wbe,emitPartials:!0}),this.asrStream.onTranscript(r=>this.handleTranscript(r)),this.asrStream.onError(r=>this.asrFailed(r)),e.controller.onCommit(()=>this.finalize(this.lastFrameAtMs,"controller")),e.emit({type:"state",turnId:e.turnId,state:"processing"})}get turnId(){return this.deps.turnId}isParked(){return this.parked}hasCommitted(){return this.finalizing}pushFrame(e,r){this.phase!=="capturing"||this.settled||(this.lastFrameAtMs=r,this.asrStream.pushAudio(e),this.deps.controller.onAudioFrame(e))}endAudio(e){this.finalize(e,"ptt")}cancel(e){if(this.settled)return;this.settled=!0,this.phase="cancelled",this.deps.controller.dispose(),this.reasonAbort.abort(e==="client_shutdown"?void 0:new ll),this.asrStream.abort();let r=this.ttsStream;this.ttsStream=null,r?.cancel();let i=this.heldDelta;if(this.heldDelta=null,this.releaseParked(),e!=="client_shutdown"){if(this.audioBytes===this.portion.audioBytes)for(let o of this.speech.slice(this.portion.acts))o.preamble!==!0&&this.deps.reasoner.settleSpeech(o.actId,{kind:"unspoken"});i?.type==="act.start"&&i.channel==="speech"&&i.preamble!==!0&&this.deps.reasoner.settleSpeech(i.actId,{kind:"unspoken"})}i?.type==="text"&&this.openSpeech!==null&&!this.openSeeded&&(this.openSpeech.characters+=i.text.length);let n=e!=="client_shutdown"&&this.turnDetached(),s=this.terminalRecord();for(let o of this.cuts)this.trySettleCut(o,!0);this.noteTerminal(this.timeline.cancelled(this.deps.clock.now(),e,s.hold,n),s),this.deps.onComplete()}park(){if(this.settled||this.parked||!this.dispatched)return!1;let e=this.ttsStream;return this.ttsStream=null,e?.cancel(),this.deps.segmenter.flush(),this.cutActId=this.openSpeech?.actId??null,this.cuts.push({from:this.portion.acts,to:this.speech.length,charsPushedFrom:this.portion.charsPushed,audioBytesFrom:this.portion.audioBytes,charsPushed:this.charsPushed,audioBytes:this.audioBytes,openActId:this.cutActId,resumed:!1,settled:!1}),this.loopDone?(this.finishDone(),!0):(this.parked=!0,this.timeline.parked(this.deps.clock.now()),!0)}resume(e){if(!this.parked||this.settled)return;this.parked=!1;let r=this.cuts.at(-1);r!==void 0&&(r.resumed=!0,this.portion={acts:r.to,charsPushed:r.charsPushed,audioBytes:r.audioBytes}),this.timeline.resumed(this.deps.clock.now(),e),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"}),r!==void 0&&this.trySettleCut(r),this.releaseParked()}acceptCutReport(e){if(e.end!=="cut")return!1;let r=this.cuts.find(i=>i.report===void 0&&!i.settled);return r===void 0?!1:(r.report=e,this.trySettleCut(r),!0)}trySettleCut(e,r=!1){if(!(e.settled||e.report===void 0||this.parked||!e.resumed)&&!(!r&&e.openActId!==null&&this.openSpeech?.actId===e.openActId)){e.settled=!0;try{this.deps.onCutSettle?.({turnId:this.deps.turnId,ledger:this.cutLedger(e),report:e.report})}catch{}}}releaseParked(){this.parked=!1;let e=this.wakeParked;this.wakeParked=null,e?.()}untilUnparked(){return this.parked?new Promise(e=>{this.wakeParked=e}):Promise.resolve()}terminalRecord(){let e=this.cuts.at(-1);return e!==void 0&&!e.settled&&!e.resumed?(e.settled=!0,{hold:e.to>e.from,ledger:this.cutLedger(e),...e.report!==void 0&&{report:e.report}}):{hold:this.speech.length>this.portion.acts,ledger:this.portionLedger()}}cutLedger(e){return{acts:this.speech.slice(e.from,e.to).map(r=>({...r})),charsPushed:e.charsPushed-e.charsPushedFrom,audioMs:(e.audioBytes-e.audioBytesFrom)/RJ}}portionLedger(){return{acts:this.speech.slice(this.portion.acts).map(e=>({...e})),charsPushed:this.charsPushed-this.portion.charsPushed,audioMs:(this.audioBytes-this.portion.audioBytes)/RJ}}noteWords(e){if(e==="partial"){if(this.partialWordsReported)return;this.partialWordsReported=!0}try{this.deps.onFirstWords?.(e)}catch{}}turnDetached(){try{return this.deps.turnDetached?.()??!1}catch{return!1}}unwound(){return this.running??Promise.resolve()}handleTranscript(e){this.phase!=="capturing"||this.settled||e.isFinal||(this.deps.emit({type:"transcript.partial",turnId:this.deps.turnId,text:e.text}),this.deps.controller.onPartial(e.text),e.text.trim()!==""&&this.noteWords("partial"))}finalize(e,r){this.phase!=="capturing"||this.finalizing||this.settled||(this.finalizing=!0,this.timeline.committed(this.deps.clock.now(),r),this.deps.controller.dispose(),this.running=this.finalizeAndRespond(e,r))}async finalizeAndRespond(e,r){let i;try{i=await this.asrStream.end()}catch(o){if(this.settled)return;this.asrFailed(o);return}if(this.settled)return;this.timeline.asrFinalResolved(this.deps.clock.now(),i.text.length);let n=this.deps.floor;if(r==="ptt"&&n?.floorState()==="aside"&&this.releaseFloor(n,"explicit"),i.text.trim()===""){this.finishBlank();return}this.noteWords("final"),this.phase="responding";let s=this.buildUserTurn(i.text,e);if(n?.floorState()==="aside")return this.runAside(s,n);if(await this.awaitDispatchGate(),!this.settled){this.emitDispatch(s);try{await this.respond(s.text)}catch(o){if(this.settled)return;this.finishError(MJ(o),o);return}this.settled||this.finishDone()}}async runAside(e,r){if(this.timeline.markAsideCommit(),!Zbe(e.text)){this.finishAsideAbsorbed(e,r);return}if(this.timeline.asideWakeword(),this.releaseFloor(r,"resume"),await this.awaitDispatchGate(),!this.settled){this.emitDispatch(e);try{await this.respond(e.text)}catch(i){if(this.settled)return;this.finishError(MJ(i),i);return}this.settled||this.finishDone()}}releaseFloor(e,r){try{e.onFloorReleased(r)}catch{}}emitDispatch(e){this.dispatched=!0,this.timeline.markDispatched();try{this.deps.onDispatched?.()}catch{}this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:e,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"})}noteSilence(e){try{this.deps.floor?.onSilence(e)}catch{}}noteOutcome(e){if(e!==null)try{this.deps.onOutcome?.(e,this.timeline.actCounts())}catch{}}noteTerminal(e,r){if(e!==null){if(typeof e=="string"){this.noteOutcome(e);return}if(this.deps.onHeld===void 0){e.emit(e.fallback),this.noteOutcome(e.fallback);return}try{this.deps.onHeld({turnId:this.deps.turnId,held:e,ledger:r.ledger,...r.report!==void 0&&{report:r.report}})}catch{}}}async awaitDispatchGate(){if(this.deps.beforeDispatch!==void 0)try{await this.deps.beforeDispatch()}catch{}}async respond(e){this.recordStartupFailure=this.deps.reasoner.beforeRunFailure(e,this.deps.turnId,this.reasonAbort.signal);let r=!1;if(this.ensureTts(),this.settled)return;let i=this.deps.reasoner.run(e,this.reasonAbort.signal,{register:"voice",turnId:this.deps.turnId});for await(let s of i){if(this.settled||(r||(r=!0,this.timeline.firstReasonerDelta(this.deps.clock.now())),this.parked&&(this.heldDelta=s,await this.untilUnparked(),this.heldDelta=null,this.settled)))return;this.dispatch(s)}if(this.loopDone=!0,this.settled)return;if(this.parked){this.parked=!1;return}for(let s of this.deps.segmenter.flush())this.push(s);let n=this.ttsStream;n!==null&&await n.end()}dispatch(e){if(e.type==="act.start"){e.channel==="speech"&&(this.openSpeech={actId:e.actId,characters:e.characters??0,...e.preamble===!0&&{preamble:!0}},this.openSeeded=e.characters!==void 0,this.speech.push(this.openSpeech)),UA(r=>this.deps.emit(r),this.deps.turnId,e);return}if(e.type==="act.end"){for(let r of this.deps.segmenter.flush())this.push(r);if(this.openSpeech?.actId===e.actId&&(this.openSpeech.characters=e.characters,e.notificationId!==void 0&&(this.openSpeech.notificationId=e.notificationId),this.openSpeech=null),UA(r=>this.deps.emit(r),this.deps.turnId,e),e.preamble!==!0&&this.timeline.actSettled(e.act),e.reason!==void 0&&(this.timeline.silence(e.reason),this.noteSilence(e.reason)),e.actId===this.cutActId){this.cutActId=null;for(let r of this.cuts)this.trySettleCut(r)}return}if(e.type!=="text"){if(e.type==="tool.start"){for(let r of this.deps.segmenter.flush())this.push(r);this.timeline.toolStarted()}Qp(r=>this.deps.emit(r),this.deps.turnId,e);return}if(this.openSpeech!==null&&!this.openSeeded&&(this.openSpeech.characters+=e.text.length),!(this.cutActId!==null&&this.openSpeech?.actId===this.cutActId)){this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:e.text});for(let r of this.deps.segmenter.push(e.text))this.push(r)}}push(e){let r;try{r=this.ensureTts()}catch(i){throw this.finishError("turn_failed",i),i}this.charsPushed+=e.length,r.pushText(e)}ensureTts(){if(this.ttsStream!==null)return this.ttsStream;let e=this.deps.ttsEngine.speak({voice:this.deps.voice,sampleRate:WN,encoding:NJ});return this.ttsStream=e,e.onAudio(r=>{this.settled||e!==this.ttsStream||(this.audioBytes+=r.byteLength,this.sawFirstAudio||(this.sawFirstAudio=!0,this.timeline.firstTtsAudio(this.deps.clock.now())),this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:r}))}),e.onError(r=>{e===this.ttsStream&&this.finishError("turn_failed",r)}),e}finishBlank(){this.settled||(this.settled=!0,this.timeline.blank(this.deps.clock.now()),this.deps.onComplete())}finishAsideAbsorbed(e,r){if(!this.settled){this.settled=!0,this.phase="cancelled",this.timeline.asideAbsorbed(this.deps.clock.now()),this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:{...e,disposition:"absorbed"},...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.onComplete();try{r.onAbsorbed()}catch{}}}finishDone(){if(this.settled)return;this.settled=!0;let e=this.terminalRecord();for(let r of this.cuts)this.trySettleCut(r,!0);this.noteTerminal(this.timeline.completed(this.deps.clock.now(),this.deps.reasoner.lastTurnTools(),e.hold),e),this.deps.emit({type:"response.done",turnId:this.deps.turnId}),this.deps.onComplete()}asrFailed(e){if(this.settled)return;let r=e instanceof Error?e:new Error(String(e));try{this.deps.onAsrFailure?.(r)}catch{}this.finishError(r instanceof fn?"asr_unavailable":"turn_failed",e)}finishError(e,r){if(this.settled)return;this.settled=!0,this.deps.controller.dispose(),this.recordStartupFailure?.(),this.deps.reasoner.noteFailure(this.deps.turnId),this.reasonAbort.abort(new ul);let i=this.ttsStream;this.ttsStream=null,i?.cancel(),this.heldDelta=null,this.releaseParked();let n=this.terminalRecord();for(let s of this.cuts)this.trySettleCut(s,!0);this.noteTerminal(this.timeline.failed(this.deps.clock.now(),e,n.hold),n),this.deps.emit({type:"error",turnId:this.deps.turnId,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId},reason:e,message:r instanceof Error?r.message:String(r)}),this.deps.onComplete()}buildUserTurn(e,r){return{source:"voice",turnId:this.deps.turnId,sessionId:this.deps.sessionId,deviceId:this.deps.deviceId,text:e,startMs:this.deps.startMs,endMs:r,...this.deps.projectId!==void 0&&{projectId:this.deps.projectId}}}}});import{randomUUID as JN}from"node:crypto";import{realpathSync as Xbe}from"node:fs";import{homedir as Kbe}from"node:os";function UJ(t){return`${(t/1e3).toFixed(1)}s`}function rQe(t){return t.length<=48?t:`${t.slice(0,48)}...`}function nQe(t){switch(t.state){case"none":return"not yet announced";case"shown":return"announced (shown)";case"played":return"announced, played in full";case"cut":return`announce cut at ${t.n} of ${t.m}: not fully heard`;case"unplayed":return"announce never played"}}function oQe(t){if(t.role!=="user"&&t.role!=="assistant")return null;if("toolCalls"in t){let e=t.toolCalls.filter(r=>sQe.has(r.name)).map(r=>typeof r.input=="object"&&r.input!==null?r.input.text:void 0).filter(r=>typeof r=="string"&&r.length>0);return e.length>0?{role:"assistant",text:e.join(" ")}:null}return t.content===""?null:{role:t.role,text:t.content}}var FJ,eQe,tQe,fI,iQe,ZN,bu,Gh,gI,sQe,OJ=D(()=>{"use strict";Tt();Gs();FA();cw();Zp();nm();$w();xO();kW();RW();JT();rN();UW();zw();$W();PW();GW();YW();HA();nN();OA();na();MN();PN();GN();qN();zN();Kp();LJ();FJ=250,eQe=4,tQe=1,fI=3e3;iQe=6,ZN=45e3,bu=class extends Error{constructor(e){super(e),this.name="ReasonerUnavailableError"}},Gh=class extends Error{constructor(e){super(e),this.name="VoiceUnavailableError"}},gI=class{deps;sessionId;deviceId;projectId;queue=new WE;closed=!1;closing=null;eventsConsumed=!1;inFlight=!1;reasoner=null;reasonerRoute=null;turnAbort=null;capturing=null;responding=null;parkBound=null;parkedAtMs=0;parkHeldFor=null;voiceTurnFailed=!1;asrUnavailable=null;mintedTurnId=null;voiceEngines=null;clock;newTurnController;newSmartTurnInference;newFrameClassifier;newTurnEvaluator;newSegmenter;smartTurnInference=null;frameClassifier=null;turnEvaluator=void 0;floorState="engaged";floorCounts={noResponse:{addressed_to_other:0,self_talk:0,no_reply_needed:0},asideEntries:0,asideExits:{resume:0,decay:0,explicit:0}};turnCounts={outcomes:{completed:0,superseded:0,barged:0,failed:0,lost:0,detached:0},acts:{}};jobs;notifications=new YE;playouts=new Map;playoutWaiters=[];cutUnwinding=null;asideDecayTimer=null;lastSpeechAtMs=0;cwd;scratch;constructor(e,r,i){this.deps=i,this.sessionId=e,this.deviceId=r.deviceId,this.projectId=r.projectId,this.cwd=r.launchDir??Kbe(),this.scratch=new pu(e,ee),this.clock=i.clock??new Gi,this.jobs=new em({now:()=>this.clock.now(),logger:ee,onDetached:n=>this.jobDetached(n),onSettled:n=>this.jobSettled(n)}),this.newSmartTurnInference=i.createSmartTurnInference??(()=>new Hh),this.newFrameClassifier=i.createFrameClassifier??(()=>new PA(new nc)),this.newTurnEvaluator=i.createTurnEvaluator??(n=>new xu(n)),this.newTurnController=i.createTurnController??(n=>{let s=this.ensureFrameClassifier();return s.reset?.(),new Ph(n,this.ensureSmartTurnInference(),{},this.speechObservingClassifier(s),this.semanticHook())}),this.newSegmenter=i.createSegmenter??(()=>new Nh),this.emit({type:"session.ready"})}async send(e){let{commandId:r}=e;if(this.closed)throw new Sr(r,"closed");if(e.sessionId!==this.sessionId)throw new Sr(r,"invalid","command sessionId does not match session");switch(e.type){case"input.text":this.acceptTextInput(e);return;case"input.audio.frame":this.acceptAudioFrame(e);return;case"input.audio.end":this.endAudioInput(e);return;case"turn.cancel":this.cancelTurn(e);return;case"turn.playout":this.acceptPlayout(e);return;case"session.close":return this.close();case"approval.resolve":throw new Sr(r,"unsupported");default:throw new Sr(r,"invalid")}}events(){if(this.eventsConsumed)throw new Error("CoreSession.events() supports a single consumer in v0.1");return this.eventsConsumed=!0,this.queue.drain()}close(){if(this.closed)return this.closing??Promise.resolve();this.closed=!0;let e=[],r;this.closing=new Promise(i=>{r=()=>{Promise.all(e).then(()=>i())}});try{this.turnAbort?.abort(),this.clearParkBound(),this.responding?.cancel("client_shutdown"),this.capturing?.cancel("client_shutdown");let i=this.jobs.cancelAll("shutdown");i>0&&(ee.debug("background jobs cancelled at shutdown",{count:i}),e.push(this.jobs.drain().catch(()=>{}))),this.asideDecayTimer!==null&&(this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=null);let n=this.smartTurnInference;this.smartTurnInference=null;let s=this.frameClassifier;this.frameClassifier=null;let o=this.turnEvaluator;this.turnEvaluator=null,this.settleHeldAtClose(),this.logFloorSummary(),this.logTurnSummary(),this.scratch.dispose(),this.queue.close(),n&&e.push(n.dispose().catch(()=>{})),s?.dispose&&e.push(s.dispose().catch(()=>{})),o?.dispose&&e.push(o.dispose().catch(()=>{}))}finally{r()}return this.closing}acceptTextInput(e){if(e.text.trim().length===0)throw new Sr(e.commandId,"invalid","input.text requires non-empty text");if(this.inFlight)throw new Sr(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0,this.exitAside("explicit");let r=JN();this.emit({type:"turn.accepted",turnId:r,clientTurnId:e.clientTurnId,source:"text",commandId:e.commandId}),this.emit({type:"turn.final",turnId:r,turn:this.toTextUserTurn(r,e),commandId:e.commandId}),this.runTextTurn(r,e)}async runTextTurn(e,r){let i=new AbortController;this.turnAbort=i;let n=!1,s=!1,o={};try{let a=this.ensureReasoner();if(await this.awaitDispatchReady(),this.closed)return;this.emit({type:"state",turnId:e,state:"responding"}),n=!0;for await(let c of a.run(r.text,i.signal,{turnId:e}))s=!0,c.type==="text"?this.emit({type:"response.delta",turnId:e,text:c.text}):c.type==="tool.start"||c.type==="tool.result"?Qp(l=>this.emit(l),e,c):(c.type==="act.end"&&(c.preamble!==!0&&(o[c.act]=(o[c.act]??0)+1),c.reason!==void 0&&this.countSilence(c.reason),c.notificationId!==void 0&&this.notifications.annotate(c.notificationId,{state:"shown"})),UA(l=>this.emit(l),e,c));this.closed||this.recordOutcome(s?"completed":"lost",o),this.emit({type:"response.done",turnId:e})}catch(a){n&&!this.closed&&this.recordOutcome("failed",o);let c=a instanceof bu?"no_text_route":a instanceof Ji?"channel_violation":"turn_failed";this.emit({type:"error",turnId:e,commandId:r.commandId,reason:c,message:a instanceof Error?a.message:String(a)})}finally{this.inFlight=!1,this.turnAbort=null}}acceptAudioFrame(e){if(this.capturing){this.capturing.pushFrame(e.audio,e.atMs);return}if(this.asrUnavailable!==null||this.voiceTurnFailed)return;if(this.inFlight&&this.responding?.isParked()!==!0)throw new Sr(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let r=JN();this.emit({type:"turn.accepted",turnId:r,clientTurnId:e.clientTurnId,source:"voice",commandId:e.commandId}),this.mintedTurnId=r;let i=this.resolveVoicePipeline(r,e.commandId);if(!i){this.voiceTurnFailed=!0;return}let n=this.floorHook(),s=new hI({turnId:r,sessionId:this.sessionId,deviceId:this.deviceId,...this.projectId!==void 0&&{projectId:this.projectId},commandId:e.commandId,startMs:e.atMs,asrEngine:i.engines.asrEngine,ttsEngine:i.engines.ttsEngine,voice:i.engines.voice,reasoner:i.reasoner,controller:this.newTurnController(this.clock),segmenter:this.newSegmenter(),clock:this.clock,emit:o=>this.emit(o),floor:n,onOutcome:(o,a)=>this.recordOutcome(o,a),onHeld:o=>this.holdTurn(o),onCutSettle:o=>this.settleCut(o),turnDetached:()=>this.jobs.hasRunningJobFrom(r),beforeDispatch:()=>this.awaitDispatchReady(),onDispatched:()=>this.turnDispatched(s),onFirstWords:o=>this.wordsHeard(o),onAsrFailure:o=>this.noteAsrFailure(o),onComplete:()=>this.completeVoiceTurn(s)});this.capturing=s,this.smartTurnInference?.prewarm?.(),this.frameClassifier?.prewarm?.(),s.pushFrame(e.audio,e.atMs)}endAudioInput(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}if(this.capturing){this.capturing.endAudio(e.atMs);return}this.exitAside("explicit")}cancelTurn(e){let r=e.turnId;if(this.voiceTurnFailed&&(r===void 0||r===this.mintedTurnId)){this.resetVoiceFailure();return}let i=r===void 0?this.capturing??this.responding:this.capturing?.turnId===r?this.capturing:this.responding?.turnId===r?this.responding:null;i!==null&&(e.reason==="barge_in"&&i===this.responding&&(i.isParked()||this.parkTurn(i))||this.abortTurn(i,e.reason))}abortTurn(e,r){if(e===this.responding){this.clearParkBound();let i=e.unwound().then(()=>{this.cutUnwinding===i&&(this.cutUnwinding=null),this.wakePlayoutWaiters()});this.cutUnwinding=i}e.cancel(r)}parkTurn(e){return e.park()?(this.clearParkBound(),e.isParked()&&(this.parkedAtMs=this.clock.now(),this.armParkBound(fI)),!0):!1}armParkBound(e){this.parkBound=this.clock.setTimer(e,()=>{this.parkBound=null,this.parkBoundElapsed()})}parkBoundElapsed(){if(this.responding?.isParked()!==!0)return;let r=this.capturing;if(r?.hasCommitted()===!0&&this.parkHeldFor!==r){this.parkHeldFor=r,this.armParkBound(fI);return}let i=this.clock.now()-Math.max(this.parkedAtMs,this.lastSpeechAtMs);i>=fI?this.resumeParked("no_words"):this.armParkBound(fI-i)}resumeParked(e){if(this.closed)return;let r=this.responding;if(r?.isParked()!==!0)return;let i=this.parkHeldFor;this.clearParkBound(),r.resume(e);let n=this.capturing;e==="no_words"&&n!==null&&(n.hasCommitted()?n===i&&(ee.debug("the barging utterance committed but its final never came - retired, the reply resumes",{turnId:n.turnId}),n.cancel("barge_in")):(ee.debug("the capturing turn the wordless barge opened is retired - no verdict could come",{turnId:n.turnId}),n.cancel("barge_in")))}clearParkBound(){this.parkHeldFor=null,this.parkBound!==null&&(this.clock.clearTimer(this.parkBound),this.parkBound=null)}wordsHeard(e){let r=this.responding;r!==null&&(ee.debug("the barging utterance carries words - the reply in flight yields",{stage:e,parked:r.isParked()}),this.abortTurn(r,"barge_in"))}turnDispatched(e){this.responding!==null&&this.responding!==e&&this.abortTurn(this.responding,"barge_in"),this.capturing===e&&(this.capturing=null),this.responding=e}noteAsrFailure(e){e instanceof fn&&(this.asrUnavailable=e.category,ee.debug("ASR terminally unavailable - voice input latched off for this session",{category:e.category}))}completeVoiceTurn(e){this.dropReportOnly(e.turnId),this.capturing===e?(this.capturing=null,this.resumeParked("blank")):this.responding===e&&(this.responding=null,this.clearParkBound()),this.inFlight=this.capturing!==null||this.responding!==null}dropReportOnly(e){if(e===null)return;let r=this.playouts.get(e);r!==void 0&&r.record===void 0&&this.playouts.delete(e)}resetVoiceFailure(){this.dropReportOnly(this.mintedTurnId),this.voiceTurnFailed=!1,this.mintedTurnId=null}resolveVoicePipeline(e,r){let i;try{i=this.ensureVoiceEngines()}catch(s){return this.emitTurnError(e,r,"no_voice_route",s),null}let n;try{n=this.ensureReasoner()}catch(s){let o=s instanceof bu?"no_text_route":"turn_failed";return this.emitTurnError(e,r,o,s),null}return{engines:i,reasoner:n}}ensureVoiceEngines(){if(this.voiceEngines)return this.voiceEngines;if(!this.deps.voiceRegistry)throw new Gh("voice is not available in this core build");let e=this.deps.configService.resolved(),r=e.routes?.stt,i=e.routes?.tts;if(!r||!i)throw new Gh("no voice route configured - run 'jarvis init' to set routes.stt and routes.tts");let n=!e.secrets?.[r.provider]&&Yr(r.provider),s=!e.secrets?.[i.provider]&&Yr(i.provider);if(n||s){let l=n?r.provider:i.provider;throw new Gh(`no API key for voice provider '${l}' - run 'jarvis init' to add it`)}let o=this.deps.voiceRegistry.asrEngine({provider:r.provider,model:r.model,...r.url!==void 0&&{url:r.url}},e.secrets?.[r.provider]??""),a=this.deps.voiceRegistry.ttsEngine({provider:i.provider,model:i.model},e.secrets?.[i.provider]??""),c=this.deps.voiceIdentity??jN(i.voiceId);return this.voiceEngines={asrEngine:o,ttsEngine:a,voice:c},this.voiceEngines}ensureSmartTurnInference(){return this.smartTurnInference??=this.newSmartTurnInference(),this.smartTurnInference}ensureFrameClassifier(){return this.frameClassifier??=this.newFrameClassifier(),this.frameClassifier}semanticHook(){if(this.turnEvaluator===void 0){let r=this.reasonerRoute;this.turnEvaluator=r?.provider==="anthropic"?this.newTurnEvaluator(r.key):null}return this.turnEvaluator===null?void 0:{evaluator:this.turnEvaluator,recentTurns:()=>{let r=[];for(let i of this.reasoner?.historySnapshot()??[]){let n=oQe(i);n&&r.push(n)}return r.slice(-iQe)}}}floorHook(){return{floorState:()=>this.floorState,onSilence:e=>{this.countSilence(e),e==="addressed_to_other"&&this.enterAside(e)},onAbsorbed:()=>this.noteSpeech(),onFloorReleased:e=>this.exitAside(e)}}enterAside(e){this.floorState!=="aside"&&(this.floorState="aside",this.floorCounts.asideEntries+=1,this.noteSpeech(),this.armAsideDecay(ZN),ee.debug("aside entered - utterances now absorb by default",{reason:e}),this.emit({type:"state",state:"aside"}))}exitAside(e){this.floorState==="aside"&&(this.floorState="engaged",this.floorCounts.asideExits[e]+=1,this.asideDecayTimer!==null&&(this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=null),ee.debug("aside exited",{reason:e}))}countSilence(e){this.floorCounts.noResponse[e]+=1}recordOutcome(e,r){this.turnCounts.outcomes[e]+=1;for(let[i,n]of Object.entries(r))this.turnCounts.acts[i]=(this.turnCounts.acts[i]??0)+n}jobDetached(e){ee.debug("background job detached",{jobId:e.jobId,tool:e.tool,origin:e.origin}),!this.closed&&this.emit({type:"job.detached",...e.turnId!==void 0&&{turnId:e.turnId},jobId:e.jobId,tool:e.tool})}jobSettled(e){this.reasoner?.settleResult(e.record.jobId,e.result,e.isError),ee.debug("background job settled",{jobId:e.record.jobId,tool:e.record.tool,outcome:e.outcome,durationMs:Math.round(e.durationMs)}),!this.closed&&(e.outcome==="ok"?this.notifications.add(`${e.record.tool} job ${e.record.jobId} finished ok in ${UJ(e.durationMs)}`,"normal"):e.outcome==="failed"&&this.notifications.add(`${e.record.tool} job ${e.record.jobId} FAILED after ${UJ(e.durationMs)}`,"high"),this.emit({type:"job.result",...e.record.turnId!==void 0&&{turnId:e.record.turnId},jobId:e.record.jobId,tool:e.record.tool,outcome:e.outcome,durationMs:Math.round(e.durationMs)}))}holdTurn(e){if(this.closed){e.held.emit(e.held.fallback);return}let r=this.playouts.get(e.turnId)??{};r.record=e,e.report!==void 0&&r.report===void 0&&(r.report=e.report),this.playouts.set(e.turnId,r),this.joinPlayout(e.turnId)}acceptPlayout(e){let r={playedMs:e.playedMs,end:e.end},i=this.responding?.turnId===e.turnId?this.responding:this.capturing?.turnId===e.turnId?this.capturing:null;if(i?.acceptCutReport(r)===!0)return;let n=this.playouts.get(e.turnId);if(n===void 0&&i===null){ee.debug("playout report for a turn with no held record - nothing to settle",{end:e.end});return}let s=n??{};s.report===void 0&&(s.report=r,this.playouts.set(e.turnId,s),this.joinPlayout(e.turnId))}joinPlayout(e){let r=this.playouts.get(e);if(r?.record===void 0||r.report===void 0)return;this.playouts.delete(e);let{held:i,ledger:n}=r.record,{end:s}=r.report,{playedMs:o,boundary:a,characters:c}=this.settleReport(n,r.report),l=i.fallback==="failed"?"failed":s==="cut"?i.detachedJob?"detached":o>0||i.commandStarted?"barged":"superseded":i.fallback;i.emit(l,{playedMs:o,spokenCharacters:a,characters:c}),this.recordOutcome(l,i.acts),this.wakePlayoutWaiters()}settleCut(e){let{playedMs:r,boundary:i,characters:n}=this.settleReport(e.ledger,e.report);ee.debug("voice turn cut settled - the audio was cut; the reply continues",{turnId:e.turnId,playedMs:r,spokenCharacters:i,characters:n})}settleReport(e,r){let{end:i}=r,n=Number.isFinite(r.playedMs)&&r.playedMs>0?r.playedMs:0,s=qw(e),a=i==="drained"&&n>0&&n>=e.audioMs-tQe?s:aO(n,e),c=cO(e.acts,a),l=new Set(e.acts.filter(u=>u.preamble===!0).map(u=>u.actId));for(let u of c){if(l.has(u.actId)){this.reasoner?.settleAnnouncement(u.actId,u);continue}this.reasoner?.settleSpeech(u.actId,u)}for(let u of e.acts){if(u.notificationId===void 0)continue;let d=c.find(h=>h.actId===u.actId);d!==void 0&&this.notifications.annotate(u.notificationId,d.kind==="spoken"?{state:"played"}:d.kind==="partial"?{state:"cut",n:d.n,m:d.m}:{state:"unplayed"})}return{playedMs:n,boundary:a,characters:s}}settleHeldAtClose(){for(let e of[...this.playouts.keys()])this.releaseHeld(e);this.playouts.clear(),this.cutUnwinding=null,this.wakePlayoutWaiters()}releaseHeld(e){let r=this.playouts.get(e);this.playouts.delete(e),r?.record!==void 0&&(r.record.held.emit(r.record.held.fallback),this.recordOutcome(r.record.held.fallback,r.record.held.acts))}expireOutstanding(){this.cutUnwinding=null;let e=[];for(let[r,i]of this.playouts)i.record!==void 0&&i.report===void 0&&(i.stale=!0,e.push(r));for(let r of e.slice(0,Math.max(0,e.length-eQe)))this.releaseHeld(r)}awaitDispatchReady(){return this.playoutOutstanding()?new Promise(e=>{let r=!1,i=()=>{r||(r=!0,this.clock.clearTimer(s),this.playoutWaiters=this.playoutWaiters.filter(o=>o!==n),e())},n=()=>{this.playoutOutstanding()||i()},s=this.clock.setTimer(FJ,()=>{ee.debug("dispatch proceeded before the last playout settled",{boundMs:FJ,awaitingReport:[...this.playouts.values()].filter(o=>o.record!==void 0&&o.report===void 0&&o.stale!==!0).length,cutUnwinding:this.cutUnwinding!==null}),this.expireOutstanding(),i()});this.playoutWaiters.push(n)}):Promise.resolve()}playoutOutstanding(){if(this.cutUnwinding!==null)return!0;for(let e of this.playouts.values())if(e.record!==void 0&&e.report===void 0&&e.stale!==!0)return!0;return!1}wakePlayoutWaiters(){for(let e of[...this.playoutWaiters])e()}sessionStateBlock(){let e=this.jobs.list(),r=this.notifications.list();if(e.length===0&&r.length===0)return;let i=["Session state:"];if(e.length>0){i.push(`- Background jobs (${e.length} of ${jw} slots; the [bracketed] value is cancel_job's jobId):`);let n=this.clock.now();for(let s of e){let o=Math.max(0,Math.round((n-s.startedAtMs)/1e3)),a=s.display!==void 0?` "${rQe(s.display)}"`:"",c=s.cancelling?"cancelling":`running, ${o}s`;i.push(` - [${s.jobId}] ${s.tool}${a} - ${c}`)}}if(r.length>0){i.push("- Queued notifications (announce with say_notification - the record then shows whether it played; dismiss_notification discards silently; when unsure whether one was heard, keep it):");for(let n of r)i.push(` - [${n.id}, ${n.priority}] ${n.text} - ${nQe(n.announce)}`)}return i.join(`
392
+ `,ms=class extends Error{status;constructor(e,r){super(e),this.status=r,this.name="TurnEvaluatorError"}},xu=class{key;fetchImpl;timeoutMs;constructor(e,r=fetch,i=Obe){this.key=e,this.fetchImpl=r,this.timeoutMs=i}async evaluate(e,r){let i={model:Ube,max_tokens:Hbe,temperature:0,stop_sequences:Vbe,system:Ybe,messages:[{role:"user",content:qbe(e)},{role:"assistant",content:kJ}]},n;try{n=await this.fetchImpl($be,{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":Pbe,"content-type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.any([r,AbortSignal.timeout(this.timeoutMs)])})}catch(o){throw o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")?o:new ms(qt(o,this.key))}if(!n.ok)throw new ms(`turn evaluator request failed (HTTP ${n.status})`,n.status);let s;try{s=await n.json()}catch{throw new ms("turn evaluator response body was not JSON")}return jbe(s)}}});function jN(t){return t===void 0?AI:{id:AI.id,engineVoice:{...AI.engineVoice,"elevenlabs-flash":{kind:"preset",voiceId:t},"elevenlabs-v3":{kind:"preset",voiceId:t}}}}var Vh,AI,zN=D(()=>{"use strict";Vh="21m00Tcm4TlvDq8ikWAM",AI={id:"jarvis-primary",engineVoice:{"elevenlabs-flash":{kind:"preset",voiceId:Vh},"elevenlabs-v3":{kind:"preset",voiceId:Vh}}}});var dI,TJ=D(()=>{"use strict";Tt();dI=class{turnId;openedAtMs;log;terminal=!1;heldOpen=!1;asideCommit=!1;silenceReason=null;dispatched=!1;acts={};commandStarted=!1;wordlessCuts=0;parkedAtMs=null;decider=null;silenceOnsetAtMs=null;commitAtMs=null;asrFinalAtMs=null;transcriptLength=null;firstDeltaAtMs=null;firstAudioAtMs=null;constructor(e,r,i=ee){this.turnId=e,this.openedAtMs=r,this.log=i}endpointerCommitted(e,r){this.decider===null&&(this.decider=e,this.silenceOnsetAtMs=r)}smartTurnResolved(e,r,i){this.log.debug("smart-turn P(complete)",{turnId:this.turnId,probability:e,inferenceMs:r,outcome:i})}smartTurnDegraded(e,r){this.log.debug("smart-turn DEGRADED to baseline - inference failed; this turn endpoints on baseline timers only",{turnId:this.turnId,inferenceMs:e,error:r instanceof Error?r.message:String(r)})}strongHoldRecognized(e){this.log.debug("lexical STRONG hold recognized - completeness vetoed, silence budget biases long",{turnId:this.turnId,cue:e})}strongHoldClearDebounced(e){this.log.debug("strong hold clear debounced - cue absent from one re-decode partial; veto holds pending a second",{turnId:this.turnId,cue:e})}heldEntered(e){this.heldOpen=!0,this.log.debug("floor-held mode entered - silence budgets escalate, stop cap suspended",{turnId:this.turnId,cue:e})}heldLadderRearmed(e){this.log.debug("held silence budget re-armed at the next ladder step",{turnId:this.turnId,budgetMs:e})}heldExited(e){this.heldOpen=!1,this.log.debug("floor-held mode exited",{turnId:this.turnId,reason:e})}evaluatorFired(e){this.log.debug("semantic evaluator fired - smart-turn resolved in a gated band during a live silence episode",{turnId:this.turnId,band:e})}evaluatorResolved(e,r,i,n){this.log.debug("semantic evaluator resolved",{turnId:this.turnId,verdict:e,confidence:r,latencyMs:i,outcome:n})}evaluatorFailed(e,r){this.log.debug("semantic evaluator failed - no signal; this episode endpoints as armed",{turnId:this.turnId,latencyMs:e,error:r instanceof Error?r.message:String(r)})}committed(e,r){this.commitAtMs===null&&(r==="ptt"&&this.heldOpen&&this.heldExited("ptt"),this.commitAtMs=e,r==="ptt"&&(this.decider??="ptt"))}asrFinalResolved(e,r){this.asrFinalAtMs===null&&(this.asrFinalAtMs=e,this.transcriptLength=r)}firstReasonerDelta(e){this.firstDeltaAtMs??=e}firstTtsAudio(e){this.firstAudioAtMs??=e}markAsideCommit(){this.asideCommit=!0}silence(e){this.silenceReason=e}asideWakeword(){this.log.debug("aside wakeword - the lexical gate opened; the utterance dispatches for the model's judgment",{turnId:this.turnId})}markDispatched(){this.dispatched=!0}actSettled(e){this.acts[e]=(this.acts[e]??0)+1}toolStarted(){this.commandStarted=!0}parked(e){this.parkedAtMs=e,this.log.debug("voice turn parked - audio cut; the reply waits for the barging utterance's first word or its blank verdict",{turnId:this.turnId})}resumed(e,r){this.wordlessCuts+=1;let i=this.parkedAtMs===null?null:e-this.parkedAtMs;this.parkedAtMs=null,this.log.debug("voice turn resumed - the barge carried no words; the reply continues",{turnId:this.turnId,verdict:r,parkedMs:i})}actCounts(){return{...this.acts}}completed(e,r,i=!1){if(this.terminal||(this.terminal=!0,!this.dispatched))return null;let n=this.firstDeltaAtMs===null?"lost":"completed";return i?this.hold(e,n,{},r):(this.summary(e,n,{},r),n)}cancelled(e,r,i=!1,n=!1){if(this.terminal||(this.terminal=!0,!this.dispatched||r==="client_shutdown"))return null;let s=n?"detached":this.firstAudioAtMs!==null||this.commandStarted?"barged":"superseded";return i?this.hold(e,s,{},void 0,n):(this.summary(e,s,{}),s)}failed(e,r,i=!1){return this.terminal||(this.terminal=!0,!this.dispatched)?null:i?this.hold(e,"failed",{reason:r}):(this.summary(e,"failed",{reason:r}),"failed")}hold(e,r,i,n,s=!1){let o=!1;return{fallback:r,commandStarted:this.commandStarted,detachedJob:s,acts:this.actCounts(),emit:(a,c)=>{o||(o=!0,this.summary(e,a,i,n,c))}}}summary(e,r,i,n,s){this.log.debug("voice turn summary",{turnId:this.turnId,outcome:r,...i,decider:this.decider,disposition:"dispatched",...this.asideCommit&&{floor:"aside"},...this.silenceReason!==null&&{silence:this.silenceReason},...Object.keys(this.acts).length>0&&{acts:{...this.acts}},...this.wordlessCuts>0&&{wordlessCuts:this.wordlessCuts},...s!==void 0&&{playedMs:s.playedMs,spokenCharacters:s.spokenCharacters,characters:s.characters},silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),finalToFirstDeltaMs:this.spanMs(this.asrFinalAtMs,this.firstDeltaAtMs),firstDeltaToFirstAudioMs:this.spanMs(this.firstDeltaAtMs,this.firstAudioAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength,...n!==void 0&&n.rounds>0&&{toolRounds:n.rounds,toolMs:n.totalMs}})}asideAbsorbed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn absorbed in the aside - no reply spoken",{turnId:this.turnId,decider:this.decider,disposition:"absorbed",floor:"aside",silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}blank(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn blank - terminated silently (no transcribed speech)",{turnId:this.turnId,decider:this.decider,silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}spanMs(e,r){return e===null||r===null?null:r-e}}});function Zbe(t){return Jbe.test(t)}function MJ(t){return t instanceof Ji?"channel_violation":"turn_failed"}var WN,NJ,RJ,zbe,Wbe,Jbe,hI,LJ=D(()=>{"use strict";cw();nm();HA();TJ();WN=16e3,NJ="pcm_s16le",RJ=WN*2/1e3,zbe="en",Wbe=["Jarvis"],Jbe=/\bjarvis\b/i;hI=class{deps;asrStream;ttsStream=null;reasonAbort=new AbortController;recordStartupFailure;phase="capturing";settled=!1;finalizing=!1;lastFrameAtMs;timeline;speech=[];openSpeech=null;openSeeded=!1;charsPushed=0;audioBytes=0;sawFirstAudio=!1;running=null;dispatched=!1;parked=!1;wakeParked=null;heldDelta=null;loopDone=!1;cutActId=null;cuts=[];portion={acts:0,charsPushed:0,audioBytes:0};partialWordsReported=!1;constructor(e){this.deps=e,this.lastFrameAtMs=e.startMs,this.timeline=new dI(e.turnId,e.clock.now()),e.controller.attachTelemetry?.(this.timeline),e.controller.setPartialStability?.(e.asrEngine.partialStability??"stable"),this.asrStream=e.asrEngine.open({sampleRate:WN,encoding:NJ,language:zbe,biasTerms:Wbe,emitPartials:!0}),this.asrStream.onTranscript(r=>this.handleTranscript(r)),this.asrStream.onError(r=>this.asrFailed(r)),e.controller.onCommit(()=>this.finalize(this.lastFrameAtMs,"controller")),e.emit({type:"state",turnId:e.turnId,state:"processing"})}get turnId(){return this.deps.turnId}isParked(){return this.parked}hasCommitted(){return this.finalizing}pushFrame(e,r){this.phase!=="capturing"||this.settled||(this.lastFrameAtMs=r,this.asrStream.pushAudio(e),this.deps.controller.onAudioFrame(e))}endAudio(e){this.finalize(e,"ptt")}cancel(e){if(this.settled)return;this.settled=!0,this.phase="cancelled",this.deps.controller.dispose(),this.reasonAbort.abort(e==="client_shutdown"?void 0:new ll),this.asrStream.abort();let r=this.ttsStream;this.ttsStream=null,r?.cancel();let i=this.heldDelta;if(this.heldDelta=null,this.releaseParked(),e!=="client_shutdown"){if(this.audioBytes===this.portion.audioBytes)for(let o of this.speech.slice(this.portion.acts))o.preamble!==!0&&this.deps.reasoner.settleSpeech(o.actId,{kind:"unspoken"});i?.type==="act.start"&&i.channel==="speech"&&i.preamble!==!0&&this.deps.reasoner.settleSpeech(i.actId,{kind:"unspoken"})}i?.type==="text"&&this.openSpeech!==null&&!this.openSeeded&&(this.openSpeech.characters+=i.text.length);let n=e!=="client_shutdown"&&this.turnDetached(),s=this.terminalRecord();for(let o of this.cuts)this.trySettleCut(o,!0);this.noteTerminal(this.timeline.cancelled(this.deps.clock.now(),e,s.hold,n),s),this.deps.onComplete()}park(){if(this.settled||this.parked||!this.dispatched)return!1;let e=this.ttsStream;return this.ttsStream=null,e?.cancel(),this.deps.segmenter.flush(),this.cutActId=this.openSpeech?.actId??null,this.cuts.push({from:this.portion.acts,to:this.speech.length,charsPushedFrom:this.portion.charsPushed,audioBytesFrom:this.portion.audioBytes,charsPushed:this.charsPushed,audioBytes:this.audioBytes,openActId:this.cutActId,resumed:!1,settled:!1}),this.loopDone?(this.finishDone(),!0):(this.parked=!0,this.timeline.parked(this.deps.clock.now()),!0)}resume(e){if(!this.parked||this.settled)return;this.parked=!1;let r=this.cuts.at(-1);r!==void 0&&(r.resumed=!0,this.portion={acts:r.to,charsPushed:r.charsPushed,audioBytes:r.audioBytes}),this.timeline.resumed(this.deps.clock.now(),e),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"}),r!==void 0&&this.trySettleCut(r),this.releaseParked()}acceptCutReport(e){if(e.end!=="cut")return!1;let r=this.cuts.find(i=>i.report===void 0&&!i.settled);return r===void 0?!1:(r.report=e,this.trySettleCut(r),!0)}trySettleCut(e,r=!1){if(!(e.settled||e.report===void 0||this.parked||!e.resumed)&&!(!r&&e.openActId!==null&&this.openSpeech?.actId===e.openActId)){e.settled=!0;try{this.deps.onCutSettle?.({turnId:this.deps.turnId,ledger:this.cutLedger(e),report:e.report})}catch{}}}releaseParked(){this.parked=!1;let e=this.wakeParked;this.wakeParked=null,e?.()}untilUnparked(){return this.parked?new Promise(e=>{this.wakeParked=e}):Promise.resolve()}terminalRecord(){let e=this.cuts.at(-1);return e!==void 0&&!e.settled&&!e.resumed?(e.settled=!0,{hold:e.to>e.from,ledger:this.cutLedger(e),...e.report!==void 0&&{report:e.report}}):{hold:this.speech.length>this.portion.acts,ledger:this.portionLedger()}}cutLedger(e){return{acts:this.speech.slice(e.from,e.to).map(r=>({...r})),charsPushed:e.charsPushed-e.charsPushedFrom,audioMs:(e.audioBytes-e.audioBytesFrom)/RJ}}portionLedger(){return{acts:this.speech.slice(this.portion.acts).map(e=>({...e})),charsPushed:this.charsPushed-this.portion.charsPushed,audioMs:(this.audioBytes-this.portion.audioBytes)/RJ}}noteWords(e){if(e==="partial"){if(this.partialWordsReported)return;this.partialWordsReported=!0}try{this.deps.onFirstWords?.(e)}catch{}}turnDetached(){try{return this.deps.turnDetached?.()??!1}catch{return!1}}unwound(){return this.running??Promise.resolve()}handleTranscript(e){this.phase!=="capturing"||this.settled||e.isFinal||(this.deps.emit({type:"transcript.partial",turnId:this.deps.turnId,text:e.text}),this.deps.controller.onPartial(e.text),e.text.trim()!==""&&this.noteWords("partial"))}finalize(e,r){this.phase!=="capturing"||this.finalizing||this.settled||(this.finalizing=!0,this.timeline.committed(this.deps.clock.now(),r),this.deps.controller.dispose(),this.running=this.finalizeAndRespond(e,r))}async finalizeAndRespond(e,r){let i;try{i=await this.asrStream.end()}catch(o){if(this.settled)return;this.asrFailed(o);return}if(this.settled)return;this.timeline.asrFinalResolved(this.deps.clock.now(),i.text.length);let n=this.deps.floor;if(r==="ptt"&&n?.floorState()==="aside"&&this.releaseFloor(n,"explicit"),i.text.trim()===""){this.finishBlank();return}this.noteWords("final"),this.phase="responding";let s=this.buildUserTurn(i.text,e);if(n?.floorState()==="aside")return this.runAside(s,n);if(await this.awaitDispatchGate(),!this.settled){this.emitDispatch(s);try{await this.respond(s.text)}catch(o){if(this.settled)return;this.finishError(MJ(o),o);return}this.settled||this.finishDone()}}async runAside(e,r){if(this.timeline.markAsideCommit(),!Zbe(e.text)){this.finishAsideAbsorbed(e,r);return}if(this.timeline.asideWakeword(),this.releaseFloor(r,"resume"),await this.awaitDispatchGate(),!this.settled){this.emitDispatch(e);try{await this.respond(e.text)}catch(i){if(this.settled)return;this.finishError(MJ(i),i);return}this.settled||this.finishDone()}}releaseFloor(e,r){try{e.onFloorReleased(r)}catch{}}emitDispatch(e){this.dispatched=!0,this.timeline.markDispatched();try{this.deps.onDispatched?.()}catch{}this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:e,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"})}noteSilence(e){try{this.deps.floor?.onSilence(e)}catch{}}noteOutcome(e){if(e!==null)try{this.deps.onOutcome?.(e,this.timeline.actCounts())}catch{}}noteTerminal(e,r){if(e!==null){if(typeof e=="string"){this.noteOutcome(e);return}if(this.deps.onHeld===void 0){e.emit(e.fallback),this.noteOutcome(e.fallback);return}try{this.deps.onHeld({turnId:this.deps.turnId,held:e,ledger:r.ledger,...r.report!==void 0&&{report:r.report}})}catch{}}}async awaitDispatchGate(){if(this.deps.beforeDispatch!==void 0)try{await this.deps.beforeDispatch()}catch{}}async respond(e){this.recordStartupFailure=this.deps.reasoner.beforeRunFailure(e,this.deps.turnId,this.reasonAbort.signal);let r=!1;if(this.ensureTts(),this.settled)return;let i=this.deps.reasoner.run(e,this.reasonAbort.signal,{register:"voice",turnId:this.deps.turnId});for await(let s of i){if(this.settled||(r||(r=!0,this.timeline.firstReasonerDelta(this.deps.clock.now())),this.parked&&(this.heldDelta=s,await this.untilUnparked(),this.heldDelta=null,this.settled)))return;this.dispatch(s)}if(this.loopDone=!0,this.settled)return;if(this.parked){this.parked=!1;return}for(let s of this.deps.segmenter.flush())this.push(s);let n=this.ttsStream;n!==null&&await n.end()}dispatch(e){if(e.type==="act.start"){e.channel==="speech"&&(this.openSpeech={actId:e.actId,characters:e.characters??0,...e.preamble===!0&&{preamble:!0}},this.openSeeded=e.characters!==void 0,this.speech.push(this.openSpeech)),UA(r=>this.deps.emit(r),this.deps.turnId,e);return}if(e.type==="act.end"){for(let r of this.deps.segmenter.flush())this.push(r);if(this.openSpeech?.actId===e.actId&&(this.openSpeech.characters=e.characters,e.notificationId!==void 0&&(this.openSpeech.notificationId=e.notificationId),this.openSpeech=null),UA(r=>this.deps.emit(r),this.deps.turnId,e),e.preamble!==!0&&this.timeline.actSettled(e.act),e.reason!==void 0&&(this.timeline.silence(e.reason),this.noteSilence(e.reason)),e.actId===this.cutActId){this.cutActId=null;for(let r of this.cuts)this.trySettleCut(r)}return}if(e.type!=="text"){if(e.type==="tool.start"){for(let r of this.deps.segmenter.flush())this.push(r);this.timeline.toolStarted()}Qp(r=>this.deps.emit(r),this.deps.turnId,e);return}if(this.openSpeech!==null&&!this.openSeeded&&(this.openSpeech.characters+=e.text.length),!(this.cutActId!==null&&this.openSpeech?.actId===this.cutActId)){this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:e.text});for(let r of this.deps.segmenter.push(e.text))this.push(r)}}push(e){let r;try{r=this.ensureTts()}catch(i){throw this.finishError("turn_failed",i),i}this.charsPushed+=e.length,r.pushText(e)}ensureTts(){if(this.ttsStream!==null)return this.ttsStream;let e=this.deps.ttsEngine.speak({voice:this.deps.voice,sampleRate:WN,encoding:NJ});return this.ttsStream=e,e.onAudio(r=>{this.settled||e!==this.ttsStream||(this.audioBytes+=r.byteLength,this.sawFirstAudio||(this.sawFirstAudio=!0,this.timeline.firstTtsAudio(this.deps.clock.now())),this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:r}))}),e.onError(r=>{e===this.ttsStream&&this.finishError("turn_failed",r)}),e}finishBlank(){this.settled||(this.settled=!0,this.timeline.blank(this.deps.clock.now()),this.deps.onComplete())}finishAsideAbsorbed(e,r){if(!this.settled){this.settled=!0,this.phase="cancelled",this.timeline.asideAbsorbed(this.deps.clock.now()),this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:{...e,disposition:"absorbed"},...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.onComplete();try{r.onAbsorbed()}catch{}}}finishDone(){if(this.settled)return;this.settled=!0;let e=this.terminalRecord();for(let r of this.cuts)this.trySettleCut(r,!0);this.noteTerminal(this.timeline.completed(this.deps.clock.now(),this.deps.reasoner.lastTurnTools(),e.hold),e),this.deps.emit({type:"response.done",turnId:this.deps.turnId}),this.deps.onComplete()}asrFailed(e){if(this.settled)return;let r=e instanceof Error?e:new Error(String(e));try{this.deps.onAsrFailure?.(r)}catch{}this.finishError(r instanceof fn?"asr_unavailable":"turn_failed",e)}finishError(e,r){if(this.settled)return;this.settled=!0,this.deps.controller.dispose(),this.recordStartupFailure?.(),this.deps.reasoner.noteFailure(this.deps.turnId),this.reasonAbort.abort(new ul);let i=this.ttsStream;this.ttsStream=null,i?.cancel(),this.heldDelta=null,this.releaseParked();let n=this.terminalRecord();for(let s of this.cuts)this.trySettleCut(s,!0);this.noteTerminal(this.timeline.failed(this.deps.clock.now(),e,n.hold),n),this.deps.emit({type:"error",turnId:this.deps.turnId,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId},reason:e,message:r instanceof Error?r.message:String(r)}),this.deps.onComplete()}buildUserTurn(e,r){return{source:"voice",turnId:this.deps.turnId,sessionId:this.deps.sessionId,deviceId:this.deps.deviceId,text:e,startMs:this.deps.startMs,endMs:r,...this.deps.projectId!==void 0&&{projectId:this.deps.projectId}}}}});import{randomUUID as JN}from"node:crypto";import{realpathSync as Xbe}from"node:fs";import{homedir as Kbe}from"node:os";function UJ(t){return`${(t/1e3).toFixed(1)}s`}function rQe(t){return t.length<=48?t:`${t.slice(0,48)}...`}function nQe(t){switch(t.state){case"none":return"not yet announced";case"shown":return"announced (shown)";case"played":return"announced, played in full";case"cut":return`announce cut at ${t.n} of ${t.m}: not fully heard`;case"unplayed":return"announce never played"}}function oQe(t){if(t.role!=="user"&&t.role!=="assistant")return null;if("toolCalls"in t){let e=t.toolCalls.filter(r=>sQe.has(r.name)).map(r=>typeof r.input=="object"&&r.input!==null?r.input.text:void 0).filter(r=>typeof r=="string"&&r.length>0);return e.length>0?{role:"assistant",text:e.join(" ")}:null}return t.content===""?null:{role:t.role,text:t.content}}var FJ,eQe,tQe,fI,iQe,ZN,bu,Gh,gI,sQe,OJ=D(()=>{"use strict";Tt();Gs();FA();cw();Zp();nm();$w();xO();kW();RW();JT();rN();UW();zw();$W();PW();GW();YW();HA();nN();OA();na();MN();PN();GN();qN();zN();Kp();LJ();FJ=250,eQe=4,tQe=1,fI=3e3;iQe=6,ZN=45e3,bu=class extends Error{constructor(e){super(e),this.name="ReasonerUnavailableError"}},Gh=class extends Error{constructor(e){super(e),this.name="VoiceUnavailableError"}},gI=class{deps;sessionId;deviceId;projectId;queue=new WE;closed=!1;closing=null;eventsConsumed=!1;inFlight=!1;reasoner=null;reasonerRoute=null;turnAbort=null;capturing=null;responding=null;parkBound=null;parkedAtMs=0;parkHeldFor=null;voiceTurnFailed=!1;asrUnavailable=null;mintedTurnId=null;voiceEngines=null;clock;newTurnController;newSmartTurnInference;newFrameClassifier;newTurnEvaluator;newSegmenter;smartTurnInference=null;frameClassifier=null;turnEvaluator=void 0;floorState="engaged";floorCounts={noResponse:{addressed_to_other:0,self_talk:0,no_reply_needed:0},asideEntries:0,asideExits:{resume:0,decay:0,explicit:0}};turnCounts={outcomes:{completed:0,superseded:0,barged:0,failed:0,lost:0,detached:0},acts:{}};jobs;notifications=new YE;playouts=new Map;playoutWaiters=[];cutUnwinding=null;asideDecayTimer=null;lastSpeechAtMs=0;cwd;scratch;constructor(e,r,i){this.deps=i,this.sessionId=e,this.deviceId=r.deviceId,this.projectId=r.projectId,this.cwd=r.launchDir??Kbe(),this.scratch=new pu(e,ee),this.clock=i.clock??new Gi,this.jobs=new em({now:()=>this.clock.now(),logger:ee,onDetached:n=>this.jobDetached(n),onSettled:n=>this.jobSettled(n)}),this.newSmartTurnInference=i.createSmartTurnInference??(()=>new Hh),this.newFrameClassifier=i.createFrameClassifier??(()=>new PA(new nc)),this.newTurnEvaluator=i.createTurnEvaluator??(n=>new xu(n)),this.newTurnController=i.createTurnController??(n=>{let s=this.ensureFrameClassifier();return new Ph(n,this.ensureSmartTurnInference(),{},this.speechObservingClassifier(s),this.semanticHook())}),this.newSegmenter=i.createSegmenter??(()=>new Nh),this.emit({type:"session.ready"})}async send(e){let{commandId:r}=e;if(this.closed)throw new Sr(r,"closed");if(e.sessionId!==this.sessionId)throw new Sr(r,"invalid","command sessionId does not match session");switch(e.type){case"input.text":this.acceptTextInput(e);return;case"input.audio.frame":this.acceptAudioFrame(e);return;case"input.audio.end":this.endAudioInput(e);return;case"turn.cancel":this.cancelTurn(e);return;case"turn.playout":this.acceptPlayout(e);return;case"session.close":return this.close();case"approval.resolve":throw new Sr(r,"unsupported");default:throw new Sr(r,"invalid")}}events(){if(this.eventsConsumed)throw new Error("CoreSession.events() supports a single consumer in v0.1");return this.eventsConsumed=!0,this.queue.drain()}close(){if(this.closed)return this.closing??Promise.resolve();this.closed=!0;let e=[],r;this.closing=new Promise(i=>{r=()=>{Promise.all(e).then(()=>i())}});try{this.turnAbort?.abort(),this.clearParkBound(),this.responding?.cancel("client_shutdown"),this.capturing?.cancel("client_shutdown");let i=this.jobs.cancelAll("shutdown");i>0&&(ee.debug("background jobs cancelled at shutdown",{count:i}),e.push(this.jobs.drain().catch(()=>{}))),this.asideDecayTimer!==null&&(this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=null);let n=this.smartTurnInference;this.smartTurnInference=null;let s=this.frameClassifier;this.frameClassifier=null;let o=this.turnEvaluator;this.turnEvaluator=null,this.settleHeldAtClose(),this.logFloorSummary(),this.logTurnSummary(),this.scratch.dispose(),this.queue.close(),n&&e.push(n.dispose().catch(()=>{})),s?.dispose&&e.push(s.dispose().catch(()=>{})),o?.dispose&&e.push(o.dispose().catch(()=>{}))}finally{r()}return this.closing}acceptTextInput(e){if(e.text.trim().length===0)throw new Sr(e.commandId,"invalid","input.text requires non-empty text");if(this.inFlight)throw new Sr(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0,this.exitAside("explicit");let r=JN();this.emit({type:"turn.accepted",turnId:r,clientTurnId:e.clientTurnId,source:"text",commandId:e.commandId}),this.emit({type:"turn.final",turnId:r,turn:this.toTextUserTurn(r,e),commandId:e.commandId}),this.runTextTurn(r,e)}async runTextTurn(e,r){let i=new AbortController;this.turnAbort=i;let n=!1,s=!1,o={};try{let a=this.ensureReasoner();if(await this.awaitDispatchReady(),this.closed)return;this.emit({type:"state",turnId:e,state:"responding"}),n=!0;for await(let c of a.run(r.text,i.signal,{turnId:e}))s=!0,c.type==="text"?this.emit({type:"response.delta",turnId:e,text:c.text}):c.type==="tool.start"||c.type==="tool.result"?Qp(l=>this.emit(l),e,c):(c.type==="act.end"&&(c.preamble!==!0&&(o[c.act]=(o[c.act]??0)+1),c.reason!==void 0&&this.countSilence(c.reason),c.notificationId!==void 0&&this.notifications.annotate(c.notificationId,{state:"shown"})),UA(l=>this.emit(l),e,c));this.closed||this.recordOutcome(s?"completed":"lost",o),this.emit({type:"response.done",turnId:e})}catch(a){n&&!this.closed&&this.recordOutcome("failed",o);let c=a instanceof bu?"no_text_route":a instanceof Ji?"channel_violation":"turn_failed";this.emit({type:"error",turnId:e,commandId:r.commandId,reason:c,message:a instanceof Error?a.message:String(a)})}finally{this.inFlight=!1,this.turnAbort=null}}acceptAudioFrame(e){if(this.capturing){this.capturing.pushFrame(e.audio,e.atMs);return}if(this.asrUnavailable!==null||this.voiceTurnFailed)return;if(this.inFlight&&this.responding?.isParked()!==!0)throw new Sr(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let r=JN();this.emit({type:"turn.accepted",turnId:r,clientTurnId:e.clientTurnId,source:"voice",commandId:e.commandId}),this.mintedTurnId=r;let i=this.resolveVoicePipeline(r,e.commandId);if(!i){this.voiceTurnFailed=!0;return}let n=this.floorHook(),s=new hI({turnId:r,sessionId:this.sessionId,deviceId:this.deviceId,...this.projectId!==void 0&&{projectId:this.projectId},commandId:e.commandId,startMs:e.atMs,asrEngine:i.engines.asrEngine,ttsEngine:i.engines.ttsEngine,voice:i.engines.voice,reasoner:i.reasoner,controller:this.newTurnController(this.clock),segmenter:this.newSegmenter(),clock:this.clock,emit:o=>this.emit(o),floor:n,onOutcome:(o,a)=>this.recordOutcome(o,a),onHeld:o=>this.holdTurn(o),onCutSettle:o=>this.settleCut(o),turnDetached:()=>this.jobs.hasRunningJobFrom(r),beforeDispatch:()=>this.awaitDispatchReady(),onDispatched:()=>this.turnDispatched(s),onFirstWords:o=>this.wordsHeard(o),onAsrFailure:o=>this.noteAsrFailure(o),onComplete:()=>this.completeVoiceTurn(s)});this.capturing=s,this.smartTurnInference?.prewarm?.(),this.frameClassifier?.prewarm?.(),s.pushFrame(e.audio,e.atMs)}endAudioInput(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}if(this.capturing){this.capturing.endAudio(e.atMs);return}this.exitAside("explicit")}cancelTurn(e){let r=e.turnId;if(this.voiceTurnFailed&&(r===void 0||r===this.mintedTurnId)){this.resetVoiceFailure();return}let i=r===void 0?this.capturing??this.responding:this.capturing?.turnId===r?this.capturing:this.responding?.turnId===r?this.responding:null;i!==null&&(e.reason==="barge_in"&&i===this.responding&&(i.isParked()||this.parkTurn(i))||this.abortTurn(i,e.reason))}abortTurn(e,r){if(e===this.responding){this.clearParkBound();let i=e.unwound().then(()=>{this.cutUnwinding===i&&(this.cutUnwinding=null),this.wakePlayoutWaiters()});this.cutUnwinding=i}e.cancel(r)}parkTurn(e){return e.park()?(this.clearParkBound(),e.isParked()&&(this.parkedAtMs=this.clock.now(),this.armParkBound(fI)),!0):!1}armParkBound(e){this.parkBound=this.clock.setTimer(e,()=>{this.parkBound=null,this.parkBoundElapsed()})}parkBoundElapsed(){if(this.responding?.isParked()!==!0)return;let r=this.capturing;if(r?.hasCommitted()===!0&&this.parkHeldFor!==r){this.parkHeldFor=r,this.armParkBound(fI);return}let i=this.clock.now()-Math.max(this.parkedAtMs,this.lastSpeechAtMs);i>=fI?this.resumeParked("no_words"):this.armParkBound(fI-i)}resumeParked(e){if(this.closed)return;let r=this.responding;if(r?.isParked()!==!0)return;let i=this.parkHeldFor;this.clearParkBound(),r.resume(e);let n=this.capturing;e==="no_words"&&n!==null&&(n.hasCommitted()?n===i&&(ee.debug("the barging utterance committed but its final never came - retired, the reply resumes",{turnId:n.turnId}),n.cancel("barge_in")):(ee.debug("the capturing turn the wordless barge opened is retired - no verdict could come",{turnId:n.turnId}),n.cancel("barge_in")))}clearParkBound(){this.parkHeldFor=null,this.parkBound!==null&&(this.clock.clearTimer(this.parkBound),this.parkBound=null)}wordsHeard(e){let r=this.responding;r!==null&&(ee.debug("the barging utterance carries words - the reply in flight yields",{stage:e,parked:r.isParked()}),this.abortTurn(r,"barge_in"))}turnDispatched(e){this.responding!==null&&this.responding!==e&&this.abortTurn(this.responding,"barge_in"),this.capturing===e&&(this.capturing=null),this.responding=e}noteAsrFailure(e){e instanceof fn&&(this.asrUnavailable=e.category,ee.debug("ASR terminally unavailable - voice input latched off for this session",{category:e.category}))}completeVoiceTurn(e){this.dropReportOnly(e.turnId),this.capturing===e?(this.capturing=null,this.resumeParked("blank")):this.responding===e&&(this.responding=null,this.clearParkBound()),this.inFlight=this.capturing!==null||this.responding!==null}dropReportOnly(e){if(e===null)return;let r=this.playouts.get(e);r!==void 0&&r.record===void 0&&this.playouts.delete(e)}resetVoiceFailure(){this.dropReportOnly(this.mintedTurnId),this.voiceTurnFailed=!1,this.mintedTurnId=null}resolveVoicePipeline(e,r){let i;try{i=this.ensureVoiceEngines()}catch(s){return this.emitTurnError(e,r,"no_voice_route",s),null}let n;try{n=this.ensureReasoner()}catch(s){let o=s instanceof bu?"no_text_route":"turn_failed";return this.emitTurnError(e,r,o,s),null}return{engines:i,reasoner:n}}ensureVoiceEngines(){if(this.voiceEngines)return this.voiceEngines;if(!this.deps.voiceRegistry)throw new Gh("voice is not available in this core build");let e=this.deps.configService.resolved(),r=e.routes?.stt,i=e.routes?.tts;if(!r||!i)throw new Gh("no voice route configured - run 'jarvis init' to set routes.stt and routes.tts");let n=!e.secrets?.[r.provider]&&Yr(r.provider),s=!e.secrets?.[i.provider]&&Yr(i.provider);if(n||s){let l=n?r.provider:i.provider;throw new Gh(`no API key for voice provider '${l}' - run 'jarvis init' to add it`)}let o=this.deps.voiceRegistry.asrEngine({provider:r.provider,model:r.model,...r.url!==void 0&&{url:r.url}},e.secrets?.[r.provider]??""),a=this.deps.voiceRegistry.ttsEngine({provider:i.provider,model:i.model},e.secrets?.[i.provider]??""),c=this.deps.voiceIdentity??jN(i.voiceId);return this.voiceEngines={asrEngine:o,ttsEngine:a,voice:c},this.voiceEngines}ensureSmartTurnInference(){return this.smartTurnInference??=this.newSmartTurnInference(),this.smartTurnInference}ensureFrameClassifier(){return this.frameClassifier??=this.newFrameClassifier(),this.frameClassifier}semanticHook(){if(this.turnEvaluator===void 0){let r=this.reasonerRoute;this.turnEvaluator=r?.provider==="anthropic"?this.newTurnEvaluator(r.key):null}return this.turnEvaluator===null?void 0:{evaluator:this.turnEvaluator,recentTurns:()=>{let r=[];for(let i of this.reasoner?.historySnapshot()??[]){let n=oQe(i);n&&r.push(n)}return r.slice(-iQe)}}}floorHook(){return{floorState:()=>this.floorState,onSilence:e=>{this.countSilence(e),e==="addressed_to_other"&&this.enterAside(e)},onAbsorbed:()=>this.noteSpeech(),onFloorReleased:e=>this.exitAside(e)}}enterAside(e){this.floorState!=="aside"&&(this.floorState="aside",this.floorCounts.asideEntries+=1,this.noteSpeech(),this.armAsideDecay(ZN),ee.debug("aside entered - utterances now absorb by default",{reason:e}),this.emit({type:"state",state:"aside"}))}exitAside(e){this.floorState==="aside"&&(this.floorState="engaged",this.floorCounts.asideExits[e]+=1,this.asideDecayTimer!==null&&(this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=null),ee.debug("aside exited",{reason:e}))}countSilence(e){this.floorCounts.noResponse[e]+=1}recordOutcome(e,r){this.turnCounts.outcomes[e]+=1;for(let[i,n]of Object.entries(r))this.turnCounts.acts[i]=(this.turnCounts.acts[i]??0)+n}jobDetached(e){ee.debug("background job detached",{jobId:e.jobId,tool:e.tool,origin:e.origin}),!this.closed&&this.emit({type:"job.detached",...e.turnId!==void 0&&{turnId:e.turnId},jobId:e.jobId,tool:e.tool})}jobSettled(e){this.reasoner?.settleResult(e.record.jobId,e.result,e.isError),ee.debug("background job settled",{jobId:e.record.jobId,tool:e.record.tool,outcome:e.outcome,durationMs:Math.round(e.durationMs)}),!this.closed&&(e.outcome==="ok"?this.notifications.add(`${e.record.tool} job ${e.record.jobId} finished ok in ${UJ(e.durationMs)}`,"normal"):e.outcome==="failed"&&this.notifications.add(`${e.record.tool} job ${e.record.jobId} FAILED after ${UJ(e.durationMs)}`,"high"),this.emit({type:"job.result",...e.record.turnId!==void 0&&{turnId:e.record.turnId},jobId:e.record.jobId,tool:e.record.tool,outcome:e.outcome,durationMs:Math.round(e.durationMs)}))}holdTurn(e){if(this.closed){e.held.emit(e.held.fallback);return}let r=this.playouts.get(e.turnId)??{};r.record=e,e.report!==void 0&&r.report===void 0&&(r.report=e.report),this.playouts.set(e.turnId,r),this.joinPlayout(e.turnId)}acceptPlayout(e){let r={playedMs:e.playedMs,end:e.end},i=this.responding?.turnId===e.turnId?this.responding:this.capturing?.turnId===e.turnId?this.capturing:null;if(i?.acceptCutReport(r)===!0)return;let n=this.playouts.get(e.turnId);if(n===void 0&&i===null){ee.debug("playout report for a turn with no held record - nothing to settle",{end:e.end});return}let s=n??{};s.report===void 0&&(s.report=r,this.playouts.set(e.turnId,s),this.joinPlayout(e.turnId))}joinPlayout(e){let r=this.playouts.get(e);if(r?.record===void 0||r.report===void 0)return;this.playouts.delete(e);let{held:i,ledger:n}=r.record,{end:s}=r.report,{playedMs:o,boundary:a,characters:c}=this.settleReport(n,r.report),l=i.fallback==="failed"?"failed":s==="cut"?i.detachedJob?"detached":o>0||i.commandStarted?"barged":"superseded":i.fallback;i.emit(l,{playedMs:o,spokenCharacters:a,characters:c}),this.recordOutcome(l,i.acts),this.wakePlayoutWaiters()}settleCut(e){let{playedMs:r,boundary:i,characters:n}=this.settleReport(e.ledger,e.report);ee.debug("voice turn cut settled - the audio was cut; the reply continues",{turnId:e.turnId,playedMs:r,spokenCharacters:i,characters:n})}settleReport(e,r){let{end:i}=r,n=Number.isFinite(r.playedMs)&&r.playedMs>0?r.playedMs:0,s=qw(e),a=i==="drained"&&n>0&&n>=e.audioMs-tQe?s:aO(n,e),c=cO(e.acts,a),l=new Set(e.acts.filter(u=>u.preamble===!0).map(u=>u.actId));for(let u of c){if(l.has(u.actId)){this.reasoner?.settleAnnouncement(u.actId,u);continue}this.reasoner?.settleSpeech(u.actId,u)}for(let u of e.acts){if(u.notificationId===void 0)continue;let d=c.find(h=>h.actId===u.actId);d!==void 0&&this.notifications.annotate(u.notificationId,d.kind==="spoken"?{state:"played"}:d.kind==="partial"?{state:"cut",n:d.n,m:d.m}:{state:"unplayed"})}return{playedMs:n,boundary:a,characters:s}}settleHeldAtClose(){for(let e of[...this.playouts.keys()])this.releaseHeld(e);this.playouts.clear(),this.cutUnwinding=null,this.wakePlayoutWaiters()}releaseHeld(e){let r=this.playouts.get(e);this.playouts.delete(e),r?.record!==void 0&&(r.record.held.emit(r.record.held.fallback),this.recordOutcome(r.record.held.fallback,r.record.held.acts))}expireOutstanding(){this.cutUnwinding=null;let e=[];for(let[r,i]of this.playouts)i.record!==void 0&&i.report===void 0&&(i.stale=!0,e.push(r));for(let r of e.slice(0,Math.max(0,e.length-eQe)))this.releaseHeld(r)}awaitDispatchReady(){return this.playoutOutstanding()?new Promise(e=>{let r=!1,i=()=>{r||(r=!0,this.clock.clearTimer(s),this.playoutWaiters=this.playoutWaiters.filter(o=>o!==n),e())},n=()=>{this.playoutOutstanding()||i()},s=this.clock.setTimer(FJ,()=>{ee.debug("dispatch proceeded before the last playout settled",{boundMs:FJ,awaitingReport:[...this.playouts.values()].filter(o=>o.record!==void 0&&o.report===void 0&&o.stale!==!0).length,cutUnwinding:this.cutUnwinding!==null}),this.expireOutstanding(),i()});this.playoutWaiters.push(n)}):Promise.resolve()}playoutOutstanding(){if(this.cutUnwinding!==null)return!0;for(let e of this.playouts.values())if(e.record!==void 0&&e.report===void 0&&e.stale!==!0)return!0;return!1}wakePlayoutWaiters(){for(let e of[...this.playoutWaiters])e()}sessionStateBlock(){let e=this.jobs.list(),r=this.notifications.list();if(e.length===0&&r.length===0)return;let i=["Session state:"];if(e.length>0){i.push(`- Background jobs (${e.length} of ${jw} slots; the [bracketed] value is cancel_job's jobId):`);let n=this.clock.now();for(let s of e){let o=Math.max(0,Math.round((n-s.startedAtMs)/1e3)),a=s.display!==void 0?` "${rQe(s.display)}"`:"",c=s.cancelling?"cancelling":`running, ${o}s`;i.push(` - [${s.jobId}] ${s.tool}${a} - ${c}`)}}if(r.length>0){i.push("- Queued notifications (announce with say_notification - the record then shows whether it played; dismiss_notification discards silently; when unsure whether one was heard, keep it):");for(let n of r)i.push(` - [${n.id}, ${n.priority}] ${n.text} - ${nQe(n.announce)}`)}return i.join(`
393
393
  `)}logTurnSummary(){let{outcomes:e,acts:r}=this.turnCounts;Object.values(e).some(i=>i>0)&&ee.debug("session turn summary",{outcomes:{...e},acts:{...r}})}logFloorSummary(){let{noResponse:e,asideEntries:r,asideExits:i}=this.floorCounts;(r>0||Object.values(e).some(s=>s>0)||Object.values(i).some(s=>s>0))&&ee.debug("session floor summary",{noResponse:{...e},asideEntries:r,asideExits:{...i}})}armAsideDecay(e){this.asideDecayTimer!==null&&this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=this.clock.setTimer(e,()=>this.asideDecayElapsed())}asideDecayElapsed(){if(this.asideDecayTimer=null,this.floorState!=="aside")return;let e=this.clock.now()-this.lastSpeechAtMs;e>=ZN?this.exitAside("decay"):this.armAsideDecay(ZN-e)}noteSpeech(){this.lastSpeechAtMs=this.clock.now()}speechObservingClassifier(e){return{classify:(r,i)=>e.classify(r,n=>{n&&this.noteSpeech(),i(n)})}}ensureReasoner(){if(this.reasoner)return this.reasoner;let e=this.deps.configService.resolved(),r=e.routes?.text;if(!r)throw new bu("no text model is configured - run 'jarvis init' to set routes.text");let i=Yr(r.provider)?e.secrets?.[r.provider]:"";if(!i&&Yr(r.provider))throw new bu(`no API key for text provider '${r.provider}' - run 'jarvis init' to add it`);let n=this.deps.registry.textAdapter({provider:r.provider,model:r.model,...r.url!==void 0&&{url:r.url}},i??"");return this.reasoner=new sd(n,r.model,this.deps.systemPrompt,this.buildTools(e)),this.reasonerRoute={provider:r.provider,key:i??""},this.reasoner}buildTools(e){let r=Yt.dir(),i=r;try{i=Xbe(r)}catch{}let n=new jE(i),s=new VE,o=new GE;o.add(n),o.add(s);let a=new qE;for(let l of cl)a.register(l);a.register(BO),a.register(_W(s,{spill:l=>this.scratch.spill("fetch",l)}));let c=this.registerWebSearch(a,e);return a.register(AO(this.jobs)),a.register(OW(this.notifications)),{registry:a,hooks:o,cwd:this.cwd,logger:ee,guard:n,jobs:this.jobs,sessionState:()=>this.sessionStateBlock(),...c!==void 0&&{searchProvider:c}}}registerWebSearch(e,r){let i=r.routes?.search;if(!i)return;let n=r.secrets?.[i.provider];if(!n){ee.debug("search route configured but no key - web_search unregistered",{provider:i.provider});return}if(this.deps.registry.searchAdapter)try{let s=this.deps.registry.searchAdapter({provider:i.provider},n);return e.register(NW(s,i.provider,{spill:o=>this.scratch.spill("search",o)})),i.provider}catch(s){ee.debug("search adapter could not be built - web_search unregistered",{provider:i.provider,errorName:s instanceof Error?s.name:typeof s});return}}toTextUserTurn(e,r){return{source:"text",turnId:e,sessionId:this.sessionId,deviceId:this.deviceId,text:r.text,atMs:r.atMs,...this.projectId!==void 0&&{projectId:this.projectId}}}emitTurnError(e,r,i,n){this.emit({type:"error",turnId:e,commandId:r,reason:i,message:n instanceof Error?n.message:String(n)}),this.inFlight=this.responding!==null}emit(e){this.queue.push({...e,sessionId:this.sessionId,eventId:JN(),atMs:Date.now()})}},sQe=new Set(cl.filter(t=>t.channel==="speech").map(t=>t.name))});function aQe(t,e,r){let i=new URL(t);i.searchParams.set("model_id",e),i.searchParams.set("audio_format",cQe(r)),i.searchParams.set("commit_strategy","manual"),r.language&&i.searchParams.set("language_code",r.language);for(let n of r.biasTerms??[])i.searchParams.append("keyterms",n);return i.toString()}function cQe(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var $J,Yh,XN,KN=D(()=>{"use strict";HA();YA();$J="wss://api.elevenlabs.io/v1/speech-to-text/realtime",Yh=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-scribe";constructor(e,r,i,n=$J){this.apiKey=e,this.socketFactory=r,this.model=i,this.endpoint=n}open(e){return new XN(this.apiKey,this.socketFactory,this.model,this.endpoint,e)}},XN=class{opts;socket;opened=!1;aborted=!1;closed=!1;pending=[];committed=[];transcriptCb;errorCb;endPending=null;commitRequested=!1;constructor(e,r,i,n,s){this.opts=s,this.socket=r(aQe(n,i,s),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(o=>this.handleMessage(o)),this.socket.onError(o=>this.handleError(o)),this.socket.onClose(()=>this.handleClose())}pushAudio(e){if(!(this.aborted||this.closed||this.commitRequested)){if(!this.opened){this.pending.push(e);return}this.sendChunk(e,!1)}}onTranscript(e){this.transcriptCb=e}onError(e){this.errorCb=e}end(){return this.aborted?Promise.reject(new Error("ASR stream already aborted")):this.endPending?Promise.reject(new Error("ASR end() already in progress")):new Promise((e,r)=>{this.endPending={resolve:e,reject:r},this.commitRequested=!0,this.opened&&this.sendCommit()})}abort(){if(this.aborted=!0,this.endPending){let{reject:e}=this.endPending;this.endPending=null,e(new Error("ASR stream aborted"))}return this.teardown(),Promise.resolve()}handleOpen(){if(!(this.aborted||this.closed)){this.opened=!0;for(let e of this.pending)this.sendChunk(e,!1);this.pending.length=0,this.commitRequested&&this.sendCommit()}}handleMessage(e){if(this.aborted||this.closed)return;let r=Ws(e);if(!r)return;let i=Xc(r);if(i){let s=zF(i);this.handleError(s!==null?new fn(`stream error (${i})`,s):new Error(`stream error (${i})`));return}let n=r.message_type;if(n==="partial_transcript"){this.opts.emitPartials&&this.transcriptCb?.({text:VA(r.text),isFinal:!1,startMs:0});return}if(n==="committed_transcript"||n==="committed_transcript_with_timestamps"){let s=VA(r.text);s.length>0&&this.committed.push(s),this.endPending&&this.resolveEnd()}}handleError(e){if(this.closed)return;let r=WF("ElevenLabs ASR",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(r)}this.errorCb?.(r),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs ASR connection closed unexpectedly");if(this.endPending){let{reject:r}=this.endPending;this.endPending=null,r(e)}this.errorCb?.(e)}resolveEnd(){if(!this.endPending)return;let e={text:this.committed.join(" ").trim(),isFinal:!0,startMs:0};this.transcriptCb?.(e);let{resolve:r}=this.endPending;this.endPending=null,this.teardown(),r(e)}sendChunk(e,r){this.socket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:jF(e),commit:r,sample_rate:this.opts.sampleRate}))}sendCommit(){this.sendChunk(new Uint8Array(0),!0)}teardown(){this.closed||(this.closed=!0,this.socket.close())}}});import{randomUUID as lQe}from"node:crypto";function AQe(t,e){let r=t.engineVoice[e];if(!r)throw new Error(`voice '${t.id}' has no '${e}' engineVoice mapping`);if(r.kind!=="preset")throw new Error(`the ${e} adapter needs a preset voiceId for '${t.id}', got kind '${r.kind}'`);return r.voiceId}function dQe(t,e,r,i){let n=new URL(t.replace("{voice_id}",encodeURIComponent(e)));return n.searchParams.set("model_id",r),n.searchParams.set("output_format",hQe(i)),n.searchParams.set("inactivity_timeout","180"),n.searchParams.set("auto_mode","true"),n.toString()}function hQe(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var PJ,uQe,qh,eR,tR=D(()=>{"use strict";YA();PJ="wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/multi-stream-input",uQe={stability:.5,similarity_boost:.75,use_speaker_boost:!0},qh=class{apiKey;socketFactory;model;endpointTemplate;id="elevenlabs-flash";constructor(e,r,i,n=PJ){this.apiKey=e,this.socketFactory=r,this.model=i,this.endpointTemplate=n}speak(e){return new eR(this.apiKey,this.socketFactory,this.model,this.endpointTemplate,this.id,e)}},eR=class{socket;contextId=lQe();opened=!1;cancelled=!1;closed=!1;endRequested=!1;closeContextSent=!1;pending=[];audioCb;errorCb;endPending=null;constructor(e,r,i,n,s,o){let a=AQe(o.voice,s);this.socket=r(dQe(n,a,i,o),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(c=>this.handleMessage(c)),this.socket.onError(c=>this.handleError(c)),this.socket.onClose(()=>this.handleClose())}pushText(e){if(!(this.cancelled||this.closed||this.endRequested)){if(!this.opened){this.pending.push(e);return}this.sendText(e)}}onAudio(e){this.audioCb=e}onError(e){this.errorCb=e}end(){return this.cancelled||this.closed?Promise.resolve():this.endPending?Promise.reject(new Error("TTS end() already in progress")):new Promise((e,r)=>{this.endPending={resolve:e,reject:r},this.endRequested=!0,this.opened&&this.sendEndOfContext()})}cancel(){if(this.cancelled||this.closed)return this.cancelled=!0,Promise.resolve();if(this.cancelled=!0,this.endPending){let{resolve:e}=this.endPending;this.endPending=null,e()}return this.opened&&this.sendCloseContext(),this.teardown(),Promise.resolve()}handleOpen(){if(!(this.cancelled||this.closed)){this.opened=!0,this.sendInit();for(let e of this.pending)this.sendText(e);this.pending.length=0,this.endRequested&&this.sendEndOfContext()}}handleMessage(e){if(this.cancelled||this.closed)return;let r=Ws(e);if(!r)return;let i=Xc(r);if(i){this.handleError(new Error(`stream error (${i})`));return}typeof r.audio=="string"&&r.audio.length>0&&this.audioCb?.(Sp(r.audio)),(r.isFinal===!0||r.is_final===!0)&&this.resolveEnd()}handleError(e){if(this.closed)return;let r=GA("ElevenLabs TTS",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(r)}this.errorCb?.(r),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs TTS connection closed unexpectedly");if(this.endPending){let{reject:r}=this.endPending;this.endPending=null,r(e)}this.errorCb?.(e)}resolveEnd(){if(!this.endPending)return;let{resolve:e}=this.endPending;this.endPending=null,this.teardown(),e()}sendInit(){this.socket.send(JSON.stringify({text:" ",voice_settings:uQe,context_id:this.contextId}))}sendText(e){let r=e.endsWith(" ")?e:`${e} `;this.socket.send(JSON.stringify({text:r,context_id:this.contextId}))}sendEndOfContext(){this.sendFlush(),this.sendCloseContext()}sendFlush(){this.socket.send(JSON.stringify({context_id:this.contextId,text:"",flush:!0}))}sendCloseContext(){this.closeContextSent||(this.closeContextSent=!0,this.socket.send(JSON.stringify({context_id:this.contextId,close_context:!0})))}teardown(){this.closed||(this.closed=!0,this.socket.close())}}});function fQe(t){if(t===void 0)return;let e;try{e=new URL(t).protocol}catch{throw new Error("sherpa-onnx ASR route url must be a valid ws:// or wss:// URL")}if(e!=="ws:"&&e!=="wss:")throw new Error(`sherpa-onnx ASR route url must use the ws:// or wss:// scheme (got '${e}//' - this is a WebSocket endpoint, not HTTP)`)}var jh,rR=D(()=>{"use strict";KN();tR();Tp();fw();_p();jp();jh=class{socketFactory;fetchImpl;constructor(e=al,r=fetch){this.socketFactory=e,this.fetchImpl=r}asrEngine(e,r){switch(e.provider){case"elevenlabs":return new Yh(r,this.socketFactory,e.model);case"sherpa-onnx":return fQe(e.url),new qA(this.socketFactory,e.url);case"openai-compat":return new vp(this.fetchImpl,e.url,e.model,r);default:throw new Error(`no stt adapter for provider '${e.provider}'`)}}ttsEngine(e,r){if(e.provider==="elevenlabs")return kp.includes(e.model)?new jA(r,this.socketFactory,e.model):new qh(r,this.socketFactory,e.model);throw new Error(`no tts adapter for provider '${e.provider}'`)}}});import{randomUUID as gQe}from"node:crypto";function iR(t={}){let e=new ea(void 0,t.logLevel);ee.setLevel(e.logLevel),ee.debug("core created",{logLevel:e.logLevel}),pu.sweepStale(ee);let{fetchImpl:r}=t,i={configService:t.configService??new wr,registry:t.registry??new LA(r),voiceRegistry:t.voiceRegistry??new jh(t.voiceSocketFactory,r),createTurnEvaluator:t.createTurnEvaluator??(n=>new xu(n,r)),...t.systemPrompt!==void 0&&{systemPrompt:t.systemPrompt},...t.voiceIdentity!==void 0&&{voiceIdentity:t.voiceIdentity},...t.createTurnController!==void 0&&{createTurnController:t.createTurnController},...t.createSmartTurnInference!==void 0&&{createSmartTurnInference:t.createSmartTurnInference},...t.createFrameClassifier!==void 0&&{createFrameClassifier:t.createFrameClassifier},...t.createSegmenter!==void 0&&{createSegmenter:t.createSegmenter},...t.clock!==void 0&&{clock:t.clock}};return new nR(i)}var pQe,mQe,nR,HJ=D(()=>{"use strict";Tt();WQ();JQ();aw();OJ();rN();qN();rR();pQe="jarvis-core",mQe="0.1.0-dev",nR=class{deps;constructor(e){this.deps=e}describe(){return Promise.resolve({name:pQe,version:mQe})}openSession(e){let r=gQe();return ee.debug("core opened session",{sessionId:r,capabilities:e.clientCapabilities}),Promise.resolve(new gI(r,e,this.deps))}}});import{readFileSync as EQe,writeFileSync as IQe}from"node:fs";function zh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function BQe(t,e){let r={};if(!zh(t))return r;for(let i of CQe){let n=t[i];if(!Array.isArray(n))continue;let s=[];for(let o of n)!zh(o)||typeof o.id!="string"||s.push(typeof o.label=="string"?{id:o.id,label:o.label}:{id:o.id});(s.length>0||e&&i==="text"&&n.length===0)&&(r[i]=s)}return r}var YJ,qJ,VJ,GJ,yQe,CQe,Es,jJ=D(()=>{"use strict";Gs();Zp();$i();Zc();YJ="model-catalogue.json",qJ=1440*60*1e3,VJ=2,GJ=1,yQe={stt:!0,tts:!0,text:!0,embedding:!0,search:!0},CQe=Object.keys(yQe);Es=class{fetchImpl;timeoutMs=3e3;home;now;ttlMs;providers;fetchFailed=new Set;constructor(e=fetch,r){this.fetchImpl=e,this.home=r?.home??Yt,this.now=r?.now??(()=>Date.now()),this.ttlMs=r?.ttlMs??qJ,this.providers=Jp}async models(e,r,i){let n=this.providers[e],s=n?.defaultModel[r],o=n?.fastModel?.[r],a={source:"prefill",models:s===void 0?[]:[{id:s}],recommended:s,recommendedFast:o};if(!n?.listModels||!n.capabilities.includes(r))return a;let c=this.readCacheEntry(e,i?.url),l=c?.models[r],u=c===void 0?0:Math.max(0,this.now()-c.fetchedAtMs),d=A=>({source:"cache",models:A,recommended:s,recommendedFast:o,cacheAgeMs:u});if(c!==void 0){let A=this.now()-c.fetchedAtMs;if(c.currentCuration&&A>=0&&A<this.ttlMs)return l===void 0?a:d(l)}let h=await this.tryFetch(e,n,i);if(h!==void 0){let A=h[r];return A===void 0?a:{source:"live",models:A,recommended:s,recommendedFast:o}}return l!==void 0?d(l):a}async refresh(e,r){let i=this.providers[e];if(!i?.listModels)return{ok:!1,status:"no-lister"};let n=this.cacheIdentity(e,r?.url);if(n===void 0)return{ok:!1,status:"failed",detail:"invalid Ollama server address"};this.fetchFailed.delete(n);let s=o=>{let a=this.readCacheEntry(e,r?.url);return a===void 0?{ok:!1,status:"failed",detail:o}:{ok:!1,status:"failed",detail:o,cached:{models:a.models,cacheAgeMs:Math.max(0,this.now()-a.fetchedAtMs)}}};if(i.keylessLister!==!0&&r?.key===void 0)return s("no API key available");try{let o=r?.signal??AbortSignal.timeout(this.timeoutMs),a=await i.listModels(r?.key,this.fetchImpl,o,r);return this.writeCacheEntry(e,a,r?.url),{ok:!0,status:"refreshed",models:a}}catch(o){return s(qt(o,r?.key))}}cached(e,r,i){let n=this.readCacheEntry(e,i?.url),s=n?.models[r];if(n===void 0||s===void 0)return;let o=this.now()-n.fetchedAtMs;return{models:s,cacheAgeMs:Math.max(0,o),fresh:n.currentCuration&&o>=0&&o<this.ttlMs}}async tryFetch(e,r,i){if(r.listModels===void 0)return;let n=this.cacheIdentity(e,i?.url);if(!(n===void 0||this.fetchFailed.has(n))&&!(r.keylessLister!==!0&&i?.key===void 0))try{let s=i?.signal??AbortSignal.timeout(this.timeoutMs),o=await r.listModels(i?.key,this.fetchImpl,s,i);return this.writeCacheEntry(e,o,i?.url),o}catch{this.fetchFailed.add(n);return}}cachePath(){return this.home.resolve(YJ)}readCacheFile(){let e;try{e=JSON.parse(EQe(this.cachePath(),"utf8"))}catch{return}if(!(!zh(e)||e.version!==VJ))return zh(e.providers)?e.providers:void 0}readCacheEntry(e,r){let i=this.cacheIdentity(e,r);if(i===void 0)return;let n=this.readCacheFile()?.[i];if(!zh(n))return;let{fetchedAtMs:s}=n;if(typeof s!="number"||!Number.isFinite(s))return;let o=BQe(n.models,e==="ollama-local");if(Object.keys(o).length===0)return;let a=e!=="elevenlabs"||n.curationRevision===GJ;return{fetchedAtMs:s,models:o,currentCuration:a}}writeCacheEntry(e,r,i){try{let n=this.cacheIdentity(e,i);if(n===void 0)return;let s=this.readCacheFile()??{};s[n]={fetchedAtMs:this.now(),models:r,...e==="elevenlabs"?{curationRevision:GJ}:{}},this.home.ensureDir(),IQe(this.cachePath(),`${JSON.stringify({version:VJ,providers:s},null,2)}
394
394
  `)}catch{}}cacheIdentity(e,r){try{return TA(e,r)}catch{return}}}});var Is=D(()=>{"use strict";HJ();JQ();Zp();jJ();aw();ow();Zc();DA();nm();Wc();jc();jp();KN();tR();Tp();_p();rR();zN();$N();PN();GN();na();MN();RN();cI();VN();nN();OA()});var vu=b((WPe,XJ)=>{"use strict";var TQe="2.0.0",NQe=Number.MAX_SAFE_INTEGER||9007199254740991,RQe=16,MQe=250,LQe=["major","premajor","minor","preminor","patch","prepatch","prerelease"];XJ.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:RQe,MAX_SAFE_BUILD_LENGTH:MQe,MAX_SAFE_INTEGER:NQe,RELEASE_TYPES:LQe,SEMVER_SPEC_VERSION:TQe,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Zh=b((JPe,KJ)=>{"use strict";var FQe=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};KJ.exports=FQe});var Su=b((Di,e5)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:aR,MAX_SAFE_BUILD_LENGTH:UQe,MAX_LENGTH:OQe}=vu(),$Qe=Zh();Di=e5.exports={};var PQe=Di.re=[],HQe=Di.safeRe=[],X=Di.src=[],VQe=Di.safeSrc=[],K=Di.t={},GQe=0,cR="[a-zA-Z0-9-]",YQe=[["\\s",1],["\\d",OQe],[cR,UQe]],qQe=t=>{for(let[e,r]of YQe)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},Be=(t,e,r)=>{let i=qQe(e),n=GQe++;$Qe(t,n,e),K[t]=n,X[n]=e,VQe[n]=i,PQe[n]=new RegExp(e,r?"g":void 0),HQe[n]=new RegExp(i,r?"g":void 0)};Be("NUMERICIDENTIFIER","0|[1-9]\\d*");Be("NUMERICIDENTIFIERLOOSE","\\d+");Be("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${cR}*`);Be("MAINVERSION",`(${X[K.NUMERICIDENTIFIER]})\\.(${X[K.NUMERICIDENTIFIER]})\\.(${X[K.NUMERICIDENTIFIER]})`);Be("MAINVERSIONLOOSE",`(${X[K.NUMERICIDENTIFIERLOOSE]})\\.(${X[K.NUMERICIDENTIFIERLOOSE]})\\.(${X[K.NUMERICIDENTIFIERLOOSE]})`);Be("PRERELEASEIDENTIFIER",`(?:${X[K.NONNUMERICIDENTIFIER]}|${X[K.NUMERICIDENTIFIER]})`);Be("PRERELEASEIDENTIFIERLOOSE",`(?:${X[K.NONNUMERICIDENTIFIER]}|${X[K.NUMERICIDENTIFIERLOOSE]})`);Be("PRERELEASE",`(?:-(${X[K.PRERELEASEIDENTIFIER]}(?:\\.${X[K.PRERELEASEIDENTIFIER]})*))`);Be("PRERELEASELOOSE",`(?:-?(${X[K.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${X[K.PRERELEASEIDENTIFIERLOOSE]})*))`);Be("BUILDIDENTIFIER",`${cR}+`);Be("BUILD",`(?:\\+(${X[K.BUILDIDENTIFIER]}(?:\\.${X[K.BUILDIDENTIFIER]})*))`);Be("FULLPLAIN",`v?${X[K.MAINVERSION]}${X[K.PRERELEASE]}?${X[K.BUILD]}?`);Be("FULL",`^${X[K.FULLPLAIN]}$`);Be("LOOSEPLAIN",`[v=\\s]*${X[K.MAINVERSIONLOOSE]}${X[K.PRERELEASELOOSE]}?${X[K.BUILD]}?`);Be("LOOSE",`^${X[K.LOOSEPLAIN]}$`);Be("GTLT","((?:<|>)?=?)");Be("XRANGEIDENTIFIERLOOSE",`${X[K.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Be("XRANGEIDENTIFIER",`${X[K.NUMERICIDENTIFIER]}|x|X|\\*`);Be("XRANGEPLAIN",`[v=\\s]*(${X[K.XRANGEIDENTIFIER]})(?:\\.(${X[K.XRANGEIDENTIFIER]})(?:\\.(${X[K.XRANGEIDENTIFIER]})(?:${X[K.PRERELEASE]})?${X[K.BUILD]}?)?)?`);Be("XRANGEPLAINLOOSE",`[v=\\s]*(${X[K.XRANGEIDENTIFIERLOOSE]})(?:\\.(${X[K.XRANGEIDENTIFIERLOOSE]})(?:\\.(${X[K.XRANGEIDENTIFIERLOOSE]})(?:${X[K.PRERELEASELOOSE]})?${X[K.BUILD]}?)?)?`);Be("XRANGE",`^${X[K.GTLT]}\\s*${X[K.XRANGEPLAIN]}$`);Be("XRANGELOOSE",`^${X[K.GTLT]}\\s*${X[K.XRANGEPLAINLOOSE]}$`);Be("COERCEPLAIN",`(^|[^\\d])(\\d{1,${aR}})(?:\\.(\\d{1,${aR}}))?(?:\\.(\\d{1,${aR}}))?`);Be("COERCE",`${X[K.COERCEPLAIN]}(?:$|[^\\d])`);Be("COERCEFULL",X[K.COERCEPLAIN]+`(?:${X[K.PRERELEASE]})?(?:${X[K.BUILD]})?(?:$|[^\\d])`);Be("COERCERTL",X[K.COERCE],!0);Be("COERCERTLFULL",X[K.COERCEFULL],!0);Be("LONETILDE","(?:~>?)");Be("TILDETRIM",`(\\s*)${X[K.LONETILDE]}\\s+`,!0);Di.tildeTrimReplace="$1~";Be("TILDE",`^${X[K.LONETILDE]}${X[K.XRANGEPLAIN]}$`);Be("TILDELOOSE",`^${X[K.LONETILDE]}${X[K.XRANGEPLAINLOOSE]}$`);Be("LONECARET","(?:\\^)");Be("CARETTRIM",`(\\s*)${X[K.LONECARET]}\\s+`,!0);Di.caretTrimReplace="$1^";Be("CARET",`^${X[K.LONECARET]}${X[K.XRANGEPLAIN]}$`);Be("CARETLOOSE",`^${X[K.LONECARET]}${X[K.XRANGEPLAINLOOSE]}$`);Be("COMPARATORLOOSE",`^${X[K.GTLT]}\\s*(${X[K.LOOSEPLAIN]})$|^$`);Be("COMPARATOR",`^${X[K.GTLT]}\\s*(${X[K.FULLPLAIN]})$|^$`);Be("COMPARATORTRIM",`(\\s*)${X[K.GTLT]}\\s*(${X[K.LOOSEPLAIN]}|${X[K.XRANGEPLAIN]})`,!0);Di.comparatorTrimReplace="$1$2$3";Be("HYPHENRANGE",`^\\s*(${X[K.XRANGEPLAIN]})\\s+-\\s+(${X[K.XRANGEPLAIN]})\\s*$`);Be("HYPHENRANGELOOSE",`^\\s*(${X[K.XRANGEPLAINLOOSE]})\\s+-\\s+(${X[K.XRANGEPLAINLOOSE]})\\s*$`);Be("STAR","(<|>)?=?\\s*\\*");Be("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Be("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var yI=b((ZPe,t5)=>{"use strict";var jQe=Object.freeze({loose:!0}),zQe=Object.freeze({}),WQe=t=>t?typeof t!="object"?jQe:t:zQe;t5.exports=WQe});var lR=b((XPe,i5)=>{"use strict";var r5=/^[0-9]+$/,n5=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let r=r5.test(t),i=r5.test(e);return r&&i&&(t=+t,e=+e),t===e?0:r&&!i?-1:i&&!r?1:t<e?-1:1},JQe=(t,e)=>n5(e,t);i5.exports={compareIdentifiers:n5,rcompareIdentifiers:JQe}});var Kt=b((KPe,o5)=>{"use strict";var CI=Zh(),{MAX_LENGTH:s5,MAX_SAFE_INTEGER:BI}=vu(),{safeRe:xI,t:bI}=Su(),ZQe=yI(),{compareIdentifiers:uR}=lR(),XQe=(t,e)=>{let r=e.split(".");if(r.length>t.length)return!1;for(let i=0;i<r.length;i++)if(uR(t[i],r[i])!==0)return!1;return!0},AR=class t{constructor(e,r){if(r=ZQe(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>s5)throw new TypeError(`version is longer than ${s5} characters`);CI("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let i=e.trim().match(r.loose?xI[bI.LOOSE]:xI[bI.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>BI||this.major<0)throw new TypeError("Invalid major version");if(this.minor>BI||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>BI||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<BI)return s}return n}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(CI("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let i=this.prerelease[r],n=e.prerelease[r];if(CI("prerelease compare",r,i,n),i===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(i===void 0)return-1;if(i===n)continue;return uR(i,n)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let i=this.build[r],n=e.build[r];if(CI("build compare",r,i,n),i===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(i===void 0)return-1;if(i===n)continue;return uR(i,n)}while(++r)}inc(e,r,i){if(e.startsWith("pre")){if(!r&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=`-${r}`.match(this.options.loose?xI[bI.PRERELEASELOOSE]:xI[bI.PRERELEASE]);if(!n||n[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,i),this.inc("pre",r,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,i),this.inc("pre",r,i);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];if(i===!1&&(s=[r]),XQe(this.prerelease,r)){let o=this.prerelease[r.split(".").length];isNaN(o)&&(this.prerelease=s)}else this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};o5.exports=AR});var To=b((eHe,c5)=>{"use strict";var a5=Kt(),KQe=(t,e,r=!1)=>{if(t instanceof a5)return t;try{return new a5(t,e)}catch(i){if(!r)return null;throw i}};c5.exports=KQe});var u5=b((tHe,l5)=>{"use strict";var ewe=To(),twe=(t,e)=>{let r=ewe(t,e);return r?r.version:null};l5.exports=twe});var d5=b((rHe,A5)=>{"use strict";var rwe=To(),nwe=(t,e)=>{let r=rwe(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};A5.exports=nwe});var g5=b((nHe,f5)=>{"use strict";var h5=Kt(),iwe=(t,e,r,i,n)=>{typeof r=="string"&&(n=i,i=r,r=void 0);try{return new h5(t instanceof h5?t.version:t,r).inc(e,i,n).version}catch{return null}};f5.exports=iwe});var E5=b((iHe,m5)=>{"use strict";var p5=To(),swe=(t,e)=>{let r=p5(t,null,!0),i=p5(e,null,!0),n=r.compare(i);if(n===0)return null;let s=n>0,o=s?r:i,a=s?i:r,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let u=c?"pre":"";return r.major!==i.major?u+"major":r.minor!==i.minor?u+"minor":r.patch!==i.patch?u+"patch":"prerelease"};m5.exports=swe});var y5=b((sHe,I5)=>{"use strict";var owe=Kt(),awe=(t,e)=>new owe(t,e).major;I5.exports=awe});var B5=b((oHe,C5)=>{"use strict";var cwe=Kt(),lwe=(t,e)=>new cwe(t,e).minor;C5.exports=lwe});var b5=b((aHe,x5)=>{"use strict";var uwe=Kt(),Awe=(t,e)=>new uwe(t,e).patch;x5.exports=Awe});var w5=b((cHe,Q5)=>{"use strict";var dwe=To(),hwe=(t,e)=>{let r=dwe(t,e);return r&&r.prerelease.length?r.prerelease:null};Q5.exports=hwe});var kn=b((lHe,S5)=>{"use strict";var v5=Kt(),fwe=(t,e,r)=>new v5(t,r).compare(new v5(e,r));S5.exports=fwe});var _5=b((uHe,D5)=>{"use strict";var gwe=kn(),pwe=(t,e,r)=>gwe(e,t,r);D5.exports=pwe});var T5=b((AHe,k5)=>{"use strict";var mwe=kn(),Ewe=(t,e)=>mwe(t,e,!0);k5.exports=Ewe});var QI=b((dHe,R5)=>{"use strict";var N5=Kt(),Iwe=(t,e,r)=>{let i=new N5(t,r),n=new N5(e,r);return i.compare(n)||i.compareBuild(n)};R5.exports=Iwe});var L5=b((hHe,M5)=>{"use strict";var ywe=QI(),Cwe=(t,e)=>t.sort((r,i)=>ywe(r,i,e));M5.exports=Cwe});var U5=b((fHe,F5)=>{"use strict";var Bwe=QI(),xwe=(t,e)=>t.sort((r,i)=>Bwe(i,r,e));F5.exports=xwe});var Xh=b((gHe,O5)=>{"use strict";var bwe=kn(),Qwe=(t,e,r)=>bwe(t,e,r)>0;O5.exports=Qwe});var wI=b((pHe,$5)=>{"use strict";var wwe=kn(),vwe=(t,e,r)=>wwe(t,e,r)<0;$5.exports=vwe});var dR=b((mHe,P5)=>{"use strict";var Swe=kn(),Dwe=(t,e,r)=>Swe(t,e,r)===0;P5.exports=Dwe});var hR=b((EHe,H5)=>{"use strict";var _we=kn(),kwe=(t,e,r)=>_we(t,e,r)!==0;H5.exports=kwe});var vI=b((IHe,V5)=>{"use strict";var Twe=kn(),Nwe=(t,e,r)=>Twe(t,e,r)>=0;V5.exports=Nwe});var SI=b((yHe,G5)=>{"use strict";var Rwe=kn(),Mwe=(t,e,r)=>Rwe(t,e,r)<=0;G5.exports=Mwe});var fR=b((CHe,Y5)=>{"use strict";var Lwe=dR(),Fwe=hR(),Uwe=Xh(),Owe=vI(),$we=wI(),Pwe=SI(),Hwe=(t,e,r,i)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Lwe(t,r,i);case"!=":return Fwe(t,r,i);case">":return Uwe(t,r,i);case">=":return Owe(t,r,i);case"<":return $we(t,r,i);case"<=":return Pwe(t,r,i);default:throw new TypeError(`Invalid operator: ${e}`)}};Y5.exports=Hwe});var j5=b((BHe,q5)=>{"use strict";var Vwe=Kt(),Gwe=To(),{safeRe:DI,t:_I}=Su(),Ywe=(t,e)=>{if(t instanceof Vwe)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?DI[_I.COERCEFULL]:DI[_I.COERCE]);else{let c=e.includePrerelease?DI[_I.COERCERTLFULL]:DI[_I.COERCERTL],l;for(;(l=c.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||l.index+l[0].length!==r.index+r[0].length)&&(r=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(r===null)return null;let i=r[2],n=r[3]||"0",s=r[4]||"0",o=e.includePrerelease&&r[5]?`-${r[5]}`:"",a=e.includePrerelease&&r[6]?`+${r[6]}`:"";return Gwe(`${i}.${n}.${s}${o}${a}`,e)};q5.exports=Ywe});var W5=b((xHe,z5)=>{"use strict";var qwe=To(),jwe=vu(),zwe=Kt(),Wwe=(t,e,r)=>{if(!jwe.RELEASE_TYPES.includes(e))return null;let i=Jwe(t,r);return i&&Zwe(i,e)},Jwe=(t,e)=>{let r=t instanceof zwe?t.version:t;return qwe(r,e)},Zwe=(t,e)=>{if(Xwe(e))return t.version;switch(t.prerelease=[],e){case"major":t.minor=0,t.patch=0;break;case"minor":t.patch=0;break}return t.format()},Xwe=t=>t.startsWith("pre");z5.exports=Wwe});var Z5=b((bHe,J5)=>{"use strict";var gR=class{constructor(){this.max=1e3,this.map=new Map}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(e,r)}return this}};J5.exports=gR});var Tn=b((QHe,t8)=>{"use strict";var Kwe=/\s+/g,pR=class t{constructor(e,r){if(r=tve(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof mR)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().replace(Kwe," "),this.set=this.raw.split("||").map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(n=>!K5(n[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&uve(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let r=this.set[e];for(let i=0;i<r.length;i++)i>0&&(this.formatted+=" "),this.formatted+=r[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(lve,"");let i=((this.options.includePrerelease&&ave)|(this.options.loose&&cve))+":"+e,n=X5.get(i);if(n)return n;let s=this.options.loose,o=s?yr[er.HYPHENRANGELOOSE]:yr[er.HYPHENRANGE];e=e.replace(o,yve(this.options.includePrerelease)),ut("hyphen replace",e),e=e.replace(yr[er.COMPARATORTRIM],ive),ut("comparator trim",e),e=e.replace(yr[er.TILDETRIM],sve),ut("tilde trim",e),e=e.replace(yr[er.CARETTRIM],ove),ut("caret trim",e);let a=e.split(" ").map(d=>Ave(d,this.options)).join(" ").split(/\s+/).map(d=>Ive(d,this.options));s&&(a=a.filter(d=>(ut("loose invalid filter",d,this.options),!!d.match(yr[er.COMPARATORLOOSE])))),ut("range list",a);let c=new Map,l=a.map(d=>new mR(d,this.options));for(let d of l){if(K5(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return X5.set(i,u),u}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(i=>e8(i,r)&&e.set.some(n=>e8(n,r)&&i.every(s=>n.every(o=>s.intersects(o,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new rve(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Cve(this.set[r],e,this.options))return!0;return!1}};t8.exports=pR;var eve=Z5(),X5=new eve,tve=yI(),mR=Kh(),ut=Zh(),rve=Kt(),{safeRe:yr,src:nve,t:er,comparatorTrimReplace:ive,tildeTrimReplace:sve,caretTrimReplace:ove}=Su(),{FLAG_INCLUDE_PRERELEASE:ave,FLAG_LOOSE:cve}=vu(),lve=new RegExp(nve[er.BUILD],"g"),K5=t=>t.value==="<0.0.0-0",uve=t=>t.value==="",e8=(t,e)=>{let r=!0,i=t.slice(),n=i.pop();for(;r&&i.length;)r=i.every(s=>n.intersects(s,e)),n=i.pop();return r},Ave=(t,e)=>(t=t.replace(yr[er.BUILD],""),ut("comp",t,e),t=fve(t,e),ut("caret",t),t=dve(t,e),ut("tildes",t),t=pve(t,e),ut("xrange",t),t=Eve(t,e),ut("stars",t),t),Cr=t=>!t||t.toLowerCase()==="x"||t==="*",dve=(t,e)=>t.trim().split(/\s+/).map(r=>hve(r,e)).join(" "),hve=(t,e)=>{let r=e.loose?yr[er.TILDELOOSE]:yr[er.TILDE];return t.replace(r,(i,n,s,o,a)=>{ut("tilde",t,i,n,s,o,a);let c;return Cr(n)?c="":Cr(s)?c=`>=${n}.0.0 <${+n+1}.0.0-0`:Cr(o)?c=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(ut("replaceTilde pr",a),c=`>=${n}.${s}.${o}-${a} <${n}.${+s+1}.0-0`):c=`>=${n}.${s}.${o} <${n}.${+s+1}.0-0`,ut("tilde return",c),c})},fve=(t,e)=>t.trim().split(/\s+/).map(r=>gve(r,e)).join(" "),gve=(t,e)=>{ut("caret",t,e);let r=e.loose?yr[er.CARETLOOSE]:yr[er.CARET],i=e.includePrerelease?"-0":"";return t.replace(r,(n,s,o,a,c)=>{ut("caret",t,n,s,o,a,c);let l;return Cr(s)?l="":Cr(o)?l=`>=${s}.0.0${i} <${+s+1}.0.0-0`:Cr(a)?s==="0"?l=`>=${s}.${o}.0${i} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${i} <${+s+1}.0.0-0`:c?(ut("replaceCaret pr",c),s==="0"?o==="0"?l=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`):(ut("no pr"),s==="0"?o==="0"?l=`>=${s}.${o}.${a}${i} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a}${i} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),ut("caret return",l),l})},pve=(t,e)=>(ut("replaceXRanges",t,e),t.split(/\s+/).map(r=>mve(r,e)).join(" ")),mve=(t,e)=>{t=t.trim();let r=e.loose?yr[er.XRANGELOOSE]:yr[er.XRANGE];return t.replace(r,(i,n,s,o,a,c)=>{ut("xRange",t,i,n,s,o,a,c);let l=Cr(s),u=l||Cr(o),d=u||Cr(a),h=d;return n==="="&&h&&(n=""),c=e.includePrerelease?"-0":"",l?n===">"||n==="<"?i="<0.0.0-0":i="*":n&&h?(u&&(o=0),a=0,n===">"?(n=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):n==="<="&&(n="<",u?s=+s+1:o=+o+1),n==="<"&&(c="-0"),i=`${n+s}.${o}.${a}${c}`):u?i=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(i=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),ut("xRange return",i),i})},Eve=(t,e)=>(ut("replaceStars",t,e),t.trim().replace(yr[er.STAR],"")),Ive=(t,e)=>(ut("replaceGTE0",t,e),t.trim().replace(yr[e.includePrerelease?er.GTE0PRE:er.GTE0],"")),yve=t=>(e,r,i,n,s,o,a,c,l,u,d,h)=>(Cr(i)?r="":Cr(n)?r=`>=${i}.0.0${t?"-0":""}`:Cr(s)?r=`>=${i}.${n}.0${t?"-0":""}`:o?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,Cr(l)?c="":Cr(u)?c=`<${+l+1}.0.0-0`:Cr(d)?c=`<${l}.${+u+1}.0-0`:h?c=`<=${l}.${u}.${d}-${h}`:t?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),Cve=(t,e,r)=>{for(let i=0;i<t.length;i++)if(!t[i].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let i=0;i<t.length;i++)if(ut(t[i].semver),t[i].semver!==mR.ANY&&t[i].semver.prerelease.length>0){let n=t[i].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0}});var Kh=b((wHe,a8)=>{"use strict";var ef=Symbol("SemVer ANY"),yR=class t{static get ANY(){return ef}constructor(e,r){if(r=r8(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),IR("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===ef?this.value="":this.value=this.operator+this.semver.version,IR("comp",this)}parse(e){let r=this.options.loose?n8[i8.COMPARATORLOOSE]:n8[i8.COMPARATOR],i=e.match(r);if(!i)throw new TypeError(`Invalid comparator: ${e}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new s8(i[2],this.options.loose):this.semver=ef}toString(){return this.value}test(e){if(IR("Comparator.test",e,this.options.loose),this.semver===ef||e===ef)return!0;if(typeof e=="string")try{e=new s8(e,this.options)}catch{return!1}return ER(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new o8(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new o8(this.value,r).test(e.semver):(r=r8(r),r.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||ER(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||ER(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};a8.exports=yR;var r8=yI(),{safeRe:n8,t:i8}=Su(),ER=fR(),IR=Zh(),s8=Kt(),o8=Tn()});var tf=b((vHe,c8)=>{"use strict";var Bve=Tn(),xve=(t,e,r)=>{try{e=new Bve(e,r)}catch{return!1}return e.test(t)};c8.exports=xve});var u8=b((SHe,l8)=>{"use strict";var bve=Tn(),Qve=(t,e)=>new bve(t,e).set.map(r=>r.map(i=>i.value).join(" ").trim().split(" "));l8.exports=Qve});var d8=b((DHe,A8)=>{"use strict";var wve=Kt(),vve=Tn(),Sve=(t,e,r)=>{let i=null,n=null,s=null;try{s=new vve(e,r)}catch{return null}return t.forEach(o=>{s.test(o)&&(!i||n.compare(o)===-1)&&(i=o,n=new wve(i,r))}),i};A8.exports=Sve});var f8=b((_He,h8)=>{"use strict";var Dve=Kt(),_ve=Tn(),kve=(t,e,r)=>{let i=null,n=null,s=null;try{s=new _ve(e,r)}catch{return null}return t.forEach(o=>{s.test(o)&&(!i||n.compare(o)===1)&&(i=o,n=new Dve(i,r))}),i};h8.exports=kve});var m8=b((kHe,p8)=>{"use strict";var CR=Kt(),Tve=Tn(),g8=Xh(),Nve=(t,e)=>{t=new Tve(t,e);let r=new CR("0.0.0");if(t.test(r)||(r=new CR("0.0.0-0"),t.test(r)))return r;r=null;for(let i=0;i<t.set.length;++i){let n=t.set[i],s=null;n.forEach(o=>{let a=new CR(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||g8(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!r||g8(r,s))&&(r=s)}return r&&t.test(r)?r:null};p8.exports=Nve});var I8=b((THe,E8)=>{"use strict";var Rve=Tn(),Mve=(t,e)=>{try{return new Rve(t,e).range||"*"}catch{return null}};E8.exports=Mve});var kI=b((NHe,x8)=>{"use strict";var Lve=Kt(),B8=Kh(),{ANY:Fve}=B8,Uve=Tn(),Ove=tf(),y8=Xh(),C8=wI(),$ve=SI(),Pve=vI(),Hve=(t,e,r,i)=>{t=new Lve(t,i),e=new Uve(e,i);let n,s,o,a,c;switch(r){case">":n=y8,s=$ve,o=C8,a=">",c=">=";break;case"<":n=C8,s=Pve,o=y8,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ove(t,e,i))return!1;for(let l=0;l<e.set.length;++l){let u=e.set[l],d=null,h=null;if(u.forEach(A=>{A.semver===Fve&&(A=new B8(">=0.0.0")),d=d||A,h=h||A,n(A.semver,d.semver,i)?d=A:o(A.semver,h.semver,i)&&(h=A)}),d.operator===a||d.operator===c||(!h.operator||h.operator===a)&&s(t,h.semver))return!1;if(h.operator===c&&o(t,h.semver))return!1}return!0};x8.exports=Hve});var Q8=b((RHe,b8)=>{"use strict";var Vve=kI(),Gve=(t,e,r)=>Vve(t,e,">",r);b8.exports=Gve});var v8=b((MHe,w8)=>{"use strict";var Yve=kI(),qve=(t,e,r)=>Yve(t,e,"<",r);w8.exports=qve});var _8=b((LHe,D8)=>{"use strict";var S8=Tn(),jve=(t,e,r)=>(t=new S8(t,r),e=new S8(e,r),t.intersects(e,r));D8.exports=jve});var T8=b((FHe,k8)=>{"use strict";var zve=tf(),Wve=kn();k8.exports=(t,e,r)=>{let i=[],n=null,s=null,o=t.sort((u,d)=>Wve(u,d,r));for(let u of o)zve(u,e,r)?(s=u,n||(n=u)):(s&&i.push([n,s]),s=null,n=null);n&&i.push([n,null]);let a=[];for(let[u,d]of i)u===d?a.push(u):!d&&u===o[0]?a.push("*"):d?u===o[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length<l.length?c:e}});var U8=b((UHe,F8)=>{"use strict";var N8=Tn(),bR=Kh(),{ANY:BR}=bR,xR=tf(),QR=kn(),Jve=(t,e,r={})=>{if(t===e)return!0;t=new N8(t,r),e=new N8(e,r);let i=!1;e:for(let n of t.set){for(let s of e.set){let o=Xve(n,s,r);if(i=i||o!==null,o)continue e}if(i)return!1}return!0},Zve=[new bR(">=0.0.0-0")],R8=[new bR(">=0.0.0")],Xve=(t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===BR){if(e.length===1&&e[0].semver===BR)return!0;r.includePrerelease?t=Zve:t=R8}if(e.length===1&&e[0].semver===BR){if(r.includePrerelease)return!0;e=R8}let i=new Set,n,s;for(let A of t)A.operator===">"||A.operator===">="?n=M8(n,A,r):A.operator==="<"||A.operator==="<="?s=L8(s,A,r):i.add(A.semver);if(i.size>1)return null;let o;if(n&&s){if(o=QR(n.semver,s.semver,r),o>0)return null;if(o===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let A of i){if(n&&!xR(A,String(n),r)||s&&!xR(A,String(s),r))return null;for(let f of e)if(!xR(A,String(f),r))return!1;return!0}let a,c,l,u,d=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,h=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let A of e){if(u=u||A.operator===">"||A.operator===">=",l=l||A.operator==="<"||A.operator==="<=",n){if(h&&A.semver.prerelease&&A.semver.prerelease.length&&A.semver.major===h.major&&A.semver.minor===h.minor&&A.semver.patch===h.patch&&(h=!1),A.operator===">"||A.operator===">="){if(a=M8(n,A,r),a===A&&a!==n)return!1}else if(n.operator===">="&&!A.test(n.semver))return!1}if(s){if(d&&A.semver.prerelease&&A.semver.prerelease.length&&A.semver.major===d.major&&A.semver.minor===d.minor&&A.semver.patch===d.patch&&(d=!1),A.operator==="<"||A.operator==="<="){if(c=L8(s,A,r),c===A&&c!==s)return!1}else if(s.operator==="<="&&!A.test(s.semver))return!1}if(!A.operator&&(s||n)&&o!==0)return!1}return!(n&&l&&!s&&o!==0||s&&u&&!n&&o!==0||h||d)},M8=(t,e,r)=>{if(!t)return e;let i=QR(t.semver,e.semver,r);return i>0?t:i<0||e.operator===">"&&t.operator===">="?e:t},L8=(t,e,r)=>{if(!t)return e;let i=QR(t.semver,e.semver,r);return i<0?t:i>0||e.operator==="<"&&t.operator==="<="?e:t};F8.exports=Jve});var H8=b((OHe,P8)=>{"use strict";var wR=Su(),O8=vu(),Kve=Kt(),$8=lR(),eSe=To(),tSe=u5(),rSe=d5(),nSe=g5(),iSe=E5(),sSe=y5(),oSe=B5(),aSe=b5(),cSe=w5(),lSe=kn(),uSe=_5(),ASe=T5(),dSe=QI(),hSe=L5(),fSe=U5(),gSe=Xh(),pSe=wI(),mSe=dR(),ESe=hR(),ISe=vI(),ySe=SI(),CSe=fR(),BSe=j5(),xSe=W5(),bSe=Kh(),QSe=Tn(),wSe=tf(),vSe=u8(),SSe=d8(),DSe=f8(),_Se=m8(),kSe=I8(),TSe=kI(),NSe=Q8(),RSe=v8(),MSe=_8(),LSe=T8(),FSe=U8();P8.exports={parse:eSe,valid:tSe,clean:rSe,inc:nSe,diff:iSe,major:sSe,minor:oSe,patch:aSe,prerelease:cSe,compare:lSe,rcompare:uSe,compareLoose:ASe,compareBuild:dSe,sort:hSe,rsort:fSe,gt:gSe,lt:pSe,eq:mSe,neq:ESe,gte:ISe,lte:ySe,cmp:CSe,coerce:BSe,truncate:xSe,Comparator:bSe,Range:QSe,satisfies:wSe,toComparators:vSe,maxSatisfying:SSe,minSatisfying:DSe,minVersion:_Se,validRange:kSe,outside:TSe,gtr:NSe,ltr:RSe,intersects:MSe,simplifyRange:LSe,subset:FSe,SemVer:Kve,re:wR.re,src:wR.src,tokens:wR.t,SEMVER_SPEC_VERSION:O8.SEMVER_SPEC_VERSION,RELEASE_TYPES:O8.RELEASE_TYPES,compareIdentifiers:$8.compareIdentifiers,rcompareIdentifiers:$8.rcompareIdentifiers}});var j8=b((zHe,vR)=>{var RI=process||{},Y8=RI.argv||[],NI=RI.env||{},PSe=!(NI.NO_COLOR||Y8.includes("--no-color"))&&(!!NI.FORCE_COLOR||Y8.includes("--color")||RI.platform==="win32"||(RI.stdout||{}).isTTY&&NI.TERM!=="dumb"||!!NI.CI),HSe=(t,e,r=t)=>i=>{let n=""+i,s=n.indexOf(e,t.length);return~s?t+VSe(n,e,r,s)+e:t+n+e},VSe=(t,e,r,i)=>{let n="",s=0;do n+=t.substring(s,i)+r,s=i+e.length,i=t.indexOf(e,s);while(~i);return n+t.substring(s)},q8=(t=PSe)=>{let e=t?HSe:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};vR.exports=q8();vR.exports.createColors=q8});var NR=b((C4e,dZ)=>{"use strict";var TR={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},dDe={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},hDe={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?TR.up():"");return t&&(e+=TR.left),e}};dZ.exports={cursor:TR,scroll:dDe,erase:hDe,beep:"\x07"}});var Bs,ey=D(()=>{"use strict";Bs=class extends Error{constructor(e){super(e),this.name="AudioUnavailableError"}}});function d7(t,e){if(e<=1)return t;let r=Math.floor(t.length/e),i=new Int16Array(r);for(let n=0;n<r;n++){let s=0,o=n*e;for(let a=0;a<e;a++)s+=t[o+a];i[n]=Math.round(s/e)}return i}var ly,h7=D(()=>{"use strict";ly=class{step;pos=0;prev=0;primed=!1;constructor(e,r){if(e<=0||r<=0)throw new RangeError("resampler rates must be positive");this.step=e/r}process(e){if(e.length===0)return new Int16Array(0);let r=[],i=e.length-1,n=this.primed?this.pos:0;for(;;){let s=Math.floor(n);if(s+1>i)break;let o=s<0?this.prev:e[s],a=e[s+1];r.push(Math.round(o+(a-o)*(n-s))),n+=this.step}return this.prev=e[i],this.primed=!0,this.pos=n-e.length,Int16Array.from(r)}}});function g7(t){return t.byteLength/2/__e}function k_e(t){let e=t.byteLength>>1,r=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let n=0;n<e;n++)i[n]=r.getInt16(n*2,!0);return i}var f7,__e,uy,p7=D(()=>{"use strict";Tt();Is();f7=32,__e=16,uy=class{constructor(e,r,i={}){this.vad=e;this.onSpeech=r;this.speechThreshold=i.speechThreshold??.5,this.onsetMs=i.onsetMs??2*f7,this.holdoffMs=i.holdoffMs??300,this.energyThreshold=i.energyThreshold??.01,this.log=i.log??ee}vad;onSpeech;speechThreshold;onsetMs;holdoffMs;energyThreshold;log;inSpeech=!1;speechRunMs=0;silenceRunMs=0;degraded=!1;closed=!1;feed(e){if(!(this.closed||e.byteLength===0)){if(this.degraded){this.applyVerdict(hn(e,this.energyThreshold),g7(e));return}this.vad.process(k_e(e)).then(r=>{if(!this.closed)for(let i of r)this.applyVerdict(i>=this.speechThreshold,f7)},r=>{this.closed||(this.degrade(r),this.applyVerdict(hn(e,this.energyThreshold),g7(e)))})}}close(){this.closed=!0}applyVerdict(e,r){e?(this.silenceRunMs=0,this.speechRunMs+=r,!this.inSpeech&&this.speechRunMs>=this.onsetMs&&(this.inSpeech=!0,this.onSpeech())):(this.speechRunMs=0,this.inSpeech&&(this.silenceRunMs+=r,this.silenceRunMs>=this.holdoffMs&&(this.inSpeech=!1,this.silenceRunMs=0)))}degrade(e){this.degraded||(this.degraded=!0,this.log.debug("barge-in DEGRADED to energy onset - silero vad failed; speech onsets detect on RMS energy for the rest of the capture session",{error:e instanceof Error?e.message:String(e)}))}}});var r2={};An(r2,{DecibriCapture:()=>e2,DecibriPlayback:()=>t2,SILENT_STREAM_TIMEOUT_MS:()=>Ay,hasInputDevice:()=>y7});function dy(){return m7??=import("decibri"),m7}async function y7(){try{let{inputDevices:t}=await dy();return t().length>0}catch(t){return ee.debug("audio module or input enumeration unavailable; treating as no microphone",{error:t}),!1}}async function N_e(){try{let{inputDevices:t}=await dy(),e=t(),r=e.find(i=>i.isDefault)??e[0];if(r&&r.defaultSampleRate>=1e3&&r.maxInputChannels>=1)return{sampleRate:Math.round(r.defaultSampleRate),channels:r.maxInputChannels}}catch(t){ee.debug("could not read default input device; opening at 16k mono",{error:t})}return{sampleRate:Af,channels:hy}}function R_e(t){return Math.max(64,Math.min(65536,Math.round(t/10)))}function M_e(t,e,r){let i=new Uint8Array(t),n=new Int16Array(i.buffer,0,i.byteLength>>1),s=r.process(d7(n,e));return Buffer.from(s.buffer,s.byteOffset,s.byteLength)}function U_e(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}var m7,Af,hy,I7,E7,Ay,T_e,e2,L_e,F_e,t2,n2=D(()=>{"use strict";Tt();Is();ey();h7();p7();m7=null;Af=16e3,hy=1,I7="int16",E7=.01,Ay=3e3,T_e=1e3;e2=class{constructor(e={}){this.deps=e}deps;mic=null;onData=null;onSpeech=null;onErr=null;vad=null;detector=null;watchdog=null;lastChunkAtMs=0;async start(e){if(!await y7())throw new Bs("no audio input device is available");let{sampleRate:r,channels:i}=await N_e(),n=(this.deps.createVad??(()=>new nc))(),s=null;try{await n.load(),s=new uy(n,()=>e.onSpeechStart(),{energyThreshold:E7})}catch(A){ee.debug("silero vad unavailable; barge-in falls back to decibri energy vad",{error:A}),n.dispose().catch(()=>{})}let{Microphone:o}=await dy(),a;try{a=await o.open({sampleRate:r,channels:i,dtype:I7,...s?{vad:!1}:{vad:"energy",vadThreshold:E7},framesPerBuffer:R_e(r)})}catch(A){throw s?.close(),s&&n.dispose().catch(()=>{}),A}this.vad=s?n:null,this.detector=s;let c=r===Af&&i===hy?null:new ly(r,Af);this.onData=c?A=>{this.lastChunkAtMs=Date.now();let f=M_e(A,i,c);f.byteLength>0&&(this.detector?.feed(f),e.onFrame(f,Date.now()))}:A=>{this.lastChunkAtMs=Date.now(),A.byteLength>0&&(this.detector?.feed(A),e.onFrame(A,Date.now()))},this.onSpeech=()=>e.onSpeechStart(),this.onErr=A=>e.onError(A);let l=null,u=new Promise(A=>{l=()=>A(),a.once("data",l)});a.on("data",this.onData),a.on("speech",this.onSpeech),a.on("error",this.onErr),this.mic=a;let d=null,h=await Promise.race([u.then(()=>!0),new Promise(A=>{d=setTimeout(()=>A(!1),Ay)})]);if(d!==null&&clearTimeout(d),!h)throw l!==null&&a.removeListener("data",l),await this.stop(),new Bs("the microphone opened but never delivered audio - treating it as unavailable");this.armWatchdog(e)}armWatchdog(e){this.clearWatchdog(),this.lastChunkAtMs=Date.now(),this.watchdog=setInterval(()=>{Date.now()-this.lastChunkAtMs<Ay||(this.clearWatchdog(),e.onError(new Error(`capture went silent - no audio for ${Ay} ms (decibri delivers no error event on device loss; treating the microphone as lost)`)))},T_e)}clearWatchdog(){this.watchdog!==null&&(clearInterval(this.watchdog),this.watchdog=null)}async stop(){this.clearWatchdog();let e=this.mic;this.mic=null,this.detector?.close(),this.detector=null,e&&(this.onData&&e.removeListener("data",this.onData),this.onSpeech&&e.removeListener("speech",this.onSpeech),this.onErr&&e.removeListener("error",this.onErr),e.on("error",()=>{}),e.stop()),this.onData=null,this.onSpeech=null,this.onErr=null;let r=this.vad;this.vad=null,r&&await r.dispose().catch(()=>{})}},L_e=Af*hy*2/1e3,F_e=250,t2=class{speaker=null;writeChain=Promise.resolve();generation=0;closed=!1;playoutEndAtMs=0;drainWakes=new Set;nativeDrainSpent=!1;playoutTap=null;play(e){if(this.closed)return;let r=this.generation;this.writeChain=this.writeChain.then(async()=>{if(!(this.closed||r!==this.generation))try{let i=await this.ensureSpeaker(r);if(this.closed||r!==this.generation||(await i.writeAsync(U_e(e)),this.closed||r!==this.generation))return;let n=Math.max(this.playoutEndAtMs,Date.now());this.playoutEndAtMs=n+e.byteLength/L_e;try{this.playoutTap?.(e,n)}catch(s){ee.debug("playout tap failed",{error:s})}}catch(i){ee.debug("playback write skipped",{error:i})}})}setPlayoutTap(e){this.playoutTap=e}remainingMs(){return Math.max(0,this.playoutEndAtMs-Date.now())}flush(){this.generation++,this.playoutEndAtMs=0;let e=this.speaker;this.speaker=null,e?.stop();for(let r of[...this.drainWakes])r()}async drained(){await this.writeChain;let e=this.speaker;if(!e)return;if(!this.nativeDrainSpent){this.nativeDrainSpent=!0;let i=Promise.resolve().then(()=>e.drainAsync()).catch(o=>{ee.debug("playback drain interrupted",{error:o})}),n=Math.max(0,this.playoutEndAtMs-Date.now())+F_e,s=this.sleep(n);await Promise.race([i,s.done]),s.wake()}let r=this.playoutEndAtMs-Date.now();r>0&&await this.sleep(r).done}sleep(e){let r;return{done:new Promise(n=>{let s=setTimeout(()=>r(),e);r=()=>{clearTimeout(s),this.drainWakes.delete(r),n()},this.drainWakes.add(r)}),wake:r}}close(){return this.closed=!0,this.flush(),Promise.resolve()}async ensureSpeaker(e){if(this.speaker===null){let{Speaker:r}=await dy();if(this.closed||e!==this.generation)throw new Error("playback cut during the native module load");this.speaker=new r({sampleRate:Af,channels:hy,dtype:I7}),this.nativeDrainSpent=!1}return this.speaker}}});Tt();Is();FA();import{readFileSync as O_e}from"node:fs";import{randomUUID as $_e}from"node:crypto";var Si=class extends Error{constructor(e,r,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},ys=class extends Si{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Wh=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:(r.push(e),r)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,i)=>{if(!this.argChoices.includes(r))throw new ys(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,i):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function pI(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}import{EventEmitter as wQe}from"node:events";import oR from"node:child_process";import Cs from"node:path";import EI from"node:fs";import Ye from"node:process";import{stripVTControlCharacters as vQe}from"node:util";import{stripVTControlCharacters as xQe}from"node:util";var Jh=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&r.push(i),this.sortSubcommands&&r.sort((n,s)=>n.name().localeCompare(s.name())),r}compareOptions(e,r){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(r))}visibleOptions(e){let r=e.options.filter(n=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),s=i.long&&e._findOption(i.long);!n&&!s?r.push(i):i.long&&!s?r.push(e.createOption(i.long,i.description)):i.short&&!n&&r.push(e.createOption(i.short,i.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);r.push(...n)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(i=>pI(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((i,n)=>Math.max(i,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(n)))),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(r.styleOptionTerm(r.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(r.styleOptionTerm(r.optionTerm(n)))),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(n)))),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0){let i=`(${r.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let i=`(${r.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatItemList(e,r,i){return r.length===0?[]:[i.styleTitle(e),...r,""]}groupItems(e,r,i){let n=new Map;return e.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[])}),r.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]),n.get(o).push(s)}),n}formatHelp(e,r){let i=r.padWidth(e,r),n=r.helpWidth??80;function s(d,h){return r.formatItem(d,i,h,r)}let o=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(e))}`,""],a=r.commandDescription(e);a.length>0&&(o=o.concat([r.boxWrap(r.styleCommandDescription(a),n),""]));let c=r.visibleArguments(e).map(d=>s(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",c,r)),this.groupItems(e.options,r.visibleOptions(e),d=>d.helpGroupHeading??"Options:").forEach((d,h)=>{let A=d.map(f=>s(r.styleOptionTerm(r.optionTerm(f)),r.styleOptionDescription(r.optionDescription(f))));o=o.concat(this.formatItemList(h,A,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(e).map(h=>s(r.styleOptionTerm(r.optionTerm(h)),r.styleOptionDescription(r.optionDescription(h))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(e.commands,r.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,h)=>{let A=d.map(f=>s(r.styleSubcommandTerm(r.subcommandTerm(f)),r.styleSubcommandDescription(r.subcommandDescription(f))));o=o.concat(this.formatItemList(h,A,r))}),o.join(`
395
395
  `)}displayWidth(e){return xQe(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,r,i,n){let o=" ".repeat(2);if(!i)return o+e;let a=e.padEnd(r+e.length-n.displayWidth(e)),c=2,u=(this.helpWidth??80)-r-c-2,d;return u<this.minWidthToWrap||n.preformatted(i)?d=i:d=n.boxWrap(i,u).replace(/\n/g,`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neuvybe/jarvis",
3
- "version": "0.50.4",
3
+ "version": "0.50.6",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {