@neuvybe/jarvis 0.49.0 → 0.49.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -68,8 +68,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
68
68
|
`,{mode:384}),Jee(n,384)}}});function iF(t,e){let r=t;for(let i of e){if(r===null||typeof r!="object")return;r=r[i]}return r}function ste(t,e,r){let i=t;for(let n=0;n<e.length-1;n++){let s=e[n],o=i[s];(o===null||typeof o!="object")&&(i[s]={}),i=i[s]}i[e[e.length-1]]=r}function ote(t,e){let r=t;for(let n=0;n<e.length-1;n++){let s=r[e[n]];if(s===null||typeof s!="object")return!1;r=s}let i=e[e.length-1];return i in r?(delete r[i],!0):!1}var ete,tte,rte,nte,ite,wr,Lb=D(()=>{"use strict";Nt();Fs();Mb();ete="<set>",tte=new Set(["upgrade.auto"]),rte=new Set(["version"]),nte=["url","voiceId"],ite=new Set(["__proto__","prototype","constructor"]),wr=class{home;constructor(e=Yt){this.home=e}freshResolver(){return new zo(this.home)}resolved(){return this.freshResolver().resolved()}list(){return this.redact(this.freshResolver().resolved())}get(e){return iF(this.list(),this.parsePath(e))}set(e,r){let i=this.parsePath(e);this.assertMutable(e);let n=this.freshResolver(),s=structuredClone(n.resolved()),o=this.coerce(e,r);this.dropProviderScopedOnSwitch(s,i,o),ste(s,i,o),n.save(this.validate(s,e))}unset(e){let r=this.parsePath(e);this.assertMutable(e);let i=this.freshResolver(),n=structuredClone(i.resolved());if(!ote(n,r))throw new Error(`nothing to unset: '${e}' is not set`);i.save(this.validate(n,e))}write(e){zo.persist(this.home,e)}validate(e,r){let i=jo.safeParse(e);if(i.success)return i.data;let n=i.error.issues.map(o=>`${o.path.join(".")}: ${o.message}`).join("; "),s=r.startsWith("routes.search")?" The search route is model-less - it takes only a provider (jarvis config set routes.search.provider <name>); run 'jarvis init' to set it up keyed.":r.startsWith("routes.")?" A route needs both a provider and a model - run 'jarvis init' to configure one.":"";throw new Error(`'${r}' would make the config invalid (${n}).${s}`)}coerce(e,r){if(tte.has(e)){if(r==="true")return!0;if(r==="false")return!1;throw new Error(`'${e}' expects 'true' or 'false', got '${r}'`)}return r}dropProviderScopedOnSwitch(e,r,i){if(r.length!==3||r[0]!=="routes"||r[2]!=="provider")return;let n=iF(e,r.slice(0,2));if(n===null||typeof n!="object")return;let s=n;if(s.provider!==i)for(let o of nte)delete s[o]}assertMutable(e){if(rte.has(e))throw new Error(`'${e}' is managed by Jarvis and cannot be changed`)}parsePath(e){let r=e.split(".");if(e.length===0||r.some(i=>i.length===0||ite.has(i)))throw new Error(`invalid config path: '${e}'`);return r}redact(e){let r=structuredClone(e);if(r.secrets)for(let i of Object.keys(r.secrets))r.secrets[i]=ete;return r}}});async function*ep(t,e={}){let{signal:r,idleTimeoutMs:i}=e,n=t.getReader(),s=new TextDecoder,o="",a=[];try{for(;;){let{value:c,done:l}=await ate(n,r,i);if(l)break;o+=s.decode(c,{stream:!0});let A;for(;(A=o.indexOf(`
|
|
69
69
|
`))!==-1;){let d=o.slice(0,A);if(o=o.slice(A+1),d.endsWith("\r")&&(d=d.slice(0,-1)),d===""){a.length>0&&(yield a.join(`
|
|
70
70
|
`),a=[]);continue}if(d.startsWith(":"))continue;let h=d.indexOf(":");if((h===-1?d:d.slice(0,h))!=="data")continue;let f=h===-1?"":d.slice(h+1);f.startsWith(" ")&&(f=f.slice(1)),a.push(f)}}}finally{n.cancel().catch(()=>{})}}function ate(t,e,r){return e?.aborted?Promise.reject(sF(e)):new Promise((i,n)=>{let s=!1,o=l=>{s||(s=!0,c!==void 0&&clearTimeout(c),e?.removeEventListener("abort",a),l())},a=()=>o(()=>n(sF(e))),c=r!==void 0?setTimeout(()=>o(()=>n(new Kg(r))),r):void 0;e?.addEventListener("abort",a,{once:!0}),t.read().then(l=>o(()=>i(l)),l=>o(()=>n(cte(l))))})}function sF(t){let e=t?.reason;return e instanceof Error?e:new Error("text stream aborted")}function cte(t){return t instanceof Error?t:new Error(String(t))}var Kg,tp=D(()=>{"use strict";Kg=class extends Error{constructor(e){super(`text stream idle for ${e}ms`),this.name="IdleTimeoutError"}}});function ute(t,e){let r=0;for(let i of e){for(;r<t.length&&/\s/.test(t[r]);)r++;if(r>=t.length)return"partial";let n=t.slice(r,r+i.length);if(n.length<i.length)return i.startsWith(n)?"partial":"no";if(n!==i)return"no";r+=i.length}return r}var Gc,lte,Fb=D(()=>{"use strict";Gc=class{opening;phase="opening";head="";pendingEscape="";heldSurrogate="";constructor(e){this.opening=["{",`"${e}"`,":",'"']}get done(){return this.phase==="done"}push(e){if(this.phase==="done"||this.phase==="unstreamable")return"";let r=e;if(this.phase==="opening"){this.head+=e;let i=ute(this.head,this.opening);if(i==="partial")return"";if(i==="no")return this.phase="unstreamable",this.head="","";r=this.head.slice(i),this.head="",this.phase="value"}return this.decode(r)}decode(e){let r=this.pendingEscape+e;this.pendingEscape="";let i="",n=0;for(;n<r.length;){let a=r[n];if(a==='"'){this.phase="done";break}if(a!=="\\"){i+=a,n++;continue}if(n+1>=r.length){this.pendingEscape=r.slice(n);break}let c=r[n+1];if(c==="u"){if(n+6>r.length){this.pendingEscape=r.slice(n);break}let l=r.slice(n+2,n+6);/^[0-9a-fA-F]{4}$/.test(l)?i+=String.fromCharCode(parseInt(l,16)):i+=r.slice(n,n+6),n+=6;continue}i+=lte[c]??`\\${c}`,n+=2}let s=this.heldSurrogate+i;this.heldSurrogate="";let o=s.charCodeAt(s.length-1);return this.phase==="value"&&s.length>0&&o>=55296&&o<=56319&&(this.heldSurrogate=s.slice(-1),s=s.slice(0,-1)),s}},lte={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
71
|
-
`,r:"\r",t:" "}});function qt(t,e){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":Ate(t.message,e):"network error"}function Ate(t,e){let r=t;for(let i of new Set([e,e?.trim()]))i!==void 0&&i.trim().length>0&&(r=r.split(i).join("<redacted>"));return r.replace(/\s+/g," ").trim()}function Us(t,e){for(let r=0;r<t.length;r+=1){let i=t.charCodeAt(r);if(i<32||i===127)throw new Error(`${e} contains a control character (check for a pasted trailing newline) - it cannot be sent as an HTTP header`)}}var Os=D(()=>{"use strict"});var _t,rp=D(()=>{"use strict";_t=class extends Error{status;constructor(e,r){super(e),this.status=r,this.name="TextAdapterError"}}});import{randomUUID as dte}from"node:crypto";function Ete(t){return"toolCalls"in t?{role:"assistant",content:[...t.content.length>0?[{type:"text",text:t.content}]:[],...t.toolCalls.map(e=>({type:"tool_use",id:e.id,name:e.name,input:yte(e.input)}))]}:t.role==="tool"?{role:"user",content:t.results.map(e=>({type:"tool_result",tool_use_id:e.id,content:e.result,...e.isError===!0&&{is_error:!0}}))}:{role:t.role,content:t.content}}function Ite(t){return"toolCalls"in t?[{role:"assistant",content:t.content.length>0?t.content:null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:Cte(e.input)}}))}]:t.role==="tool"?t.results.map(e=>({role:"tool",tool_call_id:e.id,content:e.result})):[{role:t.role,content:t.content}]}function Cte(t){return typeof t=="string"?t:JSON.stringify(t??{})}function yte(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function aF(t,e,r){let i=r.length===0?"{}":r;try{return{type:"tool_call",id:t,name:e,input:JSON.parse(i)}}catch{return{type:"tool_call",id:t,name:e,input:r}}}function cF(t){try{return JSON.parse(t)}catch{return}}function Li(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function oF(t){return Array.isArray(t)?t:void 0}function lF(t){let e=Li(t)?.message;return typeof e=="string"?e:"unknown error"}var Yc,hte,fte,gte,pte,np,mte,IA,Ub,CA,Ob,ip=D(()=>{"use strict";tp();Fb();Os();rp();Yc=3e4,hte=4096,fte="https://api.anthropic.com/v1/messages",gte="2023-06-01",pte="https://api.openai.com/v1/chat/completions",np=class{key;fetchImpl;idleTimeoutMs;constructor(e,r=fetch,i=Yc){this.key=e,this.fetchImpl=r,this.idleTimeoutMs=i,Us(e,"stored text provider key")}async*stream(e){let{url:r,init:i}=this.buildRequest(e),n;try{n=await this.fetchImpl(r,{...i,signal:e.signal})}catch(o){throw e.signal?.aborted===!0&&(o===e.signal.reason||o instanceof Error&&(o.name==="AbortError"||o.name==="TimeoutError"))?o:new _t(qt(o,this.key))}if(!n.ok)throw new _t(`text provider request failed (HTTP ${n.status})`,n.status);if(!n.body)throw new _t("text provider response had no body");let s=this.newTurnDecoder(new Map((e.streamText??[]).map(o=>[o.name,o.field])));for await(let o of ep(n.body,{signal:e.signal,idleTimeoutMs:this.idleTimeoutMs})){if(s.isDone(o))break;for(let a of s.decode(o))yield a}for(let o of s.flush())yield o}},mte="eager_input_streaming",IA=class extends np{buildRequest(e){let r=new Set((e.streamText??[]).map(n=>n.name)),i={model:e.model,max_tokens:hte,stream:!0,messages:e.messages.map(Ete),...e.system!==void 0&&{system:e.system},...e.tools!==void 0&&e.tools.length>0&&{tools:e.tools.map(n=>({name:n.name,description:n.description,input_schema:n.inputSchema,...r.has(n.name)&&{[mte]:!0}}))},...e.toolChoice==="any"&&{tool_choice:{type:"any"}}};return{url:fte,init:{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":gte,"content-type":"application/json"},body:JSON.stringify(i)}}}newTurnDecoder(e){return new Ub(e)}};Ub=class{streamText;tool=null;stopped=!1;constructor(e){this.streamText=e}isDone(){return!1}decode(e){let r=Li(cF(e));if(!r)return[];if(r.type==="error")throw new _t(`anthropic stream error: ${lF(r.error)}`);if(r.type==="message_stop")return this.stopped=!0,[];if(r.type==="content_block_start"){let i=Li(r.content_block);if(i?.type==="tool_use"&&typeof i.id=="string"){let n=typeof i.name=="string"?i.name:"",s=this.streamText.get(n);this.tool={id:i.id,name:n,json:"",text:s!==void 0?new Gc(s):null}}return[]}if(r.type==="content_block_delta"){let i=Li(r.delta);if(i?.type==="text_delta"&&typeof i.text=="string")return[{type:"text",text:i.text}];if(i?.type==="input_json_delta"&&this.tool&&typeof i.partial_json=="string"&&(this.tool.json+=i.partial_json,this.tool.text)){let n=this.tool.text.push(i.partial_json);if(n.length>0)return[{type:"tool_text",id:this.tool.id,name:this.tool.name,text:n}]}return[]}if(r.type==="content_block_stop"&&this.tool){let i=aF(this.tool.id,this.tool.name,this.tool.json);return this.tool=null,[i]}return[]}flush(){if(!this.stopped)throw new _t("anthropic stream ended before message_stop");return[]}},CA=class extends np{buildRequest(e){let r=e.messages.flatMap(Ite),i=e.system!==void 0?[{role:"system",content:e.system},...r]:r,n={model:e.model,stream:!0,messages:i,...e.tools!==void 0&&e.tools.length>0&&{tools:e.tools.map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}}))},...e.toolChoice==="any"&&{tool_choice:"required"}};return{url:pte,init:{method:"POST",headers:{Authorization:`Bearer ${this.key}`,"content-type":"application/json"},body:JSON.stringify(n)}}}newTurnDecoder(){return new Ob}};Ob=class{calls=new Map;done=!1;isDone(e){return e!=="[DONE]"?!1:(this.done=!0,!0)}decode(e){let r=Li(cF(e));if(!r)return[];if(r.error)throw new _t(`openai stream error: ${lF(r.error)}`);let i=oF(r.choices),n=Li(Li(i?.[0])?.delta);if(!n)return[];for(let o of oF(n.tool_calls)??[]){let a=Li(o);if(!a)continue;let c=typeof a.index=="number"?a.index:0,l=this.calls.get(c)??{id:"",name:"",args:""};typeof a.id=="string"&&(l.id=a.id);let A=Li(a.function);typeof A?.name=="string"&&(l.name=A.name),typeof A?.arguments=="string"&&(l.args+=A.arguments),this.calls.set(c,l)}let s=n.content;return typeof s=="string"&&s.length>0?[{type:"text",text:s}]:[]}flush(){if(!this.done)return this.calls.clear(),[];let e=[...this.calls.entries()].sort(([r],[i])=>r-i).map(([r,i])=>aF(i.id.length>0?i.id:`call-${r}-${dte().slice(0,8)}`,i.name,i.args));return this.calls.clear(),e}}});var Fi,$b=D(()=>{"use strict";Fi=class extends Error{status;constructor(e,r){super(e),this.status=r,this.name="SearchAdapterError"}}});function yA(t,e){if(typeof t!="object"||t===null)return[];let r=t,i=r.url;if(typeof i!="string"||i.length===0)return[];let n=r.title,s=r[e];return[{title:typeof n=="string"&&n.length>0?n:i,url:i,...typeof s=="string"&&s.length>0&&{content:s}}]}function BA(t,e=["results"]){let r=t;for(let i of e)r=typeof r=="object"&&r!==null?r[i]:void 0;if(!Array.isArray(r))throw new Fi("search provider returned an unexpected shape");return r}var Bte,xte,Qte,bte,wte,Wo,sp,op,ap,cp,lp,uF=D(()=>{"use strict";Os();$b();Bte="https://ollama.com/api/web_search",xte="https://api.exa.ai/search",Qte="https://api.firecrawl.dev/v2/search",bte="https://api.tavily.com/search",wte="https://api.search.brave.com/res/v1/web/search",Wo=class{key;fetchImpl;constructor(e,r=fetch){this.key=e,this.fetchImpl=r,Us(e,"stored search provider key")}async search(e,r,i){let n=this.request(e,r),s=n.method??"POST",o=n.query===void 0?n.url:`${n.url}?${new URLSearchParams(n.query).toString()}`,a;try{a=await this.fetchImpl(o,{method:s,headers:s==="GET"?n.headers:{"content-type":"application/json",...n.headers},...s==="POST"&&{body:JSON.stringify(n.body)},redirect:"error",signal:i})}catch(l){throw i.aborted?l:new Fi(qt(l,this.key))}if(!a.ok)throw new Fi(`search provider returned ${a.status}`,a.status);let c;try{c=await a.json()}catch{throw new Fi("search provider returned a malformed response")}return this.parse(c).slice(0,r)}};sp=class extends Wo{request(e,r){return{url:Bte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,max_results:r}}}parse(e){return BA(e).flatMap(r=>yA(r,"content"))}},op=class extends Wo{request(e,r){return{url:xte,headers:{"x-api-key":this.key},body:{query:e,numResults:r,contents:{text:!0}}}}parse(e){return BA(e).flatMap(r=>yA(r,"text"))}},ap=class extends Wo{request(e,r){return{url:Qte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,limit:r}}}parse(e){return BA(e,["data","web"]).flatMap(r=>yA(r,"description"))}},cp=class extends Wo{request(e,r){return{url:bte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,max_results:r}}}parse(e){return BA(e).flatMap(r=>yA(r,"content"))}},lp=class extends Wo{request(e,r){return{url:wte,headers:{"x-subscription-token":this.key},method:"GET",query:{q:e,count:String(r)}}}parse(e){return BA(e,["web","results"]).flatMap(r=>yA(r,"description"))}}});function up(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function vte(t){return typeof t=="string"?t:JSON.stringify(t??{})}function Ui(){return new _t("invalid openai response stream")}var Ap,Pb,AF=D(()=>{"use strict";ip();Os();tp();Fb();rp();Ap=class{key;fetchImpl;idleTimeoutMs;continuations=[];constructor(e,r=fetch,i=Yc){this.key=e,this.fetchImpl=r,this.idleTimeoutMs=i,Us(e,"stored text provider key")}async*stream(e){let r=this.renderHistory(e.messages),i=new Pb(new Map((e.streamText??[]).map(n=>[n.name,n.field])));try{e.signal?.throwIfAborted();let n=await this.fetchImpl("https://api.openai.com/v1/responses",{method:"POST",headers:{Authorization:`Bearer ${this.key}`,"content-type":"application/json"},signal:e.signal,body:JSON.stringify({model:e.model,stream:!0,store:!1,input:r,...e.system!==void 0&&{instructions:e.system},...e.tools!==void 0&&e.tools.length>0&&{tools:e.tools.map(o=>({type:"function",name:o.name,description:o.description,parameters:o.inputSchema,strict:!1}))},...e.toolChoice==="any"&&{tool_choice:"required"}})});if(!n.ok)throw new _t(`text provider request failed (HTTP ${n.status})`,n.status);if(!n.body)throw new _t("text provider response had no body");for await(let o of ep(n.body,{signal:e.signal,idleTimeoutMs:this.idleTimeoutMs})){e.signal?.throwIfAborted();for(let a of i.decode(o))yield a;if(i.completed)break}e.signal?.throwIfAborted();let s=i.finish();for(let o of s){e.signal?.throwIfAborted();for(let a of i.speechBefore(o))yield a;e.signal?.throwIfAborted(),yield{type:"tool_call",...o}}e.signal?.throwIfAborted(),s.length>0&&i.reasoning.length>0&&this.continuations.push({calls:structuredClone(s),items:i.continuationItems})}catch(n){throw e.signal?.aborted?e.signal.reason:new _t(qt(n,this.key),n instanceof _t?n.status:void 0)}}renderHistory(e){let r=-1;for(let n=e.length-1;n>=0;n--)if(e[n].role==="user"){r=n;break}let i=new Set(e.slice(r+1).flatMap(n=>"toolCalls"in n?n.toolCalls.map(s=>s.id):[]));return this.continuations=this.continuations.filter(n=>n.calls.some(s=>i.has(s.id))),e.flatMap(n=>{if("toolCalls"in n){let s=this.continuations.filter(a=>a.calls.some(c=>n.toolCalls.some(l=>l.id===c.id))),o=s.flatMap(a=>{if(JSON.stringify(a.calls)!==JSON.stringify(n.toolCalls))throw new _t("openai continuation no longer matches retained calls");return a.items});return[...n.content.length>0?[{role:"assistant",content:n.content}]:[],...s.length>0?o:n.toolCalls.map(a=>({type:"function_call",call_id:a.id,name:a.name,arguments:vte(a.input)}))]}return n.role==="tool"?n.results.map(s=>({type:"function_call_output",call_id:s.id,output:s.result})):[{role:n.role,content:n.content}]})}},Pb=class{streamText;calls=new Map;firstItemId;bufferedSpeech=new Map;output=[];completed=!1;reasoning=[];continuationItems=[];constructor(e){this.streamText=e}decode(e){let r;try{r=up(JSON.parse(e))}catch{}if(!r||typeof r.type!="string")throw Ui();if(["error","response.failed","response.incomplete","response.cancelled"].includes(r.type))throw new _t("openai response did not complete");if(r.type==="response.output_item.added"){let i=up(r.item);if(i?.type==="function_call"){if(typeof i.id!="string"||typeof i.call_id!="string"||typeof i.name!="string"||this.calls.has(i.id))throw Ui();let n=this.streamText.get(i.name);this.firstItemId??=i.id,this.calls.set(i.id,{id:i.call_id,name:i.name,args:"",...n!==void 0&&{text:new Gc(n)}})}}if(r.type==="response.function_call_arguments.delta"){let i=typeof r.item_id=="string"?this.calls.get(r.item_id):void 0;if(!i||typeof r.delta!="string")throw Ui();i.args+=r.delta;let n=i.text?.push(r.delta)??"";return r.item_id!==this.firstItemId?(this.bufferedSpeech.set(i.id,(this.bufferedSpeech.get(i.id)??"")+n),[]):n.length>0?[{type:"tool_text",id:i.id,name:i.name,text:n}]:[]}if(r.type==="response.output_text.delta"){if(typeof r.delta!="string")throw Ui();return r.delta.length>0?[{type:"text",text:r.delta}]:[]}if(r.type==="response.completed"){let i=up(r.response);if(i?.status!=="completed"||!Array.isArray(i.output))throw Ui();this.output=i.output.map(n=>{let s=up(n);if(!s)throw Ui();return s}),this.completed=!0}return[]}finish(){if(!this.completed)throw new _t("openai stream ended before response.completed");let e=[],r=new Set;for(let n of this.output)if(n.type==="reasoning"){if(typeof n.encrypted_content!="string"||n.encrypted_content.length===0)throw new _t("openai response omitted continuation reasoning");this.reasoning.push(n)}else if(n.type==="function_call"){if(typeof n.id!="string"||typeof n.call_id!="string"||typeof n.name!="string"||typeof n.arguments!="string"||n.status!=="completed"||r.has(n.call_id))throw Ui();let s=this.calls.get(n.id);if(s?.id!==n.call_id||s.name!==n.name||s.args.length>0&&s.args!==n.arguments)throw Ui();r.add(n.call_id);let o;try{o=JSON.parse(n.arguments.length===0?"{}":n.arguments)}catch{o=n.arguments}e.push({id:n.call_id,name:n.name,input:o})}let i=[...this.calls.values()];if(e.length!==i.length||e.some((n,s)=>n.id!==i[s].id))throw Ui();return this.continuationItems=this.output.filter(n=>n.type==="reasoning"||n.type==="function_call"),e}speechBefore(e){let r=this.bufferedSpeech.get(e.id)??"";return r.length>0?[{type:"tool_text",id:e.id,name:e.name,text:r}]:[]}}});var qc,Hb=D(()=>{"use strict";qc=class{providers=new Map([["anthropic",{protocol:"anthropic-messages"}],["openai",{protocol:"openai-chat-completions",include:/^(gpt-(4\.1|4o|5)|o\d)/,exclude:/-\d{4}-\d{2}-\d{2}$|-(audio|realtime|transcribe|tts|image|search|codex|chat-latest|instruct|deep-research|pro)\b/,overrides:new Map([["gpt-6-astra",{protocol:"openai-responses",catalogueEligible:!0}]])}]]);catalogueEligible(e,r){let i=this.providers.get(e);if(i===void 0)return!1;let n=i.overrides?.get(r);return n!==void 0?n.catalogueEligible:(i.include?.test(r)??!0)&&!(i.exclude?.test(r)??!1)}protocol(e,r){let i=this.providers.get(e);return i?.overrides?.get(r)?.protocol??i?.protocol}}});var xA,Vb=D(()=>{"use strict";ip();uF();AF();Hb();xA=class{fetchImpl;idleTimeoutMs;brainModels=new qc;constructor(e=fetch,r=Yc){this.fetchImpl=e,this.idleTimeoutMs=r}textAdapter(e,r){switch(this.brainModels.protocol(e.provider,e.model)){case"anthropic-messages":return new IA(r,this.fetchImpl,this.idleTimeoutMs);case"openai-responses":return new Ap(r,this.fetchImpl,this.idleTimeoutMs);case"openai-chat-completions":return new CA(r,this.fetchImpl,this.idleTimeoutMs);default:throw new Error(`no text adapter for provider '${e.provider}'`)}}searchAdapter(e,r){switch(e.provider){case"ollama":return new sp(r,this.fetchImpl);case"exa":return new op(r,this.fetchImpl);case"firecrawl":return new ap(r,this.fetchImpl);case"tavily":return new cp(r,this.fetchImpl);case"brave":return new lp(r,this.fetchImpl);default:throw new Error(`no search adapter for provider '${e.provider}'`)}}}});var vr,dF=D(()=>{"use strict";vr=class extends Error{commandId;reason;constructor(e,r,i){super(i??`send rejected (${r}) for command ${e}`),this.commandId=e,this.reason=r,this.name="SessionSendError"}}});var hF=D(()=>{"use strict"});var QA=D(()=>{"use strict";dF();hF()});function Ste(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Dte(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function dp(t,e,r){if(r.type==="tool.start")t({type:"tool.start",turnId:e,toolId:r.toolId,name:r.tool,summary:r.summary??""});else{let i=[`${r.ok?"ok":"failed"} in ${Ste(r.durationMs)}`];r.bytes!==void 0&&i.push(Dte(r.bytes)),r.results!==void 0&&i.push(`${r.results} result${r.results===1?"":"s"}`),t({type:"tool.result",turnId:e,toolId:r.toolId,ok:r.ok,durationMs:r.durationMs,summary:i.join(" - ")})}}function bA(t,e,r){r.type==="act.start"?t({type:"act.start",turnId:e,actId:r.actId,act:r.act}):t({type:"act.end",turnId:e,actId:r.actId,act:r.act,characters:r.characters})}var Gb=D(()=>{"use strict"});var Oi,wA=D(()=>{"use strict";Oi=class{nextId=1;timers=new Map;now(){return Date.now()}setTimer(e,r){let i=this.nextId++,n=setTimeout(()=>{this.timers.delete(i),r()},e);return this.timers.set(i,n),i}clearTimer(e){let r=this.timers.get(e);r!==void 0&&(clearTimeout(r),this.timers.delete(e))}}});function An(t,e){let r=Math.floor(t.byteLength/2);if(r===0)return!1;let i=new DataView(t.buffer,t.byteOffset,t.byteLength),n=0;for(let s=0;s<r;s++){let o=i.getInt16(s*2,!0)/32768;n+=o*o}return Math.sqrt(n/r)>=e}function _te(t){let e=t.byteLength>>1,r=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let n=0;n<e;n++)i[n]=r.getInt16(n*2,!0);return i}var $s,vA,SA,Jo=D(()=>{"use strict";Nt();$s=.02;vA=class{threshold;constructor(e){this.threshold=e}classify(e,r){r(An(e,this.threshold))}},SA=class{vad;speechThreshold;energyThreshold;log;degraded=!1;announced=!1;disposed=!1;constructor(e,r={}){this.vad=e,this.speechThreshold=r.speechThreshold??.5,this.energyThreshold=r.energyThreshold??$s,this.log=r.log??ie}classify(e,r){if(this.degraded){this.announce("energy (fallback)"),r(An(e,this.energyThreshold));return}this.vad.process(_te(e)).then(i=>{if(!this.disposed){this.announce("silero");for(let n of i)r(n>=this.speechThreshold)}},i=>{this.disposed||(this.degrade(i),this.announce("energy (fallback)"),r(An(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}`))}}});function Yb(t){return new Error(`openai-compat ASR decode failed (HTTP ${t})`)}function qb(t){t.body?.cancel().catch(()=>{})}function Tte(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Lte(t){return t.replace(Mte," ")}function Fte(t){let e;try{e=new URL(t)}catch{throw new Error("openai-compat ASR route url must be a valid http:// or https:// URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`openai-compat ASR route url must use the http:// or https:// scheme (got '${e.protocol}//' - this is an HTTP endpoint, not a WebSocket)`);if(e.username!==""||e.password!=="")throw new Error("openai-compat ASR route url must not embed credentials (user:pass@) - configure the key in secrets instead");return t.replace(/\/+$/,"")}function Ute(t,e){let r=new Uint8Array(e),i=0;for(let n of t)r.set(n,i),i+=n.byteLength;return r}function Ote(t,e){let r=new Uint8Array(44+t.byteLength),i=new DataView(r.buffer);return hp(r,0,"RIFF"),i.setUint32(4,36+t.byteLength,!0),hp(r,8,"WAVE"),hp(r,12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,e,!0),i.setUint32(28,e*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),hp(r,36,"data"),i.setUint32(40,t.byteLength,!0),r.set(t,44),r}function hp(t,e,r){for(let i=0;i<r.length;i+=1)t[e+i]=r.charCodeAt(i)}function pF(t,e=0){if(!(t instanceof Error)||e>3)return"network error";if(t instanceof AggregateError&&t.message.length===0){let r=t.errors.find(i=>i instanceof Error&&i.message.length>0);if(r)return r.message}return t.cause instanceof Error&&(t.message.length===0||t.message==="fetch failed")?pF(t.cause,e+1):t.message.length>0?t.message:t.name.length>0?t.name:"network error"}var zb,Wb,fF,kte,fp,jb,gF,Nte,Rte,Mte,Jb=D(()=>{"use strict";Nt();Os();wA();Jo();zb="http://localhost:8081",Wb="large-v3-turbo",fF=1e3,kte=1e4,fp=class{fetchImpl;model;clock;id="openai-compat";partialStability="redecode";baseUrl;key;negotiation={dialect:null};constructor(e,r=zb,i=Wb,n,s=new Oi){this.fetchImpl=e,this.model=i,this.clock=s,this.baseUrl=Fte(r),this.key=n!==void 0&&n.length>0?n:void 0,this.key!==void 0&&Us(this.key,"openai-compat ASR key")}open(e){return e.biasTerms!==void 0&&e.biasTerms.length>0&&ie.debug("openai-compat ASR: biasTerms are deliberately not mapped on this engine (the whisper initial-prompt hook measured mildly negative in the 0033 E1 bake-off) - proceeding unbiased",{count:e.biasTerms.length}),new jb({fetchImpl:this.fetchImpl,baseUrl:this.baseUrl,model:this.model,key:this.key,negotiation:this.negotiation,clock:this.clock},e)}},jb=class{ctx;opts;aborted=!1;closed=!1;endRequested=!1;buffered=[];bufferedBytes=0;inFlightDecode=null;inFlightAbort=null;speechSinceLastDecode=!1;lastDecodeAtMs=-1/0;lastEmittedPartial=null;transcriptCb;errorCb;endPending=null;constructor(e,r){this.ctx=e,this.opts=r}pushAudio(e){this.aborted||this.closed||this.endRequested||(this.buffered.push(e.slice()),this.bufferedBytes+=e.byteLength,!this.speechSinceLastDecode&&An(e,$s)&&(this.speechSinceLastDecode=!0),this.opts.emitPartials&&this.maybeRedecodeTick())}onTranscript(e){this.transcriptCb=e}onError(e){this.errorCb=e}end(){return this.aborted?Promise.reject(new Error("ASR stream already aborted")):this.closed?Promise.reject(new Error("ASR stream already closed")):this.endPending?Promise.reject(new Error("ASR end() already in progress")):new Promise((e,r)=>{this.endPending={resolve:e,reject:r},this.endRequested=!0,this.runFinalDecode()})}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()}maybeRedecodeTick(){if(this.inFlightDecode!==null||!this.speechSinceLastDecode||this.bufferedBytes<this.opts.sampleRate*2*(fF/1e3))return;let e=this.ctx.clock.now();e-this.lastDecodeAtMs<fF||(this.lastDecodeAtMs=e,this.speechSinceLastDecode=!1,this.inFlightDecode=this.decodeFullBuffer().then(r=>{this.aborted||this.closed||this.endRequested||r!==this.lastEmittedPartial&&(this.lastEmittedPartial=r,this.transcriptCb?.({text:r,isFinal:!1,startMs:0}))}).catch(r=>{ie.debug("openai-compat ASR re-decode tick failed - missed partial",{message:r instanceof Error?r.message:String(r)})}).finally(()=>{this.inFlightDecode=null}))}async runFinalDecode(){if(this.inFlightDecode!==null&&await this.inFlightDecode,this.aborted||this.closed||this.endPending===null)return;if(this.bufferedBytes===0){this.resolveEnd("");return}let e;try{e=await this.decodeFullBuffer()}catch(r){if(this.aborted||this.closed)return;this.failStream(r instanceof Error?r:new Error(String(r)));return}this.aborted||this.closed||this.resolveEnd(e)}resolveEnd(e){if(!this.endPending)return;let r={text:e.trim(),isFinal:!0,startMs:0};this.transcriptCb?.(r);let{resolve:i}=this.endPending;this.endPending=null,this.teardown(),i(r)}failStream(e){if(this.endPending){let{reject:r}=this.endPending;this.endPending=null,r(e)}this.errorCb?.(e),this.teardown()}async decodeFullBuffer(){let e=Ote(Ute(this.buffered,this.bufferedBytes),this.opts.sampleRate),r=new AbortController,i={timedOut:!1};this.inFlightAbort=r;let n=this.ctx.clock.setTimer(this.decodeReplyTimeoutMs(),()=>{i.timedOut=!0,r.abort()});try{let s=await this.postWithNegotiation(e,r.signal),o;try{o=await s.json()}catch{throw new Error("openai-compat ASR decode returned invalid JSON")}let a=Tte(o)&&typeof o.text=="string"?o.text:"";return Lte(a)}catch(s){throw i.timedOut?new Error("openai-compat ASR decode timed out",{cause:s}):s instanceof Error?s:new Error(String(s))}finally{this.ctx.clock.clearTimer(n),this.inFlightAbort===r&&(this.inFlightAbort=null)}}async postWithNegotiation(e,r){let i=this.ctx.negotiation.dialect;if(i!==null){let o=await this.post(i,e,r);if(!o.ok)throw qb(o),Yb(o.status);return o}let n=await this.post("standard",e,r);if(n.ok)return this.ctx.negotiation.dialect="standard",n;if(qb(n),n.status!==404)throw Yb(n.status);let s=await this.post("inference",e,r);if(s.ok)return this.ctx.negotiation.dialect="inference",s;throw qb(s),Yb(s.status)}async post(e,r,i){let n=e==="standard"?`${this.ctx.baseUrl}/v1/audio/transcriptions`:`${this.ctx.baseUrl}/inference`,s=new FormData;s.append("file",new Blob([r],{type:"audio/wav"}),"utterance.wav"),e==="standard"&&s.append("model",this.ctx.model),this.opts.language!==void 0&&s.append("language",this.opts.language),s.append("temperature","0"),s.append("response_format","json");try{return await this.ctx.fetchImpl(n,{method:"POST",body:s,...this.ctx.key!==void 0&&{headers:{Authorization:`Bearer ${this.ctx.key}`}},signal:i})}catch(o){throw i.aborted?new Error("openai-compat ASR request aborted",{cause:o}):new Error(`openai-compat ASR request failed: ${pF(o)}`,{cause:o})}}decodeReplyTimeoutMs(){let e=this.bufferedBytes/2/this.opts.sampleRate*1e3;return kte+Math.ceil(e)}teardown(){this.closed||(this.closed=!0,this.inFlightAbort?.abort(),this.inFlightAbort=null)}};gF=" ",Nte="\r",Rte=`
|
|
72
|
-
`,Mte=new RegExp(`[ ${gF}]*[${Nte}${Rte}]+[ ${gF}]*`,"g")});var dn,DA=D(()=>{"use strict";dn=class extends Error{category;constructor(e,r){super(e),this.category=r,this.name="ASRTerminalError"}}});function Ps(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function _A(t){return typeof t=="string"?t:""}function jc(t){let e=t.message_type;return typeof e=="string"&&($te.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function mF(t){return Buffer.from(t).toString("base64")}function gp(t){return new Uint8Array(Buffer.from(t,"base64"))}function kA(t,e){return new Error(`${t} connection error: ${e.message}`)}function EF(t){return Pte[t]??null}function IF(t,e){if(e instanceof dn)return new dn(`${t} connection error: ${e.message}`,e.category);let r=Hte.exec(e.message)?.[1];return r!==void 0?new dn(`${t} connection error: rejected credential (HTTP ${r})`,"auth"):kA(t,e)}var $te,Pte,Hte,TA=D(()=>{"use strict";DA();$te=new Set(["error","auth_error","quota_exceeded","rate_limited"]);Pte={quota_exceeded:"quota",auth_error:"auth"};Hte=/^Unexpected server response: (401|403)\b/});function BF(t,e){let r=new Uint8Array(e),i=0;for(let n of t)r.set(n,i),i+=n.byteLength;return r}function Gte(t){if(t.message.length>0)return t.message;if(t instanceof AggregateError){let e=t.errors.find(r=>r instanceof Error&&r.message.length>0);if(e)return e.message}return t.name.length>0?t.name:"connection failed"}function Yte(t){let e=Math.floor(t.byteLength/2),r=new DataView(t.buffer,t.byteOffset,e*2),i=new Float32Array(e);for(let n=0;n<e;n+=1)i[n]=r.getInt16(n*2,!0)/32768;return i}var pp,CF,yF,Vte,NA,Zb,mp=D(()=>{"use strict";Nt();wA();Jo();TA();pp="ws://localhost:6007",CF=1e3,yF=10240,Vte=1e4,NA=class{socketFactory;url;clock;id="sherpa-onnx";partialStability="redecode";constructor(e,r=pp,i=new Oi){this.socketFactory=e,this.url=r,this.clock=i}open(e){return e.biasTerms!==void 0&&e.biasTerms.length>0&&ie.debug("sherpa ASR: biasTerms are not mappable on this engine (the TDT export ships no hotword vocab; watch k2-fsa/sherpa-onnx#3573) - proceeding unbiased",{count:e.biasTerms.length}),new Zb(this.socketFactory,this.url,this.clock,e)}},Zb=class{clock;opts;socket;opened=!1;aborted=!1;closed=!1;endRequested=!1;buffered=[];bufferedBytes=0;inFlightDecode=null;speechSinceLastDecode=!1;pendingReply=null;staleReplies=0;lastDecodeAtMs=-1/0;lastEmittedPartial=null;transcriptCb;errorCb;endPending=null;constructor(e,r,i,n){this.clock=i,this.opts=n,this.socket=e(r,{}),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){this.aborted||this.closed||this.endRequested||(this.buffered.push(e.slice()),this.bufferedBytes+=e.byteLength,!this.speechSinceLastDecode&&An(e,$s)&&(this.speechSinceLastDecode=!0),this.opened&&this.opts.emitPartials&&this.maybeRedecodeTick())}onTranscript(e){this.transcriptCb=e}onError(e){this.errorCb=e}end(){return this.aborted?Promise.reject(new Error("ASR stream already aborted")):this.closed?Promise.reject(new Error("ASR stream already closed")):this.endPending?Promise.reject(new Error("ASR end() already in progress")):new Promise((e,r)=>{this.endPending={resolve:e,reject:r},this.endRequested=!0,this.opened&&this.runFinalDecode()})}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(){this.aborted||this.closed||(this.opened=!0,this.endRequested&&this.runFinalDecode())}handleMessage(e){if(this.aborted||this.closed)return;let r=Ps(e);if(r){if(this.staleReplies>0){this.staleReplies-=1;return}if(this.pendingReply){let{resolve:i,timer:n}=this.pendingReply;this.pendingReply=null,this.clock.clearTimer(n),i(_A(r.text))}}}handleError(e){if(this.closed)return;let r=kA("sherpa ASR",new Error(Gte(e)));this.failStream(r)}handleClose(){this.closed||(this.closed=!0,this.settleFailure(new Error("sherpa ASR connection closed unexpectedly")))}failStream(e){this.settleFailure(e),this.teardown()}settleFailure(e){if(this.endPending){let{reject:r}=this.endPending;this.endPending=null,r(e)}this.rejectPendingReply(e),this.errorCb?.(e)}rejectPendingReply(e){if(!this.pendingReply)return;let{reject:r,timer:i}=this.pendingReply;this.pendingReply=null,this.clock.clearTimer(i),r(e)}maybeRedecodeTick(){if(this.inFlightDecode!==null||!this.speechSinceLastDecode||this.bufferedBytes<this.opts.sampleRate*2*(CF/1e3))return;let e=this.clock.now();e-this.lastDecodeAtMs<CF||(this.lastDecodeAtMs=e,this.speechSinceLastDecode=!1,this.inFlightDecode=this.decodeFullBuffer().then(r=>{this.aborted||this.closed||this.endRequested||r!==this.lastEmittedPartial&&(this.lastEmittedPartial=r,this.transcriptCb?.({text:r,isFinal:!1,startMs:0}))}).catch(()=>{}).finally(()=>{this.inFlightDecode=null}))}async runFinalDecode(){if(this.inFlightDecode!==null&&await this.inFlightDecode,this.aborted||this.closed||this.endPending===null)return;if(this.bufferedBytes===0){this.resolveEnd("");return}let e;try{e=await this.decodeFullBuffer()}catch(r){if(this.aborted||this.closed)return;this.failStream(r instanceof Error?r:new Error(String(r)));return}this.aborted||this.closed||this.resolveEnd(e)}resolveEnd(e){if(!this.endPending)return;let r={text:e.trim(),isFinal:!0,startMs:0};this.transcriptCb?.(r);let{resolve:i}=this.endPending;this.endPending=null,this.socket.send("Done"),this.teardown(),i(r)}decodeFullBuffer(){let e=Yte(BF(this.buffered,this.bufferedBytes)),r=new Uint8Array(e.buffer,0,e.byteLength),i=new Uint8Array(8),n=new DataView(i.buffer);n.setUint32(0,this.opts.sampleRate,!0),n.setUint32(4,r.byteLength,!0);let s=BF([i,r],i.byteLength+r.byteLength),o=new Promise((a,c)=>{let l=this.clock.setTimer(this.decodeReplyTimeoutMs(),()=>{this.pendingReply&&(this.pendingReply=null,this.staleReplies+=1,c(new Error("sherpa ASR decode timed out")))});this.pendingReply={resolve:a,reject:c,timer:l}});try{for(let a=0;a<s.byteLength;a+=yF)this.socket.send(s.subarray(a,Math.min(a+yF,s.byteLength)))}catch(a){this.rejectPendingReply(a instanceof Error?a:new Error(String(a)))}return o}decodeReplyTimeoutMs(){let e=this.bufferedBytes/2/this.opts.sampleRate*1e3;return Vte+Math.ceil(e)}teardown(){this.closed||(this.closed=!0,this.rejectPendingReply(new Error("sherpa ASR stream closed")),this.socket.close())}}});var xF,Ep,qte,jte,zte,RA,Xb,Ip=D(()=>{"use strict";TA();xF="wss://api.elevenlabs.io/v1/text-to-dialogue/stream-input",Ep=["eleven_v3","eleven_v3_conversational"],qte=1e4,jte=1e4,zte=6e4,RA=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-v3";constructor(e,r,i,n=xF){this.apiKey=e,this.socketFactory=r,this.model=i,this.endpoint=n}speak(e){let r=e.voice.engineVoice[this.id];if(!r)throw new Error(`voice '${e.voice.id}' has no '${this.id}' engineVoice mapping`);if(r.kind!=="preset")throw new Error(`the ${this.id} adapter needs a preset voiceId for '${e.voice.id}'`);if(e.encoding!=="pcm_s16le")throw new Error("ElevenLabs v3 TTS requires pcm_s16le audio");let i=new URL(this.endpoint);return i.searchParams.set("model_id",this.model),i.searchParams.set("output_format",`pcm_${e.sampleRate}`),new Xb(this.apiKey,this.socketFactory,i.toString(),r.voiceId)}},Xb=class{voiceId;socket;state="active";opened=!1;closeRequested=!1;pending=[];failure;audioCb;errorCb;endPending=null;handshakeTimer;keepAliveTimer;finalTimer;constructor(e,r,i,n){this.voiceId=n;try{this.socket=r(i,{"xi-api-key":e})}catch{throw new Error("ElevenLabs v3 TTS connection error")}this.handshakeTimer=setTimeout(()=>this.fail(new Error("ElevenLabs v3 TTS connection timed out")),qte),this.handshakeTimer.unref(),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(s=>this.handleMessage(s)),this.socket.onError(()=>this.fail(new Error("ElevenLabs v3 TTS connection error"))),this.socket.onClose(()=>this.fail(new Error("ElevenLabs v3 TTS connection closed unexpectedly")))}pushText(e){if(!(this.state!=="active"||e.trim().length===0)){if(!this.opened){this.pending.push(e);return}this.sendText(e)}}onAudio(e){this.audioCb=e}onError(e){this.errorCb=e,this.failure&&e(this.failure)}end(){return this.failure?Promise.reject(this.failure):this.terminal()?Promise.resolve():this.endPending?Promise.reject(new Error("TTS end() already in progress")):new Promise((e,r)=>{this.endPending={resolve:e,reject:r},this.state="ending",this.opened&&this.sendEnd()})}cancel(){if(this.terminal())return Promise.resolve();this.state="cancelled";let e=this.endPending;return this.endPending=null,this.teardown(),e?.resolve(),Promise.resolve()}handleOpen(){if(!(this.terminal()||this.opened)&&(this.opened=!0,clearTimeout(this.handshakeTimer),this.handshakeTimer=void 0,!!this.send({voices:[this.voiceId],voice_settings:{stability:.5}}))){this.state==="active"&&(this.keepAliveTimer=setInterval(()=>this.send({keep_alive:!0}),jte),this.keepAliveTimer.unref());for(let e of this.pending.splice(0))if(!this.sendText(e))return;this.state==="ending"&&this.sendEnd()}}sendText(e){let r=e.endsWith(" ")?e:`${e} `;return this.send({inputs:[{text:r,voice_id:this.voiceId}],flush:!0})}sendEnd(){this.terminal()||this.closeRequested||(this.closeRequested=!0,clearInterval(this.keepAliveTimer),this.keepAliveTimer=void 0,this.finalTimer=setTimeout(()=>this.fail(new Error("ElevenLabs v3 TTS final audio timed out")),zte),this.finalTimer.unref(),this.send({close_socket:!0}))}handleMessage(e){if(this.terminal()||!this.opened)return;let r=Ps(e);if(r){if(typeof r.error=="string"||jc(r)!==null){this.fail(new Error("ElevenLabs v3 TTS stream error"));return}if(typeof r.audio=="string"&&r.audio.length>0&&this.audioCb?.(gp(r.audio)),!this.terminal()&&r.is_final===!0){if(this.state!=="ending"||!this.closeRequested){this.fail(new Error("ElevenLabs v3 TTS stream ended unexpectedly"));return}this.state="complete";let i=this.endPending;this.endPending=null,this.teardown(),i?.resolve()}}}send(e){if(this.terminal())return!1;try{return this.socket.send(JSON.stringify(e)),!this.terminal()}catch{return this.fail(new Error("ElevenLabs v3 TTS failed to send")),!1}}fail(e){if(this.terminal())return;this.failure=e,this.state="failed";let r=this.endPending;this.endPending=null,this.teardown(),r?.reject(e),this.errorCb?.(e)}terminal(){return this.state==="complete"||this.state==="cancelled"||this.state==="failed"}teardown(){this.pending.length=0,clearTimeout(this.handshakeTimer),clearInterval(this.keepAliveTimer),clearTimeout(this.finalTimer),this.handshakeTimer=void 0,this.keepAliveTimer=void 0,this.finalTimer=void 0;try{this.socket.close()}catch{}}}});var $i=Q((bRe,wF)=>{"use strict";var QF=["nodebuffer","arraybuffer","fragments"],bF=typeof Blob<"u";bF&&QF.push("blob");wF.exports={BINARY_TYPES:QF,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bF,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var MA=Q((wRe,Cp)=>{"use strict";var{EMPTY_BUFFER:Wte}=$i(),Kb=Buffer[Symbol.species];function Jte(t,e){if(t.length===0)return Wte;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let n=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return i<e?new Kb(r.buffer,r.byteOffset,i):r}function vF(t,e,r,i,n){for(let s=0;s<n;s++)r[i+s]=t[s]^e[s&3]}function SF(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Zte(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ew(t){if(ew.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Kb(t):ArrayBuffer.isView(t)?e=new Kb(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ew.readOnly=!1),e}Cp.exports={concat:Jte,mask:vF,toArrayBuffer:Zte,toBuffer:ew,unmask:SF};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=R("bufferutil");Cp.exports.mask=function(e,r,i,n,s){s<48?vF(e,r,i,n,s):t.mask(e,r,i,n,s)},Cp.exports.unmask=function(e,r){e.length<32?SF(e,r):t.unmask(e,r)}}catch{}});var kF=Q((vRe,_F)=>{"use strict";var DF=Symbol("kDone"),tw=Symbol("kRun"),rw=class{constructor(e){this[DF]=()=>{this.pending--,this[tw]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[tw]()}[tw](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[DF])}}};_F.exports=rw});var Jc=Q((SRe,MF)=>{"use strict";var LA=R("zlib"),TF=MA(),Xte=kF(),{kStatusCode:NF}=$i(),Kte=Buffer[Symbol.species],ere=Buffer.from([0,0,255,255]),Bp=Symbol("permessage-deflate"),Pi=Symbol("total-length"),zc=Symbol("callback"),Hs=Symbol("buffers"),Wc=Symbol("error"),yp,nw=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,!yp){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;yp=new Xte(r)}}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[zc];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let n=r[i];if(n.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(n=n[0],i==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else if(i==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=n})}),e}decompress(e,r,i){yp.add(n=>{this._decompress(e,r,(s,o)=>{n(),i(s,o)})})}compress(e,r,i){yp.add(n=>{this._compress(e,r,(s,o)=>{n(),i(s,o)})})}_decompress(e,r,i){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,o=typeof this.params[s]!="number"?LA.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=LA.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Bp]=this,this._inflate[Pi]=0,this._inflate[Hs]=[],this._inflate.on("error",rre),this._inflate.on("data",RF)}this._inflate[zc]=i,this._inflate.write(e),r&&this._inflate.write(ere),this._inflate.flush(()=>{let s=this._inflate[Wc];if(s){this._inflate.close(),this._inflate=null,i(s);return}let o=TF.concat(this._inflate[Hs],this._inflate[Pi]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Pi]=0,this._inflate[Hs]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),i(null,o)})}_compress(e,r,i){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,o=typeof this.params[s]!="number"?LA.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=LA.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Pi]=0,this._deflate[Hs]=[],this._deflate.on("data",tre)}this._deflate[zc]=i,this._deflate.write(e),this._deflate.flush(LA.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=TF.concat(this._deflate[Hs],this._deflate[Pi]);r&&(s=new Kte(s.buffer,s.byteOffset,s.length-4)),this._deflate[zc]=null,this._deflate[Pi]=0,this._deflate[Hs]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,s)})}};MF.exports=nw;function tre(t){this[Hs].push(t),this[Pi]+=t.length}function RF(t){if(this[Pi]+=t.length,this[Bp]._maxPayload<1||this[Pi]<=this[Bp]._maxPayload){this[Hs].push(t);return}this[Wc]=new RangeError("Max payload size exceeded"),this[Wc].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Wc][NF]=1009,this.removeListener("data",RF),this.reset()}function rre(t){if(this[Bp]._inflate=null,this[Wc]){this[zc](this[Wc]);return}t[NF]=1007,this[zc](t)}});var Zc=Q((DRe,xp)=>{"use strict";var{isUtf8:LF}=R("buffer"),{hasBlob:nre}=$i(),ire=[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 sre(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function iw(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function ore(t){return nre&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}xp.exports={isBlob:ore,isValidStatusCode:sre,isValidUTF8:iw,tokenChars:ire};if(LF)xp.exports.isValidUTF8=function(t){return t.length<24?iw(t):LF(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=R("utf-8-validate");xp.exports.isValidUTF8=function(e){return e.length<32?iw(e):t(e)}}catch{}});var lw=Q((_Re,VF)=>{"use strict";var{Writable:are}=R("stream"),FF=Jc(),{BINARY_TYPES:cre,EMPTY_BUFFER:UF,kStatusCode:lre,kWebSocket:ure}=$i(),{concat:sw,toArrayBuffer:Are,unmask:dre}=MA(),{isValidStatusCode:hre,isValidUTF8:OF}=Zc(),Qp=Buffer[Symbol.species],hn=0,$F=1,PF=2,HF=3,ow=4,aw=5,bp=6,cw=class extends are{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||cre[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[ure]=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=hn}_write(e,r,i){if(this._opcode===8&&this._state==hn)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 Qp(i.buffer,i.byteOffset+e,i.length-e),new Qp(i.buffer,i.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let i=this._buffers[0],n=r.length-e;e>=i.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),n),this._buffers[0]=new Qp(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case hn:this.getInfo(e);break;case $F:this.getPayloadLength16(e);break;case PF:this.getPayloadLength64(e);break;case HF:this.getMask();break;case ow:this.getData(e);break;case aw:case bp:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let i=(r[0]&64)===64;if(i&&!this._extensions[FF.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=$F:this._payloadLength===127?this._state=PF: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 r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=i*Math.pow(2,32)+r.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 r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=HF:this._state=ow}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ow}getData(e){let r=UF;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&dre(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=aw,this.decompress(r,e);return}if(r.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(r)}this.dataMessage(e)}decompress(e,r){this._extensions[FF.extensionName].decompress(e,this._fin,(n,s)=>{if(n)return r(n);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(o);return}this._fragments.push(s)}this.dataMessage(r),this._state===hn&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=hn;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=sw(i,r):this._binaryType==="arraybuffer"?n=Are(sw(i,r)):this._binaryType==="blob"?n=new Blob(i):n=i,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=hn):(this._state=bp,setImmediate(()=>{this.emit("message",n,!0),this._state=hn,this.startLoop(e)}))}else{let n=sw(i,r);if(!this._skipUTF8Validation&&!OF(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===aw||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=hn):(this._state=bp,setImmediate(()=>{this.emit("message",n,!1),this._state=hn,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,UF),this.end();else{let i=e.readUInt16BE(0);if(!hre(i)){let s=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let n=new Qp(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!OF(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",i,n),this.end()}this._state=hn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=hn):(this._state=bp,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=hn,this.startLoop(r)}))}createError(e,r,i,n,s){this._loop=!1,this._errored=!0;let o=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=s,o[lre]=n,o}};VF.exports=cw});var dw=Q((TRe,qF)=>{"use strict";var{Duplex:kRe}=R("stream"),{randomFillSync:fre}=R("crypto"),{types:{isUint8Array:gre}}=R("util"),GF=Jc(),{EMPTY_BUFFER:pre,kWebSocket:mre,NOOP:Ere}=$i(),{isBlob:Xc,isValidStatusCode:Ire}=Zc(),{mask:YF,toBuffer:Zo}=MA(),fn=Symbol("kByteLength"),Cre=Buffer.alloc(4),wp=8*1024,Xo,Kc=wp,Ln=0,yre=1,Bre=2,uw=class t{constructor(e,r,i){this._extensions=r||{},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=Ln,this.onerror=Ere,this[mre]=void 0}static frame(e,r){let i,n=!1,s=2,o=!1;r.mask&&(i=r.maskBuffer||Cre,r.generateMask?r.generateMask(i):(Kc===wp&&(Xo===void 0&&(Xo=Buffer.alloc(wp)),fre(Xo,0,wp),Kc=0),i[0]=Xo[Kc++],i[1]=Xo[Kc++],i[2]=Xo[Kc++],i[3]=Xo[Kc++]),o=(i[0]|i[1]|i[2]|i[3])===0,s=6);let a;typeof e=="string"?(!r.mask||o)&&r[fn]!==void 0?a=r[fn]:(e=Buffer.from(e),a=e.length):(a=e.length,n=r.mask&&r.readOnly&&!o);let c=a;a>=65536?(s+=8,c=127):a>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(n?a+s:s);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[s-4]=i[0],l[s-3]=i[1],l[s-2]=i[2],l[s-1]=i[3],o?[l,e]:n?(YF(e,i,l,s,a),[l]):(YF(e,i,e,0,a),[l,e])):[l,e]}close(e,r,i,n){let s;if(e===void 0)s=pre;else{if(typeof e!="number"||!Ire(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof r=="string")s.write(r,2);else if(gre(r))s.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[fn]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ln?this.enqueue([this.dispatch,s,!1,o,n]):this.sendFrame(t.frame(s,o),n)}ping(e,r,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):Xc(e)?(n=e.size,s=!1):(e=Zo(e),n=e.length,s=Zo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[fn]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Xc(e)?this._state!==Ln?this.enqueue([this.getBlobData,e,!1,o,i]):this.getBlobData(e,!1,o,i):this._state!==Ln?this.enqueue([this.dispatch,e,!1,o,i]):this.sendFrame(t.frame(e,o),i)}pong(e,r,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):Xc(e)?(n=e.size,s=!1):(e=Zo(e),n=e.length,s=Zo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[fn]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Xc(e)?this._state!==Ln?this.enqueue([this.getBlobData,e,!1,o,i]):this.getBlobData(e,!1,o,i):this._state!==Ln?this.enqueue([this.dispatch,e,!1,o,i]):this.sendFrame(t.frame(e,o),i)}send(e,r,i){let n=this._extensions[GF.extensionName],s=r.binary?2:1,o=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Xc(e)?(a=e.size,c=!1):(e=Zo(e),a=e.length,c=Zo.readOnly),this._firstFragment?(this._firstFragment=!1,o&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=n._threshold),this._compress=o):(o=!1,s=0),r.fin&&(this._firstFragment=!0);let l={[fn]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};Xc(e)?this._state!==Ln?this.enqueue([this.getBlobData,e,this._compress,l,i]):this.getBlobData(e,this._compress,l,i):this._state!==Ln?this.enqueue([this.dispatch,e,this._compress,l,i]):this.dispatch(e,this._compress,l,i)}getBlobData(e,r,i,n){this._bufferedBytes+=i[fn],this._state=Bre,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Aw,this,a,n);return}this._bufferedBytes-=i[fn];let o=Zo(s);r?this.dispatch(o,r,i,n):(this._state=Ln,this.sendFrame(t.frame(o,i),n),this.dequeue())}).catch(s=>{process.nextTick(xre,this,s,n)})}dispatch(e,r,i,n){if(!r){this.sendFrame(t.frame(e,i),n);return}let s=this._extensions[GF.extensionName];this._bufferedBytes+=i[fn],this._state=yre,s.compress(e,i.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Aw(this,c,n);return}this._bufferedBytes-=i[fn],this._state=Ln,i.readOnly=!1,this.sendFrame(t.frame(a,i),n),this.dequeue()})}dequeue(){for(;this._state===Ln&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][fn],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][fn],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};qF.exports=uw;function Aw(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let n=t._queue[i],s=n[n.length-1];typeof s=="function"&&s(e)}}function xre(t,e,r){Aw(t,e,r),t.onerror(e)}});var tU=Q((NRe,eU)=>{"use strict";var{kForOnEventAttribute:FA,kListener:hw}=$i(),jF=Symbol("kCode"),zF=Symbol("kData"),WF=Symbol("kError"),JF=Symbol("kMessage"),ZF=Symbol("kReason"),el=Symbol("kTarget"),XF=Symbol("kType"),KF=Symbol("kWasClean"),Hi=class{constructor(e){this[el]=null,this[XF]=e}get target(){return this[el]}get type(){return this[XF]}};Object.defineProperty(Hi.prototype,"target",{enumerable:!0});Object.defineProperty(Hi.prototype,"type",{enumerable:!0});var Ko=class extends Hi{constructor(e,r={}){super(e),this[jF]=r.code===void 0?0:r.code,this[ZF]=r.reason===void 0?"":r.reason,this[KF]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[jF]}get reason(){return this[ZF]}get wasClean(){return this[KF]}};Object.defineProperty(Ko.prototype,"code",{enumerable:!0});Object.defineProperty(Ko.prototype,"reason",{enumerable:!0});Object.defineProperty(Ko.prototype,"wasClean",{enumerable:!0});var tl=class extends Hi{constructor(e,r={}){super(e),this[WF]=r.error===void 0?null:r.error,this[JF]=r.message===void 0?"":r.message}get error(){return this[WF]}get message(){return this[JF]}};Object.defineProperty(tl.prototype,"error",{enumerable:!0});Object.defineProperty(tl.prototype,"message",{enumerable:!0});var UA=class extends Hi{constructor(e,r={}){super(e),this[zF]=r.data===void 0?null:r.data}get data(){return this[zF]}};Object.defineProperty(UA.prototype,"data",{enumerable:!0});var Qre={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[FA]&&n[hw]===e&&!n[FA])return;let i;if(t==="message")i=function(s,o){let a=new UA("message",{data:o?s:s.toString()});a[el]=this,vp(e,this,a)};else if(t==="close")i=function(s,o){let a=new Ko("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[el]=this,vp(e,this,a)};else if(t==="error")i=function(s){let o=new tl("error",{error:s,message:s.message});o[el]=this,vp(e,this,o)};else if(t==="open")i=function(){let s=new Hi("open");s[el]=this,vp(e,this,s)};else return;i[FA]=!!r[FA],i[hw]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[hw]===e&&!r[FA]){this.removeListener(t,r);break}}};eU.exports={CloseEvent:Ko,ErrorEvent:tl,Event:Hi,EventTarget:Qre,MessageEvent:UA};function vp(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Sp=Q((RRe,rU)=>{"use strict";var{tokenChars:OA}=Zc();function oi(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function bre(t){let e=Object.create(null),r=Object.create(null),i=!1,n=!1,s=!1,o,a,c=-1,l=-1,A=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),o===void 0)if(A===-1&&OA[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))A===-1&&c!==-1&&(A=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);A===-1&&(A=d);let u=t.slice(c,A);l===44?(oi(e,u,r),r=Object.create(null)):o=u,c=A=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(A===-1&&OA[l]===1)c===-1&&(c=d);else if(l===32||l===9)A===-1&&c!==-1&&(A=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);A===-1&&(A=d),oi(r,t.slice(c,A),!0),l===44&&(oi(e,o,r),r=Object.create(null),o=void 0),c=A=-1}else if(l===61&&c!==-1&&A===-1)a=t.slice(c,d),c=A=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(n){if(OA[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:i||(i=!0),n=!1}else if(s)if(OA[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)s=!1,A=d;else if(l===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)s=!0;else if(A===-1&&OA[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))A===-1&&(A=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);A===-1&&(A=d);let u=t.slice(c,A);i&&(u=u.replace(/\\/g,""),i=!1),oi(r,a,u),l===44&&(oi(e,o,r),r=Object.create(null),o=void 0),a=void 0,c=A=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");A===-1&&(A=d);let h=t.slice(c,A);return o===void 0?oi(e,h,r):(a===void 0?oi(r,h,!0):i?oi(r,a,h.replace(/\\/g,"")):oi(r,a,h),oi(e,o,r)),e}function wre(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(n=>{let s=i[n];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?n:`${n}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}rU.exports={format:wre,parse:bre}});var Tp=Q((FRe,fU)=>{"use strict";var vre=R("events"),Sre=R("https"),Dre=R("http"),sU=R("net"),_re=R("tls"),{randomBytes:kre,createHash:Tre}=R("crypto"),{Duplex:MRe,Readable:LRe}=R("stream"),{URL:fw}=R("url"),Vs=Jc(),Nre=lw(),Rre=dw(),{isBlob:Mre}=Zc(),{BINARY_TYPES:nU,CLOSE_TIMEOUT:Lre,EMPTY_BUFFER:Dp,GUID:Fre,kForOnEventAttribute:gw,kListener:Ure,kStatusCode:Ore,kWebSocket:Lt,NOOP:oU}=$i(),{EventTarget:{addEventListener:$re,removeEventListener:Pre}}=tU(),{format:Hre,parse:Vre}=Sp(),{toBuffer:Gre}=MA(),aU=Symbol("kAborted"),pw=[8,13],Vi=["CONNECTING","OPEN","CLOSING","CLOSED"],Yre=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,At=class t extends vre{constructor(e,r,i){super(),this._binaryType=nU[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Dp,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,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),cU(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){nU.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,r,i){let n=new Nre({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),s=new Rre(e,this._extensions,i.generateMask);this._receiver=n,this._sender=s,this._socket=e,n[Lt]=this,s[Lt]=this,e[Lt]=this,n.on("conclude",zre),n.on("drain",Wre),n.on("error",Jre),n.on("message",Zre),n.on("ping",Xre),n.on("pong",Kre),s.onerror=ene,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",AU),e.on("data",kp),e.on("end",dU),e.on("error",hU),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[Vs.extensionName]&&this._extensions[Vs.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Vr(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,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),uU(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){mw(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Dp,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){mw(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Dp,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){mw(this,e,i);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Vs.extensionName]||(n.compress=!1),this._sender.send(e||Dp,n,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Vr(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(At,"CONNECTING",{enumerable:!0,value:Vi.indexOf("CONNECTING")});Object.defineProperty(At.prototype,"CONNECTING",{enumerable:!0,value:Vi.indexOf("CONNECTING")});Object.defineProperty(At,"OPEN",{enumerable:!0,value:Vi.indexOf("OPEN")});Object.defineProperty(At.prototype,"OPEN",{enumerable:!0,value:Vi.indexOf("OPEN")});Object.defineProperty(At,"CLOSING",{enumerable:!0,value:Vi.indexOf("CLOSING")});Object.defineProperty(At.prototype,"CLOSING",{enumerable:!0,value:Vi.indexOf("CLOSING")});Object.defineProperty(At,"CLOSED",{enumerable:!0,value:Vi.indexOf("CLOSED")});Object.defineProperty(At.prototype,"CLOSED",{enumerable:!0,value:Vi.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(At.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(At.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[gw])return e[Ure];return null},set(e){for(let r of this.listeners(t))if(r[gw]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[gw]:!0})}})});At.prototype.addEventListener=$re;At.prototype.removeEventListener=Pre;fU.exports=At;function cU(t,e,r,i){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Lre,protocolVersion:pw[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=n.autoPong,t._closeTimeout=n.closeTimeout,!pw.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${pw.join(", ")})`);let s;if(e instanceof fw)s=e;else try{s=new fw(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;_p(t,m);return}let l=o?443:80,A=kre(16).toString("base64"),d=o?Sre.request:Dre.request,h=new Set,u;if(n.createConnection=n.createConnection||(o?jre:qre),n.defaultPort=n.defaultPort||l,n.port=s.port||l,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":A,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(u=new Vs({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=Hre({[Vs.extensionName]:u.offer()})),r.length){for(let m of r){if(typeof m!="string"||!Yre.test(m)||h.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(m)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),a){let m=n.path.split(":");n.socketPath=m[0],n.path=m[1]}let f;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?n.socketPath:s.host;let m=i&&i.headers;if(i={...i,headers:{}},m)for(let[E,I]of Object.entries(m))i.headers[E.toLowerCase()]=I}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,m||delete n.headers.host,n.auth=void 0)}n.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),f=t._req=d(n),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(n);n.timeout&&f.on("timeout",()=>{Vr(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[aU]||(f=t._req=null,_p(t,m))}),f.on("response",m=>{let E=m.headers.location,I=m.statusCode;if(E&&n.followRedirects&&I>=300&&I<400){if(++t._redirects>n.maxRedirects){Vr(t,f,"Maximum redirects exceeded");return}f.abort();let C;try{C=new fw(E,e)}catch{let v=new SyntaxError(`Invalid URL: ${E}`);_p(t,v);return}cU(t,C,r,i)}else t.emit("unexpected-response",f,m)||Vr(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,E,I)=>{if(t.emit("upgrade",m),t.readyState!==At.CONNECTING)return;f=t._req=null;let C=m.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){Vr(t,E,"Invalid Upgrade header");return}let b=Tre("sha1").update(A+Fre).digest("base64");if(m.headers["sec-websocket-accept"]!==b){Vr(t,E,"Invalid Sec-WebSocket-Accept header");return}let v=m.headers["sec-websocket-protocol"],S;if(v!==void 0?h.size?h.has(v)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":h.size&&(S="Server sent no subprotocol"),S){Vr(t,E,S);return}v&&(t._protocol=v);let O=m.headers["sec-websocket-extensions"];if(O!==void 0){if(!u){Vr(t,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Vre(O)}catch{Vr(t,E,"Invalid Sec-WebSocket-Extensions header");return}let M=Object.keys(U);if(M.length!==1||M[0]!==Vs.extensionName){Vr(t,E,"Server indicated an extension that was not requested");return}try{u.accept(U[Vs.extensionName])}catch{Vr(t,E,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Vs.extensionName]=u}t.setSocket(E,I,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(f,t):f.end()}function _p(t,e){t._readyState=At.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function qre(t){return t.path=t.socketPath,sU.connect(t)}function jre(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=sU.isIP(t.host)?"":t.host),_re.connect(t)}function Vr(t,e,r){t._readyState=At.CLOSING;let i=new Error(r);Error.captureStackTrace(i,Vr),e.setHeader?(e[aU]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_p,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function mw(t,e,r){if(e){let i=Mre(e)?e.size:Gre(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Vi[t.readyState]})`);process.nextTick(r,i)}}function zre(t,e){let r=this[Lt];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Lt]!==void 0&&(r._socket.removeListener("data",kp),process.nextTick(lU,r._socket),t===1005?r.close():r.close(t,e))}function Wre(){let t=this[Lt];t.isPaused||t._socket.resume()}function Jre(t){let e=this[Lt];e._socket[Lt]!==void 0&&(e._socket.removeListener("data",kp),process.nextTick(lU,e._socket),e.close(t[Ore])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function iU(){this[Lt].emitClose()}function Zre(t,e){this[Lt].emit("message",t,e)}function Xre(t){let e=this[Lt];e._autoPong&&e.pong(t,!this._isServer,oU),e.emit("ping",t)}function Kre(t){this[Lt].emit("pong",t)}function lU(t){t.resume()}function ene(t){let e=this[Lt];e.readyState!==At.CLOSED&&(e.readyState===At.OPEN&&(e._readyState=At.CLOSING,uU(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function uU(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function AU(){let t=this[Lt];if(this.removeListener("close",AU),this.removeListener("data",kp),this.removeListener("end",dU),t._readyState=At.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[Lt]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",iU),t._receiver.on("finish",iU))}function kp(t){this[Lt]._receiver.write(t)||this.pause()}function dU(){let t=this[Lt];t._readyState=At.CLOSING,t._receiver.end(),this.end()}function hU(){let t=this[Lt];this.removeListener("error",hU),this.on("error",oU),t&&(t._readyState=At.CLOSING,this.destroy())}});var EU=Q((ORe,mU)=>{"use strict";var URe=Tp(),{Duplex:tne}=R("stream");function gU(t){t.emit("close")}function rne(){!this.destroyed&&this._writableState.finished&&this.destroy()}function pU(t){this.removeListener("error",pU),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function nne(t,e){let r=!0,i=new tne({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&i._readableState.objectMode?s.toString():s;i.push(a)||t.pause()}),t.once("error",function(s){i.destroyed||(r=!1,i.destroy(s))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(n,s){if(t.readyState===t.CLOSED){s(n),process.nextTick(gU,i);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(n),process.nextTick(gU,i)}),r&&t.terminate()},i._final=function(n){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(n)});return}t._socket!==null&&(t._socket._writableState.finished?(n(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){n()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(n,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(n,s,o)});return}t.send(n,o)},i.on("end",rne),i.on("error",pU),i}mU.exports=nne});var Ew=Q(($Re,IU)=>{"use strict";var{tokenChars:ine}=Zc();function sne(t){let e=new Set,r=-1,i=-1,n=0;for(n;n<t.length;n++){let o=t.charCodeAt(n);if(i===-1&&ine[o]===1)r===-1&&(r=n);else if(n!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=n);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);i===-1&&(i=n);let a=t.slice(r,i);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,n);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}IU.exports={parse:sne}});var wU=Q((HRe,bU)=>{"use strict";var one=R("events"),Np=R("http"),{Duplex:PRe}=R("stream"),{createHash:ane}=R("crypto"),CU=Sp(),ea=Jc(),cne=Ew(),lne=Tp(),{CLOSE_TIMEOUT:une,GUID:Ane,kWebSocket:dne}=$i(),hne=/^[+/0-9A-Za-z]{22}==$/,yU=0,BU=1,QU=2,Iw=class extends one{constructor(e,r){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:une,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:lne,...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=Np.createServer((i,n)=>{let s=Np.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=fne(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,o)=>{this.handleUpgrade(n,s,o,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=yU}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===QU){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick($A,this);return}if(e&&this.once("close",e),this._state!==BU)if(this._state=BU,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($A,this):process.nextTick($A,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{$A(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,n){r.on("error",xU);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ta(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ta(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!hne.test(s)){ta(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ta(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){PA(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=cne.parse(c)}catch{ta(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let A=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&A!==void 0){let h=new ea({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let u=CU.parse(A);u[ea.extensionName]&&(h.accept(u[ea.extensionName]),d[ea.extensionName]=h)}catch{ta(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={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(h,(u,f,m,E)=>{if(!u)return PA(r,f||401,m,E);this.completeUpgrade(d,s,l,e,r,i,n)});return}if(!this.options.verifyClient(h))return PA(r,401)}this.completeUpgrade(d,s,l,e,r,i,n)}completeUpgrade(e,r,i,n,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[dne])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>yU)return PA(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ane("sha1").update(r+Ane).digest("base64")}`],A=new this.options.WebSocket(null,void 0,this.options);if(i.size){let d=this.options.handleProtocols?this.options.handleProtocols(i,n):i.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),A._protocol=d)}if(e[ea.extensionName]){let d=e[ea.extensionName].params,h=CU.format({[ea.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${h}`),A._extensions=e}this.emit("headers",l,n),s.write(l.concat(`\r
|
|
71
|
+
`,r:"\r",t:" "}});function qt(t,e){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":Ate(t.message,e):"network error"}function Ate(t,e){let r=t;for(let i of new Set([e,e?.trim()]))i!==void 0&&i.trim().length>0&&(r=r.split(i).join("<redacted>"));return r.replace(/\s+/g," ").trim()}function Us(t,e){for(let r=0;r<t.length;r+=1){let i=t.charCodeAt(r);if(i<32||i===127)throw new Error(`${e} contains a control character (check for a pasted trailing newline) - it cannot be sent as an HTTP header`)}}var Os=D(()=>{"use strict"});var _t,rp=D(()=>{"use strict";_t=class extends Error{status;constructor(e,r){super(e),this.status=r,this.name="TextAdapterError"}}});import{randomUUID as dte}from"node:crypto";function Ete(t){return"toolCalls"in t?{role:"assistant",content:[...t.content.length>0?[{type:"text",text:t.content}]:[],...t.toolCalls.map(e=>({type:"tool_use",id:e.id,name:e.name,input:yte(e.input)}))]}:t.role==="tool"?{role:"user",content:t.results.map(e=>({type:"tool_result",tool_use_id:e.id,content:e.result,...e.isError===!0&&{is_error:!0}}))}:{role:t.role,content:t.content}}function Ite(t){return"toolCalls"in t?[{role:"assistant",content:t.content.length>0?t.content:null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:Cte(e.input)}}))}]:t.role==="tool"?t.results.map(e=>({role:"tool",tool_call_id:e.id,content:e.result})):[{role:t.role,content:t.content}]}function Cte(t){return typeof t=="string"?t:JSON.stringify(t??{})}function yte(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function aF(t,e,r){let i=r.length===0?"{}":r;try{return{type:"tool_call",id:t,name:e,input:JSON.parse(i)}}catch{return{type:"tool_call",id:t,name:e,input:r}}}function cF(t){try{return JSON.parse(t)}catch{return}}function Li(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function oF(t){return Array.isArray(t)?t:void 0}function lF(t){let e=Li(t)?.message;return typeof e=="string"?e:"unknown error"}var Yc,hte,fte,gte,pte,np,mte,IA,Ub,CA,Ob,ip=D(()=>{"use strict";tp();Fb();Os();rp();Yc=3e4,hte=4096,fte="https://api.anthropic.com/v1/messages",gte="2023-06-01",pte="https://api.openai.com/v1/chat/completions",np=class{key;fetchImpl;idleTimeoutMs;constructor(e,r=fetch,i=Yc){this.key=e,this.fetchImpl=r,this.idleTimeoutMs=i,Us(e,"stored text provider key")}async*stream(e){let{url:r,init:i}=this.buildRequest(e),n;try{n=await this.fetchImpl(r,{...i,signal:e.signal})}catch(o){throw e.signal?.aborted===!0&&(o===e.signal.reason||o instanceof Error&&(o.name==="AbortError"||o.name==="TimeoutError"))?o:new _t(qt(o,this.key))}if(!n.ok)throw new _t(`text provider request failed (HTTP ${n.status})`,n.status);if(!n.body)throw new _t("text provider response had no body");let s=this.newTurnDecoder(new Map((e.streamText??[]).map(o=>[o.name,o.field])));for await(let o of ep(n.body,{signal:e.signal,idleTimeoutMs:this.idleTimeoutMs})){if(s.isDone(o))break;for(let a of s.decode(o))yield a}for(let o of s.flush())yield o}},mte="eager_input_streaming",IA=class extends np{buildRequest(e){let r=new Set((e.streamText??[]).map(n=>n.name)),i={model:e.model,max_tokens:hte,stream:!0,messages:e.messages.map(Ete),...e.system!==void 0&&{system:e.system},...e.tools!==void 0&&e.tools.length>0&&{tools:e.tools.map(n=>({name:n.name,description:n.description,input_schema:n.inputSchema,...r.has(n.name)&&{[mte]:!0}}))},...e.toolChoice==="any"&&{tool_choice:{type:"any"}}};return{url:fte,init:{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":gte,"content-type":"application/json"},body:JSON.stringify(i)}}}newTurnDecoder(e){return new Ub(e)}};Ub=class{streamText;tool=null;stopped=!1;constructor(e){this.streamText=e}isDone(){return!1}decode(e){let r=Li(cF(e));if(!r)return[];if(r.type==="error")throw new _t(`anthropic stream error: ${lF(r.error)}`);if(r.type==="message_stop")return this.stopped=!0,[];if(r.type==="content_block_start"){let i=Li(r.content_block);if(i?.type==="tool_use"&&typeof i.id=="string"){let n=typeof i.name=="string"?i.name:"",s=this.streamText.get(n);this.tool={id:i.id,name:n,json:"",text:s!==void 0?new Gc(s):null}}return[]}if(r.type==="content_block_delta"){let i=Li(r.delta);if(i?.type==="text_delta"&&typeof i.text=="string")return[{type:"text",text:i.text}];if(i?.type==="input_json_delta"&&this.tool&&typeof i.partial_json=="string"&&(this.tool.json+=i.partial_json,this.tool.text)){let n=this.tool.text.push(i.partial_json);if(n.length>0)return[{type:"tool_text",id:this.tool.id,name:this.tool.name,text:n}]}return[]}if(r.type==="content_block_stop"&&this.tool){let i=aF(this.tool.id,this.tool.name,this.tool.json);return this.tool=null,[i]}return[]}flush(){if(!this.stopped)throw new _t("anthropic stream ended before message_stop");return[]}},CA=class extends np{buildRequest(e){let r=e.messages.flatMap(Ite),i=e.system!==void 0?[{role:"system",content:e.system},...r]:r,n={model:e.model,stream:!0,messages:i,...e.tools!==void 0&&e.tools.length>0&&{tools:e.tools.map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}}))},...e.toolChoice==="any"&&{tool_choice:"required"}};return{url:pte,init:{method:"POST",headers:{Authorization:`Bearer ${this.key}`,"content-type":"application/json"},body:JSON.stringify(n)}}}newTurnDecoder(){return new Ob}};Ob=class{calls=new Map;done=!1;isDone(e){return e!=="[DONE]"?!1:(this.done=!0,!0)}decode(e){let r=Li(cF(e));if(!r)return[];if(r.error)throw new _t(`openai stream error: ${lF(r.error)}`);let i=oF(r.choices),n=Li(Li(i?.[0])?.delta);if(!n)return[];for(let o of oF(n.tool_calls)??[]){let a=Li(o);if(!a)continue;let c=typeof a.index=="number"?a.index:0,l=this.calls.get(c)??{id:"",name:"",args:""};typeof a.id=="string"&&(l.id=a.id);let A=Li(a.function);typeof A?.name=="string"&&(l.name=A.name),typeof A?.arguments=="string"&&(l.args+=A.arguments),this.calls.set(c,l)}let s=n.content;return typeof s=="string"&&s.length>0?[{type:"text",text:s}]:[]}flush(){if(!this.done)return this.calls.clear(),[];let e=[...this.calls.entries()].sort(([r],[i])=>r-i).map(([r,i])=>aF(i.id.length>0?i.id:`call-${r}-${dte().slice(0,8)}`,i.name,i.args));return this.calls.clear(),e}}});var Fi,$b=D(()=>{"use strict";Fi=class extends Error{status;constructor(e,r){super(e),this.status=r,this.name="SearchAdapterError"}}});function yA(t,e){if(typeof t!="object"||t===null)return[];let r=t,i=r.url;if(typeof i!="string"||i.length===0)return[];let n=r.title,s=r[e];return[{title:typeof n=="string"&&n.length>0?n:i,url:i,...typeof s=="string"&&s.length>0&&{content:s}}]}function BA(t,e=["results"]){let r=t;for(let i of e)r=typeof r=="object"&&r!==null?r[i]:void 0;if(!Array.isArray(r))throw new Fi("search provider returned an unexpected shape");return r}var Bte,xte,Qte,bte,wte,Wo,sp,op,ap,cp,lp,uF=D(()=>{"use strict";Os();$b();Bte="https://ollama.com/api/web_search",xte="https://api.exa.ai/search",Qte="https://api.firecrawl.dev/v2/search",bte="https://api.tavily.com/search",wte="https://api.search.brave.com/res/v1/web/search",Wo=class{key;fetchImpl;constructor(e,r=fetch){this.key=e,this.fetchImpl=r,Us(e,"stored search provider key")}async search(e,r,i){let n=this.request(e,r),s=n.method??"POST",o=n.query===void 0?n.url:`${n.url}?${new URLSearchParams(n.query).toString()}`,a;try{a=await this.fetchImpl(o,{method:s,headers:s==="GET"?n.headers:{"content-type":"application/json",...n.headers},...s==="POST"&&{body:JSON.stringify(n.body)},redirect:"error",signal:i})}catch(l){throw i.aborted?l:new Fi(qt(l,this.key))}if(!a.ok)throw new Fi(`search provider returned ${a.status}`,a.status);let c;try{c=await a.json()}catch{throw new Fi("search provider returned a malformed response")}return this.parse(c).slice(0,r)}};sp=class extends Wo{request(e,r){return{url:Bte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,max_results:r}}}parse(e){return BA(e).flatMap(r=>yA(r,"content"))}},op=class extends Wo{request(e,r){return{url:xte,headers:{"x-api-key":this.key},body:{query:e,numResults:r,contents:{text:!0}}}}parse(e){return BA(e).flatMap(r=>yA(r,"text"))}},ap=class extends Wo{request(e,r){return{url:Qte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,limit:r}}}parse(e){return BA(e,["data","web"]).flatMap(r=>yA(r,"description"))}},cp=class extends Wo{request(e,r){return{url:bte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,max_results:r}}}parse(e){return BA(e).flatMap(r=>yA(r,"content"))}},lp=class extends Wo{request(e,r){return{url:wte,headers:{"x-subscription-token":this.key},method:"GET",query:{q:e,count:String(r)}}}parse(e){return BA(e,["web","results"]).flatMap(r=>yA(r,"description"))}}});function up(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function vte(t){return typeof t=="string"?t:JSON.stringify(t??{})}function Ui(){return new _t("invalid openai response stream")}var Ap,Pb,AF=D(()=>{"use strict";ip();Os();tp();Fb();rp();Ap=class{key;fetchImpl;idleTimeoutMs;continuations=[];constructor(e,r=fetch,i=Yc){this.key=e,this.fetchImpl=r,this.idleTimeoutMs=i,Us(e,"stored text provider key")}async*stream(e){let r=this.renderHistory(e.messages),i=new Pb(new Map((e.streamText??[]).map(n=>[n.name,n.field])));try{e.signal?.throwIfAborted();let n=await this.fetchImpl("https://api.openai.com/v1/responses",{method:"POST",headers:{Authorization:`Bearer ${this.key}`,"content-type":"application/json"},signal:e.signal,body:JSON.stringify({model:e.model,stream:!0,store:!1,input:r,...e.system!==void 0&&{instructions:e.system},...e.tools!==void 0&&e.tools.length>0&&{tools:e.tools.map(o=>({type:"function",name:o.name,description:o.description,parameters:o.inputSchema,strict:!1}))},...e.toolChoice==="any"&&{tool_choice:"required"}})});if(!n.ok)throw new _t(`text provider request failed (HTTP ${n.status})`,n.status);if(!n.body)throw new _t("text provider response had no body");for await(let o of ep(n.body,{signal:e.signal,idleTimeoutMs:this.idleTimeoutMs})){e.signal?.throwIfAborted();for(let a of i.decode(o))yield a;if(i.completed)break}e.signal?.throwIfAborted();let s=i.finish();for(let o of s){e.signal?.throwIfAborted();for(let a of i.speechBefore(o))yield a;e.signal?.throwIfAborted(),yield{type:"tool_call",...o}}e.signal?.throwIfAborted(),s.length>0&&i.reasoning.length>0&&this.continuations.push({calls:structuredClone(s),items:i.continuationItems})}catch(n){throw e.signal?.aborted?e.signal.reason:new _t(qt(n,this.key),n instanceof _t?n.status:void 0)}}renderHistory(e){let r=-1;for(let n=e.length-1;n>=0;n--)if(e[n].role==="user"){r=n;break}let i=new Set(e.slice(r+1).flatMap(n=>"toolCalls"in n?n.toolCalls.map(s=>s.id):[]));return this.continuations=this.continuations.filter(n=>n.calls.some(s=>i.has(s.id))),e.flatMap(n=>{if("toolCalls"in n){let s=this.continuations.filter(a=>a.calls.some(c=>n.toolCalls.some(l=>l.id===c.id))),o=s.flatMap(a=>{if(JSON.stringify(a.calls)!==JSON.stringify(n.toolCalls))throw new _t("openai continuation no longer matches retained calls");return a.items});return[...n.content.length>0?[{role:"assistant",content:n.content}]:[],...s.length>0?o:n.toolCalls.map(a=>({type:"function_call",call_id:a.id,name:a.name,arguments:vte(a.input)}))]}return n.role==="tool"?n.results.map(s=>({type:"function_call_output",call_id:s.id,output:s.result})):[{role:n.role,content:n.content}]})}},Pb=class{streamText;calls=new Map;firstItemId;bufferedSpeech=new Map;output=[];completed=!1;reasoning=[];continuationItems=[];constructor(e){this.streamText=e}decode(e){let r;try{r=up(JSON.parse(e))}catch{}if(!r||typeof r.type!="string")throw Ui();if(["error","response.failed","response.incomplete","response.cancelled"].includes(r.type))throw new _t("openai response did not complete");if(r.type==="response.output_item.added"){let i=up(r.item);if(i?.type==="function_call"){if(typeof i.id!="string"||typeof i.call_id!="string"||typeof i.name!="string"||this.calls.has(i.id))throw Ui();let n=this.streamText.get(i.name);this.firstItemId??=i.id,this.calls.set(i.id,{id:i.call_id,name:i.name,args:"",...n!==void 0&&{text:new Gc(n)}})}}if(r.type==="response.function_call_arguments.delta"){let i=typeof r.item_id=="string"?this.calls.get(r.item_id):void 0;if(!i||typeof r.delta!="string")throw Ui();i.args+=r.delta;let n=i.text?.push(r.delta)??"";return r.item_id!==this.firstItemId?(this.bufferedSpeech.set(i.id,(this.bufferedSpeech.get(i.id)??"")+n),[]):n.length>0?[{type:"tool_text",id:i.id,name:i.name,text:n}]:[]}if(r.type==="response.output_text.delta"){if(typeof r.delta!="string")throw Ui();return r.delta.length>0?[{type:"text",text:r.delta}]:[]}if(r.type==="response.completed"){let i=up(r.response);if(i?.status!=="completed"||!Array.isArray(i.output))throw Ui();this.output=i.output.map(n=>{let s=up(n);if(!s)throw Ui();return s}),this.completed=!0}return[]}finish(){if(!this.completed)throw new _t("openai stream ended before response.completed");let e=[],r=new Set;for(let n of this.output)if(n.type==="reasoning"){if(typeof n.encrypted_content!="string"||n.encrypted_content.length===0)throw new _t("openai response omitted continuation reasoning");this.reasoning.push(n)}else if(n.type==="function_call"){if(typeof n.id!="string"||typeof n.call_id!="string"||typeof n.name!="string"||typeof n.arguments!="string"||n.status!=="completed"||r.has(n.call_id))throw Ui();let s=this.calls.get(n.id);if(s?.id!==n.call_id||s.name!==n.name||s.args.length>0&&s.args!==n.arguments)throw Ui();r.add(n.call_id);let o;try{o=JSON.parse(n.arguments.length===0?"{}":n.arguments)}catch{o=n.arguments}e.push({id:n.call_id,name:n.name,input:o})}let i=[...this.calls.values()];if(e.length!==i.length||e.some((n,s)=>n.id!==i[s].id))throw Ui();return this.continuationItems=this.output.filter(n=>n.type==="reasoning"||n.type==="function_call"),e}speechBefore(e){let r=this.bufferedSpeech.get(e.id)??"";return r.length>0?[{type:"tool_text",id:e.id,name:e.name,text:r}]:[]}}});var qc,Hb=D(()=>{"use strict";qc=class{providers=new Map([["anthropic",{protocol:"anthropic-messages"}],["openai",{protocol:"openai-chat-completions",include:/^(gpt-(4\.1|4o|5)|o\d)/,exclude:/-\d{4}-\d{2}-\d{2}$|-(audio|realtime|transcribe|tts|image|search|codex|chat-latest|instruct|deep-research|pro)\b/,overrides:new Map([["gpt-6-astra",{protocol:"openai-responses",catalogueEligible:!0}],["gpt-5.6-sol",{protocol:"openai-responses",catalogueEligible:!0}],["gpt-5.6-terra",{protocol:"openai-responses",catalogueEligible:!0}],["gpt-5.6-luna",{protocol:"openai-responses",catalogueEligible:!0}],["gpt-5.6",{protocol:"openai-responses",catalogueEligible:!0}]])}]]);catalogueEligible(e,r){let i=this.providers.get(e);if(i===void 0)return!1;let n=i.overrides?.get(r);return n!==void 0?n.catalogueEligible:(i.include?.test(r)??!0)&&!(i.exclude?.test(r)??!1)}protocol(e,r){let i=this.providers.get(e);return i?.overrides?.get(r)?.protocol??i?.protocol}}});var xA,Vb=D(()=>{"use strict";ip();uF();AF();Hb();xA=class{fetchImpl;idleTimeoutMs;brainModels=new qc;constructor(e=fetch,r=Yc){this.fetchImpl=e,this.idleTimeoutMs=r}textAdapter(e,r){switch(this.brainModels.protocol(e.provider,e.model)){case"anthropic-messages":return new IA(r,this.fetchImpl,this.idleTimeoutMs);case"openai-responses":return new Ap(r,this.fetchImpl,this.idleTimeoutMs);case"openai-chat-completions":return new CA(r,this.fetchImpl,this.idleTimeoutMs);default:throw new Error(`no text adapter for provider '${e.provider}'`)}}searchAdapter(e,r){switch(e.provider){case"ollama":return new sp(r,this.fetchImpl);case"exa":return new op(r,this.fetchImpl);case"firecrawl":return new ap(r,this.fetchImpl);case"tavily":return new cp(r,this.fetchImpl);case"brave":return new lp(r,this.fetchImpl);default:throw new Error(`no search adapter for provider '${e.provider}'`)}}}});var vr,dF=D(()=>{"use strict";vr=class extends Error{commandId;reason;constructor(e,r,i){super(i??`send rejected (${r}) for command ${e}`),this.commandId=e,this.reason=r,this.name="SessionSendError"}}});var hF=D(()=>{"use strict"});var QA=D(()=>{"use strict";dF();hF()});function Ste(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Dte(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function dp(t,e,r){if(r.type==="tool.start")t({type:"tool.start",turnId:e,toolId:r.toolId,name:r.tool,summary:r.summary??""});else{let i=[`${r.ok?"ok":"failed"} in ${Ste(r.durationMs)}`];r.bytes!==void 0&&i.push(Dte(r.bytes)),r.results!==void 0&&i.push(`${r.results} result${r.results===1?"":"s"}`),t({type:"tool.result",turnId:e,toolId:r.toolId,ok:r.ok,durationMs:r.durationMs,summary:i.join(" - ")})}}function bA(t,e,r){r.type==="act.start"?t({type:"act.start",turnId:e,actId:r.actId,act:r.act}):t({type:"act.end",turnId:e,actId:r.actId,act:r.act,characters:r.characters})}var Gb=D(()=>{"use strict"});var Oi,wA=D(()=>{"use strict";Oi=class{nextId=1;timers=new Map;now(){return Date.now()}setTimer(e,r){let i=this.nextId++,n=setTimeout(()=>{this.timers.delete(i),r()},e);return this.timers.set(i,n),i}clearTimer(e){let r=this.timers.get(e);r!==void 0&&(clearTimeout(r),this.timers.delete(e))}}});function An(t,e){let r=Math.floor(t.byteLength/2);if(r===0)return!1;let i=new DataView(t.buffer,t.byteOffset,t.byteLength),n=0;for(let s=0;s<r;s++){let o=i.getInt16(s*2,!0)/32768;n+=o*o}return Math.sqrt(n/r)>=e}function _te(t){let e=t.byteLength>>1,r=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let n=0;n<e;n++)i[n]=r.getInt16(n*2,!0);return i}var $s,vA,SA,Jo=D(()=>{"use strict";Nt();$s=.02;vA=class{threshold;constructor(e){this.threshold=e}classify(e,r){r(An(e,this.threshold))}},SA=class{vad;speechThreshold;energyThreshold;log;degraded=!1;announced=!1;disposed=!1;constructor(e,r={}){this.vad=e,this.speechThreshold=r.speechThreshold??.5,this.energyThreshold=r.energyThreshold??$s,this.log=r.log??ie}classify(e,r){if(this.degraded){this.announce("energy (fallback)"),r(An(e,this.energyThreshold));return}this.vad.process(_te(e)).then(i=>{if(!this.disposed){this.announce("silero");for(let n of i)r(n>=this.speechThreshold)}},i=>{this.disposed||(this.degrade(i),this.announce("energy (fallback)"),r(An(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}`))}}});function Yb(t){return new Error(`openai-compat ASR decode failed (HTTP ${t})`)}function qb(t){t.body?.cancel().catch(()=>{})}function Tte(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Lte(t){return t.replace(Mte," ")}function Fte(t){let e;try{e=new URL(t)}catch{throw new Error("openai-compat ASR route url must be a valid http:// or https:// URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`openai-compat ASR route url must use the http:// or https:// scheme (got '${e.protocol}//' - this is an HTTP endpoint, not a WebSocket)`);if(e.username!==""||e.password!=="")throw new Error("openai-compat ASR route url must not embed credentials (user:pass@) - configure the key in secrets instead");return t.replace(/\/+$/,"")}function Ute(t,e){let r=new Uint8Array(e),i=0;for(let n of t)r.set(n,i),i+=n.byteLength;return r}function Ote(t,e){let r=new Uint8Array(44+t.byteLength),i=new DataView(r.buffer);return hp(r,0,"RIFF"),i.setUint32(4,36+t.byteLength,!0),hp(r,8,"WAVE"),hp(r,12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,e,!0),i.setUint32(28,e*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),hp(r,36,"data"),i.setUint32(40,t.byteLength,!0),r.set(t,44),r}function hp(t,e,r){for(let i=0;i<r.length;i+=1)t[e+i]=r.charCodeAt(i)}function pF(t,e=0){if(!(t instanceof Error)||e>3)return"network error";if(t instanceof AggregateError&&t.message.length===0){let r=t.errors.find(i=>i instanceof Error&&i.message.length>0);if(r)return r.message}return t.cause instanceof Error&&(t.message.length===0||t.message==="fetch failed")?pF(t.cause,e+1):t.message.length>0?t.message:t.name.length>0?t.name:"network error"}var zb,Wb,fF,kte,fp,jb,gF,Nte,Rte,Mte,Jb=D(()=>{"use strict";Nt();Os();wA();Jo();zb="http://localhost:8081",Wb="large-v3-turbo",fF=1e3,kte=1e4,fp=class{fetchImpl;model;clock;id="openai-compat";partialStability="redecode";baseUrl;key;negotiation={dialect:null};constructor(e,r=zb,i=Wb,n,s=new Oi){this.fetchImpl=e,this.model=i,this.clock=s,this.baseUrl=Fte(r),this.key=n!==void 0&&n.length>0?n:void 0,this.key!==void 0&&Us(this.key,"openai-compat ASR key")}open(e){return e.biasTerms!==void 0&&e.biasTerms.length>0&&ie.debug("openai-compat ASR: biasTerms are deliberately not mapped on this engine (the whisper initial-prompt hook measured mildly negative in the 0033 E1 bake-off) - proceeding unbiased",{count:e.biasTerms.length}),new jb({fetchImpl:this.fetchImpl,baseUrl:this.baseUrl,model:this.model,key:this.key,negotiation:this.negotiation,clock:this.clock},e)}},jb=class{ctx;opts;aborted=!1;closed=!1;endRequested=!1;buffered=[];bufferedBytes=0;inFlightDecode=null;inFlightAbort=null;speechSinceLastDecode=!1;lastDecodeAtMs=-1/0;lastEmittedPartial=null;transcriptCb;errorCb;endPending=null;constructor(e,r){this.ctx=e,this.opts=r}pushAudio(e){this.aborted||this.closed||this.endRequested||(this.buffered.push(e.slice()),this.bufferedBytes+=e.byteLength,!this.speechSinceLastDecode&&An(e,$s)&&(this.speechSinceLastDecode=!0),this.opts.emitPartials&&this.maybeRedecodeTick())}onTranscript(e){this.transcriptCb=e}onError(e){this.errorCb=e}end(){return this.aborted?Promise.reject(new Error("ASR stream already aborted")):this.closed?Promise.reject(new Error("ASR stream already closed")):this.endPending?Promise.reject(new Error("ASR end() already in progress")):new Promise((e,r)=>{this.endPending={resolve:e,reject:r},this.endRequested=!0,this.runFinalDecode()})}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()}maybeRedecodeTick(){if(this.inFlightDecode!==null||!this.speechSinceLastDecode||this.bufferedBytes<this.opts.sampleRate*2*(fF/1e3))return;let e=this.ctx.clock.now();e-this.lastDecodeAtMs<fF||(this.lastDecodeAtMs=e,this.speechSinceLastDecode=!1,this.inFlightDecode=this.decodeFullBuffer().then(r=>{this.aborted||this.closed||this.endRequested||r!==this.lastEmittedPartial&&(this.lastEmittedPartial=r,this.transcriptCb?.({text:r,isFinal:!1,startMs:0}))}).catch(r=>{ie.debug("openai-compat ASR re-decode tick failed - missed partial",{message:r instanceof Error?r.message:String(r)})}).finally(()=>{this.inFlightDecode=null}))}async runFinalDecode(){if(this.inFlightDecode!==null&&await this.inFlightDecode,this.aborted||this.closed||this.endPending===null)return;if(this.bufferedBytes===0){this.resolveEnd("");return}let e;try{e=await this.decodeFullBuffer()}catch(r){if(this.aborted||this.closed)return;this.failStream(r instanceof Error?r:new Error(String(r)));return}this.aborted||this.closed||this.resolveEnd(e)}resolveEnd(e){if(!this.endPending)return;let r={text:e.trim(),isFinal:!0,startMs:0};this.transcriptCb?.(r);let{resolve:i}=this.endPending;this.endPending=null,this.teardown(),i(r)}failStream(e){if(this.endPending){let{reject:r}=this.endPending;this.endPending=null,r(e)}this.errorCb?.(e),this.teardown()}async decodeFullBuffer(){let e=Ote(Ute(this.buffered,this.bufferedBytes),this.opts.sampleRate),r=new AbortController,i={timedOut:!1};this.inFlightAbort=r;let n=this.ctx.clock.setTimer(this.decodeReplyTimeoutMs(),()=>{i.timedOut=!0,r.abort()});try{let s=await this.postWithNegotiation(e,r.signal),o;try{o=await s.json()}catch{throw new Error("openai-compat ASR decode returned invalid JSON")}let a=Tte(o)&&typeof o.text=="string"?o.text:"";return Lte(a)}catch(s){throw i.timedOut?new Error("openai-compat ASR decode timed out",{cause:s}):s instanceof Error?s:new Error(String(s))}finally{this.ctx.clock.clearTimer(n),this.inFlightAbort===r&&(this.inFlightAbort=null)}}async postWithNegotiation(e,r){let i=this.ctx.negotiation.dialect;if(i!==null){let o=await this.post(i,e,r);if(!o.ok)throw qb(o),Yb(o.status);return o}let n=await this.post("standard",e,r);if(n.ok)return this.ctx.negotiation.dialect="standard",n;if(qb(n),n.status!==404)throw Yb(n.status);let s=await this.post("inference",e,r);if(s.ok)return this.ctx.negotiation.dialect="inference",s;throw qb(s),Yb(s.status)}async post(e,r,i){let n=e==="standard"?`${this.ctx.baseUrl}/v1/audio/transcriptions`:`${this.ctx.baseUrl}/inference`,s=new FormData;s.append("file",new Blob([r],{type:"audio/wav"}),"utterance.wav"),e==="standard"&&s.append("model",this.ctx.model),this.opts.language!==void 0&&s.append("language",this.opts.language),s.append("temperature","0"),s.append("response_format","json");try{return await this.ctx.fetchImpl(n,{method:"POST",body:s,...this.ctx.key!==void 0&&{headers:{Authorization:`Bearer ${this.ctx.key}`}},signal:i})}catch(o){throw i.aborted?new Error("openai-compat ASR request aborted",{cause:o}):new Error(`openai-compat ASR request failed: ${pF(o)}`,{cause:o})}}decodeReplyTimeoutMs(){let e=this.bufferedBytes/2/this.opts.sampleRate*1e3;return kte+Math.ceil(e)}teardown(){this.closed||(this.closed=!0,this.inFlightAbort?.abort(),this.inFlightAbort=null)}};gF=" ",Nte="\r",Rte=`
|
|
72
|
+
`,Mte=new RegExp(`[ ${gF}]*[${Nte}${Rte}]+[ ${gF}]*`,"g")});var dn,DA=D(()=>{"use strict";dn=class extends Error{category;constructor(e,r){super(e),this.category=r,this.name="ASRTerminalError"}}});function Ps(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function _A(t){return typeof t=="string"?t:""}function jc(t){let e=t.message_type;return typeof e=="string"&&($te.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function mF(t){return Buffer.from(t).toString("base64")}function gp(t){return new Uint8Array(Buffer.from(t,"base64"))}function kA(t,e){return new Error(`${t} connection error: ${e.message}`)}function EF(t){return Pte[t]??null}function IF(t,e){if(e instanceof dn)return new dn(`${t} connection error: ${e.message}`,e.category);let r=Hte.exec(e.message)?.[1];return r!==void 0?new dn(`${t} connection error: rejected credential (HTTP ${r})`,"auth"):kA(t,e)}var $te,Pte,Hte,TA=D(()=>{"use strict";DA();$te=new Set(["error","auth_error","quota_exceeded","rate_limited"]);Pte={quota_exceeded:"quota",auth_error:"auth"};Hte=/^Unexpected server response: (401|403)\b/});function BF(t,e){let r=new Uint8Array(e),i=0;for(let n of t)r.set(n,i),i+=n.byteLength;return r}function Gte(t){if(t.message.length>0)return t.message;if(t instanceof AggregateError){let e=t.errors.find(r=>r instanceof Error&&r.message.length>0);if(e)return e.message}return t.name.length>0?t.name:"connection failed"}function Yte(t){let e=Math.floor(t.byteLength/2),r=new DataView(t.buffer,t.byteOffset,e*2),i=new Float32Array(e);for(let n=0;n<e;n+=1)i[n]=r.getInt16(n*2,!0)/32768;return i}var pp,CF,yF,Vte,NA,Zb,mp=D(()=>{"use strict";Nt();wA();Jo();TA();pp="ws://localhost:6007",CF=1e3,yF=10240,Vte=1e4,NA=class{socketFactory;url;clock;id="sherpa-onnx";partialStability="redecode";constructor(e,r=pp,i=new Oi){this.socketFactory=e,this.url=r,this.clock=i}open(e){return e.biasTerms!==void 0&&e.biasTerms.length>0&&ie.debug("sherpa ASR: biasTerms are not mappable on this engine (the TDT export ships no hotword vocab; watch k2-fsa/sherpa-onnx#3573) - proceeding unbiased",{count:e.biasTerms.length}),new Zb(this.socketFactory,this.url,this.clock,e)}},Zb=class{clock;opts;socket;opened=!1;aborted=!1;closed=!1;endRequested=!1;buffered=[];bufferedBytes=0;inFlightDecode=null;speechSinceLastDecode=!1;pendingReply=null;staleReplies=0;lastDecodeAtMs=-1/0;lastEmittedPartial=null;transcriptCb;errorCb;endPending=null;constructor(e,r,i,n){this.clock=i,this.opts=n,this.socket=e(r,{}),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){this.aborted||this.closed||this.endRequested||(this.buffered.push(e.slice()),this.bufferedBytes+=e.byteLength,!this.speechSinceLastDecode&&An(e,$s)&&(this.speechSinceLastDecode=!0),this.opened&&this.opts.emitPartials&&this.maybeRedecodeTick())}onTranscript(e){this.transcriptCb=e}onError(e){this.errorCb=e}end(){return this.aborted?Promise.reject(new Error("ASR stream already aborted")):this.closed?Promise.reject(new Error("ASR stream already closed")):this.endPending?Promise.reject(new Error("ASR end() already in progress")):new Promise((e,r)=>{this.endPending={resolve:e,reject:r},this.endRequested=!0,this.opened&&this.runFinalDecode()})}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(){this.aborted||this.closed||(this.opened=!0,this.endRequested&&this.runFinalDecode())}handleMessage(e){if(this.aborted||this.closed)return;let r=Ps(e);if(r){if(this.staleReplies>0){this.staleReplies-=1;return}if(this.pendingReply){let{resolve:i,timer:n}=this.pendingReply;this.pendingReply=null,this.clock.clearTimer(n),i(_A(r.text))}}}handleError(e){if(this.closed)return;let r=kA("sherpa ASR",new Error(Gte(e)));this.failStream(r)}handleClose(){this.closed||(this.closed=!0,this.settleFailure(new Error("sherpa ASR connection closed unexpectedly")))}failStream(e){this.settleFailure(e),this.teardown()}settleFailure(e){if(this.endPending){let{reject:r}=this.endPending;this.endPending=null,r(e)}this.rejectPendingReply(e),this.errorCb?.(e)}rejectPendingReply(e){if(!this.pendingReply)return;let{reject:r,timer:i}=this.pendingReply;this.pendingReply=null,this.clock.clearTimer(i),r(e)}maybeRedecodeTick(){if(this.inFlightDecode!==null||!this.speechSinceLastDecode||this.bufferedBytes<this.opts.sampleRate*2*(CF/1e3))return;let e=this.clock.now();e-this.lastDecodeAtMs<CF||(this.lastDecodeAtMs=e,this.speechSinceLastDecode=!1,this.inFlightDecode=this.decodeFullBuffer().then(r=>{this.aborted||this.closed||this.endRequested||r!==this.lastEmittedPartial&&(this.lastEmittedPartial=r,this.transcriptCb?.({text:r,isFinal:!1,startMs:0}))}).catch(()=>{}).finally(()=>{this.inFlightDecode=null}))}async runFinalDecode(){if(this.inFlightDecode!==null&&await this.inFlightDecode,this.aborted||this.closed||this.endPending===null)return;if(this.bufferedBytes===0){this.resolveEnd("");return}let e;try{e=await this.decodeFullBuffer()}catch(r){if(this.aborted||this.closed)return;this.failStream(r instanceof Error?r:new Error(String(r)));return}this.aborted||this.closed||this.resolveEnd(e)}resolveEnd(e){if(!this.endPending)return;let r={text:e.trim(),isFinal:!0,startMs:0};this.transcriptCb?.(r);let{resolve:i}=this.endPending;this.endPending=null,this.socket.send("Done"),this.teardown(),i(r)}decodeFullBuffer(){let e=Yte(BF(this.buffered,this.bufferedBytes)),r=new Uint8Array(e.buffer,0,e.byteLength),i=new Uint8Array(8),n=new DataView(i.buffer);n.setUint32(0,this.opts.sampleRate,!0),n.setUint32(4,r.byteLength,!0);let s=BF([i,r],i.byteLength+r.byteLength),o=new Promise((a,c)=>{let l=this.clock.setTimer(this.decodeReplyTimeoutMs(),()=>{this.pendingReply&&(this.pendingReply=null,this.staleReplies+=1,c(new Error("sherpa ASR decode timed out")))});this.pendingReply={resolve:a,reject:c,timer:l}});try{for(let a=0;a<s.byteLength;a+=yF)this.socket.send(s.subarray(a,Math.min(a+yF,s.byteLength)))}catch(a){this.rejectPendingReply(a instanceof Error?a:new Error(String(a)))}return o}decodeReplyTimeoutMs(){let e=this.bufferedBytes/2/this.opts.sampleRate*1e3;return Vte+Math.ceil(e)}teardown(){this.closed||(this.closed=!0,this.rejectPendingReply(new Error("sherpa ASR stream closed")),this.socket.close())}}});var xF,Ep,qte,jte,zte,RA,Xb,Ip=D(()=>{"use strict";TA();xF="wss://api.elevenlabs.io/v1/text-to-dialogue/stream-input",Ep=["eleven_v3","eleven_v3_conversational"],qte=1e4,jte=1e4,zte=6e4,RA=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-v3";constructor(e,r,i,n=xF){this.apiKey=e,this.socketFactory=r,this.model=i,this.endpoint=n}speak(e){let r=e.voice.engineVoice[this.id];if(!r)throw new Error(`voice '${e.voice.id}' has no '${this.id}' engineVoice mapping`);if(r.kind!=="preset")throw new Error(`the ${this.id} adapter needs a preset voiceId for '${e.voice.id}'`);if(e.encoding!=="pcm_s16le")throw new Error("ElevenLabs v3 TTS requires pcm_s16le audio");let i=new URL(this.endpoint);return i.searchParams.set("model_id",this.model),i.searchParams.set("output_format",`pcm_${e.sampleRate}`),new Xb(this.apiKey,this.socketFactory,i.toString(),r.voiceId)}},Xb=class{voiceId;socket;state="active";opened=!1;closeRequested=!1;pending=[];failure;audioCb;errorCb;endPending=null;handshakeTimer;keepAliveTimer;finalTimer;constructor(e,r,i,n){this.voiceId=n;try{this.socket=r(i,{"xi-api-key":e})}catch{throw new Error("ElevenLabs v3 TTS connection error")}this.handshakeTimer=setTimeout(()=>this.fail(new Error("ElevenLabs v3 TTS connection timed out")),qte),this.handshakeTimer.unref(),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(s=>this.handleMessage(s)),this.socket.onError(()=>this.fail(new Error("ElevenLabs v3 TTS connection error"))),this.socket.onClose(()=>this.fail(new Error("ElevenLabs v3 TTS connection closed unexpectedly")))}pushText(e){if(!(this.state!=="active"||e.trim().length===0)){if(!this.opened){this.pending.push(e);return}this.sendText(e)}}onAudio(e){this.audioCb=e}onError(e){this.errorCb=e,this.failure&&e(this.failure)}end(){return this.failure?Promise.reject(this.failure):this.terminal()?Promise.resolve():this.endPending?Promise.reject(new Error("TTS end() already in progress")):new Promise((e,r)=>{this.endPending={resolve:e,reject:r},this.state="ending",this.opened&&this.sendEnd()})}cancel(){if(this.terminal())return Promise.resolve();this.state="cancelled";let e=this.endPending;return this.endPending=null,this.teardown(),e?.resolve(),Promise.resolve()}handleOpen(){if(!(this.terminal()||this.opened)&&(this.opened=!0,clearTimeout(this.handshakeTimer),this.handshakeTimer=void 0,!!this.send({voices:[this.voiceId],voice_settings:{stability:.5}}))){this.state==="active"&&(this.keepAliveTimer=setInterval(()=>this.send({keep_alive:!0}),jte),this.keepAliveTimer.unref());for(let e of this.pending.splice(0))if(!this.sendText(e))return;this.state==="ending"&&this.sendEnd()}}sendText(e){let r=e.endsWith(" ")?e:`${e} `;return this.send({inputs:[{text:r,voice_id:this.voiceId}],flush:!0})}sendEnd(){this.terminal()||this.closeRequested||(this.closeRequested=!0,clearInterval(this.keepAliveTimer),this.keepAliveTimer=void 0,this.refreshFinalDeadline(),this.send({close_socket:!0}))}refreshFinalDeadline(){clearTimeout(this.finalTimer),this.finalTimer=setTimeout(()=>this.fail(new Error("ElevenLabs v3 TTS final audio timed out")),zte),this.finalTimer.unref()}handleMessage(e){if(this.terminal()||!this.opened)return;let r=Ps(e);if(r){if(typeof r.error=="string"||jc(r)!==null){this.fail(new Error("ElevenLabs v3 TTS stream error"));return}if(typeof r.audio=="string"&&r.audio.length>0){let i=gp(r.audio);i.byteLength>0&&(this.closeRequested&&this.refreshFinalDeadline(),this.audioCb?.(i))}if(!this.terminal()&&r.is_final===!0){if(this.state!=="ending"||!this.closeRequested){this.fail(new Error("ElevenLabs v3 TTS stream ended unexpectedly"));return}this.state="complete";let i=this.endPending;this.endPending=null,this.teardown(),i?.resolve()}}}send(e){if(this.terminal())return!1;try{return this.socket.send(JSON.stringify(e)),!this.terminal()}catch{return this.fail(new Error("ElevenLabs v3 TTS failed to send")),!1}}fail(e){if(this.terminal())return;this.failure=e,this.state="failed";let r=this.endPending;this.endPending=null,this.teardown(),r?.reject(e),this.errorCb?.(e)}terminal(){return this.state==="complete"||this.state==="cancelled"||this.state==="failed"}teardown(){this.pending.length=0,clearTimeout(this.handshakeTimer),clearInterval(this.keepAliveTimer),clearTimeout(this.finalTimer),this.handshakeTimer=void 0,this.keepAliveTimer=void 0,this.finalTimer=void 0;try{this.socket.close()}catch{}}}});var $i=Q((bRe,wF)=>{"use strict";var QF=["nodebuffer","arraybuffer","fragments"],bF=typeof Blob<"u";bF&&QF.push("blob");wF.exports={BINARY_TYPES:QF,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bF,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var MA=Q((wRe,Cp)=>{"use strict";var{EMPTY_BUFFER:Wte}=$i(),Kb=Buffer[Symbol.species];function Jte(t,e){if(t.length===0)return Wte;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let n=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return i<e?new Kb(r.buffer,r.byteOffset,i):r}function vF(t,e,r,i,n){for(let s=0;s<n;s++)r[i+s]=t[s]^e[s&3]}function SF(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Zte(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ew(t){if(ew.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Kb(t):ArrayBuffer.isView(t)?e=new Kb(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ew.readOnly=!1),e}Cp.exports={concat:Jte,mask:vF,toArrayBuffer:Zte,toBuffer:ew,unmask:SF};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=R("bufferutil");Cp.exports.mask=function(e,r,i,n,s){s<48?vF(e,r,i,n,s):t.mask(e,r,i,n,s)},Cp.exports.unmask=function(e,r){e.length<32?SF(e,r):t.unmask(e,r)}}catch{}});var kF=Q((vRe,_F)=>{"use strict";var DF=Symbol("kDone"),tw=Symbol("kRun"),rw=class{constructor(e){this[DF]=()=>{this.pending--,this[tw]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[tw]()}[tw](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[DF])}}};_F.exports=rw});var Jc=Q((SRe,MF)=>{"use strict";var LA=R("zlib"),TF=MA(),Xte=kF(),{kStatusCode:NF}=$i(),Kte=Buffer[Symbol.species],ere=Buffer.from([0,0,255,255]),Bp=Symbol("permessage-deflate"),Pi=Symbol("total-length"),zc=Symbol("callback"),Hs=Symbol("buffers"),Wc=Symbol("error"),yp,nw=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,!yp){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;yp=new Xte(r)}}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[zc];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let n=r[i];if(n.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(n=n[0],i==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else if(i==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=n})}),e}decompress(e,r,i){yp.add(n=>{this._decompress(e,r,(s,o)=>{n(),i(s,o)})})}compress(e,r,i){yp.add(n=>{this._compress(e,r,(s,o)=>{n(),i(s,o)})})}_decompress(e,r,i){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,o=typeof this.params[s]!="number"?LA.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=LA.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Bp]=this,this._inflate[Pi]=0,this._inflate[Hs]=[],this._inflate.on("error",rre),this._inflate.on("data",RF)}this._inflate[zc]=i,this._inflate.write(e),r&&this._inflate.write(ere),this._inflate.flush(()=>{let s=this._inflate[Wc];if(s){this._inflate.close(),this._inflate=null,i(s);return}let o=TF.concat(this._inflate[Hs],this._inflate[Pi]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Pi]=0,this._inflate[Hs]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),i(null,o)})}_compress(e,r,i){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,o=typeof this.params[s]!="number"?LA.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=LA.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Pi]=0,this._deflate[Hs]=[],this._deflate.on("data",tre)}this._deflate[zc]=i,this._deflate.write(e),this._deflate.flush(LA.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=TF.concat(this._deflate[Hs],this._deflate[Pi]);r&&(s=new Kte(s.buffer,s.byteOffset,s.length-4)),this._deflate[zc]=null,this._deflate[Pi]=0,this._deflate[Hs]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,s)})}};MF.exports=nw;function tre(t){this[Hs].push(t),this[Pi]+=t.length}function RF(t){if(this[Pi]+=t.length,this[Bp]._maxPayload<1||this[Pi]<=this[Bp]._maxPayload){this[Hs].push(t);return}this[Wc]=new RangeError("Max payload size exceeded"),this[Wc].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Wc][NF]=1009,this.removeListener("data",RF),this.reset()}function rre(t){if(this[Bp]._inflate=null,this[Wc]){this[zc](this[Wc]);return}t[NF]=1007,this[zc](t)}});var Zc=Q((DRe,xp)=>{"use strict";var{isUtf8:LF}=R("buffer"),{hasBlob:nre}=$i(),ire=[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 sre(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function iw(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function ore(t){return nre&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}xp.exports={isBlob:ore,isValidStatusCode:sre,isValidUTF8:iw,tokenChars:ire};if(LF)xp.exports.isValidUTF8=function(t){return t.length<24?iw(t):LF(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=R("utf-8-validate");xp.exports.isValidUTF8=function(e){return e.length<32?iw(e):t(e)}}catch{}});var lw=Q((_Re,VF)=>{"use strict";var{Writable:are}=R("stream"),FF=Jc(),{BINARY_TYPES:cre,EMPTY_BUFFER:UF,kStatusCode:lre,kWebSocket:ure}=$i(),{concat:sw,toArrayBuffer:Are,unmask:dre}=MA(),{isValidStatusCode:hre,isValidUTF8:OF}=Zc(),Qp=Buffer[Symbol.species],hn=0,$F=1,PF=2,HF=3,ow=4,aw=5,bp=6,cw=class extends are{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||cre[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[ure]=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=hn}_write(e,r,i){if(this._opcode===8&&this._state==hn)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 Qp(i.buffer,i.byteOffset+e,i.length-e),new Qp(i.buffer,i.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let i=this._buffers[0],n=r.length-e;e>=i.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),n),this._buffers[0]=new Qp(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case hn:this.getInfo(e);break;case $F:this.getPayloadLength16(e);break;case PF:this.getPayloadLength64(e);break;case HF:this.getMask();break;case ow:this.getData(e);break;case aw:case bp:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let i=(r[0]&64)===64;if(i&&!this._extensions[FF.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=$F:this._payloadLength===127?this._state=PF: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 r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=i*Math.pow(2,32)+r.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 r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=HF:this._state=ow}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ow}getData(e){let r=UF;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&dre(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=aw,this.decompress(r,e);return}if(r.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(r)}this.dataMessage(e)}decompress(e,r){this._extensions[FF.extensionName].decompress(e,this._fin,(n,s)=>{if(n)return r(n);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(o);return}this._fragments.push(s)}this.dataMessage(r),this._state===hn&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=hn;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=sw(i,r):this._binaryType==="arraybuffer"?n=Are(sw(i,r)):this._binaryType==="blob"?n=new Blob(i):n=i,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=hn):(this._state=bp,setImmediate(()=>{this.emit("message",n,!0),this._state=hn,this.startLoop(e)}))}else{let n=sw(i,r);if(!this._skipUTF8Validation&&!OF(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===aw||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=hn):(this._state=bp,setImmediate(()=>{this.emit("message",n,!1),this._state=hn,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,UF),this.end();else{let i=e.readUInt16BE(0);if(!hre(i)){let s=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let n=new Qp(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!OF(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",i,n),this.end()}this._state=hn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=hn):(this._state=bp,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=hn,this.startLoop(r)}))}createError(e,r,i,n,s){this._loop=!1,this._errored=!0;let o=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=s,o[lre]=n,o}};VF.exports=cw});var dw=Q((TRe,qF)=>{"use strict";var{Duplex:kRe}=R("stream"),{randomFillSync:fre}=R("crypto"),{types:{isUint8Array:gre}}=R("util"),GF=Jc(),{EMPTY_BUFFER:pre,kWebSocket:mre,NOOP:Ere}=$i(),{isBlob:Xc,isValidStatusCode:Ire}=Zc(),{mask:YF,toBuffer:Zo}=MA(),fn=Symbol("kByteLength"),Cre=Buffer.alloc(4),wp=8*1024,Xo,Kc=wp,Ln=0,yre=1,Bre=2,uw=class t{constructor(e,r,i){this._extensions=r||{},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=Ln,this.onerror=Ere,this[mre]=void 0}static frame(e,r){let i,n=!1,s=2,o=!1;r.mask&&(i=r.maskBuffer||Cre,r.generateMask?r.generateMask(i):(Kc===wp&&(Xo===void 0&&(Xo=Buffer.alloc(wp)),fre(Xo,0,wp),Kc=0),i[0]=Xo[Kc++],i[1]=Xo[Kc++],i[2]=Xo[Kc++],i[3]=Xo[Kc++]),o=(i[0]|i[1]|i[2]|i[3])===0,s=6);let a;typeof e=="string"?(!r.mask||o)&&r[fn]!==void 0?a=r[fn]:(e=Buffer.from(e),a=e.length):(a=e.length,n=r.mask&&r.readOnly&&!o);let c=a;a>=65536?(s+=8,c=127):a>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(n?a+s:s);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[s-4]=i[0],l[s-3]=i[1],l[s-2]=i[2],l[s-1]=i[3],o?[l,e]:n?(YF(e,i,l,s,a),[l]):(YF(e,i,e,0,a),[l,e])):[l,e]}close(e,r,i,n){let s;if(e===void 0)s=pre;else{if(typeof e!="number"||!Ire(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof r=="string")s.write(r,2);else if(gre(r))s.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[fn]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ln?this.enqueue([this.dispatch,s,!1,o,n]):this.sendFrame(t.frame(s,o),n)}ping(e,r,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):Xc(e)?(n=e.size,s=!1):(e=Zo(e),n=e.length,s=Zo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[fn]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Xc(e)?this._state!==Ln?this.enqueue([this.getBlobData,e,!1,o,i]):this.getBlobData(e,!1,o,i):this._state!==Ln?this.enqueue([this.dispatch,e,!1,o,i]):this.sendFrame(t.frame(e,o),i)}pong(e,r,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):Xc(e)?(n=e.size,s=!1):(e=Zo(e),n=e.length,s=Zo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[fn]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Xc(e)?this._state!==Ln?this.enqueue([this.getBlobData,e,!1,o,i]):this.getBlobData(e,!1,o,i):this._state!==Ln?this.enqueue([this.dispatch,e,!1,o,i]):this.sendFrame(t.frame(e,o),i)}send(e,r,i){let n=this._extensions[GF.extensionName],s=r.binary?2:1,o=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Xc(e)?(a=e.size,c=!1):(e=Zo(e),a=e.length,c=Zo.readOnly),this._firstFragment?(this._firstFragment=!1,o&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=n._threshold),this._compress=o):(o=!1,s=0),r.fin&&(this._firstFragment=!0);let l={[fn]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};Xc(e)?this._state!==Ln?this.enqueue([this.getBlobData,e,this._compress,l,i]):this.getBlobData(e,this._compress,l,i):this._state!==Ln?this.enqueue([this.dispatch,e,this._compress,l,i]):this.dispatch(e,this._compress,l,i)}getBlobData(e,r,i,n){this._bufferedBytes+=i[fn],this._state=Bre,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Aw,this,a,n);return}this._bufferedBytes-=i[fn];let o=Zo(s);r?this.dispatch(o,r,i,n):(this._state=Ln,this.sendFrame(t.frame(o,i),n),this.dequeue())}).catch(s=>{process.nextTick(xre,this,s,n)})}dispatch(e,r,i,n){if(!r){this.sendFrame(t.frame(e,i),n);return}let s=this._extensions[GF.extensionName];this._bufferedBytes+=i[fn],this._state=yre,s.compress(e,i.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Aw(this,c,n);return}this._bufferedBytes-=i[fn],this._state=Ln,i.readOnly=!1,this.sendFrame(t.frame(a,i),n),this.dequeue()})}dequeue(){for(;this._state===Ln&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][fn],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][fn],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};qF.exports=uw;function Aw(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let n=t._queue[i],s=n[n.length-1];typeof s=="function"&&s(e)}}function xre(t,e,r){Aw(t,e,r),t.onerror(e)}});var tU=Q((NRe,eU)=>{"use strict";var{kForOnEventAttribute:FA,kListener:hw}=$i(),jF=Symbol("kCode"),zF=Symbol("kData"),WF=Symbol("kError"),JF=Symbol("kMessage"),ZF=Symbol("kReason"),el=Symbol("kTarget"),XF=Symbol("kType"),KF=Symbol("kWasClean"),Hi=class{constructor(e){this[el]=null,this[XF]=e}get target(){return this[el]}get type(){return this[XF]}};Object.defineProperty(Hi.prototype,"target",{enumerable:!0});Object.defineProperty(Hi.prototype,"type",{enumerable:!0});var Ko=class extends Hi{constructor(e,r={}){super(e),this[jF]=r.code===void 0?0:r.code,this[ZF]=r.reason===void 0?"":r.reason,this[KF]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[jF]}get reason(){return this[ZF]}get wasClean(){return this[KF]}};Object.defineProperty(Ko.prototype,"code",{enumerable:!0});Object.defineProperty(Ko.prototype,"reason",{enumerable:!0});Object.defineProperty(Ko.prototype,"wasClean",{enumerable:!0});var tl=class extends Hi{constructor(e,r={}){super(e),this[WF]=r.error===void 0?null:r.error,this[JF]=r.message===void 0?"":r.message}get error(){return this[WF]}get message(){return this[JF]}};Object.defineProperty(tl.prototype,"error",{enumerable:!0});Object.defineProperty(tl.prototype,"message",{enumerable:!0});var UA=class extends Hi{constructor(e,r={}){super(e),this[zF]=r.data===void 0?null:r.data}get data(){return this[zF]}};Object.defineProperty(UA.prototype,"data",{enumerable:!0});var Qre={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[FA]&&n[hw]===e&&!n[FA])return;let i;if(t==="message")i=function(s,o){let a=new UA("message",{data:o?s:s.toString()});a[el]=this,vp(e,this,a)};else if(t==="close")i=function(s,o){let a=new Ko("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[el]=this,vp(e,this,a)};else if(t==="error")i=function(s){let o=new tl("error",{error:s,message:s.message});o[el]=this,vp(e,this,o)};else if(t==="open")i=function(){let s=new Hi("open");s[el]=this,vp(e,this,s)};else return;i[FA]=!!r[FA],i[hw]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[hw]===e&&!r[FA]){this.removeListener(t,r);break}}};eU.exports={CloseEvent:Ko,ErrorEvent:tl,Event:Hi,EventTarget:Qre,MessageEvent:UA};function vp(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Sp=Q((RRe,rU)=>{"use strict";var{tokenChars:OA}=Zc();function oi(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function bre(t){let e=Object.create(null),r=Object.create(null),i=!1,n=!1,s=!1,o,a,c=-1,l=-1,A=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),o===void 0)if(A===-1&&OA[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))A===-1&&c!==-1&&(A=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);A===-1&&(A=d);let u=t.slice(c,A);l===44?(oi(e,u,r),r=Object.create(null)):o=u,c=A=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(A===-1&&OA[l]===1)c===-1&&(c=d);else if(l===32||l===9)A===-1&&c!==-1&&(A=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);A===-1&&(A=d),oi(r,t.slice(c,A),!0),l===44&&(oi(e,o,r),r=Object.create(null),o=void 0),c=A=-1}else if(l===61&&c!==-1&&A===-1)a=t.slice(c,d),c=A=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(n){if(OA[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:i||(i=!0),n=!1}else if(s)if(OA[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)s=!1,A=d;else if(l===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)s=!0;else if(A===-1&&OA[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))A===-1&&(A=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);A===-1&&(A=d);let u=t.slice(c,A);i&&(u=u.replace(/\\/g,""),i=!1),oi(r,a,u),l===44&&(oi(e,o,r),r=Object.create(null),o=void 0),a=void 0,c=A=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");A===-1&&(A=d);let h=t.slice(c,A);return o===void 0?oi(e,h,r):(a===void 0?oi(r,h,!0):i?oi(r,a,h.replace(/\\/g,"")):oi(r,a,h),oi(e,o,r)),e}function wre(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(n=>{let s=i[n];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?n:`${n}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}rU.exports={format:wre,parse:bre}});var Tp=Q((FRe,fU)=>{"use strict";var vre=R("events"),Sre=R("https"),Dre=R("http"),sU=R("net"),_re=R("tls"),{randomBytes:kre,createHash:Tre}=R("crypto"),{Duplex:MRe,Readable:LRe}=R("stream"),{URL:fw}=R("url"),Vs=Jc(),Nre=lw(),Rre=dw(),{isBlob:Mre}=Zc(),{BINARY_TYPES:nU,CLOSE_TIMEOUT:Lre,EMPTY_BUFFER:Dp,GUID:Fre,kForOnEventAttribute:gw,kListener:Ure,kStatusCode:Ore,kWebSocket:Lt,NOOP:oU}=$i(),{EventTarget:{addEventListener:$re,removeEventListener:Pre}}=tU(),{format:Hre,parse:Vre}=Sp(),{toBuffer:Gre}=MA(),aU=Symbol("kAborted"),pw=[8,13],Vi=["CONNECTING","OPEN","CLOSING","CLOSED"],Yre=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,At=class t extends vre{constructor(e,r,i){super(),this._binaryType=nU[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Dp,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,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),cU(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){nU.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,r,i){let n=new Nre({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),s=new Rre(e,this._extensions,i.generateMask);this._receiver=n,this._sender=s,this._socket=e,n[Lt]=this,s[Lt]=this,e[Lt]=this,n.on("conclude",zre),n.on("drain",Wre),n.on("error",Jre),n.on("message",Zre),n.on("ping",Xre),n.on("pong",Kre),s.onerror=ene,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",AU),e.on("data",kp),e.on("end",dU),e.on("error",hU),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[Vs.extensionName]&&this._extensions[Vs.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Vr(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,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),uU(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){mw(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Dp,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){mw(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Dp,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){mw(this,e,i);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Vs.extensionName]||(n.compress=!1),this._sender.send(e||Dp,n,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Vr(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(At,"CONNECTING",{enumerable:!0,value:Vi.indexOf("CONNECTING")});Object.defineProperty(At.prototype,"CONNECTING",{enumerable:!0,value:Vi.indexOf("CONNECTING")});Object.defineProperty(At,"OPEN",{enumerable:!0,value:Vi.indexOf("OPEN")});Object.defineProperty(At.prototype,"OPEN",{enumerable:!0,value:Vi.indexOf("OPEN")});Object.defineProperty(At,"CLOSING",{enumerable:!0,value:Vi.indexOf("CLOSING")});Object.defineProperty(At.prototype,"CLOSING",{enumerable:!0,value:Vi.indexOf("CLOSING")});Object.defineProperty(At,"CLOSED",{enumerable:!0,value:Vi.indexOf("CLOSED")});Object.defineProperty(At.prototype,"CLOSED",{enumerable:!0,value:Vi.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(At.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(At.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[gw])return e[Ure];return null},set(e){for(let r of this.listeners(t))if(r[gw]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[gw]:!0})}})});At.prototype.addEventListener=$re;At.prototype.removeEventListener=Pre;fU.exports=At;function cU(t,e,r,i){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Lre,protocolVersion:pw[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=n.autoPong,t._closeTimeout=n.closeTimeout,!pw.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${pw.join(", ")})`);let s;if(e instanceof fw)s=e;else try{s=new fw(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;_p(t,m);return}let l=o?443:80,A=kre(16).toString("base64"),d=o?Sre.request:Dre.request,h=new Set,u;if(n.createConnection=n.createConnection||(o?jre:qre),n.defaultPort=n.defaultPort||l,n.port=s.port||l,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":A,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(u=new Vs({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=Hre({[Vs.extensionName]:u.offer()})),r.length){for(let m of r){if(typeof m!="string"||!Yre.test(m)||h.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(m)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),a){let m=n.path.split(":");n.socketPath=m[0],n.path=m[1]}let f;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?n.socketPath:s.host;let m=i&&i.headers;if(i={...i,headers:{}},m)for(let[E,I]of Object.entries(m))i.headers[E.toLowerCase()]=I}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,m||delete n.headers.host,n.auth=void 0)}n.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),f=t._req=d(n),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(n);n.timeout&&f.on("timeout",()=>{Vr(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[aU]||(f=t._req=null,_p(t,m))}),f.on("response",m=>{let E=m.headers.location,I=m.statusCode;if(E&&n.followRedirects&&I>=300&&I<400){if(++t._redirects>n.maxRedirects){Vr(t,f,"Maximum redirects exceeded");return}f.abort();let C;try{C=new fw(E,e)}catch{let v=new SyntaxError(`Invalid URL: ${E}`);_p(t,v);return}cU(t,C,r,i)}else t.emit("unexpected-response",f,m)||Vr(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,E,I)=>{if(t.emit("upgrade",m),t.readyState!==At.CONNECTING)return;f=t._req=null;let C=m.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){Vr(t,E,"Invalid Upgrade header");return}let b=Tre("sha1").update(A+Fre).digest("base64");if(m.headers["sec-websocket-accept"]!==b){Vr(t,E,"Invalid Sec-WebSocket-Accept header");return}let v=m.headers["sec-websocket-protocol"],S;if(v!==void 0?h.size?h.has(v)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":h.size&&(S="Server sent no subprotocol"),S){Vr(t,E,S);return}v&&(t._protocol=v);let O=m.headers["sec-websocket-extensions"];if(O!==void 0){if(!u){Vr(t,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Vre(O)}catch{Vr(t,E,"Invalid Sec-WebSocket-Extensions header");return}let M=Object.keys(U);if(M.length!==1||M[0]!==Vs.extensionName){Vr(t,E,"Server indicated an extension that was not requested");return}try{u.accept(U[Vs.extensionName])}catch{Vr(t,E,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Vs.extensionName]=u}t.setSocket(E,I,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(f,t):f.end()}function _p(t,e){t._readyState=At.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function qre(t){return t.path=t.socketPath,sU.connect(t)}function jre(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=sU.isIP(t.host)?"":t.host),_re.connect(t)}function Vr(t,e,r){t._readyState=At.CLOSING;let i=new Error(r);Error.captureStackTrace(i,Vr),e.setHeader?(e[aU]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_p,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function mw(t,e,r){if(e){let i=Mre(e)?e.size:Gre(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Vi[t.readyState]})`);process.nextTick(r,i)}}function zre(t,e){let r=this[Lt];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Lt]!==void 0&&(r._socket.removeListener("data",kp),process.nextTick(lU,r._socket),t===1005?r.close():r.close(t,e))}function Wre(){let t=this[Lt];t.isPaused||t._socket.resume()}function Jre(t){let e=this[Lt];e._socket[Lt]!==void 0&&(e._socket.removeListener("data",kp),process.nextTick(lU,e._socket),e.close(t[Ore])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function iU(){this[Lt].emitClose()}function Zre(t,e){this[Lt].emit("message",t,e)}function Xre(t){let e=this[Lt];e._autoPong&&e.pong(t,!this._isServer,oU),e.emit("ping",t)}function Kre(t){this[Lt].emit("pong",t)}function lU(t){t.resume()}function ene(t){let e=this[Lt];e.readyState!==At.CLOSED&&(e.readyState===At.OPEN&&(e._readyState=At.CLOSING,uU(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function uU(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function AU(){let t=this[Lt];if(this.removeListener("close",AU),this.removeListener("data",kp),this.removeListener("end",dU),t._readyState=At.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[Lt]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",iU),t._receiver.on("finish",iU))}function kp(t){this[Lt]._receiver.write(t)||this.pause()}function dU(){let t=this[Lt];t._readyState=At.CLOSING,t._receiver.end(),this.end()}function hU(){let t=this[Lt];this.removeListener("error",hU),this.on("error",oU),t&&(t._readyState=At.CLOSING,this.destroy())}});var EU=Q((ORe,mU)=>{"use strict";var URe=Tp(),{Duplex:tne}=R("stream");function gU(t){t.emit("close")}function rne(){!this.destroyed&&this._writableState.finished&&this.destroy()}function pU(t){this.removeListener("error",pU),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function nne(t,e){let r=!0,i=new tne({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&i._readableState.objectMode?s.toString():s;i.push(a)||t.pause()}),t.once("error",function(s){i.destroyed||(r=!1,i.destroy(s))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(n,s){if(t.readyState===t.CLOSED){s(n),process.nextTick(gU,i);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(n),process.nextTick(gU,i)}),r&&t.terminate()},i._final=function(n){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(n)});return}t._socket!==null&&(t._socket._writableState.finished?(n(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){n()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(n,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(n,s,o)});return}t.send(n,o)},i.on("end",rne),i.on("error",pU),i}mU.exports=nne});var Ew=Q(($Re,IU)=>{"use strict";var{tokenChars:ine}=Zc();function sne(t){let e=new Set,r=-1,i=-1,n=0;for(n;n<t.length;n++){let o=t.charCodeAt(n);if(i===-1&&ine[o]===1)r===-1&&(r=n);else if(n!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=n);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);i===-1&&(i=n);let a=t.slice(r,i);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,n);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}IU.exports={parse:sne}});var wU=Q((HRe,bU)=>{"use strict";var one=R("events"),Np=R("http"),{Duplex:PRe}=R("stream"),{createHash:ane}=R("crypto"),CU=Sp(),ea=Jc(),cne=Ew(),lne=Tp(),{CLOSE_TIMEOUT:une,GUID:Ane,kWebSocket:dne}=$i(),hne=/^[+/0-9A-Za-z]{22}==$/,yU=0,BU=1,QU=2,Iw=class extends one{constructor(e,r){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:une,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:lne,...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=Np.createServer((i,n)=>{let s=Np.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=fne(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,o)=>{this.handleUpgrade(n,s,o,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=yU}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===QU){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick($A,this);return}if(e&&this.once("close",e),this._state!==BU)if(this._state=BU,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($A,this):process.nextTick($A,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{$A(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,n){r.on("error",xU);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ta(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ta(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!hne.test(s)){ta(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ta(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){PA(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=cne.parse(c)}catch{ta(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let A=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&A!==void 0){let h=new ea({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let u=CU.parse(A);u[ea.extensionName]&&(h.accept(u[ea.extensionName]),d[ea.extensionName]=h)}catch{ta(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={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(h,(u,f,m,E)=>{if(!u)return PA(r,f||401,m,E);this.completeUpgrade(d,s,l,e,r,i,n)});return}if(!this.options.verifyClient(h))return PA(r,401)}this.completeUpgrade(d,s,l,e,r,i,n)}completeUpgrade(e,r,i,n,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[dne])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>yU)return PA(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ane("sha1").update(r+Ane).digest("base64")}`],A=new this.options.WebSocket(null,void 0,this.options);if(i.size){let d=this.options.handleProtocols?this.options.handleProtocols(i,n):i.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),A._protocol=d)}if(e[ea.extensionName]){let d=e[ea.extensionName].params,h=CU.format({[ea.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${h}`),A._extensions=e}this.emit("headers",l,n),s.write(l.concat(`\r
|
|
73
73
|
`).join(`\r
|
|
74
74
|
`)),s.removeListener("error",xU),A.setSocket(s,o,{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(A),A.on("close",()=>{this.clients.delete(A),this._shouldEmitClose&&!this.clients.size&&process.nextTick($A,this)})),a(A,n)}};bU.exports=Iw;function fne(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function $A(t){t._state=QU,t.emit("close")}function xU(){this.destroy()}function PA(t,e,r,i){r=r||Np.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Np.STATUS_CODES[e]}\r
|
|
75
75
|
`+Object.keys(i).map(n=>`${n}: ${i[n]}`).join(`\r
|