@neuvybe/jarvis 0.20.2 → 0.20.3

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 +43 -43
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -75,7 +75,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
75
75
  - The transcript of a single user turn may contain a pause request ("give me a second", "let me think") followed by the user's continued thought: the pause already happened. Respond to the completed thought; never offer to wait for a pause that is already over.`,wi=class{adapter;model;systemPrompt;history=[];constructor(e,n,i=Vb){this.adapter=e,this.model=n,this.systemPrompt=i}async*run(e,n,i){if(e.trim()==="")return;let r=this.assemble(e),o=i?.register==="voice"?`${this.systemPrompt}
76
76
 
77
77
  ${Zb}`:this.systemPrompt,s="";for await(let a of this.adapter.stream({model:this.model,system:o,messages:r,...n!==void 0&&{signal:n}}))s+=a.text,yield a;this.history.push({role:"user",content:e},{role:"assistant",content:s})}historySnapshot(){return[...this.history]}assemble(e){return[...this.history,{role:"user",content:e}]}}});var ra,Bb=v(()=>{"use strict";ra=class{buffer=[];pending=null;closed=!1;push(e){if(this.closed)return;let n=this.pending;if(n){this.pending=null,n({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(n=>{this.pending=n});if(e.done)return;yield e.value}}}});var zT,NT,Gb,Si,rp=v(()=>{"use strict";zT=new Set([".","!","?"]),NT=new Set([",",";",":"]),Gb={minClauseLength:12},Si=class{buffer="";minClauseLength;constructor(e=Gb){this.minClauseLength=e.minClauseLength}push(e){this.buffer+=e;let n=[];for(let i=this.findBoundary();i!==-1;i=this.findBoundary()){let r=this.buffer.slice(0,i+1).trim();this.buffer=this.buffer.slice(i+1).replace(/^\s+/,""),r.length>0&&n.push(r)}return n}flush(){let e=this.buffer.trim();return this.buffer="",e.length>0?[e]:[]}findBoundary(){for(let e=0;e<this.buffer.length;e++){let n=this.buffer[e];if(n===`
78
- `)return e;let i=e+1<this.buffer.length?this.buffer[e+1]:"";if(i!==""&&/\s/.test(i)&&(zT.has(n)||NT.has(n)&&e+1>=this.minClauseLength))return e}return-1}}});var ki,np=v(()=>{"use strict";ki=class{nextId=1;timers=new Map;now(){return Date.now()}setTimer(e,n){let i=this.nextId++,r=setTimeout(()=>{this.timers.delete(i),n()},e);return this.timers.set(i,r),i}clearTimer(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}}});function Bt(t,e){let n=Math.floor(t.byteLength/2);if(n===0)return!1;let i=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0;for(let o=0;o<n;o++){let s=i.getInt16(o*2,!0)/32768;r+=s*s}return Math.sqrt(r/n)>=e}function RT(t){let e=t.byteLength>>1,n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let r=0;r<e;r++)i[r]=n.getInt16(r*2,!0);return i}var na,Ii,Ei,Ti=v(()=>{"use strict";De();na=.02;Ii=class{threshold;constructor(e){this.threshold=e}classify(e,n){n(Bt(e,this.threshold))}},Ei=class{vad;speechThreshold;energyThreshold;log;degraded=!1;announced=!1;disposed=!1;constructor(e,n={}){this.vad=e,this.speechThreshold=n.speechThreshold??.5,this.energyThreshold=n.energyThreshold??na,this.log=n.log??q}classify(e,n){if(this.degraded){this.announce("energy (fallback)"),n(Bt(e,this.energyThreshold));return}this.vad.process(RT(e)).then(i=>{if(!this.disposed){this.announce("silero");for(let r of i)n(r>=this.speechThreshold)}},i=>{this.disposed||(this.degrade(i),this.announce("energy (fallback)"),n(Bt(e,this.energyThreshold)))})}reset(){!this.degraded&&!this.disposed&&this.vad.reset()}prewarm(){this.degraded||this.disposed||this.vad.load().then(()=>{},e=>this.degrade(e))}dispose(){return this.disposed=!0,this.vad.dispose()}degrade(e){this.degraded||this.disposed||(this.degraded=!0,this.log.debug("frame classifier DEGRADED to energy (fallback) - silero vad failed; turn-end classifies on RMS energy for the rest of the session",{error:e instanceof Error?e.message:String(e)}))}announce(e){this.announced||(this.announced=!0,this.log.debug(`frame classifier: ${e}`))}}});var ia,mr,fn,DT,Wb,ip=v(()=>{ia=new Map,mr=[],fn=(t,e,n)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let i=ia.get(t);if(i===void 0)ia.set(t,{backend:e,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${n}`)}if(n>=0){let r=mr.indexOf(t);r!==-1&&mr.splice(r,1);for(let o=0;o<mr.length;o++)if(ia.get(mr[o]).priority<=n){mr.splice(o,0,t);return}mr.push(t)}return}throw new TypeError("not a valid backend")},DT=async t=>{let e=ia.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let n=!!e.initPromise;try{return n||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(i){return n||(e.error=`${i}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Wb=async t=>{let e=t.executionProviders||[],n=e.map(u=>typeof u=="string"?u:u.name),i=n.length===0?mr:n,r,o=[],s=new Set;for(let u of i){let c=await DT(u);typeof c=="string"?o.push({name:u,err:c}):(r||(r=c),r===c&&s.add(u))}if(!r)throw new Error(`no available backend found. ERR: ${o.map(u=>`[${u.name}] ${u.err}`).join(", ")}`);for(let{name:u,err:c}of o)n.includes(u)&&console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${c}`);let a=e.filter(u=>s.has(typeof u=="string"?u:u.name));return[r,new Proxy(t,{get:(u,c)=>c==="executionProviders"?a:Reflect.get(u,c)})]}});var qb=v(()=>{ip()});var Hb,Jb=v(()=>{Hb="1.26.0"});var Kb,de,op=v(()=>{Jb();Kb="warning",de={wasm:{},webgl:{},webgpu:{},versions:{common:Hb},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}`);Kb=t}},get logLevel(){return Kb}};Object.defineProperty(de,"logLevel",{enumerable:!0})});var ie,Yb=v(()=>{op();ie=de});var Xb,Qb,e$=v(()=>{Xb=(t,e)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=t.dims[3],n.height=t.dims[2];let i=n.getContext("2d");if(i!=null){let r,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(r=t.dims[2],o=t.dims[3]):(r=t.dims[3],o=t.dims[2]);let s=e?.format!==void 0?e.format:"RGB",a=e?.norm,u,c;a===void 0||a.mean===void 0?u=[255,255,255,255]:typeof a.mean=="number"?u=[a.mean,a.mean,a.mean,a.mean]:(u=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(u[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let l=o*r,d=0,f=l,h=l*2,p=-1;s==="RGBA"?(d=0,f=l,h=l*2,p=l*3):s==="RGB"?(d=0,f=l,h=l*2):s==="RBG"&&(d=0,h=l,f=l*2);for(let _=0;_<o;_++)for(let S=0;S<r;S++){let k=(t.data[d++]-c[0])*u[0],C=(t.data[f++]-c[1])*u[1],A=(t.data[h++]-c[2])*u[2],I=p===-1?255:(t.data[p++]-c[3])*u[3];i.fillStyle="rgba("+k+","+C+","+A+","+I+")",i.fillRect(S,_,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Qb=(t,e)=>{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let r,o,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(r=t.dims[2],o=t.dims[1],s=t.dims[3]):(r=t.dims[3],o=t.dims[2],s=t.dims[1]);let a=e!==void 0&&e.format!==void 0?e.format:"RGB",u=e?.norm,c,l;u===void 0||u.mean===void 0?c=[255,255,255,255]:typeof u.mean=="number"?c=[u.mean,u.mean,u.mean,u.mean]:(c=[u.mean[0],u.mean[1],u.mean[2],255],u.mean[3]!==void 0&&(c[3]=u.mean[3])),u===void 0||u.bias===void 0?l=[0,0,0,0]:typeof u.bias=="number"?l=[u.bias,u.bias,u.bias,u.bias]:(l=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(l[3]=u.bias[3]));let d=o*r;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,h=0,p=1,_=2,S=3,k=0,C=d,A=d*2,I=-1;a==="RGBA"?(k=0,C=d,A=d*2,I=d*3):a==="RGB"?(k=0,C=d,A=d*2):a==="RBG"&&(k=0,A=d,C=d*2),i=n.createImageData(r,o);for(let T=0;T<o*r;h+=f,p+=f,_+=f,S+=f,T++)i.data[h]=(t.data[k++]-l[0])*c[0],i.data[p]=(t.data[C++]-l[1])*c[1],i.data[_]=(t.data[A++]-l[2])*c[2],i.data[S]=I===-1?255:(t.data[I++]-l[3])*c[3]}else throw new Error("Can not access image data");return i}});var sp,t$,r$,n$,i$,o$,s$=v(()=>{oa();sp=(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:n,width:i}=e,r=e.norm??{mean:255,bias:0},o,s;typeof r.mean=="number"?o=[r.mean,r.mean,r.mean,r.mean]:o=[r.mean[0],r.mean[1],r.mean[2],r.mean[3]??255],typeof r.bias=="number"?s=[r.bias,r.bias,r.bias,r.bias]:s=[r.bias[0],r.bias[1],r.bias[2],r.bias[3]??0];let a=e.format!==void 0?e.format:"RGBA",u=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=n*i,l=u==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,f=0,h=1,p=2,_=3,S=0,k=c,C=c*2,A=-1;a==="RGB"&&(d=3,f=0,h=1,p=2,_=-1),u==="RGBA"?A=c*3:u==="RBG"?(S=0,C=c,k=c*2):u==="BGR"&&(C=0,k=c,S=c*2);for(let T=0;T<c;T++,f+=d,p+=d,h+=d,_+=d)l[S++]=(t[f]+s[0])/o[0],l[k++]=(t[h]+s[1])/o[1],l[C++]=(t[p]+s[2])/o[2],A!==-1&&_!==-1&&(l[A++]=(t[_]+s[3])/o[3]);return u==="RGBA"?new ye("float32",l,[1,4,n,i]):new ye("float32",l,[1,3,n,i])},t$=async(t,e)=>{let n=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,i=typeof ImageData<"u"&&t instanceof ImageData,r=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",s,a=e??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=l=>typeof HTMLCanvasElement<"u"&&l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas?l.getContext("2d"):null;if(n){let l=u();l.width=t.width,l.height=t.height;let d=c(l);if(d!=null){let f=t.height,h=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(f=e.resizedHeight,h=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=f,a.width=h}else a.tensorFormat="RGBA",a.height=f,a.width=h;d.drawImage(t,0,0),s=d.getImageData(0,0,h,f).data}else throw new Error("Can not access image data")}else if(i){let l,d;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(l=e.resizedHeight,d=e.resizedWidth):(l=t.height,d=t.width),e!==void 0&&(a=e),a.format="RGBA",a.height=l,a.width=d,e!==void 0){let f=u();f.width=d,f.height=l;let h=c(f);if(h!=null)h.putImageData(t,0,0),s=h.getImageData(0,0,d,l).data;else throw new Error("Can not access image data")}else s=t.data}else if(r){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let l=u();l.width=t.width,l.height=t.height;let d=c(l);if(d!=null){let f=t.height,h=t.width;return d.drawImage(t,0,0,h,f),s=d.getImageData(0,0,h,f).data,a.height=f,a.width=h,sp(s,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((l,d)=>{let f=u(),h=c(f);if(!t||!h)return d();let p=new Image;p.crossOrigin="Anonymous",p.src=t,p.onload=()=>{f.width=p.width,f.height=p.height,h.drawImage(p,0,0,f.width,f.height);let _=h.getImageData(0,0,f.width,f.height);a.height=f.height,a.width=f.width,l(sp(_.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return sp(s,a);throw new Error("Input data provided is not supported - aborted tensor creation")},r$=(t,e)=>{let{width:n,height:i,download:r,dispose:o}=e,s=[1,i,n,4];return new ye({location:"texture",type:"float32",texture:t,dims:s,download:r,dispose:o})},n$=(t,e)=>{let{dataType:n,dims:i,download:r,dispose:o}=e;return new ye({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:i,download:r,dispose:o})},i$=(t,e)=>{let{dataType:n,dims:i,download:r,dispose:o}=e;return new ye({location:"ml-tensor",type:n??"float32",mlTensor:t,dims:i,download:r,dispose:o})},o$=(t,e,n)=>new ye({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]})});var gr,Oi,a$,u$,c$=v(()=>{gr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Oi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),a$=!1,u$=()=>{if(!a$){a$=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;t&&(gr.set("int64",BigInt64Array),Oi.set(BigInt64Array,"int64")),e&&(gr.set("uint64",BigUint64Array),Oi.set(BigUint64Array,"uint64")),i?(gr.set("float16",n),Oi.set(n,"float16")):gr.set("float16",Uint16Array)}}});var l$,d$,f$=v(()=>{oa();l$=t=>{let e=1;for(let n=0;n<t.length;n++){let i=t[n];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${n}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${i}`);e*=i}return e},d$=(t,e)=>{switch(t.location){case"cpu":return new ye(t.type,t.data,e);case"cpu-pinned":return new ye({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new ye({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new ye({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new ye({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}});var ye,oa=v(()=>{e$();s$();c$();f$();ye=class{constructor(e,n,i){u$();let r,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,r=e.type,o=e.dims,e.location){case"cpu-pinned":{let a=gr.get(r);if(!a)throw new TypeError(`unsupported type "${r}" 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(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint64"&&r!=="int8"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" 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,u;if(typeof e=="string")if(r=e,u=i,e==="string"){if(!Array.isArray(n))throw new TypeError("A string tensor's data must be a string array.");a=n}else{let c=gr.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(n)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?a=c.from(n,BigInt):a=c.from(n)}else if(n instanceof c)a=n;else if(n instanceof Uint8ClampedArray)if(e==="uint8")a=Uint8Array.from(n);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&n instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(n.buffer,n.byteOffset,n.length);else throw new TypeError(`A ${r} tensor's data must be type of ${c}`)}else if(u=n,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")r="string",a=e;else if(c==="boolean")r="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)r="uint8",a=Uint8Array.from(e);else{let c=Oi.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=c,a=e}if(u===void 0)u=[a.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");o=u,this.cpuData=a,this.dataLocation="cpu"}let s=l$(o);if(this.cpuData&&s!==this.cpuData.length&&!((r==="uint4"||r==="int4")&&Math.ceil(s/2)===this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=o,this.size=s}static async fromImage(e,n){return t$(e,n)}static fromTexture(e,n){return r$(e,n)}static fromGpuBuffer(e,n){return n$(e,n)}static fromMLTensor(e,n){return i$(e,n)}static fromPinnedBuffer(e,n,i){return o$(e,n,i)}toDataURL(e){return Xb(this,e)}toImageData(e){return Qb(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 n=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=n,e&&this.disposer&&(this.disposer(),this.disposer=void 0),n}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 d$(this,e)}}});var Ye,ap=v(()=>{oa();Ye=ye});var up,h$,Gt,Wt,qt,Ht,cp=v(()=>{op();up=(t,e)=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||console.timeStamp(`${t}::ORT::${e}`)},h$=(t,e)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let r=0;r<n.length;r++){if(i&&!n[r].includes("TRACE_FUNC")){let o=`FUNC_${t}::${n[r].trim().split(" ")[1]}`;e&&(o+=`::${e}`),up("CPU",o);return}n[r].includes("TRACE_FUNC")&&(i=!0)}},Gt=t=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||h$("BEGIN",t)},Wt=t=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||h$("END",t)},qt=t=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||console.time(`ORT::${t}`)},Ht=t=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||console.timeEnd(`ORT::${t}`)}});var sa,p$=v(()=>{ip();ap();cp();sa=class t{constructor(e){this.handler=e}async run(e,n,i){Gt(),qt("InferenceSession.run");let r={},o={};if(typeof e!="object"||e===null||e instanceof Ye||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof Ye)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let c of n){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);r[c]=null}if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,l=Object.getOwnPropertyNames(n);for(let d of this.outputNames)if(l.indexOf(d)!==-1){let f=n[d];(f===null||f instanceof Ye)&&(c=!0,s=!1,r[d]=f)}if(c){if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else o=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(s)for(let c of this.outputNames)r[c]=null;let a=await this.handler.run(e,r,o),u={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let l=a[c];l instanceof Ye?u[c]=l:u[c]=new Ye(l.type,l.data,l.dims)}return Ht("InferenceSession.run"),Wt(),u}async release(){return this.handler.dispose()}static async create(e,n,i,r){Gt(),qt("InferenceSession.create");let o,s={};if(typeof e=="string"){if(o=e,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let l=e,d=0,f=e.byteLength;if(typeof n=="object"&&n!==null)s=n;else if(typeof n=="number"){if(d=n,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=l.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${l.byteLength}).`);if(f=e.byteLength-d,typeof i=="number"){if(f=i,!Number.isSafeInteger(f))throw new RangeError("'byteLength' must be an integer.");if(f<=0||d+f>l.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${l.byteLength-d}].`);if(typeof r=="object"&&r!==null)s=r;else if(typeof r<"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 n<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(l,d,f)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,u]=await Wb(s),c=await a.createInferenceSessionHandler(o,u);return Ht("InferenceSession.create"),Wt(),new t(c)}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 m$,g$=v(()=>{p$();m$=sa});var v$=v(()=>{});var y$=v(()=>{});var _$=v(()=>{});var b$=v(()=>{});var lp={};He(lp,{InferenceSession:()=>m$,TRACE:()=>up,TRACE_EVENT_BEGIN:()=>qt,TRACE_EVENT_END:()=>Ht,TRACE_FUNC_BEGIN:()=>Gt,TRACE_FUNC_END:()=>Wt,Tensor:()=>Ye,env:()=>ie,registerBackend:()=>fn});var Jt=v(()=>{qb();Yb();g$();ap();v$();y$();cp();_$();b$()});var dx={};He(dx,{InferenceSession:()=>m$,TRACE:()=>up,TRACE_EVENT_BEGIN:()=>qt,TRACE_EVENT_END:()=>Ht,TRACE_FUNC_BEGIN:()=>Gt,TRACE_FUNC_END:()=>Wt,Tensor:()=>Ye,default:()=>KT,env:()=>ie,registerBackend:()=>fn});import{createRequire as LT}from"module";var hn,kp,UT,jT,MT,$p,Xe,FT,VT,ZT,gn,Ip,dp,$$,x$,wt,L$,fp,w$,S$,k$,I$,hp,U$,j$,pp,aa,Pi,mp,E$,T$,O$,M$,ee,Ci,at,la,K,Ep,F$,BT,P$,C$,A$,vr,z$,V$,GT,pn,ca,mn,Z$,B$,Tp,Op,G$,W$,da,q$,N$,H$,J$,yr,R$,gp,xp,K$,Y$,vp,X$,Q$,WT,ua,yp,_p,ex,tx,rx,nx,ix,ox,sx,ax,bp,D$,ux,qT,cx,wp,Sp,lx,HT,JT,KT,fx=v(()=>{Jt();Jt();Jt();Jt();Jt();Jt();Jt();hn=LT(import.meta.url),kp=Object.defineProperty,UT=Object.getOwnPropertyDescriptor,jT=Object.getOwnPropertyNames,MT=Object.prototype.hasOwnProperty,$p=(t=>typeof hn<"u"?hn:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof hn<"u"?hn:e)[n]}):t)(function(t){if(typeof hn<"u")return hn.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),Xe=(t,e)=>()=>(t&&(e=t(t=0)),e),FT=(t,e)=>{for(var n in e)kp(t,n,{get:e[n],enumerable:!0})},VT=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jT(e))!MT.call(t,r)&&r!==n&&kp(t,r,{get:()=>e[r],enumerable:!(i=UT(e,r))||i.enumerable});return t},ZT=t=>VT(kp({},"__esModule",{value:!0}),t),Ip=Xe(()=>{"use strict";gn=!!(typeof process<"u"&&process.versions&&process.versions.node)}),j$=Xe(()=>{"use strict";Ip(),dp=gn||typeof location>"u"?void 0:location.origin,$$=import.meta.url>"file:"&&import.meta.url<"file;",x$=()=>{if(!gn){if($$){let t=URL;return new URL(new t("ort.node.min.mjs",import.meta.url).href,dp).href}return import.meta.url}},wt=x$(),L$=()=>{if(wt&&!wt.startsWith("blob:"))return wt.substring(0,wt.lastIndexOf("/")+1)},fp=(t,e)=>{try{let n=e??wt;return(n?new URL(t,n):new URL(t)).origin===dp}catch{return!1}},w$=(t,e)=>{let n=e??wt;try{return(n?new URL(t,n):new URL(t)).href}catch{return}},S$=(t,e)=>`${e??"./"}${t}`,k$=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},I$=async t=>(await import(t)).default,hp=void 0,U$=async(t,e,n,i)=>{let r=hp&&!(t||e);if(r)if(wt)r=fp(wt)||i&&!n;else if(i&&!n)r=!0;else throw new Error("cannot determine the script source URL.");if(r)return[void 0,hp];{let o="ort-wasm-simd-threaded.mjs",s=t??w$(o,e),a=!gn&&n&&s&&!fp(s,e),u=a?await k$(s):s??S$(o,e);return[a?u:void 0,await I$(u)]}}}),Ci=Xe(()=>{"use strict";j$(),aa=!1,Pi=!1,mp=!1,E$=()=>{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}},T$=()=>{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}},O$=()=>{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}},M$=async t=>{if(aa)return Promise.resolve();if(Pi)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(mp)throw new Error("previous call to 'initializeWebAssembly()' failed.");Pi=!0;let e=t.initTimeout,n=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!O$())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!T$())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=E$();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", 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=n=1);let r=t.wasmPaths,o=typeof r=="string"?r:void 0,s=r?.mjs,a=s?.href??s,u=r?.wasm,c=u?.href??u,l=t.wasmBinary,[d,f]=await U$(a,o,n>1,!!l||!!c),h=!1,p=[];if(e>0&&p.push(new Promise(_=>{setTimeout(()=>{h=!0,_()},e)})),p.push(new Promise((_,S)=>{let k={numThreads:n};if(l)k.wasmBinary=l,k.locateFile=C=>C;else if(c||o)k.locateFile=C=>c??o+C;else if(a&&a.indexOf("blob:")!==0)k.locateFile=C=>new URL(C,a).href;else if(d){let C=L$();C&&(k.locateFile=A=>C+A)}f(k).then(C=>{Pi=!1,aa=!0,pp=C,_(),d&&URL.revokeObjectURL(d)},C=>{Pi=!1,mp=!0,S(C)})})),await Promise.race(p),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},ee=()=>{if(aa&&pp)return pp;throw new Error("WebAssembly is not initialized yet.")}}),Ep=Xe(()=>{"use strict";Ci(),at=(t,e)=>{let n=ee(),i=n.lengthBytesUTF8(t)+1,r=n._malloc(i);return n.stringToUTF8(t,r,i),e.push(r),r},la=(t,e,n,i)=>{if(typeof t=="object"&&t!==null){if(n.has(t))throw new Error("Circular reference in options");n.add(t)}Object.entries(t).forEach(([r,o])=>{let s=e?e+r:r;if(typeof o=="object")la(o,s+".",n,i);else if(typeof o=="string"||typeof o=="number")i(s,o.toString());else if(typeof o=="boolean")i(s,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},K=t=>{let e=ee(),n=e.stackSave();try{let i=e.PTR_SIZE,r=e.stackAlloc(2*i);e._OrtGetLastError(r,r+i);let o=Number(e.getValue(r,i===4?"i32":"i64")),s=e.getValue(r+i,"*"),a=s?e.UTF8ToString(s):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${a}`)}finally{e.stackRestore(n)}}}),BT=Xe(()=>{"use strict";Ci(),Ep(),F$=t=>{let e=ee(),n=0,i=[],r=t||{};try{if(t?.logSeverityLevel===void 0)r.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)r.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&&(r.terminate=!1);let o=0;return t?.tag!==void 0&&(o=at(t.tag,i)),n=e._OrtCreateRunOptions(r.logSeverityLevel,r.logVerbosityLevel,!!r.terminate,o),n===0&&K("Can't create run options."),t?.extra!==void 0&&la(t.extra,"",new WeakSet,(s,a)=>{let u=at(s,i),c=at(a,i);e._OrtAddRunConfigEntry(n,u,c)!==0&&K(`Can't set a run config entry: ${s} - ${a}.`)}),[n,i]}catch(o){throw n!==0&&e._OrtReleaseRunOptions(n),i.forEach(s=>e._free(s)),o}}}),GT=Xe(()=>{"use strict";Ci(),Ep(),P$=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}`)}},C$=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},A$=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(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(t.enableMemPattern=!1)},vr=(t,e,n,i)=>{let r=at(e,i),o=at(n,i);ee()._OrtAddSessionConfigEntry(t,r,o)!==0&&K(`Can't set a session config entry: ${e} - ${n}.`)},z$=async(t,e,n)=>{let i=e.executionProviders;for(let r of i){let o=typeof r=="string"?r:r.name,s=[];switch(o){case"webnn":if(o="WEBNN",vr(t,"session.disable_quant_qdq","1",n),vr(t,"session.disable_qdq_constant_folding","1",n),typeof r!="string"){let d=r?.deviceType;d&&vr(t,"deviceType",d,n)}break;case"webgpu":if(o="JS",typeof r!="string"){let d=r;if(d?.preferredLayout){if(d.preferredLayout!=="NCHW"&&d.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${d.preferredLayout}`);vr(t,"preferredLayout",d.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let a=at(o,n),u=s.length,c=0,l=0;if(u>0){c=ee()._malloc(u*ee().PTR_SIZE),n.push(c),l=ee()._malloc(u*ee().PTR_SIZE),n.push(l);for(let d=0;d<u;d++)ee().setValue(c+d*ee().PTR_SIZE,s[d][0],"*"),ee().setValue(l+d*ee().PTR_SIZE,s[d][1],"*")}await ee()._OrtAppendExecutionProvider(t,a,c,l,u)!==0&&K(`Can't append execution provider: ${o}.`)}},V$=async t=>{let e=ee(),n=0,i=[],r=t||{};A$(r);try{let o=P$(r.graphOptimizationLevel??"all"),s=C$(r.executionMode??"sequential"),a=typeof r.logId=="string"?at(r.logId,i):0,u=r.logSeverityLevel??2;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log severity level is not valid: ${u}`);let c=r.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let l=typeof r.optimizedModelFilePath=="string"?at(r.optimizedModelFilePath,i):0;if(n=e._OrtCreateSessionOptions(o,!!r.enableCpuMemArena,!!r.enableMemPattern,s,!!r.enableProfiling,0,a,u,c,l),n===0&&K("Can't create session options."),r.executionProviders&&await z$(n,r,i),r.enableGraphCapture!==void 0){if(typeof r.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${r.enableGraphCapture}`);vr(n,"enableGraphCapture",r.enableGraphCapture.toString(),i)}if(r.freeDimensionOverrides)for(let[d,f]of Object.entries(r.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error(`free dimension override value must be a non-negative integer: ${f}`);let h=at(d,i);e._OrtAddFreeDimensionOverride(n,h,f)!==0&&K(`Can't set a free dimension override: ${d} - ${f}.`)}return r.extra!==void 0&&la(r.extra,"",new WeakSet,(d,f)=>{vr(n,d,f,i)}),[n,i]}catch(o){throw n!==0&&e._OrtReleaseSessionOptions(n)!==0&&K("Can't release session options."),i.forEach(s=>e._free(s)),o}}}),W$=Xe(()=>{"use strict";pn=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}`)}},ca=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}`)}},mn=(t,e)=>{let n=[-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((r,o)=>r*o,1);return n>0?Math.ceil(i*n):void 0},Z$=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}`)}},B$=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}`)}},Tp=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Op=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",G$=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}`)}}}),q$=Xe(()=>{"use strict";Ip(),da=async t=>{if(typeof t=="string")if(gn)try{let{readFile:e}=$p("node:fs/promises");return new Uint8Array(await e(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let{createReadStream:n}=$p("node:fs"),i=n(t),r=[];for await(let o of i)r.push(o);return new Uint8Array(Buffer.concat(r))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let n=e.headers.get("Content-Length"),i=n?parseInt(n,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 r=e.body.getReader(),o;try{o=new ArrayBuffer(i)}catch(a){if(a instanceof RangeError){let u=Math.ceil(i/65536);o=new WebAssembly.Memory({initial:u,maximum:u}).buffer}else throw a}let s=0;for(;;){let{done:a,value:u}=await r.read();if(a)break;let c=u.byteLength;new Uint8Array(o,s,c).set(u),s+=c}return new Uint8Array(o,0,i)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),WT=Xe(()=>{"use strict";BT(),GT(),W$(),Ci(),Ep(),q$(),N$=(t,e)=>{ee()._OrtInit(t,e)!==0&&K("Can't initialize onnxruntime.")},H$=async t=>{N$(t.wasm.numThreads,B$(t.logLevel))},J$=async(t,e)=>{ee().asyncInit?.();let n=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.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 r=t.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:r}),!n)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")},yr=new Map,R$=t=>{let e=ee(),n=e.stackSave();try{let i=e.PTR_SIZE,r=e.stackAlloc(2*i);e._OrtGetInputOutputCount(t,r,r+i)!==0&&K("Can't get session input/output count.");let o=i===4?"i32":"i64";return[Number(e.getValue(r,o)),Number(e.getValue(r+i,o))]}finally{e.stackRestore(n)}},gp=(t,e)=>{let n=ee(),i=n.stackSave(),r=0;try{let o=n.PTR_SIZE,s=n.stackAlloc(2*o);n._OrtGetInputOutputMetadata(t,e,s,s+o)!==0&&K("Can't get session input/output metadata.");let a=Number(n.getValue(s,"*"));r=Number(n.getValue(s+o,"*"));let u=n.HEAP32[r/4];if(u===0)return[a,0];let c=n.HEAPU32[r/4+1],l=[];for(let d=0;d<c;d++){let f=Number(n.getValue(r+8+d*o,"*"));l.push(f!==0?n.UTF8ToString(f):Number(n.getValue(r+8+(d+c)*o,"*")))}return[a,u,l]}finally{n.stackRestore(i),r!==0&&n._OrtFree(r)}},xp=t=>{let e=ee(),n=e._malloc(t.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,n),[n,t.byteLength]},K$=async(t,e)=>{let n,i,r=ee();Array.isArray(t)?[n,i]=t:t.buffer===r.HEAPU8.buffer?[n,i]=[t.byteOffset,t.byteLength]:[n,i]=xp(t);let o=0,s=0,a=0,u=[],c=[],l=[];try{if([s,u]=await V$(e),e?.externalData&&r.mountExternalData){let A=[];for(let I of e.externalData){let T=typeof I=="string"?I:I.path;A.push(da(typeof I=="string"?I:I.data).then(Z=>{r.mountExternalData(T,Z)}))}await Promise.all(A)}for(let A of e?.executionProviders??[])if((typeof A=="string"?A:A.name)==="webnn"){if(r.shouldTransferToMLTensor=!1,typeof A!="string"){let I=A,T=I?.context,Z=I?.gpuDevice,F=I?.deviceType,W=I?.powerPreference;T?r.currentContext=T:Z?r.currentContext=await r.webnnCreateMLContext(Z):r.currentContext=await r.webnnCreateMLContext({deviceType:F,powerPreference:W})}else r.currentContext=await r.webnnCreateMLContext();break}o=await r._OrtCreateSession(n,i,s),r.webgpuOnCreateSession?.(o),o===0&&K("Can't create a session."),r.jsepOnCreateSession?.(),r.currentContext&&(r.webnnRegisterMLContext(o,r.currentContext),r.currentContext=void 0,r.shouldTransferToMLTensor=!0);let[d,f]=R$(o),h=!!e?.enableGraphCapture,p=[],_=[],S=[],k=[],C=[];for(let A=0;A<d;A++){let[I,T,Z]=gp(o,A);I===0&&K("Can't get an input name."),c.push(I);let F=r.UTF8ToString(I);p.push(F),S.push(T===0?{name:F,isTensor:!1}:{name:F,isTensor:!0,type:ca(T),shape:Z})}for(let A=0;A<f;A++){let[I,T,Z]=gp(o,A+d);I===0&&K("Can't get an output name."),l.push(I);let F=r.UTF8ToString(I);_.push(F),k.push(T===0?{name:F,isTensor:!1}:{name:F,isTensor:!0,type:ca(T),shape:Z})}return yr.set(o,[o,c,l,null,h,!1]),[o,p,_,S,k]}catch(d){throw c.forEach(f=>r._OrtFree(f)),l.forEach(f=>r._OrtFree(f)),a!==0&&r._OrtReleaseBinding(a)!==0&&K("Can't release IO binding."),o!==0&&r._OrtReleaseSession(o)!==0&&K("Can't release session."),d}finally{r._free(n),s!==0&&r._OrtReleaseSessionOptions(s)!==0&&K("Can't release session options."),u.forEach(d=>r._free(d)),r.unmountExternalData?.()}},Y$=t=>{let e=ee(),n=yr.get(t);if(!n)throw new Error(`cannot release session. invalid session id: ${t}`);let[i,r,o,s,a]=n;s&&(a&&e._OrtClearBoundOutputs(s.handle)!==0&&K("Can't clear bound outputs."),e._OrtReleaseBinding(s.handle)!==0&&K("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),r.forEach(u=>e._OrtFree(u)),o.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(i)!==0&&K("Can't release session."),yr.delete(t)},vp=async(t,e,n,i,r,o,s=!1)=>{if(!t){e.push(0);return}let a=ee(),u=a.PTR_SIZE,c=t[0],l=t[1],d=t[3],f=d,h,p;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(s&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let k=t[2].gpuBuffer;p=mn(pn(c),l);{let C=a.jsepRegisterBuffer;if(!C)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=C(i,o,k,p)}}else if(d==="ml-tensor"){let k=t[2].mlTensor;p=mn(pn(c),l);let C=a.webnnRegisterMLTensor;if(!C)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=C(i,k,pn(c),l)}else{let k=t[2];if(Array.isArray(k)){p=u*k.length,h=a._malloc(p),n.push(h);for(let C=0;C<k.length;C++){if(typeof k[C]!="string")throw new TypeError(`tensor data at index ${C} is not a string`);a.setValue(h+C*u,at(k[C],n),"*")}}else{let C=a.webnnIsGraphInput,A=a.webnnIsGraphOutput;if(c!=="string"&&C&&A){let I=a.UTF8ToString(r);if(C(i,I)||A(i,I)){let T=pn(c);p=mn(T,l),f="ml-tensor";let Z=a.webnnCreateTemporaryTensor,F=a.webnnUploadTensor;if(!Z||!F)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let W=await Z(i,T,l);F(W,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),h=W}else p=k.byteLength,h=a._malloc(p),n.push(h),a.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,p),h)}else p=k.byteLength,h=a._malloc(p),n.push(h),a.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,p),h)}}let _=a.stackSave(),S=a.stackAlloc(4*l.length);try{l.forEach((C,A)=>a.setValue(S+A*u,C,u===4?"i32":"i64"));let k=a._OrtCreateTensor(pn(c),h,p,S,l.length,G$(f));k===0&&K(`Can't create tensor for input/output. session=${i}, index=${o}.`),e.push(k)}finally{a.stackRestore(_)}},X$=async(t,e,n,i,r,o)=>{let s=ee(),a=s.PTR_SIZE,u=yr.get(t);if(!u)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=u[0],l=u[1],d=u[2],f=u[3],h=u[4],p=u[5],_=e.length,S=i.length,k=0,C=[],A=[],I=[],T=[],Z=[],F=s.stackSave(),W=s.stackAlloc(_*a),ne=s.stackAlloc(_*a),$e=s.stackAlloc(S*a),he=s.stackAlloc(S*a);try{[k,C]=F$(o),qt("wasm prepareInputOutputTensor");for(let D=0;D<_;D++)await vp(n[D],A,T,t,l[e[D]],e[D],h);for(let D=0;D<S;D++)await vp(r[D],I,T,t,d[i[D]],_+i[D],h);Ht("wasm prepareInputOutputTensor");for(let D=0;D<_;D++)s.setValue(W+D*a,A[D],"*"),s.setValue(ne+D*a,l[e[D]],"*");for(let D=0;D<S;D++)s.setValue($e+D*a,I[D],"*"),s.setValue(he+D*a,d[i[D]],"*");s.jsepOnRunStart?.(c),s.webnnOnRunStart?.(c);let Se;Se=await s._OrtRun(c,ne,W,_,he,S,$e,k),Se!==0&&K("failed to call OrtRun().");let ke=[],Q=[];qt("wasm ProcessOutputTensor");for(let D=0;D<S;D++){let ce=Number(s.getValue($e+D*a,"*"));if(ce===I[D]||Z.includes(I[D])){ke.push(r[D]),ce!==I[D]&&s._OrtReleaseTensor(ce)!==0&&K("Can't release tensor.");continue}let it=s.stackSave(),je=s.stackAlloc(4*a),Ar=!1,le,Me=0;try{s._OrtGetTensorData(ce,je,je+a,je+2*a,je+3*a)!==0&&K(`Can't access output tensor data on index ${D}.`);let Ou=a===4?"i32":"i64",lo=Number(s.getValue(je,Ou));Me=s.getValue(je+a,"*");let Eg=s.getValue(je+a*2,"*"),fI=Number(s.getValue(je+a*3,Ou)),Ct=[];for(let pe=0;pe<fI;pe++)Ct.push(Number(s.getValue(Eg+pe*a,Ou)));s._OrtFree(Eg)!==0&&K("Can't free memory for tensor dims.");let At=Ct.reduce((pe,se)=>pe*se,1);le=ca(lo);let Nn=f?.outputPreferredLocations[i[D]];if(le==="string"){if(Nn==="gpu-buffer"||Nn==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let pe=[];for(let se=0;se<At;se++){let _t=s.getValue(Me+se*a,"*"),hI=s.getValue(Me+(se+1)*a,"*"),pI=se===At-1?void 0:hI-_t;pe.push(s.UTF8ToString(_t,pI))}ke.push([le,Ct,pe,"cpu"])}else if(Nn==="gpu-buffer"&&At>0){let pe=s.jsepGetBuffer;if(!pe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let se=pe(Me),_t=mn(lo,At);if(_t===void 0||!Tp(le))throw new Error(`Unsupported data type: ${le}`);Ar=!0,ke.push([le,Ct,{gpuBuffer:se,download:s.jsepCreateDownloader(se,_t,le),dispose:()=>{s._OrtReleaseTensor(ce)!==0&&K("Can't release tensor.")}},"gpu-buffer"])}else if(Nn==="ml-tensor"&&At>0){let pe=s.webnnEnsureTensor,se=s.webnnIsGraphInputOutputTypeSupported;if(!pe||!se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(mn(lo,At)===void 0||!Op(le))throw new Error(`Unsupported data type: ${le}`);if(!se(t,le,!1))throw new Error(`preferredLocation "ml-tensor" for ${le} output is not supported by current WebNN Context.`);let _t=await pe(t,Me,lo,Ct,!1);Ar=!0,ke.push([le,Ct,{mlTensor:_t,download:s.webnnCreateMLTensorDownloader(Me,le),dispose:()=>{s.webnnReleaseTensorId(Me),s._OrtReleaseTensor(ce)}},"ml-tensor"])}else if(Nn==="ml-tensor-cpu-output"&&At>0){let pe=s.webnnCreateMLTensorDownloader(Me,le)(),se=ke.length;Ar=!0,Q.push((async()=>{let _t=[se,await pe];return s.webnnReleaseTensorId(Me),s._OrtReleaseTensor(ce),_t})()),ke.push([le,Ct,[],"cpu"])}else{let pe=Z$(le),se=new pe(At);new Uint8Array(se.buffer,se.byteOffset,se.byteLength).set(s.HEAPU8.subarray(Me,Me+se.byteLength)),ke.push([le,Ct,se,"cpu"])}}finally{s.stackRestore(it),le==="string"&&Me&&s._free(Me),Ar||s._OrtReleaseTensor(ce)}}f&&!h&&(s._OrtClearBoundOutputs(f.handle)!==0&&K("Can't clear bound outputs."),yr.set(t,[c,l,d,f,h,!1]));for(let[D,ce]of await Promise.all(Q))ke[D][2]=ce;return Ht("wasm ProcessOutputTensor"),ke}finally{s.webnnOnRunEnd?.(c),s.stackRestore(F),A.forEach(Se=>s._OrtReleaseTensor(Se)),I.forEach(Se=>s._OrtReleaseTensor(Se)),T.forEach(Se=>s._free(Se)),k!==0&&s._OrtReleaseRunOptions(k),C.forEach(Se=>s._free(Se))}},Q$=t=>{let e=ee(),n=yr.get(t);if(!n)throw new Error("invalid session id");let i=n[0],r=e._OrtEndProfiling(i);r===0&&K("Can't get an profile file name."),e._OrtFree(r)}}),ax=Xe(()=>{"use strict";WT(),Ci(),j$(),ua=!1,yp=!1,_p=!1,ex=async()=>{if(!yp){if(ua)throw new Error("multiple calls to 'initWasm()' detected.");if(_p)throw new Error("previous call to 'initWasm()' failed.");ua=!0;try{await M$(ie.wasm),await H$(ie),yp=!0}catch(t){throw _p=!0,t}finally{ua=!1}}},tx=async t=>{await J$(ie,t)},rx=async t=>xp(t),nx=async(t,e)=>K$(t,e),ix=async t=>{Y$(t)},ox=async(t,e,n,i,r,o)=>X$(t,e,n,i,r,o),sx=async t=>{Q$(t)}}),qT=Xe(()=>{"use strict";ax(),W$(),Ip(),q$(),bp=(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()}`)}},D$=t=>{switch(t[3]){case"cpu":return new Ye(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Tp(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:r}=t[2];return Ye.fromGpuBuffer(n,{dataType:e,dims:t[1],download:i,dispose:r})}case"ml-tensor":{let e=t[0];if(!Op(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:r}=t[2];return Ye.fromMLTensor(n,{dataType:e,dims:t[1],download:i,dispose:r})}default:throw new Error(`invalid data location: ${t[3]}`)}},ux=class{async fetchModelAndCopyToWasmMemory(t){return rx(await da(t))}async loadModel(t,e){Gt();let n;typeof t=="string"?gn?n=await da(t):n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await nx(n,e),Wt()}async dispose(){return ix(this.sessionId)}async run(t,e,n){Gt();let i=[],r=[];Object.entries(t).forEach(d=>{let f=d[0],h=d[1],p=this.inputNames.indexOf(f);if(p===-1)throw new Error(`invalid input '${f}'`);i.push(h),r.push(p)});let o=[],s=[];Object.entries(e).forEach(d=>{let f=d[0],h=d[1],p=this.outputNames.indexOf(f);if(p===-1)throw new Error(`invalid output '${f}'`);o.push(h),s.push(p)});let a=i.map((d,f)=>bp(d,()=>`input "${this.inputNames[r[f]]}"`)),u=o.map((d,f)=>d?bp(d,()=>`output "${this.outputNames[s[f]]}"`):null),c=await ox(this.sessionId,r,a,s,u,n),l={};for(let d=0;d<c.length;d++)l[this.outputNames[s[d]]]=o[d]??D$(c[d]);return Wt(),l}startProfiling(){}endProfiling(){sx(this.sessionId)}}}),cx={};FT(cx,{OnnxruntimeWebAssemblyBackend:()=>Sp,initializeFlags:()=>wp,wasmBackend:()=>lx});HT=Xe(()=>{"use strict";ax(),qT(),wp=()=>{(typeof ie.wasm.initTimeout!="number"||ie.wasm.initTimeout<0)&&(ie.wasm.initTimeout=0);let t=ie.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.`),ie.wasm.simd=!1),typeof ie.wasm.proxy!="boolean"&&(ie.wasm.proxy=!1),typeof ie.wasm.trace!="boolean"&&(ie.wasm.trace=!1),typeof ie.wasm.numThreads!="number"||!Number.isInteger(ie.wasm.numThreads)||ie.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ie.wasm.numThreads=1;else{let e=typeof navigator>"u"?$p("node:os").cpus().length:navigator.hardwareConcurrency;ie.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Sp=class{async init(t){wp(),await ex(),await tx(t)}async createInferenceSessionHandler(t,e){let n=new ux;return await n.loadModel(t,e),n}},lx=new Sp}),JT="1.26.0",KT=lp;{let t=(HT(),ZT(cx)).wasmBackend;fn("cpu",t,10),fn("wasm",t,10)}Object.defineProperty(ie.versions,"web",{value:JT,enumerable:!0})});import{existsSync as YT}from"node:fs";import{createRequire as XT}from"node:module";import{dirname as QT,join as eO,sep as hx}from"node:path";import{fileURLToPath as tO,pathToFileURL as rO}from"node:url";async function fa(){let t=await Promise.resolve().then(()=>(fx(),dx));return t.default??t}function ha(t,e){t.env.wasm.numThreads=1,t.env.wasm.wasmPaths=iO(e)}function nO(t){return[new URL("./",t),new URL("../",t)].map(e=>tO(e))}function iO(t=import.meta.url){let e=nO(t);try{e.push(QT(XT(t).resolve("onnxruntime-web")))}catch{}let n=null;for(let i of e){let r=px.filter(o=>!YT(eO(i,o)));if(r.length===0)return oO(i);r.length<px.length&&n===null&&(n={dir:i,missing:r})}throw n!==null?new Error(`ort-web WASM runtime at '${n.dir}' is missing '${n.missing.join("', '")}' - the .wasm and its .mjs glue must be copied together`):new Error(`ort-web WASM runtime ('${mx}' + '${gx}') not found beside the bundle or in node_modules`)}function oO(t){return rO(t.endsWith(hx)?t:t+hx).href}var mx,gx,px,Pp=v(()=>{"use strict";mx="ort-wasm-simd-threaded.wasm",gx="ort-wasm-simd-threaded.mjs",px=[mx,gx]});import{existsSync as sO}from"node:fs";import{fileURLToPath as aO}from"node:url";function Cp(t,e){return[new URL(`../../assets/${t}`,e),new URL(`./assets/${t}`,e),new URL(`../assets/${t}`,e)].map(n=>aO(n))}function pa(t,e,n,i={}){let r=i.baseUrl??n,o=i.exists??sO,s="envPath"in i?i.envPath:process.env[e];if(s&&o(s))return s;let a=Cp(t,r);for(let u of a)if(o(u))return u;throw new Error(`model '${t}' not found. Tried: ${a.join(", ")}. Set ${e} to override.`)}var Ap=v(()=>{"use strict"});function zp(t={}){return pa(vx,yx,import.meta.url,t)}var vx,yx,Np=v(()=>{"use strict";Ap();vx="silero_vad.onnx",yx="JARVIS_SILERO_VAD_MODEL_PATH"});var vn,Ai,_x,_r,Rp=v(()=>{"use strict";Pp();Np();vn=512,Ai=64,_x=256,_r=class{modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;pending=new Int16Array(vn);pendingLen=0;state=new Float32Array(_x);context=new Float32Array(Ai);chain=Promise.resolve();constructor(e={}){this.modelPath=e.modelPath}process(e){if(this.disposed)return Promise.reject(new Error("SileroVadRunner is disposed"));let n=this.chain.then(()=>this.runWindows(e));return this.chain=n.then(()=>{},()=>{}),n}reset(){this.chain=this.chain.then(()=>{this.pendingLen=0,this.state=new Float32Array(_x),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 n=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let r=[],o=0;for(;;){let s=Math.min(vn-this.pendingLen,e.length-o);if(s>0&&(this.pending.set(e.subarray(o,o+s),this.pendingLen),this.pendingLen+=s,o+=s),this.pendingLen<vn)break;this.pendingLen=0,r.push(await this.inferWindow(n,i))}return r}async inferWindow(e,n){let i=new Float32Array(Ai+vn);i.set(this.context,0);for(let a=0;a<vn;a++)i[Ai+a]=this.pending[a]/32768;let r=await e.run({input:new n.Tensor("float32",i,[1,i.length]),state:new n.Tensor("float32",this.state,[2,1,128]),sr:new n.Tensor("int64",BigInt64Array.from([16000n]),[])});if(this.disposed)throw new Error("SileroVadRunner is disposed");let o=r[e.outputNames[0]].data;this.state=r[e.outputNames[1]].data,this.context.set(i.subarray(i.length-Ai));let s=o[0];if(!Number.isFinite(s))throw new Error("silero vad produced a non-finite output");return s<0?0:s>1?1:s}ensureSession(){return this.sessionPromise?this.sessionPromise:(this.sessionPromise=this.loadSession(),this.sessionPromise)}async loadSession(){let e=await fa();this.ort=e,ha(e);let n=this.modelPath??zp(),i=await e.InferenceSession.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SileroVadRunner is disposed");return this.session=i,i}}});function uO(t){let e=1;for(;e<t;)e<<=1;return e}var Dp,ma,bx=v(()=>{"use strict";Dp=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 n=Math.log2(e);this.rev=new Uint32Array(e);for(let r=0;r<e;r++){let o=0;for(let s=0;s<n;s++)o|=(r>>s&1)<<n-1-s;this.rev[r]=o}let i=e>>1;this.cos=new Float64Array(i),this.sin=new Float64Array(i);for(let r=0;r<i;r++){let o=2*Math.PI*r/e;this.cos[r]=Math.cos(o),this.sin[r]=Math.sin(o)}}transform(e,n,i){let r=this.size,o=this.rev;for(let s=0;s<r;s++){let a=o[s];if(a>s){let u=e[s];e[s]=e[a],e[a]=u;let c=n[s];n[s]=n[a],n[a]=c}}for(let s=2;s<=r;s<<=1){let a=s>>1,u=r/s;for(let c=0;c<r;c+=s)for(let l=0;l<a;l++){let d=l*u,f=this.cos[d],h=i?this.sin[d]:-this.sin[d],p=c+l,_=p+a,S=e[_]*f-n[_]*h,k=e[_]*h+n[_]*f;e[_]=e[p]-S,n[_]=n[p]-k,e[p]+=S,n[p]+=k}}if(i){let s=1/r;for(let a=0;a<r;a++)e[a]*=s,n[a]*=s}}};ma=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=uO(2*e-1),this.fft=new Dp(this.m),this.chirpCos=new Float64Array(e),this.chirpSin=new Float64Array(e);for(let n=0;n<e;n++){let i=n*n%(2*e),r=Math.PI*i/e;this.chirpCos[n]=Math.cos(r),this.chirpSin[n]=Math.sin(r)}this.bRe=new Float64Array(this.m),this.bIm=new Float64Array(this.m);for(let n=0;n<e;n++){let i=this.chirpCos[n],r=this.chirpSin[n];this.bRe[n]=i,this.bIm[n]=r,n!==0&&(this.bRe[this.m-n]=i,this.bIm[this.m-n]=r)}this.fft.transform(this.bRe,this.bIm,!1),this.aRe=new Float64Array(this.m),this.aIm=new Float64Array(this.m)}computePower(e,n){let{n:i,m:r,aRe:o,aIm:s}=this;o.fill(0),s.fill(0);for(let a=0;a<i;a++){let u=e[a];o[a]=u*this.chirpCos[a],s[a]=-u*this.chirpSin[a]}this.fft.transform(o,s,!1);for(let a=0;a<r;a++){let u=o[a],c=s[a],l=this.bRe[a],d=this.bIm[a];o[a]=u*l-c*d,s[a]=u*d+c*l}this.fft.transform(o,s,!0);for(let a=0;a<this.bins;a++){let u=o[a],c=s[a];n[a]=u*u+c*c}}}});function wx(t){let i=27/Math.log(6.4);return t>=1e3?15+Math.log(t/1e3)*i:3*t/200}function dO(t){let i=Math.log(6.4)/27;return t>=15?1e3*Math.exp(i*(t-15)):200*t/3}function Sx(t,e,n){let i=new Float64Array(n),r=n>1?(e-t)/(n-1):0;for(let o=0;o<n;o++)i[o]=t+o*r;return n>1&&(i[n-1]=e),i}function fO(){let t=wx(0),e=wx(Lp/2),n=Sx(t,e,St+2),i=new Float64Array(St+2);for(let a=0;a<n.length;a++)i[a]=dO(n[a]);let r=Sx(0,Lp/2,zi),o=new Float64Array(St+1);for(let a=0;a<St+1;a++)o[a]=i[a+1]-i[a];let s=[];for(let a=0;a<St;a++){let u=2/(i[a+2]-i[a]),c=new Float64Array(zi),l=zi,d=0;for(let f=0;f<zi;f++){let h=-(i[a]-r[f])/o[a],p=(i[a+2]-r[f])/o[a+1],_=Math.max(0,Math.min(h,p))*u;c[f]=_,_>0&&(f<l&&(l=f),d=f+1)}l>d&&(l=d=0),s.push({lo:l,hi:d,weights:c.slice(l,d)})}return s}function hO(){let t=new Float64Array(ut);for(let e=0;e<ut;e++)t[e]=.5-.5*Math.cos(2*Math.PI*e/ut);return t}var Lp,ut,cO,St,zi,$x,lO,xx,Ue,br,Up,Ni,ga=v(()=>{"use strict";bx();Lp=16e3,ut=400,cO=160,St=80,zi=(ut>>1)+1,$x=1e-10,lO=1e-7,xx=32768,Ue=Lp*8,br=800,Up=St;Ni=class{hann=hO();filters=fO();spectrum=new ma(ut);padded=new Float64Array(Ue+ut);frame=new Float64Array(ut);power=new Float64Array(zi);logBuf=new Float64Array(St*br);fromPcm16(e){return this.window(e),this.normalize(),this.reflectPad(),this.melSpectrogram()}window(e){let n=this.padded,i=ut/2,r=e.length;if(r>=Ue){let o=r-Ue;for(let s=0;s<Ue;s++)n[i+s]=e[o+s]/xx}else{let o=Ue-r;for(let s=0;s<o;s++)n[i+s]=0;for(let s=0;s<r;s++)n[i+o+s]=e[s]/xx}}normalize(){let e=this.padded,n=ut/2,i=Ue,r=0;for(let a=0;a<i;a++)r+=e[n+a];r/=i;let o=0;for(let a=0;a<i;a++){let u=e[n+a]-r;o+=u*u}o/=i;let s=1/Math.sqrt(o+lO);for(let a=0;a<i;a++)e[n+a]=(e[n+a]-r)*s}reflectPad(){let e=this.padded,n=ut/2,i=Ue;for(let r=0;r<n;r++)e[r]=e[n+(n-r)],e[n+i+r]=e[n+(i-2-r)]}melSpectrogram(){let{padded:e,frame:n,power:i,hann:r,filters:o,logBuf:s}=this;for(let l=0;l<br;l++){let d=l*cO;for(let f=0;f<ut;f++)n[f]=e[d+f]*r[f];this.spectrum.computePower(n,i);for(let f=0;f<St;f++){let{lo:h,hi:p,weights:_}=o[f],S=0;for(let k=h;k<p;k++)S+=_[k-h]*i[k];s[f*br+l]=Math.log10(S<$x?$x:S)}}let a=-1/0;for(let l of s)l>a&&(a=l);let u=a-8,c=new Float32Array(St*br);for(let l=0;l<s.length;l++){let d=s[l]<u?u:s[l];c[l]=(d+4)/4}return c}}});function pO(t){return t.toLowerCase().replace(/[.,!?;:]+$/g,"").trim()}function jp(t,e){return e.some(n=>Ix(t,n))}function Ix(t,e){if(!t.endsWith(e))return!1;let n=t.length-e.length-1;return n<0||t[n]===" "}function mO(t,e){let n=gO(t);return n===""?null:e.find(i=>vO(n,i))??null}function gO(t){let e=/^.*[.!?]\s+/s.exec(t);return(e?t.slice(e[0].length):t).trim()}function vO(t,e){for(let n=t.indexOf(e);n!==-1;n=t.indexOf(e,n+1)){let i=n===0||!kx(t[n-1]),r=n+e.length===t.length||!kx(t[n+e.length]);if(i&&r)return!0}return!1}function kx(t){return/[a-z0-9']/.test(t)}var va,Mp,Ri,Fp=v(()=>{"use strict";Ti();Ti();va={silenceEnergyThreshold:na,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"]},Mp="semantic",Ri=class{clock;config;classifier;telemetry=null;phase="listening";inSilence=!1;silenceStartedAt=null;firstSpeechAt=null;budgetOwner="baseline";armedBudgetMs=null;lastRawPartial="";lastNormPartial="";strongHoldCue=null;held=!1;heldLadderStep=0;heldCeilingDeadlineAtMs=null;commitCb;silenceTimer=null;graceTimer=null;stopTimer=null;ceilingTimer=null;constructor(e,n={},i){this.clock=e,this.config={...va,...n},this.classifier=i??new Ii(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=pO(e),jp(this.lastNormPartial,this.config.commitCues)){this.commit("lexical");return}let n=this.strongHoldCue;if(this.strongHoldCue=mO(this.lastNormPartial,this.config.strongHoldCues),this.strongHoldCue!==null){if(this.strongHoldCue!==n){this.telemetry?.strongHoldRecognized(this.strongHoldCue),this.held||this.enterHeld(this.strongHoldCue);return}if(this.held)return;if(Ix(this.lastNormPartial,this.strongHoldCue)){this.enterHeld(this.strongHoldCue);return}this.holdFloor();return}if(jp(this.lastNormPartial,this.config.weakHoldCues)){if(this.held)return;this.holdFloor()}}onCommit(e){this.commitCb=e}attachTelemetry(e){this.telemetry=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,n="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=n),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:/[.!?]$/.test(this.lastRawPartial)?!0:jp(this.lastNormPartial,this.config.commitCues)}enterHeld(e){if(this.held)return;let n=this.clock.now();this.heldCeilingDeadlineAtMs??=n+this.config.heldCeilingMs;let i=this.heldCeilingDeadlineAtMs-n;if(!(i<=0&&e===Mp)){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 Ex,Di,Vp=v(()=>{"use strict";ga();Fp();Ex={...va,commitThreshold:.65,holdThreshold:.35},Di=class extends Ri{smartConfig;inference;buffer=new Int16Array(Ue*2);bufferLen=0;silenceEpoch=0;degraded=!1;smartDisposed=!1;semantics;evaluatedEpoch=0;evaluationAbort=new AbortController;constructor(e,n,i={},r,o){super(e,i,r),this.smartConfig={...Ex,...i},this.inference=n,o&&(this.semantics=o)}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,n=this.snapshotBuffer();this.runInference(n,e)}async runInference(e,n){let i=this.clock.now(),r;try{r=await this.inference.infer(e)}catch(s){let a=this.degraded;this.degraded=!0,!a&&!this.smartDisposed&&this.telemetry?.smartTurnDegraded(this.clock.now()-i,s);return}let o=this.clock.now()-i;if(this.smartDisposed||n!==this.silenceEpoch||!this.canRefineBudget()){this.telemetry?.smartTurnResolved(r,o,"stale");return}r>=this.smartConfig.commitThreshold?(this.telemetry?.smartTurnResolved(r,o,"shorten"),this.rearmSilence(this.smartConfig.shortSilenceMs),this.maybeEvaluateTurn(n,"shorten")):r<=this.smartConfig.holdThreshold?(this.telemetry?.smartTurnResolved(r,o,"extend"),this.rearmSilence(this.smartConfig.longSilenceMs)):(this.telemetry?.smartTurnResolved(r,o,"inconclusive"),this.maybeEvaluateTurn(n,"inconclusive"))}maybeEvaluateTurn(e,n){if(!this.semantics||this.evaluatedEpoch===e||this.isHeld())return;let i=this.livePartial();i!==""&&(this.evaluatedEpoch=e,this.runEvaluation(this.semantics,i,e,n))}async runEvaluation(e,n,i,r){this.telemetry?.evaluatorFired?.(r);let o=this.clock.now(),s;try{s=await e.evaluator.evaluate({recentTurns:e.recentTurns(),livePartial:n},this.evaluationAbort.signal)}catch(u){this.smartDisposed||this.telemetry?.evaluatorFailed?.(this.clock.now()-o,u);return}let a=this.clock.now()-o;if(this.smartDisposed||i!==this.silenceEpoch||!this.canApplySemanticVerdict()){this.telemetry?.evaluatorResolved?.(s.verdict,s.confidence,a,"stale");return}if(this.telemetry?.evaluatorResolved?.(s.verdict,s.confidence,a,"applied"),s.verdict==="done")this.rearmSilence(this.smartConfig.shortSilenceMs,"semantic");else if(s.verdict==="mid_thought")this.rearmSilence(this.smartConfig.longSilenceMs,"semantic");else{if(this.heldAllowanceExhausted())return;this.enterHeld(Mp),this.resumeHeldSilence()}}appendToBuffer(e){let n=e.byteLength>>1;if(n===0)return;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n>Ue?n-Ue:0,o=n-r;if(this.bufferLen+o>this.buffer.length){let s=Math.min(this.bufferLen,Ue);this.buffer.copyWithin(0,this.bufferLen-s,this.bufferLen),this.bufferLen=s}for(let s=r;s<n;s++)this.buffer[this.bufferLen++]=i.getInt16(s*2,!0)}snapshotBuffer(){let e=Math.max(0,this.bufferLen-Ue);return this.buffer.slice(e,this.bufferLen)}}});function Zp(t={}){return pa(Tx,Ox,import.meta.url,t)}var Tx,Ox,Bp=v(()=>{"use strict";Ap();Tx="smart-turn-v3.1-cpu.onnx",Ox="JARVIS_SMART_TURN_MODEL_PATH"});var Li,Gp=v(()=>{"use strict";ga();Pp();Bp();Li=class{logMel;modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;constructor(e={}){this.logMel=e.logMel??new Ni,this.modelPath=e.modelPath}async infer(e){if(this.disposed)throw new Error("SmartTurnRunner is disposed");let n=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let r=this.logMel.fromPcm16(e),o=new i.Tensor("float32",r,[1,Up,br]),s=await n.run({input_features:o});if(this.disposed)throw new Error("SmartTurnRunner is disposed");let a=n.outputNames[0],c=s[a].data[0];if(!Number.isFinite(c))throw new Error("smart-turn produced a non-finite output");return c<0?0:c>1?1:c}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 fa();this.ort=e,ha(e);let n=this.modelPath??Zp(),i=await e.InferenceSession.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SmartTurnRunner is disposed");return this.session=i,i}}});function SO(t){let e=[];if(t.recentTurns.length>0){e.push("Recent conversation:");for(let n of t.recentTurns)e.push(`${n.role==="assistant"?"Assistant":"User"}: ${n.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(`
78
+ `)return e;let i=e+1<this.buffer.length?this.buffer[e+1]:"";if(i!==""&&/\s/.test(i)&&(zT.has(n)||NT.has(n)&&e+1>=this.minClauseLength))return e}return-1}}});var ki,np=v(()=>{"use strict";ki=class{nextId=1;timers=new Map;now(){return Date.now()}setTimer(e,n){let i=this.nextId++,r=setTimeout(()=>{this.timers.delete(i),n()},e);return this.timers.set(i,r),i}clearTimer(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}}});function Bt(t,e){let n=Math.floor(t.byteLength/2);if(n===0)return!1;let i=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0;for(let o=0;o<n;o++){let s=i.getInt16(o*2,!0)/32768;r+=s*s}return Math.sqrt(r/n)>=e}function RT(t){let e=t.byteLength>>1,n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let r=0;r<e;r++)i[r]=n.getInt16(r*2,!0);return i}var na,Ii,Ei,Ti=v(()=>{"use strict";De();na=.02;Ii=class{threshold;constructor(e){this.threshold=e}classify(e,n){n(Bt(e,this.threshold))}},Ei=class{vad;speechThreshold;energyThreshold;log;degraded=!1;announced=!1;disposed=!1;constructor(e,n={}){this.vad=e,this.speechThreshold=n.speechThreshold??.5,this.energyThreshold=n.energyThreshold??na,this.log=n.log??q}classify(e,n){if(this.degraded){this.announce("energy (fallback)"),n(Bt(e,this.energyThreshold));return}this.vad.process(RT(e)).then(i=>{if(!this.disposed){this.announce("silero");for(let r of i)n(r>=this.speechThreshold)}},i=>{this.disposed||(this.degrade(i),this.announce("energy (fallback)"),n(Bt(e,this.energyThreshold)))})}reset(){!this.degraded&&!this.disposed&&this.vad.reset()}prewarm(){this.degraded||this.disposed||this.vad.load().then(()=>{},e=>this.degrade(e))}dispose(){return this.disposed=!0,this.vad.dispose()}degrade(e){this.degraded||this.disposed||(this.degraded=!0,this.log.debug("frame classifier DEGRADED to energy (fallback) - silero vad failed; turn-end classifies on RMS energy for the rest of the session",{error:e instanceof Error?e.message:String(e)}))}announce(e){this.announced||(this.announced=!0,this.log.debug(`frame classifier: ${e}`))}}});var ia,mr,fn,DT,Wb,ip=v(()=>{ia=new Map,mr=[],fn=(t,e,n)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let i=ia.get(t);if(i===void 0)ia.set(t,{backend:e,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${n}`)}if(n>=0){let r=mr.indexOf(t);r!==-1&&mr.splice(r,1);for(let o=0;o<mr.length;o++)if(ia.get(mr[o]).priority<=n){mr.splice(o,0,t);return}mr.push(t)}return}throw new TypeError("not a valid backend")},DT=async t=>{let e=ia.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let n=!!e.initPromise;try{return n||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(i){return n||(e.error=`${i}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Wb=async t=>{let e=t.executionProviders||[],n=e.map(u=>typeof u=="string"?u:u.name),i=n.length===0?mr:n,r,o=[],s=new Set;for(let u of i){let c=await DT(u);typeof c=="string"?o.push({name:u,err:c}):(r||(r=c),r===c&&s.add(u))}if(!r)throw new Error(`no available backend found. ERR: ${o.map(u=>`[${u.name}] ${u.err}`).join(", ")}`);for(let{name:u,err:c}of o)n.includes(u)&&console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${c}`);let a=e.filter(u=>s.has(typeof u=="string"?u:u.name));return[r,new Proxy(t,{get:(u,c)=>c==="executionProviders"?a:Reflect.get(u,c)})]}});var qb=v(()=>{ip()});var Hb,Jb=v(()=>{Hb="1.26.0"});var Kb,de,op=v(()=>{Jb();Kb="warning",de={wasm:{},webgl:{},webgpu:{},versions:{common:Hb},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}`);Kb=t}},get logLevel(){return Kb}};Object.defineProperty(de,"logLevel",{enumerable:!0})});var ie,Yb=v(()=>{op();ie=de});var Xb,Qb,e$=v(()=>{Xb=(t,e)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=t.dims[3],n.height=t.dims[2];let i=n.getContext("2d");if(i!=null){let r,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(r=t.dims[2],o=t.dims[3]):(r=t.dims[3],o=t.dims[2]);let s=e?.format!==void 0?e.format:"RGB",a=e?.norm,u,c;a===void 0||a.mean===void 0?u=[255,255,255,255]:typeof a.mean=="number"?u=[a.mean,a.mean,a.mean,a.mean]:(u=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(u[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let l=o*r,d=0,f=l,h=l*2,p=-1;s==="RGBA"?(d=0,f=l,h=l*2,p=l*3):s==="RGB"?(d=0,f=l,h=l*2):s==="RBG"&&(d=0,h=l,f=l*2);for(let _=0;_<o;_++)for(let S=0;S<r;S++){let k=(t.data[d++]-c[0])*u[0],C=(t.data[f++]-c[1])*u[1],A=(t.data[h++]-c[2])*u[2],I=p===-1?255:(t.data[p++]-c[3])*u[3];i.fillStyle="rgba("+k+","+C+","+A+","+I+")",i.fillRect(S,_,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Qb=(t,e)=>{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let r,o,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(r=t.dims[2],o=t.dims[1],s=t.dims[3]):(r=t.dims[3],o=t.dims[2],s=t.dims[1]);let a=e!==void 0&&e.format!==void 0?e.format:"RGB",u=e?.norm,c,l;u===void 0||u.mean===void 0?c=[255,255,255,255]:typeof u.mean=="number"?c=[u.mean,u.mean,u.mean,u.mean]:(c=[u.mean[0],u.mean[1],u.mean[2],255],u.mean[3]!==void 0&&(c[3]=u.mean[3])),u===void 0||u.bias===void 0?l=[0,0,0,0]:typeof u.bias=="number"?l=[u.bias,u.bias,u.bias,u.bias]:(l=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(l[3]=u.bias[3]));let d=o*r;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,h=0,p=1,_=2,S=3,k=0,C=d,A=d*2,I=-1;a==="RGBA"?(k=0,C=d,A=d*2,I=d*3):a==="RGB"?(k=0,C=d,A=d*2):a==="RBG"&&(k=0,A=d,C=d*2),i=n.createImageData(r,o);for(let T=0;T<o*r;h+=f,p+=f,_+=f,S+=f,T++)i.data[h]=(t.data[k++]-l[0])*c[0],i.data[p]=(t.data[C++]-l[1])*c[1],i.data[_]=(t.data[A++]-l[2])*c[2],i.data[S]=I===-1?255:(t.data[I++]-l[3])*c[3]}else throw new Error("Can not access image data");return i}});var sp,t$,r$,n$,i$,o$,s$=v(()=>{oa();sp=(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:n,width:i}=e,r=e.norm??{mean:255,bias:0},o,s;typeof r.mean=="number"?o=[r.mean,r.mean,r.mean,r.mean]:o=[r.mean[0],r.mean[1],r.mean[2],r.mean[3]??255],typeof r.bias=="number"?s=[r.bias,r.bias,r.bias,r.bias]:s=[r.bias[0],r.bias[1],r.bias[2],r.bias[3]??0];let a=e.format!==void 0?e.format:"RGBA",u=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=n*i,l=u==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,f=0,h=1,p=2,_=3,S=0,k=c,C=c*2,A=-1;a==="RGB"&&(d=3,f=0,h=1,p=2,_=-1),u==="RGBA"?A=c*3:u==="RBG"?(S=0,C=c,k=c*2):u==="BGR"&&(C=0,k=c,S=c*2);for(let T=0;T<c;T++,f+=d,p+=d,h+=d,_+=d)l[S++]=(t[f]+s[0])/o[0],l[k++]=(t[h]+s[1])/o[1],l[C++]=(t[p]+s[2])/o[2],A!==-1&&_!==-1&&(l[A++]=(t[_]+s[3])/o[3]);return u==="RGBA"?new ye("float32",l,[1,4,n,i]):new ye("float32",l,[1,3,n,i])},t$=async(t,e)=>{let n=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,i=typeof ImageData<"u"&&t instanceof ImageData,r=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",s,a=e??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=l=>typeof HTMLCanvasElement<"u"&&l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas?l.getContext("2d"):null;if(n){let l=u();l.width=t.width,l.height=t.height;let d=c(l);if(d!=null){let f=t.height,h=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(f=e.resizedHeight,h=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=f,a.width=h}else a.tensorFormat="RGBA",a.height=f,a.width=h;d.drawImage(t,0,0),s=d.getImageData(0,0,h,f).data}else throw new Error("Can not access image data")}else if(i){let l,d;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(l=e.resizedHeight,d=e.resizedWidth):(l=t.height,d=t.width),e!==void 0&&(a=e),a.format="RGBA",a.height=l,a.width=d,e!==void 0){let f=u();f.width=d,f.height=l;let h=c(f);if(h!=null)h.putImageData(t,0,0),s=h.getImageData(0,0,d,l).data;else throw new Error("Can not access image data")}else s=t.data}else if(r){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let l=u();l.width=t.width,l.height=t.height;let d=c(l);if(d!=null){let f=t.height,h=t.width;return d.drawImage(t,0,0,h,f),s=d.getImageData(0,0,h,f).data,a.height=f,a.width=h,sp(s,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((l,d)=>{let f=u(),h=c(f);if(!t||!h)return d();let p=new Image;p.crossOrigin="Anonymous",p.src=t,p.onload=()=>{f.width=p.width,f.height=p.height,h.drawImage(p,0,0,f.width,f.height);let _=h.getImageData(0,0,f.width,f.height);a.height=f.height,a.width=f.width,l(sp(_.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return sp(s,a);throw new Error("Input data provided is not supported - aborted tensor creation")},r$=(t,e)=>{let{width:n,height:i,download:r,dispose:o}=e,s=[1,i,n,4];return new ye({location:"texture",type:"float32",texture:t,dims:s,download:r,dispose:o})},n$=(t,e)=>{let{dataType:n,dims:i,download:r,dispose:o}=e;return new ye({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:i,download:r,dispose:o})},i$=(t,e)=>{let{dataType:n,dims:i,download:r,dispose:o}=e;return new ye({location:"ml-tensor",type:n??"float32",mlTensor:t,dims:i,download:r,dispose:o})},o$=(t,e,n)=>new ye({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]})});var gr,Oi,a$,u$,c$=v(()=>{gr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Oi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),a$=!1,u$=()=>{if(!a$){a$=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;t&&(gr.set("int64",BigInt64Array),Oi.set(BigInt64Array,"int64")),e&&(gr.set("uint64",BigUint64Array),Oi.set(BigUint64Array,"uint64")),i?(gr.set("float16",n),Oi.set(n,"float16")):gr.set("float16",Uint16Array)}}});var l$,d$,f$=v(()=>{oa();l$=t=>{let e=1;for(let n=0;n<t.length;n++){let i=t[n];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${n}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${i}`);e*=i}return e},d$=(t,e)=>{switch(t.location){case"cpu":return new ye(t.type,t.data,e);case"cpu-pinned":return new ye({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new ye({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new ye({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new ye({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}});var ye,oa=v(()=>{e$();s$();c$();f$();ye=class{constructor(e,n,i){u$();let r,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,r=e.type,o=e.dims,e.location){case"cpu-pinned":{let a=gr.get(r);if(!a)throw new TypeError(`unsupported type "${r}" 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(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint64"&&r!=="int8"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" 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,u;if(typeof e=="string")if(r=e,u=i,e==="string"){if(!Array.isArray(n))throw new TypeError("A string tensor's data must be a string array.");a=n}else{let c=gr.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(n)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?a=c.from(n,BigInt):a=c.from(n)}else if(n instanceof c)a=n;else if(n instanceof Uint8ClampedArray)if(e==="uint8")a=Uint8Array.from(n);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&n instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(n.buffer,n.byteOffset,n.length);else throw new TypeError(`A ${r} tensor's data must be type of ${c}`)}else if(u=n,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")r="string",a=e;else if(c==="boolean")r="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)r="uint8",a=Uint8Array.from(e);else{let c=Oi.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=c,a=e}if(u===void 0)u=[a.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");o=u,this.cpuData=a,this.dataLocation="cpu"}let s=l$(o);if(this.cpuData&&s!==this.cpuData.length&&!((r==="uint4"||r==="int4")&&Math.ceil(s/2)===this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=o,this.size=s}static async fromImage(e,n){return t$(e,n)}static fromTexture(e,n){return r$(e,n)}static fromGpuBuffer(e,n){return n$(e,n)}static fromMLTensor(e,n){return i$(e,n)}static fromPinnedBuffer(e,n,i){return o$(e,n,i)}toDataURL(e){return Xb(this,e)}toImageData(e){return Qb(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 n=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=n,e&&this.disposer&&(this.disposer(),this.disposer=void 0),n}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 d$(this,e)}}});var Ye,ap=v(()=>{oa();Ye=ye});var up,h$,Gt,Wt,qt,Ht,cp=v(()=>{op();up=(t,e)=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||console.timeStamp(`${t}::ORT::${e}`)},h$=(t,e)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let r=0;r<n.length;r++){if(i&&!n[r].includes("TRACE_FUNC")){let o=`FUNC_${t}::${n[r].trim().split(" ")[1]}`;e&&(o+=`::${e}`),up("CPU",o);return}n[r].includes("TRACE_FUNC")&&(i=!0)}},Gt=t=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||h$("BEGIN",t)},Wt=t=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||h$("END",t)},qt=t=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||console.time(`ORT::${t}`)},Ht=t=>{(typeof de.trace>"u"?!de.wasm.trace:!de.trace)||console.timeEnd(`ORT::${t}`)}});var sa,p$=v(()=>{ip();ap();cp();sa=class t{constructor(e){this.handler=e}async run(e,n,i){Gt(),qt("InferenceSession.run");let r={},o={};if(typeof e!="object"||e===null||e instanceof Ye||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof Ye)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let c of n){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);r[c]=null}if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,l=Object.getOwnPropertyNames(n);for(let d of this.outputNames)if(l.indexOf(d)!==-1){let f=n[d];(f===null||f instanceof Ye)&&(c=!0,s=!1,r[d]=f)}if(c){if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else o=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(s)for(let c of this.outputNames)r[c]=null;let a=await this.handler.run(e,r,o),u={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let l=a[c];l instanceof Ye?u[c]=l:u[c]=new Ye(l.type,l.data,l.dims)}return Ht("InferenceSession.run"),Wt(),u}async release(){return this.handler.dispose()}static async create(e,n,i,r){Gt(),qt("InferenceSession.create");let o,s={};if(typeof e=="string"){if(o=e,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let l=e,d=0,f=e.byteLength;if(typeof n=="object"&&n!==null)s=n;else if(typeof n=="number"){if(d=n,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=l.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${l.byteLength}).`);if(f=e.byteLength-d,typeof i=="number"){if(f=i,!Number.isSafeInteger(f))throw new RangeError("'byteLength' must be an integer.");if(f<=0||d+f>l.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${l.byteLength-d}].`);if(typeof r=="object"&&r!==null)s=r;else if(typeof r<"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 n<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(l,d,f)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,u]=await Wb(s),c=await a.createInferenceSessionHandler(o,u);return Ht("InferenceSession.create"),Wt(),new t(c)}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 m$,g$=v(()=>{p$();m$=sa});var v$=v(()=>{});var y$=v(()=>{});var _$=v(()=>{});var b$=v(()=>{});var lp={};He(lp,{InferenceSession:()=>m$,TRACE:()=>up,TRACE_EVENT_BEGIN:()=>qt,TRACE_EVENT_END:()=>Ht,TRACE_FUNC_BEGIN:()=>Gt,TRACE_FUNC_END:()=>Wt,Tensor:()=>Ye,env:()=>ie,registerBackend:()=>fn});var Jt=v(()=>{qb();Yb();g$();ap();v$();y$();cp();_$();b$()});var dx={};He(dx,{InferenceSession:()=>m$,TRACE:()=>up,TRACE_EVENT_BEGIN:()=>qt,TRACE_EVENT_END:()=>Ht,TRACE_FUNC_BEGIN:()=>Gt,TRACE_FUNC_END:()=>Wt,Tensor:()=>Ye,default:()=>KT,env:()=>ie,registerBackend:()=>fn});import{createRequire as LT}from"module";var hn,kp,UT,jT,MT,$p,Xe,FT,VT,ZT,gn,Ip,dp,$$,x$,wt,L$,fp,w$,S$,k$,I$,hp,U$,j$,pp,aa,Pi,mp,E$,T$,O$,M$,ee,Ci,at,la,K,Ep,F$,BT,P$,C$,A$,vr,z$,V$,GT,pn,ca,mn,Z$,B$,Tp,Op,G$,W$,da,q$,N$,H$,J$,yr,R$,gp,xp,K$,Y$,vp,X$,Q$,WT,ua,yp,_p,ex,tx,rx,nx,ix,ox,sx,ax,bp,D$,ux,qT,cx,wp,Sp,lx,HT,JT,KT,fx=v(()=>{Jt();Jt();Jt();Jt();Jt();Jt();Jt();hn=LT(import.meta.url),kp=Object.defineProperty,UT=Object.getOwnPropertyDescriptor,jT=Object.getOwnPropertyNames,MT=Object.prototype.hasOwnProperty,$p=(t=>typeof hn<"u"?hn:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof hn<"u"?hn:e)[n]}):t)(function(t){if(typeof hn<"u")return hn.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),Xe=(t,e)=>()=>(t&&(e=t(t=0)),e),FT=(t,e)=>{for(var n in e)kp(t,n,{get:e[n],enumerable:!0})},VT=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jT(e))!MT.call(t,r)&&r!==n&&kp(t,r,{get:()=>e[r],enumerable:!(i=UT(e,r))||i.enumerable});return t},ZT=t=>VT(kp({},"__esModule",{value:!0}),t),Ip=Xe(()=>{"use strict";gn=!!(typeof process<"u"&&process.versions&&process.versions.node)}),j$=Xe(()=>{"use strict";Ip(),dp=gn||typeof location>"u"?void 0:location.origin,$$=import.meta.url>"file:"&&import.meta.url<"file;",x$=()=>{if(!gn){if($$){let t=URL;return new URL(new t("ort.node.min.mjs",import.meta.url).href,dp).href}return import.meta.url}},wt=x$(),L$=()=>{if(wt&&!wt.startsWith("blob:"))return wt.substring(0,wt.lastIndexOf("/")+1)},fp=(t,e)=>{try{let n=e??wt;return(n?new URL(t,n):new URL(t)).origin===dp}catch{return!1}},w$=(t,e)=>{let n=e??wt;try{return(n?new URL(t,n):new URL(t)).href}catch{return}},S$=(t,e)=>`${e??"./"}${t}`,k$=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},I$=async t=>(await import(t)).default,hp=void 0,U$=async(t,e,n,i)=>{let r=hp&&!(t||e);if(r)if(wt)r=fp(wt)||i&&!n;else if(i&&!n)r=!0;else throw new Error("cannot determine the script source URL.");if(r)return[void 0,hp];{let o="ort-wasm-simd-threaded.mjs",s=t??w$(o,e),a=!gn&&n&&s&&!fp(s,e),u=a?await k$(s):s??S$(o,e);return[a?u:void 0,await I$(u)]}}}),Ci=Xe(()=>{"use strict";j$(),aa=!1,Pi=!1,mp=!1,E$=()=>{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}},T$=()=>{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}},O$=()=>{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}},M$=async t=>{if(aa)return Promise.resolve();if(Pi)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(mp)throw new Error("previous call to 'initializeWebAssembly()' failed.");Pi=!0;let e=t.initTimeout,n=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!O$())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!T$())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=E$();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", 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=n=1);let r=t.wasmPaths,o=typeof r=="string"?r:void 0,s=r?.mjs,a=s?.href??s,u=r?.wasm,c=u?.href??u,l=t.wasmBinary,[d,f]=await U$(a,o,n>1,!!l||!!c),h=!1,p=[];if(e>0&&p.push(new Promise(_=>{setTimeout(()=>{h=!0,_()},e)})),p.push(new Promise((_,S)=>{let k={numThreads:n};if(l)k.wasmBinary=l,k.locateFile=C=>C;else if(c||o)k.locateFile=C=>c??o+C;else if(a&&a.indexOf("blob:")!==0)k.locateFile=C=>new URL(C,a).href;else if(d){let C=L$();C&&(k.locateFile=A=>C+A)}f(k).then(C=>{Pi=!1,aa=!0,pp=C,_(),d&&URL.revokeObjectURL(d)},C=>{Pi=!1,mp=!0,S(C)})})),await Promise.race(p),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},ee=()=>{if(aa&&pp)return pp;throw new Error("WebAssembly is not initialized yet.")}}),Ep=Xe(()=>{"use strict";Ci(),at=(t,e)=>{let n=ee(),i=n.lengthBytesUTF8(t)+1,r=n._malloc(i);return n.stringToUTF8(t,r,i),e.push(r),r},la=(t,e,n,i)=>{if(typeof t=="object"&&t!==null){if(n.has(t))throw new Error("Circular reference in options");n.add(t)}Object.entries(t).forEach(([r,o])=>{let s=e?e+r:r;if(typeof o=="object")la(o,s+".",n,i);else if(typeof o=="string"||typeof o=="number")i(s,o.toString());else if(typeof o=="boolean")i(s,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},K=t=>{let e=ee(),n=e.stackSave();try{let i=e.PTR_SIZE,r=e.stackAlloc(2*i);e._OrtGetLastError(r,r+i);let o=Number(e.getValue(r,i===4?"i32":"i64")),s=e.getValue(r+i,"*"),a=s?e.UTF8ToString(s):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${a}`)}finally{e.stackRestore(n)}}}),BT=Xe(()=>{"use strict";Ci(),Ep(),F$=t=>{let e=ee(),n=0,i=[],r=t||{};try{if(t?.logSeverityLevel===void 0)r.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)r.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&&(r.terminate=!1);let o=0;return t?.tag!==void 0&&(o=at(t.tag,i)),n=e._OrtCreateRunOptions(r.logSeverityLevel,r.logVerbosityLevel,!!r.terminate,o),n===0&&K("Can't create run options."),t?.extra!==void 0&&la(t.extra,"",new WeakSet,(s,a)=>{let u=at(s,i),c=at(a,i);e._OrtAddRunConfigEntry(n,u,c)!==0&&K(`Can't set a run config entry: ${s} - ${a}.`)}),[n,i]}catch(o){throw n!==0&&e._OrtReleaseRunOptions(n),i.forEach(s=>e._free(s)),o}}}),GT=Xe(()=>{"use strict";Ci(),Ep(),P$=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}`)}},C$=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},A$=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(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(t.enableMemPattern=!1)},vr=(t,e,n,i)=>{let r=at(e,i),o=at(n,i);ee()._OrtAddSessionConfigEntry(t,r,o)!==0&&K(`Can't set a session config entry: ${e} - ${n}.`)},z$=async(t,e,n)=>{let i=e.executionProviders;for(let r of i){let o=typeof r=="string"?r:r.name,s=[];switch(o){case"webnn":if(o="WEBNN",vr(t,"session.disable_quant_qdq","1",n),vr(t,"session.disable_qdq_constant_folding","1",n),typeof r!="string"){let d=r?.deviceType;d&&vr(t,"deviceType",d,n)}break;case"webgpu":if(o="JS",typeof r!="string"){let d=r;if(d?.preferredLayout){if(d.preferredLayout!=="NCHW"&&d.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${d.preferredLayout}`);vr(t,"preferredLayout",d.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let a=at(o,n),u=s.length,c=0,l=0;if(u>0){c=ee()._malloc(u*ee().PTR_SIZE),n.push(c),l=ee()._malloc(u*ee().PTR_SIZE),n.push(l);for(let d=0;d<u;d++)ee().setValue(c+d*ee().PTR_SIZE,s[d][0],"*"),ee().setValue(l+d*ee().PTR_SIZE,s[d][1],"*")}await ee()._OrtAppendExecutionProvider(t,a,c,l,u)!==0&&K(`Can't append execution provider: ${o}.`)}},V$=async t=>{let e=ee(),n=0,i=[],r=t||{};A$(r);try{let o=P$(r.graphOptimizationLevel??"all"),s=C$(r.executionMode??"sequential"),a=typeof r.logId=="string"?at(r.logId,i):0,u=r.logSeverityLevel??2;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log severity level is not valid: ${u}`);let c=r.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let l=typeof r.optimizedModelFilePath=="string"?at(r.optimizedModelFilePath,i):0;if(n=e._OrtCreateSessionOptions(o,!!r.enableCpuMemArena,!!r.enableMemPattern,s,!!r.enableProfiling,0,a,u,c,l),n===0&&K("Can't create session options."),r.executionProviders&&await z$(n,r,i),r.enableGraphCapture!==void 0){if(typeof r.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${r.enableGraphCapture}`);vr(n,"enableGraphCapture",r.enableGraphCapture.toString(),i)}if(r.freeDimensionOverrides)for(let[d,f]of Object.entries(r.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error(`free dimension override value must be a non-negative integer: ${f}`);let h=at(d,i);e._OrtAddFreeDimensionOverride(n,h,f)!==0&&K(`Can't set a free dimension override: ${d} - ${f}.`)}return r.extra!==void 0&&la(r.extra,"",new WeakSet,(d,f)=>{vr(n,d,f,i)}),[n,i]}catch(o){throw n!==0&&e._OrtReleaseSessionOptions(n)!==0&&K("Can't release session options."),i.forEach(s=>e._free(s)),o}}}),W$=Xe(()=>{"use strict";pn=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}`)}},ca=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}`)}},mn=(t,e)=>{let n=[-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((r,o)=>r*o,1);return n>0?Math.ceil(i*n):void 0},Z$=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}`)}},B$=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}`)}},Tp=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Op=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",G$=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}`)}}}),q$=Xe(()=>{"use strict";Ip(),da=async t=>{if(typeof t=="string")if(gn)try{let{readFile:e}=$p("node:fs/promises");return new Uint8Array(await e(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let{createReadStream:n}=$p("node:fs"),i=n(t),r=[];for await(let o of i)r.push(o);return new Uint8Array(Buffer.concat(r))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let n=e.headers.get("Content-Length"),i=n?parseInt(n,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 r=e.body.getReader(),o;try{o=new ArrayBuffer(i)}catch(a){if(a instanceof RangeError){let u=Math.ceil(i/65536);o=new WebAssembly.Memory({initial:u,maximum:u}).buffer}else throw a}let s=0;for(;;){let{done:a,value:u}=await r.read();if(a)break;let c=u.byteLength;new Uint8Array(o,s,c).set(u),s+=c}return new Uint8Array(o,0,i)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),WT=Xe(()=>{"use strict";BT(),GT(),W$(),Ci(),Ep(),q$(),N$=(t,e)=>{ee()._OrtInit(t,e)!==0&&K("Can't initialize onnxruntime.")},H$=async t=>{N$(t.wasm.numThreads,B$(t.logLevel))},J$=async(t,e)=>{ee().asyncInit?.();let n=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.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 r=t.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:r}),!n)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")},yr=new Map,R$=t=>{let e=ee(),n=e.stackSave();try{let i=e.PTR_SIZE,r=e.stackAlloc(2*i);e._OrtGetInputOutputCount(t,r,r+i)!==0&&K("Can't get session input/output count.");let o=i===4?"i32":"i64";return[Number(e.getValue(r,o)),Number(e.getValue(r+i,o))]}finally{e.stackRestore(n)}},gp=(t,e)=>{let n=ee(),i=n.stackSave(),r=0;try{let o=n.PTR_SIZE,s=n.stackAlloc(2*o);n._OrtGetInputOutputMetadata(t,e,s,s+o)!==0&&K("Can't get session input/output metadata.");let a=Number(n.getValue(s,"*"));r=Number(n.getValue(s+o,"*"));let u=n.HEAP32[r/4];if(u===0)return[a,0];let c=n.HEAPU32[r/4+1],l=[];for(let d=0;d<c;d++){let f=Number(n.getValue(r+8+d*o,"*"));l.push(f!==0?n.UTF8ToString(f):Number(n.getValue(r+8+(d+c)*o,"*")))}return[a,u,l]}finally{n.stackRestore(i),r!==0&&n._OrtFree(r)}},xp=t=>{let e=ee(),n=e._malloc(t.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,n),[n,t.byteLength]},K$=async(t,e)=>{let n,i,r=ee();Array.isArray(t)?[n,i]=t:t.buffer===r.HEAPU8.buffer?[n,i]=[t.byteOffset,t.byteLength]:[n,i]=xp(t);let o=0,s=0,a=0,u=[],c=[],l=[];try{if([s,u]=await V$(e),e?.externalData&&r.mountExternalData){let A=[];for(let I of e.externalData){let T=typeof I=="string"?I:I.path;A.push(da(typeof I=="string"?I:I.data).then(Z=>{r.mountExternalData(T,Z)}))}await Promise.all(A)}for(let A of e?.executionProviders??[])if((typeof A=="string"?A:A.name)==="webnn"){if(r.shouldTransferToMLTensor=!1,typeof A!="string"){let I=A,T=I?.context,Z=I?.gpuDevice,F=I?.deviceType,W=I?.powerPreference;T?r.currentContext=T:Z?r.currentContext=await r.webnnCreateMLContext(Z):r.currentContext=await r.webnnCreateMLContext({deviceType:F,powerPreference:W})}else r.currentContext=await r.webnnCreateMLContext();break}o=await r._OrtCreateSession(n,i,s),r.webgpuOnCreateSession?.(o),o===0&&K("Can't create a session."),r.jsepOnCreateSession?.(),r.currentContext&&(r.webnnRegisterMLContext(o,r.currentContext),r.currentContext=void 0,r.shouldTransferToMLTensor=!0);let[d,f]=R$(o),h=!!e?.enableGraphCapture,p=[],_=[],S=[],k=[],C=[];for(let A=0;A<d;A++){let[I,T,Z]=gp(o,A);I===0&&K("Can't get an input name."),c.push(I);let F=r.UTF8ToString(I);p.push(F),S.push(T===0?{name:F,isTensor:!1}:{name:F,isTensor:!0,type:ca(T),shape:Z})}for(let A=0;A<f;A++){let[I,T,Z]=gp(o,A+d);I===0&&K("Can't get an output name."),l.push(I);let F=r.UTF8ToString(I);_.push(F),k.push(T===0?{name:F,isTensor:!1}:{name:F,isTensor:!0,type:ca(T),shape:Z})}return yr.set(o,[o,c,l,null,h,!1]),[o,p,_,S,k]}catch(d){throw c.forEach(f=>r._OrtFree(f)),l.forEach(f=>r._OrtFree(f)),a!==0&&r._OrtReleaseBinding(a)!==0&&K("Can't release IO binding."),o!==0&&r._OrtReleaseSession(o)!==0&&K("Can't release session."),d}finally{r._free(n),s!==0&&r._OrtReleaseSessionOptions(s)!==0&&K("Can't release session options."),u.forEach(d=>r._free(d)),r.unmountExternalData?.()}},Y$=t=>{let e=ee(),n=yr.get(t);if(!n)throw new Error(`cannot release session. invalid session id: ${t}`);let[i,r,o,s,a]=n;s&&(a&&e._OrtClearBoundOutputs(s.handle)!==0&&K("Can't clear bound outputs."),e._OrtReleaseBinding(s.handle)!==0&&K("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),r.forEach(u=>e._OrtFree(u)),o.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(i)!==0&&K("Can't release session."),yr.delete(t)},vp=async(t,e,n,i,r,o,s=!1)=>{if(!t){e.push(0);return}let a=ee(),u=a.PTR_SIZE,c=t[0],l=t[1],d=t[3],f=d,h,p;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(s&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let k=t[2].gpuBuffer;p=mn(pn(c),l);{let C=a.jsepRegisterBuffer;if(!C)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=C(i,o,k,p)}}else if(d==="ml-tensor"){let k=t[2].mlTensor;p=mn(pn(c),l);let C=a.webnnRegisterMLTensor;if(!C)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=C(i,k,pn(c),l)}else{let k=t[2];if(Array.isArray(k)){p=u*k.length,h=a._malloc(p),n.push(h);for(let C=0;C<k.length;C++){if(typeof k[C]!="string")throw new TypeError(`tensor data at index ${C} is not a string`);a.setValue(h+C*u,at(k[C],n),"*")}}else{let C=a.webnnIsGraphInput,A=a.webnnIsGraphOutput;if(c!=="string"&&C&&A){let I=a.UTF8ToString(r);if(C(i,I)||A(i,I)){let T=pn(c);p=mn(T,l),f="ml-tensor";let Z=a.webnnCreateTemporaryTensor,F=a.webnnUploadTensor;if(!Z||!F)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let W=await Z(i,T,l);F(W,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),h=W}else p=k.byteLength,h=a._malloc(p),n.push(h),a.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,p),h)}else p=k.byteLength,h=a._malloc(p),n.push(h),a.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,p),h)}}let _=a.stackSave(),S=a.stackAlloc(4*l.length);try{l.forEach((C,A)=>a.setValue(S+A*u,C,u===4?"i32":"i64"));let k=a._OrtCreateTensor(pn(c),h,p,S,l.length,G$(f));k===0&&K(`Can't create tensor for input/output. session=${i}, index=${o}.`),e.push(k)}finally{a.stackRestore(_)}},X$=async(t,e,n,i,r,o)=>{let s=ee(),a=s.PTR_SIZE,u=yr.get(t);if(!u)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=u[0],l=u[1],d=u[2],f=u[3],h=u[4],p=u[5],_=e.length,S=i.length,k=0,C=[],A=[],I=[],T=[],Z=[],F=s.stackSave(),W=s.stackAlloc(_*a),ne=s.stackAlloc(_*a),$e=s.stackAlloc(S*a),he=s.stackAlloc(S*a);try{[k,C]=F$(o),qt("wasm prepareInputOutputTensor");for(let D=0;D<_;D++)await vp(n[D],A,T,t,l[e[D]],e[D],h);for(let D=0;D<S;D++)await vp(r[D],I,T,t,d[i[D]],_+i[D],h);Ht("wasm prepareInputOutputTensor");for(let D=0;D<_;D++)s.setValue(W+D*a,A[D],"*"),s.setValue(ne+D*a,l[e[D]],"*");for(let D=0;D<S;D++)s.setValue($e+D*a,I[D],"*"),s.setValue(he+D*a,d[i[D]],"*");s.jsepOnRunStart?.(c),s.webnnOnRunStart?.(c);let Se;Se=await s._OrtRun(c,ne,W,_,he,S,$e,k),Se!==0&&K("failed to call OrtRun().");let ke=[],Q=[];qt("wasm ProcessOutputTensor");for(let D=0;D<S;D++){let ce=Number(s.getValue($e+D*a,"*"));if(ce===I[D]||Z.includes(I[D])){ke.push(r[D]),ce!==I[D]&&s._OrtReleaseTensor(ce)!==0&&K("Can't release tensor.");continue}let it=s.stackSave(),je=s.stackAlloc(4*a),Ar=!1,le,Me=0;try{s._OrtGetTensorData(ce,je,je+a,je+2*a,je+3*a)!==0&&K(`Can't access output tensor data on index ${D}.`);let Ou=a===4?"i32":"i64",lo=Number(s.getValue(je,Ou));Me=s.getValue(je+a,"*");let Eg=s.getValue(je+a*2,"*"),fI=Number(s.getValue(je+a*3,Ou)),Ct=[];for(let pe=0;pe<fI;pe++)Ct.push(Number(s.getValue(Eg+pe*a,Ou)));s._OrtFree(Eg)!==0&&K("Can't free memory for tensor dims.");let At=Ct.reduce((pe,se)=>pe*se,1);le=ca(lo);let Nn=f?.outputPreferredLocations[i[D]];if(le==="string"){if(Nn==="gpu-buffer"||Nn==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let pe=[];for(let se=0;se<At;se++){let _t=s.getValue(Me+se*a,"*"),hI=s.getValue(Me+(se+1)*a,"*"),pI=se===At-1?void 0:hI-_t;pe.push(s.UTF8ToString(_t,pI))}ke.push([le,Ct,pe,"cpu"])}else if(Nn==="gpu-buffer"&&At>0){let pe=s.jsepGetBuffer;if(!pe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let se=pe(Me),_t=mn(lo,At);if(_t===void 0||!Tp(le))throw new Error(`Unsupported data type: ${le}`);Ar=!0,ke.push([le,Ct,{gpuBuffer:se,download:s.jsepCreateDownloader(se,_t,le),dispose:()=>{s._OrtReleaseTensor(ce)!==0&&K("Can't release tensor.")}},"gpu-buffer"])}else if(Nn==="ml-tensor"&&At>0){let pe=s.webnnEnsureTensor,se=s.webnnIsGraphInputOutputTypeSupported;if(!pe||!se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(mn(lo,At)===void 0||!Op(le))throw new Error(`Unsupported data type: ${le}`);if(!se(t,le,!1))throw new Error(`preferredLocation "ml-tensor" for ${le} output is not supported by current WebNN Context.`);let _t=await pe(t,Me,lo,Ct,!1);Ar=!0,ke.push([le,Ct,{mlTensor:_t,download:s.webnnCreateMLTensorDownloader(Me,le),dispose:()=>{s.webnnReleaseTensorId(Me),s._OrtReleaseTensor(ce)}},"ml-tensor"])}else if(Nn==="ml-tensor-cpu-output"&&At>0){let pe=s.webnnCreateMLTensorDownloader(Me,le)(),se=ke.length;Ar=!0,Q.push((async()=>{let _t=[se,await pe];return s.webnnReleaseTensorId(Me),s._OrtReleaseTensor(ce),_t})()),ke.push([le,Ct,[],"cpu"])}else{let pe=Z$(le),se=new pe(At);new Uint8Array(se.buffer,se.byteOffset,se.byteLength).set(s.HEAPU8.subarray(Me,Me+se.byteLength)),ke.push([le,Ct,se,"cpu"])}}finally{s.stackRestore(it),le==="string"&&Me&&s._free(Me),Ar||s._OrtReleaseTensor(ce)}}f&&!h&&(s._OrtClearBoundOutputs(f.handle)!==0&&K("Can't clear bound outputs."),yr.set(t,[c,l,d,f,h,!1]));for(let[D,ce]of await Promise.all(Q))ke[D][2]=ce;return Ht("wasm ProcessOutputTensor"),ke}finally{s.webnnOnRunEnd?.(c),s.stackRestore(F),A.forEach(Se=>s._OrtReleaseTensor(Se)),I.forEach(Se=>s._OrtReleaseTensor(Se)),T.forEach(Se=>s._free(Se)),k!==0&&s._OrtReleaseRunOptions(k),C.forEach(Se=>s._free(Se))}},Q$=t=>{let e=ee(),n=yr.get(t);if(!n)throw new Error("invalid session id");let i=n[0],r=e._OrtEndProfiling(i);r===0&&K("Can't get an profile file name."),e._OrtFree(r)}}),ax=Xe(()=>{"use strict";WT(),Ci(),j$(),ua=!1,yp=!1,_p=!1,ex=async()=>{if(!yp){if(ua)throw new Error("multiple calls to 'initWasm()' detected.");if(_p)throw new Error("previous call to 'initWasm()' failed.");ua=!0;try{await M$(ie.wasm),await H$(ie),yp=!0}catch(t){throw _p=!0,t}finally{ua=!1}}},tx=async t=>{await J$(ie,t)},rx=async t=>xp(t),nx=async(t,e)=>K$(t,e),ix=async t=>{Y$(t)},ox=async(t,e,n,i,r,o)=>X$(t,e,n,i,r,o),sx=async t=>{Q$(t)}}),qT=Xe(()=>{"use strict";ax(),W$(),Ip(),q$(),bp=(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()}`)}},D$=t=>{switch(t[3]){case"cpu":return new Ye(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Tp(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:r}=t[2];return Ye.fromGpuBuffer(n,{dataType:e,dims:t[1],download:i,dispose:r})}case"ml-tensor":{let e=t[0];if(!Op(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:r}=t[2];return Ye.fromMLTensor(n,{dataType:e,dims:t[1],download:i,dispose:r})}default:throw new Error(`invalid data location: ${t[3]}`)}},ux=class{async fetchModelAndCopyToWasmMemory(t){return rx(await da(t))}async loadModel(t,e){Gt();let n;typeof t=="string"?gn?n=await da(t):n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await nx(n,e),Wt()}async dispose(){return ix(this.sessionId)}async run(t,e,n){Gt();let i=[],r=[];Object.entries(t).forEach(d=>{let f=d[0],h=d[1],p=this.inputNames.indexOf(f);if(p===-1)throw new Error(`invalid input '${f}'`);i.push(h),r.push(p)});let o=[],s=[];Object.entries(e).forEach(d=>{let f=d[0],h=d[1],p=this.outputNames.indexOf(f);if(p===-1)throw new Error(`invalid output '${f}'`);o.push(h),s.push(p)});let a=i.map((d,f)=>bp(d,()=>`input "${this.inputNames[r[f]]}"`)),u=o.map((d,f)=>d?bp(d,()=>`output "${this.outputNames[s[f]]}"`):null),c=await ox(this.sessionId,r,a,s,u,n),l={};for(let d=0;d<c.length;d++)l[this.outputNames[s[d]]]=o[d]??D$(c[d]);return Wt(),l}startProfiling(){}endProfiling(){sx(this.sessionId)}}}),cx={};FT(cx,{OnnxruntimeWebAssemblyBackend:()=>Sp,initializeFlags:()=>wp,wasmBackend:()=>lx});HT=Xe(()=>{"use strict";ax(),qT(),wp=()=>{(typeof ie.wasm.initTimeout!="number"||ie.wasm.initTimeout<0)&&(ie.wasm.initTimeout=0);let t=ie.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.`),ie.wasm.simd=!1),typeof ie.wasm.proxy!="boolean"&&(ie.wasm.proxy=!1),typeof ie.wasm.trace!="boolean"&&(ie.wasm.trace=!1),typeof ie.wasm.numThreads!="number"||!Number.isInteger(ie.wasm.numThreads)||ie.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ie.wasm.numThreads=1;else{let e=typeof navigator>"u"?$p("node:os").cpus().length:navigator.hardwareConcurrency;ie.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Sp=class{async init(t){wp(),await ex(),await tx(t)}async createInferenceSessionHandler(t,e){let n=new ux;return await n.loadModel(t,e),n}},lx=new Sp}),JT="1.26.0",KT=lp;{let t=(HT(),ZT(cx)).wasmBackend;fn("cpu",t,10),fn("wasm",t,10)}Object.defineProperty(ie.versions,"web",{value:JT,enumerable:!0})});import{existsSync as YT}from"node:fs";import{createRequire as XT}from"node:module";import{dirname as QT,join as eO,sep as hx}from"node:path";import{fileURLToPath as tO,pathToFileURL as rO}from"node:url";async function fa(){let t=await Promise.resolve().then(()=>(fx(),dx));return t.default??t}function ha(t,e){t.env.wasm.numThreads=1,t.env.wasm.wasmPaths=iO(e)}function nO(t){return[new URL("./",t),new URL("../",t)].map(e=>tO(e))}function iO(t=import.meta.url){let e=nO(t);try{e.push(QT(XT(t).resolve("onnxruntime-web")))}catch{}let n=null;for(let i of e){let r=px.filter(o=>!YT(eO(i,o)));if(r.length===0)return oO(i);r.length<px.length&&n===null&&(n={dir:i,missing:r})}throw n!==null?new Error(`ort-web WASM runtime at '${n.dir}' is missing '${n.missing.join("', '")}' - the .wasm and its .mjs glue must be copied together`):new Error(`ort-web WASM runtime ('${mx}' + '${gx}') not found beside the bundle or in node_modules`)}function oO(t){return rO(t.endsWith(hx)?t:t+hx).href}var mx,gx,px,Pp=v(()=>{"use strict";mx="ort-wasm-simd-threaded.wasm",gx="ort-wasm-simd-threaded.mjs",px=[mx,gx]});import{existsSync as sO}from"node:fs";import{fileURLToPath as aO}from"node:url";function Cp(t,e){return[new URL(`../../assets/${t}`,e),new URL(`./assets/${t}`,e),new URL(`../assets/${t}`,e)].map(n=>aO(n))}function pa(t,e,n,i={}){let r=i.baseUrl??n,o=i.exists??sO,s="envPath"in i?i.envPath:process.env[e];if(s&&o(s))return s;let a=Cp(t,r);for(let u of a)if(o(u))return u;throw new Error(`model '${t}' not found. Tried: ${a.join(", ")}. Set ${e} to override.`)}var Ap=v(()=>{"use strict"});function zp(t={}){return pa(vx,yx,import.meta.url,t)}var vx,yx,Np=v(()=>{"use strict";Ap();vx="silero_vad.onnx",yx="JARVIS_SILERO_VAD_MODEL_PATH"});var vn,Ai,_x,_r,Rp=v(()=>{"use strict";Pp();Np();vn=512,Ai=64,_x=256,_r=class{modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;pending=new Int16Array(vn);pendingLen=0;state=new Float32Array(_x);context=new Float32Array(Ai);chain=Promise.resolve();constructor(e={}){this.modelPath=e.modelPath}process(e){if(this.disposed)return Promise.reject(new Error("SileroVadRunner is disposed"));let n=this.chain.then(()=>this.runWindows(e));return this.chain=n.then(()=>{},()=>{}),n}reset(){this.chain=this.chain.then(()=>{this.pendingLen=0,this.state=new Float32Array(_x),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 n=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let r=[],o=0;for(;;){let s=Math.min(vn-this.pendingLen,e.length-o);if(s>0&&(this.pending.set(e.subarray(o,o+s),this.pendingLen),this.pendingLen+=s,o+=s),this.pendingLen<vn)break;this.pendingLen=0,r.push(await this.inferWindow(n,i))}return r}async inferWindow(e,n){let i=new Float32Array(Ai+vn);i.set(this.context,0);for(let a=0;a<vn;a++)i[Ai+a]=this.pending[a]/32768;let r=await e.run({input:new n.Tensor("float32",i,[1,i.length]),state:new n.Tensor("float32",this.state,[2,1,128]),sr:new n.Tensor("int64",BigInt64Array.from([16000n]),[])});if(this.disposed)throw new Error("SileroVadRunner is disposed");let o=r[e.outputNames[0]].data;this.state=r[e.outputNames[1]].data,this.context.set(i.subarray(i.length-Ai));let s=o[0];if(!Number.isFinite(s))throw new Error("silero vad produced a non-finite output");return s<0?0:s>1?1:s}ensureSession(){return this.sessionPromise?this.sessionPromise:(this.sessionPromise=this.loadSession(),this.sessionPromise)}async loadSession(){let e=await fa();this.ort=e,ha(e);let n=this.modelPath??zp(),i=await e.InferenceSession.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SileroVadRunner is disposed");return this.session=i,i}}});function uO(t){let e=1;for(;e<t;)e<<=1;return e}var Dp,ma,bx=v(()=>{"use strict";Dp=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 n=Math.log2(e);this.rev=new Uint32Array(e);for(let r=0;r<e;r++){let o=0;for(let s=0;s<n;s++)o|=(r>>s&1)<<n-1-s;this.rev[r]=o}let i=e>>1;this.cos=new Float64Array(i),this.sin=new Float64Array(i);for(let r=0;r<i;r++){let o=2*Math.PI*r/e;this.cos[r]=Math.cos(o),this.sin[r]=Math.sin(o)}}transform(e,n,i){let r=this.size,o=this.rev;for(let s=0;s<r;s++){let a=o[s];if(a>s){let u=e[s];e[s]=e[a],e[a]=u;let c=n[s];n[s]=n[a],n[a]=c}}for(let s=2;s<=r;s<<=1){let a=s>>1,u=r/s;for(let c=0;c<r;c+=s)for(let l=0;l<a;l++){let d=l*u,f=this.cos[d],h=i?this.sin[d]:-this.sin[d],p=c+l,_=p+a,S=e[_]*f-n[_]*h,k=e[_]*h+n[_]*f;e[_]=e[p]-S,n[_]=n[p]-k,e[p]+=S,n[p]+=k}}if(i){let s=1/r;for(let a=0;a<r;a++)e[a]*=s,n[a]*=s}}};ma=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=uO(2*e-1),this.fft=new Dp(this.m),this.chirpCos=new Float64Array(e),this.chirpSin=new Float64Array(e);for(let n=0;n<e;n++){let i=n*n%(2*e),r=Math.PI*i/e;this.chirpCos[n]=Math.cos(r),this.chirpSin[n]=Math.sin(r)}this.bRe=new Float64Array(this.m),this.bIm=new Float64Array(this.m);for(let n=0;n<e;n++){let i=this.chirpCos[n],r=this.chirpSin[n];this.bRe[n]=i,this.bIm[n]=r,n!==0&&(this.bRe[this.m-n]=i,this.bIm[this.m-n]=r)}this.fft.transform(this.bRe,this.bIm,!1),this.aRe=new Float64Array(this.m),this.aIm=new Float64Array(this.m)}computePower(e,n){let{n:i,m:r,aRe:o,aIm:s}=this;o.fill(0),s.fill(0);for(let a=0;a<i;a++){let u=e[a];o[a]=u*this.chirpCos[a],s[a]=-u*this.chirpSin[a]}this.fft.transform(o,s,!1);for(let a=0;a<r;a++){let u=o[a],c=s[a],l=this.bRe[a],d=this.bIm[a];o[a]=u*l-c*d,s[a]=u*d+c*l}this.fft.transform(o,s,!0);for(let a=0;a<this.bins;a++){let u=o[a],c=s[a];n[a]=u*u+c*c}}}});function wx(t){let i=27/Math.log(6.4);return t>=1e3?15+Math.log(t/1e3)*i:3*t/200}function dO(t){let i=Math.log(6.4)/27;return t>=15?1e3*Math.exp(i*(t-15)):200*t/3}function Sx(t,e,n){let i=new Float64Array(n),r=n>1?(e-t)/(n-1):0;for(let o=0;o<n;o++)i[o]=t+o*r;return n>1&&(i[n-1]=e),i}function fO(){let t=wx(0),e=wx(Lp/2),n=Sx(t,e,St+2),i=new Float64Array(St+2);for(let a=0;a<n.length;a++)i[a]=dO(n[a]);let r=Sx(0,Lp/2,zi),o=new Float64Array(St+1);for(let a=0;a<St+1;a++)o[a]=i[a+1]-i[a];let s=[];for(let a=0;a<St;a++){let u=2/(i[a+2]-i[a]),c=new Float64Array(zi),l=zi,d=0;for(let f=0;f<zi;f++){let h=-(i[a]-r[f])/o[a],p=(i[a+2]-r[f])/o[a+1],_=Math.max(0,Math.min(h,p))*u;c[f]=_,_>0&&(f<l&&(l=f),d=f+1)}l>d&&(l=d=0),s.push({lo:l,hi:d,weights:c.slice(l,d)})}return s}function hO(){let t=new Float64Array(ut);for(let e=0;e<ut;e++)t[e]=.5-.5*Math.cos(2*Math.PI*e/ut);return t}var Lp,ut,cO,St,zi,$x,lO,xx,Ue,br,Up,Ni,ga=v(()=>{"use strict";bx();Lp=16e3,ut=400,cO=160,St=80,zi=(ut>>1)+1,$x=1e-10,lO=1e-7,xx=32768,Ue=Lp*8,br=800,Up=St;Ni=class{hann=hO();filters=fO();spectrum=new ma(ut);padded=new Float64Array(Ue+ut);frame=new Float64Array(ut);power=new Float64Array(zi);logBuf=new Float64Array(St*br);fromPcm16(e){return this.window(e),this.normalize(),this.reflectPad(),this.melSpectrogram()}window(e){let n=this.padded,i=ut/2,r=e.length;if(r>=Ue){let o=r-Ue;for(let s=0;s<Ue;s++)n[i+s]=e[o+s]/xx}else{let o=Ue-r;for(let s=0;s<o;s++)n[i+s]=0;for(let s=0;s<r;s++)n[i+o+s]=e[s]/xx}}normalize(){let e=this.padded,n=ut/2,i=Ue,r=0;for(let a=0;a<i;a++)r+=e[n+a];r/=i;let o=0;for(let a=0;a<i;a++){let u=e[n+a]-r;o+=u*u}o/=i;let s=1/Math.sqrt(o+lO);for(let a=0;a<i;a++)e[n+a]=(e[n+a]-r)*s}reflectPad(){let e=this.padded,n=ut/2,i=Ue;for(let r=0;r<n;r++)e[r]=e[n+(n-r)],e[n+i+r]=e[n+(i-2-r)]}melSpectrogram(){let{padded:e,frame:n,power:i,hann:r,filters:o,logBuf:s}=this;for(let l=0;l<br;l++){let d=l*cO;for(let f=0;f<ut;f++)n[f]=e[d+f]*r[f];this.spectrum.computePower(n,i);for(let f=0;f<St;f++){let{lo:h,hi:p,weights:_}=o[f],S=0;for(let k=h;k<p;k++)S+=_[k-h]*i[k];s[f*br+l]=Math.log10(S<$x?$x:S)}}let a=-1/0;for(let l of s)l>a&&(a=l);let u=a-8,c=new Float32Array(St*br);for(let l=0;l<s.length;l++){let d=s[l]<u?u:s[l];c[l]=(d+4)/4}return c}}});function pO(t){return t.toLowerCase().replace(/[.,!?;:]+$/g,"").trim()}function jp(t,e){return e.some(n=>Ix(t,n))}function Ix(t,e){if(!t.endsWith(e))return!1;let n=t.length-e.length-1;return n<0||t[n]===" "}function mO(t,e){let n=gO(t);return n===""?null:e.find(i=>vO(n,i))??null}function gO(t){let e=/^.*[.!?\u3002\uFF01\uFF1F]\s+/s.exec(t);return(e?t.slice(e[0].length):t).trim()}function vO(t,e){for(let n=t.indexOf(e);n!==-1;n=t.indexOf(e,n+1)){let i=n===0||!kx(t[n-1]),r=n+e.length===t.length||!kx(t[n+e.length]);if(i&&r)return!0}return!1}function kx(t){return/[a-z0-9']/.test(t)}var va,Mp,Ri,Fp=v(()=>{"use strict";Ti();Ti();va={silenceEnergyThreshold:na,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"]},Mp="semantic",Ri=class{clock;config;classifier;telemetry=null;phase="listening";inSilence=!1;silenceStartedAt=null;firstSpeechAt=null;budgetOwner="baseline";armedBudgetMs=null;lastRawPartial="";lastNormPartial="";strongHoldCue=null;held=!1;heldLadderStep=0;heldCeilingDeadlineAtMs=null;commitCb;silenceTimer=null;graceTimer=null;stopTimer=null;ceilingTimer=null;constructor(e,n={},i){this.clock=e,this.config={...va,...n},this.classifier=i??new Ii(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=pO(e),jp(this.lastNormPartial,this.config.commitCues)){this.commit("lexical");return}let n=this.strongHoldCue;if(this.strongHoldCue=mO(this.lastNormPartial,this.config.strongHoldCues),this.strongHoldCue!==null){if(this.strongHoldCue!==n){this.telemetry?.strongHoldRecognized(this.strongHoldCue),this.held||this.enterHeld(this.strongHoldCue);return}if(this.held)return;if(Ix(this.lastNormPartial,this.strongHoldCue)){this.enterHeld(this.strongHoldCue);return}this.holdFloor();return}if(jp(this.lastNormPartial,this.config.weakHoldCues)){if(this.held)return;this.holdFloor()}}onCommit(e){this.commitCb=e}attachTelemetry(e){this.telemetry=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,n="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=n),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:jp(this.lastNormPartial,this.config.commitCues)}enterHeld(e){if(this.held)return;let n=this.clock.now();this.heldCeilingDeadlineAtMs??=n+this.config.heldCeilingMs;let i=this.heldCeilingDeadlineAtMs-n;if(!(i<=0&&e===Mp)){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 Ex,Di,Vp=v(()=>{"use strict";ga();Fp();Ex={...va,commitThreshold:.65,holdThreshold:.35},Di=class extends Ri{smartConfig;inference;buffer=new Int16Array(Ue*2);bufferLen=0;silenceEpoch=0;degraded=!1;smartDisposed=!1;semantics;evaluatedEpoch=0;evaluationAbort=new AbortController;constructor(e,n,i={},r,o){super(e,i,r),this.smartConfig={...Ex,...i},this.inference=n,o&&(this.semantics=o)}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,n=this.snapshotBuffer();this.runInference(n,e)}async runInference(e,n){let i=this.clock.now(),r;try{r=await this.inference.infer(e)}catch(s){let a=this.degraded;this.degraded=!0,!a&&!this.smartDisposed&&this.telemetry?.smartTurnDegraded(this.clock.now()-i,s);return}let o=this.clock.now()-i;if(this.smartDisposed||n!==this.silenceEpoch||!this.canRefineBudget()){this.telemetry?.smartTurnResolved(r,o,"stale");return}r>=this.smartConfig.commitThreshold?(this.telemetry?.smartTurnResolved(r,o,"shorten"),this.rearmSilence(this.smartConfig.shortSilenceMs),this.maybeEvaluateTurn(n,"shorten")):r<=this.smartConfig.holdThreshold?(this.telemetry?.smartTurnResolved(r,o,"extend"),this.rearmSilence(this.smartConfig.longSilenceMs)):(this.telemetry?.smartTurnResolved(r,o,"inconclusive"),this.maybeEvaluateTurn(n,"inconclusive"))}maybeEvaluateTurn(e,n){if(!this.semantics||this.evaluatedEpoch===e||this.isHeld())return;let i=this.livePartial();i!==""&&(this.evaluatedEpoch=e,this.runEvaluation(this.semantics,i,e,n))}async runEvaluation(e,n,i,r){this.telemetry?.evaluatorFired?.(r);let o=this.clock.now(),s;try{s=await e.evaluator.evaluate({recentTurns:e.recentTurns(),livePartial:n},this.evaluationAbort.signal)}catch(u){this.smartDisposed||this.telemetry?.evaluatorFailed?.(this.clock.now()-o,u);return}let a=this.clock.now()-o;if(this.smartDisposed||i!==this.silenceEpoch||!this.canApplySemanticVerdict()){this.telemetry?.evaluatorResolved?.(s.verdict,s.confidence,a,"stale");return}if(this.telemetry?.evaluatorResolved?.(s.verdict,s.confidence,a,"applied"),s.verdict==="done")this.rearmSilence(this.smartConfig.shortSilenceMs,"semantic");else if(s.verdict==="mid_thought")this.rearmSilence(this.smartConfig.longSilenceMs,"semantic");else{if(this.heldAllowanceExhausted())return;this.enterHeld(Mp),this.resumeHeldSilence()}}appendToBuffer(e){let n=e.byteLength>>1;if(n===0)return;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n>Ue?n-Ue:0,o=n-r;if(this.bufferLen+o>this.buffer.length){let s=Math.min(this.bufferLen,Ue);this.buffer.copyWithin(0,this.bufferLen-s,this.bufferLen),this.bufferLen=s}for(let s=r;s<n;s++)this.buffer[this.bufferLen++]=i.getInt16(s*2,!0)}snapshotBuffer(){let e=Math.max(0,this.bufferLen-Ue);return this.buffer.slice(e,this.bufferLen)}}});function Zp(t={}){return pa(Tx,Ox,import.meta.url,t)}var Tx,Ox,Bp=v(()=>{"use strict";Ap();Tx="smart-turn-v3.1-cpu.onnx",Ox="JARVIS_SMART_TURN_MODEL_PATH"});var Li,Gp=v(()=>{"use strict";ga();Pp();Bp();Li=class{logMel;modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;constructor(e={}){this.logMel=e.logMel??new Ni,this.modelPath=e.modelPath}async infer(e){if(this.disposed)throw new Error("SmartTurnRunner is disposed");let n=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let r=this.logMel.fromPcm16(e),o=new i.Tensor("float32",r,[1,Up,br]),s=await n.run({input_features:o});if(this.disposed)throw new Error("SmartTurnRunner is disposed");let a=n.outputNames[0],c=s[a].data[0];if(!Number.isFinite(c))throw new Error("smart-turn produced a non-finite output");return c<0?0:c>1?1:c}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 fa();this.ort=e,ha(e);let n=this.modelPath??Zp(),i=await e.InferenceSession.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SmartTurnRunner is disposed");return this.session=i,i}}});function SO(t){let e=[];if(t.recentTurns.length>0){e.push("Recent conversation:");for(let n of t.recentTurns)e.push(`${n.role==="assistant"?"Assistant":"User"}: ${n.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(`
79
79
  `)}function kO(t){let e=Wp(t)?.content,n=(Array.isArray(e)?e:[]).map(l=>Wp(l)).filter(l=>l?.type==="text").map(l=>typeof l?.text=="string"?l.text:"").join(""),i=Px+n;i.includes("}")||(i+="}");let r=i.indexOf("{"),o=i.lastIndexOf("}");if(r===-1||o<=r)throw new Kt("turn evaluator reply carried no JSON object");let s;try{s=JSON.parse(i.slice(r,o+1))}catch{throw new Kt("turn evaluator reply was not valid JSON")}let a=Wp(s),u=a?.verdict;if(typeof u!="string"||!xO.includes(u))throw new Kt("turn evaluator reply carried an unknown verdict");let c=a?.confidence;if(typeof c!="number"||!Number.isFinite(c)||c<0||c>1)throw new Kt("turn evaluator confidence missing or out of range");return{verdict:u,confidence:c}}function Wp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}var yO,_O,bO,Px,$O,xO,wO,Kt,ya,Cx=v(()=>{"use strict";yO="claude-haiku-4-5-20251001",_O="https://api.anthropic.com/v1/messages",bO="2023-06-01",Px='{"verdict":"',$O=["}"],xO=["done","mid_thought","hold_floor"],wO=`You are the semantic turn evaluator inside a real-time voice assistant's
80
80
  turn-taking system. The user is speaking; a streaming ASR produces a live
81
81
  partial transcript. Your only job is to judge whether the user's turn reads
@@ -117,25 +117,25 @@ Rules:
117
117
  Output exactly one line of strict JSON and nothing else:
118
118
  {"verdict":"done"|"mid_thought"|"hold_floor","confidence":<number 0..1>}
119
119
  confidence is your certainty in the verdict.
120
- `,Kt=class extends Error{status;constructor(e,n){super(e),this.status=n,this.name="TurnEvaluatorError"}},ya=class{key;fetchImpl;timeoutMs;constructor(e,n=fetch,i=2e3){this.key=e,this.fetchImpl=n,this.timeoutMs=i}async evaluate(e,n){let i={model:yO,max_tokens:64,temperature:0,stop_sequences:$O,system:wO,messages:[{role:"user",content:SO(e)},{role:"assistant",content:Px}]},r=await this.fetchImpl(_O,{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":bO,"content-type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.any([n,AbortSignal.timeout(this.timeoutMs)])});if(!r.ok)throw new Kt(`turn evaluator request failed (HTTP ${r.status})`,r.status);let o;try{o=await r.json()}catch{throw new Kt("turn evaluator response body was not JSON")}return kO(o)}}});var Ax,qp,Hp=v(()=>{"use strict";Ax="21m00Tcm4TlvDq8ikWAM",qp={id:"jarvis-primary",engineVoice:{"elevenlabs-flash":{kind:"preset",voiceId:Ax}}}});var _a,zx=v(()=>{"use strict";De();_a=class{turnId;openedAtMs;log;terminal=!1;heldOpen=!1;decider=null;silenceOnsetAtMs=null;commitAtMs=null;asrFinalAtMs=null;transcriptLength=null;firstDeltaAtMs=null;firstAudioAtMs=null;constructor(e,n,i=q){this.turnId=e,this.openedAtMs=n,this.log=i}endpointerCommitted(e,n){this.decider===null&&(this.decider=e,this.silenceOnsetAtMs=n)}smartTurnResolved(e,n,i){this.log.debug("smart-turn P(complete)",{turnId:this.turnId,probability:e,inferenceMs:n,outcome:i})}smartTurnDegraded(e,n){this.log.debug("smart-turn DEGRADED to baseline - inference failed; this turn endpoints on baseline timers only",{turnId:this.turnId,inferenceMs:e,error:n instanceof Error?n.message:String(n)})}strongHoldRecognized(e){this.log.debug("lexical STRONG hold recognized - completeness vetoed, silence budget biases long",{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,n,i,r){this.log.debug("semantic evaluator resolved",{turnId:this.turnId,verdict:e,confidence:n,latencyMs:i,outcome:r})}evaluatorFailed(e,n){this.log.debug("semantic evaluator failed - no signal; this episode endpoints as armed",{turnId:this.turnId,latencyMs:e,error:n instanceof Error?n.message:String(n)})}committed(e,n){this.commitAtMs===null&&(n==="ptt"&&this.heldOpen&&this.heldExited("ptt"),this.commitAtMs=e,n==="ptt"&&(this.decider??="ptt"))}asrFinalResolved(e,n){this.asrFinalAtMs===null&&(this.asrFinalAtMs=e,this.transcriptLength=n)}firstReasonerDelta(e){this.firstDeltaAtMs??=e}firstTtsAudio(e){this.firstAudioAtMs??=e}completed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn summary",{turnId:this.turnId,decider:this.decider,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}))}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,n){return e===null||n===null?null:n-e}}});var Nx,Rx,ba,Dx=v(()=>{"use strict";zx();Nx=16e3,Rx="pcm_s16le",ba=class{deps;asrStream;ttsStream=null;reasonAbort=new AbortController;phase="capturing";settled=!1;finalizing=!1;lastFrameAtMs;timeline;constructor(e){this.deps=e,this.lastFrameAtMs=e.startMs,this.timeline=new _a(e.turnId,e.clock.now()),e.controller.attachTelemetry?.(this.timeline),this.asrStream=e.asrEngine.open({sampleRate:Nx,encoding:Rx,emitPartials:!0}),this.asrStream.onTranscript(n=>this.handleTranscript(n)),this.asrStream.onError(n=>this.finishError("turn_failed",n)),e.controller.onCommit(()=>this.finalize(this.lastFrameAtMs,"controller")),e.emit({type:"state",turnId:e.turnId,state:"processing"})}pushFrame(e,n){this.phase!=="capturing"||this.settled||(this.lastFrameAtMs=n,this.asrStream.pushAudio(e),this.deps.controller.onAudioFrame(e))}endAudio(e){this.finalize(e,"ptt")}cancel(){this.settled||(this.settled=!0,this.phase="cancelled",this.deps.controller.dispose(),this.reasonAbort.abort(),this.asrStream.abort(),this.ttsStream?.cancel(),this.deps.onComplete())}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))}finalize(e,n){this.phase!=="capturing"||this.finalizing||this.settled||(this.finalizing=!0,this.timeline.committed(this.deps.clock.now(),n),this.deps.controller.dispose(),this.finalizeAndRespond(e))}async finalizeAndRespond(e){let n;try{n=await this.asrStream.end()}catch(r){if(this.settled)return;this.finishError("turn_failed",r);return}if(this.settled)return;if(this.timeline.asrFinalResolved(this.deps.clock.now(),n.text.length),n.text.trim()===""){this.finishBlank();return}this.phase="responding";let i=this.buildUserTurn(n.text,e);this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:i,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"});try{await this.respond(i.text)}catch(r){if(this.settled)return;this.finishError("turn_failed",r);return}this.settled||this.finishDone()}async respond(e){let n=!1,i=!1,r=this.deps.ttsEngine.speak({voice:this.deps.voice,sampleRate:Nx,encoding:Rx});this.ttsStream=r,r.onAudio(s=>{this.settled||(i||(i=!0,this.timeline.firstTtsAudio(this.deps.clock.now())),this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:s}))}),r.onError(s=>this.finishError("turn_failed",s));let o=this.deps.reasoner.run(e,this.reasonAbort.signal,{register:"voice"});for await(let s of o){if(this.settled)return;n||(n=!0,this.timeline.firstReasonerDelta(this.deps.clock.now())),this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:s.text});for(let a of this.deps.segmenter.push(s.text))r.pushText(a)}if(!this.settled){for(let s of this.deps.segmenter.flush())r.pushText(s);await r.end()}}finishBlank(){this.settled||(this.settled=!0,this.timeline.blank(this.deps.clock.now()),this.deps.onComplete())}finishDone(){this.settled||(this.settled=!0,this.timeline.completed(this.deps.clock.now()),this.deps.emit({type:"response.done",turnId:this.deps.turnId}),this.deps.onComplete())}finishError(e,n){this.settled||(this.settled=!0,this.deps.controller.dispose(),this.reasonAbort.abort(),this.ttsStream?.cancel(),this.deps.emit({type:"error",turnId:this.deps.turnId,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId},reason:e,message:n instanceof Error?n.message:String(n)}),this.deps.onComplete())}buildUserTurn(e,n){return{source:"voice",turnId:this.deps.turnId,sessionId:this.deps.sessionId,deviceId:this.deps.deviceId,text:e,startMs:this.deps.startMs,endMs:n,...this.deps.projectId!==void 0&&{projectId:this.deps.projectId}}}}});import{randomUUID as Jp}from"node:crypto";var IO,yn,Ui,$a,Lx=v(()=>{"use strict";xi();tp();Bb();rp();np();Ti();Rp();Vp();Gp();Cx();Hp();Dx();IO=6,yn=class extends Error{constructor(e){super(e),this.name="ReasonerUnavailableError"}},Ui=class extends Error{constructor(e){super(e),this.name="VoiceUnavailableError"}},$a=class{deps;sessionId;deviceId;projectId;queue=new ra;closed=!1;eventsConsumed=!1;inFlight=!1;reasoner=null;reasonerRoute=null;turnAbort=null;voiceTurn=null;voiceTurnFailed=!1;voiceEngines=null;clock;newTurnController;newSmartTurnInference;newFrameClassifier;newTurnEvaluator;newSegmenter;voiceIdentity;smartTurnInference=null;frameClassifier=null;turnEvaluator=void 0;constructor(e,n,i){this.deps=i,this.sessionId=e,this.deviceId=n.deviceId,this.projectId=n.projectId,this.clock=i.clock??new ki,this.newSmartTurnInference=i.createSmartTurnInference??(()=>new Li),this.newFrameClassifier=i.createFrameClassifier??(()=>new Ei(new _r)),this.newTurnEvaluator=i.createTurnEvaluator??(r=>new ya(r)),this.newTurnController=i.createTurnController??(r=>{let o=this.ensureFrameClassifier();return o.reset?.(),new Di(r,this.ensureSmartTurnInference(),{},o,this.semanticHook())}),this.newSegmenter=i.createSegmenter??(()=>new Si),this.voiceIdentity=i.voiceIdentity??qp,this.emit({type:"session.ready"})}async send(e){let{commandId:n}=e;if(this.closed)throw new Le(n,"closed");if(e.sessionId!==this.sessionId)throw new Le(n,"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"session.close":return this.close();case"approval.resolve":throw new Le(n,"unsupported");default:throw new Le(n,"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){this.closed=!0,this.turnAbort?.abort(),this.voiceTurn?.cancel();let e=this.smartTurnInference;this.smartTurnInference=null;let n=this.frameClassifier;this.frameClassifier=null;let i=this.turnEvaluator;this.turnEvaluator=null,this.queue.close();let r=[];if(e&&r.push(e.dispose().catch(()=>{})),n?.dispose&&r.push(n.dispose().catch(()=>{})),i?.dispose&&r.push(i.dispose().catch(()=>{})),r.length>0)return Promise.all(r).then(()=>{})}return Promise.resolve()}acceptTextInput(e){if(e.text.trim().length===0)throw new Le(e.commandId,"invalid","input.text requires non-empty text");if(this.inFlight)throw new Le(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=Jp();this.emit({type:"turn.accepted",turnId:n,clientTurnId:e.clientTurnId,source:"text",commandId:e.commandId}),this.emit({type:"turn.final",turnId:n,turn:this.toTextUserTurn(n,e),commandId:e.commandId}),this.runTextTurn(n,e)}async runTextTurn(e,n){let i=new AbortController;this.turnAbort=i;try{let r=this.ensureReasoner();this.emit({type:"state",turnId:e,state:"responding"});for await(let o of r.run(n.text,i.signal))this.emit({type:"response.delta",turnId:e,text:o.text});this.emit({type:"response.done",turnId:e})}catch(r){let o=r instanceof yn?"no_text_route":"turn_failed";this.emit({type:"error",turnId:e,commandId:n.commandId,reason:o,message:r instanceof Error?r.message:String(r)})}finally{this.inFlight=!1,this.turnAbort=null}}acceptAudioFrame(e){if(this.voiceTurn){this.voiceTurn.pushFrame(e.audio,e.atMs);return}if(this.voiceTurnFailed)return;if(this.inFlight)throw new Le(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=Jp();this.emit({type:"turn.accepted",turnId:n,clientTurnId:e.clientTurnId,source:"voice",commandId:e.commandId});let i=this.resolveVoicePipeline(n,e.commandId);if(!i){this.voiceTurnFailed=!0;return}this.voiceTurn=new ba({turnId:n,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:this.voiceIdentity,reasoner:i.reasoner,controller:this.newTurnController(this.clock),segmenter:this.newSegmenter(),clock:this.clock,emit:r=>this.emit(r),onComplete:()=>this.completeVoiceTurn()}),this.smartTurnInference?.prewarm?.(),this.frameClassifier?.prewarm?.(),this.voiceTurn.pushFrame(e.audio,e.atMs)}endAudioInput(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}this.voiceTurn?.endAudio(e.atMs)}cancelTurn(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}this.voiceTurn?.cancel()}completeVoiceTurn(){this.voiceTurn=null,this.inFlight=!1}resetVoiceFailure(){this.voiceTurnFailed=!1}resolveVoicePipeline(e,n){let i;try{i=this.ensureVoiceEngines()}catch(o){return this.emitTurnError(e,n,"no_voice_route",o),null}let r;try{r=this.ensureReasoner()}catch(o){let s=o instanceof yn?"no_text_route":"turn_failed";return this.emitTurnError(e,n,s,o),null}return{engines:i,reasoner:r}}ensureVoiceEngines(){if(this.voiceEngines)return this.voiceEngines;if(!this.deps.voiceRegistry)throw new Ui("voice is not available in this core build");let e=this.deps.configService.resolved(),n=e.routes?.stt,i=e.routes?.tts;if(!n||!i)throw new Ui("no voice route configured - run 'jarvis init' to set routes.stt and routes.tts");let r=e.secrets?.[n.provider],o=e.secrets?.[i.provider];if(!r||!o){let u=r?i.provider:n.provider;throw new Ui(`no API key for voice provider '${u}' - run 'jarvis init' to add it`)}let s=this.deps.voiceRegistry.asrEngine({provider:n.provider,model:n.model},r),a=this.deps.voiceRegistry.ttsEngine({provider:i.provider,model:i.model},o);return this.voiceEngines={asrEngine:s,ttsEngine:a},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 n=this.reasonerRoute;this.turnEvaluator=n?.provider==="anthropic"?this.newTurnEvaluator(n.key):null}return this.turnEvaluator===null?void 0:{evaluator:this.turnEvaluator,recentTurns:()=>{let n=[];for(let i of this.reasoner?.historySnapshot()??[])(i.role==="user"||i.role==="assistant")&&n.push({role:i.role,text:i.content});return n.slice(-IO)}}}ensureReasoner(){if(this.reasoner)return this.reasoner;let e=this.deps.configService.resolved(),n=e.routes?.text;if(!n)throw new yn("no text model is configured - run 'jarvis init' to set routes.text");let i=e.secrets?.[n.provider];if(!i)throw new yn(`no API key for text provider '${n.provider}' - run 'jarvis init' to add it`);let r=this.deps.registry.textAdapter({provider:n.provider,model:n.model},i);return this.reasoner=new wi(r,n.model,this.deps.systemPrompt),this.reasonerRoute={provider:n.provider,key:i},this.reasoner}toTextUserTurn(e,n){return{source:"text",turnId:e,sessionId:this.sessionId,deviceId:this.deviceId,text:n.text,atMs:n.atMs,...this.projectId!==void 0&&{projectId:this.projectId}}}emitTurnError(e,n,i,r){this.emit({type:"error",turnId:e,commandId:n,reason:i,message:r instanceof Error?r.message:String(r)}),this.inFlight=!1}emit(e){this.queue.push({...e,sessionId:this.sessionId,eventId:Jp(),atMs:Date.now()})}}});function xa(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function Kp(t){return typeof t=="string"?t:""}function wa(t){let e=t.message_type;return typeof e=="string"&&(EO.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function Ux(t){return Buffer.from(t).toString("base64")}function jx(t){return new Uint8Array(Buffer.from(t,"base64"))}function Sa(t,e){return new Error(`${t} connection error: ${e.message}`)}var EO,Yp=v(()=>{"use strict";EO=new Set(["error","auth_error","quota_exceeded","rate_limited"])});function TO(t,e,n){let i=new URL(t);i.searchParams.set("model_id",e),i.searchParams.set("audio_format",OO(n)),i.searchParams.set("commit_strategy","manual"),n.language&&i.searchParams.set("language_code",n.language);for(let r of n.biasTerms??[])i.searchParams.append("keyterms",r);return i.toString()}function OO(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var Mx,ji,Xp,Qp=v(()=>{"use strict";Yp();Mx="wss://api.elevenlabs.io/v1/speech-to-text/realtime",ji=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-scribe";constructor(e,n,i,r=Mx){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpoint=r}open(e){return new Xp(this.apiKey,this.socketFactory,this.model,this.endpoint,e)}},Xp=class{opts;socket;opened=!1;aborted=!1;closed=!1;pending=[];committed=[];transcriptCb;errorCb;endPending=null;commitRequested=!1;constructor(e,n,i,r,o){this.opts=o,this.socket=n(TO(r,i,o),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(s=>this.handleMessage(s)),this.socket.onError(s=>this.handleError(s)),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,n)=>{this.endPending={resolve:e,reject:n},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 n=xa(e);if(!n)return;let i=wa(n);if(i){this.handleError(new Error(`stream error (${i})`));return}let r=n.message_type;if(r==="partial_transcript"){this.opts.emitPartials&&this.transcriptCb?.({text:Kp(n.text),isFinal:!1,startMs:0});return}if(r==="committed_transcript"||r==="committed_transcript_with_timestamps"){let o=Kp(n.text);o.length>0&&this.committed.push(o),this.endPending&&this.resolveEnd()}}handleError(e){if(this.closed)return;let n=Sa("ElevenLabs ASR",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(n)}this.errorCb?.(n),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs ASR connection closed unexpectedly");if(this.endPending){let{reject:n}=this.endPending;this.endPending=null,n(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:n}=this.endPending;this.endPending=null,this.teardown(),n(e)}sendChunk(e,n){this.socket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:Ux(e),commit:n,sample_rate:this.opts.sampleRate}))}sendCommit(){this.sendChunk(new Uint8Array(0),!0)}teardown(){this.closed||(this.closed=!0,this.socket.close())}}});import{randomUUID as PO}from"node:crypto";function AO(t,e){let n=t.engineVoice[e];if(!n)throw new Error(`voice '${t.id}' has no '${e}' engineVoice mapping`);if(n.kind!=="preset")throw new Error(`the ${e} adapter needs a preset voiceId for '${t.id}', got kind '${n.kind}'`);return n.voiceId}function zO(t,e,n,i){let r=new URL(t.replace("{voice_id}",encodeURIComponent(e)));return r.searchParams.set("model_id",n),r.searchParams.set("output_format",NO(i)),r.searchParams.set("auto_mode","true"),r.toString()}function NO(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var Fx,CO,Mi,em,tm=v(()=>{"use strict";Yp();Fx="wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/multi-stream-input",CO={stability:.5,similarity_boost:.75,use_speaker_boost:!0},Mi=class{apiKey;socketFactory;model;endpointTemplate;id="elevenlabs-flash";constructor(e,n,i,r=Fx){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpointTemplate=r}speak(e){return new em(this.apiKey,this.socketFactory,this.model,this.endpointTemplate,this.id,e)}},em=class{socket;contextId=PO();opened=!1;cancelled=!1;closed=!1;endRequested=!1;closeContextSent=!1;pending=[];audioCb;errorCb;endPending=null;constructor(e,n,i,r,o,s){let a=AO(s.voice,o);this.socket=n(zO(r,a,i,s),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(u=>this.handleMessage(u)),this.socket.onError(u=>this.handleError(u)),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,n)=>{this.endPending={resolve:e,reject:n},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 n=xa(e);if(!n)return;let i=wa(n);if(i){this.handleError(new Error(`stream error (${i})`));return}typeof n.audio=="string"&&n.audio.length>0&&this.audioCb?.(jx(n.audio)),(n.isFinal===!0||n.is_final===!0)&&this.resolveEnd()}handleError(e){if(this.closed)return;let n=Sa("ElevenLabs TTS",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(n)}this.errorCb?.(n),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs TTS connection closed unexpectedly");if(this.endPending){let{reject:n}=this.endPending;this.endPending=null,n(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:CO,context_id:this.contextId}))}sendText(e){let n=e.endsWith(" ")?e:`${e} `;this.socket.send(JSON.stringify({text:n,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())}}});var kt=z((r2,Bx)=>{"use strict";var Vx=["nodebuffer","arraybuffer","fragments"],Zx=typeof Blob<"u";Zx&&Vx.push("blob");Bx.exports={BINARY_TYPES:Vx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Fi=z((n2,ka)=>{"use strict";var{EMPTY_BUFFER:RO}=kt(),rm=Buffer[Symbol.species];function DO(t,e){if(t.length===0)return RO;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let r=0;r<t.length;r++){let o=t[r];n.set(o,i),i+=o.length}return i<e?new rm(n.buffer,n.byteOffset,i):n}function Gx(t,e,n,i,r){for(let o=0;o<r;o++)n[i+o]=t[o]^e[o&3]}function Wx(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function LO(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function nm(t){if(nm.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new rm(t):ArrayBuffer.isView(t)?e=new rm(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),nm.readOnly=!1),e}ka.exports={concat:DO,mask:Gx,toArrayBuffer:LO,toBuffer:nm,unmask:Wx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ae("bufferutil");ka.exports.mask=function(e,n,i,r,o){o<48?Gx(e,n,i,r,o):t.mask(e,n,i,r,o)},ka.exports.unmask=function(e,n){e.length<32?Wx(e,n):t.unmask(e,n)}}catch{}});var Jx=z((i2,Hx)=>{"use strict";var qx=Symbol("kDone"),im=Symbol("kRun"),om=class{constructor(e){this[qx]=()=>{this.pending--,this[im]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[im]()}[im](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[qx])}}};Hx.exports=om});var $n=z((o2,Qx)=>{"use strict";var Vi=ae("zlib"),Kx=Fi(),UO=Jx(),{kStatusCode:Yx}=kt(),jO=Buffer[Symbol.species],MO=Buffer.from([0,0,255,255]),Ea=Symbol("permessage-deflate"),It=Symbol("total-length"),_n=Symbol("callback"),Yt=Symbol("buffers"),bn=Symbol("error"),Ia,sm=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ia){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ia=new UO(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[_n];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let r=n[i];if(r.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(r=r[0],i==="client_max_window_bits"){if(r!==!0){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else if(i==="server_max_window_bits"){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=r})}),e}decompress(e,n,i){Ia.add(r=>{this._decompress(e,n,(o,s)=>{r(),i(o,s)})})}compress(e,n,i){Ia.add(r=>{this._compress(e,n,(o,s)=>{r(),i(o,s)})})}_decompress(e,n,i){let r=this._isServer?"client":"server";if(!this._inflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ea]=this,this._inflate[It]=0,this._inflate[Yt]=[],this._inflate.on("error",VO),this._inflate.on("data",Xx)}this._inflate[_n]=i,this._inflate.write(e),n&&this._inflate.write(MO),this._inflate.flush(()=>{let o=this._inflate[bn];if(o){this._inflate.close(),this._inflate=null,i(o);return}let s=Kx.concat(this._inflate[Yt],this._inflate[It]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[It]=0,this._inflate[Yt]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),i(null,s)})}_compress(e,n,i){let r=this._isServer?"server":"client";if(!this._deflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[It]=0,this._deflate[Yt]=[],this._deflate.on("data",FO)}this._deflate[_n]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Kx.concat(this._deflate[Yt],this._deflate[It]);n&&(o=new jO(o.buffer,o.byteOffset,o.length-4)),this._deflate[_n]=null,this._deflate[It]=0,this._deflate[Yt]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),i(null,o)})}};Qx.exports=sm;function FO(t){this[Yt].push(t),this[It]+=t.length}function Xx(t){if(this[It]+=t.length,this[Ea]._maxPayload<1||this[It]<=this[Ea]._maxPayload){this[Yt].push(t);return}this[bn]=new RangeError("Max payload size exceeded"),this[bn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[bn][Yx]=1009,this.removeListener("data",Xx),this.reset()}function VO(t){if(this[Ea]._inflate=null,this[bn]){this[_n](this[bn]);return}t[Yx]=1007,this[_n](t)}});var xn=z((s2,Ta)=>{"use strict";var{isUtf8:ew}=ae("buffer"),{hasBlob:ZO}=kt(),BO=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function GO(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function am(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function WO(t){return ZO&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ta.exports={isBlob:WO,isValidStatusCode:GO,isValidUTF8:am,tokenChars:BO};if(ew)Ta.exports.isValidUTF8=function(t){return t.length<24?am(t):ew(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ae("utf-8-validate");Ta.exports.isValidUTF8=function(e){return e.length<32?am(e):t(e)}}catch{}});var fm=z((a2,aw)=>{"use strict";var{Writable:qO}=ae("stream"),tw=$n(),{BINARY_TYPES:HO,EMPTY_BUFFER:rw,kStatusCode:JO,kWebSocket:KO}=kt(),{concat:um,toArrayBuffer:YO,unmask:XO}=Fi(),{isValidStatusCode:QO,isValidUTF8:nw}=xn(),Oa=Buffer[Symbol.species],Qe=0,iw=1,ow=2,sw=3,cm=4,lm=5,Pa=6,dm=class extends qO{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||HO[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[KO]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Qe}_write(e,n,i){if(this._opcode===8&&this._state==Qe)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Oa(i.buffer,i.byteOffset+e,i.length-e),new Oa(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],r=n.length-e;e>=i.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),r),this._buffers[0]=new Oa(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Qe:this.getInfo(e);break;case iw:this.getPayloadLength16(e);break;case ow:this.getPayloadLength64(e);break;case sw:this.getMask();break;case cm:this.getData(e);break;case lm:case Pa:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let i=(n[0]&64)===64;if(i&&!this._extensions[tw.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=iw:this._payloadLength===127?this._state=ow:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=sw:this._state=cm}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=cm}getData(e){let n=rw;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&XO(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=lm,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[tw.extensionName].decompress(e,this._fin,(r,o)=>{if(r)return n(r);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===Qe&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Qe;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=um(i,n):this._binaryType==="arraybuffer"?r=YO(um(i,n)):this._binaryType==="blob"?r=new Blob(i):r=i,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=Qe):(this._state=Pa,setImmediate(()=>{this.emit("message",r,!0),this._state=Qe,this.startLoop(e)}))}else{let r=um(i,n);if(!this._skipUTF8Validation&&!nw(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===lm||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=Qe):(this._state=Pa,setImmediate(()=>{this.emit("message",r,!1),this._state=Qe,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,rw),this.end();else{let i=e.readUInt16BE(0);if(!QO(i)){let o=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let r=new Oa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!nw(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",i,r),this.end()}this._state=Qe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe):(this._state=Pa,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe,this.startLoop(n)}))}createError(e,n,i,r,o){this._loop=!1,this._errored=!0;let s=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[JO]=r,s}};aw.exports=dm});var mm=z((c2,lw)=>{"use strict";var{Duplex:u2}=ae("stream"),{randomFillSync:eP}=ae("crypto"),{types:{isUint8Array:tP}}=ae("util"),uw=$n(),{EMPTY_BUFFER:rP,kWebSocket:nP,NOOP:iP}=kt(),{isBlob:wn,isValidStatusCode:oP}=xn(),{mask:cw,toBuffer:$r}=Fi(),et=Symbol("kByteLength"),sP=Buffer.alloc(4),Ca=8*1024,xr,Sn=Ca,ct=0,aP=1,uP=2,hm=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=iP,this[nP]=void 0}static frame(e,n){let i,r=!1,o=2,s=!1;n.mask&&(i=n.maskBuffer||sP,n.generateMask?n.generateMask(i):(Sn===Ca&&(xr===void 0&&(xr=Buffer.alloc(Ca)),eP(xr,0,Ca),Sn=0),i[0]=xr[Sn++],i[1]=xr[Sn++],i[2]=xr[Sn++],i[3]=xr[Sn++]),s=(i[0]|i[1]|i[2]|i[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[et]!==void 0?a=n[et]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!s);let u=a;a>=65536?(o+=8,u=127):a>125&&(o+=2,u=126);let c=Buffer.allocUnsafe(r?a+o:o);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(a,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[o-4]=i[0],c[o-3]=i[1],c[o-2]=i[2],c[o-1]=i[3],s?[c,e]:r?(cw(e,i,c,o,a),[c]):(cw(e,i,e,0,a),[c,e])):[c,e]}close(e,n,i,r){let o;if(e===void 0)o=rP;else{if(typeof e!="number"||!oP(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(tP(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[et]:o.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,o,!1,s,r]):this.sendFrame(t.frame(o,s),r)}ping(e,n,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):wn(e)?(r=e.size,o=!1):(e=$r(e),r=e.length,o=$r.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[et]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};wn(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==ct?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(t.frame(e,s),i)}pong(e,n,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):wn(e)?(r=e.size,o=!1):(e=$r(e),r=e.length,o=$r.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[et]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};wn(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==ct?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(t.frame(e,s),i)}send(e,n,i){let r=this._extensions[uw.extensionName],o=n.binary?2:1,s=n.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):wn(e)?(a=e.size,u=!1):(e=$r(e),a=e.length,u=$r.readOnly),this._firstFragment?(this._firstFragment=!1,s&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=r._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let c={[et]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:u,rsv1:s};wn(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,c,i]):this.getBlobData(e,this._compress,c,i):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,c,i]):this.dispatch(e,this._compress,c,i)}getBlobData(e,n,i,r){this._bufferedBytes+=i[et],this._state=uP,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(pm,this,a,r);return}this._bufferedBytes-=i[et];let s=$r(o);n?this.dispatch(s,n,i,r):(this._state=ct,this.sendFrame(t.frame(s,i),r),this.dequeue())}).catch(o=>{process.nextTick(cP,this,o,r)})}dispatch(e,n,i,r){if(!n){this.sendFrame(t.frame(e,i),r);return}let o=this._extensions[uw.extensionName];this._bufferedBytes+=i[et],this._state=aP,o.compress(e,i.fin,(s,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");pm(this,u,r);return}this._bufferedBytes-=i[et],this._state=ct,i.readOnly=!1,this.sendFrame(t.frame(a,i),r),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][et],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][et],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};lw.exports=hm;function pm(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let r=t._queue[i],o=r[r.length-1];typeof o=="function"&&o(e)}}function cP(t,e,n){pm(t,e,n),t.onerror(e)}});var _w=z((l2,yw)=>{"use strict";var{kForOnEventAttribute:Zi,kListener:gm}=kt(),dw=Symbol("kCode"),fw=Symbol("kData"),hw=Symbol("kError"),pw=Symbol("kMessage"),mw=Symbol("kReason"),kn=Symbol("kTarget"),gw=Symbol("kType"),vw=Symbol("kWasClean"),Et=class{constructor(e){this[kn]=null,this[gw]=e}get target(){return this[kn]}get type(){return this[gw]}};Object.defineProperty(Et.prototype,"target",{enumerable:!0});Object.defineProperty(Et.prototype,"type",{enumerable:!0});var wr=class extends Et{constructor(e,n={}){super(e),this[dw]=n.code===void 0?0:n.code,this[mw]=n.reason===void 0?"":n.reason,this[vw]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[dw]}get reason(){return this[mw]}get wasClean(){return this[vw]}};Object.defineProperty(wr.prototype,"code",{enumerable:!0});Object.defineProperty(wr.prototype,"reason",{enumerable:!0});Object.defineProperty(wr.prototype,"wasClean",{enumerable:!0});var In=class extends Et{constructor(e,n={}){super(e),this[hw]=n.error===void 0?null:n.error,this[pw]=n.message===void 0?"":n.message}get error(){return this[hw]}get message(){return this[pw]}};Object.defineProperty(In.prototype,"error",{enumerable:!0});Object.defineProperty(In.prototype,"message",{enumerable:!0});var Bi=class extends Et{constructor(e,n={}){super(e),this[fw]=n.data===void 0?null:n.data}get data(){return this[fw]}};Object.defineProperty(Bi.prototype,"data",{enumerable:!0});var lP={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[Zi]&&r[gm]===e&&!r[Zi])return;let i;if(t==="message")i=function(o,s){let a=new Bi("message",{data:s?o:o.toString()});a[kn]=this,Aa(e,this,a)};else if(t==="close")i=function(o,s){let a=new wr("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[kn]=this,Aa(e,this,a)};else if(t==="error")i=function(o){let s=new In("error",{error:o,message:o.message});s[kn]=this,Aa(e,this,s)};else if(t==="open")i=function(){let o=new Et("open");o[kn]=this,Aa(e,this,o)};else return;i[Zi]=!!n[Zi],i[gm]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[gm]===e&&!n[Zi]){this.removeListener(t,n);break}}};yw.exports={CloseEvent:wr,ErrorEvent:In,Event:Et,EventTarget:lP,MessageEvent:Bi};function Aa(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var za=z((d2,bw)=>{"use strict";var{tokenChars:Gi}=xn();function pt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function dP(t){let e=Object.create(null),n=Object.create(null),i=!1,r=!1,o=!1,s,a,u=-1,c=-1,l=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),s===void 0)if(l===-1&&Gi[c]===1)u===-1&&(u=d);else if(d!==0&&(c===32||c===9))l===-1&&u!==-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(u,l);c===44?(pt(e,h,n),n=Object.create(null)):s=h,u=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&Gi[c]===1)u===-1&&(u=d);else if(c===32||c===9)l===-1&&u!==-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),pt(n,t.slice(u,l),!0),c===44&&(pt(e,s,n),n=Object.create(null),s=void 0),u=l=-1}else if(c===61&&u!==-1&&l===-1)a=t.slice(u,d),u=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(Gi[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1?u=d:i||(i=!0),r=!1}else if(o)if(Gi[c]===1)u===-1&&(u=d);else if(c===34&&u!==-1)o=!1,l=d;else if(c===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&Gi[c]===1)u===-1&&(u=d);else if(u!==-1&&(c===32||c===9))l===-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(u,l);i&&(h=h.replace(/\\/g,""),i=!1),pt(n,a,h),c===44&&(pt(e,s,n),n=Object.create(null),s=void 0),a=void 0,u=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(u===-1||o||c===32||c===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let f=t.slice(u,l);return s===void 0?pt(e,f,n):(a===void 0?pt(n,f,!0):i?pt(n,a,f.replace(/\\/g,"")):pt(n,a,f),pt(e,s,n)),e}function fP(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(r=>{let o=i[r];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?r:`${r}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bw.exports={format:fP,parse:dP}});var La=z((p2,Aw)=>{"use strict";var hP=ae("events"),pP=ae("https"),mP=ae("http"),ww=ae("net"),gP=ae("tls"),{randomBytes:vP,createHash:yP}=ae("crypto"),{Duplex:f2,Readable:h2}=ae("stream"),{URL:vm}=ae("url"),Xt=$n(),_P=fm(),bP=mm(),{isBlob:$P}=xn(),{BINARY_TYPES:$w,CLOSE_TIMEOUT:xP,EMPTY_BUFFER:Na,GUID:wP,kForOnEventAttribute:ym,kListener:SP,kStatusCode:kP,kWebSocket:ge,NOOP:Sw}=kt(),{EventTarget:{addEventListener:IP,removeEventListener:EP}}=_w(),{format:TP,parse:OP}=za(),{toBuffer:PP}=Fi(),kw=Symbol("kAborted"),_m=[8,13],Tt=["CONNECTING","OPEN","CLOSING","CLOSED"],CP=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,re=class t extends hP{constructor(e,n,i){super(),this._binaryType=$w[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Na,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),Iw(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){$w.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let r=new _P({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),o=new bP(e,this._extensions,i.generateMask);this._receiver=r,this._sender=o,this._socket=e,r[ge]=this,o[ge]=this,e[ge]=this,r.on("conclude",NP),r.on("drain",RP),r.on("error",DP),r.on("message",LP),r.on("ping",UP),r.on("pong",jP),o.onerror=MP,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Ow),e.on("data",Da),e.on("end",Pw),e.on("error",Cw),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Xt.extensionName]&&this._extensions[Xt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Tw(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bm(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Na,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bm(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Na,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bm(this,e,i);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Xt.extensionName]||(r.compress=!1),this._sender.send(e||Na,r,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(re,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")});Object.defineProperty(re.prototype,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")});Object.defineProperty(re,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")});Object.defineProperty(re.prototype,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")});Object.defineProperty(re,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")});Object.defineProperty(re.prototype,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")});Object.defineProperty(re,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")});Object.defineProperty(re.prototype,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(re.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(re.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ym])return e[SP];return null},set(e){for(let n of this.listeners(t))if(n[ym]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ym]:!0})}})});re.prototype.addEventListener=IP;re.prototype.removeEventListener=EP;Aw.exports=re;function Iw(t,e,n,i){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:xP,protocolVersion:_m[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=r.autoPong,t._closeTimeout=r.closeTimeout,!_m.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${_m.join(", ")})`);let o;if(e instanceof vm)o=e;else try{o=new vm(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",u;if(o.protocol!=="ws:"&&!s&&!a?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?u="The URL's pathname is empty":o.hash&&(u="The URL contains a fragment identifier"),u){let _=new SyntaxError(u);if(t._redirects===0)throw _;Ra(t,_);return}let c=s?443:80,l=vP(16).toString("base64"),d=s?pP.request:mP.request,f=new Set,h;if(r.createConnection=r.createConnection||(s?zP:AP),r.defaultPort=r.defaultPort||c,r.port=o.port||c,r.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},r.path=o.pathname+o.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(h=new Xt({...r.perMessageDeflate,isServer:!1,maxPayload:r.maxPayload}),r.headers["Sec-WebSocket-Extensions"]=TP({[Xt.extensionName]:h.offer()})),n.length){for(let _ of n){if(typeof _!="string"||!CP.test(_)||f.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(_)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(o.username||o.password)&&(r.auth=`${o.username}:${o.password}`),a){let _=r.path.split(":");r.socketPath=_[0],r.path=_[1]}let p;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?r.socketPath:o.host;let _=i&&i.headers;if(i={...i,headers:{}},_)for(let[S,k]of Object.entries(_))i.headers[S.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let _=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!_||t._originalSecure&&!s)&&(delete r.headers.authorization,delete r.headers.cookie,_||delete r.headers.host,r.auth=void 0)}r.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),p=t._req=d(r),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=d(r);r.timeout&&p.on("timeout",()=>{We(t,p,"Opening handshake has timed out")}),p.on("error",_=>{p===null||p[kw]||(p=t._req=null,Ra(t,_))}),p.on("response",_=>{let S=_.headers.location,k=_.statusCode;if(S&&r.followRedirects&&k>=300&&k<400){if(++t._redirects>r.maxRedirects){We(t,p,"Maximum redirects exceeded");return}p.abort();let C;try{C=new vm(S,e)}catch{let I=new SyntaxError(`Invalid URL: ${S}`);Ra(t,I);return}Iw(t,C,n,i)}else t.emit("unexpected-response",p,_)||We(t,p,`Unexpected server response: ${_.statusCode}`)}),p.on("upgrade",(_,S,k)=>{if(t.emit("upgrade",_),t.readyState!==re.CONNECTING)return;p=t._req=null;let C=_.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){We(t,S,"Invalid Upgrade header");return}let A=yP("sha1").update(l+wP).digest("base64");if(_.headers["sec-websocket-accept"]!==A){We(t,S,"Invalid Sec-WebSocket-Accept header");return}let I=_.headers["sec-websocket-protocol"],T;if(I!==void 0?f.size?f.has(I)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":f.size&&(T="Server sent no subprotocol"),T){We(t,S,T);return}I&&(t._protocol=I);let Z=_.headers["sec-websocket-extensions"];if(Z!==void 0){if(!h){We(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let F;try{F=OP(Z)}catch{We(t,S,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(F);if(W.length!==1||W[0]!==Xt.extensionName){We(t,S,"Server indicated an extension that was not requested");return}try{h.accept(F[Xt.extensionName])}catch{We(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Xt.extensionName]=h}t.setSocket(S,k,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(p,t):p.end()}function Ra(t,e){t._readyState=re.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function AP(t){return t.path=t.socketPath,ww.connect(t)}function zP(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ww.isIP(t.host)?"":t.host),gP.connect(t)}function We(t,e,n){t._readyState=re.CLOSING;let i=new Error(n);Error.captureStackTrace(i,We),e.setHeader?(e[kw]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ra,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function bm(t,e,n){if(e){let i=$P(e)?e.size:PP(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Tt[t.readyState]})`);process.nextTick(n,i)}}function NP(t,e){let n=this[ge];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ge]!==void 0&&(n._socket.removeListener("data",Da),process.nextTick(Ew,n._socket),t===1005?n.close():n.close(t,e))}function RP(){let t=this[ge];t.isPaused||t._socket.resume()}function DP(t){let e=this[ge];e._socket[ge]!==void 0&&(e._socket.removeListener("data",Da),process.nextTick(Ew,e._socket),e.close(t[kP])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function xw(){this[ge].emitClose()}function LP(t,e){this[ge].emit("message",t,e)}function UP(t){let e=this[ge];e._autoPong&&e.pong(t,!this._isServer,Sw),e.emit("ping",t)}function jP(t){this[ge].emit("pong",t)}function Ew(t){t.resume()}function MP(t){let e=this[ge];e.readyState!==re.CLOSED&&(e.readyState===re.OPEN&&(e._readyState=re.CLOSING,Tw(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Tw(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ow(){let t=this[ge];if(this.removeListener("close",Ow),this.removeListener("data",Da),this.removeListener("end",Pw),t._readyState=re.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ge]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",xw),t._receiver.on("finish",xw))}function Da(t){this[ge]._receiver.write(t)||this.pause()}function Pw(){let t=this[ge];t._readyState=re.CLOSING,t._receiver.end(),this.end()}function Cw(){let t=this[ge];this.removeListener("error",Cw),this.on("error",Sw),t&&(t._readyState=re.CLOSING,this.destroy())}});var Dw=z((g2,Rw)=>{"use strict";var m2=La(),{Duplex:FP}=ae("stream");function zw(t){t.emit("close")}function VP(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Nw(t){this.removeListener("error",Nw),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function ZP(t,e){let n=!0,i=new FP({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&i._readableState.objectMode?o.toString():o;i.push(a)||t.pause()}),t.once("error",function(o){i.destroyed||(n=!1,i.destroy(o))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(r,o){if(t.readyState===t.CLOSED){o(r),process.nextTick(zw,i);return}let s=!1;t.once("error",function(u){s=!0,o(u)}),t.once("close",function(){s||o(r),process.nextTick(zw,i)}),n&&t.terminate()},i._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(r,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(r,o,s)});return}t.send(r,s)},i.on("end",VP),i.on("error",Nw),i}Rw.exports=ZP});var $m=z((v2,Lw)=>{"use strict";var{tokenChars:BP}=xn();function GP(t){let e=new Set,n=-1,i=-1,r=0;for(r;r<t.length;r++){let s=t.charCodeAt(r);if(i===-1&&BP[s]===1)n===-1&&(n=r);else if(r!==0&&(s===32||s===9))i===-1&&n!==-1&&(i=r);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);i===-1&&(i=r);let a=t.slice(n,i);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,r);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Lw.exports={parse:GP}});var Bw=z((_2,Zw)=>{"use strict";var WP=ae("events"),Ua=ae("http"),{Duplex:y2}=ae("stream"),{createHash:qP}=ae("crypto"),Uw=za(),Sr=$n(),HP=$m(),JP=La(),{CLOSE_TIMEOUT:KP,GUID:YP,kWebSocket:XP}=kt(),QP=/^[+/0-9A-Za-z]{22}==$/,jw=0,Mw=1,Vw=2,xm=class extends WP{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:KP,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:JP,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ua.createServer((i,r)=>{let o=Ua.STATUS_CODES[426];r.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),r.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=eC(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,o,s)=>{this.handleUpgrade(r,o,s,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=jw}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Vw){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Wi,this);return}if(e&&this.once("close",e),this._state!==Mw)if(this._state=Mw,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Wi,this):process.nextTick(Wi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Wi(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,r){n.on("error",Fw);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){kr(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){kr(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!QP.test(o)){kr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){kr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){qi(n,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=HP.parse(u)}catch{kr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let f=new Sr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Uw.parse(l);h[Sr.extensionName]&&(f.accept(h[Sr.extensionName]),d[Sr.extensionName]=f)}catch{kr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,p,_,S)=>{if(!h)return qi(n,p||401,_,S);this.completeUpgrade(d,o,c,e,n,i,r)});return}if(!this.options.verifyClient(f))return qi(n,401)}this.completeUpgrade(d,o,c,e,n,i,r)}completeUpgrade(e,n,i,r,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[XP])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>jw)return qi(o,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${qP("sha1").update(n+YP).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(i.size){let d=this.options.handleProtocols?this.options.handleProtocols(i,r):i.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[Sr.extensionName]){let d=e[Sr.extensionName].params,f=Uw.format({[Sr.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",c,r),o.write(c.concat(`\r
120
+ `,Kt=class extends Error{status;constructor(e,n){super(e),this.status=n,this.name="TurnEvaluatorError"}},ya=class{key;fetchImpl;timeoutMs;constructor(e,n=fetch,i=2e3){this.key=e,this.fetchImpl=n,this.timeoutMs=i}async evaluate(e,n){let i={model:yO,max_tokens:64,temperature:0,stop_sequences:$O,system:wO,messages:[{role:"user",content:SO(e)},{role:"assistant",content:Px}]},r=await this.fetchImpl(_O,{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":bO,"content-type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.any([n,AbortSignal.timeout(this.timeoutMs)])});if(!r.ok)throw new Kt(`turn evaluator request failed (HTTP ${r.status})`,r.status);let o;try{o=await r.json()}catch{throw new Kt("turn evaluator response body was not JSON")}return kO(o)}}});var Ax,qp,Hp=v(()=>{"use strict";Ax="21m00Tcm4TlvDq8ikWAM",qp={id:"jarvis-primary",engineVoice:{"elevenlabs-flash":{kind:"preset",voiceId:Ax}}}});var _a,zx=v(()=>{"use strict";De();_a=class{turnId;openedAtMs;log;terminal=!1;heldOpen=!1;decider=null;silenceOnsetAtMs=null;commitAtMs=null;asrFinalAtMs=null;transcriptLength=null;firstDeltaAtMs=null;firstAudioAtMs=null;constructor(e,n,i=q){this.turnId=e,this.openedAtMs=n,this.log=i}endpointerCommitted(e,n){this.decider===null&&(this.decider=e,this.silenceOnsetAtMs=n)}smartTurnResolved(e,n,i){this.log.debug("smart-turn P(complete)",{turnId:this.turnId,probability:e,inferenceMs:n,outcome:i})}smartTurnDegraded(e,n){this.log.debug("smart-turn DEGRADED to baseline - inference failed; this turn endpoints on baseline timers only",{turnId:this.turnId,inferenceMs:e,error:n instanceof Error?n.message:String(n)})}strongHoldRecognized(e){this.log.debug("lexical STRONG hold recognized - completeness vetoed, silence budget biases long",{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,n,i,r){this.log.debug("semantic evaluator resolved",{turnId:this.turnId,verdict:e,confidence:n,latencyMs:i,outcome:r})}evaluatorFailed(e,n){this.log.debug("semantic evaluator failed - no signal; this episode endpoints as armed",{turnId:this.turnId,latencyMs:e,error:n instanceof Error?n.message:String(n)})}committed(e,n){this.commitAtMs===null&&(n==="ptt"&&this.heldOpen&&this.heldExited("ptt"),this.commitAtMs=e,n==="ptt"&&(this.decider??="ptt"))}asrFinalResolved(e,n){this.asrFinalAtMs===null&&(this.asrFinalAtMs=e,this.transcriptLength=n)}firstReasonerDelta(e){this.firstDeltaAtMs??=e}firstTtsAudio(e){this.firstAudioAtMs??=e}completed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn summary",{turnId:this.turnId,decider:this.decider,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}))}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,n){return e===null||n===null?null:n-e}}});var Nx,Rx,IO,ba,Dx=v(()=>{"use strict";zx();Nx=16e3,Rx="pcm_s16le",IO="en",ba=class{deps;asrStream;ttsStream=null;reasonAbort=new AbortController;phase="capturing";settled=!1;finalizing=!1;lastFrameAtMs;timeline;constructor(e){this.deps=e,this.lastFrameAtMs=e.startMs,this.timeline=new _a(e.turnId,e.clock.now()),e.controller.attachTelemetry?.(this.timeline),this.asrStream=e.asrEngine.open({sampleRate:Nx,encoding:Rx,language:IO,emitPartials:!0}),this.asrStream.onTranscript(n=>this.handleTranscript(n)),this.asrStream.onError(n=>this.finishError("turn_failed",n)),e.controller.onCommit(()=>this.finalize(this.lastFrameAtMs,"controller")),e.emit({type:"state",turnId:e.turnId,state:"processing"})}pushFrame(e,n){this.phase!=="capturing"||this.settled||(this.lastFrameAtMs=n,this.asrStream.pushAudio(e),this.deps.controller.onAudioFrame(e))}endAudio(e){this.finalize(e,"ptt")}cancel(){this.settled||(this.settled=!0,this.phase="cancelled",this.deps.controller.dispose(),this.reasonAbort.abort(),this.asrStream.abort(),this.ttsStream?.cancel(),this.deps.onComplete())}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))}finalize(e,n){this.phase!=="capturing"||this.finalizing||this.settled||(this.finalizing=!0,this.timeline.committed(this.deps.clock.now(),n),this.deps.controller.dispose(),this.finalizeAndRespond(e))}async finalizeAndRespond(e){let n;try{n=await this.asrStream.end()}catch(r){if(this.settled)return;this.finishError("turn_failed",r);return}if(this.settled)return;if(this.timeline.asrFinalResolved(this.deps.clock.now(),n.text.length),n.text.trim()===""){this.finishBlank();return}this.phase="responding";let i=this.buildUserTurn(n.text,e);this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:i,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"});try{await this.respond(i.text)}catch(r){if(this.settled)return;this.finishError("turn_failed",r);return}this.settled||this.finishDone()}async respond(e){let n=!1,i=!1,r=this.deps.ttsEngine.speak({voice:this.deps.voice,sampleRate:Nx,encoding:Rx});this.ttsStream=r,r.onAudio(s=>{this.settled||(i||(i=!0,this.timeline.firstTtsAudio(this.deps.clock.now())),this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:s}))}),r.onError(s=>this.finishError("turn_failed",s));let o=this.deps.reasoner.run(e,this.reasonAbort.signal,{register:"voice"});for await(let s of o){if(this.settled)return;n||(n=!0,this.timeline.firstReasonerDelta(this.deps.clock.now())),this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:s.text});for(let a of this.deps.segmenter.push(s.text))r.pushText(a)}if(!this.settled){for(let s of this.deps.segmenter.flush())r.pushText(s);await r.end()}}finishBlank(){this.settled||(this.settled=!0,this.timeline.blank(this.deps.clock.now()),this.deps.onComplete())}finishDone(){this.settled||(this.settled=!0,this.timeline.completed(this.deps.clock.now()),this.deps.emit({type:"response.done",turnId:this.deps.turnId}),this.deps.onComplete())}finishError(e,n){this.settled||(this.settled=!0,this.deps.controller.dispose(),this.reasonAbort.abort(),this.ttsStream?.cancel(),this.deps.emit({type:"error",turnId:this.deps.turnId,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId},reason:e,message:n instanceof Error?n.message:String(n)}),this.deps.onComplete())}buildUserTurn(e,n){return{source:"voice",turnId:this.deps.turnId,sessionId:this.deps.sessionId,deviceId:this.deps.deviceId,text:e,startMs:this.deps.startMs,endMs:n,...this.deps.projectId!==void 0&&{projectId:this.deps.projectId}}}}});import{randomUUID as Jp}from"node:crypto";var EO,yn,Ui,$a,Lx=v(()=>{"use strict";xi();tp();Bb();rp();np();Ti();Rp();Vp();Gp();Cx();Hp();Dx();EO=6,yn=class extends Error{constructor(e){super(e),this.name="ReasonerUnavailableError"}},Ui=class extends Error{constructor(e){super(e),this.name="VoiceUnavailableError"}},$a=class{deps;sessionId;deviceId;projectId;queue=new ra;closed=!1;eventsConsumed=!1;inFlight=!1;reasoner=null;reasonerRoute=null;turnAbort=null;voiceTurn=null;voiceTurnFailed=!1;voiceEngines=null;clock;newTurnController;newSmartTurnInference;newFrameClassifier;newTurnEvaluator;newSegmenter;voiceIdentity;smartTurnInference=null;frameClassifier=null;turnEvaluator=void 0;constructor(e,n,i){this.deps=i,this.sessionId=e,this.deviceId=n.deviceId,this.projectId=n.projectId,this.clock=i.clock??new ki,this.newSmartTurnInference=i.createSmartTurnInference??(()=>new Li),this.newFrameClassifier=i.createFrameClassifier??(()=>new Ei(new _r)),this.newTurnEvaluator=i.createTurnEvaluator??(r=>new ya(r)),this.newTurnController=i.createTurnController??(r=>{let o=this.ensureFrameClassifier();return o.reset?.(),new Di(r,this.ensureSmartTurnInference(),{},o,this.semanticHook())}),this.newSegmenter=i.createSegmenter??(()=>new Si),this.voiceIdentity=i.voiceIdentity??qp,this.emit({type:"session.ready"})}async send(e){let{commandId:n}=e;if(this.closed)throw new Le(n,"closed");if(e.sessionId!==this.sessionId)throw new Le(n,"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"session.close":return this.close();case"approval.resolve":throw new Le(n,"unsupported");default:throw new Le(n,"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){this.closed=!0,this.turnAbort?.abort(),this.voiceTurn?.cancel();let e=this.smartTurnInference;this.smartTurnInference=null;let n=this.frameClassifier;this.frameClassifier=null;let i=this.turnEvaluator;this.turnEvaluator=null,this.queue.close();let r=[];if(e&&r.push(e.dispose().catch(()=>{})),n?.dispose&&r.push(n.dispose().catch(()=>{})),i?.dispose&&r.push(i.dispose().catch(()=>{})),r.length>0)return Promise.all(r).then(()=>{})}return Promise.resolve()}acceptTextInput(e){if(e.text.trim().length===0)throw new Le(e.commandId,"invalid","input.text requires non-empty text");if(this.inFlight)throw new Le(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=Jp();this.emit({type:"turn.accepted",turnId:n,clientTurnId:e.clientTurnId,source:"text",commandId:e.commandId}),this.emit({type:"turn.final",turnId:n,turn:this.toTextUserTurn(n,e),commandId:e.commandId}),this.runTextTurn(n,e)}async runTextTurn(e,n){let i=new AbortController;this.turnAbort=i;try{let r=this.ensureReasoner();this.emit({type:"state",turnId:e,state:"responding"});for await(let o of r.run(n.text,i.signal))this.emit({type:"response.delta",turnId:e,text:o.text});this.emit({type:"response.done",turnId:e})}catch(r){let o=r instanceof yn?"no_text_route":"turn_failed";this.emit({type:"error",turnId:e,commandId:n.commandId,reason:o,message:r instanceof Error?r.message:String(r)})}finally{this.inFlight=!1,this.turnAbort=null}}acceptAudioFrame(e){if(this.voiceTurn){this.voiceTurn.pushFrame(e.audio,e.atMs);return}if(this.voiceTurnFailed)return;if(this.inFlight)throw new Le(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=Jp();this.emit({type:"turn.accepted",turnId:n,clientTurnId:e.clientTurnId,source:"voice",commandId:e.commandId});let i=this.resolveVoicePipeline(n,e.commandId);if(!i){this.voiceTurnFailed=!0;return}this.voiceTurn=new ba({turnId:n,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:this.voiceIdentity,reasoner:i.reasoner,controller:this.newTurnController(this.clock),segmenter:this.newSegmenter(),clock:this.clock,emit:r=>this.emit(r),onComplete:()=>this.completeVoiceTurn()}),this.smartTurnInference?.prewarm?.(),this.frameClassifier?.prewarm?.(),this.voiceTurn.pushFrame(e.audio,e.atMs)}endAudioInput(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}this.voiceTurn?.endAudio(e.atMs)}cancelTurn(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}this.voiceTurn?.cancel()}completeVoiceTurn(){this.voiceTurn=null,this.inFlight=!1}resetVoiceFailure(){this.voiceTurnFailed=!1}resolveVoicePipeline(e,n){let i;try{i=this.ensureVoiceEngines()}catch(o){return this.emitTurnError(e,n,"no_voice_route",o),null}let r;try{r=this.ensureReasoner()}catch(o){let s=o instanceof yn?"no_text_route":"turn_failed";return this.emitTurnError(e,n,s,o),null}return{engines:i,reasoner:r}}ensureVoiceEngines(){if(this.voiceEngines)return this.voiceEngines;if(!this.deps.voiceRegistry)throw new Ui("voice is not available in this core build");let e=this.deps.configService.resolved(),n=e.routes?.stt,i=e.routes?.tts;if(!n||!i)throw new Ui("no voice route configured - run 'jarvis init' to set routes.stt and routes.tts");let r=e.secrets?.[n.provider],o=e.secrets?.[i.provider];if(!r||!o){let u=r?i.provider:n.provider;throw new Ui(`no API key for voice provider '${u}' - run 'jarvis init' to add it`)}let s=this.deps.voiceRegistry.asrEngine({provider:n.provider,model:n.model},r),a=this.deps.voiceRegistry.ttsEngine({provider:i.provider,model:i.model},o);return this.voiceEngines={asrEngine:s,ttsEngine:a},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 n=this.reasonerRoute;this.turnEvaluator=n?.provider==="anthropic"?this.newTurnEvaluator(n.key):null}return this.turnEvaluator===null?void 0:{evaluator:this.turnEvaluator,recentTurns:()=>{let n=[];for(let i of this.reasoner?.historySnapshot()??[])(i.role==="user"||i.role==="assistant")&&n.push({role:i.role,text:i.content});return n.slice(-EO)}}}ensureReasoner(){if(this.reasoner)return this.reasoner;let e=this.deps.configService.resolved(),n=e.routes?.text;if(!n)throw new yn("no text model is configured - run 'jarvis init' to set routes.text");let i=e.secrets?.[n.provider];if(!i)throw new yn(`no API key for text provider '${n.provider}' - run 'jarvis init' to add it`);let r=this.deps.registry.textAdapter({provider:n.provider,model:n.model},i);return this.reasoner=new wi(r,n.model,this.deps.systemPrompt),this.reasonerRoute={provider:n.provider,key:i},this.reasoner}toTextUserTurn(e,n){return{source:"text",turnId:e,sessionId:this.sessionId,deviceId:this.deviceId,text:n.text,atMs:n.atMs,...this.projectId!==void 0&&{projectId:this.projectId}}}emitTurnError(e,n,i,r){this.emit({type:"error",turnId:e,commandId:n,reason:i,message:r instanceof Error?r.message:String(r)}),this.inFlight=!1}emit(e){this.queue.push({...e,sessionId:this.sessionId,eventId:Jp(),atMs:Date.now()})}}});function xa(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function Kp(t){return typeof t=="string"?t:""}function wa(t){let e=t.message_type;return typeof e=="string"&&(TO.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function Ux(t){return Buffer.from(t).toString("base64")}function jx(t){return new Uint8Array(Buffer.from(t,"base64"))}function Sa(t,e){return new Error(`${t} connection error: ${e.message}`)}var TO,Yp=v(()=>{"use strict";TO=new Set(["error","auth_error","quota_exceeded","rate_limited"])});function OO(t,e,n){let i=new URL(t);i.searchParams.set("model_id",e),i.searchParams.set("audio_format",PO(n)),i.searchParams.set("commit_strategy","manual"),n.language&&i.searchParams.set("language_code",n.language);for(let r of n.biasTerms??[])i.searchParams.append("keyterms",r);return i.toString()}function PO(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var Mx,ji,Xp,Qp=v(()=>{"use strict";Yp();Mx="wss://api.elevenlabs.io/v1/speech-to-text/realtime",ji=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-scribe";constructor(e,n,i,r=Mx){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpoint=r}open(e){return new Xp(this.apiKey,this.socketFactory,this.model,this.endpoint,e)}},Xp=class{opts;socket;opened=!1;aborted=!1;closed=!1;pending=[];committed=[];transcriptCb;errorCb;endPending=null;commitRequested=!1;constructor(e,n,i,r,o){this.opts=o,this.socket=n(OO(r,i,o),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(s=>this.handleMessage(s)),this.socket.onError(s=>this.handleError(s)),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,n)=>{this.endPending={resolve:e,reject:n},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 n=xa(e);if(!n)return;let i=wa(n);if(i){this.handleError(new Error(`stream error (${i})`));return}let r=n.message_type;if(r==="partial_transcript"){this.opts.emitPartials&&this.transcriptCb?.({text:Kp(n.text),isFinal:!1,startMs:0});return}if(r==="committed_transcript"||r==="committed_transcript_with_timestamps"){let o=Kp(n.text);o.length>0&&this.committed.push(o),this.endPending&&this.resolveEnd()}}handleError(e){if(this.closed)return;let n=Sa("ElevenLabs ASR",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(n)}this.errorCb?.(n),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs ASR connection closed unexpectedly");if(this.endPending){let{reject:n}=this.endPending;this.endPending=null,n(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:n}=this.endPending;this.endPending=null,this.teardown(),n(e)}sendChunk(e,n){this.socket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:Ux(e),commit:n,sample_rate:this.opts.sampleRate}))}sendCommit(){this.sendChunk(new Uint8Array(0),!0)}teardown(){this.closed||(this.closed=!0,this.socket.close())}}});import{randomUUID as CO}from"node:crypto";function zO(t,e){let n=t.engineVoice[e];if(!n)throw new Error(`voice '${t.id}' has no '${e}' engineVoice mapping`);if(n.kind!=="preset")throw new Error(`the ${e} adapter needs a preset voiceId for '${t.id}', got kind '${n.kind}'`);return n.voiceId}function NO(t,e,n,i){let r=new URL(t.replace("{voice_id}",encodeURIComponent(e)));return r.searchParams.set("model_id",n),r.searchParams.set("output_format",RO(i)),r.searchParams.set("auto_mode","true"),r.toString()}function RO(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var Fx,AO,Mi,em,tm=v(()=>{"use strict";Yp();Fx="wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/multi-stream-input",AO={stability:.5,similarity_boost:.75,use_speaker_boost:!0},Mi=class{apiKey;socketFactory;model;endpointTemplate;id="elevenlabs-flash";constructor(e,n,i,r=Fx){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpointTemplate=r}speak(e){return new em(this.apiKey,this.socketFactory,this.model,this.endpointTemplate,this.id,e)}},em=class{socket;contextId=CO();opened=!1;cancelled=!1;closed=!1;endRequested=!1;closeContextSent=!1;pending=[];audioCb;errorCb;endPending=null;constructor(e,n,i,r,o,s){let a=zO(s.voice,o);this.socket=n(NO(r,a,i,s),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(u=>this.handleMessage(u)),this.socket.onError(u=>this.handleError(u)),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,n)=>{this.endPending={resolve:e,reject:n},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 n=xa(e);if(!n)return;let i=wa(n);if(i){this.handleError(new Error(`stream error (${i})`));return}typeof n.audio=="string"&&n.audio.length>0&&this.audioCb?.(jx(n.audio)),(n.isFinal===!0||n.is_final===!0)&&this.resolveEnd()}handleError(e){if(this.closed)return;let n=Sa("ElevenLabs TTS",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(n)}this.errorCb?.(n),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs TTS connection closed unexpectedly");if(this.endPending){let{reject:n}=this.endPending;this.endPending=null,n(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:AO,context_id:this.contextId}))}sendText(e){let n=e.endsWith(" ")?e:`${e} `;this.socket.send(JSON.stringify({text:n,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())}}});var kt=z((n2,Bx)=>{"use strict";var Vx=["nodebuffer","arraybuffer","fragments"],Zx=typeof Blob<"u";Zx&&Vx.push("blob");Bx.exports={BINARY_TYPES:Vx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Fi=z((i2,ka)=>{"use strict";var{EMPTY_BUFFER:DO}=kt(),rm=Buffer[Symbol.species];function LO(t,e){if(t.length===0)return DO;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let r=0;r<t.length;r++){let o=t[r];n.set(o,i),i+=o.length}return i<e?new rm(n.buffer,n.byteOffset,i):n}function Gx(t,e,n,i,r){for(let o=0;o<r;o++)n[i+o]=t[o]^e[o&3]}function Wx(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function UO(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function nm(t){if(nm.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new rm(t):ArrayBuffer.isView(t)?e=new rm(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),nm.readOnly=!1),e}ka.exports={concat:LO,mask:Gx,toArrayBuffer:UO,toBuffer:nm,unmask:Wx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ae("bufferutil");ka.exports.mask=function(e,n,i,r,o){o<48?Gx(e,n,i,r,o):t.mask(e,n,i,r,o)},ka.exports.unmask=function(e,n){e.length<32?Wx(e,n):t.unmask(e,n)}}catch{}});var Jx=z((o2,Hx)=>{"use strict";var qx=Symbol("kDone"),im=Symbol("kRun"),om=class{constructor(e){this[qx]=()=>{this.pending--,this[im]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[im]()}[im](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[qx])}}};Hx.exports=om});var $n=z((s2,Qx)=>{"use strict";var Vi=ae("zlib"),Kx=Fi(),jO=Jx(),{kStatusCode:Yx}=kt(),MO=Buffer[Symbol.species],FO=Buffer.from([0,0,255,255]),Ea=Symbol("permessage-deflate"),It=Symbol("total-length"),_n=Symbol("callback"),Yt=Symbol("buffers"),bn=Symbol("error"),Ia,sm=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ia){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ia=new jO(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[_n];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let r=n[i];if(r.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(r=r[0],i==="client_max_window_bits"){if(r!==!0){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else if(i==="server_max_window_bits"){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=r})}),e}decompress(e,n,i){Ia.add(r=>{this._decompress(e,n,(o,s)=>{r(),i(o,s)})})}compress(e,n,i){Ia.add(r=>{this._compress(e,n,(o,s)=>{r(),i(o,s)})})}_decompress(e,n,i){let r=this._isServer?"client":"server";if(!this._inflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ea]=this,this._inflate[It]=0,this._inflate[Yt]=[],this._inflate.on("error",ZO),this._inflate.on("data",Xx)}this._inflate[_n]=i,this._inflate.write(e),n&&this._inflate.write(FO),this._inflate.flush(()=>{let o=this._inflate[bn];if(o){this._inflate.close(),this._inflate=null,i(o);return}let s=Kx.concat(this._inflate[Yt],this._inflate[It]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[It]=0,this._inflate[Yt]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),i(null,s)})}_compress(e,n,i){let r=this._isServer?"server":"client";if(!this._deflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[It]=0,this._deflate[Yt]=[],this._deflate.on("data",VO)}this._deflate[_n]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Kx.concat(this._deflate[Yt],this._deflate[It]);n&&(o=new MO(o.buffer,o.byteOffset,o.length-4)),this._deflate[_n]=null,this._deflate[It]=0,this._deflate[Yt]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),i(null,o)})}};Qx.exports=sm;function VO(t){this[Yt].push(t),this[It]+=t.length}function Xx(t){if(this[It]+=t.length,this[Ea]._maxPayload<1||this[It]<=this[Ea]._maxPayload){this[Yt].push(t);return}this[bn]=new RangeError("Max payload size exceeded"),this[bn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[bn][Yx]=1009,this.removeListener("data",Xx),this.reset()}function ZO(t){if(this[Ea]._inflate=null,this[bn]){this[_n](this[bn]);return}t[Yx]=1007,this[_n](t)}});var xn=z((a2,Ta)=>{"use strict";var{isUtf8:ew}=ae("buffer"),{hasBlob:BO}=kt(),GO=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function WO(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function am(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function qO(t){return BO&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ta.exports={isBlob:qO,isValidStatusCode:WO,isValidUTF8:am,tokenChars:GO};if(ew)Ta.exports.isValidUTF8=function(t){return t.length<24?am(t):ew(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ae("utf-8-validate");Ta.exports.isValidUTF8=function(e){return e.length<32?am(e):t(e)}}catch{}});var fm=z((u2,aw)=>{"use strict";var{Writable:HO}=ae("stream"),tw=$n(),{BINARY_TYPES:JO,EMPTY_BUFFER:rw,kStatusCode:KO,kWebSocket:YO}=kt(),{concat:um,toArrayBuffer:XO,unmask:QO}=Fi(),{isValidStatusCode:eP,isValidUTF8:nw}=xn(),Oa=Buffer[Symbol.species],Qe=0,iw=1,ow=2,sw=3,cm=4,lm=5,Pa=6,dm=class extends HO{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||JO[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[YO]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Qe}_write(e,n,i){if(this._opcode===8&&this._state==Qe)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Oa(i.buffer,i.byteOffset+e,i.length-e),new Oa(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],r=n.length-e;e>=i.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),r),this._buffers[0]=new Oa(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Qe:this.getInfo(e);break;case iw:this.getPayloadLength16(e);break;case ow:this.getPayloadLength64(e);break;case sw:this.getMask();break;case cm:this.getData(e);break;case lm:case Pa:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let i=(n[0]&64)===64;if(i&&!this._extensions[tw.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=iw:this._payloadLength===127?this._state=ow:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=sw:this._state=cm}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=cm}getData(e){let n=rw;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&QO(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=lm,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[tw.extensionName].decompress(e,this._fin,(r,o)=>{if(r)return n(r);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===Qe&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Qe;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=um(i,n):this._binaryType==="arraybuffer"?r=XO(um(i,n)):this._binaryType==="blob"?r=new Blob(i):r=i,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=Qe):(this._state=Pa,setImmediate(()=>{this.emit("message",r,!0),this._state=Qe,this.startLoop(e)}))}else{let r=um(i,n);if(!this._skipUTF8Validation&&!nw(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===lm||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=Qe):(this._state=Pa,setImmediate(()=>{this.emit("message",r,!1),this._state=Qe,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,rw),this.end();else{let i=e.readUInt16BE(0);if(!eP(i)){let o=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let r=new Oa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!nw(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",i,r),this.end()}this._state=Qe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe):(this._state=Pa,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe,this.startLoop(n)}))}createError(e,n,i,r,o){this._loop=!1,this._errored=!0;let s=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[KO]=r,s}};aw.exports=dm});var mm=z((l2,lw)=>{"use strict";var{Duplex:c2}=ae("stream"),{randomFillSync:tP}=ae("crypto"),{types:{isUint8Array:rP}}=ae("util"),uw=$n(),{EMPTY_BUFFER:nP,kWebSocket:iP,NOOP:oP}=kt(),{isBlob:wn,isValidStatusCode:sP}=xn(),{mask:cw,toBuffer:$r}=Fi(),et=Symbol("kByteLength"),aP=Buffer.alloc(4),Ca=8*1024,xr,Sn=Ca,ct=0,uP=1,cP=2,hm=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=oP,this[iP]=void 0}static frame(e,n){let i,r=!1,o=2,s=!1;n.mask&&(i=n.maskBuffer||aP,n.generateMask?n.generateMask(i):(Sn===Ca&&(xr===void 0&&(xr=Buffer.alloc(Ca)),tP(xr,0,Ca),Sn=0),i[0]=xr[Sn++],i[1]=xr[Sn++],i[2]=xr[Sn++],i[3]=xr[Sn++]),s=(i[0]|i[1]|i[2]|i[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[et]!==void 0?a=n[et]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!s);let u=a;a>=65536?(o+=8,u=127):a>125&&(o+=2,u=126);let c=Buffer.allocUnsafe(r?a+o:o);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(a,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[o-4]=i[0],c[o-3]=i[1],c[o-2]=i[2],c[o-1]=i[3],s?[c,e]:r?(cw(e,i,c,o,a),[c]):(cw(e,i,e,0,a),[c,e])):[c,e]}close(e,n,i,r){let o;if(e===void 0)o=nP;else{if(typeof e!="number"||!sP(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(rP(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[et]:o.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,o,!1,s,r]):this.sendFrame(t.frame(o,s),r)}ping(e,n,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):wn(e)?(r=e.size,o=!1):(e=$r(e),r=e.length,o=$r.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[et]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};wn(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==ct?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(t.frame(e,s),i)}pong(e,n,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):wn(e)?(r=e.size,o=!1):(e=$r(e),r=e.length,o=$r.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[et]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};wn(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==ct?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(t.frame(e,s),i)}send(e,n,i){let r=this._extensions[uw.extensionName],o=n.binary?2:1,s=n.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):wn(e)?(a=e.size,u=!1):(e=$r(e),a=e.length,u=$r.readOnly),this._firstFragment?(this._firstFragment=!1,s&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=r._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let c={[et]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:u,rsv1:s};wn(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,c,i]):this.getBlobData(e,this._compress,c,i):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,c,i]):this.dispatch(e,this._compress,c,i)}getBlobData(e,n,i,r){this._bufferedBytes+=i[et],this._state=cP,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(pm,this,a,r);return}this._bufferedBytes-=i[et];let s=$r(o);n?this.dispatch(s,n,i,r):(this._state=ct,this.sendFrame(t.frame(s,i),r),this.dequeue())}).catch(o=>{process.nextTick(lP,this,o,r)})}dispatch(e,n,i,r){if(!n){this.sendFrame(t.frame(e,i),r);return}let o=this._extensions[uw.extensionName];this._bufferedBytes+=i[et],this._state=uP,o.compress(e,i.fin,(s,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");pm(this,u,r);return}this._bufferedBytes-=i[et],this._state=ct,i.readOnly=!1,this.sendFrame(t.frame(a,i),r),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][et],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][et],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};lw.exports=hm;function pm(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let r=t._queue[i],o=r[r.length-1];typeof o=="function"&&o(e)}}function lP(t,e,n){pm(t,e,n),t.onerror(e)}});var _w=z((d2,yw)=>{"use strict";var{kForOnEventAttribute:Zi,kListener:gm}=kt(),dw=Symbol("kCode"),fw=Symbol("kData"),hw=Symbol("kError"),pw=Symbol("kMessage"),mw=Symbol("kReason"),kn=Symbol("kTarget"),gw=Symbol("kType"),vw=Symbol("kWasClean"),Et=class{constructor(e){this[kn]=null,this[gw]=e}get target(){return this[kn]}get type(){return this[gw]}};Object.defineProperty(Et.prototype,"target",{enumerable:!0});Object.defineProperty(Et.prototype,"type",{enumerable:!0});var wr=class extends Et{constructor(e,n={}){super(e),this[dw]=n.code===void 0?0:n.code,this[mw]=n.reason===void 0?"":n.reason,this[vw]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[dw]}get reason(){return this[mw]}get wasClean(){return this[vw]}};Object.defineProperty(wr.prototype,"code",{enumerable:!0});Object.defineProperty(wr.prototype,"reason",{enumerable:!0});Object.defineProperty(wr.prototype,"wasClean",{enumerable:!0});var In=class extends Et{constructor(e,n={}){super(e),this[hw]=n.error===void 0?null:n.error,this[pw]=n.message===void 0?"":n.message}get error(){return this[hw]}get message(){return this[pw]}};Object.defineProperty(In.prototype,"error",{enumerable:!0});Object.defineProperty(In.prototype,"message",{enumerable:!0});var Bi=class extends Et{constructor(e,n={}){super(e),this[fw]=n.data===void 0?null:n.data}get data(){return this[fw]}};Object.defineProperty(Bi.prototype,"data",{enumerable:!0});var dP={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[Zi]&&r[gm]===e&&!r[Zi])return;let i;if(t==="message")i=function(o,s){let a=new Bi("message",{data:s?o:o.toString()});a[kn]=this,Aa(e,this,a)};else if(t==="close")i=function(o,s){let a=new wr("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[kn]=this,Aa(e,this,a)};else if(t==="error")i=function(o){let s=new In("error",{error:o,message:o.message});s[kn]=this,Aa(e,this,s)};else if(t==="open")i=function(){let o=new Et("open");o[kn]=this,Aa(e,this,o)};else return;i[Zi]=!!n[Zi],i[gm]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[gm]===e&&!n[Zi]){this.removeListener(t,n);break}}};yw.exports={CloseEvent:wr,ErrorEvent:In,Event:Et,EventTarget:dP,MessageEvent:Bi};function Aa(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var za=z((f2,bw)=>{"use strict";var{tokenChars:Gi}=xn();function pt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function fP(t){let e=Object.create(null),n=Object.create(null),i=!1,r=!1,o=!1,s,a,u=-1,c=-1,l=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),s===void 0)if(l===-1&&Gi[c]===1)u===-1&&(u=d);else if(d!==0&&(c===32||c===9))l===-1&&u!==-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(u,l);c===44?(pt(e,h,n),n=Object.create(null)):s=h,u=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&Gi[c]===1)u===-1&&(u=d);else if(c===32||c===9)l===-1&&u!==-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),pt(n,t.slice(u,l),!0),c===44&&(pt(e,s,n),n=Object.create(null),s=void 0),u=l=-1}else if(c===61&&u!==-1&&l===-1)a=t.slice(u,d),u=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(Gi[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1?u=d:i||(i=!0),r=!1}else if(o)if(Gi[c]===1)u===-1&&(u=d);else if(c===34&&u!==-1)o=!1,l=d;else if(c===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&Gi[c]===1)u===-1&&(u=d);else if(u!==-1&&(c===32||c===9))l===-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(u,l);i&&(h=h.replace(/\\/g,""),i=!1),pt(n,a,h),c===44&&(pt(e,s,n),n=Object.create(null),s=void 0),a=void 0,u=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(u===-1||o||c===32||c===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let f=t.slice(u,l);return s===void 0?pt(e,f,n):(a===void 0?pt(n,f,!0):i?pt(n,a,f.replace(/\\/g,"")):pt(n,a,f),pt(e,s,n)),e}function hP(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(r=>{let o=i[r];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?r:`${r}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bw.exports={format:hP,parse:fP}});var La=z((m2,Aw)=>{"use strict";var pP=ae("events"),mP=ae("https"),gP=ae("http"),ww=ae("net"),vP=ae("tls"),{randomBytes:yP,createHash:_P}=ae("crypto"),{Duplex:h2,Readable:p2}=ae("stream"),{URL:vm}=ae("url"),Xt=$n(),bP=fm(),$P=mm(),{isBlob:xP}=xn(),{BINARY_TYPES:$w,CLOSE_TIMEOUT:wP,EMPTY_BUFFER:Na,GUID:SP,kForOnEventAttribute:ym,kListener:kP,kStatusCode:IP,kWebSocket:ge,NOOP:Sw}=kt(),{EventTarget:{addEventListener:EP,removeEventListener:TP}}=_w(),{format:OP,parse:PP}=za(),{toBuffer:CP}=Fi(),kw=Symbol("kAborted"),_m=[8,13],Tt=["CONNECTING","OPEN","CLOSING","CLOSED"],AP=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,re=class t extends pP{constructor(e,n,i){super(),this._binaryType=$w[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Na,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),Iw(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){$w.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let r=new bP({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),o=new $P(e,this._extensions,i.generateMask);this._receiver=r,this._sender=o,this._socket=e,r[ge]=this,o[ge]=this,e[ge]=this,r.on("conclude",RP),r.on("drain",DP),r.on("error",LP),r.on("message",UP),r.on("ping",jP),r.on("pong",MP),o.onerror=FP,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Ow),e.on("data",Da),e.on("end",Pw),e.on("error",Cw),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Xt.extensionName]&&this._extensions[Xt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Tw(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bm(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Na,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bm(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Na,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bm(this,e,i);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Xt.extensionName]||(r.compress=!1),this._sender.send(e||Na,r,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(re,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")});Object.defineProperty(re.prototype,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")});Object.defineProperty(re,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")});Object.defineProperty(re.prototype,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")});Object.defineProperty(re,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")});Object.defineProperty(re.prototype,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")});Object.defineProperty(re,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")});Object.defineProperty(re.prototype,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(re.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(re.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ym])return e[kP];return null},set(e){for(let n of this.listeners(t))if(n[ym]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ym]:!0})}})});re.prototype.addEventListener=EP;re.prototype.removeEventListener=TP;Aw.exports=re;function Iw(t,e,n,i){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:wP,protocolVersion:_m[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=r.autoPong,t._closeTimeout=r.closeTimeout,!_m.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${_m.join(", ")})`);let o;if(e instanceof vm)o=e;else try{o=new vm(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",u;if(o.protocol!=="ws:"&&!s&&!a?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?u="The URL's pathname is empty":o.hash&&(u="The URL contains a fragment identifier"),u){let _=new SyntaxError(u);if(t._redirects===0)throw _;Ra(t,_);return}let c=s?443:80,l=yP(16).toString("base64"),d=s?mP.request:gP.request,f=new Set,h;if(r.createConnection=r.createConnection||(s?NP:zP),r.defaultPort=r.defaultPort||c,r.port=o.port||c,r.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},r.path=o.pathname+o.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(h=new Xt({...r.perMessageDeflate,isServer:!1,maxPayload:r.maxPayload}),r.headers["Sec-WebSocket-Extensions"]=OP({[Xt.extensionName]:h.offer()})),n.length){for(let _ of n){if(typeof _!="string"||!AP.test(_)||f.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(_)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(o.username||o.password)&&(r.auth=`${o.username}:${o.password}`),a){let _=r.path.split(":");r.socketPath=_[0],r.path=_[1]}let p;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?r.socketPath:o.host;let _=i&&i.headers;if(i={...i,headers:{}},_)for(let[S,k]of Object.entries(_))i.headers[S.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let _=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!_||t._originalSecure&&!s)&&(delete r.headers.authorization,delete r.headers.cookie,_||delete r.headers.host,r.auth=void 0)}r.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),p=t._req=d(r),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=d(r);r.timeout&&p.on("timeout",()=>{We(t,p,"Opening handshake has timed out")}),p.on("error",_=>{p===null||p[kw]||(p=t._req=null,Ra(t,_))}),p.on("response",_=>{let S=_.headers.location,k=_.statusCode;if(S&&r.followRedirects&&k>=300&&k<400){if(++t._redirects>r.maxRedirects){We(t,p,"Maximum redirects exceeded");return}p.abort();let C;try{C=new vm(S,e)}catch{let I=new SyntaxError(`Invalid URL: ${S}`);Ra(t,I);return}Iw(t,C,n,i)}else t.emit("unexpected-response",p,_)||We(t,p,`Unexpected server response: ${_.statusCode}`)}),p.on("upgrade",(_,S,k)=>{if(t.emit("upgrade",_),t.readyState!==re.CONNECTING)return;p=t._req=null;let C=_.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){We(t,S,"Invalid Upgrade header");return}let A=_P("sha1").update(l+SP).digest("base64");if(_.headers["sec-websocket-accept"]!==A){We(t,S,"Invalid Sec-WebSocket-Accept header");return}let I=_.headers["sec-websocket-protocol"],T;if(I!==void 0?f.size?f.has(I)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":f.size&&(T="Server sent no subprotocol"),T){We(t,S,T);return}I&&(t._protocol=I);let Z=_.headers["sec-websocket-extensions"];if(Z!==void 0){if(!h){We(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let F;try{F=PP(Z)}catch{We(t,S,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(F);if(W.length!==1||W[0]!==Xt.extensionName){We(t,S,"Server indicated an extension that was not requested");return}try{h.accept(F[Xt.extensionName])}catch{We(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Xt.extensionName]=h}t.setSocket(S,k,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(p,t):p.end()}function Ra(t,e){t._readyState=re.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function zP(t){return t.path=t.socketPath,ww.connect(t)}function NP(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ww.isIP(t.host)?"":t.host),vP.connect(t)}function We(t,e,n){t._readyState=re.CLOSING;let i=new Error(n);Error.captureStackTrace(i,We),e.setHeader?(e[kw]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ra,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function bm(t,e,n){if(e){let i=xP(e)?e.size:CP(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Tt[t.readyState]})`);process.nextTick(n,i)}}function RP(t,e){let n=this[ge];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ge]!==void 0&&(n._socket.removeListener("data",Da),process.nextTick(Ew,n._socket),t===1005?n.close():n.close(t,e))}function DP(){let t=this[ge];t.isPaused||t._socket.resume()}function LP(t){let e=this[ge];e._socket[ge]!==void 0&&(e._socket.removeListener("data",Da),process.nextTick(Ew,e._socket),e.close(t[IP])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function xw(){this[ge].emitClose()}function UP(t,e){this[ge].emit("message",t,e)}function jP(t){let e=this[ge];e._autoPong&&e.pong(t,!this._isServer,Sw),e.emit("ping",t)}function MP(t){this[ge].emit("pong",t)}function Ew(t){t.resume()}function FP(t){let e=this[ge];e.readyState!==re.CLOSED&&(e.readyState===re.OPEN&&(e._readyState=re.CLOSING,Tw(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Tw(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ow(){let t=this[ge];if(this.removeListener("close",Ow),this.removeListener("data",Da),this.removeListener("end",Pw),t._readyState=re.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ge]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",xw),t._receiver.on("finish",xw))}function Da(t){this[ge]._receiver.write(t)||this.pause()}function Pw(){let t=this[ge];t._readyState=re.CLOSING,t._receiver.end(),this.end()}function Cw(){let t=this[ge];this.removeListener("error",Cw),this.on("error",Sw),t&&(t._readyState=re.CLOSING,this.destroy())}});var Dw=z((v2,Rw)=>{"use strict";var g2=La(),{Duplex:VP}=ae("stream");function zw(t){t.emit("close")}function ZP(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Nw(t){this.removeListener("error",Nw),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function BP(t,e){let n=!0,i=new VP({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&i._readableState.objectMode?o.toString():o;i.push(a)||t.pause()}),t.once("error",function(o){i.destroyed||(n=!1,i.destroy(o))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(r,o){if(t.readyState===t.CLOSED){o(r),process.nextTick(zw,i);return}let s=!1;t.once("error",function(u){s=!0,o(u)}),t.once("close",function(){s||o(r),process.nextTick(zw,i)}),n&&t.terminate()},i._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(r,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(r,o,s)});return}t.send(r,s)},i.on("end",ZP),i.on("error",Nw),i}Rw.exports=BP});var $m=z((y2,Lw)=>{"use strict";var{tokenChars:GP}=xn();function WP(t){let e=new Set,n=-1,i=-1,r=0;for(r;r<t.length;r++){let s=t.charCodeAt(r);if(i===-1&&GP[s]===1)n===-1&&(n=r);else if(r!==0&&(s===32||s===9))i===-1&&n!==-1&&(i=r);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);i===-1&&(i=r);let a=t.slice(n,i);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,r);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Lw.exports={parse:WP}});var Bw=z((b2,Zw)=>{"use strict";var qP=ae("events"),Ua=ae("http"),{Duplex:_2}=ae("stream"),{createHash:HP}=ae("crypto"),Uw=za(),Sr=$n(),JP=$m(),KP=La(),{CLOSE_TIMEOUT:YP,GUID:XP,kWebSocket:QP}=kt(),eC=/^[+/0-9A-Za-z]{22}==$/,jw=0,Mw=1,Vw=2,xm=class extends qP{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:YP,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:KP,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ua.createServer((i,r)=>{let o=Ua.STATUS_CODES[426];r.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),r.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=tC(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,o,s)=>{this.handleUpgrade(r,o,s,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=jw}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Vw){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Wi,this);return}if(e&&this.once("close",e),this._state!==Mw)if(this._state=Mw,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Wi,this):process.nextTick(Wi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Wi(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,r){n.on("error",Fw);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){kr(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){kr(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!eC.test(o)){kr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){kr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){qi(n,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=JP.parse(u)}catch{kr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let f=new Sr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Uw.parse(l);h[Sr.extensionName]&&(f.accept(h[Sr.extensionName]),d[Sr.extensionName]=f)}catch{kr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,p,_,S)=>{if(!h)return qi(n,p||401,_,S);this.completeUpgrade(d,o,c,e,n,i,r)});return}if(!this.options.verifyClient(f))return qi(n,401)}this.completeUpgrade(d,o,c,e,n,i,r)}completeUpgrade(e,n,i,r,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[QP])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>jw)return qi(o,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${HP("sha1").update(n+XP).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(i.size){let d=this.options.handleProtocols?this.options.handleProtocols(i,r):i.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[Sr.extensionName]){let d=e[Sr.extensionName].params,f=Uw.format({[Sr.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",c,r),o.write(c.concat(`\r
121
121
  `).join(`\r
122
- `)),o.removeListener("error",Fw),l.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Wi,this)})),a(l,r)}};Zw.exports=xm;function eC(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function Wi(t){t._state=Vw,t.emit("close")}function Fw(){this.destroy()}function qi(t,e,n,i){n=n||Ua.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Ua.STATUS_CODES[e]}\r
122
+ `)),o.removeListener("error",Fw),l.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Wi,this)})),a(l,r)}};Zw.exports=xm;function tC(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function Wi(t){t._state=Vw,t.emit("close")}function Fw(){this.destroy()}function qi(t,e,n,i){n=n||Ua.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Ua.STATUS_CODES[e]}\r
123
123
  `+Object.keys(i).map(r=>`${r}: ${i[r]}`).join(`\r
124
124
  `)+`\r
125
125
  \r
126
- `+n)}function kr(t,e,n,i,r,o){if(t.listenerCount("wsClientError")){let s=new Error(r);Error.captureStackTrace(s,kr),t.emit("wsClientError",s,n,e)}else qi(n,i,r,o)}});var tC,rC,nC,iC,oC,sC,wm,aC,Gw=v(()=>{tC=Je(Dw(),1),rC=Je(za(),1),nC=Je($n(),1),iC=Je(fm(),1),oC=Je(mm(),1),sC=Je($m(),1),wm=Je(La(),1),aC=Je(Bw(),1)});function uC(t){return Array.isArray(t)?Buffer.concat(t).toString("utf8"):Buffer.isBuffer(t)?t.toString("utf8"):Buffer.from(t).toString("utf8")}var Sm,km=v(()=>{"use strict";Gw();Sm=(t,e)=>{let n=new wm.default(t,{headers:e});return{send:i=>n.send(i),close:()=>n.close(),onOpen:i=>{n.on("open",i)},onMessage:i=>{n.on("message",r=>i(uC(r)))},onError:i=>{n.on("error",i)},onClose:i=>{n.on("close",()=>i())}}}});var Hi,Im=v(()=>{"use strict";Qp();tm();km();Hi=class{socketFactory;constructor(e=Sm){this.socketFactory=e}asrEngine(e,n){if(e.provider==="elevenlabs")return new ji(n,this.socketFactory,e.model);throw new Error(`no stt adapter for provider '${e.provider}'`)}ttsEngine(e,n){if(e.provider==="elevenlabs")return new Mi(n,this.socketFactory,e.model);throw new Error(`no tts adapter for provider '${e.provider}'`)}}});import{randomUUID as cC}from"node:crypto";function Tm(t={}){let e=new pr;q.setLevel(e.logLevel),q.debug("core created",{logLevel:e.logLevel});let n={configService:t.configService??new Ge,registry:t.registry??new $i(t.fetchImpl),voiceRegistry:t.voiceRegistry??new Hi(t.voiceSocketFactory),...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 Em(n)}var lC,dC,Em,Ww=v(()=>{"use strict";De();Jh();Kh();ep();Lx();Im();lC="jarvis-core",dC="0.1.0-dev",Em=class{deps;constructor(e){this.deps=e}describe(){return Promise.resolve({name:lC,version:dC})}openSession(e){let n=cC();return q.debug("core opened session",{sessionId:n,capabilities:e.clientCapabilities}),Promise.resolve(new $a(n,e,this.deps))}}});function ja(t){return t>=200&&t<300?{ok:!0,status:"valid"}:t===401||t===403?{ok:!1,status:"invalid",detail:`key rejected (HTTP ${t})`}:{ok:!1,status:"unreachable",detail:`unexpected response (HTTP ${t})`}}function qw(t){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":t.message:"network error"}function En(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Om(t,e,n,i){let r=await n(t,{headers:e,signal:i});if(!r.ok)throw new Error(`HTTP ${r.status}`);try{return await r.json()}catch{throw new Error("invalid JSON response")}}function Pm(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&i.length>0&&(e[n]=i);if(Object.keys(e).length===0)throw new Error("catalogue curated to nothing");return e}function yC(t){return!/^gpt-(4\.1|4o|5)/.test(t)&&!/^o\d/.test(t)||vC.test(t)?!1:!/-(audio|realtime|transcribe|tts|image|search|codex|chat-latest|instruct|deep-research|pro)\b/.test(t)}var fC,hC,pC,mC,gC,vC,_C,bC,Hw,Tn,Cm=v(()=>{"use strict";fC=async(t,e,n)=>{let i=await e("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${t}`},signal:n});return ja(i.status)},hC=async(t,e,n)=>{let i=await e("https://api.anthropic.com/v1/models",{headers:{"x-api-key":t,"anthropic-version":"2023-06-01"},signal:n});return ja(i.status)},pC=async(t,e,n)=>{let i=await e("https://api.deepgram.com/v1/projects",{headers:{Authorization:`Token ${t}`},signal:n});return ja(i.status)},mC=async(t,e,n)=>{let i=await e("https://api.elevenlabs.io/v1/user",{headers:{"xi-api-key":t},signal:n});return i.status===401||i.status===403?{ok:!1,status:"unverifiable",detail:"an ElevenLabs key scoped to the voice endpoints cannot reach a free validation endpoint; it will be confirmed at first use"}:ja(i.status)};gC=async(t,e,n)=>{if(!t)throw new Error("API key required");let i=await Om("https://api.anthropic.com/v1/models?limit=100",{"x-api-key":t,"anthropic-version":"2023-06-01"},e,n),r=En(i)&&Array.isArray(i.data)?i.data:[],o=[];for(let s of r){if(!En(s)||typeof s.id!="string")continue;let a=typeof s.display_name=="string"?s.display_name:void 0;o.push(a===void 0?{id:s.id}:{id:s.id,label:a})}return Pm({text:o})},vC=/-\d{4}-\d{2}-\d{2}$/;_C=async(t,e,n)=>{if(!t)throw new Error("API key required");let i=await Om("https://api.openai.com/v1/models",{Authorization:`Bearer ${t}`},e,n),r=En(i)&&Array.isArray(i.data)?i.data:[],o=[];for(let a of r)En(a)&&typeof a.id=="string"&&o.push(a.id);o.sort();let s=a=>o.filter(a).map(u=>({id:u}));return Pm({text:s(yC),stt:s(a=>a==="whisper-1"||a.endsWith("-transcribe")),tts:s(a=>/^tts-1(-hd)?$/.test(a)||a.endsWith("-tts")),embedding:s(a=>a.startsWith("text-embedding-3-"))})},bC=async(t,e,n)=>{let i=await Om("https://api.deepgram.com/v1/models",{},e,n),r=En(i)&&Array.isArray(i.stt)?i.stt:[],o=new Set,s=[];for(let a of r){if(!En(a)||a.streaming!==!0)continue;let{canonical_name:u,architecture:c}=a;typeof u!="string"||typeof c!="string"||c.startsWith("nova-")&&(o.has(u)||(o.add(u),s.push({id:u,architecture:c})))}return s.sort((a,u)=>a.architecture===u.architecture?a.id.localeCompare(u.id,"en"):u.architecture.localeCompare(a.architecture,"en",{numeric:!0})),Pm({stt:s.map(({id:a})=>({id:a}))})},Hw={elevenlabs:{capabilities:["stt","tts"],defaultModel:{stt:"scribe_v2_realtime",tts:"eleven_flash_v2_5"},keyEnv:"ELEVENLABS_API_KEY",probe:mC},anthropic:{capabilities:["text"],defaultModel:{text:"claude-opus-4-8"},fastModel:{text:"claude-sonnet-5"},keyEnv:"ANTHROPIC_API_KEY",probe:hC,listModels:gC},openai:{capabilities:["text","stt","tts","embedding"],defaultModel:{text:"gpt-4o",stt:"whisper-1",tts:"tts-1",embedding:"text-embedding-3-small"},fastModel:{text:"gpt-4o-mini"},keyEnv:"OPENAI_API_KEY",probe:fC,listModels:_C},deepgram:{capabilities:["stt"],defaultModel:{stt:"nova-3-general"},keyEnv:"DEEPGRAM_API_KEY",probe:pC,listModels:bC,keylessLister:!0}},Tn=class{fetchImpl;timeoutMs=3e3;providers;constructor(e=fetch){this.fetchImpl=e,this.providers=Hw}async probe(e,n,i){let r=this.providers[e]?.probe;if(!r)return{ok:!1,status:"unimplemented",detail:`no probe for provider '${e}'`};let o=i?.signal??AbortSignal.timeout(this.timeoutMs);try{return await r(n,this.fetchImpl,o)}catch(s){return{ok:!1,status:"unreachable",detail:qw(s)}}}providersFor(e){return Object.keys(this.providers).filter(n=>this.providers[n].capabilities.includes(e))}defaultModel(e,n){return this.providers[e]?.defaultModel[n]}}});var $C,xC,U2,Jw=v(()=>{"use strict";hr();Cm();$C=1440*60*1e3,xC={stt:!0,tts:!0,text:!0,embedding:!0},U2=Object.keys(xC)});var Ma=v(()=>{"use strict";Ww();Kh();Cm();Jw();ep();Qh();tp();Xh();Yh();km();Qp();tm();Im();Hp();Fp();Vp();Gp();Ti();Rp();Np();ga();Bp();rp();np()});var Cn=z((WM,eS)=>{"use strict";var AC="2.0.0",zC=Number.MAX_SAFE_INTEGER||9007199254740991,NC=16,RC=250,DC=["major","premajor","minor","preminor","patch","prepatch","prerelease"];eS.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:NC,MAX_SAFE_BUILD_LENGTH:RC,MAX_SAFE_INTEGER:zC,RELEASE_TYPES:DC,SEMVER_SPEC_VERSION:AC,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Yi=z((qM,tS)=>{"use strict";var LC=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};tS.exports=LC});var An=z((gt,rS)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Nm,MAX_SAFE_BUILD_LENGTH:UC,MAX_LENGTH:jC}=Cn(),MC=Yi();gt=rS.exports={};var FC=gt.re=[],VC=gt.safeRe=[],O=gt.src=[],ZC=gt.safeSrc=[],P=gt.t={},BC=0,Rm="[a-zA-Z0-9-]",GC=[["\\s",1],["\\d",jC],[Rm,UC]],WC=t=>{for(let[e,n]of GC)t=t.split(`${e}*`).join(`${e}{0,${n}}`).split(`${e}+`).join(`${e}{1,${n}}`);return t},U=(t,e,n)=>{let i=WC(e),r=BC++;MC(t,r,e),P[t]=r,O[r]=e,ZC[r]=i,FC[r]=new RegExp(e,n?"g":void 0),VC[r]=new RegExp(i,n?"g":void 0)};U("NUMERICIDENTIFIER","0|[1-9]\\d*");U("NUMERICIDENTIFIERLOOSE","\\d+");U("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Rm}*`);U("MAINVERSION",`(${O[P.NUMERICIDENTIFIER]})\\.(${O[P.NUMERICIDENTIFIER]})\\.(${O[P.NUMERICIDENTIFIER]})`);U("MAINVERSIONLOOSE",`(${O[P.NUMERICIDENTIFIERLOOSE]})\\.(${O[P.NUMERICIDENTIFIERLOOSE]})\\.(${O[P.NUMERICIDENTIFIERLOOSE]})`);U("PRERELEASEIDENTIFIER",`(?:${O[P.NONNUMERICIDENTIFIER]}|${O[P.NUMERICIDENTIFIER]})`);U("PRERELEASEIDENTIFIERLOOSE",`(?:${O[P.NONNUMERICIDENTIFIER]}|${O[P.NUMERICIDENTIFIERLOOSE]})`);U("PRERELEASE",`(?:-(${O[P.PRERELEASEIDENTIFIER]}(?:\\.${O[P.PRERELEASEIDENTIFIER]})*))`);U("PRERELEASELOOSE",`(?:-?(${O[P.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${O[P.PRERELEASEIDENTIFIERLOOSE]})*))`);U("BUILDIDENTIFIER",`${Rm}+`);U("BUILD",`(?:\\+(${O[P.BUILDIDENTIFIER]}(?:\\.${O[P.BUILDIDENTIFIER]})*))`);U("FULLPLAIN",`v?${O[P.MAINVERSION]}${O[P.PRERELEASE]}?${O[P.BUILD]}?`);U("FULL",`^${O[P.FULLPLAIN]}$`);U("LOOSEPLAIN",`[v=\\s]*${O[P.MAINVERSIONLOOSE]}${O[P.PRERELEASELOOSE]}?${O[P.BUILD]}?`);U("LOOSE",`^${O[P.LOOSEPLAIN]}$`);U("GTLT","((?:<|>)?=?)");U("XRANGEIDENTIFIERLOOSE",`${O[P.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);U("XRANGEIDENTIFIER",`${O[P.NUMERICIDENTIFIER]}|x|X|\\*`);U("XRANGEPLAIN",`[v=\\s]*(${O[P.XRANGEIDENTIFIER]})(?:\\.(${O[P.XRANGEIDENTIFIER]})(?:\\.(${O[P.XRANGEIDENTIFIER]})(?:${O[P.PRERELEASE]})?${O[P.BUILD]}?)?)?`);U("XRANGEPLAINLOOSE",`[v=\\s]*(${O[P.XRANGEIDENTIFIERLOOSE]})(?:\\.(${O[P.XRANGEIDENTIFIERLOOSE]})(?:\\.(${O[P.XRANGEIDENTIFIERLOOSE]})(?:${O[P.PRERELEASELOOSE]})?${O[P.BUILD]}?)?)?`);U("XRANGE",`^${O[P.GTLT]}\\s*${O[P.XRANGEPLAIN]}$`);U("XRANGELOOSE",`^${O[P.GTLT]}\\s*${O[P.XRANGEPLAINLOOSE]}$`);U("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Nm}})(?:\\.(\\d{1,${Nm}}))?(?:\\.(\\d{1,${Nm}}))?`);U("COERCE",`${O[P.COERCEPLAIN]}(?:$|[^\\d])`);U("COERCEFULL",O[P.COERCEPLAIN]+`(?:${O[P.PRERELEASE]})?(?:${O[P.BUILD]})?(?:$|[^\\d])`);U("COERCERTL",O[P.COERCE],!0);U("COERCERTLFULL",O[P.COERCEFULL],!0);U("LONETILDE","(?:~>?)");U("TILDETRIM",`(\\s*)${O[P.LONETILDE]}\\s+`,!0);gt.tildeTrimReplace="$1~";U("TILDE",`^${O[P.LONETILDE]}${O[P.XRANGEPLAIN]}$`);U("TILDELOOSE",`^${O[P.LONETILDE]}${O[P.XRANGEPLAINLOOSE]}$`);U("LONECARET","(?:\\^)");U("CARETTRIM",`(\\s*)${O[P.LONECARET]}\\s+`,!0);gt.caretTrimReplace="$1^";U("CARET",`^${O[P.LONECARET]}${O[P.XRANGEPLAIN]}$`);U("CARETLOOSE",`^${O[P.LONECARET]}${O[P.XRANGEPLAINLOOSE]}$`);U("COMPARATORLOOSE",`^${O[P.GTLT]}\\s*(${O[P.LOOSEPLAIN]})$|^$`);U("COMPARATOR",`^${O[P.GTLT]}\\s*(${O[P.FULLPLAIN]})$|^$`);U("COMPARATORTRIM",`(\\s*)${O[P.GTLT]}\\s*(${O[P.LOOSEPLAIN]}|${O[P.XRANGEPLAIN]})`,!0);gt.comparatorTrimReplace="$1$2$3";U("HYPHENRANGE",`^\\s*(${O[P.XRANGEPLAIN]})\\s+-\\s+(${O[P.XRANGEPLAIN]})\\s*$`);U("HYPHENRANGELOOSE",`^\\s*(${O[P.XRANGEPLAINLOOSE]})\\s+-\\s+(${O[P.XRANGEPLAINLOOSE]})\\s*$`);U("STAR","(<|>)?=?\\s*\\*");U("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");U("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Ga=z((HM,nS)=>{"use strict";var qC=Object.freeze({loose:!0}),HC=Object.freeze({}),JC=t=>t?typeof t!="object"?qC:t:HC;nS.exports=JC});var Dm=z((JM,sS)=>{"use strict";var iS=/^[0-9]+$/,oS=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let n=iS.test(t),i=iS.test(e);return n&&i&&(t=+t,e=+e),t===e?0:n&&!i?-1:i&&!n?1:t<e?-1:1},KC=(t,e)=>oS(e,t);sS.exports={compareIdentifiers:oS,rcompareIdentifiers:KC}});var _e=z((KM,uS)=>{"use strict";var Wa=Yi(),{MAX_LENGTH:aS,MAX_SAFE_INTEGER:qa}=Cn(),{safeRe:Ha,t:Ja}=An(),YC=Ga(),{compareIdentifiers:Lm}=Dm(),XC=(t,e)=>{let n=e.split(".");if(n.length>t.length)return!1;for(let i=0;i<n.length;i++)if(Lm(t[i],n[i])!==0)return!1;return!0},Um=class t{constructor(e,n){if(n=YC(n),e instanceof t){if(e.loose===!!n.loose&&e.includePrerelease===!!n.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>aS)throw new TypeError(`version is longer than ${aS} characters`);Wa("SemVer",e,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let i=e.trim().match(n.loose?Ha[Ja.LOOSE]:Ha[Ja.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>qa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qa||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(r=>{if(/^[0-9]+$/.test(r)){let o=+r;if(o>=0&&o<qa)return o}return r}):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(Wa("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 n=0;do{let i=this.prerelease[n],r=e.prerelease[n];if(Wa("prerelease compare",n,i,r),i===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;if(i===r)continue;return Lm(i,r)}while(++n)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let n=0;do{let i=this.build[n],r=e.build[n];if(Wa("build compare",n,i,r),i===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;if(i===r)continue;return Lm(i,r)}while(++n)}inc(e,n,i){if(e.startsWith("pre")){if(!n&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(n){let r=`-${n}`.match(this.options.loose?Ha[Ja.PRERELEASELOOSE]:Ha[Ja.PRERELEASE]);if(!r||r[1]!==n)throw new Error(`invalid identifier: ${n}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,i),this.inc("pre",n,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",n,i),this.inc("pre",n,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 r=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[r];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(n===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(r)}}if(n){let o=[n,r];if(i===!1&&(o=[n]),XC(this.prerelease,n)){let s=this.prerelease[n.split(".").length];isNaN(s)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};uS.exports=Um});var Qt=z((YM,lS)=>{"use strict";var cS=_e(),QC=(t,e,n=!1)=>{if(t instanceof cS)return t;try{return new cS(t,e)}catch(i){if(!n)return null;throw i}};lS.exports=QC});var fS=z((XM,dS)=>{"use strict";var eA=Qt(),tA=(t,e)=>{let n=eA(t,e);return n?n.version:null};dS.exports=tA});var pS=z((QM,hS)=>{"use strict";var rA=Qt(),nA=(t,e)=>{let n=rA(t.trim().replace(/^[=v]+/,""),e);return n?n.version:null};hS.exports=nA});var vS=z((eF,gS)=>{"use strict";var mS=_e(),iA=(t,e,n,i,r)=>{typeof n=="string"&&(r=i,i=n,n=void 0);try{return new mS(t instanceof mS?t.version:t,n).inc(e,i,r).version}catch{return null}};gS.exports=iA});var bS=z((tF,_S)=>{"use strict";var yS=Qt(),oA=(t,e)=>{let n=yS(t,null,!0),i=yS(e,null,!0),r=n.compare(i);if(r===0)return null;let o=r>0,s=o?n:i,a=o?i:n,u=!!s.prerelease.length;if(!!a.prerelease.length&&!u){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let l=u?"pre":"";return n.major!==i.major?l+"major":n.minor!==i.minor?l+"minor":n.patch!==i.patch?l+"patch":"prerelease"};_S.exports=oA});var xS=z((rF,$S)=>{"use strict";var sA=_e(),aA=(t,e)=>new sA(t,e).major;$S.exports=aA});var SS=z((nF,wS)=>{"use strict";var uA=_e(),cA=(t,e)=>new uA(t,e).minor;wS.exports=cA});var IS=z((iF,kS)=>{"use strict";var lA=_e(),dA=(t,e)=>new lA(t,e).patch;kS.exports=dA});var TS=z((oF,ES)=>{"use strict";var fA=Qt(),hA=(t,e)=>{let n=fA(t,e);return n&&n.prerelease.length?n.prerelease:null};ES.exports=hA});var tt=z((sF,PS)=>{"use strict";var OS=_e(),pA=(t,e,n)=>new OS(t,n).compare(new OS(e,n));PS.exports=pA});var AS=z((aF,CS)=>{"use strict";var mA=tt(),gA=(t,e,n)=>mA(e,t,n);CS.exports=gA});var NS=z((uF,zS)=>{"use strict";var vA=tt(),yA=(t,e)=>vA(t,e,!0);zS.exports=yA});var Ka=z((cF,DS)=>{"use strict";var RS=_e(),_A=(t,e,n)=>{let i=new RS(t,n),r=new RS(e,n);return i.compare(r)||i.compareBuild(r)};DS.exports=_A});var US=z((lF,LS)=>{"use strict";var bA=Ka(),$A=(t,e)=>t.sort((n,i)=>bA(n,i,e));LS.exports=$A});var MS=z((dF,jS)=>{"use strict";var xA=Ka(),wA=(t,e)=>t.sort((n,i)=>xA(i,n,e));jS.exports=wA});var Xi=z((fF,FS)=>{"use strict";var SA=tt(),kA=(t,e,n)=>SA(t,e,n)>0;FS.exports=kA});var Ya=z((hF,VS)=>{"use strict";var IA=tt(),EA=(t,e,n)=>IA(t,e,n)<0;VS.exports=EA});var jm=z((pF,ZS)=>{"use strict";var TA=tt(),OA=(t,e,n)=>TA(t,e,n)===0;ZS.exports=OA});var Mm=z((mF,BS)=>{"use strict";var PA=tt(),CA=(t,e,n)=>PA(t,e,n)!==0;BS.exports=CA});var Xa=z((gF,GS)=>{"use strict";var AA=tt(),zA=(t,e,n)=>AA(t,e,n)>=0;GS.exports=zA});var Qa=z((vF,WS)=>{"use strict";var NA=tt(),RA=(t,e,n)=>NA(t,e,n)<=0;WS.exports=RA});var Fm=z((yF,qS)=>{"use strict";var DA=jm(),LA=Mm(),UA=Xi(),jA=Xa(),MA=Ya(),FA=Qa(),VA=(t,e,n,i)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t===n;case"!==":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t!==n;case"":case"=":case"==":return DA(t,n,i);case"!=":return LA(t,n,i);case">":return UA(t,n,i);case">=":return jA(t,n,i);case"<":return MA(t,n,i);case"<=":return FA(t,n,i);default:throw new TypeError(`Invalid operator: ${e}`)}};qS.exports=VA});var JS=z((_F,HS)=>{"use strict";var ZA=_e(),BA=Qt(),{safeRe:eu,t:tu}=An(),GA=(t,e)=>{if(t instanceof ZA)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let n=null;if(!e.rtl)n=t.match(e.includePrerelease?eu[tu.COERCEFULL]:eu[tu.COERCE]);else{let u=e.includePrerelease?eu[tu.COERCERTLFULL]:eu[tu.COERCERTL],c;for(;(c=u.exec(t))&&(!n||n.index+n[0].length!==t.length);)(!n||c.index+c[0].length!==n.index+n[0].length)&&(n=c),u.lastIndex=c.index+c[1].length+c[2].length;u.lastIndex=-1}if(n===null)return null;let i=n[2],r=n[3]||"0",o=n[4]||"0",s=e.includePrerelease&&n[5]?`-${n[5]}`:"",a=e.includePrerelease&&n[6]?`+${n[6]}`:"";return BA(`${i}.${r}.${o}${s}${a}`,e)};HS.exports=GA});var YS=z((bF,KS)=>{"use strict";var WA=Qt(),qA=Cn(),HA=_e(),JA=(t,e,n)=>{if(!qA.RELEASE_TYPES.includes(e))return null;let i=KA(t,n);return i&&YA(i,e)},KA=(t,e)=>{let n=t instanceof HA?t.version:t;return WA(n,e)},YA=(t,e)=>{if(XA(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()},XA=t=>t.startsWith("pre");KS.exports=JA});var QS=z(($F,XS)=>{"use strict";var Vm=class{constructor(){this.max=1e3,this.map=new Map}get(e){let n=this.map.get(e);if(n!==void 0)return this.map.delete(e),this.map.set(e,n),n}delete(e){return this.map.delete(e)}set(e,n){if(!this.delete(e)&&n!==void 0){if(this.map.size>=this.max){let r=this.map.keys().next().value;this.delete(r)}this.map.set(e,n)}return this}};XS.exports=Vm});var rt=z((xF,n0)=>{"use strict";var QA=/\s+/g,Zm=class t{constructor(e,n){if(n=tz(n),e instanceof t)return e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease?e:new t(e.raw,n);if(e instanceof Bm)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=e.trim().replace(QA," "),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(r=>!t0(r[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let r of this.set)if(r.length===1&&lz(r[0])){this.set=[r];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 n=this.set[e];for(let i=0;i<n.length;i++)i>0&&(this.formatted+=" "),this.formatted+=n[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(cz,"");let i=((this.options.includePrerelease&&az)|(this.options.loose&&uz))+":"+e,r=e0.get(i);if(r)return r;let o=this.options.loose,s=o?Pe[be.HYPHENRANGELOOSE]:Pe[be.HYPHENRANGE];e=e.replace(s,bz(this.options.includePrerelease)),te("hyphen replace",e),e=e.replace(Pe[be.COMPARATORTRIM],iz),te("comparator trim",e),e=e.replace(Pe[be.TILDETRIM],oz),te("tilde trim",e),e=e.replace(Pe[be.CARETTRIM],sz),te("caret trim",e);let a=e.split(" ").map(d=>dz(d,this.options)).join(" ").split(/\s+/).map(d=>_z(d,this.options));o&&(a=a.filter(d=>(te("loose invalid filter",d,this.options),!!d.match(Pe[be.COMPARATORLOOSE])))),te("range list",a);let u=new Map,c=a.map(d=>new Bm(d,this.options));for(let d of c){if(t0(d))return[d];u.set(d.value,d)}u.size>1&&u.has("")&&u.delete("");let l=[...u.values()];return e0.set(i,l),l}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(i=>r0(i,n)&&e.set.some(r=>r0(r,n)&&i.every(o=>r.every(s=>o.intersects(s,n)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new rz(e,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if($z(this.set[n],e,this.options))return!0;return!1}};n0.exports=Zm;var ez=QS(),e0=new ez,tz=Ga(),Bm=Qi(),te=Yi(),rz=_e(),{safeRe:Pe,src:nz,t:be,comparatorTrimReplace:iz,tildeTrimReplace:oz,caretTrimReplace:sz}=An(),{FLAG_INCLUDE_PRERELEASE:az,FLAG_LOOSE:uz}=Cn(),cz=new RegExp(nz[be.BUILD],"g"),t0=t=>t.value==="<0.0.0-0",lz=t=>t.value==="",r0=(t,e)=>{let n=!0,i=t.slice(),r=i.pop();for(;n&&i.length;)n=i.every(o=>r.intersects(o,e)),r=i.pop();return n},dz=(t,e)=>(t=t.replace(Pe[be.BUILD],""),te("comp",t,e),t=pz(t,e),te("caret",t),t=fz(t,e),te("tildes",t),t=gz(t,e),te("xrange",t),t=yz(t,e),te("stars",t),t),Ce=t=>!t||t.toLowerCase()==="x"||t==="*",fz=(t,e)=>t.trim().split(/\s+/).map(n=>hz(n,e)).join(" "),hz=(t,e)=>{let n=e.loose?Pe[be.TILDELOOSE]:Pe[be.TILDE];return t.replace(n,(i,r,o,s,a)=>{te("tilde",t,i,r,o,s,a);let u;return Ce(r)?u="":Ce(o)?u=`>=${r}.0.0 <${+r+1}.0.0-0`:Ce(s)?u=`>=${r}.${o}.0 <${r}.${+o+1}.0-0`:a?(te("replaceTilde pr",a),u=`>=${r}.${o}.${s}-${a} <${r}.${+o+1}.0-0`):u=`>=${r}.${o}.${s} <${r}.${+o+1}.0-0`,te("tilde return",u),u})},pz=(t,e)=>t.trim().split(/\s+/).map(n=>mz(n,e)).join(" "),mz=(t,e)=>{te("caret",t,e);let n=e.loose?Pe[be.CARETLOOSE]:Pe[be.CARET],i=e.includePrerelease?"-0":"";return t.replace(n,(r,o,s,a,u)=>{te("caret",t,r,o,s,a,u);let c;return Ce(o)?c="":Ce(s)?c=`>=${o}.0.0${i} <${+o+1}.0.0-0`:Ce(a)?o==="0"?c=`>=${o}.${s}.0${i} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.0${i} <${+o+1}.0.0-0`:u?(te("replaceCaret pr",u),o==="0"?s==="0"?c=`>=${o}.${s}.${a}-${u} <${o}.${s}.${+a+1}-0`:c=`>=${o}.${s}.${a}-${u} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.${a}-${u} <${+o+1}.0.0-0`):(te("no pr"),o==="0"?s==="0"?c=`>=${o}.${s}.${a}${i} <${o}.${s}.${+a+1}-0`:c=`>=${o}.${s}.${a}${i} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),te("caret return",c),c})},gz=(t,e)=>(te("replaceXRanges",t,e),t.split(/\s+/).map(n=>vz(n,e)).join(" ")),vz=(t,e)=>{t=t.trim();let n=e.loose?Pe[be.XRANGELOOSE]:Pe[be.XRANGE];return t.replace(n,(i,r,o,s,a,u)=>{te("xRange",t,i,r,o,s,a,u);let c=Ce(o),l=c||Ce(s),d=l||Ce(a),f=d;return r==="="&&f&&(r=""),u=e.includePrerelease?"-0":"",c?r===">"||r==="<"?i="<0.0.0-0":i="*":r&&f?(l&&(s=0),a=0,r===">"?(r=">=",l?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):r==="<="&&(r="<",l?o=+o+1:s=+s+1),r==="<"&&(u="-0"),i=`${r+o}.${s}.${a}${u}`):l?i=`>=${o}.0.0${u} <${+o+1}.0.0-0`:d&&(i=`>=${o}.${s}.0${u} <${o}.${+s+1}.0-0`),te("xRange return",i),i})},yz=(t,e)=>(te("replaceStars",t,e),t.trim().replace(Pe[be.STAR],"")),_z=(t,e)=>(te("replaceGTE0",t,e),t.trim().replace(Pe[e.includePrerelease?be.GTE0PRE:be.GTE0],"")),bz=t=>(e,n,i,r,o,s,a,u,c,l,d,f)=>(Ce(i)?n="":Ce(r)?n=`>=${i}.0.0${t?"-0":""}`:Ce(o)?n=`>=${i}.${r}.0${t?"-0":""}`:s?n=`>=${n}`:n=`>=${n}${t?"-0":""}`,Ce(c)?u="":Ce(l)?u=`<${+c+1}.0.0-0`:Ce(d)?u=`<${c}.${+l+1}.0-0`:f?u=`<=${c}.${l}.${d}-${f}`:t?u=`<${c}.${l}.${+d+1}-0`:u=`<=${u}`,`${n} ${u}`.trim()),$z=(t,e,n)=>{for(let i=0;i<t.length;i++)if(!t[i].test(e))return!1;if(e.prerelease.length&&!n.includePrerelease){for(let i=0;i<t.length;i++)if(te(t[i].semver),t[i].semver!==Bm.ANY&&t[i].semver.prerelease.length>0){let r=t[i].semver;if(r.major===e.major&&r.minor===e.minor&&r.patch===e.patch)return!0}return!1}return!0}});var Qi=z((wF,c0)=>{"use strict";var eo=Symbol("SemVer ANY"),qm=class t{static get ANY(){return eo}constructor(e,n){if(n=i0(n),e instanceof t){if(e.loose===!!n.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Wm("comparator",e,n),this.options=n,this.loose=!!n.loose,this.parse(e),this.semver===eo?this.value="":this.value=this.operator+this.semver.version,Wm("comp",this)}parse(e){let n=this.options.loose?o0[s0.COMPARATORLOOSE]:o0[s0.COMPARATOR],i=e.match(n);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 a0(i[2],this.options.loose):this.semver=eo}toString(){return this.value}test(e){if(Wm("Comparator.test",e,this.options.loose),this.semver===eo||e===eo)return!0;if(typeof e=="string")try{e=new a0(e,this.options)}catch{return!1}return Gm(e,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u0(e.value,n).test(this.value):e.operator===""?e.value===""?!0:new u0(this.value,n).test(e.semver):(n=i0(n),n.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!n.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("=")||Gm(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Gm(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};c0.exports=qm;var i0=Ga(),{safeRe:o0,t:s0}=An(),Gm=Fm(),Wm=Yi(),a0=_e(),u0=rt()});var to=z((SF,l0)=>{"use strict";var xz=rt(),wz=(t,e,n)=>{try{e=new xz(e,n)}catch{return!1}return e.test(t)};l0.exports=wz});var f0=z((kF,d0)=>{"use strict";var Sz=rt(),kz=(t,e)=>new Sz(t,e).set.map(n=>n.map(i=>i.value).join(" ").trim().split(" "));d0.exports=kz});var p0=z((IF,h0)=>{"use strict";var Iz=_e(),Ez=rt(),Tz=(t,e,n)=>{let i=null,r=null,o=null;try{o=new Ez(e,n)}catch{return null}return t.forEach(s=>{o.test(s)&&(!i||r.compare(s)===-1)&&(i=s,r=new Iz(i,n))}),i};h0.exports=Tz});var g0=z((EF,m0)=>{"use strict";var Oz=_e(),Pz=rt(),Cz=(t,e,n)=>{let i=null,r=null,o=null;try{o=new Pz(e,n)}catch{return null}return t.forEach(s=>{o.test(s)&&(!i||r.compare(s)===1)&&(i=s,r=new Oz(i,n))}),i};m0.exports=Cz});var _0=z((TF,y0)=>{"use strict";var Hm=_e(),Az=rt(),v0=Xi(),zz=(t,e)=>{t=new Az(t,e);let n=new Hm("0.0.0");if(t.test(n)||(n=new Hm("0.0.0-0"),t.test(n)))return n;n=null;for(let i=0;i<t.set.length;++i){let r=t.set[i],o=null;r.forEach(s=>{let a=new Hm(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||v0(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),o&&(!n||v0(n,o))&&(n=o)}return n&&t.test(n)?n:null};y0.exports=zz});var $0=z((OF,b0)=>{"use strict";var Nz=rt(),Rz=(t,e)=>{try{return new Nz(t,e).range||"*"}catch{return null}};b0.exports=Rz});var ru=z((PF,k0)=>{"use strict";var Dz=_e(),S0=Qi(),{ANY:Lz}=S0,Uz=rt(),jz=to(),x0=Xi(),w0=Ya(),Mz=Qa(),Fz=Xa(),Vz=(t,e,n,i)=>{t=new Dz(t,i),e=new Uz(e,i);let r,o,s,a,u;switch(n){case">":r=x0,o=Mz,s=w0,a=">",u=">=";break;case"<":r=w0,o=Fz,s=x0,a="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(jz(t,e,i))return!1;for(let c=0;c<e.set.length;++c){let l=e.set[c],d=null,f=null;if(l.forEach(h=>{h.semver===Lz&&(h=new S0(">=0.0.0")),d=d||h,f=f||h,r(h.semver,d.semver,i)?d=h:s(h.semver,f.semver,i)&&(f=h)}),d.operator===a||d.operator===u||(!f.operator||f.operator===a)&&o(t,f.semver))return!1;if(f.operator===u&&s(t,f.semver))return!1}return!0};k0.exports=Vz});var E0=z((CF,I0)=>{"use strict";var Zz=ru(),Bz=(t,e,n)=>Zz(t,e,">",n);I0.exports=Bz});var O0=z((AF,T0)=>{"use strict";var Gz=ru(),Wz=(t,e,n)=>Gz(t,e,"<",n);T0.exports=Wz});var A0=z((zF,C0)=>{"use strict";var P0=rt(),qz=(t,e,n)=>(t=new P0(t,n),e=new P0(e,n),t.intersects(e,n));C0.exports=qz});var N0=z((NF,z0)=>{"use strict";var Hz=to(),Jz=tt();z0.exports=(t,e,n)=>{let i=[],r=null,o=null,s=t.sort((l,d)=>Jz(l,d,n));for(let l of s)Hz(l,e,n)?(o=l,r||(r=l)):(o&&i.push([r,o]),o=null,r=null);r&&i.push([r,null]);let a=[];for(let[l,d]of i)l===d?a.push(l):!d&&l===s[0]?a.push("*"):d?l===s[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);let u=a.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return u.length<c.length?u:e}});var M0=z((RF,j0)=>{"use strict";var R0=rt(),Ym=Qi(),{ANY:Jm}=Ym,Km=to(),Xm=tt(),Kz=(t,e,n={})=>{if(t===e)return!0;t=new R0(t,n),e=new R0(e,n);let i=!1;e:for(let r of t.set){for(let o of e.set){let s=Xz(r,o,n);if(i=i||s!==null,s)continue e}if(i)return!1}return!0},Yz=[new Ym(">=0.0.0-0")],D0=[new Ym(">=0.0.0")],Xz=(t,e,n)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===Jm){if(e.length===1&&e[0].semver===Jm)return!0;n.includePrerelease?t=Yz:t=D0}if(e.length===1&&e[0].semver===Jm){if(n.includePrerelease)return!0;e=D0}let i=new Set,r,o;for(let h of t)h.operator===">"||h.operator===">="?r=L0(r,h,n):h.operator==="<"||h.operator==="<="?o=U0(o,h,n):i.add(h.semver);if(i.size>1)return null;let s;if(r&&o){if(s=Xm(r.semver,o.semver,n),s>0)return null;if(s===0&&(r.operator!==">="||o.operator!=="<="))return null}for(let h of i){if(r&&!Km(h,String(r),n)||o&&!Km(h,String(o),n))return null;for(let p of e)if(!Km(h,String(p),n))return!1;return!0}let a,u,c,l,d=o&&!n.includePrerelease&&o.semver.prerelease.length?o.semver:!1,f=r&&!n.includePrerelease&&r.semver.prerelease.length?r.semver:!1;d&&d.prerelease.length===1&&o.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let h of e){if(l=l||h.operator===">"||h.operator===">=",c=c||h.operator==="<"||h.operator==="<=",r){if(f&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===f.major&&h.semver.minor===f.minor&&h.semver.patch===f.patch&&(f=!1),h.operator===">"||h.operator===">="){if(a=L0(r,h,n),a===h&&a!==r)return!1}else if(r.operator===">="&&!h.test(r.semver))return!1}if(o){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator==="<"||h.operator==="<="){if(u=U0(o,h,n),u===h&&u!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||r)&&s!==0)return!1}return!(r&&c&&!o&&s!==0||o&&l&&!r&&s!==0||f||d)},L0=(t,e,n)=>{if(!t)return e;let i=Xm(t.semver,e.semver,n);return i>0?t:i<0||e.operator===">"&&t.operator===">="?e:t},U0=(t,e,n)=>{if(!t)return e;let i=Xm(t.semver,e.semver,n);return i<0?t:i>0||e.operator==="<"&&t.operator==="<="?e:t};j0.exports=Kz});var B0=z((DF,Z0)=>{"use strict";var Qm=An(),F0=Cn(),Qz=_e(),V0=Dm(),eN=Qt(),tN=fS(),rN=pS(),nN=vS(),iN=bS(),oN=xS(),sN=SS(),aN=IS(),uN=TS(),cN=tt(),lN=AS(),dN=NS(),fN=Ka(),hN=US(),pN=MS(),mN=Xi(),gN=Ya(),vN=jm(),yN=Mm(),_N=Xa(),bN=Qa(),$N=Fm(),xN=JS(),wN=YS(),SN=Qi(),kN=rt(),IN=to(),EN=f0(),TN=p0(),ON=g0(),PN=_0(),CN=$0(),AN=ru(),zN=E0(),NN=O0(),RN=A0(),DN=N0(),LN=M0();Z0.exports={parse:eN,valid:tN,clean:rN,inc:nN,diff:iN,major:oN,minor:sN,patch:aN,prerelease:uN,compare:cN,rcompare:lN,compareLoose:dN,compareBuild:fN,sort:hN,rsort:pN,gt:mN,lt:gN,eq:vN,neq:yN,gte:_N,lte:bN,cmp:$N,coerce:xN,truncate:wN,Comparator:SN,Range:kN,satisfies:IN,toComparators:EN,maxSatisfying:TN,minSatisfying:ON,minVersion:PN,validRange:CN,outside:AN,gtr:zN,ltr:NN,intersects:RN,simplifyRange:DN,subset:LN,SemVer:Qz,re:Qm.re,src:Qm.src,tokens:Qm.t,SEMVER_SPEC_VERSION:F0.SEMVER_SPEC_VERSION,RELEASE_TYPES:F0.RELEASE_TYPES,compareIdentifiers:V0.compareIdentifiers,rcompareIdentifiers:V0.rcompareIdentifiers}});var J0=z((GF,eg)=>{var ou=process||{},q0=ou.argv||[],iu=ou.env||{},FN=!(iu.NO_COLOR||q0.includes("--no-color"))&&(!!iu.FORCE_COLOR||q0.includes("--color")||ou.platform==="win32"||(ou.stdout||{}).isTTY&&iu.TERM!=="dumb"||!!iu.CI),VN=(t,e,n=t)=>i=>{let r=""+i,o=r.indexOf(e,t.length);return~o?t+ZN(r,e,n,o)+e:t+r+e},ZN=(t,e,n,i)=>{let r="",o=0;do r+=t.substring(o,i)+n,o=i+e.length,i=t.indexOf(e,o);while(~i);return r+t.substring(o)},H0=(t=FN)=>{let e=t?VN:()=>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")}};eg.exports=H0();eg.exports.createColors=H0});var sg=z((vV,pk)=>{"use strict";var og={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},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"},fR={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},hR={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 n=0;n<t;n++)e+=this.line+(n<t-1?og.up():"");return t&&(e+=og.left),e}};pk.exports={cursor:og,scroll:fR,erase:hR,beep:"\x07"}});function iI(t,e){if(e<=1)return t;let n=Math.floor(t.length/e),i=new Int16Array(n);for(let r=0;r<n;r++){let o=0,s=r*e;for(let a=0;a<e;a++)o+=t[s+a];i[r]=Math.round(o/e)}return i}var Iu,oI=v(()=>{"use strict";Iu=class{step;pos=0;prev=0;primed=!1;constructor(e,n){if(e<=0||n<=0)throw new RangeError("resampler rates must be positive");this.step=e/n}process(e){if(e.length===0)return new Int16Array(0);let n=[],i=e.length-1,r=this.primed?this.pos:0;for(;;){let o=Math.floor(r);if(o+1>i)break;let s=o<0?this.prev:e[o],a=e[o+1];n.push(Math.round(s+(a-s)*(r-o))),r+=this.step}return this.prev=e[i],this.primed=!0,this.pos=r-e.length,Int16Array.from(n)}}});function aI(t){return t.byteLength/2/u4}function c4(t){let e=t.byteLength>>1,n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let r=0;r<e;r++)i[r]=n.getInt16(r*2,!0);return i}var sI,u4,Eu,uI=v(()=>{"use strict";De();Ma();sI=32,u4=16,Eu=class{constructor(e,n,i={}){this.vad=e;this.onSpeech=n;this.speechThreshold=i.speechThreshold??.5,this.onsetMs=i.onsetMs??2*sI,this.holdoffMs=i.holdoffMs??300,this.energyThreshold=i.energyThreshold??.01,this.log=i.log??q}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(Bt(e,this.energyThreshold),aI(e));return}this.vad.process(c4(e)).then(n=>{if(!this.closed)for(let i of n)this.applyVerdict(i>=this.speechThreshold,sI)},n=>{this.closed||(this.degrade(n),this.applyVerdict(Bt(e,this.energyThreshold),aI(e)))})}}close(){this.closed=!0}applyVerdict(e,n){e?(this.silenceRunMs=0,this.speechRunMs+=n,!this.inSpeech&&this.speechRunMs>=this.onsetMs&&(this.inSpeech=!0,this.onSpeech())):(this.speechRunMs=0,this.inSpeech&&(this.silenceRunMs+=n,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 kg={};He(kg,{DecibriCapture:()=>wg,DecibriPlayback:()=>Sg,hasInputDevice:()=>f4});import{Microphone as l4,Speaker as d4,inputDevices as lI}from"decibri";function f4(){try{return lI().length>0}catch(t){return q.debug("audio input enumeration failed; treating as no microphone",{error:t}),!1}}function h4(){try{let t=lI(),e=t.find(n=>n.isDefault)??t[0];if(e&&e.defaultSampleRate>=1e3&&e.maxInputChannels>=1)return{sampleRate:Math.round(e.defaultSampleRate),channels:e.maxInputChannels}}catch(t){q.debug("could not read default input device; opening at 16k mono",{error:t})}return{sampleRate:co,channels:Tu}}function p4(t){return Math.max(64,Math.min(65536,Math.round(t/10)))}function m4(t,e,n){let i=new Uint8Array(t),r=new Int16Array(i.buffer,0,i.byteLength>>1),o=n.process(iI(r,e));return Buffer.from(o.buffer,o.byteOffset,o.byteLength)}function y4(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}var co,Tu,dI,cI,wg,g4,v4,Sg,Ig=v(()=>{"use strict";De();Ma();oI();uI();co=16e3,Tu=1,dI="int16",cI=.01;wg=class{constructor(e={}){this.deps=e}deps;mic=null;onData=null;onSpeech=null;onErr=null;vad=null;detector=null;async start(e){let{sampleRate:n,channels:i}=h4(),r=(this.deps.createVad??(()=>new _r))(),o=null;try{await r.load(),o=new Eu(r,()=>e.onSpeechStart(),{energyThreshold:cI})}catch(u){q.debug("silero vad unavailable; barge-in falls back to decibri energy vad",{error:u}),r.dispose().catch(()=>{})}let s;try{s=await l4.open({sampleRate:n,channels:i,dtype:dI,...o?{vad:!1}:{vad:"energy",vadThreshold:cI},framesPerBuffer:p4(n)})}catch(u){throw o?.close(),o&&r.dispose().catch(()=>{}),u}this.vad=o?r:null,this.detector=o;let a=n===co&&i===Tu?null:new Iu(n,co);this.onData=a?u=>{let c=m4(u,i,a);c.byteLength>0&&(this.detector?.feed(c),e.onFrame(c,Date.now()))}:u=>{this.detector?.feed(u),e.onFrame(u,Date.now())},this.onSpeech=()=>e.onSpeechStart(),this.onErr=u=>e.onError(u),s.on("data",this.onData),s.on("speech",this.onSpeech),s.on("error",this.onErr),this.mic=s}async stop(){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 n=this.vad;this.vad=null,n&&await n.dispose().catch(()=>{})}},g4=co*Tu*2/1e3,v4=250,Sg=class{speaker=null;writeChain=Promise.resolve();generation=0;closed=!1;playoutEndAtMs=0;drainWakes=new Set;play(e){if(this.closed)return;let n=this.generation;this.writeChain=this.writeChain.then(async()=>{if(!(this.closed||n!==this.generation))try{if(await this.ensureSpeaker().writeAsync(y4(e)),this.closed||n!==this.generation)return;this.playoutEndAtMs=Math.max(this.playoutEndAtMs,Date.now())+e.byteLength/g4}catch(i){q.debug("playback write skipped",{error:i})}})}flush(){this.generation++,this.playoutEndAtMs=0;let e=this.speaker;this.speaker=null,e?.stop();for(let n of[...this.drainWakes])n()}async drained(){await this.writeChain;let e=this.speaker;if(!e)return;let n=Promise.resolve().then(()=>e.drainAsync()).catch(s=>{q.debug("playback drain interrupted",{error:s})}),i=Math.max(0,this.playoutEndAtMs-Date.now())+v4,r=this.sleep(i);await Promise.race([n,r.done]),r.wake();let o=this.playoutEndAtMs-Date.now();o>0&&await this.sleep(o).done}sleep(e){let n;return{done:new Promise(r=>{let o=setTimeout(()=>n(),e);n=()=>{clearTimeout(o),this.drainWakes.delete(n),r()},this.drainWakes.add(n)}),wake:n}}close(){return this.closed=!0,this.flush(),Promise.resolve()}ensureSpeaker(){return this.speaker??=new d4({sampleRate:co,channels:Tu,dtype:dI}),this.speaker}}});De();Ma();xi();import{readFileSync as _4}from"node:fs";import{randomUUID as b4}from"node:crypto";var mt=class extends Error{constructor(e,n,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},Ot=class extends mt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Ji=class{constructor(e,n){switch(this.description=n||"",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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Ot(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Fa(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}import{EventEmitter as IC}from"node:events";import zm from"node:child_process";import Pt from"node:path";import Za from"node:fs";import B from"node:process";import{stripVTControlCharacters as EC}from"node:util";import{stripVTControlCharacters as wC}from"node:util";var Ki=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 n=e.commands.filter(r=>!r._hidden),i=e._getHelpCommand();return i&&!i._hidden&&n.push(i),this.sortSubcommands&&n.sort((r,o)=>r.name().localeCompare(o.name())),n}compareOptions(e,n){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(e).localeCompare(i(n))}visibleOptions(e){let n=e.options.filter(r=>!r.hidden),i=e._getHelpOption();if(i&&!i.hidden){let r=i.short&&e._findOption(i.short),o=i.long&&e._findOption(i.long);!r&&!o?n.push(i):i.long&&!o?n.push(e.createOption(i.long,i.description)):i.short&&!r&&n.push(e.createOption(i.short,i.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let i=e.parent;i;i=i.parent){let r=i.options.filter(o=>!o.hidden);n.push(...r)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(i=>Fa(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(r)))),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(r)))),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(r)))),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let i="";for(let r=e.parent;r;r=r.parent)i=r.name()+" "+i;return i+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatItemList(e,n,i){return n.length===0?[]:[i.styleTitle(e),...n,""]}groupItems(e,n,i){let r=new Map;return e.forEach(o=>{let s=i(o);r.has(s)||r.set(s,[])}),n.forEach(o=>{let s=i(o);r.has(s)||r.set(s,[]),r.get(s).push(o)}),r}formatHelp(e,n){let i=n.padWidth(e,n),r=n.helpWidth??80;function o(d,f){return n.formatItem(d,i,f,n)}let s=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(e))}`,""],a=n.commandDescription(e);a.length>0&&(s=s.concat([n.boxWrap(n.styleCommandDescription(a),r),""]));let u=n.visibleArguments(e).map(d=>o(n.styleArgumentTerm(n.argumentTerm(d)),n.styleArgumentDescription(n.argumentDescription(d))));if(s=s.concat(this.formatItemList("Arguments:",u,n)),this.groupItems(e.options,n.visibleOptions(e),d=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let h=d.map(p=>o(n.styleOptionTerm(n.optionTerm(p)),n.styleOptionDescription(n.optionDescription(p))));s=s.concat(this.formatItemList(f,h,n))}),n.showGlobalOptions){let d=n.visibleGlobalOptions(e).map(f=>o(n.styleOptionTerm(n.optionTerm(f)),n.styleOptionDescription(n.optionDescription(f))));s=s.concat(this.formatItemList("Global Options:",d,n))}return this.groupItems(e.commands,n.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,f)=>{let h=d.map(p=>o(n.styleSubcommandTerm(n.subcommandTerm(p)),n.styleSubcommandDescription(n.subcommandDescription(p))));s=s.concat(this.formatItemList(f,h,n))}),s.join(`
127
- `)}displayWidth(e){return wC(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).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(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).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,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,n,i,r){let s=" ".repeat(2);if(!i)return s+e;let a=e.padEnd(n+e.length-r.displayWidth(e)),u=2,l=(this.helpWidth??80)-n-u-2,d;return l<this.minWidthToWrap||r.preformatted(i)?d=i:d=r.boxWrap(i,l).replace(/\n/g,`
126
+ `+n)}function kr(t,e,n,i,r,o){if(t.listenerCount("wsClientError")){let s=new Error(r);Error.captureStackTrace(s,kr),t.emit("wsClientError",s,n,e)}else qi(n,i,r,o)}});var rC,nC,iC,oC,sC,aC,wm,uC,Gw=v(()=>{rC=Je(Dw(),1),nC=Je(za(),1),iC=Je($n(),1),oC=Je(fm(),1),sC=Je(mm(),1),aC=Je($m(),1),wm=Je(La(),1),uC=Je(Bw(),1)});function cC(t){return Array.isArray(t)?Buffer.concat(t).toString("utf8"):Buffer.isBuffer(t)?t.toString("utf8"):Buffer.from(t).toString("utf8")}var Sm,km=v(()=>{"use strict";Gw();Sm=(t,e)=>{let n=new wm.default(t,{headers:e});return{send:i=>n.send(i),close:()=>n.close(),onOpen:i=>{n.on("open",i)},onMessage:i=>{n.on("message",r=>i(cC(r)))},onError:i=>{n.on("error",i)},onClose:i=>{n.on("close",()=>i())}}}});var Hi,Im=v(()=>{"use strict";Qp();tm();km();Hi=class{socketFactory;constructor(e=Sm){this.socketFactory=e}asrEngine(e,n){if(e.provider==="elevenlabs")return new ji(n,this.socketFactory,e.model);throw new Error(`no stt adapter for provider '${e.provider}'`)}ttsEngine(e,n){if(e.provider==="elevenlabs")return new Mi(n,this.socketFactory,e.model);throw new Error(`no tts adapter for provider '${e.provider}'`)}}});import{randomUUID as lC}from"node:crypto";function Tm(t={}){let e=new pr;q.setLevel(e.logLevel),q.debug("core created",{logLevel:e.logLevel});let n={configService:t.configService??new Ge,registry:t.registry??new $i(t.fetchImpl),voiceRegistry:t.voiceRegistry??new Hi(t.voiceSocketFactory),...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 Em(n)}var dC,fC,Em,Ww=v(()=>{"use strict";De();Jh();Kh();ep();Lx();Im();dC="jarvis-core",fC="0.1.0-dev",Em=class{deps;constructor(e){this.deps=e}describe(){return Promise.resolve({name:dC,version:fC})}openSession(e){let n=lC();return q.debug("core opened session",{sessionId:n,capabilities:e.clientCapabilities}),Promise.resolve(new $a(n,e,this.deps))}}});function ja(t){return t>=200&&t<300?{ok:!0,status:"valid"}:t===401||t===403?{ok:!1,status:"invalid",detail:`key rejected (HTTP ${t})`}:{ok:!1,status:"unreachable",detail:`unexpected response (HTTP ${t})`}}function qw(t){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":t.message:"network error"}function En(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Om(t,e,n,i){let r=await n(t,{headers:e,signal:i});if(!r.ok)throw new Error(`HTTP ${r.status}`);try{return await r.json()}catch{throw new Error("invalid JSON response")}}function Pm(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&i.length>0&&(e[n]=i);if(Object.keys(e).length===0)throw new Error("catalogue curated to nothing");return e}function _C(t){return!/^gpt-(4\.1|4o|5)/.test(t)&&!/^o\d/.test(t)||yC.test(t)?!1:!/-(audio|realtime|transcribe|tts|image|search|codex|chat-latest|instruct|deep-research|pro)\b/.test(t)}var hC,pC,mC,gC,vC,yC,bC,$C,Hw,Tn,Cm=v(()=>{"use strict";hC=async(t,e,n)=>{let i=await e("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${t}`},signal:n});return ja(i.status)},pC=async(t,e,n)=>{let i=await e("https://api.anthropic.com/v1/models",{headers:{"x-api-key":t,"anthropic-version":"2023-06-01"},signal:n});return ja(i.status)},mC=async(t,e,n)=>{let i=await e("https://api.deepgram.com/v1/projects",{headers:{Authorization:`Token ${t}`},signal:n});return ja(i.status)},gC=async(t,e,n)=>{let i=await e("https://api.elevenlabs.io/v1/user",{headers:{"xi-api-key":t},signal:n});return i.status===401||i.status===403?{ok:!1,status:"unverifiable",detail:"an ElevenLabs key scoped to the voice endpoints cannot reach a free validation endpoint; it will be confirmed at first use"}:ja(i.status)};vC=async(t,e,n)=>{if(!t)throw new Error("API key required");let i=await Om("https://api.anthropic.com/v1/models?limit=100",{"x-api-key":t,"anthropic-version":"2023-06-01"},e,n),r=En(i)&&Array.isArray(i.data)?i.data:[],o=[];for(let s of r){if(!En(s)||typeof s.id!="string")continue;let a=typeof s.display_name=="string"?s.display_name:void 0;o.push(a===void 0?{id:s.id}:{id:s.id,label:a})}return Pm({text:o})},yC=/-\d{4}-\d{2}-\d{2}$/;bC=async(t,e,n)=>{if(!t)throw new Error("API key required");let i=await Om("https://api.openai.com/v1/models",{Authorization:`Bearer ${t}`},e,n),r=En(i)&&Array.isArray(i.data)?i.data:[],o=[];for(let a of r)En(a)&&typeof a.id=="string"&&o.push(a.id);o.sort();let s=a=>o.filter(a).map(u=>({id:u}));return Pm({text:s(_C),stt:s(a=>a==="whisper-1"||a.endsWith("-transcribe")),tts:s(a=>/^tts-1(-hd)?$/.test(a)||a.endsWith("-tts")),embedding:s(a=>a.startsWith("text-embedding-3-"))})},$C=async(t,e,n)=>{let i=await Om("https://api.deepgram.com/v1/models",{},e,n),r=En(i)&&Array.isArray(i.stt)?i.stt:[],o=new Set,s=[];for(let a of r){if(!En(a)||a.streaming!==!0)continue;let{canonical_name:u,architecture:c}=a;typeof u!="string"||typeof c!="string"||c.startsWith("nova-")&&(o.has(u)||(o.add(u),s.push({id:u,architecture:c})))}return s.sort((a,u)=>a.architecture===u.architecture?a.id.localeCompare(u.id,"en"):u.architecture.localeCompare(a.architecture,"en",{numeric:!0})),Pm({stt:s.map(({id:a})=>({id:a}))})},Hw={elevenlabs:{capabilities:["stt","tts"],defaultModel:{stt:"scribe_v2_realtime",tts:"eleven_flash_v2_5"},keyEnv:"ELEVENLABS_API_KEY",probe:gC},anthropic:{capabilities:["text"],defaultModel:{text:"claude-opus-4-8"},fastModel:{text:"claude-sonnet-5"},keyEnv:"ANTHROPIC_API_KEY",probe:pC,listModels:vC},openai:{capabilities:["text","stt","tts","embedding"],defaultModel:{text:"gpt-4o",stt:"whisper-1",tts:"tts-1",embedding:"text-embedding-3-small"},fastModel:{text:"gpt-4o-mini"},keyEnv:"OPENAI_API_KEY",probe:hC,listModels:bC},deepgram:{capabilities:["stt"],defaultModel:{stt:"nova-3-general"},keyEnv:"DEEPGRAM_API_KEY",probe:mC,listModels:$C,keylessLister:!0}},Tn=class{fetchImpl;timeoutMs=3e3;providers;constructor(e=fetch){this.fetchImpl=e,this.providers=Hw}async probe(e,n,i){let r=this.providers[e]?.probe;if(!r)return{ok:!1,status:"unimplemented",detail:`no probe for provider '${e}'`};let o=i?.signal??AbortSignal.timeout(this.timeoutMs);try{return await r(n,this.fetchImpl,o)}catch(s){return{ok:!1,status:"unreachable",detail:qw(s)}}}providersFor(e){return Object.keys(this.providers).filter(n=>this.providers[n].capabilities.includes(e))}defaultModel(e,n){return this.providers[e]?.defaultModel[n]}}});var xC,wC,j2,Jw=v(()=>{"use strict";hr();Cm();xC=1440*60*1e3,wC={stt:!0,tts:!0,text:!0,embedding:!0},j2=Object.keys(wC)});var Ma=v(()=>{"use strict";Ww();Kh();Cm();Jw();ep();Qh();tp();Xh();Yh();km();Qp();tm();Im();Hp();Fp();Vp();Gp();Ti();Rp();Np();ga();Bp();rp();np()});var Cn=z((qM,eS)=>{"use strict";var zC="2.0.0",NC=Number.MAX_SAFE_INTEGER||9007199254740991,RC=16,DC=250,LC=["major","premajor","minor","preminor","patch","prepatch","prerelease"];eS.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:RC,MAX_SAFE_BUILD_LENGTH:DC,MAX_SAFE_INTEGER:NC,RELEASE_TYPES:LC,SEMVER_SPEC_VERSION:zC,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Yi=z((HM,tS)=>{"use strict";var UC=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};tS.exports=UC});var An=z((gt,rS)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Nm,MAX_SAFE_BUILD_LENGTH:jC,MAX_LENGTH:MC}=Cn(),FC=Yi();gt=rS.exports={};var VC=gt.re=[],ZC=gt.safeRe=[],O=gt.src=[],BC=gt.safeSrc=[],P=gt.t={},GC=0,Rm="[a-zA-Z0-9-]",WC=[["\\s",1],["\\d",MC],[Rm,jC]],qC=t=>{for(let[e,n]of WC)t=t.split(`${e}*`).join(`${e}{0,${n}}`).split(`${e}+`).join(`${e}{1,${n}}`);return t},U=(t,e,n)=>{let i=qC(e),r=GC++;FC(t,r,e),P[t]=r,O[r]=e,BC[r]=i,VC[r]=new RegExp(e,n?"g":void 0),ZC[r]=new RegExp(i,n?"g":void 0)};U("NUMERICIDENTIFIER","0|[1-9]\\d*");U("NUMERICIDENTIFIERLOOSE","\\d+");U("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Rm}*`);U("MAINVERSION",`(${O[P.NUMERICIDENTIFIER]})\\.(${O[P.NUMERICIDENTIFIER]})\\.(${O[P.NUMERICIDENTIFIER]})`);U("MAINVERSIONLOOSE",`(${O[P.NUMERICIDENTIFIERLOOSE]})\\.(${O[P.NUMERICIDENTIFIERLOOSE]})\\.(${O[P.NUMERICIDENTIFIERLOOSE]})`);U("PRERELEASEIDENTIFIER",`(?:${O[P.NONNUMERICIDENTIFIER]}|${O[P.NUMERICIDENTIFIER]})`);U("PRERELEASEIDENTIFIERLOOSE",`(?:${O[P.NONNUMERICIDENTIFIER]}|${O[P.NUMERICIDENTIFIERLOOSE]})`);U("PRERELEASE",`(?:-(${O[P.PRERELEASEIDENTIFIER]}(?:\\.${O[P.PRERELEASEIDENTIFIER]})*))`);U("PRERELEASELOOSE",`(?:-?(${O[P.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${O[P.PRERELEASEIDENTIFIERLOOSE]})*))`);U("BUILDIDENTIFIER",`${Rm}+`);U("BUILD",`(?:\\+(${O[P.BUILDIDENTIFIER]}(?:\\.${O[P.BUILDIDENTIFIER]})*))`);U("FULLPLAIN",`v?${O[P.MAINVERSION]}${O[P.PRERELEASE]}?${O[P.BUILD]}?`);U("FULL",`^${O[P.FULLPLAIN]}$`);U("LOOSEPLAIN",`[v=\\s]*${O[P.MAINVERSIONLOOSE]}${O[P.PRERELEASELOOSE]}?${O[P.BUILD]}?`);U("LOOSE",`^${O[P.LOOSEPLAIN]}$`);U("GTLT","((?:<|>)?=?)");U("XRANGEIDENTIFIERLOOSE",`${O[P.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);U("XRANGEIDENTIFIER",`${O[P.NUMERICIDENTIFIER]}|x|X|\\*`);U("XRANGEPLAIN",`[v=\\s]*(${O[P.XRANGEIDENTIFIER]})(?:\\.(${O[P.XRANGEIDENTIFIER]})(?:\\.(${O[P.XRANGEIDENTIFIER]})(?:${O[P.PRERELEASE]})?${O[P.BUILD]}?)?)?`);U("XRANGEPLAINLOOSE",`[v=\\s]*(${O[P.XRANGEIDENTIFIERLOOSE]})(?:\\.(${O[P.XRANGEIDENTIFIERLOOSE]})(?:\\.(${O[P.XRANGEIDENTIFIERLOOSE]})(?:${O[P.PRERELEASELOOSE]})?${O[P.BUILD]}?)?)?`);U("XRANGE",`^${O[P.GTLT]}\\s*${O[P.XRANGEPLAIN]}$`);U("XRANGELOOSE",`^${O[P.GTLT]}\\s*${O[P.XRANGEPLAINLOOSE]}$`);U("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Nm}})(?:\\.(\\d{1,${Nm}}))?(?:\\.(\\d{1,${Nm}}))?`);U("COERCE",`${O[P.COERCEPLAIN]}(?:$|[^\\d])`);U("COERCEFULL",O[P.COERCEPLAIN]+`(?:${O[P.PRERELEASE]})?(?:${O[P.BUILD]})?(?:$|[^\\d])`);U("COERCERTL",O[P.COERCE],!0);U("COERCERTLFULL",O[P.COERCEFULL],!0);U("LONETILDE","(?:~>?)");U("TILDETRIM",`(\\s*)${O[P.LONETILDE]}\\s+`,!0);gt.tildeTrimReplace="$1~";U("TILDE",`^${O[P.LONETILDE]}${O[P.XRANGEPLAIN]}$`);U("TILDELOOSE",`^${O[P.LONETILDE]}${O[P.XRANGEPLAINLOOSE]}$`);U("LONECARET","(?:\\^)");U("CARETTRIM",`(\\s*)${O[P.LONECARET]}\\s+`,!0);gt.caretTrimReplace="$1^";U("CARET",`^${O[P.LONECARET]}${O[P.XRANGEPLAIN]}$`);U("CARETLOOSE",`^${O[P.LONECARET]}${O[P.XRANGEPLAINLOOSE]}$`);U("COMPARATORLOOSE",`^${O[P.GTLT]}\\s*(${O[P.LOOSEPLAIN]})$|^$`);U("COMPARATOR",`^${O[P.GTLT]}\\s*(${O[P.FULLPLAIN]})$|^$`);U("COMPARATORTRIM",`(\\s*)${O[P.GTLT]}\\s*(${O[P.LOOSEPLAIN]}|${O[P.XRANGEPLAIN]})`,!0);gt.comparatorTrimReplace="$1$2$3";U("HYPHENRANGE",`^\\s*(${O[P.XRANGEPLAIN]})\\s+-\\s+(${O[P.XRANGEPLAIN]})\\s*$`);U("HYPHENRANGELOOSE",`^\\s*(${O[P.XRANGEPLAINLOOSE]})\\s+-\\s+(${O[P.XRANGEPLAINLOOSE]})\\s*$`);U("STAR","(<|>)?=?\\s*\\*");U("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");U("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Ga=z((JM,nS)=>{"use strict";var HC=Object.freeze({loose:!0}),JC=Object.freeze({}),KC=t=>t?typeof t!="object"?HC:t:JC;nS.exports=KC});var Dm=z((KM,sS)=>{"use strict";var iS=/^[0-9]+$/,oS=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let n=iS.test(t),i=iS.test(e);return n&&i&&(t=+t,e=+e),t===e?0:n&&!i?-1:i&&!n?1:t<e?-1:1},YC=(t,e)=>oS(e,t);sS.exports={compareIdentifiers:oS,rcompareIdentifiers:YC}});var _e=z((YM,uS)=>{"use strict";var Wa=Yi(),{MAX_LENGTH:aS,MAX_SAFE_INTEGER:qa}=Cn(),{safeRe:Ha,t:Ja}=An(),XC=Ga(),{compareIdentifiers:Lm}=Dm(),QC=(t,e)=>{let n=e.split(".");if(n.length>t.length)return!1;for(let i=0;i<n.length;i++)if(Lm(t[i],n[i])!==0)return!1;return!0},Um=class t{constructor(e,n){if(n=XC(n),e instanceof t){if(e.loose===!!n.loose&&e.includePrerelease===!!n.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>aS)throw new TypeError(`version is longer than ${aS} characters`);Wa("SemVer",e,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let i=e.trim().match(n.loose?Ha[Ja.LOOSE]:Ha[Ja.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>qa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qa||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(r=>{if(/^[0-9]+$/.test(r)){let o=+r;if(o>=0&&o<qa)return o}return r}):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(Wa("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 n=0;do{let i=this.prerelease[n],r=e.prerelease[n];if(Wa("prerelease compare",n,i,r),i===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;if(i===r)continue;return Lm(i,r)}while(++n)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let n=0;do{let i=this.build[n],r=e.build[n];if(Wa("build compare",n,i,r),i===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;if(i===r)continue;return Lm(i,r)}while(++n)}inc(e,n,i){if(e.startsWith("pre")){if(!n&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(n){let r=`-${n}`.match(this.options.loose?Ha[Ja.PRERELEASELOOSE]:Ha[Ja.PRERELEASE]);if(!r||r[1]!==n)throw new Error(`invalid identifier: ${n}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,i),this.inc("pre",n,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",n,i),this.inc("pre",n,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 r=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[r];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(n===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(r)}}if(n){let o=[n,r];if(i===!1&&(o=[n]),QC(this.prerelease,n)){let s=this.prerelease[n.split(".").length];isNaN(s)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};uS.exports=Um});var Qt=z((XM,lS)=>{"use strict";var cS=_e(),eA=(t,e,n=!1)=>{if(t instanceof cS)return t;try{return new cS(t,e)}catch(i){if(!n)return null;throw i}};lS.exports=eA});var fS=z((QM,dS)=>{"use strict";var tA=Qt(),rA=(t,e)=>{let n=tA(t,e);return n?n.version:null};dS.exports=rA});var pS=z((eF,hS)=>{"use strict";var nA=Qt(),iA=(t,e)=>{let n=nA(t.trim().replace(/^[=v]+/,""),e);return n?n.version:null};hS.exports=iA});var vS=z((tF,gS)=>{"use strict";var mS=_e(),oA=(t,e,n,i,r)=>{typeof n=="string"&&(r=i,i=n,n=void 0);try{return new mS(t instanceof mS?t.version:t,n).inc(e,i,r).version}catch{return null}};gS.exports=oA});var bS=z((rF,_S)=>{"use strict";var yS=Qt(),sA=(t,e)=>{let n=yS(t,null,!0),i=yS(e,null,!0),r=n.compare(i);if(r===0)return null;let o=r>0,s=o?n:i,a=o?i:n,u=!!s.prerelease.length;if(!!a.prerelease.length&&!u){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let l=u?"pre":"";return n.major!==i.major?l+"major":n.minor!==i.minor?l+"minor":n.patch!==i.patch?l+"patch":"prerelease"};_S.exports=sA});var xS=z((nF,$S)=>{"use strict";var aA=_e(),uA=(t,e)=>new aA(t,e).major;$S.exports=uA});var SS=z((iF,wS)=>{"use strict";var cA=_e(),lA=(t,e)=>new cA(t,e).minor;wS.exports=lA});var IS=z((oF,kS)=>{"use strict";var dA=_e(),fA=(t,e)=>new dA(t,e).patch;kS.exports=fA});var TS=z((sF,ES)=>{"use strict";var hA=Qt(),pA=(t,e)=>{let n=hA(t,e);return n&&n.prerelease.length?n.prerelease:null};ES.exports=pA});var tt=z((aF,PS)=>{"use strict";var OS=_e(),mA=(t,e,n)=>new OS(t,n).compare(new OS(e,n));PS.exports=mA});var AS=z((uF,CS)=>{"use strict";var gA=tt(),vA=(t,e,n)=>gA(e,t,n);CS.exports=vA});var NS=z((cF,zS)=>{"use strict";var yA=tt(),_A=(t,e)=>yA(t,e,!0);zS.exports=_A});var Ka=z((lF,DS)=>{"use strict";var RS=_e(),bA=(t,e,n)=>{let i=new RS(t,n),r=new RS(e,n);return i.compare(r)||i.compareBuild(r)};DS.exports=bA});var US=z((dF,LS)=>{"use strict";var $A=Ka(),xA=(t,e)=>t.sort((n,i)=>$A(n,i,e));LS.exports=xA});var MS=z((fF,jS)=>{"use strict";var wA=Ka(),SA=(t,e)=>t.sort((n,i)=>wA(i,n,e));jS.exports=SA});var Xi=z((hF,FS)=>{"use strict";var kA=tt(),IA=(t,e,n)=>kA(t,e,n)>0;FS.exports=IA});var Ya=z((pF,VS)=>{"use strict";var EA=tt(),TA=(t,e,n)=>EA(t,e,n)<0;VS.exports=TA});var jm=z((mF,ZS)=>{"use strict";var OA=tt(),PA=(t,e,n)=>OA(t,e,n)===0;ZS.exports=PA});var Mm=z((gF,BS)=>{"use strict";var CA=tt(),AA=(t,e,n)=>CA(t,e,n)!==0;BS.exports=AA});var Xa=z((vF,GS)=>{"use strict";var zA=tt(),NA=(t,e,n)=>zA(t,e,n)>=0;GS.exports=NA});var Qa=z((yF,WS)=>{"use strict";var RA=tt(),DA=(t,e,n)=>RA(t,e,n)<=0;WS.exports=DA});var Fm=z((_F,qS)=>{"use strict";var LA=jm(),UA=Mm(),jA=Xi(),MA=Xa(),FA=Ya(),VA=Qa(),ZA=(t,e,n,i)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t===n;case"!==":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t!==n;case"":case"=":case"==":return LA(t,n,i);case"!=":return UA(t,n,i);case">":return jA(t,n,i);case">=":return MA(t,n,i);case"<":return FA(t,n,i);case"<=":return VA(t,n,i);default:throw new TypeError(`Invalid operator: ${e}`)}};qS.exports=ZA});var JS=z((bF,HS)=>{"use strict";var BA=_e(),GA=Qt(),{safeRe:eu,t:tu}=An(),WA=(t,e)=>{if(t instanceof BA)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let n=null;if(!e.rtl)n=t.match(e.includePrerelease?eu[tu.COERCEFULL]:eu[tu.COERCE]);else{let u=e.includePrerelease?eu[tu.COERCERTLFULL]:eu[tu.COERCERTL],c;for(;(c=u.exec(t))&&(!n||n.index+n[0].length!==t.length);)(!n||c.index+c[0].length!==n.index+n[0].length)&&(n=c),u.lastIndex=c.index+c[1].length+c[2].length;u.lastIndex=-1}if(n===null)return null;let i=n[2],r=n[3]||"0",o=n[4]||"0",s=e.includePrerelease&&n[5]?`-${n[5]}`:"",a=e.includePrerelease&&n[6]?`+${n[6]}`:"";return GA(`${i}.${r}.${o}${s}${a}`,e)};HS.exports=WA});var YS=z(($F,KS)=>{"use strict";var qA=Qt(),HA=Cn(),JA=_e(),KA=(t,e,n)=>{if(!HA.RELEASE_TYPES.includes(e))return null;let i=YA(t,n);return i&&XA(i,e)},YA=(t,e)=>{let n=t instanceof JA?t.version:t;return qA(n,e)},XA=(t,e)=>{if(QA(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()},QA=t=>t.startsWith("pre");KS.exports=KA});var QS=z((xF,XS)=>{"use strict";var Vm=class{constructor(){this.max=1e3,this.map=new Map}get(e){let n=this.map.get(e);if(n!==void 0)return this.map.delete(e),this.map.set(e,n),n}delete(e){return this.map.delete(e)}set(e,n){if(!this.delete(e)&&n!==void 0){if(this.map.size>=this.max){let r=this.map.keys().next().value;this.delete(r)}this.map.set(e,n)}return this}};XS.exports=Vm});var rt=z((wF,n0)=>{"use strict";var ez=/\s+/g,Zm=class t{constructor(e,n){if(n=rz(n),e instanceof t)return e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease?e:new t(e.raw,n);if(e instanceof Bm)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=e.trim().replace(ez," "),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(r=>!t0(r[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let r of this.set)if(r.length===1&&dz(r[0])){this.set=[r];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 n=this.set[e];for(let i=0;i<n.length;i++)i>0&&(this.formatted+=" "),this.formatted+=n[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(lz,"");let i=((this.options.includePrerelease&&uz)|(this.options.loose&&cz))+":"+e,r=e0.get(i);if(r)return r;let o=this.options.loose,s=o?Pe[be.HYPHENRANGELOOSE]:Pe[be.HYPHENRANGE];e=e.replace(s,$z(this.options.includePrerelease)),te("hyphen replace",e),e=e.replace(Pe[be.COMPARATORTRIM],oz),te("comparator trim",e),e=e.replace(Pe[be.TILDETRIM],sz),te("tilde trim",e),e=e.replace(Pe[be.CARETTRIM],az),te("caret trim",e);let a=e.split(" ").map(d=>fz(d,this.options)).join(" ").split(/\s+/).map(d=>bz(d,this.options));o&&(a=a.filter(d=>(te("loose invalid filter",d,this.options),!!d.match(Pe[be.COMPARATORLOOSE])))),te("range list",a);let u=new Map,c=a.map(d=>new Bm(d,this.options));for(let d of c){if(t0(d))return[d];u.set(d.value,d)}u.size>1&&u.has("")&&u.delete("");let l=[...u.values()];return e0.set(i,l),l}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(i=>r0(i,n)&&e.set.some(r=>r0(r,n)&&i.every(o=>r.every(s=>o.intersects(s,n)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new nz(e,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if(xz(this.set[n],e,this.options))return!0;return!1}};n0.exports=Zm;var tz=QS(),e0=new tz,rz=Ga(),Bm=Qi(),te=Yi(),nz=_e(),{safeRe:Pe,src:iz,t:be,comparatorTrimReplace:oz,tildeTrimReplace:sz,caretTrimReplace:az}=An(),{FLAG_INCLUDE_PRERELEASE:uz,FLAG_LOOSE:cz}=Cn(),lz=new RegExp(iz[be.BUILD],"g"),t0=t=>t.value==="<0.0.0-0",dz=t=>t.value==="",r0=(t,e)=>{let n=!0,i=t.slice(),r=i.pop();for(;n&&i.length;)n=i.every(o=>r.intersects(o,e)),r=i.pop();return n},fz=(t,e)=>(t=t.replace(Pe[be.BUILD],""),te("comp",t,e),t=mz(t,e),te("caret",t),t=hz(t,e),te("tildes",t),t=vz(t,e),te("xrange",t),t=_z(t,e),te("stars",t),t),Ce=t=>!t||t.toLowerCase()==="x"||t==="*",hz=(t,e)=>t.trim().split(/\s+/).map(n=>pz(n,e)).join(" "),pz=(t,e)=>{let n=e.loose?Pe[be.TILDELOOSE]:Pe[be.TILDE];return t.replace(n,(i,r,o,s,a)=>{te("tilde",t,i,r,o,s,a);let u;return Ce(r)?u="":Ce(o)?u=`>=${r}.0.0 <${+r+1}.0.0-0`:Ce(s)?u=`>=${r}.${o}.0 <${r}.${+o+1}.0-0`:a?(te("replaceTilde pr",a),u=`>=${r}.${o}.${s}-${a} <${r}.${+o+1}.0-0`):u=`>=${r}.${o}.${s} <${r}.${+o+1}.0-0`,te("tilde return",u),u})},mz=(t,e)=>t.trim().split(/\s+/).map(n=>gz(n,e)).join(" "),gz=(t,e)=>{te("caret",t,e);let n=e.loose?Pe[be.CARETLOOSE]:Pe[be.CARET],i=e.includePrerelease?"-0":"";return t.replace(n,(r,o,s,a,u)=>{te("caret",t,r,o,s,a,u);let c;return Ce(o)?c="":Ce(s)?c=`>=${o}.0.0${i} <${+o+1}.0.0-0`:Ce(a)?o==="0"?c=`>=${o}.${s}.0${i} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.0${i} <${+o+1}.0.0-0`:u?(te("replaceCaret pr",u),o==="0"?s==="0"?c=`>=${o}.${s}.${a}-${u} <${o}.${s}.${+a+1}-0`:c=`>=${o}.${s}.${a}-${u} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.${a}-${u} <${+o+1}.0.0-0`):(te("no pr"),o==="0"?s==="0"?c=`>=${o}.${s}.${a}${i} <${o}.${s}.${+a+1}-0`:c=`>=${o}.${s}.${a}${i} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),te("caret return",c),c})},vz=(t,e)=>(te("replaceXRanges",t,e),t.split(/\s+/).map(n=>yz(n,e)).join(" ")),yz=(t,e)=>{t=t.trim();let n=e.loose?Pe[be.XRANGELOOSE]:Pe[be.XRANGE];return t.replace(n,(i,r,o,s,a,u)=>{te("xRange",t,i,r,o,s,a,u);let c=Ce(o),l=c||Ce(s),d=l||Ce(a),f=d;return r==="="&&f&&(r=""),u=e.includePrerelease?"-0":"",c?r===">"||r==="<"?i="<0.0.0-0":i="*":r&&f?(l&&(s=0),a=0,r===">"?(r=">=",l?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):r==="<="&&(r="<",l?o=+o+1:s=+s+1),r==="<"&&(u="-0"),i=`${r+o}.${s}.${a}${u}`):l?i=`>=${o}.0.0${u} <${+o+1}.0.0-0`:d&&(i=`>=${o}.${s}.0${u} <${o}.${+s+1}.0-0`),te("xRange return",i),i})},_z=(t,e)=>(te("replaceStars",t,e),t.trim().replace(Pe[be.STAR],"")),bz=(t,e)=>(te("replaceGTE0",t,e),t.trim().replace(Pe[e.includePrerelease?be.GTE0PRE:be.GTE0],"")),$z=t=>(e,n,i,r,o,s,a,u,c,l,d,f)=>(Ce(i)?n="":Ce(r)?n=`>=${i}.0.0${t?"-0":""}`:Ce(o)?n=`>=${i}.${r}.0${t?"-0":""}`:s?n=`>=${n}`:n=`>=${n}${t?"-0":""}`,Ce(c)?u="":Ce(l)?u=`<${+c+1}.0.0-0`:Ce(d)?u=`<${c}.${+l+1}.0-0`:f?u=`<=${c}.${l}.${d}-${f}`:t?u=`<${c}.${l}.${+d+1}-0`:u=`<=${u}`,`${n} ${u}`.trim()),xz=(t,e,n)=>{for(let i=0;i<t.length;i++)if(!t[i].test(e))return!1;if(e.prerelease.length&&!n.includePrerelease){for(let i=0;i<t.length;i++)if(te(t[i].semver),t[i].semver!==Bm.ANY&&t[i].semver.prerelease.length>0){let r=t[i].semver;if(r.major===e.major&&r.minor===e.minor&&r.patch===e.patch)return!0}return!1}return!0}});var Qi=z((SF,c0)=>{"use strict";var eo=Symbol("SemVer ANY"),qm=class t{static get ANY(){return eo}constructor(e,n){if(n=i0(n),e instanceof t){if(e.loose===!!n.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Wm("comparator",e,n),this.options=n,this.loose=!!n.loose,this.parse(e),this.semver===eo?this.value="":this.value=this.operator+this.semver.version,Wm("comp",this)}parse(e){let n=this.options.loose?o0[s0.COMPARATORLOOSE]:o0[s0.COMPARATOR],i=e.match(n);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 a0(i[2],this.options.loose):this.semver=eo}toString(){return this.value}test(e){if(Wm("Comparator.test",e,this.options.loose),this.semver===eo||e===eo)return!0;if(typeof e=="string")try{e=new a0(e,this.options)}catch{return!1}return Gm(e,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u0(e.value,n).test(this.value):e.operator===""?e.value===""?!0:new u0(this.value,n).test(e.semver):(n=i0(n),n.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!n.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("=")||Gm(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Gm(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};c0.exports=qm;var i0=Ga(),{safeRe:o0,t:s0}=An(),Gm=Fm(),Wm=Yi(),a0=_e(),u0=rt()});var to=z((kF,l0)=>{"use strict";var wz=rt(),Sz=(t,e,n)=>{try{e=new wz(e,n)}catch{return!1}return e.test(t)};l0.exports=Sz});var f0=z((IF,d0)=>{"use strict";var kz=rt(),Iz=(t,e)=>new kz(t,e).set.map(n=>n.map(i=>i.value).join(" ").trim().split(" "));d0.exports=Iz});var p0=z((EF,h0)=>{"use strict";var Ez=_e(),Tz=rt(),Oz=(t,e,n)=>{let i=null,r=null,o=null;try{o=new Tz(e,n)}catch{return null}return t.forEach(s=>{o.test(s)&&(!i||r.compare(s)===-1)&&(i=s,r=new Ez(i,n))}),i};h0.exports=Oz});var g0=z((TF,m0)=>{"use strict";var Pz=_e(),Cz=rt(),Az=(t,e,n)=>{let i=null,r=null,o=null;try{o=new Cz(e,n)}catch{return null}return t.forEach(s=>{o.test(s)&&(!i||r.compare(s)===1)&&(i=s,r=new Pz(i,n))}),i};m0.exports=Az});var _0=z((OF,y0)=>{"use strict";var Hm=_e(),zz=rt(),v0=Xi(),Nz=(t,e)=>{t=new zz(t,e);let n=new Hm("0.0.0");if(t.test(n)||(n=new Hm("0.0.0-0"),t.test(n)))return n;n=null;for(let i=0;i<t.set.length;++i){let r=t.set[i],o=null;r.forEach(s=>{let a=new Hm(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||v0(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),o&&(!n||v0(n,o))&&(n=o)}return n&&t.test(n)?n:null};y0.exports=Nz});var $0=z((PF,b0)=>{"use strict";var Rz=rt(),Dz=(t,e)=>{try{return new Rz(t,e).range||"*"}catch{return null}};b0.exports=Dz});var ru=z((CF,k0)=>{"use strict";var Lz=_e(),S0=Qi(),{ANY:Uz}=S0,jz=rt(),Mz=to(),x0=Xi(),w0=Ya(),Fz=Qa(),Vz=Xa(),Zz=(t,e,n,i)=>{t=new Lz(t,i),e=new jz(e,i);let r,o,s,a,u;switch(n){case">":r=x0,o=Fz,s=w0,a=">",u=">=";break;case"<":r=w0,o=Vz,s=x0,a="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Mz(t,e,i))return!1;for(let c=0;c<e.set.length;++c){let l=e.set[c],d=null,f=null;if(l.forEach(h=>{h.semver===Uz&&(h=new S0(">=0.0.0")),d=d||h,f=f||h,r(h.semver,d.semver,i)?d=h:s(h.semver,f.semver,i)&&(f=h)}),d.operator===a||d.operator===u||(!f.operator||f.operator===a)&&o(t,f.semver))return!1;if(f.operator===u&&s(t,f.semver))return!1}return!0};k0.exports=Zz});var E0=z((AF,I0)=>{"use strict";var Bz=ru(),Gz=(t,e,n)=>Bz(t,e,">",n);I0.exports=Gz});var O0=z((zF,T0)=>{"use strict";var Wz=ru(),qz=(t,e,n)=>Wz(t,e,"<",n);T0.exports=qz});var A0=z((NF,C0)=>{"use strict";var P0=rt(),Hz=(t,e,n)=>(t=new P0(t,n),e=new P0(e,n),t.intersects(e,n));C0.exports=Hz});var N0=z((RF,z0)=>{"use strict";var Jz=to(),Kz=tt();z0.exports=(t,e,n)=>{let i=[],r=null,o=null,s=t.sort((l,d)=>Kz(l,d,n));for(let l of s)Jz(l,e,n)?(o=l,r||(r=l)):(o&&i.push([r,o]),o=null,r=null);r&&i.push([r,null]);let a=[];for(let[l,d]of i)l===d?a.push(l):!d&&l===s[0]?a.push("*"):d?l===s[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);let u=a.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return u.length<c.length?u:e}});var M0=z((DF,j0)=>{"use strict";var R0=rt(),Ym=Qi(),{ANY:Jm}=Ym,Km=to(),Xm=tt(),Yz=(t,e,n={})=>{if(t===e)return!0;t=new R0(t,n),e=new R0(e,n);let i=!1;e:for(let r of t.set){for(let o of e.set){let s=Qz(r,o,n);if(i=i||s!==null,s)continue e}if(i)return!1}return!0},Xz=[new Ym(">=0.0.0-0")],D0=[new Ym(">=0.0.0")],Qz=(t,e,n)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===Jm){if(e.length===1&&e[0].semver===Jm)return!0;n.includePrerelease?t=Xz:t=D0}if(e.length===1&&e[0].semver===Jm){if(n.includePrerelease)return!0;e=D0}let i=new Set,r,o;for(let h of t)h.operator===">"||h.operator===">="?r=L0(r,h,n):h.operator==="<"||h.operator==="<="?o=U0(o,h,n):i.add(h.semver);if(i.size>1)return null;let s;if(r&&o){if(s=Xm(r.semver,o.semver,n),s>0)return null;if(s===0&&(r.operator!==">="||o.operator!=="<="))return null}for(let h of i){if(r&&!Km(h,String(r),n)||o&&!Km(h,String(o),n))return null;for(let p of e)if(!Km(h,String(p),n))return!1;return!0}let a,u,c,l,d=o&&!n.includePrerelease&&o.semver.prerelease.length?o.semver:!1,f=r&&!n.includePrerelease&&r.semver.prerelease.length?r.semver:!1;d&&d.prerelease.length===1&&o.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let h of e){if(l=l||h.operator===">"||h.operator===">=",c=c||h.operator==="<"||h.operator==="<=",r){if(f&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===f.major&&h.semver.minor===f.minor&&h.semver.patch===f.patch&&(f=!1),h.operator===">"||h.operator===">="){if(a=L0(r,h,n),a===h&&a!==r)return!1}else if(r.operator===">="&&!h.test(r.semver))return!1}if(o){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator==="<"||h.operator==="<="){if(u=U0(o,h,n),u===h&&u!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||r)&&s!==0)return!1}return!(r&&c&&!o&&s!==0||o&&l&&!r&&s!==0||f||d)},L0=(t,e,n)=>{if(!t)return e;let i=Xm(t.semver,e.semver,n);return i>0?t:i<0||e.operator===">"&&t.operator===">="?e:t},U0=(t,e,n)=>{if(!t)return e;let i=Xm(t.semver,e.semver,n);return i<0?t:i>0||e.operator==="<"&&t.operator==="<="?e:t};j0.exports=Yz});var B0=z((LF,Z0)=>{"use strict";var Qm=An(),F0=Cn(),eN=_e(),V0=Dm(),tN=Qt(),rN=fS(),nN=pS(),iN=vS(),oN=bS(),sN=xS(),aN=SS(),uN=IS(),cN=TS(),lN=tt(),dN=AS(),fN=NS(),hN=Ka(),pN=US(),mN=MS(),gN=Xi(),vN=Ya(),yN=jm(),_N=Mm(),bN=Xa(),$N=Qa(),xN=Fm(),wN=JS(),SN=YS(),kN=Qi(),IN=rt(),EN=to(),TN=f0(),ON=p0(),PN=g0(),CN=_0(),AN=$0(),zN=ru(),NN=E0(),RN=O0(),DN=A0(),LN=N0(),UN=M0();Z0.exports={parse:tN,valid:rN,clean:nN,inc:iN,diff:oN,major:sN,minor:aN,patch:uN,prerelease:cN,compare:lN,rcompare:dN,compareLoose:fN,compareBuild:hN,sort:pN,rsort:mN,gt:gN,lt:vN,eq:yN,neq:_N,gte:bN,lte:$N,cmp:xN,coerce:wN,truncate:SN,Comparator:kN,Range:IN,satisfies:EN,toComparators:TN,maxSatisfying:ON,minSatisfying:PN,minVersion:CN,validRange:AN,outside:zN,gtr:NN,ltr:RN,intersects:DN,simplifyRange:LN,subset:UN,SemVer:eN,re:Qm.re,src:Qm.src,tokens:Qm.t,SEMVER_SPEC_VERSION:F0.SEMVER_SPEC_VERSION,RELEASE_TYPES:F0.RELEASE_TYPES,compareIdentifiers:V0.compareIdentifiers,rcompareIdentifiers:V0.rcompareIdentifiers}});var J0=z((WF,eg)=>{var ou=process||{},q0=ou.argv||[],iu=ou.env||{},VN=!(iu.NO_COLOR||q0.includes("--no-color"))&&(!!iu.FORCE_COLOR||q0.includes("--color")||ou.platform==="win32"||(ou.stdout||{}).isTTY&&iu.TERM!=="dumb"||!!iu.CI),ZN=(t,e,n=t)=>i=>{let r=""+i,o=r.indexOf(e,t.length);return~o?t+BN(r,e,n,o)+e:t+r+e},BN=(t,e,n,i)=>{let r="",o=0;do r+=t.substring(o,i)+n,o=i+e.length,i=t.indexOf(e,o);while(~i);return r+t.substring(o)},H0=(t=VN)=>{let e=t?ZN:()=>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")}};eg.exports=H0();eg.exports.createColors=H0});var sg=z((yV,pk)=>{"use strict";var og={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},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"},hR={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},pR={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 n=0;n<t;n++)e+=this.line+(n<t-1?og.up():"");return t&&(e+=og.left),e}};pk.exports={cursor:og,scroll:hR,erase:pR,beep:"\x07"}});function iI(t,e){if(e<=1)return t;let n=Math.floor(t.length/e),i=new Int16Array(n);for(let r=0;r<n;r++){let o=0,s=r*e;for(let a=0;a<e;a++)o+=t[s+a];i[r]=Math.round(o/e)}return i}var Iu,oI=v(()=>{"use strict";Iu=class{step;pos=0;prev=0;primed=!1;constructor(e,n){if(e<=0||n<=0)throw new RangeError("resampler rates must be positive");this.step=e/n}process(e){if(e.length===0)return new Int16Array(0);let n=[],i=e.length-1,r=this.primed?this.pos:0;for(;;){let o=Math.floor(r);if(o+1>i)break;let s=o<0?this.prev:e[o],a=e[o+1];n.push(Math.round(s+(a-s)*(r-o))),r+=this.step}return this.prev=e[i],this.primed=!0,this.pos=r-e.length,Int16Array.from(n)}}});function aI(t){return t.byteLength/2/c4}function l4(t){let e=t.byteLength>>1,n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let r=0;r<e;r++)i[r]=n.getInt16(r*2,!0);return i}var sI,c4,Eu,uI=v(()=>{"use strict";De();Ma();sI=32,c4=16,Eu=class{constructor(e,n,i={}){this.vad=e;this.onSpeech=n;this.speechThreshold=i.speechThreshold??.5,this.onsetMs=i.onsetMs??2*sI,this.holdoffMs=i.holdoffMs??300,this.energyThreshold=i.energyThreshold??.01,this.log=i.log??q}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(Bt(e,this.energyThreshold),aI(e));return}this.vad.process(l4(e)).then(n=>{if(!this.closed)for(let i of n)this.applyVerdict(i>=this.speechThreshold,sI)},n=>{this.closed||(this.degrade(n),this.applyVerdict(Bt(e,this.energyThreshold),aI(e)))})}}close(){this.closed=!0}applyVerdict(e,n){e?(this.silenceRunMs=0,this.speechRunMs+=n,!this.inSpeech&&this.speechRunMs>=this.onsetMs&&(this.inSpeech=!0,this.onSpeech())):(this.speechRunMs=0,this.inSpeech&&(this.silenceRunMs+=n,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 kg={};He(kg,{DecibriCapture:()=>wg,DecibriPlayback:()=>Sg,hasInputDevice:()=>h4});import{Microphone as d4,Speaker as f4,inputDevices as lI}from"decibri";function h4(){try{return lI().length>0}catch(t){return q.debug("audio input enumeration failed; treating as no microphone",{error:t}),!1}}function p4(){try{let t=lI(),e=t.find(n=>n.isDefault)??t[0];if(e&&e.defaultSampleRate>=1e3&&e.maxInputChannels>=1)return{sampleRate:Math.round(e.defaultSampleRate),channels:e.maxInputChannels}}catch(t){q.debug("could not read default input device; opening at 16k mono",{error:t})}return{sampleRate:co,channels:Tu}}function m4(t){return Math.max(64,Math.min(65536,Math.round(t/10)))}function g4(t,e,n){let i=new Uint8Array(t),r=new Int16Array(i.buffer,0,i.byteLength>>1),o=n.process(iI(r,e));return Buffer.from(o.buffer,o.byteOffset,o.byteLength)}function _4(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}var co,Tu,dI,cI,wg,v4,y4,Sg,Ig=v(()=>{"use strict";De();Ma();oI();uI();co=16e3,Tu=1,dI="int16",cI=.01;wg=class{constructor(e={}){this.deps=e}deps;mic=null;onData=null;onSpeech=null;onErr=null;vad=null;detector=null;async start(e){let{sampleRate:n,channels:i}=p4(),r=(this.deps.createVad??(()=>new _r))(),o=null;try{await r.load(),o=new Eu(r,()=>e.onSpeechStart(),{energyThreshold:cI})}catch(u){q.debug("silero vad unavailable; barge-in falls back to decibri energy vad",{error:u}),r.dispose().catch(()=>{})}let s;try{s=await d4.open({sampleRate:n,channels:i,dtype:dI,...o?{vad:!1}:{vad:"energy",vadThreshold:cI},framesPerBuffer:m4(n)})}catch(u){throw o?.close(),o&&r.dispose().catch(()=>{}),u}this.vad=o?r:null,this.detector=o;let a=n===co&&i===Tu?null:new Iu(n,co);this.onData=a?u=>{let c=g4(u,i,a);c.byteLength>0&&(this.detector?.feed(c),e.onFrame(c,Date.now()))}:u=>{this.detector?.feed(u),e.onFrame(u,Date.now())},this.onSpeech=()=>e.onSpeechStart(),this.onErr=u=>e.onError(u),s.on("data",this.onData),s.on("speech",this.onSpeech),s.on("error",this.onErr),this.mic=s}async stop(){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 n=this.vad;this.vad=null,n&&await n.dispose().catch(()=>{})}},v4=co*Tu*2/1e3,y4=250,Sg=class{speaker=null;writeChain=Promise.resolve();generation=0;closed=!1;playoutEndAtMs=0;drainWakes=new Set;play(e){if(this.closed)return;let n=this.generation;this.writeChain=this.writeChain.then(async()=>{if(!(this.closed||n!==this.generation))try{if(await this.ensureSpeaker().writeAsync(_4(e)),this.closed||n!==this.generation)return;this.playoutEndAtMs=Math.max(this.playoutEndAtMs,Date.now())+e.byteLength/v4}catch(i){q.debug("playback write skipped",{error:i})}})}flush(){this.generation++,this.playoutEndAtMs=0;let e=this.speaker;this.speaker=null,e?.stop();for(let n of[...this.drainWakes])n()}async drained(){await this.writeChain;let e=this.speaker;if(!e)return;let n=Promise.resolve().then(()=>e.drainAsync()).catch(s=>{q.debug("playback drain interrupted",{error:s})}),i=Math.max(0,this.playoutEndAtMs-Date.now())+y4,r=this.sleep(i);await Promise.race([n,r.done]),r.wake();let o=this.playoutEndAtMs-Date.now();o>0&&await this.sleep(o).done}sleep(e){let n;return{done:new Promise(r=>{let o=setTimeout(()=>n(),e);n=()=>{clearTimeout(o),this.drainWakes.delete(n),r()},this.drainWakes.add(n)}),wake:n}}close(){return this.closed=!0,this.flush(),Promise.resolve()}ensureSpeaker(){return this.speaker??=new f4({sampleRate:co,channels:Tu,dtype:dI}),this.speaker}}});De();Ma();xi();import{readFileSync as b4}from"node:fs";import{randomUUID as $4}from"node:crypto";var mt=class extends Error{constructor(e,n,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},Ot=class extends mt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Ji=class{constructor(e,n){switch(this.description=n||"",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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Ot(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Fa(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}import{EventEmitter as EC}from"node:events";import zm from"node:child_process";import Pt from"node:path";import Za from"node:fs";import B from"node:process";import{stripVTControlCharacters as TC}from"node:util";import{stripVTControlCharacters as SC}from"node:util";var Ki=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 n=e.commands.filter(r=>!r._hidden),i=e._getHelpCommand();return i&&!i._hidden&&n.push(i),this.sortSubcommands&&n.sort((r,o)=>r.name().localeCompare(o.name())),n}compareOptions(e,n){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(e).localeCompare(i(n))}visibleOptions(e){let n=e.options.filter(r=>!r.hidden),i=e._getHelpOption();if(i&&!i.hidden){let r=i.short&&e._findOption(i.short),o=i.long&&e._findOption(i.long);!r&&!o?n.push(i):i.long&&!o?n.push(e.createOption(i.long,i.description)):i.short&&!r&&n.push(e.createOption(i.short,i.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let i=e.parent;i;i=i.parent){let r=i.options.filter(o=>!o.hidden);n.push(...r)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(i=>Fa(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(r)))),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(r)))),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(r)))),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let i="";for(let r=e.parent;r;r=r.parent)i=r.name()+" "+i;return i+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatItemList(e,n,i){return n.length===0?[]:[i.styleTitle(e),...n,""]}groupItems(e,n,i){let r=new Map;return e.forEach(o=>{let s=i(o);r.has(s)||r.set(s,[])}),n.forEach(o=>{let s=i(o);r.has(s)||r.set(s,[]),r.get(s).push(o)}),r}formatHelp(e,n){let i=n.padWidth(e,n),r=n.helpWidth??80;function o(d,f){return n.formatItem(d,i,f,n)}let s=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(e))}`,""],a=n.commandDescription(e);a.length>0&&(s=s.concat([n.boxWrap(n.styleCommandDescription(a),r),""]));let u=n.visibleArguments(e).map(d=>o(n.styleArgumentTerm(n.argumentTerm(d)),n.styleArgumentDescription(n.argumentDescription(d))));if(s=s.concat(this.formatItemList("Arguments:",u,n)),this.groupItems(e.options,n.visibleOptions(e),d=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let h=d.map(p=>o(n.styleOptionTerm(n.optionTerm(p)),n.styleOptionDescription(n.optionDescription(p))));s=s.concat(this.formatItemList(f,h,n))}),n.showGlobalOptions){let d=n.visibleGlobalOptions(e).map(f=>o(n.styleOptionTerm(n.optionTerm(f)),n.styleOptionDescription(n.optionDescription(f))));s=s.concat(this.formatItemList("Global Options:",d,n))}return this.groupItems(e.commands,n.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,f)=>{let h=d.map(p=>o(n.styleSubcommandTerm(n.subcommandTerm(p)),n.styleSubcommandDescription(n.subcommandDescription(p))));s=s.concat(this.formatItemList(f,h,n))}),s.join(`
127
+ `)}displayWidth(e){return SC(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).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(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).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,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,n,i,r){let s=" ".repeat(2);if(!i)return s+e;let a=e.padEnd(n+e.length-r.displayWidth(e)),u=2,l=(this.helpWidth??80)-n-u-2,d;return l<this.minWidthToWrap||r.preformatted(i)?d=i:d=r.boxWrap(i,l).replace(/\n/g,`
128
128
  `+" ".repeat(n+u)),s+a+" ".repeat(u)+d.replace(/\n/g,`
129
129
  ${s}`)}boxWrap(e,n){if(n<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,o=[];return i.forEach(s=>{let a=s.match(r);if(a===null){o.push("");return}let u=[a.shift()],c=this.displayWidth(u[0]);a.forEach(l=>{let d=this.displayWidth(l);if(c+d<=n){u.push(l),c+=d;return}o.push(u.join(""));let f=l.trimStart();u=[f],c=this.displayWidth(f)}),o.push(u.join(""))}),o.join(`
130
- `)}};var On=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=SC(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Ot(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Kw(this.name().replace(/^no-/,"")):Kw(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Va=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,n){let i=n.attributeName();if(!this.dualOptions.has(i))return!0;let r=this.negativeOptions.get(i).presetArg,o=r!==void 0?r:!1;return n.negate===(o===e)}};function Kw(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function SC(t){let e,n,i=/^-[^-]$/,r=/^--[^-]/,o=t.split(/[ |,]+/).concat("guard");if(i.test(o[0])&&(e=o.shift()),r.test(o[0])&&(n=o.shift()),!e&&i.test(o[0])&&(e=o.shift()),!e&&r.test(o[0])&&(e=n,n=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${t}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
130
+ `)}};var On=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=kC(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Ot(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Kw(this.name().replace(/^no-/,"")):Kw(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Va=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,n){let i=n.attributeName();if(!this.dualOptions.has(i))return!0;let r=this.negativeOptions.get(i).presetArg,o=r!==void 0?r:!1;return n.negate===(o===e)}};function Kw(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function kC(t){let e,n,i=/^-[^-]$/,r=/^--[^-]/,o=t.split(/[ |,]+/).concat("guard");if(i.test(o[0])&&(e=o.shift()),r.test(o[0])&&(n=o.shift()),!e&&i.test(o[0])&&(e=o.shift()),!e&&r.test(o[0])&&(e=n,n=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${t}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
131
131
  - a short flag is a single dash and a single character
132
132
  - either use a single dash and a single character (for a short flag)
133
133
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(s)?new Error(`${a}
134
134
  - too many short flags`):r.test(s)?new Error(`${a}
135
135
  - too many long flags`):new Error(`${a}
136
- - unrecognised flag format`)}if(e===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:n}}function kC(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let i=0;i<=t.length;i++)n[i]=[i];for(let i=0;i<=e.length;i++)n[0][i]=i;for(let i=1;i<=e.length;i++)for(let r=1;r<=t.length;r++){let o;t[r-1]===e[i-1]?o=0:o=1,n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+o),r>1&&i>1&&t[r-1]===e[i-2]&&t[r-2]===e[i-1]&&(n[r][i]=Math.min(n[r][i],n[r-2][i-2]+1))}return n[t.length][e.length]}function Am(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(s=>s.slice(2)));let i=[],r=3,o=.4;return e.forEach(s=>{if(s.length<=1)return;let a=kC(t,s),u=Math.max(t.length,s.length);(u-a)/u>o&&(a<r?(r=a,i=[s]):a===r&&i.push(s))}),i.sort((s,a)=>s.localeCompare(a)),n&&(i=i.map(s=>`--${s}`)),i.length>1?`
136
+ - unrecognised flag format`)}if(e===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:n}}function IC(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let i=0;i<=t.length;i++)n[i]=[i];for(let i=0;i<=e.length;i++)n[0][i]=i;for(let i=1;i<=e.length;i++)for(let r=1;r<=t.length;r++){let o;t[r-1]===e[i-1]?o=0:o=1,n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+o),r>1&&i>1&&t[r-1]===e[i-2]&&t[r-2]===e[i-1]&&(n[r][i]=Math.min(n[r][i],n[r-2][i-2]+1))}return n[t.length][e.length]}function Am(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(s=>s.slice(2)));let i=[],r=3,o=.4;return e.forEach(s=>{if(s.length<=1)return;let a=IC(t,s),u=Math.max(t.length,s.length);(u-a)/u>o&&(a<r?(r=a,i=[s]):a===r&&i.push(s))}),i.sort((s,a)=>s.localeCompare(a)),n&&(i=i.map(s=>`--${s}`)),i.length>1?`
137
137
  (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
138
- (Did you mean ${i[0]}?)`:""}var Pn=class t extends IC{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>B.stdout.write(n),writeErr:n=>B.stderr.write(n),outputError:(n,i)=>i(n),getOutHelpWidth:()=>B.stdout.isTTY?B.stdout.columns:void 0,getErrHelpWidth:()=>B.stderr.isTTY?B.stderr.columns:void 0,getOutHasColors:()=>Xw()??(B.stdout.isTTY&&B.stdout.hasColors?.()),getErrHasColors:()=>Xw()??(B.stderr.isTTY&&B.stderr.hasColors?.()),stripColor:n=>EC(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,i){let r=n,o=i;typeof r=="object"&&r!==null&&(o=r,r=null),o=o||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(s);return r&&(u.description(r),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),r?this:u}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Ki,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
138
+ (Did you mean ${i[0]}?)`:""}var Pn=class t extends EC{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>B.stdout.write(n),writeErr:n=>B.stderr.write(n),outputError:(n,i)=>i(n),getOutHelpWidth:()=>B.stdout.isTTY?B.stdout.columns:void 0,getErrHelpWidth:()=>B.stderr.isTTY?B.stderr.columns:void 0,getOutHasColors:()=>Xw()??(B.stdout.isTTY&&B.stdout.hasColors?.()),getErrHasColors:()=>Xw()??(B.stderr.isTTY&&B.stderr.hasColors?.()),stripColor:n=>TC(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,i){let r=n,o=i;typeof r=="object"&&r!==null&&(o=r,r=null),o=o||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(s);return r&&(u.description(r),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),r?this:u}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Ki,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
139
139
  - specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new Ji(e,n)}argument(e,n,i,r){let o=this.createArgument(e,n);return typeof i=="function"?o.default(r).argParser(i):o.default(i),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n?.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let i=e??"help [command]",[,r,o]=i.match(/([^ ]+) *(.*)/),s=n??"display help for command",a=this.createCommand(r);return a.helpOption(!1),o&&a.arguments(o),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||n)&&this._initCommandGroup(a),this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,n){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
140
140
  Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,i){this._exitCallback&&this._exitCallback(new mt(e,n,i)),B.exit(e)}action(e){let n=i=>{let r=this.registeredArguments.length,o=i.slice(0,r);return this._storeOptionsAsProperties?o[r]=this:o[r]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=n,this}createOption(e,n){return new On(e,n)}_callParseArg(e,n,i,r){try{return e.parseArg(n,i)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${r} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
141
141
  - already used by option '${n.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let n=r=>[r.name()].concat(r.aliases()),i=n(e).find(r=>this._findCommand(r));if(i){let r=n(this._findCommand(i)).join("|"),o=n(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),i=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let r=(o,s,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let u=this.getOptionValue(i);o!==null&&e.parseArg?o=this._callParseArg(e,o,u,s):o!==null&&e.variadic&&(o=e._collectValue(o,u)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(i,o,a)};return this.on("option:"+n,o=>{let s=`error: option '${e.flags}' argument '${o}' is invalid.`;r(o,s,"cli")}),e.envVar&&this.on("optionEnv:"+n,o=>{let s=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;r(o,s,"env")}),this}_optionEx(e,n,i,r,o){if(typeof n=="object"&&n instanceof On)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(n,i);if(s.makeOptionMandatory(!!e.mandatory),typeof r=="function")s.default(o).argParser(r);else if(r instanceof RegExp){let a=r;r=(u,c)=>{let l=a.exec(u);return l?l[0]:c},s.default(o).argParser(r)}else s.default(r);return this.addOption(s)}option(e,n,i,r){return this._optionEx({},e,n,i,r)}requiredOption(e,n,i,r){return this._optionEx({mandatory:!0},e,n,i,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,i){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(n=i.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){B.versions?.electron&&(n.from="electron");let r=B.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(n.from="eval")}e===void 0&&(e=B.argv),this.rawArgs=e.slice();let i;switch(n.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":B.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,n){this._prepareForParse();let i=this._prepareUserArgs(e,n);return this._parseCommand([],i),this}async parseAsync(e,n){this._prepareForParse();let i=this._prepareUserArgs(e,n);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let n=e.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
@@ -148,7 +148,7 @@ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
148
148
  `),this.outputHelp({error:!0}));let i=n||{},r=i.exitCode||1,o=i.code||"commander.error";this._exit(r,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in B.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,B.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Va(this.options),n=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&n(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(r=>!n(r)).forEach(r=>{this.setOptionValueWithSource(r,i.implied[r],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let i=s=>{let a=s.attributeName(),u=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),l=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&u===!1||c.presetArg!==void 0&&u===c.presetArg)?c:l||s},r=s=>{let a=i(s),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${r(e)} cannot be used with ${r(n)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],o=this;do{let s=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);r=r.concat(s),o=o.parent}while(o&&!o._enablePositionalOptions);n=Am(e,r)}let i=`error: unknown option '${e}'${n}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,i=n===1?"":"s",r=e.length,o=this.parent?` for '${this.name()}'`:"",s=e.join(", "),a=`error: too many arguments${o}. Expected ${n} argument${i} but got ${r}: ${s}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(o=>{r.push(o.name()),o.alias()&&r.push(o.alias())}),n=Am(e,r)}let i=`error: unknown command '${e}'${n}`;this.error(i,{code:"commander.unknownCommand"})}version(e,n,i){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",i=i||"output the version number";let r=this.createOption(n,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
149
149
  `),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let r=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(i=>Fa(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=Pt.basename(e,Pt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp(),i=this._getOutputContext(e);n.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let r=n.formatHelp(this,n);return i.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let n=!!e.error,i,r,o;return n?(i=a=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(r||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:r,helpWidth:o}}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let i=this._getOutputContext(e),r={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let o=this.helpInformation({error:i.error});if(n&&(o=n(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}helpOption(e,n){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",n??"display help for command"),(e||n)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let n=Number(B.exitCode??0);n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
150
150
  Expecting one of '${i.join("', '")}'`);let r=`${e}Help`;return this.on(r,o=>{let s;typeof n=="function"?s=n({error:o.error,command:o.command}):s=n,s&&o.write(`${s}
151
- `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(r=>n.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Yw(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,i="127.0.0.1",r="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?n=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=o[1],/^\d+$/.test(o[3])?r=o[3]:i=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=o[1],i=o[3],r=o[4]),n&&r!=="0"?`${n}=${i}:${parseInt(r)+1}`:e})}function Xw(){if(B.env.NO_COLOR||B.env.FORCE_COLOR==="0"||B.env.FORCE_COLOR==="false")return!1;if(B.env.FORCE_COLOR||B.env.CLICOLOR_FORCE!==void 0)return!0}var jM=new Pn;De();var ue={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function TC(t){if(t==="debug"||t==="info"||t==="warn"||t==="error")return t;throw new Ot("expected one of debug|info|warn|error")}function Ba(t){return t.option("--log-level <level>","set log verbosity (debug|info|warn|error)",TC).option("--project <path>","approved project scope (default: cwd)").option("--text","force text-only operation").option("--no-voice","force text-only operation (disable voice)").option("--half-duplex","mute barge-in; mute the mic while jarvis speaks (no headphones)").option("--ptt","push-to-talk: press space to talk, again to send")}function OC(t){return t.text===!0||t.voice===!1}function PC(t,e,n,i=ue){let r=new Pn;r.name("jarvis").description("jarvis - voice-first personal agent").configureOutput({writeOut:s=>i.out(s),writeErr:s=>i.err(s)}).showHelpAfterError().exitOverride().allowExcessArguments(!0).version(t,"-v, --version","print version"),Ba(r),r.hook("preAction",(s,a)=>{let u=a.optsWithGlobals();u.logLevel&&q.setLevel(u.logLevel)}),r.action(async(s,a)=>{if(a.args.length>0){a.error(`error: unknown command '${a.args[0]}'`,{exitCode:1,code:"commander.unknownCommand"});return}n.exitCode=await e.activate({project:s.project??process.cwd(),textOnly:OC(s),halfDuplex:s.halfDuplex===!0,ptt:s.ptt===!0})});let o=(s,a)=>{let u=r.command(s).description(a).allowExcessArguments(!1);return Ba(u)};return o("init","first-run setup (interactive wizard)").action(async()=>{n.exitCode=await e.init()}),o("start","start the local core service").action(()=>{n.exitCode=e.stub("start")}),o("stop","stop the local core service").action(()=>{n.exitCode=e.stub("stop")}),o("restart","restart the local core service").action(()=>{n.exitCode=e.stub("restart")}),o("status","show version and check for updates").action(async()=>{n.exitCode=await e.status()}),o("doctor","run diagnostics").action(async()=>{n.exitCode=await e.doctor()}),o("devices","list audio devices").action(()=>{n.exitCode=e.stub("devices")}),o("upgrade","upgrade the installed CLI to the latest published version").action(async()=>{n.exitCode=await e.upgrade()}),CC(r,e,n),r}function CC(t,e,n){let i=t.command("config").description("inspect and edit configuration").allowExcessArguments(!0);Ba(i),i.action((o,s)=>{if(s.args.length>0){s.error(`error: unknown command 'config ${s.args[0]}'`,{exitCode:1,code:"commander.unknownCommand"});return}s.outputHelp(),n.exitCode=0});let r=(o,s)=>{let a=i.command(o).description(s).allowExcessArguments(!1);return Ba(a)};r("list","print the resolved config (secrets redacted)").action(async()=>{n.exitCode=await e.configList()}),r("get <path>","print one config value by dotted path").action(async o=>{n.exitCode=await e.configGet(o)}),r("set <path> <value>","set one config value by dotted path").action(async(o,s)=>{n.exitCode=await e.configSet(o,s)}),r("unset <path>","remove one config value by dotted path").action(async o=>{n.exitCode=await e.configUnset(o)})}async function Qw(t,e,n,i=ue){let r={exitCode:0},o=PC(e,n,r,i);try{return await o.parseAsync(t,{from:"user"}),r.exitCode}catch(s){if(s instanceof mt)return s.exitCode;throw s}}De();import{execSync as W0,spawnSync as UN}from"node:child_process";import{existsSync as jN}from"node:fs";import{join as MN}from"node:path";var nu=Je(B0(),1);function Ir(t,e){let n=G0(t),i=G0(e);return n===null||i===null?!1:nu.default.gt(n,i)}function G0(t){return nu.default.valid(t)??nu.default.coerce(t)?.version??null}var Er=class{constructor(e,n=ue){this.currentVersion=e;this.io=n}currentVersion;io;packageName="@neuvybe/jarvis";registryTimeoutMs=3e3;safeVersion=/^[0-9A-Za-z.\-+]+$/;npmCmd(){return process.platform==="win32"?"npm.cmd":"npm"}async fetchLatest(){try{let e=await fetch(`https://registry.npmjs.org/${this.packageName}/latest`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(this.registryTimeoutMs)});if(!e.ok)return null;let n=await e.json();return typeof n.version=="string"?n.version:null}catch{return null}}async status(){this.io.out(`jarvis ${this.currentVersion}
151
+ `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(r=>n.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Yw(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,i="127.0.0.1",r="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?n=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=o[1],/^\d+$/.test(o[3])?r=o[3]:i=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=o[1],i=o[3],r=o[4]),n&&r!=="0"?`${n}=${i}:${parseInt(r)+1}`:e})}function Xw(){if(B.env.NO_COLOR||B.env.FORCE_COLOR==="0"||B.env.FORCE_COLOR==="false")return!1;if(B.env.FORCE_COLOR||B.env.CLICOLOR_FORCE!==void 0)return!0}var MM=new Pn;De();var ue={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function OC(t){if(t==="debug"||t==="info"||t==="warn"||t==="error")return t;throw new Ot("expected one of debug|info|warn|error")}function Ba(t){return t.option("--log-level <level>","set log verbosity (debug|info|warn|error)",OC).option("--project <path>","approved project scope (default: cwd)").option("--text","force text-only operation").option("--no-voice","force text-only operation (disable voice)").option("--half-duplex","mute barge-in; mute the mic while jarvis speaks (no headphones)").option("--ptt","push-to-talk: press space to talk, again to send")}function PC(t){return t.text===!0||t.voice===!1}function CC(t,e,n,i=ue){let r=new Pn;r.name("jarvis").description("jarvis - voice-first personal agent").configureOutput({writeOut:s=>i.out(s),writeErr:s=>i.err(s)}).showHelpAfterError().exitOverride().allowExcessArguments(!0).version(t,"-v, --version","print version"),Ba(r),r.hook("preAction",(s,a)=>{let u=a.optsWithGlobals();u.logLevel&&q.setLevel(u.logLevel)}),r.action(async(s,a)=>{if(a.args.length>0){a.error(`error: unknown command '${a.args[0]}'`,{exitCode:1,code:"commander.unknownCommand"});return}n.exitCode=await e.activate({project:s.project??process.cwd(),textOnly:PC(s),halfDuplex:s.halfDuplex===!0,ptt:s.ptt===!0})});let o=(s,a)=>{let u=r.command(s).description(a).allowExcessArguments(!1);return Ba(u)};return o("init","first-run setup (interactive wizard)").action(async()=>{n.exitCode=await e.init()}),o("start","start the local core service").action(()=>{n.exitCode=e.stub("start")}),o("stop","stop the local core service").action(()=>{n.exitCode=e.stub("stop")}),o("restart","restart the local core service").action(()=>{n.exitCode=e.stub("restart")}),o("status","show version and check for updates").action(async()=>{n.exitCode=await e.status()}),o("doctor","run diagnostics").action(async()=>{n.exitCode=await e.doctor()}),o("devices","list audio devices").action(()=>{n.exitCode=e.stub("devices")}),o("upgrade","upgrade the installed CLI to the latest published version").action(async()=>{n.exitCode=await e.upgrade()}),AC(r,e,n),r}function AC(t,e,n){let i=t.command("config").description("inspect and edit configuration").allowExcessArguments(!0);Ba(i),i.action((o,s)=>{if(s.args.length>0){s.error(`error: unknown command 'config ${s.args[0]}'`,{exitCode:1,code:"commander.unknownCommand"});return}s.outputHelp(),n.exitCode=0});let r=(o,s)=>{let a=i.command(o).description(s).allowExcessArguments(!1);return Ba(a)};r("list","print the resolved config (secrets redacted)").action(async()=>{n.exitCode=await e.configList()}),r("get <path>","print one config value by dotted path").action(async o=>{n.exitCode=await e.configGet(o)}),r("set <path> <value>","set one config value by dotted path").action(async(o,s)=>{n.exitCode=await e.configSet(o,s)}),r("unset <path>","remove one config value by dotted path").action(async o=>{n.exitCode=await e.configUnset(o)})}async function Qw(t,e,n,i=ue){let r={exitCode:0},o=CC(e,n,r,i);try{return await o.parseAsync(t,{from:"user"}),r.exitCode}catch(s){if(s instanceof mt)return s.exitCode;throw s}}De();import{execSync as W0,spawnSync as jN}from"node:child_process";import{existsSync as MN}from"node:fs";import{join as FN}from"node:path";var nu=Je(B0(),1);function Ir(t,e){let n=G0(t),i=G0(e);return n===null||i===null?!1:nu.default.gt(n,i)}function G0(t){return nu.default.valid(t)??nu.default.coerce(t)?.version??null}var Er=class{constructor(e,n=ue){this.currentVersion=e;this.io=n}currentVersion;io;packageName="@neuvybe/jarvis";registryTimeoutMs=3e3;safeVersion=/^[0-9A-Za-z.\-+]+$/;npmCmd(){return process.platform==="win32"?"npm.cmd":"npm"}async fetchLatest(){try{let e=await fetch(`https://registry.npmjs.org/${this.packageName}/latest`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(this.registryTimeoutMs)});if(!e.ok)return null;let n=await e.json();return typeof n.version=="string"?n.version:null}catch{return null}}async status(){this.io.out(`jarvis ${this.currentVersion}
152
152
  `);let e=await this.fetchLatest();return e===null?this.io.out(`could not check for updates (offline?)
153
153
  `):Ir(e,this.currentVersion)?this.io.out(`upgrade available: ${this.currentVersion} -> ${e} (run: jarvis upgrade)
154
154
  `):this.io.out(`up to date
@@ -160,9 +160,9 @@ Expecting one of '${i.join("', '")}'`);let r=`${e}Help`;return this.on(r,o=>{let
160
160
  `),await this.stopCore();let n=`${this.npmCmd()} install -g ${this.packageName}@${e}`;try{W0(n,{stdio:"inherit"})}catch{return this.io.err(`upgrade failed; run manually: ${this.npmCmd()} install -g ${this.packageName}@latest
161
161
  `),1}let i=this.resolveFreshEntrypoint();return i===null?(this.io.out(`upgraded to ${e}. run "jarvis --version" to confirm.
162
162
  `),0):(this.io.err(`verifying the freshly installed jarvis...
163
- `),UN(process.execPath,[i,"--version"],{stdio:"inherit"}).status!==0?(this.io.err(`upgrade installed but the fresh entrypoint exited abnormally; run "jarvis --version" to confirm
163
+ `),jN(process.execPath,[i,"--version"],{stdio:"inherit"}).status!==0?(this.io.err(`upgrade installed but the fresh entrypoint exited abnormally; run "jarvis --version" to confirm
164
164
  `),0):(this.io.out(`upgraded to ${e}.
165
- `),0))}async stopCore(){return q.debug("stop-core hook: no daemon in v0.1; nothing to stop (proposal 0013 fills this in)"),Promise.resolve()}resolveFreshEntrypoint(){try{let e=W0(`${this.npmCmd()} root -g`,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(!e)return null;let n=MN(e,this.packageName,"dist","index.js");return jN(n)?n:null}catch{return null}}};De();hr();import{spawn as BN}from"node:child_process";import{existsSync as GN,readFileSync as WN,writeFileSync as qN}from"node:fs";var Tr=Je(J0(),1),R={dim:t=>Tr.default.dim(t),bold:t=>Tr.default.bold(t),ok:t=>Tr.default.green(t),warn:t=>Tr.default.yellow(t),fail:t=>Tr.default.red(t),accent:t=>Tr.default.cyan(t)};var su=class{constructor(e,n=Be){this.currentVersion=e;this.home=n}currentVersion;home;packageName="@neuvybe/jarvis";cacheFile="update-check.json";ttlMs=360*60*1e3;cachePath(){return this.home.resolve(this.cacheFile)}read(){let e=this.cachePath();if(!GN(e))return null;try{let n=JSON.parse(WN(e,"utf8"));return typeof n.lastCheckedAt=="number"&&typeof n.latestVersion=="string"?{lastCheckedAt:n.lastCheckedAt,latestVersion:n.latestVersion}:null}catch{return null}}write(e,n){let i={lastCheckedAt:n,latestVersion:e};try{this.home.ensureDir(),qN(this.cachePath(),JSON.stringify(i))}catch{}}isStale(e){let n=this.read();return!n||e-n.lastCheckedAt>this.ttlMs}notice(){let e=this.read();return!e||!Ir(e.latestVersion,this.currentVersion)?null:R.dim(`upgrade available: ${this.currentVersion} -> ${e.latestVersion} (run: jarvis upgrade)`)}refreshInBackground(){try{let e=this.cachePath();this.home.ensureDir();let n=`
165
+ `),0))}async stopCore(){return q.debug("stop-core hook: no daemon in v0.1; nothing to stop (proposal 0013 fills this in)"),Promise.resolve()}resolveFreshEntrypoint(){try{let e=W0(`${this.npmCmd()} root -g`,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(!e)return null;let n=FN(e,this.packageName,"dist","index.js");return MN(n)?n:null}catch{return null}}};De();hr();import{spawn as GN}from"node:child_process";import{existsSync as WN,readFileSync as qN,writeFileSync as HN}from"node:fs";var Tr=Je(J0(),1),R={dim:t=>Tr.default.dim(t),bold:t=>Tr.default.bold(t),ok:t=>Tr.default.green(t),warn:t=>Tr.default.yellow(t),fail:t=>Tr.default.red(t),accent:t=>Tr.default.cyan(t)};var su=class{constructor(e,n=Be){this.currentVersion=e;this.home=n}currentVersion;home;packageName="@neuvybe/jarvis";cacheFile="update-check.json";ttlMs=360*60*1e3;cachePath(){return this.home.resolve(this.cacheFile)}read(){let e=this.cachePath();if(!WN(e))return null;try{let n=JSON.parse(qN(e,"utf8"));return typeof n.lastCheckedAt=="number"&&typeof n.latestVersion=="string"?{lastCheckedAt:n.lastCheckedAt,latestVersion:n.latestVersion}:null}catch{return null}}write(e,n){let i={lastCheckedAt:n,latestVersion:e};try{this.home.ensureDir(),HN(this.cachePath(),JSON.stringify(i))}catch{}}isStale(e){let n=this.read();return!n||e-n.lastCheckedAt>this.ttlMs}notice(){let e=this.read();return!e||!Ir(e.latestVersion,this.currentVersion)?null:R.dim(`upgrade available: ${this.currentVersion} -> ${e.latestVersion} (run: jarvis upgrade)`)}refreshInBackground(){try{let e=this.cachePath();this.home.ensureDir();let n=`
166
166
  import { writeFileSync } from 'node:fs';
167
167
  try {
168
168
  const res = await fetch('https://registry.npmjs.org/${this.packageName}/latest', {
@@ -179,36 +179,36 @@ try {
179
179
  }
180
180
  }
181
181
  } catch {}
182
- `;BN(process.execPath,["--input-type=module","-e",n],{detached:!0,stdio:"ignore"}).unref()}catch{q.debug("background update check skipped (could not refresh cache)")}}};var Or=class{constructor(e,n=ue){this.config=e;this.io=n}config;io;list(){let e=K0(this.config.list());for(let[n,i]of e)this.io.out(`${R.accent(n)} = ${this.renderValue(n,i)}
182
+ `;GN(process.execPath,["--input-type=module","-e",n],{detached:!0,stdio:"ignore"}).unref()}catch{q.debug("background update check skipped (could not refresh cache)")}}};var Or=class{constructor(e,n=ue){this.config=e;this.io=n}config;io;list(){let e=K0(this.config.list());for(let[n,i]of e)this.io.out(`${R.accent(n)} = ${this.renderValue(n,i)}
183
183
  `);return 0}get(e){let n;try{n=this.config.get(e)}catch(i){return this.io.err(`error: ${tg(i)}
184
184
  `),1}return n===void 0?(this.io.err(`config: '${e}' is not set
185
- `),1):(this.io.out(`${HN(n)}
185
+ `),1):(this.io.out(`${JN(n)}
186
186
  `),0)}set(e,n){try{this.config.set(e,n)}catch(i){return this.io.err(`error: ${tg(i)}
187
187
  `),1}return this.io.out(`${R.ok("set")} ${R.accent(e)}
188
188
  `),0}unset(e){try{this.config.unset(e)}catch(n){return this.io.err(`error: ${tg(n)}
189
189
  `),1}return this.io.out(`${R.ok("unset")} ${R.accent(e)}
190
- `),0}renderValue(e,n){return e.startsWith("secrets.")?R.dim(String(n)):String(n)}};function K0(t,e=""){let n=[];for(let[i,r]of Object.entries(t)){let o=e?`${e}.${i}`:i;r!==null&&typeof r=="object"&&!Array.isArray(r)?n.push(...K0(r,o)):n.push([o,r])}return n}function HN(t){return t!==null&&typeof t=="object"?JSON.stringify(t,null,2):String(t)}function tg(t){return t instanceof Error?t.message:String(t)}hr();import{existsSync as Y0,statSync as X0}from"node:fs";var Q0=["text","stt","tts","embedding"],JN={text:"Brain",stt:"Voice",tts:"Voice",embedding:"Memory"},au=class{config;probe;version;io;homeCheck;checkUpdate;constructor(e){this.config=e.config,this.probe=e.probe,this.version=e.version,this.io=e.io??ue,this.homeCheck=e.homeCheck??YN,this.checkUpdate=e.checkUpdate??(async()=>({latest:await new Er(this.version).fetchLatest()}))}async run(){let e=[],n;try{n=this.config.resolved(),e.push({level:"ok",label:"config",detail:"valid"})}catch(r){e.push({level:"fail",label:"config",detail:`invalid - ${XN(r)}`})}e.push(this.homeLine()),n&&e.push(...await this.routeLines(n)),e.push(await this.versionLine()),e.push({level:"info",label:"project",detail:process.cwd()});let i=e.some(r=>r.level==="fail")?1:0;return this.render(e,i),i}homeLine(){let e=this.homeCheck();return e.permsOk===!1?{level:"fail",label:"home",detail:`${e.dir} - ${e.detail??"permissions wrong"}`}:e.exists?{level:"ok",label:"home",detail:`${e.dir} (${e.detail??"owner-only"})`}:{level:"info",label:"home",detail:`${e.dir} (${e.detail??"not created yet"})`}}async routeLines(e){let n=e.routes??{},i=new Map;for(let s of Q0){let a=n[s],u=a&&e.secrets?.[a.provider];a&&u&&i.set(a.provider,u)}let r=new Map;await Promise.all([...i].map(async([s,a])=>{let u=await this.probe.probe(s,a);r.set(s,u.status)}));let o=[];for(let s of Q0){let a=n[s];if(!a){o.push(this.unconfiguredLine(s));continue}let u=`${a.provider}/${a.model}`;if(!e.secrets?.[a.provider]){o.push({level:"fail",label:`${s} route`,detail:`${u} - key for '${a.provider}' is missing`});continue}o.push(this.probedLine(s,u,a.provider,r.get(a.provider)))}return o}unconfiguredLine(e){return e==="text"?{level:"fail",label:"text route",detail:"not configured - Jarvis cannot reason (run: jarvis init)"}:{level:"info",label:`${e} route`,detail:`not configured (optional, ${JN[e]})`}}probedLine(e,n,i,r){let o=`${e} route`,s=e==="text";switch(r){case"valid":return{level:"ok",label:o,detail:`${n} (key valid)`};case"invalid":return{level:s?"fail":"warn",label:o,detail:`${n} - key rejected by ${i}`};case"unreachable":return{level:"warn",label:o,detail:`${n} (key present; could not verify - offline/unreachable)`};case"unimplemented":return{level:"warn",label:o,detail:`${n} (key present; no probe for ${i})`};case"unverifiable":return{level:"warn",label:o,detail:`${n} (key present; reached ${i} but cannot verify this key here - confirmed at first use)`};default:return{level:"warn",label:o,detail:`${n} (key present; not verified)`}}}async versionLine(){let{latest:e}=await this.checkUpdate();return e===null?{level:"info",label:"version",detail:`${this.version} (could not check for updates)`}:Ir(e,this.version)?{level:"warn",label:"version",detail:`${this.version} -> ${e} available (run: jarvis upgrade)`}:{level:"ok",label:"version",detail:`${this.version} (up to date)`}}render(e,n){this.io.out(`
190
+ `),0}renderValue(e,n){return e.startsWith("secrets.")?R.dim(String(n)):String(n)}};function K0(t,e=""){let n=[];for(let[i,r]of Object.entries(t)){let o=e?`${e}.${i}`:i;r!==null&&typeof r=="object"&&!Array.isArray(r)?n.push(...K0(r,o)):n.push([o,r])}return n}function JN(t){return t!==null&&typeof t=="object"?JSON.stringify(t,null,2):String(t)}function tg(t){return t instanceof Error?t.message:String(t)}hr();import{existsSync as Y0,statSync as X0}from"node:fs";var Q0=["text","stt","tts","embedding"],KN={text:"Brain",stt:"Voice",tts:"Voice",embedding:"Memory"},au=class{config;probe;version;io;homeCheck;checkUpdate;constructor(e){this.config=e.config,this.probe=e.probe,this.version=e.version,this.io=e.io??ue,this.homeCheck=e.homeCheck??XN,this.checkUpdate=e.checkUpdate??(async()=>({latest:await new Er(this.version).fetchLatest()}))}async run(){let e=[],n;try{n=this.config.resolved(),e.push({level:"ok",label:"config",detail:"valid"})}catch(r){e.push({level:"fail",label:"config",detail:`invalid - ${QN(r)}`})}e.push(this.homeLine()),n&&e.push(...await this.routeLines(n)),e.push(await this.versionLine()),e.push({level:"info",label:"project",detail:process.cwd()});let i=e.some(r=>r.level==="fail")?1:0;return this.render(e,i),i}homeLine(){let e=this.homeCheck();return e.permsOk===!1?{level:"fail",label:"home",detail:`${e.dir} - ${e.detail??"permissions wrong"}`}:e.exists?{level:"ok",label:"home",detail:`${e.dir} (${e.detail??"owner-only"})`}:{level:"info",label:"home",detail:`${e.dir} (${e.detail??"not created yet"})`}}async routeLines(e){let n=e.routes??{},i=new Map;for(let s of Q0){let a=n[s],u=a&&e.secrets?.[a.provider];a&&u&&i.set(a.provider,u)}let r=new Map;await Promise.all([...i].map(async([s,a])=>{let u=await this.probe.probe(s,a);r.set(s,u.status)}));let o=[];for(let s of Q0){let a=n[s];if(!a){o.push(this.unconfiguredLine(s));continue}let u=`${a.provider}/${a.model}`;if(!e.secrets?.[a.provider]){o.push({level:"fail",label:`${s} route`,detail:`${u} - key for '${a.provider}' is missing`});continue}o.push(this.probedLine(s,u,a.provider,r.get(a.provider)))}return o}unconfiguredLine(e){return e==="text"?{level:"fail",label:"text route",detail:"not configured - Jarvis cannot reason (run: jarvis init)"}:{level:"info",label:`${e} route`,detail:`not configured (optional, ${KN[e]})`}}probedLine(e,n,i,r){let o=`${e} route`,s=e==="text";switch(r){case"valid":return{level:"ok",label:o,detail:`${n} (key valid)`};case"invalid":return{level:s?"fail":"warn",label:o,detail:`${n} - key rejected by ${i}`};case"unreachable":return{level:"warn",label:o,detail:`${n} (key present; could not verify - offline/unreachable)`};case"unimplemented":return{level:"warn",label:o,detail:`${n} (key present; no probe for ${i})`};case"unverifiable":return{level:"warn",label:o,detail:`${n} (key present; reached ${i} but cannot verify this key here - confirmed at first use)`};default:return{level:"warn",label:o,detail:`${n} (key present; not verified)`}}}async versionLine(){let{latest:e}=await this.checkUpdate();return e===null?{level:"info",label:"version",detail:`${this.version} (could not check for updates)`}:Ir(e,this.version)?{level:"warn",label:"version",detail:`${this.version} -> ${e} available (run: jarvis upgrade)`}:{level:"ok",label:"version",detail:`${this.version} (up to date)`}}render(e,n){this.io.out(`
191
191
  ${R.bold("jarvis doctor")}
192
192
 
193
- `);for(let i of e){let r=i.detail?`: ${i.detail}`:"";this.io.out(` ${KN(i.level)} ${i.label}${r}
193
+ `);for(let i of e){let r=i.detail?`: ${i.detail}`:"";this.io.out(` ${YN(i.level)} ${i.label}${r}
194
194
  `)}this.io.out(`
195
195
  `),n!==0?this.io.out(`${R.fail("not ready")} - resolve the failing checks above (start with: jarvis init)
196
196
  `):e.some(i=>i.level==="warn")?this.io.out(`${R.warn("ready, with warnings")}
197
197
  `):this.io.out(`${R.ok("all checks passed")}
198
- `)}};function KN(t){switch(t){case"ok":return R.ok("OK ");case"warn":return R.warn("WARN");case"fail":return R.fail("FAIL");case"info":return R.dim("INFO")}}function YN(){let t=Be.dir();if(!Y0(t))return{dir:t,exists:!1,permsOk:"n/a",detail:"not created yet - run: jarvis init"};if(process.platform==="win32")return{dir:t,exists:!0,permsOk:"n/a",detail:"permissions not enforced on this platform"};let e=(X0(t).mode&63)===0,n=Be.resolve("config.json"),i=!Y0(n)||(X0(n).mode&63)===0,r=e&&i;return{dir:t,exists:!0,permsOk:r,detail:r?"owner-only":"should be owner-only (chmod 700 ~/.jarvis; chmod 600 ~/.jarvis/config.json)"}}function XN(t){return t instanceof Error?t.message:String(t)}import{styleText as ag}from"node:util";import{stdout as cg,stdin as gk}from"node:process";import*as er from"node:readline";import pR from"node:readline";var ek=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let n=0;for(t.lastIndex=0;t.test(e);)n+=1;return e.length-n}})(),tk=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,rk=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var QN=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,eR=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,nk=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,tR=/\t{1,1000}/y,ik=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,rR=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,nR=/\p{M}+/gu,iR={limit:1/0,ellipsis:""},ok=(t,e={},n={})=>{let i=e.limit??1/0,r=e.ellipsis??"",o=e?.ellipsisWidth??(r?ok(r,iR,n).width:0),s=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,d=n.regularWidth??1,f=n.wideWidth??l,h=[[rR,d],[QN,s],[eR,a],[tR,u],[ik,c],[nk,f]],p=0,_=0,S=t.length,k=0,C=!1,A=S,I=Math.max(0,i-o),T=0,Z=0,F=0,W=0;e:for(;;){if(Z>T||_>=S&&_>p){let ne=t.slice(T,Z)||t.slice(p,_);k=0;for(let $e of ne.replaceAll(nR,"")){let he=$e.codePointAt(0)||0;if(tk(he)?W=l:rk(he)?W=f:W=d,F+W>I&&(A=Math.min(A,Math.max(T,p)+k)),F+W>i){C=!0;break e}k+=$e.length,F+=W}T=Z=0}if(_>=S)break e;for(let ne=0,$e=h.length;ne<$e;ne++){let[he,Se]=h[ne];if(he.lastIndex=_,he.test(t)){if(k=he===nk?ek(t.slice(_,he.lastIndex)):he===ik?1:he.lastIndex-_,W=k*Se,F+W>I&&(A=Math.min(A,_+Math.floor((I-F)/Se))),F+W>i){C=!0;break e}F+=W,T=p,Z=_,_=p=he.lastIndex;continue e}}_+=1}return{width:C?I:F,index:C?A:S,truncated:C,ellipsed:C&&i>=o}},sk=ok;var oR={limit:1/0,ellipsis:"",ellipsisWidth:0},sR=(t,e={})=>sk(t,oR,e).width,Ae=sR;var uu="\x1B",dk="\x9B",aR=39,ng="\x07",fk="[",uR="]",hk="m",ig=`${uR}8;;`,ak=new RegExp(`(?:\\${fk}(?<code>\\d+)m|\\${ig}(?<uri>.*)${ng})`,"y"),uk=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},ck=t=>`${uu}${fk}${t}${hk}`,lk=t=>`${uu}${ig}${t}${ng}`,rg=(t,e,n)=>{let i=e[Symbol.iterator](),r=!1,o=!1,s=t.at(-1),a=s===void 0?0:Ae(s),u=i.next(),c=i.next(),l=0;for(;!u.done;){let d=u.value,f=Ae(d);a+f<=n?t[t.length-1]+=d:(t.push(d),a=0),(d===uu||d===dk)&&(r=!0,o=e.startsWith(ig,l+1)),r?o?d===ng&&(r=!1,o=!1):d===hk&&(r=!1):(a+=f,a===n&&!c.done&&(t.push(""),a=0)),u=c,c=i.next(),l+=d.length}s=t.at(-1),!a&&s!==void 0&&s.length&&t.length>1&&(t[t.length-2]+=t.pop())},cR=t=>{let e=t.split(" "),n=e.length;for(;n&&!Ae(e[n-1]);)n--;return n===e.length?t:e.slice(0,n).join(" ")+e.slice(n).join("")},lR=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let i="",r,o,s=t.split(" "),a=[""],u=0;for(let d=0;d<s.length;d++){let f=s[d];if(n.trim!==!1){let p=a.at(-1)??"",_=p.trimStart();p.length!==_.length&&(a[a.length-1]=_,u=Ae(_))}d!==0&&(u>=e&&(n.wordWrap===!1||n.trim===!1)&&(a.push(""),u=0),(u||n.trim===!1)&&(a[a.length-1]+=" ",u++));let h=Ae(f);if(n.hard&&h>e){let p=e-u,_=1+Math.floor((h-p-1)/e);Math.floor((h-1)/e)<_&&a.push(""),rg(a,f,e),u=Ae(a.at(-1)??"");continue}if(u+h>e&&u&&h){if(n.wordWrap===!1&&u<e){rg(a,f,e),u=Ae(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>e&&n.wordWrap===!1){rg(a,f,e),u=Ae(a.at(-1)??"");continue}a[a.length-1]+=f,u+=h}n.trim!==!1&&(a=a.map(d=>cR(d)));let c=a.join(`
199
- `),l=!1;for(let d=0;d<c.length;d++){let f=c[d];if(i+=f,l)l=!1;else if(l=f>="\uD800"&&f<="\uDBFF",l)continue;if(f===uu||f===dk){ak.lastIndex=d+1;let p=ak.exec(c)?.groups;if(p?.code!==void 0){let _=Number.parseFloat(p.code);r=_===aR?void 0:_}else p?.uri!==void 0&&(o=p.uri.length===0?void 0:p.uri)}if(c[d+1]===`
198
+ `)}};function YN(t){switch(t){case"ok":return R.ok("OK ");case"warn":return R.warn("WARN");case"fail":return R.fail("FAIL");case"info":return R.dim("INFO")}}function XN(){let t=Be.dir();if(!Y0(t))return{dir:t,exists:!1,permsOk:"n/a",detail:"not created yet - run: jarvis init"};if(process.platform==="win32")return{dir:t,exists:!0,permsOk:"n/a",detail:"permissions not enforced on this platform"};let e=(X0(t).mode&63)===0,n=Be.resolve("config.json"),i=!Y0(n)||(X0(n).mode&63)===0,r=e&&i;return{dir:t,exists:!0,permsOk:r,detail:r?"owner-only":"should be owner-only (chmod 700 ~/.jarvis; chmod 600 ~/.jarvis/config.json)"}}function QN(t){return t instanceof Error?t.message:String(t)}import{styleText as ag}from"node:util";import{stdout as cg,stdin as gk}from"node:process";import*as er from"node:readline";import mR from"node:readline";var ek=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let n=0;for(t.lastIndex=0;t.test(e);)n+=1;return e.length-n}})(),tk=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,rk=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var eR=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,tR=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,nk=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,rR=/\t{1,1000}/y,ik=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,nR=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,iR=/\p{M}+/gu,oR={limit:1/0,ellipsis:""},ok=(t,e={},n={})=>{let i=e.limit??1/0,r=e.ellipsis??"",o=e?.ellipsisWidth??(r?ok(r,oR,n).width:0),s=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,d=n.regularWidth??1,f=n.wideWidth??l,h=[[nR,d],[eR,s],[tR,a],[rR,u],[ik,c],[nk,f]],p=0,_=0,S=t.length,k=0,C=!1,A=S,I=Math.max(0,i-o),T=0,Z=0,F=0,W=0;e:for(;;){if(Z>T||_>=S&&_>p){let ne=t.slice(T,Z)||t.slice(p,_);k=0;for(let $e of ne.replaceAll(iR,"")){let he=$e.codePointAt(0)||0;if(tk(he)?W=l:rk(he)?W=f:W=d,F+W>I&&(A=Math.min(A,Math.max(T,p)+k)),F+W>i){C=!0;break e}k+=$e.length,F+=W}T=Z=0}if(_>=S)break e;for(let ne=0,$e=h.length;ne<$e;ne++){let[he,Se]=h[ne];if(he.lastIndex=_,he.test(t)){if(k=he===nk?ek(t.slice(_,he.lastIndex)):he===ik?1:he.lastIndex-_,W=k*Se,F+W>I&&(A=Math.min(A,_+Math.floor((I-F)/Se))),F+W>i){C=!0;break e}F+=W,T=p,Z=_,_=p=he.lastIndex;continue e}}_+=1}return{width:C?I:F,index:C?A:S,truncated:C,ellipsed:C&&i>=o}},sk=ok;var sR={limit:1/0,ellipsis:"",ellipsisWidth:0},aR=(t,e={})=>sk(t,sR,e).width,Ae=aR;var uu="\x1B",dk="\x9B",uR=39,ng="\x07",fk="[",cR="]",hk="m",ig=`${cR}8;;`,ak=new RegExp(`(?:\\${fk}(?<code>\\d+)m|\\${ig}(?<uri>.*)${ng})`,"y"),uk=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},ck=t=>`${uu}${fk}${t}${hk}`,lk=t=>`${uu}${ig}${t}${ng}`,rg=(t,e,n)=>{let i=e[Symbol.iterator](),r=!1,o=!1,s=t.at(-1),a=s===void 0?0:Ae(s),u=i.next(),c=i.next(),l=0;for(;!u.done;){let d=u.value,f=Ae(d);a+f<=n?t[t.length-1]+=d:(t.push(d),a=0),(d===uu||d===dk)&&(r=!0,o=e.startsWith(ig,l+1)),r?o?d===ng&&(r=!1,o=!1):d===hk&&(r=!1):(a+=f,a===n&&!c.done&&(t.push(""),a=0)),u=c,c=i.next(),l+=d.length}s=t.at(-1),!a&&s!==void 0&&s.length&&t.length>1&&(t[t.length-2]+=t.pop())},lR=t=>{let e=t.split(" "),n=e.length;for(;n&&!Ae(e[n-1]);)n--;return n===e.length?t:e.slice(0,n).join(" ")+e.slice(n).join("")},dR=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let i="",r,o,s=t.split(" "),a=[""],u=0;for(let d=0;d<s.length;d++){let f=s[d];if(n.trim!==!1){let p=a.at(-1)??"",_=p.trimStart();p.length!==_.length&&(a[a.length-1]=_,u=Ae(_))}d!==0&&(u>=e&&(n.wordWrap===!1||n.trim===!1)&&(a.push(""),u=0),(u||n.trim===!1)&&(a[a.length-1]+=" ",u++));let h=Ae(f);if(n.hard&&h>e){let p=e-u,_=1+Math.floor((h-p-1)/e);Math.floor((h-1)/e)<_&&a.push(""),rg(a,f,e),u=Ae(a.at(-1)??"");continue}if(u+h>e&&u&&h){if(n.wordWrap===!1&&u<e){rg(a,f,e),u=Ae(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>e&&n.wordWrap===!1){rg(a,f,e),u=Ae(a.at(-1)??"");continue}a[a.length-1]+=f,u+=h}n.trim!==!1&&(a=a.map(d=>lR(d)));let c=a.join(`
199
+ `),l=!1;for(let d=0;d<c.length;d++){let f=c[d];if(i+=f,l)l=!1;else if(l=f>="\uD800"&&f<="\uDBFF",l)continue;if(f===uu||f===dk){ak.lastIndex=d+1;let p=ak.exec(c)?.groups;if(p?.code!==void 0){let _=Number.parseFloat(p.code);r=_===uR?void 0:_}else p?.uri!==void 0&&(o=p.uri.length===0?void 0:p.uri)}if(c[d+1]===`
200
200
  `){o&&(i+=lk(""));let h=r?uk(r):void 0;r&&h&&(i+=ck(h))}else f===`
201
- `&&(r&&uk(r)&&(i+=ck(r)),o&&(i+=lk(o)))}return i},dR=/\r?\n/;function vt(t,e,n){return String(t).normalize().split(dR).map(i=>lR(i,e,n)).join(`
202
- `)}var we=Je(sg(),1);import{ReadStream as mk}from"node:tty";function Pr(t,e,n){if(!n.some(s=>!s.disabled))return t;let i=t+e,r=Math.max(n.length-1,0),o=i<0?r:i>r?0:i;return n[o].disabled?Pr(o,e<0?-1:1,n):o}var mR=["up","down","left","right","space","enter","cancel"],gR=["January","February","March","April","May","June","July","August","September","October","November","December"],fe={actions:new Set(mR),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...gR],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function lg(t,e){if(typeof t=="string")return fe.aliases.get(t)===e;for(let n of t)if(n!==void 0&&lg(n,e))return!0;return!1}function vR(t,e){if(t===e)return;let n=t.split(`
201
+ `&&(r&&uk(r)&&(i+=ck(r)),o&&(i+=lk(o)))}return i},fR=/\r?\n/;function vt(t,e,n){return String(t).normalize().split(fR).map(i=>dR(i,e,n)).join(`
202
+ `)}var we=Je(sg(),1);import{ReadStream as mk}from"node:tty";function Pr(t,e,n){if(!n.some(s=>!s.disabled))return t;let i=t+e,r=Math.max(n.length-1,0),o=i<0?r:i>r?0:i;return n[o].disabled?Pr(o,e<0?-1:1,n):o}var gR=["up","down","left","right","space","enter","cancel"],vR=["January","February","March","April","May","June","July","August","September","October","November","December"],fe={actions:new Set(gR),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...vR],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function lg(t,e){if(typeof t=="string")return fe.aliases.get(t)===e;for(let n of t)if(n!==void 0&&lg(n,e))return!0;return!1}function yR(t,e){if(t===e)return;let n=t.split(`
203
203
  `),i=e.split(`
204
- `),r=Math.max(n.length,i.length),o=[];for(let s=0;s<r;s++)n[s]!==i[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:i.length,numLines:r}}var yR=globalThis.process.platform.startsWith("win"),ug=Symbol("clack:cancel");function pu(t){return t===ug}function cu(t,e){let n=t;n.isTTY&&n.setRawMode(e)}function vk({input:t=gk,output:e=cg,overwrite:n=!0,hideCursor:i=!0}={}){let r=er.createInterface({input:t,output:e,prompt:"",tabSize:1});er.emitKeypressEvents(t,r),t instanceof mk&&t.isTTY&&t.setRawMode(!0);let o=(s,{name:a,sequence:u})=>{let c=String(s);if(lg([c,a,u],"cancel")){i&&e.write(we.cursor.show),process.exit(0);return}if(!n)return;er.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{er.clearLine(e,1,()=>{t.once("keypress",o)})})};return i&&e.write(we.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),i&&e.write(we.cursor.show),t instanceof mk&&t.isTTY&&!yR&&t.setRawMode(!1),r.terminal=!1,r.close()}}var ro=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,dg=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;function tr(t,e,n,i=n,r=n,o){let s=ro(t??cg);return vt(e,s-n.length,{hard:!0,trim:!1}).split(`
204
+ `),r=Math.max(n.length,i.length),o=[];for(let s=0;s<r;s++)n[s]!==i[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:i.length,numLines:r}}var _R=globalThis.process.platform.startsWith("win"),ug=Symbol("clack:cancel");function pu(t){return t===ug}function cu(t,e){let n=t;n.isTTY&&n.setRawMode(e)}function vk({input:t=gk,output:e=cg,overwrite:n=!0,hideCursor:i=!0}={}){let r=er.createInterface({input:t,output:e,prompt:"",tabSize:1});er.emitKeypressEvents(t,r),t instanceof mk&&t.isTTY&&t.setRawMode(!0);let o=(s,{name:a,sequence:u})=>{let c=String(s);if(lg([c,a,u],"cancel")){i&&e.write(we.cursor.show),process.exit(0);return}if(!n)return;er.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{er.clearLine(e,1,()=>{t.once("keypress",o)})})};return i&&e.write(we.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),i&&e.write(we.cursor.show),t instanceof mk&&t.isTTY&&!_R&&t.setRawMode(!1),r.terminal=!1,r.close()}}var ro=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,dg=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;function tr(t,e,n,i=n,r=n,o){let s=ro(t??cg);return vt(e,s-n.length,{hard:!0,trim:!1}).split(`
205
205
  `).map((a,u,c)=>{let l=o?o(a,u):a;return u===0?`${i}${l}`:u===c.length-1?`${r}${l}`:`${n}${l}`}).join(`
206
- `)}function yk(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}var Cr=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,n=!0){let{input:i=gk,output:r=cg,render:o,signal:s,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=o.bind(this),this._track=n,this._abortSignal=s,this.input=i,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let i=this._subscribers.get(e)??[];i.push(n),this._subscribers.set(e,i)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let i=this._subscribers.get(e)??[],r=[];for(let o of i)o.cb(...n),o.once&&r.push(()=>i.splice(i.indexOf(o),1));for(let o of r)o()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(ug);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=pR.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),cu(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(we.cursor.show),this.output.off("resize",this.render),cu(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(we.cursor.show),this.output.off("resize",this.render),cu(this.input,!1),e(ug)})})}_isActionKey(e,n){return e===" "}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&fe.aliases.has(n.name)&&this.emit("cursor",fe.aliases.get(n.name)),fe.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let i=yk(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}lg([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
206
+ `)}function yk(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}var Cr=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,n=!0){let{input:i=gk,output:r=cg,render:o,signal:s,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=o.bind(this),this._track=n,this._abortSignal=s,this.input=i,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let i=this._subscribers.get(e)??[];i.push(n),this._subscribers.set(e,i)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let i=this._subscribers.get(e)??[],r=[];for(let o of i)o.cb(...n),o.once&&r.push(()=>i.splice(i.indexOf(o),1));for(let o of r)o()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(ug);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=mR.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),cu(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(we.cursor.show),this.output.off("resize",this.render),cu(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(we.cursor.show),this.output.off("resize",this.render),cu(this.input,!1),e(ug)})})}_isActionKey(e,n){return e===" "}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&fe.aliases.has(n.name)&&this.emit("cursor",fe.aliases.get(n.name)),fe.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let i=yk(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}lg([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
207
207
  `),cu(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=vt(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
208
- `).length-1;this.output.write(we.cursor.move(-999,e*-1))}render(){let e=vt(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(we.cursor.hide);else{let n=vR(this._prevFrame,e),i=dg(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-i),o=Math.max(0,n.numLinesBefore-i),s=n.lines.find(a=>a>=r);if(s===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(we.cursor.move(0,s-o)),this.output.write(we.erase.lines(1));let a=e.split(`
208
+ `).length-1;this.output.write(we.cursor.move(-999,e*-1))}render(){let e=vt(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(we.cursor.hide);else{let n=yR(this._prevFrame,e),i=dg(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-i),o=Math.max(0,n.numLinesBefore-i),s=n.lines.find(a=>a>=r);if(s===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(we.cursor.move(0,s-o)),this.output.write(we.erase.lines(1));let a=e.split(`
209
209
  `);this.output.write(a[s]),this._prevFrame=e,this.output.write(we.cursor.move(0,a.length-s-1));return}else if(n.lines.length>1){if(r<o)s=r;else{let u=s-o;u>0&&this.output.write(we.cursor.move(0,u))}this.output.write(we.erase.down());let a=e.split(`
210
210
  `).slice(s);this.output.write(a.join(`
211
- `)),this._prevFrame=e;return}}this.output.write(we.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var lu=class extends Cr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(we.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var _k=class extends Cr{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,n=this.value!==void 0&&this.value.length===e.length;this.value=n?[]:e.map(i=>i.value)}toggleInvert(){let e=this.value;if(!e)return;let n=this._enabledOptions.filter(i=>!e.includes(i.value));this.value=n.map(i=>i.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(n=>n!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let n=Math.max(this.options.findIndex(({value:i})=>i===e.cursorAt),0);this.cursor=this.options[n].disabled?Pr(n,1,this.options):n,this.on("key",(i,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=Pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Pr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},du=class extends Cr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${ag(["inverse","hidden"],"_")}`;let n=this.masked,i=n.slice(0,this.cursor),r=n.slice(this.cursor);return`${i}${ag("inverse",r[0])}${r.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...n}){super(n),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},fu=class extends Cr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:r})=>r===e.initialValue),i=n===-1?0:n;this.cursor=this.options[i].disabled?Pr(i,1,this.options):i,this.changeValue(),this.on("cursor",r=>{switch(r){case"left":case"up":this.cursor=Pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Pr(this.cursor,1,this.options);break}this.changeValue()})}};var hu=class extends Cr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let n=e.slice(0,this.cursor),[i,...r]=e.slice(this.cursor);return`${n}${ag("inverse",i)}${r.join("")}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",n=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as y,stripVTControlCharacters as zV}from"node:util";import nt from"node:process";var io=Je(sg(),1);function _R(){return nt.platform!=="win32"?nt.env.TERM!=="linux":!!nt.env.CI||!!nt.env.WT_SESSION||!!nt.env.TERMINUS_SUBLIME||nt.env.ConEmuTask==="{cmd::Cmder}"||nt.env.TERM_PROGRAM==="Terminus-Sublime"||nt.env.TERM_PROGRAM==="vscode"||nt.env.TERM==="xterm-256color"||nt.env.TERM==="alacritty"||nt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var fg=_R(),bR=()=>process.env.CI==="true";var Y=(t,e)=>fg?t:e,$R=Y("\u25C6","*"),Sk=Y("\u25A0","x"),kk=Y("\u25B2","x"),vu=Y("\u25C7","o"),xR=Y("\u250C","T"),M=Y("\u2502","|"),yt=Y("\u2514","\u2014"),LV=Y("\u2510","T"),UV=Y("\u2518","\u2014"),hg=Y("\u25CF",">"),gu=Y("\u25CB"," "),wR=Y("\u25FB","[\u2022]"),bk=Y("\u25FC","[+]"),$k=Y("\u25FB","[ ]"),SR=Y("\u25AA","\u2022"),xk=Y("\u2500","-"),kR=Y("\u256E","+"),IR=Y("\u251C","+"),ER=Y("\u256F","+"),TR=Y("\u2570","+"),jV=Y("\u256D","+"),OR=Y("\u25CF","\u2022"),PR=Y("\u25C6","*"),CR=Y("\u25B2","!"),AR=Y("\u25A0","x"),oo=t=>{switch(t){case"initial":case"active":return y("cyan",$R);case"cancel":return y("red",Sk);case"error":return y("yellow",kk);case"submit":return y("green",vu)}},Ik=t=>{switch(t){case"initial":case"active":return y("cyan",M);case"cancel":return y("red",M);case"error":return y("yellow",M);case"submit":return y("green",M)}},wk=(t,e,n,i,r,o=!1)=>{let s=e,a=0;if(o)for(let u=i-1;u>=n&&(s-=t[u].length,a++,!(s<=r));u--);else for(let u=n;u<i&&(s-=t[u].length,a++,!(s<=r));u++);return{lineCount:s,removals:a}},pg=({cursor:t,options:e,style:n,output:i=process.stdout,maxItems:r=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let a=ro(i)-o,u=dg(i),c=y("dim","..."),l=Math.max(u-s,0),d=Math.max(Math.min(r,l),5),f=0;t>=d-3&&(f=Math.max(Math.min(t-d+3,e.length-d),0));let h=d<e.length&&f>0,p=d<e.length&&f+d<e.length,_=Math.min(f+d,e.length),S=[],k=0;h&&k++,p&&k++;let C=f+(h?1:0),A=_-(p?1:0);for(let T=C;T<A;T++){let Z=vt(n(e[T],T===t),a,{hard:!0,trim:!1}).split(`
211
+ `)),this._prevFrame=e;return}}this.output.write(we.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var lu=class extends Cr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(we.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var _k=class extends Cr{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,n=this.value!==void 0&&this.value.length===e.length;this.value=n?[]:e.map(i=>i.value)}toggleInvert(){let e=this.value;if(!e)return;let n=this._enabledOptions.filter(i=>!e.includes(i.value));this.value=n.map(i=>i.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(n=>n!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let n=Math.max(this.options.findIndex(({value:i})=>i===e.cursorAt),0);this.cursor=this.options[n].disabled?Pr(n,1,this.options):n,this.on("key",(i,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=Pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Pr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},du=class extends Cr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${ag(["inverse","hidden"],"_")}`;let n=this.masked,i=n.slice(0,this.cursor),r=n.slice(this.cursor);return`${i}${ag("inverse",r[0])}${r.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...n}){super(n),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},fu=class extends Cr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:r})=>r===e.initialValue),i=n===-1?0:n;this.cursor=this.options[i].disabled?Pr(i,1,this.options):i,this.changeValue(),this.on("cursor",r=>{switch(r){case"left":case"up":this.cursor=Pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Pr(this.cursor,1,this.options);break}this.changeValue()})}};var hu=class extends Cr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let n=e.slice(0,this.cursor),[i,...r]=e.slice(this.cursor);return`${n}${ag("inverse",i)}${r.join("")}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",n=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as y,stripVTControlCharacters as NV}from"node:util";import nt from"node:process";var io=Je(sg(),1);function bR(){return nt.platform!=="win32"?nt.env.TERM!=="linux":!!nt.env.CI||!!nt.env.WT_SESSION||!!nt.env.TERMINUS_SUBLIME||nt.env.ConEmuTask==="{cmd::Cmder}"||nt.env.TERM_PROGRAM==="Terminus-Sublime"||nt.env.TERM_PROGRAM==="vscode"||nt.env.TERM==="xterm-256color"||nt.env.TERM==="alacritty"||nt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var fg=bR(),$R=()=>process.env.CI==="true";var Y=(t,e)=>fg?t:e,xR=Y("\u25C6","*"),Sk=Y("\u25A0","x"),kk=Y("\u25B2","x"),vu=Y("\u25C7","o"),wR=Y("\u250C","T"),M=Y("\u2502","|"),yt=Y("\u2514","\u2014"),UV=Y("\u2510","T"),jV=Y("\u2518","\u2014"),hg=Y("\u25CF",">"),gu=Y("\u25CB"," "),SR=Y("\u25FB","[\u2022]"),bk=Y("\u25FC","[+]"),$k=Y("\u25FB","[ ]"),kR=Y("\u25AA","\u2022"),xk=Y("\u2500","-"),IR=Y("\u256E","+"),ER=Y("\u251C","+"),TR=Y("\u256F","+"),OR=Y("\u2570","+"),MV=Y("\u256D","+"),PR=Y("\u25CF","\u2022"),CR=Y("\u25C6","*"),AR=Y("\u25B2","!"),zR=Y("\u25A0","x"),oo=t=>{switch(t){case"initial":case"active":return y("cyan",xR);case"cancel":return y("red",Sk);case"error":return y("yellow",kk);case"submit":return y("green",vu)}},Ik=t=>{switch(t){case"initial":case"active":return y("cyan",M);case"cancel":return y("red",M);case"error":return y("yellow",M);case"submit":return y("green",M)}},wk=(t,e,n,i,r,o=!1)=>{let s=e,a=0;if(o)for(let u=i-1;u>=n&&(s-=t[u].length,a++,!(s<=r));u--);else for(let u=n;u<i&&(s-=t[u].length,a++,!(s<=r));u++);return{lineCount:s,removals:a}},pg=({cursor:t,options:e,style:n,output:i=process.stdout,maxItems:r=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let a=ro(i)-o,u=dg(i),c=y("dim","..."),l=Math.max(u-s,0),d=Math.max(Math.min(r,l),5),f=0;t>=d-3&&(f=Math.max(Math.min(t-d+3,e.length-d),0));let h=d<e.length&&f>0,p=d<e.length&&f+d<e.length,_=Math.min(f+d,e.length),S=[],k=0;h&&k++,p&&k++;let C=f+(h?1:0),A=_-(p?1:0);for(let T=C;T<A;T++){let Z=vt(n(e[T],T===t),a,{hard:!0,trim:!1}).split(`
212
212
  `);S.push(Z),k+=Z.length}if(k>l){let T=0,Z=0,F=k,W=t-C,ne=l,$e=()=>wk(S,F,0,W,ne),he=()=>wk(S,F,W+1,S.length,ne,!0);h?({lineCount:F,removals:T}=$e(),F>ne&&(p||(ne-=1),{lineCount:F,removals:Z}=he())):(p||(ne-=1),{lineCount:F,removals:Z}=he(),F>ne&&(ne-=1,{lineCount:F,removals:T}=$e())),T>0&&(h=!0,S.splice(0,T)),Z>0&&(p=!0,S.splice(S.length-Z,Z))}let I=[];h&&I.push(c);for(let T of S)for(let Z of T)I.push(Z);return p&&I.push(c),I};var yu=t=>{let e=t.active??"Yes",n=t.inactive??"No";return new lu({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let i=t.withGuide??fe.withGuide,r=`${oo(this.state)} `,o=i?`${y("gray",M)} `:"",s=tr(t.output,t.message,o,r),a=`${i?`${y("gray",M)}
213
213
  `:""}${s}
214
214
  `,u=this.value?e:n;switch(this.state){case"submit":{let c=i?`${y("gray",M)} `:"";return`${a}${c}${y("dim",u)}`}case"cancel":{let c=i?`${y("gray",M)} `:"";return`${a}${c}${y(["strikethrough","dim"],u)}${i?`
@@ -219,15 +219,15 @@ ${l}
219
219
  `}}}}).prompt()};var qe={message:(t=[],{symbol:e=y("gray",M),secondarySymbol:n=y("gray",M),output:i=process.stdout,spacing:r=1,withGuide:o}={})=>{let s=[],a=o??fe.withGuide,u=a?n:"",c=a?`${e} `:"",l=a?`${n} `:"";for(let f=0;f<r;f++)s.push(u);let d=Array.isArray(t)?t:t.split(`
220
220
  `);if(d.length>0){let[f,...h]=d;f.length>0?s.push(`${c}${f}`):s.push(a?e:"");for(let p of h)p.length>0?s.push(`${l}${p}`):s.push(a?n:"")}i.write(`${s.join(`
221
221
  `)}
222
- `)},info:(t,e)=>{qe.message(t,{...e,symbol:y("blue",OR)})},success:(t,e)=>{qe.message(t,{...e,symbol:y("green",PR)})},step:(t,e)=>{qe.message(t,{...e,symbol:y("green",vu)})},warn:(t,e)=>{qe.message(t,{...e,symbol:y("yellow",CR)})},warning:(t,e)=>{qe.warn(t,e)},error:(t,e)=>{qe.message(t,{...e,symbol:y("red",AR)})}},Ek=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",yt)} `:"";n.write(`${i}${y("red",t)}
222
+ `)},info:(t,e)=>{qe.message(t,{...e,symbol:y("blue",PR)})},success:(t,e)=>{qe.message(t,{...e,symbol:y("green",CR)})},step:(t,e)=>{qe.message(t,{...e,symbol:y("green",vu)})},warn:(t,e)=>{qe.message(t,{...e,symbol:y("yellow",AR)})},warning:(t,e)=>{qe.warn(t,e)},error:(t,e)=>{qe.message(t,{...e,symbol:y("red",zR)})}},Ek=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",yt)} `:"";n.write(`${i}${y("red",t)}
223
223
 
224
- `)},Tk=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",xR)} `:"";n.write(`${i}${t}
224
+ `)},Tk=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",wR)} `:"";n.write(`${i}${t}
225
225
  `)},Ok=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",M)}
226
226
  ${y("gray",yt)} `:"";n.write(`${i}${t}
227
227
 
228
228
  `)};var no=(t,e)=>t.split(`
229
229
  `).map(n=>e(n)).join(`
230
- `),Pk=t=>{let e=(i,r)=>{let o=i.label??String(i.value);return r==="disabled"?`${y("gray",$k)} ${no(o,s=>y(["strikethrough","gray"],s))}${i.hint?` ${y("dim",`(${i.hint??"disabled"})`)}`:""}`:r==="active"?`${y("cyan",wR)} ${o}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="selected"?`${y("green",bk)} ${no(o,s=>y("dim",s))}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="cancelled"?`${no(o,s=>y(["strikethrough","dim"],s))}`:r==="active-selected"?`${y("green",bk)} ${o}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="submitted"?`${no(o,s=>y("dim",s))}`:`${y("dim",$k)} ${no(o,s=>y("dim",s))}`},n=t.required??!0;return new _k({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
230
+ `),Pk=t=>{let e=(i,r)=>{let o=i.label??String(i.value);return r==="disabled"?`${y("gray",$k)} ${no(o,s=>y(["strikethrough","gray"],s))}${i.hint?` ${y("dim",`(${i.hint??"disabled"})`)}`:""}`:r==="active"?`${y("cyan",SR)} ${o}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="selected"?`${y("green",bk)} ${no(o,s=>y("dim",s))}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="cancelled"?`${no(o,s=>y(["strikethrough","dim"],s))}`:r==="active-selected"?`${y("green",bk)} ${o}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="submitted"?`${no(o,s=>y("dim",s))}`:`${y("dim",$k)} ${no(o,s=>y("dim",s))}`},n=t.required??!0;return new _k({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
231
231
  ${y("reset",y("dim",`Press ${y(["gray","bgWhite","inverse"]," space ")} to select, ${y("gray",y("bgWhite",y("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??fe.withGuide,r=tr(t.output,t.message,i?`${Ik(this.state)} `:"",`${oo(this.state)} `),o=`${i?`${y("gray",M)}
232
232
  `:""}${r}
233
233
  `,s=this.value??[],a=(u,c)=>{if(u.disabled)return e(u,"disabled");let l=s.includes(u.value);return c&&l?e(u,"active-selected"):l?e(u,"selected"):e(u,c?"active":"inactive")};switch(this.state){case"submit":{let u=this.options.filter(({value:l})=>s.includes(l)).map(l=>e(l,"submitted")).join(y("dim",", "))||y("dim","none"),c=tr(t.output,u,i?`${y("gray",M)} `:"");return`${o}${c}`}case"cancel":{let u=this.options.filter(({value:l})=>s.includes(l)).map(l=>e(l,"cancelled")).join(y("dim",", "));if(u.trim()==="")return`${o}${y("gray",M)}`;let c=tr(t.output,u,i?`${y("gray",M)} `:"");return`${o}${c}${i?`
@@ -242,14 +242,14 @@ ${c}
242
242
  `).length,l=i?2:1;return`${o}${u}${pg({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:u.length,rowPadding:c+l,style:a}).join(`
243
243
  ${u}`)}
244
244
  ${i?y("cyan",yt):""}
245
- `}}}}).prompt()},zR=t=>y("dim",t),NR=(t,e,n)=>{let i={hard:!0,trim:!1},r=vt(t,e,i).split(`
246
- `),o=r.reduce((u,c)=>Math.max(Ae(c),u),0),s=r.map(n).reduce((u,c)=>Math.max(Ae(c),u),0),a=e-(s-o);return vt(t,a,i)},mg=(t="",e="",n)=>{let i=n?.output??nt.stdout,r=n?.withGuide??fe.withGuide,o=n?.format??zR,s=["",...NR(t,ro(i)-6,o).split(`
245
+ `}}}}).prompt()},NR=t=>y("dim",t),RR=(t,e,n)=>{let i={hard:!0,trim:!1},r=vt(t,e,i).split(`
246
+ `),o=r.reduce((u,c)=>Math.max(Ae(c),u),0),s=r.map(n).reduce((u,c)=>Math.max(Ae(c),u),0),a=e-(s-o);return vt(t,a,i)},mg=(t="",e="",n)=>{let i=n?.output??nt.stdout,r=n?.withGuide??fe.withGuide,o=n?.format??NR,s=["",...RR(t,ro(i)-6,o).split(`
247
247
  `).map(o),""],a=Ae(e),u=Math.max(s.reduce((f,h)=>{let p=Ae(h);return p>f?p:f},0),a)+2,c=s.map(f=>`${y("gray",M)} ${f}${" ".repeat(u-Ae(f))}${y("gray",M)}`).join(`
248
248
  `),l=r?`${y("gray",M)}
249
- `:"",d=r?IR:TR;i.write(`${l}${y("green",vu)} ${y("reset",e)} ${y("gray",xk.repeat(Math.max(u-a-1,1))+kR)}
249
+ `:"",d=r?ER:OR;i.write(`${l}${y("green",vu)} ${y("reset",e)} ${y("gray",xk.repeat(Math.max(u-a-1,1))+IR)}
250
250
  ${c}
251
- ${y("gray",d+xk.repeat(u+2)+ER)}
252
- `)},Ck=t=>new du({validate:t.validate,mask:t.mask??SR,signal:t.signal,input:t.input,output:t.output,render(){let e=t.withGuide??fe.withGuide,n=`${e?`${y("gray",M)}
251
+ ${y("gray",d+xk.repeat(u+2)+TR)}
252
+ `)},Ck=t=>new du({validate:t.validate,mask:t.mask??kR,signal:t.signal,input:t.input,output:t.output,render(){let e=t.withGuide??fe.withGuide,n=`${e?`${y("gray",M)}
253
253
  `:""}${oo(this.state)} ${t.message}
254
254
  `,i=this.userInputWithCursor,r=this.masked;switch(this.state){case"error":{let o=e?`${y("yellow",M)} `:"",s=e?`${y("yellow",yt)} `:"",a=r??"";return t.clearOnError&&this.clear(),`${n.trim()}
255
255
  ${o}${a}
@@ -257,12 +257,12 @@ ${s}${y("yellow",this.error)}
257
257
  `}case"submit":{let o=e?`${y("gray",M)} `:"",s=r?y("dim",r):"";return`${n}${o}${s}`}case"cancel":{let o=e?`${y("gray",M)} `:"",s=r?y(["strikethrough","dim"],r):"";return`${n}${o}${s}${r&&e?`
258
258
  ${y("gray",M)}`:""}`}default:{let o=e?`${y("cyan",M)} `:"",s=e?y("cyan",yt):"";return`${n}${o}${i}
259
259
  ${s}
260
- `}}}}).prompt();var RR=t=>y("magenta",t),Ak=({indicator:t="dots",onCancel:e,output:n=process.stdout,cancelMessage:i,errorMessage:r,frames:o=fg?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:s=fg?80:120,signal:a,...u}={})=>{let c=bR(),l,d,f=!1,h=!1,p="",_,S=performance.now(),k=ro(n),C=u?.styleFrame??RR,A=Q=>{let D=Q>1?r??fe.messages.error:i??fe.messages.cancel;h=Q===1,f&&(ke(D,Q),h&&typeof e=="function"&&e())},I=()=>A(2),T=()=>A(1),Z=()=>{process.on("uncaughtExceptionMonitor",I),process.on("unhandledRejection",I),process.on("SIGINT",T),process.on("SIGTERM",T),process.on("exit",A),a&&a.addEventListener("abort",T)},F=()=>{process.removeListener("uncaughtExceptionMonitor",I),process.removeListener("unhandledRejection",I),process.removeListener("SIGINT",T),process.removeListener("SIGTERM",T),process.removeListener("exit",A),a&&a.removeEventListener("abort",T)},W=()=>{if(_===void 0)return;c&&n.write(`
260
+ `}}}}).prompt();var DR=t=>y("magenta",t),Ak=({indicator:t="dots",onCancel:e,output:n=process.stdout,cancelMessage:i,errorMessage:r,frames:o=fg?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:s=fg?80:120,signal:a,...u}={})=>{let c=$R(),l,d,f=!1,h=!1,p="",_,S=performance.now(),k=ro(n),C=u?.styleFrame??DR,A=Q=>{let D=Q>1?r??fe.messages.error:i??fe.messages.cancel;h=Q===1,f&&(ke(D,Q),h&&typeof e=="function"&&e())},I=()=>A(2),T=()=>A(1),Z=()=>{process.on("uncaughtExceptionMonitor",I),process.on("unhandledRejection",I),process.on("SIGINT",T),process.on("SIGTERM",T),process.on("exit",A),a&&a.addEventListener("abort",T)},F=()=>{process.removeListener("uncaughtExceptionMonitor",I),process.removeListener("unhandledRejection",I),process.removeListener("SIGINT",T),process.removeListener("SIGTERM",T),process.removeListener("exit",A),a&&a.removeEventListener("abort",T)},W=()=>{if(_===void 0)return;c&&n.write(`
261
261
  `);let Q=vt(_,k,{hard:!0,trim:!1}).split(`
262
262
  `);Q.length>1&&n.write(io.cursor.up(Q.length-1)),n.write(io.cursor.to(0)),n.write(io.erase.down())},ne=Q=>Q.replace(/\.+$/,""),$e=Q=>{let D=(performance.now()-Q)/1e3,ce=Math.floor(D/60),it=Math.floor(D%60);return ce>0?`[${ce}m ${it}s]`:`[${it}s]`},he=u.withGuide??fe.withGuide,Se=(Q="")=>{f=!0,l=vk({output:n}),p=ne(Q),S=performance.now(),he&&n.write(`${y("gray",M)}
263
263
  `);let D=0,ce=0;Z(),d=setInterval(()=>{if(c&&p===_)return;W(),_=p;let it=C(o[D]),je;if(c)je=`${it} ${p}...`;else if(t==="timer")je=`${it} ${p} ${$e(S)}`;else{let le=".".repeat(Math.floor(ce)).slice(0,3);je=`${it} ${p}${le}`}let Ar=vt(je,k,{hard:!0,trim:!1});n.write(Ar),D=D+1<o.length?D+1:0,ce=ce<4?ce+.125:0},s)},ke=(Q="",D=0,ce=!1)=>{if(!f)return;f=!1,clearInterval(d),W();let it=D===0?y("green",vu):D===1?y("red",Sk):y("red",kk);p=Q??p,ce||(t==="timer"?n.write(`${it} ${p} ${$e(S)}
264
264
  `):n.write(`${it} ${p}
265
- `)),F(),l()};return{start:Se,stop:(Q="")=>ke(Q,0),message:(Q="")=>{p=ne(Q??p)},cancel:(Q="")=>ke(Q,1),error:(Q="")=>ke(Q,2),clear:()=>ke("",0,!0),get isCancelled(){return h}}},MV={light:Y("\u2500","-"),heavy:Y("\u2501","="),block:Y("\u2588","#")};var mu=(t,e)=>t.includes(`
265
+ `)),F(),l()};return{start:Se,stop:(Q="")=>ke(Q,0),message:(Q="")=>{p=ne(Q??p)},cancel:(Q="")=>ke(Q,1),error:(Q="")=>ke(Q,2),clear:()=>ke("",0,!0),get isCancelled(){return h}}},FV={light:Y("\u2500","-"),heavy:Y("\u2501","="),block:Y("\u2588","#")};var mu=(t,e)=>t.includes(`
266
266
  `)?t.split(`
267
267
  `).map(n=>e(n)).join(`
268
268
  `):e(t),so=t=>{let e=(n,i)=>{let r=n.label??String(n.value);switch(i){case"disabled":return`${y("gray",gu)} ${mu(r,o=>y("gray",o))}${n.hint?` ${y("dim",`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${mu(r,o=>y("dim",o))}`;case"active":return`${y("green",hg)} ${r}${n.hint?` ${y("dim",`(${n.hint})`)}`:""}`;case"cancelled":return`${mu(r,o=>y(["strikethrough","dim"],o))}`;default:return`${y("dim",gu)} ${mu(r,o=>y("dim",o))}`}};return new fu({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let n=t.withGuide??fe.withGuide,i=`${oo(this.state)} `,r=`${Ik(this.state)} `,o=tr(t.output,t.message,r,i),s=`${n?`${y("gray",M)}
@@ -272,7 +272,7 @@ ${y("gray",M)}`:""}`}default:{let a=n?`${y("cyan",M)} `:"",u=n?y("cyan",yt):"",
272
272
  `).length,l=n?2:1;return`${s}${a}${pg({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:a.length,rowPadding:c+l,style:(d,f)=>e(d,d.disabled?"disabled":f?"active":"inactive")}).join(`
273
273
  ${a}`)}
274
274
  ${u}
275
- `}}}}).prompt()};var FV=`${y("gray",M)} `;var zk=t=>new hu({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??fe.withGuide,n=`${`${e?`${y("gray",M)}
275
+ `}}}}).prompt()};var VV=`${y("gray",M)} `;var zk=t=>new hu({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??fe.withGuide,n=`${`${e?`${y("gray",M)}
276
276
  `:""}${oo(this.state)} `}${t.message}
277
277
  `,i=t.placeholder?y("inverse",t.placeholder[0])+y("dim",t.placeholder.slice(1)):y(["inverse","hidden"],"_"),r=this.userInput?this.userInputWithCursor:i,o=this.value??"";switch(this.state){case"error":{let s=this.error?` ${y("yellow",this.error)}`:"",a=e?`${y("yellow",M)} `:"",u=e?y("yellow",yt):"";return`${n.trim()}
278
278
  ${a}${r}
@@ -280,30 +280,30 @@ ${u}${s}
280
280
  `}case"submit":{let s=o?` ${y("dim",o)}`:"",a=e?y("gray",M):"";return`${n}${a}${s}`}case"cancel":{let s=o?` ${y(["strikethrough","dim"],o)}`:"",a=e?y("gray",M):"";return`${n}${a}${s}${o.trim()?`
281
281
  ${a}`:""}`}default:{let s=e?`${y("cyan",M)} `:"",a=e?y("cyan",yt):"";return`${n}${s}${r}
282
282
  ${a}
283
- `}}}}).prompt();De();hr();var DR={brain:["text"],voice:["stt","tts"],memory:["embedding"]},Nk=["brain","voice","memory"],gg="brain",LR=["text","stt","tts","embedding"];function UR(t){return t==="text"}function Rk(t){let e=new Set;for(let n of t)for(let i of DR[n])e.add(i);return LR.filter(n=>e.has(n))}function Dk(t){let e=["brain"],n=t.routes;return(n?.stt||n?.tts)&&e.push("voice"),n?.embedding&&e.push("memory"),e}function Lk(t,e){if(e==="valid")return[];let n=UR(t);return e==="invalid"?n?["retry","change"]:["retry","change","skip"]:n?["save","retry","change"]:["save","retry","change","skip"]}function Uk(t){let e={},n={};for(let r of t.routes){e[r.capability]={provider:r.provider,model:r.model};let o=t.keys.get(r.provider);o!==void 0&&o.length>0&&(n[r.provider]=o)}let i={version:t.existing.version,defaults:{logLevel:t.logLevel,modality:t.modality},upgrade:{auto:t.existing.upgrade.auto}};return Object.keys(e).length>0&&(i.routes=e),Object.keys(n).length>0&&(i.secrets=n),i}function jk(t,e){return!!t.isTTY&&!!e.isTTY}var ao=class extends Error{},Mk={save:{label:"save anyway",hint:"keep this key; verify later with jarvis doctor"},retry:{label:"re-enter the key"},change:{label:"choose a different provider"},skip:{label:"skip this capability",hint:"optional"}},_u=class{config;probe;io;stdin;stdout;constructor(e){this.config=e.config,this.probe=e.probe,this.io=e.io??ue,this.stdin=e.stdin??process.stdin,this.stdout=e.stdout??process.stdout}async run(){if(!jk(this.stdin,this.stdout))return this.printHeadlessGuidance(),1;try{return await this.wizard()}catch(e){if(e instanceof ao)return Ek("no changes written."),130;throw e}}loadExisting(){try{return{config:this.config.resolved(),corrupt:!1}}catch{return{config:fr.parse({}),corrupt:!0}}}async wizard(){let{config:e,corrupt:n}=this.loadExisting(),i=!n&&!!(e.routes??e.secrets);Tk(R.bold("jarvis init")),n&&qe.warn("the existing config.json is invalid; init will replace it with a fresh config."),mg(`Writes ${R.accent(Be.resolve("config.json"))} (owner-only).`+(i?`
283
+ `}}}}).prompt();De();hr();var LR={brain:["text"],voice:["stt","tts"],memory:["embedding"]},Nk=["brain","voice","memory"],gg="brain",UR=["text","stt","tts","embedding"];function jR(t){return t==="text"}function Rk(t){let e=new Set;for(let n of t)for(let i of LR[n])e.add(i);return UR.filter(n=>e.has(n))}function Dk(t){let e=["brain"],n=t.routes;return(n?.stt||n?.tts)&&e.push("voice"),n?.embedding&&e.push("memory"),e}function Lk(t,e){if(e==="valid")return[];let n=jR(t);return e==="invalid"?n?["retry","change"]:["retry","change","skip"]:n?["save","retry","change"]:["save","retry","change","skip"]}function Uk(t){let e={},n={};for(let r of t.routes){e[r.capability]={provider:r.provider,model:r.model};let o=t.keys.get(r.provider);o!==void 0&&o.length>0&&(n[r.provider]=o)}let i={version:t.existing.version,defaults:{logLevel:t.logLevel,modality:t.modality},upgrade:{auto:t.existing.upgrade.auto}};return Object.keys(e).length>0&&(i.routes=e),Object.keys(n).length>0&&(i.secrets=n),i}function jk(t,e){return!!t.isTTY&&!!e.isTTY}var ao=class extends Error{},Mk={save:{label:"save anyway",hint:"keep this key; verify later with jarvis doctor"},retry:{label:"re-enter the key"},change:{label:"choose a different provider"},skip:{label:"skip this capability",hint:"optional"}},_u=class{config;probe;io;stdin;stdout;constructor(e){this.config=e.config,this.probe=e.probe,this.io=e.io??ue,this.stdin=e.stdin??process.stdin,this.stdout=e.stdout??process.stdout}async run(){if(!jk(this.stdin,this.stdout))return this.printHeadlessGuidance(),1;try{return await this.wizard()}catch(e){if(e instanceof ao)return Ek("no changes written."),130;throw e}}loadExisting(){try{return{config:this.config.resolved(),corrupt:!1}}catch{return{config:fr.parse({}),corrupt:!0}}}async wizard(){let{config:e,corrupt:n}=this.loadExisting(),i=!n&&!!(e.routes??e.secrets);Tk(R.bold("jarvis init")),n&&qe.warn("the existing config.json is invalid; init will replace it with a fresh config."),mg(`Writes ${R.accent(Be.resolve("config.json"))} (owner-only).`+(i?`
284
284
  A config already exists - values are prefilled; edit or keep them.`:""),"setup");let r=await this.pickCapabilities(e),o=new Map,s=[];for(let d of Rk(r)){let f=await this.configureCapability(d,e,o);f&&s.push(f)}let a=this.ensure(await so({message:"Default modality",options:[{value:"voice",label:"voice",hint:"speak and listen when available"},{value:"text",label:"text",hint:"text-only"}],initialValue:e.defaults.modality})),u=this.ensure(await so({message:"Log level",options:["debug","info","warn","error"].map(d=>({value:d,label:d})),initialValue:e.defaults.logLevel}));if(this.review(s,o,a,u),!this.ensure(await yu({message:"Write this configuration?"})))throw new ao;return this.config.write(Uk({existing:e,routes:s,keys:o,modality:a,logLevel:u})),qe.success(`wrote ${Be.resolve("config.json")}`),await yu({message:"Start Jarvis now?",initialValue:!1})===!0&&qe.info("starting is not wired yet in v0.1 - run `jarvis` to begin a session."),Ok(R.ok("done.")),0}async pickCapabilities(e){let n=this.ensure(await Pk({message:"Which capabilities do you want to set up?",options:[{value:"brain",label:"Brain (text)",hint:"required - the reasoning model"},{value:"voice",label:"Voice (speech in + out)",hint:"optional"},{value:"memory",label:"Memory (embeddings)",hint:"optional"}],initialValues:Dk(e),required:!1}));n.includes(gg)||qe.warn("Brain (text) is required; keeping it selected.");let i=new Set(n);return i.add(gg),Nk.filter(r=>i.has(r))}async configureCapability(e,n,i){let r=this.probe.providersFor(e);if(r.length===0)return qe.warn(`no providers available for ${e}; skipping.`),null;for(;;){let o=await this.pickProvider(e,r,n),s=await this.pickModel(e,o,n);if(i.has(o))return{capability:e,provider:o,model:s};let a=await this.resolveKey(e,o,s,n,i);if(a!=="change-provider")return a}}async resolveKey(e,n,i,r,o){let s=await this.firstKey(n,r);for(;;){let a=await this.validateKey(n,s);if(a==="valid")return o.set(n,s),{capability:e,provider:n,model:i};let u=await this.pickAfterFailure(e,a);if(u==="save")return o.set(n,s),{capability:e,provider:n,model:i};if(u==="skip")return qe.info(`skipped ${e} (optional).`),null;if(u==="change")return"change-provider";s=await this.promptPassword(n)}}async pickProvider(e,n,i){let r=i.routes?.[e]?.provider;return this.ensure(await so({message:`${e} provider`,options:n.map(o=>({value:o,label:o})),initialValue:r&&n.includes(r)?r:void 0}))}async pickModel(e,n,i){let r=i.routes?.[e],o=r?.provider===n?r.model:this.probe.defaultModel(n,e)??"";return this.ensure(await zk({message:`${e} model`,initialValue:o,validate:s=>s?.trim()?void 0:"a model is required"}))}async firstKey(e,n){let i=n.secrets?.[e];return i&&this.ensure(await yu({message:`Reuse the saved key for ${e}?`,initialValue:!0}))?i.trim():this.promptPassword(e)}async promptPassword(e){return this.ensure(await Ck({message:`${e} API key`,validate:i=>i?.trim()?void 0:"a key is required"})).trim()}async validateKey(e,n){let i=Ak();i.start(`validating ${e} key...`);let r=await this.probe.probe(e,n),o=r.detail?` (${r.detail})`:"";return r.ok?i.stop(R.ok(`${e} key valid`)):r.status==="invalid"?i.stop(R.fail(`${e} key rejected${o}`)):r.status==="unverifiable"?i.stop(R.warn(`could not verify ${e} here${o}`)):i.stop(R.warn(`could not validate ${e}${o}`)),r.status}async pickAfterFailure(e,n){let i=Lk(e,n);return this.ensure(await so({message:`${e}: how do you want to proceed?`,options:i.map(r=>({value:r,label:Mk[r].label,hint:Mk[r].hint}))}))}review(e,n,i,r){let o=[];if(e.length===0)o.push("routes: none");else for(let s of e){let a=n.has(s.provider)?R.ok("key set"):R.warn("no key");o.push(`${s.capability}: ${s.provider}/${s.model} (${a})`)}o.push(`defaults: modality=${i}, logLevel=${r}`),mg(o.join(`
285
285
  `),"review (secrets redacted)")}printHeadlessGuidance(){this.io.err(["jarvis init needs an interactive terminal.","","On a headless or non-interactive host:"," - run `jarvis init` over an interactive SSH session, or"," - set secrets and defaults non-interactively, e.g.:"," jarvis config set secrets.anthropic <key>"," jarvis config set defaults.modality text"," - relocate the home with the JARVIS_HOME env var if needed.","","Note: configuring a provider route (provider + model together) is interactive","in v0.1 - use `jarvis init` for that. Verify any setup with: jarvis doctor"].join(`
286
286
  `)+`
287
- `)}ensure(e){if(pu(e))throw new ao;return e}};xi();import{randomUUID as jR}from"node:crypto";var vg=class{constructor(e,n,i=ue){this.session=e;this.reader=n;this.io=i}session;reader;io;prompt="you ";labelShown=!1;async run(){try{for await(let e of this.session.events())if(!await this.handle(e))break}finally{this.reader.close(),await this.session.close()}}async handle(e){switch(e.type){case"session.ready":return this.greet(),this.promptAndSend();case"turn.accepted":return this.labelShown=!1,!0;case"state":return e.state==="responding"&&this.showLabel(),!0;case"response.delta":return this.showLabel(),this.io.out(e.text),!0;case"response.done":return this.labelShown&&this.io.out(`
287
+ `)}ensure(e){if(pu(e))throw new ao;return e}};xi();import{randomUUID as MR}from"node:crypto";var vg=class{constructor(e,n,i=ue){this.session=e;this.reader=n;this.io=i}session;reader;io;prompt="you ";labelShown=!1;async run(){try{for await(let e of this.session.events())if(!await this.handle(e))break}finally{this.reader.close(),await this.session.close()}}async handle(e){switch(e.type){case"session.ready":return this.greet(),this.promptAndSend();case"turn.accepted":return this.labelShown=!1,!0;case"state":return e.state==="responding"&&this.showLabel(),!0;case"response.delta":return this.showLabel(),this.io.out(e.text),!0;case"response.done":return this.labelShown&&this.io.out(`
288
288
  `),this.promptAndSend();case"error":return this.labelShown&&this.io.out(`
289
- `),this.renderError(e),this.promptAndSend();default:return!0}}async promptAndSend(){for(;;){let e=await this.reader.next(this.prompt);if(e===null)return!1;let n=e.trim();if(n.length!==0)try{return await this.session.send({type:"input.text",sessionId:this.session.sessionId,commandId:jR(),atMs:Date.now(),text:n}),!0}catch(i){if(i instanceof Le){if(i.reason==="closed")return!1;this.renderSendError(i);continue}throw i}}}greet(){this.io.out(R.dim("jarvis is ready. type a message, or press ctrl-c to exit.")+`
289
+ `),this.renderError(e),this.promptAndSend();default:return!0}}async promptAndSend(){for(;;){let e=await this.reader.next(this.prompt);if(e===null)return!1;let n=e.trim();if(n.length!==0)try{return await this.session.send({type:"input.text",sessionId:this.session.sessionId,commandId:MR(),atMs:Date.now(),text:n}),!0}catch(i){if(i instanceof Le){if(i.reason==="closed")return!1;this.renderSendError(i);continue}throw i}}}greet(){this.io.out(R.dim("jarvis is ready. type a message, or press ctrl-c to exit.")+`
290
290
  `)}showLabel(){this.labelShown||(this.io.out(R.dim("jarvis")+" "),this.labelShown=!0)}renderError(e){if(e.reason==="no_text_route"){this.io.out(R.warn("no brain configured yet - run `jarvis init` to add one.")+`
291
291
  `);return}this.io.out(R.fail(`something went wrong - ${e.message}`)+`
292
292
  `)}renderSendError(e){this.io.out(R.warn(`could not send that (${e.reason}) - ${e.message}`)+`
293
293
  `)}};async function Fk(t){if(!t.stdin.isTTY)return t.io.err(R.dim("jarvis is interactive - run it in a terminal.")+`
294
294
  `),1;let e;try{e=await t.openSession()}catch{return t.io.err(R.fail("could not start jarvis - your config may be invalid. run `jarvis doctor`.")+`
295
- `),1}let n=t.createReader();return await new vg(e,n,t.io).run(),0}import{createInterface as MR}from"node:readline";var bu=class{rl;closed=!1;pending=null;constructor(e,n){this.rl=MR({input:e,output:n}),this.rl.on("line",i=>this.settle(i)),this.rl.on("close",()=>{this.closed=!0,this.settle(null)}),this.rl.on("SIGINT",()=>this.close())}next(e){return this.closed?Promise.resolve(null):new Promise(n=>{this.pending=n,this.rl.setPrompt(e),this.rl.prompt()})}close(){this.closed||(this.closed=!0,this.rl.close())}settle(e){let n=this.pending;this.pending=null,n?.(e)}};var zn=class extends Error{constructor(e){super(e),this.name="AudioUnavailableError"}};function Vk(t){let e=t.routes?.stt,n=t.routes?.tts;return!e||!n?!1:!!t.secrets?.[e.provider]&&!!t.secrets?.[n.provider]}async function Zk(t){if(!t.stdin.isTTY)return t.io.err(R.dim("jarvis is interactive - run it in a terminal.")+`
295
+ `),1}let n=t.createReader();return await new vg(e,n,t.io).run(),0}import{createInterface as FR}from"node:readline";var bu=class{rl;closed=!1;pending=null;constructor(e,n){this.rl=FR({input:e,output:n}),this.rl.on("line",i=>this.settle(i)),this.rl.on("close",()=>{this.closed=!0,this.settle(null)}),this.rl.on("SIGINT",()=>this.close())}next(e){return this.closed?Promise.resolve(null):new Promise(n=>{this.pending=n,this.rl.setPrompt(e),this.rl.prompt()})}close(){this.closed||(this.closed=!0,this.rl.close())}settle(e){let n=this.pending;this.pending=null,n?.(e)}};var zn=class extends Error{constructor(e){super(e),this.name="AudioUnavailableError"}};function Vk(t){let e=t.routes?.stt,n=t.routes?.tts;return!e||!n?!1:!!t.secrets?.[e.provider]&&!!t.secrets?.[n.provider]}async function Zk(t){if(!t.stdin.isTTY)return t.io.err(R.dim("jarvis is interactive - run it in a terminal.")+`
296
296
  `),1;if(t.textOnly||!t.voiceConfigured)return t.runText();if(!await t.micAvailable())return t.io.err(R.warn("no microphone detected - check it is plugged in and mic access / privacy is enabled. starting in text mode.")+`
297
297
  `),t.runText();let e;try{e=await t.openVoiceSession()}catch{return t.io.err(R.fail("could not start jarvis - your config may be invalid. run `jarvis doctor`.")+`
298
298
  `),1}try{return await t.runVoice(e),0}catch(n){if(n instanceof zn)return t.io.err(R.warn("could not start the microphone - check mic access / privacy. starting in text mode.")+`
299
- `),t.runText();throw n}}import{randomUUID as $g}from"node:crypto";function yg({onlyFirst:t=!1}={}){let r="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(r,t?void 0:"g")}var FR=yg();function _g(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return!t.includes("\x1B")&&!t.includes("\x9B")?t:t.replace(FR,"")}var Bk=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Gk=12288,Wk=65510,qk=[12288,12288,65281,65376,65504,65510];var Hk=4352,Jk=262141,bg=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var $u=(t,e)=>{let n=0,i=Math.floor(t.length/2)-1;for(;n<=i;){let r=Math.floor((n+i)/2),o=r*2;if(e<t[o])i=r-1;else if(e>t[o+1])n=r+1;else return!0}return!1};var Kk=19968,[BR,GR]=WR(bg);function WR(t){let e=t[0],n=t[1];for(let i=0;i<t.length;i+=2){let r=t[i],o=t[i+1];if(Kk>=r&&Kk<=o)return[r,o];o-r>n-e&&(e=r,n=o)}return[e,n]}var Yk=t=>t<161||t>1114109?!1:$u(Bk,t),Xk=t=>t<Gk||t>Wk?!1:$u(qk,t);var Qk=t=>t>=BR&&t<=GR?!0:t<Hk||t>Jk?!1:$u(bg,t);function qR(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function uo(t,{ambiguousAsWide:e=!1}={}){return qR(t),Xk(t)||Qk(t)||e&&Yk(t)?2:1}var HR=new Intl.Segmenter,eI=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,JR=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,KR=/^\p{RGI_Emoji}$/v,YR=/^[\d#*]\u20E3$/,XR=/\p{Extended_Pictographic}/gu;function QR(t){if(t.length>50)return!1;if(YR.test(t))return!0;if(t.includes("\u200D")){let e=t.match(XR);return e!==null&&e.length>=2}return!1}function e4(t){return t.replace(JR,"")}function t4(t){return eI.test(t)}function tI(t){return t>=4352&&t<=4447||t>=43360&&t<=43388}function rI(t){return t>=4448&&t<=4519||t>=55216&&t<=55238}function nI(t){return t>=4520&&t<=4607||t>=55243&&t<=55291}function r4(t){return tI(t)||rI(t)||nI(t)}function n4(t,e){let n=[];for(let r of t)eI.test(r)||n.push(r.codePointAt(0));if(n.length===0)return;let i=0;for(let r=0;r<n.length;r++){let o=n[r];if(!r4(o)){if(i===0)return;for(let s=r;s<n.length;s++)i+=uo(n[s],e);return i}if(tI(o)&&rI(n[r+1])){i+=2,r+=nI(n[r+2])?2:1;continue}i+=uo(o,e)}return i}function i4(t,e){let n=0,i=!0;for(let r of t){if(i){i=!1;continue}r>="\uFF00"&&r<="\uFFEF"&&(n+=uo(r.codePointAt(0),e))}return n}function xu(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:i=!1}=e,r=t;if(!i&&(r.includes("\x1B")||r.includes("\x9B"))&&(r=_g(r)),r.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(r))return r.length;let o=0,s={ambiguousAsWide:!n};for(let{segment:a}of HR.segment(r)){if(t4(a))continue;if(KR.test(a)||QR(a)){o+=2;continue}let u=e4(a),c=n4(u,s);if(c!==void 0){o+=c;continue}let l=u.codePointAt(0);o+=uo(l,s),o+=i4(u,s)}return o}xi();De();function xg(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}var wu="\x1B[2K\r",o4=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Su=class{session;capture;playback;io;terminalWidth;ptt;halfDuplex;signal;phase="listening";labelShown=!1;partialShown=!1;statusShown=!1;listenEpoch=0;turnStats={};talking;currentTurnId;cleanedUp=!1;onAbort=()=>{this.session.close()};constructor(e){this.session=e.session,this.capture=e.capture,this.playback=e.playback,this.io=e.io??ue,this.terminalWidth=e.terminalWidth??(()=>process.stdout.columns),this.ptt=e.pushToTalk,this.halfDuplex=e.options?.halfDuplex??!1,this.signal=e.signal,this.talking=this.ptt===void 0}async run(){if(this.signal){if(this.signal.aborted){await this.cleanup();return}this.signal.addEventListener("abort",this.onAbort,{once:!0})}try{await this.capture.start({onFrame:(e,n)=>this.handleFrame(e,n),onSpeechStart:()=>this.handleSpeechStart(),onError:e=>this.handleCaptureError(e)})}catch(e){throw await this.cleanup(),new zn(e instanceof Error?e.message:String(e))}this.ptt?.listen({onStart:()=>{this.talking=!0},onEnd:()=>this.commitPushToTalkTurn()});try{for await(let e of this.session.events())this.handle(e)}finally{await this.cleanup()}}handleFrame(e,n){this.phase==="listening"&&this.talking&&this.sendFrame(e,n)}async sendFrame(e,n){try{await this.session.send({type:"input.audio.frame",sessionId:this.session.sessionId,commandId:$g(),atMs:n,audio:e})}catch(i){if(i instanceof Le&&i.reason==="closed"){this.capture.stop();return}q.debug("dropped an audio frame",{error:i})}}handleSpeechStart(){if(this.phase!=="responding"||this.halfDuplex||this.ptt)return;let e=this.currentTurnId;this.playback.flush(),this.closeOpenLine(),this.toListening(),this.cancelTurn(e,"barge_in")}async cancelTurn(e,n){try{await this.session.send({type:"turn.cancel",sessionId:this.session.sessionId,commandId:$g(),atMs:Date.now(),reason:n,...e!==void 0&&{turnId:e}})}catch{}}commitPushToTalkTurn(){this.talking=!1,this.endAudioInput()}async endAudioInput(){try{await this.session.send({type:"input.audio.end",sessionId:this.session.sessionId,commandId:$g(),atMs:Date.now()})}catch{}}handleCaptureError(e){this.cleanedUp||(this.closeOpenLine(),this.io.out(R.fail(`the microphone stopped - ${e.message}`)+`
299
+ `),t.runText();throw n}}import{randomUUID as $g}from"node:crypto";function yg({onlyFirst:t=!1}={}){let r="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(r,t?void 0:"g")}var VR=yg();function _g(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return!t.includes("\x1B")&&!t.includes("\x9B")?t:t.replace(VR,"")}var Bk=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Gk=12288,Wk=65510,qk=[12288,12288,65281,65376,65504,65510];var Hk=4352,Jk=262141,bg=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var $u=(t,e)=>{let n=0,i=Math.floor(t.length/2)-1;for(;n<=i;){let r=Math.floor((n+i)/2),o=r*2;if(e<t[o])i=r-1;else if(e>t[o+1])n=r+1;else return!0}return!1};var Kk=19968,[GR,WR]=qR(bg);function qR(t){let e=t[0],n=t[1];for(let i=0;i<t.length;i+=2){let r=t[i],o=t[i+1];if(Kk>=r&&Kk<=o)return[r,o];o-r>n-e&&(e=r,n=o)}return[e,n]}var Yk=t=>t<161||t>1114109?!1:$u(Bk,t),Xk=t=>t<Gk||t>Wk?!1:$u(qk,t);var Qk=t=>t>=GR&&t<=WR?!0:t<Hk||t>Jk?!1:$u(bg,t);function HR(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function uo(t,{ambiguousAsWide:e=!1}={}){return HR(t),Xk(t)||Qk(t)||e&&Yk(t)?2:1}var JR=new Intl.Segmenter,eI=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,KR=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,YR=/^\p{RGI_Emoji}$/v,XR=/^[\d#*]\u20E3$/,QR=/\p{Extended_Pictographic}/gu;function e4(t){if(t.length>50)return!1;if(XR.test(t))return!0;if(t.includes("\u200D")){let e=t.match(QR);return e!==null&&e.length>=2}return!1}function t4(t){return t.replace(KR,"")}function r4(t){return eI.test(t)}function tI(t){return t>=4352&&t<=4447||t>=43360&&t<=43388}function rI(t){return t>=4448&&t<=4519||t>=55216&&t<=55238}function nI(t){return t>=4520&&t<=4607||t>=55243&&t<=55291}function n4(t){return tI(t)||rI(t)||nI(t)}function i4(t,e){let n=[];for(let r of t)eI.test(r)||n.push(r.codePointAt(0));if(n.length===0)return;let i=0;for(let r=0;r<n.length;r++){let o=n[r];if(!n4(o)){if(i===0)return;for(let s=r;s<n.length;s++)i+=uo(n[s],e);return i}if(tI(o)&&rI(n[r+1])){i+=2,r+=nI(n[r+2])?2:1;continue}i+=uo(o,e)}return i}function o4(t,e){let n=0,i=!0;for(let r of t){if(i){i=!1;continue}r>="\uFF00"&&r<="\uFFEF"&&(n+=uo(r.codePointAt(0),e))}return n}function xu(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:i=!1}=e,r=t;if(!i&&(r.includes("\x1B")||r.includes("\x9B"))&&(r=_g(r)),r.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(r))return r.length;let o=0,s={ambiguousAsWide:!n};for(let{segment:a}of JR.segment(r)){if(r4(a))continue;if(YR.test(a)||e4(a)){o+=2;continue}let u=t4(a),c=i4(u,s);if(c!==void 0){o+=c;continue}let l=u.codePointAt(0);o+=uo(l,s),o+=o4(u,s)}return o}xi();De();function xg(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}var wu="\x1B[2K\r",s4=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Su=class{session;capture;playback;io;terminalWidth;ptt;halfDuplex;signal;phase="listening";labelShown=!1;partialShown=!1;statusShown=!1;listenEpoch=0;turnStats={};talking;currentTurnId;cleanedUp=!1;onAbort=()=>{this.session.close()};constructor(e){this.session=e.session,this.capture=e.capture,this.playback=e.playback,this.io=e.io??ue,this.terminalWidth=e.terminalWidth??(()=>process.stdout.columns),this.ptt=e.pushToTalk,this.halfDuplex=e.options?.halfDuplex??!1,this.signal=e.signal,this.talking=this.ptt===void 0}async run(){if(this.signal){if(this.signal.aborted){await this.cleanup();return}this.signal.addEventListener("abort",this.onAbort,{once:!0})}try{await this.capture.start({onFrame:(e,n)=>this.handleFrame(e,n),onSpeechStart:()=>this.handleSpeechStart(),onError:e=>this.handleCaptureError(e)})}catch(e){throw await this.cleanup(),new zn(e instanceof Error?e.message:String(e))}this.ptt?.listen({onStart:()=>{this.talking=!0},onEnd:()=>this.commitPushToTalkTurn()});try{for await(let e of this.session.events())this.handle(e)}finally{await this.cleanup()}}handleFrame(e,n){this.phase==="listening"&&this.talking&&this.sendFrame(e,n)}async sendFrame(e,n){try{await this.session.send({type:"input.audio.frame",sessionId:this.session.sessionId,commandId:$g(),atMs:n,audio:e})}catch(i){if(i instanceof Le&&i.reason==="closed"){this.capture.stop();return}q.debug("dropped an audio frame",{error:i})}}handleSpeechStart(){if(this.phase!=="responding"||this.halfDuplex||this.ptt)return;let e=this.currentTurnId;this.playback.flush(),this.closeOpenLine(),this.toListening(),this.cancelTurn(e,"barge_in")}async cancelTurn(e,n){try{await this.session.send({type:"turn.cancel",sessionId:this.session.sessionId,commandId:$g(),atMs:Date.now(),reason:n,...e!==void 0&&{turnId:e}})}catch{}}commitPushToTalkTurn(){this.talking=!1,this.endAudioInput()}async endAudioInput(){try{await this.session.send({type:"input.audio.end",sessionId:this.session.sessionId,commandId:$g(),atMs:Date.now()})}catch{}}handleCaptureError(e){this.cleanedUp||(this.closeOpenLine(),this.io.out(R.fail(`the microphone stopped - ${e.message}`)+`
300
300
  `),this.session.close())}handle(e){switch(e.type){case"session.ready":this.greet();return;case"turn.accepted":this.currentTurnId=e.turnId,this.labelShown=!1,this.turnStats={};return;case"transcript.partial":if(e.turnId!==this.currentTurnId)return;this.renderPartial(e.text);return;case"turn.final":if(e.turn.turnId!==this.currentTurnId)return;this.renderFinalUser(e.turn),this.turnStats.finalAtMs=e.atMs,this.renderStatus("thinking");return;case"state":e.state==="responding"&&(this.phase="responding");return;case"response.delta":if(this.phase!=="responding")return;this.turnStats.firstTokenAtMs??=e.atMs,this.showLabel(),this.io.out(e.text);return;case"response.audio":if(this.phase!=="responding")return;this.turnStats.firstAudioAtMs===void 0&&(this.turnStats.firstAudioAtMs=e.atMs,this.turnStats.playbackStartAtMs=Date.now(),this.labelShown||this.renderStatus("speaking")),this.playback.play(e.audio);return;case"response.done":if(this.phase!=="responding")return;this.closeOpenLine(),this.turnStats.playbackStartAtMs!==void 0&&this.renderStatus("speaking"),this.awaitPlaybackDrain();return;case"error":{let n=this.currentTurnId;this.playback.flush(),this.closeOpenLine(),this.renderError(e),this.toListening(),this.cancelTurn(n,"user_cancel");return}default:return}}greet(){let e=this.ptt?"jarvis is ready (push-to-talk). press space to talk, again to send.":"jarvis is listening. just speak.",n=this.halfDuplex?" half-duplex: barge-in is off.":"";this.io.out(R.dim(`${e}${n} press ctrl-c to exit.`)+`
301
- `),this.renderStatus("listening")}renderPartial(e){this.io.out(`${wu}you ${R.dim(this.clampPartialToOneRow(e))}`),this.partialShown=!0,this.statusShown=!1}clampPartialToOneRow(e){let n=this.terminalWidth(),r=(n!==void 0&&n>0?n:80)-5;if(xu(e)<=r)return e;let o=r-3;if(o<=0)return"...";let s=[...o4.segment(e)],a=s.length,u=0;for(;a>0;){let c=u+xu(s[a-1].segment);if(c>o)break;u=c,a-=1}return a<s.length?"..."+e.slice(s[a].index):"..."}renderFinalUser(e){this.io.out(`${wu}you ${e.text}
301
+ `),this.renderStatus("listening")}renderPartial(e){this.io.out(`${wu}you ${R.dim(this.clampPartialToOneRow(e))}`),this.partialShown=!0,this.statusShown=!1}clampPartialToOneRow(e){let n=this.terminalWidth(),r=(n!==void 0&&n>0?n:80)-5;if(xu(e)<=r)return e;let o=r-3;if(o<=0)return"...";let s=[...s4.segment(e)],a=s.length,u=0;for(;a>0;){let c=u+xu(s[a-1].segment);if(c>o)break;u=c,a-=1}return a<s.length?"..."+e.slice(s[a].index):"..."}renderFinalUser(e){this.io.out(`${wu}you ${e.text}
302
302
  `),this.partialShown=!1,this.statusShown=!1}showLabel(){this.labelShown||(this.eraseStatusLine(),this.io.out(R.dim("jarvis")+" "),this.labelShown=!0)}renderStatus(e){this.partialShown||this.labelShown||(this.io.out(wu+R.dim(`${e}...`)),this.statusShown=!0)}eraseStatusLine(){this.statusShown&&(this.io.out(wu),this.statusShown=!1)}renderError(e){if(e.reason==="no_voice_route"){this.io.out(R.warn("no voice configured yet - run `jarvis init` to add speech routes.")+`
303
303
  `);return}if(e.reason==="no_text_route"){this.io.out(R.warn("no brain configured yet - run `jarvis init` to add one.")+`
304
304
  `);return}this.io.out(R.fail(`something went wrong - ${e.message}`)+`
305
305
  `)}closeOpenLine(){if(this.labelShown||this.partialShown){this.io.out(`
306
306
  `),this.labelShown=!1,this.partialShown=!1;return}this.eraseStatusLine()}awaitPlaybackDrain(){let e=this.listenEpoch;this.playback.drained().then(()=>{this.cleanedUp||e!==this.listenEpoch||(this.printTurnSummary(),this.toListening())})}printTurnSummary(){if(q.getLevel()!=="debug")return;let{finalAtMs:e,firstTokenAtMs:n,firstAudioAtMs:i,playbackStartAtMs:r}=this.turnStats,o=[];e!==void 0&&n!==void 0&&o.push(`commit->token ${xg(n-e)}`),n!==void 0&&i!==void 0&&o.push(`token->audio ${xg(i-n)}`),r!==void 0&&o.push(`spoke ${xg(Date.now()-r)}`),o.length!==0&&(this.eraseStatusLine(),this.io.out(R.dim(`turn ${o.join(", ")}`)+`
307
- `))}toListening(){this.listenEpoch++,this.phase="listening",this.labelShown=!1,this.partialShown=!1,this.currentTurnId=void 0,this.renderStatus("listening")}async cleanup(){this.cleanedUp||(this.cleanedUp=!0,this.closeOpenLine(),this.signal?.removeEventListener("abort",this.onAbort),this.ptt?.close(),await this.capture.stop().catch(()=>{}),await this.playback.close().catch(()=>{}),await this.session.close().catch(()=>{}))}};import{emitKeypressEvents as s4}from"node:readline";var ku=class{constructor(e,n,i=a4){this.input=e;this.onQuit=n;this.prepare=i}input;onQuit;prepare;handlers=null;talking=!1;listening=!1;onKeypress=(e,n)=>{if(n.ctrl&&n.name==="c"){this.onQuit();return}n.name==="space"&&this.toggle()};listen(e){this.listening||(this.listening=!0,this.handlers=e,this.prepare(this.input),this.input.isTTY&&this.input.setRawMode&&this.input.setRawMode(!0),this.input.resume?.(),this.input.on("keypress",this.onKeypress))}close(){this.listening&&(this.listening=!1,this.input.removeListener("keypress",this.onKeypress),this.input.isTTY&&this.input.setRawMode&&this.input.setRawMode(!1),this.input.pause?.(),this.handlers=null)}toggle(){this.talking=!this.talking,this.talking?this.handlers?.onStart():this.handlers?.onEnd()}};function a4(t){s4(t)}var $4={start:"starting...",stop:"stopping...",restart:"restarting...",devices:"listing devices..."};function x4(){try{let t=_4(new URL("../package.json",import.meta.url),"utf8"),e=JSON.parse(t);return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}function w4(t,e){let n=new su(t),i=n.notice();i!==null&&ue.err(`${i}
308
- `),n.isStale(Date.now())&&n.refreshInBackground();let r=!1,o=!1;try{let c=new Ge().resolved();r=Vk(c),o=c.defaults.modality==="text"}catch{}let s=b4(),a=c=>(q.debug("opening interactive session",{project:e.project,capabilities:c}),Tm().openSession({deviceId:s,projectId:e.project,clientCapabilities:c})),u=()=>Fk({stdin:process.stdin,io:ue,openSession:()=>a(["text"]),createReader:()=>new bu(process.stdin,process.stdout)});return Zk({stdin:process.stdin,io:ue,textOnly:e.textOnly||o,voiceConfigured:r,micAvailable:k4,openVoiceSession:()=>a(["text","audio-in","audio-out"]),runVoice:c=>S4(c,e),runText:u})}async function S4(t,e){let{DecibriCapture:n,DecibriPlayback:i}=await Promise.resolve().then(()=>(Ig(),kg)),r=new AbortController,o=e.ptt?new ku(process.stdin,()=>r.abort()):void 0,s=()=>r.abort();process.once("SIGINT",s);try{await new Su({session:t,capture:new n,playback:new i,io:ue,...o&&{pushToTalk:o},options:{halfDuplex:e.halfDuplex},signal:r.signal}).run()}finally{process.removeListener("SIGINT",s)}}async function k4(){try{let{hasInputDevice:t}=await Promise.resolve().then(()=>(Ig(),kg));return t()}catch(t){return q.debug("audio module unavailable; treating as no microphone",{error:t}),!1}}function I4(t){return{activate:e=>w4(t,e),status:()=>new Er(t).status(),upgrade:()=>new Er(t).upgrade(),init:()=>new _u({config:new Ge,probe:new Tn}).run(),doctor:()=>new au({config:new Ge,probe:new Tn,version:t}).run(),configList:()=>new Or(new Ge).list(),configGet:e=>new Or(new Ge).get(e),configSet:(e,n)=>new Or(new Ge).set(e,n),configUnset:e=>new Or(new Ge).unset(e),stub:e=>(ue.err(`${$4[e]??`${e}: not implemented yet`}
309
- `),0)}}try{let t=x4();process.exitCode=await Qw(process.argv.slice(2),t,I4(t))}catch(t){q.error("jarvis failed",{error:t}),process.exitCode=1}
307
+ `))}toListening(){this.listenEpoch++,this.phase="listening",this.labelShown=!1,this.partialShown=!1,this.currentTurnId=void 0,this.renderStatus("listening")}async cleanup(){this.cleanedUp||(this.cleanedUp=!0,this.closeOpenLine(),this.signal?.removeEventListener("abort",this.onAbort),this.ptt?.close(),await this.capture.stop().catch(()=>{}),await this.playback.close().catch(()=>{}),await this.session.close().catch(()=>{}))}};import{emitKeypressEvents as a4}from"node:readline";var ku=class{constructor(e,n,i=u4){this.input=e;this.onQuit=n;this.prepare=i}input;onQuit;prepare;handlers=null;talking=!1;listening=!1;onKeypress=(e,n)=>{if(n.ctrl&&n.name==="c"){this.onQuit();return}n.name==="space"&&this.toggle()};listen(e){this.listening||(this.listening=!0,this.handlers=e,this.prepare(this.input),this.input.isTTY&&this.input.setRawMode&&this.input.setRawMode(!0),this.input.resume?.(),this.input.on("keypress",this.onKeypress))}close(){this.listening&&(this.listening=!1,this.input.removeListener("keypress",this.onKeypress),this.input.isTTY&&this.input.setRawMode&&this.input.setRawMode(!1),this.input.pause?.(),this.handlers=null)}toggle(){this.talking=!this.talking,this.talking?this.handlers?.onStart():this.handlers?.onEnd()}};function u4(t){a4(t)}var x4={start:"starting...",stop:"stopping...",restart:"restarting...",devices:"listing devices..."};function w4(){try{let t=b4(new URL("../package.json",import.meta.url),"utf8"),e=JSON.parse(t);return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}function S4(t,e){let n=new su(t),i=n.notice();i!==null&&ue.err(`${i}
308
+ `),n.isStale(Date.now())&&n.refreshInBackground();let r=!1,o=!1;try{let c=new Ge().resolved();r=Vk(c),o=c.defaults.modality==="text"}catch{}let s=$4(),a=c=>(q.debug("opening interactive session",{project:e.project,capabilities:c}),Tm().openSession({deviceId:s,projectId:e.project,clientCapabilities:c})),u=()=>Fk({stdin:process.stdin,io:ue,openSession:()=>a(["text"]),createReader:()=>new bu(process.stdin,process.stdout)});return Zk({stdin:process.stdin,io:ue,textOnly:e.textOnly||o,voiceConfigured:r,micAvailable:I4,openVoiceSession:()=>a(["text","audio-in","audio-out"]),runVoice:c=>k4(c,e),runText:u})}async function k4(t,e){let{DecibriCapture:n,DecibriPlayback:i}=await Promise.resolve().then(()=>(Ig(),kg)),r=new AbortController,o=e.ptt?new ku(process.stdin,()=>r.abort()):void 0,s=()=>r.abort();process.once("SIGINT",s);try{await new Su({session:t,capture:new n,playback:new i,io:ue,...o&&{pushToTalk:o},options:{halfDuplex:e.halfDuplex},signal:r.signal}).run()}finally{process.removeListener("SIGINT",s)}}async function I4(){try{let{hasInputDevice:t}=await Promise.resolve().then(()=>(Ig(),kg));return t()}catch(t){return q.debug("audio module unavailable; treating as no microphone",{error:t}),!1}}function E4(t){return{activate:e=>S4(t,e),status:()=>new Er(t).status(),upgrade:()=>new Er(t).upgrade(),init:()=>new _u({config:new Ge,probe:new Tn}).run(),doctor:()=>new au({config:new Ge,probe:new Tn,version:t}).run(),configList:()=>new Or(new Ge).list(),configGet:e=>new Or(new Ge).get(e),configSet:(e,n)=>new Or(new Ge).set(e,n),configUnset:e=>new Or(new Ge).unset(e),stub:e=>(ue.err(`${x4[e]??`${e}: not implemented yet`}
309
+ `),0)}}try{let t=w4();process.exitCode=await Qw(process.argv.slice(2),t,E4(t))}catch(t){q.error("jarvis failed",{error:t}),process.exitCode=1}