@neuvybe/jarvis 0.50.1 → 0.50.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -70,7 +70,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
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 Rte(t,e,r){return e?.aborted?Promise.reject(wF(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(wF(e))),c=r!==void 0?setTimeout(()=>o(()=>n(new Gs(r))),r):void 0;e?.addEventListener("abort",a,{once:!0}),t.read().then(l=>o(()=>i(l)),l=>o(()=>n(Mte(l))))})}function wF(t){let e=t?.reason;return e instanceof Error?e:new Error("text stream aborted")}function Mte(t){return t instanceof Error?t:new Error(String(t))}var Gs,jc=D(()=>{"use strict";Gs=class extends Error{constructor(e){super(`text stream idle for ${e}ms`),this.name="IdleTimeoutError"}}});function Fte(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 zc,Lte,JQ=D(()=>{"use strict";zc=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=Fte(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
71
  `,r:"\r",t:" "}});function qt(t,e){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":Ute(t.message,e):"network error"}function Ute(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 ci(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 Oi=D(()=>{"use strict"});var Me,Wc=D(()=>{"use strict";Me=class extends Error{status;diagnostic;constructor(e,r,i){super(e),this.status=r,this.diagnostic=i,this.name="TextAdapterError"}}});import{randomUUID as Ote}from"node:crypto";function Yte(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:zte(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 qte(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:jte(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 jte(t){return typeof t=="string"?t:JSON.stringify(t??{})}function zte(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function SF(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 DF(t){try{return JSON.parse(t)}catch{return}}function $i(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function vF(t){return Array.isArray(t)?t:void 0}function _F(t){let e=$i(t)?.message;return typeof e=="string"?e:"unknown error"}var Ys,$te,Pte,Hte,Vte,pp,Gte,vA,ZQ,SA,XQ,DA=D(()=>{"use strict";jc();JQ();Oi();Wc();Ys=3e4,$te=4096,Pte="https://api.anthropic.com/v1/messages",Hte="2023-06-01",Vte="https://api.openai.com/v1/chat/completions",pp=class{key;fetchImpl;idleTimeoutMs;constructor(e,r=fetch,i=Ys){this.key=e,this.fetchImpl=r,this.idleTimeoutMs=i,ci(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 Me(qt(o,this.key))}if(!n.ok)throw new Me(`text provider request failed (HTTP ${n.status})`,n.status);if(!n.body)throw new Me("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 gp(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}},Gte="eager_input_streaming",vA=class extends pp{buildRequest(e){let r=e.recoveryInstructions===void 0?e.system:[e.system,e.recoveryInstructions].filter(s=>s!==void 0).join(`
72
72
 
73
- `),i=new Set((e.streamText??[]).map(s=>s.name)),n={model:e.model,max_tokens:$te,stream:!0,messages:e.messages.map(Yte),...r!==void 0&&{system:r},...e.tools!==void 0&&e.tools.length>0&&{tools:e.tools.map(s=>({name:s.name,description:s.description,input_schema:s.inputSchema,...i.has(s.name)&&{[Gte]:!0}}))},...e.toolChoice==="any"&&{tool_choice:{type:"any"}}};return{url:Pte,init:{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":Hte,"content-type":"application/json"},body:JSON.stringify(n)}}}newTurnDecoder(e){return new ZQ(e)}};ZQ=class{streamText;tool=null;stopped=!1;constructor(e){this.streamText=e}isDone(){return!1}decode(e){let r=$i(DF(e));if(!r)return[];if(r.type==="error")throw new Me(`anthropic stream error: ${_F(r.error)}`);if(r.type==="message_stop")return this.stopped=!0,[];if(r.type==="content_block_start"){let i=$i(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 zc(s):null}}return[]}if(r.type==="content_block_delta"){let i=$i(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=SF(this.tool.id,this.tool.name,this.tool.json);return this.tool=null,[i]}return[]}flush(){if(!this.stopped)throw new Me("anthropic stream ended before message_stop");return[]}},SA=class extends pp{buildRequest(e){let r=e.messages.flatMap(qte),i=[...e.system===void 0?[]:[{role:"system",content:e.system}],...r,...e.recoveryInstructions===void 0?[]:[{role:"system",content:e.recoveryInstructions}]],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:Vte,init:{method:"POST",headers:{Authorization:`Bearer ${this.key}`,"content-type":"application/json"},body:JSON.stringify(n)}}}newTurnDecoder(){return new XQ}};XQ=class{calls=new Map;done=!1;isDone(e){return e!=="[DONE]"?!1:(this.done=!0,!0)}decode(e){let r=$i(DF(e));if(!r)return[];if(r.error)throw new Me(`openai stream error: ${_F(r.error)}`);let i=vF(r.choices),n=$i($i(i?.[0])?.delta);if(!n)return[];for(let o of vF(n.tool_calls)??[]){let a=$i(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 u=$i(a.function);typeof u?.name=="string"&&(l.name=u.name),typeof u?.arguments=="string"&&(l.args+=u.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)throw this.calls.clear(),new Me("openai stream ended before [DONE]");let e=[...this.calls.entries()].sort(([r],[i])=>r-i).map(([r,i])=>SF(i.id.length>0?i.id:`call-${r}-${Ote().slice(0,8)}`,i.name,i.args));return this.calls.clear(),e}}});var Pi,KQ=D(()=>{"use strict";Pi=class extends Error{status;constructor(e,r){super(e),this.status=r,this.name="SearchAdapterError"}}});function _A(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 kA(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 Pi("search provider returned an unexpected shape");return r}var Wte,Jte,Zte,Xte,Kte,ta,mp,Ep,Ip,yp,Cp,kF=D(()=>{"use strict";Oi();KQ();Wte="https://ollama.com/api/web_search",Jte="https://api.exa.ai/search",Zte="https://api.firecrawl.dev/v2/search",Xte="https://api.tavily.com/search",Kte="https://api.search.brave.com/res/v1/web/search",ta=class{key;fetchImpl;constructor(e,r=fetch){this.key=e,this.fetchImpl=r,ci(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 Pi(qt(l,this.key))}if(!a.ok)throw new Pi(`search provider returned ${a.status}`,a.status);let c;try{c=await a.json()}catch{throw new Pi("search provider returned a malformed response")}return this.parse(c).slice(0,r)}};mp=class extends ta{request(e,r){return{url:Wte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,max_results:r}}}parse(e){return kA(e).flatMap(r=>_A(r,"content"))}},Ep=class extends ta{request(e,r){return{url:Jte,headers:{"x-api-key":this.key},body:{query:e,numResults:r,contents:{text:!0}}}}parse(e){return kA(e).flatMap(r=>_A(r,"text"))}},Ip=class extends ta{request(e,r){return{url:Zte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,limit:r}}}parse(e){return kA(e,["data","web"]).flatMap(r=>_A(r,"description"))}},yp=class extends ta{request(e,r){return{url:Xte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,max_results:r}}}parse(e){return kA(e).flatMap(r=>_A(r,"content"))}},Cp=class extends ta{request(e,r){return{url:Kte,headers:{"x-subscription-token":this.key},method:"GET",query:{q:e,count:String(r)}}}parse(e){return kA(e,["web","results"]).flatMap(r=>_A(r,"description"))}}});function Bp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function ere(t){return typeof t=="string"?t:JSON.stringify(t??{})}function Hi(){return new Me("invalid openai response stream")}var xp,ew,TF=D(()=>{"use strict";DA();Oi();jc();JQ();Wc();xp=class{key;fetchImpl;idleTimeoutMs;continuations=[];constructor(e,r=fetch,i=Ys){this.key=e,this.fetchImpl=r,this.idleTimeoutMs=i,ci(e,"stored text provider key")}async*stream(e){let r=this.renderHistory(e.messages),i=new ew(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.recoveryInstructions===void 0?[]:[{role:"system",content:e.recoveryInstructions}]],...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 Me(`text provider request failed (HTTP ${n.status})`,n.status);if(!n.body)throw new Me("text provider response had no body");for await(let o of gp(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 Me(qt(n,this.key),n instanceof Me?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 Me("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:ere(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}]})}},ew=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=Bp(JSON.parse(e))}catch{}if(!r||typeof r.type!="string")throw Hi();if(["error","response.failed","response.incomplete","response.cancelled"].includes(r.type))throw new Me("openai response did not complete");if(r.type==="response.output_item.added"){let i=Bp(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 Hi();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 zc(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 Hi();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 Hi();return r.delta.length>0?[{type:"text",text:r.delta}]:[]}if(r.type==="response.completed"){let i=Bp(r.response);if(i?.status!=="completed"||!Array.isArray(i.output))throw Hi();this.output=i.output.map(n=>{let s=Bp(n);if(!s)throw Hi();return s}),this.completed=!0}return[]}finish(){if(!this.completed)throw new Me("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 Me("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 Hi();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 Hi();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 Hi();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 Jc,tw=D(()=>{"use strict";Jc=class{providers=new Map([["anthropic",{protocol:"anthropic-messages"}],["ollama",{protocol:"ollama-native"}],["ollama-local",{protocol:"ollama-native"}],["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}ollamaThinking(e,r){return e==="ollama-local"&&r==="gemma4:12b"?!0:/^(?:[^/]+\/)*gpt-oss(?::|$)/.test(r)?"low":!1}}});import{createHash as tre}from"node:crypto";function vr(t,e){if(t==="ollama")return rre;if(t!=="ollama-local")throw new Error("unknown Ollama provider");try{let r=new URL(e??ra);if(!["http:","https:"].includes(r.protocol)||r.username||r.password||r.href.includes("?")||r.href.includes("#"))throw new Error;return r.href.replace(/\/+$/,"")}catch{throw new Error("Ollama server address must be HTTP(S), without credentials, query or fragment")}}function TA(t,e){if(t!=="ollama-local")return t;let r=vr(t,e);return`${t}:${tre("sha256").update(r).digest("hex")}`}var ra,rre,Zc=D(()=>{"use strict";ra="http://localhost:11434",rre="https://ollama.com"});async function RF(t,e){if(e?.throwIfAborted(),!t.body)return;let r;try{r=t.body.getReader()}catch{return}let i,n,s=new Promise((a,c)=>{i=setTimeout(()=>a(void 0),250),n=()=>c(e?.reason instanceof Error?e.reason:new Error("the caller aborted")),e?.addEventListener("abort",n,{once:!0})}),o=async()=>{let a=new TextDecoder("utf-8",{fatal:!0}),c=0,l="";for(;;){let u=await r.read();if(u.done)break;if(c+=u.value.byteLength,c>16384)return;l+=a.decode(u.value,{stream:!0})}return l+=a.decode(),nre(l)};try{let a=await Promise.race([o(),s]);return e?.throwIfAborted(),a}catch{e?.throwIfAborted();return}finally{clearTimeout(i),n&&e?.removeEventListener("abort",n),r.cancel().catch(()=>{})}}function nre(t){if(t===rw)return{code:"context_exceeded"};let e=JSON.parse(t);for(let r=0;r<3;r++){if(e===rw)return{code:"context_exceeded"};if(typeof e!="object"||e===null||Array.isArray(e))return;let i=e;if(i.type==="exceed_context_size_error"){let n=NF(i.n_prompt_tokens,0),s=NF(i.n_ctx,1);return{code:"context_exceeded",...n!==void 0&&{promptTokens:n},...s!==void 0&&{contextTokens:s}}}e=i.error,typeof e=="string"&&e!==rw&&(e=JSON.parse(e))}}function NF(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=e?t:void 0}var rw,MF=D(()=>{"use strict";rw="the prompt is longer than the context length currently available to the model; shorten the prompt, adjust the context length in settings, or use a model with a longer context length"});async function*LF(t,e={}){let r=t.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),n="";try{for(;;){let{value:s,done:o}=await ire(r,e);n+=o?i.decode():i.decode(s,{stream:!0});let a;for(;(a=n.indexOf(`
73
+ `),i=new Set((e.streamText??[]).map(s=>s.name)),n={model:e.model,max_tokens:$te,stream:!0,messages:e.messages.map(Yte),...r!==void 0&&{system:r},...e.tools!==void 0&&e.tools.length>0&&{tools:e.tools.map(s=>({name:s.name,description:s.description,input_schema:s.inputSchema,...i.has(s.name)&&{[Gte]:!0}}))},...e.toolChoice==="any"&&{tool_choice:{type:"any"}}};return{url:Pte,init:{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":Hte,"content-type":"application/json"},body:JSON.stringify(n)}}}newTurnDecoder(e){return new ZQ(e)}};ZQ=class{streamText;tool=null;stopped=!1;constructor(e){this.streamText=e}isDone(){return!1}decode(e){let r=$i(DF(e));if(!r)return[];if(r.type==="error")throw new Me(`anthropic stream error: ${_F(r.error)}`);if(r.type==="message_stop")return this.stopped=!0,[];if(r.type==="content_block_start"){let i=$i(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 zc(s):null}}return[]}if(r.type==="content_block_delta"){let i=$i(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=SF(this.tool.id,this.tool.name,this.tool.json);return this.tool=null,[i]}return[]}flush(){if(!this.stopped)throw new Me("anthropic stream ended before message_stop");return[]}},SA=class extends pp{buildRequest(e){let r=e.messages.flatMap(qte),i=[...e.system===void 0?[]:[{role:"system",content:e.system}],...r,...e.recoveryInstructions===void 0?[]:[{role:"system",content:e.recoveryInstructions}]],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:Vte,init:{method:"POST",headers:{Authorization:`Bearer ${this.key}`,"content-type":"application/json"},body:JSON.stringify(n)}}}newTurnDecoder(){return new XQ}};XQ=class{calls=new Map;done=!1;isDone(e){return e!=="[DONE]"?!1:(this.done=!0,!0)}decode(e){let r=$i(DF(e));if(!r)return[];if(r.error)throw new Me(`openai stream error: ${_F(r.error)}`);let i=vF(r.choices),n=$i($i(i?.[0])?.delta);if(!n)return[];for(let o of vF(n.tool_calls)??[]){let a=$i(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 u=$i(a.function);typeof u?.name=="string"&&(l.name=u.name),typeof u?.arguments=="string"&&(l.args+=u.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)throw this.calls.clear(),new Me("openai stream ended before [DONE]");let e=[...this.calls.entries()].sort(([r],[i])=>r-i).map(([r,i])=>SF(i.id.length>0?i.id:`call-${r}-${Ote().slice(0,8)}`,i.name,i.args));return this.calls.clear(),e}}});var Pi,KQ=D(()=>{"use strict";Pi=class extends Error{status;constructor(e,r){super(e),this.status=r,this.name="SearchAdapterError"}}});function _A(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 kA(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 Pi("search provider returned an unexpected shape");return r}var Wte,Jte,Zte,Xte,Kte,ta,mp,Ep,Ip,yp,Cp,kF=D(()=>{"use strict";Oi();KQ();Wte="https://ollama.com/api/web_search",Jte="https://api.exa.ai/search",Zte="https://api.firecrawl.dev/v2/search",Xte="https://api.tavily.com/search",Kte="https://api.search.brave.com/res/v1/web/search",ta=class{key;fetchImpl;constructor(e,r=fetch){this.key=e,this.fetchImpl=r,ci(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 Pi(qt(l,this.key))}if(!a.ok)throw new Pi(`search provider returned ${a.status}`,a.status);let c;try{c=await a.json()}catch{throw new Pi("search provider returned a malformed response")}return this.parse(c).slice(0,r)}};mp=class extends ta{request(e,r){return{url:Wte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,max_results:r}}}parse(e){return kA(e).flatMap(r=>_A(r,"content"))}},Ep=class extends ta{request(e,r){return{url:Jte,headers:{"x-api-key":this.key},body:{query:e,numResults:r,contents:{text:!0}}}}parse(e){return kA(e).flatMap(r=>_A(r,"text"))}},Ip=class extends ta{request(e,r){return{url:Zte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,limit:r}}}parse(e){return kA(e,["data","web"]).flatMap(r=>_A(r,"description"))}},yp=class extends ta{request(e,r){return{url:Xte,headers:{authorization:`Bearer ${this.key}`},body:{query:e,max_results:r}}}parse(e){return kA(e).flatMap(r=>_A(r,"content"))}},Cp=class extends ta{request(e,r){return{url:Kte,headers:{"x-subscription-token":this.key},method:"GET",query:{q:e,count:String(r)}}}parse(e){return kA(e,["web","results"]).flatMap(r=>_A(r,"description"))}}});function Bp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function ere(t){return typeof t=="string"?t:JSON.stringify(t??{})}function Hi(){return new Me("invalid openai response stream")}var xp,ew,TF=D(()=>{"use strict";DA();Oi();jc();JQ();Wc();xp=class{key;fetchImpl;idleTimeoutMs;continuations=[];constructor(e,r=fetch,i=Ys){this.key=e,this.fetchImpl=r,this.idleTimeoutMs=i,ci(e,"stored text provider key")}async*stream(e){let r=this.renderHistory(e.messages),i=new ew(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.recoveryInstructions===void 0?[]:[{role:"system",content:e.recoveryInstructions}]],...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 Me(`text provider request failed (HTTP ${n.status})`,n.status);if(!n.body)throw new Me("text provider response had no body");for await(let o of gp(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 Me(qt(n,this.key),n instanceof Me?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 Me("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:ere(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}]})}},ew=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=Bp(JSON.parse(e))}catch{}if(!r||typeof r.type!="string")throw Hi();if(["error","response.failed","response.incomplete","response.cancelled"].includes(r.type))throw new Me("openai response did not complete");if(r.type==="response.output_item.added"){let i=Bp(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 Hi();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 zc(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 Hi();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 Hi();return r.delta.length>0?[{type:"text",text:r.delta}]:[]}if(r.type==="response.completed"){let i=Bp(r.response);if(i?.status!=="completed"||!Array.isArray(i.output))throw Hi();this.output=i.output.map(n=>{let s=Bp(n);if(!s)throw Hi();return s}),this.completed=!0}return[]}finish(){if(!this.completed)throw new Me("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 Me("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 Hi();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 Hi();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 Hi();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 Jc,tw=D(()=>{"use strict";Jc=class{providers=new Map([["anthropic",{protocol:"anthropic-messages"}],["ollama",{protocol:"ollama-native"}],["ollama-local",{protocol:"ollama-native"}],["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}ollamaThinking(e,r){return e==="ollama-local"&&r==="gemma4:12b"?!0:/^(?:[^/]+\/)*(?:gpt-oss|glm-5\.3-flash)(?::|$)/.test(r)?"low":!1}}});import{createHash as tre}from"node:crypto";function vr(t,e){if(t==="ollama")return rre;if(t!=="ollama-local")throw new Error("unknown Ollama provider");try{let r=new URL(e??ra);if(!["http:","https:"].includes(r.protocol)||r.username||r.password||r.href.includes("?")||r.href.includes("#"))throw new Error;return r.href.replace(/\/+$/,"")}catch{throw new Error("Ollama server address must be HTTP(S), without credentials, query or fragment")}}function TA(t,e){if(t!=="ollama-local")return t;let r=vr(t,e);return`${t}:${tre("sha256").update(r).digest("hex")}`}var ra,rre,Zc=D(()=>{"use strict";ra="http://localhost:11434",rre="https://ollama.com"});async function RF(t,e){if(e?.throwIfAborted(),!t.body)return;let r;try{r=t.body.getReader()}catch{return}let i,n,s=new Promise((a,c)=>{i=setTimeout(()=>a(void 0),250),n=()=>c(e?.reason instanceof Error?e.reason:new Error("the caller aborted")),e?.addEventListener("abort",n,{once:!0})}),o=async()=>{let a=new TextDecoder("utf-8",{fatal:!0}),c=0,l="";for(;;){let u=await r.read();if(u.done)break;if(c+=u.value.byteLength,c>16384)return;l+=a.decode(u.value,{stream:!0})}return l+=a.decode(),nre(l)};try{let a=await Promise.race([o(),s]);return e?.throwIfAborted(),a}catch{e?.throwIfAborted();return}finally{clearTimeout(i),n&&e?.removeEventListener("abort",n),r.cancel().catch(()=>{})}}function nre(t){if(t===rw)return{code:"context_exceeded"};let e=JSON.parse(t);for(let r=0;r<3;r++){if(e===rw)return{code:"context_exceeded"};if(typeof e!="object"||e===null||Array.isArray(e))return;let i=e;if(i.type==="exceed_context_size_error"){let n=NF(i.n_prompt_tokens,0),s=NF(i.n_ctx,1);return{code:"context_exceeded",...n!==void 0&&{promptTokens:n},...s!==void 0&&{contextTokens:s}}}e=i.error,typeof e=="string"&&e!==rw&&(e=JSON.parse(e))}}function NF(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=e?t:void 0}var rw,MF=D(()=>{"use strict";rw="the prompt is longer than the context length currently available to the model; shorten the prompt, adjust the context length in settings, or use a model with a longer context length"});async function*LF(t,e={}){let r=t.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),n="";try{for(;;){let{value:s,done:o}=await ire(r,e);n+=o?i.decode():i.decode(s,{stream:!0});let a;for(;(a=n.indexOf(`
74
74
  `))!==-1;){let c=n.slice(0,a).trim();n=n.slice(a+1),e.signal?.throwIfAborted(),c&&(yield c)}if(o){e.signal?.throwIfAborted(),n.trim()&&(yield n.trim());return}}}finally{r.cancel().catch(()=>{})}}function ire(t,{signal:e,idleTimeoutMs:r}){return e?.throwIfAborted(),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(e?.reason)),c=r===void 0?void 0:setTimeout(()=>o(()=>n(new Gs(r))),r);e?.addEventListener("abort",a,{once:!0}),t.read().then(l=>o(()=>i(l)),()=>o(()=>n(new Error("text stream read failed"))))})}var FF=D(()=>{"use strict";jc()});import{randomUUID as sre}from"node:crypto";function bp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function qs(){return new Me("invalid Ollama response stream")}var NA,nw=D(()=>{"use strict";DA();Zc();MF();FF();Oi();jc();Wc();NA=class{provider;fetchImpl;idleTimeoutMs;thinking;endpoint;key;continuations=[];constructor(e,r,i,n=fetch,s=Ys,o=!1){this.provider=e,this.fetchImpl=n,this.idleTimeoutMs=s,this.thinking=o,this.endpoint=vr(e,i),this.key=e==="ollama"?r:"",ci(this.key,"stored text provider key")}async*stream(e){let r=this.renderHistory(e.messages),i=[],n="",s=!1;try{e.signal?.throwIfAborted();let o=await this.fetchImpl(`${this.endpoint}/api/chat`,{method:"POST",headers:{"content-type":"application/json",...this.provider==="ollama"&&{Authorization:`Bearer ${this.key}`}},redirect:"error",signal:e.signal,body:JSON.stringify({model:e.model,stream:!0,think:this.thinking,messages:[...e.system===void 0?[]:[{role:"system",content:e.system}],...r,...e.recoveryInstructions===void 0?[]:[{role:"system",content:e.recoveryInstructions}]],...e.tools?.length&&{tools:e.tools.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema}}))}})});if(!o.ok){let a=o.status===400?await RF(o,e.signal):void 0;throw o.status!==400&&o.body?.cancel().catch(()=>{}),new Me(a?.code==="context_exceeded"?`Brain request exceeded the model's allocated context (HTTP ${o.status})`:`text provider request failed (HTTP ${o.status})`,o.status,a)}if(!o.body)throw new Me("text provider response had no body");for await(let a of LF(o.body,{signal:e.signal,idleTimeoutMs:this.idleTimeoutMs})){e.signal?.throwIfAborted();let c;try{c=bp(JSON.parse(a))}catch{throw qs()}if(!c)throw qs();if("error"in c)throw new Me("Ollama response did not complete");if(typeof c.done!="boolean")throw qs();let l=bp(c.message);if(l?.role!=="assistant")throw qs();if(l.thinking!==void 0){if(typeof l.thinking!="string")throw qs();n+=l.thinking}if(l.tool_calls!==void 0){if(!Array.isArray(l.tool_calls))throw qs();for(let u of l.tool_calls){let d=bp(u),h=bp(d?.function);if(!h||typeof h.name!="string"||!h.name.trim()||!("arguments"in h))throw qs();i.push({id:sre(),name:h.name,input:h.arguments})}}if(l.content!==void 0){if(typeof l.content!="string")throw qs();l.content&&(e.signal?.throwIfAborted(),yield{type:"text",text:l.content})}if(c.done){s=!0;break}}if(e.signal?.throwIfAborted(),!s)throw new Me("Ollama stream ended before completion");for(let a of i)e.signal?.throwIfAborted(),yield{type:"tool_call",...a};e.signal?.throwIfAborted(),i.length&&n&&this.continuations.push({calls:structuredClone(i),thinking:n})}catch(o){throw e.signal?.aborted?e.signal.reason:o instanceof Me?o:o instanceof Gs?new Me(o.message):new Me("Ollama text request or stream failed")}}renderHistory(e){let r=-1;for(let s=e.length-1;s>=0;s--)if(e[s].role==="user"){r=s;break}let i=new Set(e.slice(r+1).flatMap(s=>"toolCalls"in s?s.toolCalls.map(o=>o.id):[]));this.continuations=this.continuations.filter(s=>s.calls.some(o=>i.has(o.id)));let n=new Map;return e.flatMap(s=>{if("toolCalls"in s){let o=this.continuations.filter(a=>a.calls.some(c=>s.toolCalls.some(l=>l.id===c.id)));if(o.length>1||o.some(a=>JSON.stringify(a.calls)!==JSON.stringify(s.toolCalls)))throw new Me("Ollama continuation no longer matches retained calls");for(let a of s.toolCalls)n.set(a.id,a.name);return[{role:"assistant",content:s.content,...o.length&&{thinking:o[0].thinking},tool_calls:s.toolCalls.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:a.input}}))}]}return s.role==="tool"?s.results.map(o=>{let a=n.get(o.id);if(!a)throw new Me("Ollama tool result has no retained call");return{role:"tool",tool_name:a,tool_call_id:o.id,content:o.result}}):[{role:s.role,content:s.content}]})}}});var RA,iw=D(()=>{"use strict";DA();kF();TF();tw();nw();RA=class{fetchImpl;idleTimeoutMs;brainModels=new Jc;constructor(e=fetch,r=Ys){this.fetchImpl=e,this.idleTimeoutMs=r}textAdapter(e,r){switch(this.brainModels.protocol(e.provider,e.model)){case"anthropic-messages":return new vA(r,this.fetchImpl,this.idleTimeoutMs);case"openai-responses":return new xp(r,this.fetchImpl,this.idleTimeoutMs);case"openai-chat-completions":return new SA(r,this.fetchImpl,this.idleTimeoutMs);case"ollama-native":return new NA(e.provider,r,e.url,this.fetchImpl,this.idleTimeoutMs,this.brainModels.ollamaThinking(e.provider,e.model));default:throw new Error(`no text adapter for provider '${e.provider}'`)}}searchAdapter(e,r){switch(e.provider){case"ollama":return new mp(r,this.fetchImpl);case"exa":return new Ep(r,this.fetchImpl);case"firecrawl":return new Ip(r,this.fetchImpl);case"tavily":return new yp(r,this.fetchImpl);case"brave":return new Cp(r,this.fetchImpl);default:throw new Error(`no search adapter for provider '${e.provider}'`)}}}});var Sr,UF=D(()=>{"use strict";Sr=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 OF=D(()=>{"use strict"});var MA=D(()=>{"use strict";UF();OF()});function ore(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function are(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Qp(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 ${ore(r.durationMs)}`];r.bytes!==void 0&&i.push(are(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 LA(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 sw=D(()=>{"use strict"});function $F(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}var FA,PF=D(()=>{"use strict";Zc();FA=class{provider;constructor(e){this.provider=e}async list(e,r,i){let n=vr(this.provider,i),s=await this.json(`${n}/api/tags`,e,r);if(!Array.isArray(s?.models))throw new Error("invalid Ollama model catalogue");let o=new Map,a=!1;for(let A of s.models){let f=$F(A);f&&typeof f.name=="string"&&f.name.trim()?o.set(f.name,f):a=!0}let c=[...o],l=new Array(c.length),u=0,d=async()=>{for(;u<c.length;){r.throwIfAborted();let A=u++,[f,m]=c[A];try{let E=await this.json(`${n}/api/show`,e,r,{model:f}),I=E?.capabilities;if(!Array.isArray(I)||this.provider==="ollama-local"&&I.some(Q=>typeof Q!="string")){a=!0;continue}if(!I.includes("completion")||!I.includes("tools"))continue;let y=m.remote_model??E?.remote_model;l[A]={id:f,...typeof y=="string"&&y.length>0&&{label:"runs through Ollama Cloud"}}}catch{r.throwIfAborted(),a=!0}}};await Promise.all(Array.from({length:Math.min(4,c.length)},d)),r.throwIfAborted();let h=l.filter(A=>A!==void 0);if(!h.length&&(this.provider!=="ollama-local"||a))throw new Error("no Ollama models reporting completion and tools");return{text:h}}async json(e,r,i,n){let s;try{s=await r(e,{method:n===void 0?"GET":"POST",headers:{"content-type":"application/json"},...n!==void 0&&{body:JSON.stringify(n)},redirect:"error",signal:i})}catch{throw new Error("Ollama model catalogue unavailable")}if(!s.ok)throw s.body?.cancel().catch(()=>{}),new Error(`Ollama model catalogue failed (HTTP ${s.status})`);try{return $F(await s.json())}catch{throw new Error("invalid Ollama model catalogue")}}}});var Vi,UA=D(()=>{"use strict";Vi=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 hn(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 cre(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 js,OA,$A,na=D(()=>{"use strict";Nt();js=.02;OA=class{threshold;constructor(e){this.threshold=e}classify(e,r){r(hn(e,this.threshold))}},$A=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??js,this.log=r.log??ne}classify(e,r){if(this.degraded){this.announce("energy (fallback)"),r(hn(e,this.energyThreshold));return}this.vad.process(cre(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(hn(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 ow(t){return new Error(`openai-compat ASR decode failed (HTTP ${t})`)}function aw(t){t.body?.cancel().catch(()=>{})}function ure(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function fre(t){return t.replace(hre," ")}function gre(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 pre(t,e){let r=new Uint8Array(e),i=0;for(let n of t)r.set(n,i),i+=n.byteLength;return r}function mre(t,e){let r=new Uint8Array(44+t.byteLength),i=new DataView(r.buffer);return wp(r,0,"RIFF"),i.setUint32(4,36+t.byteLength,!0),wp(r,8,"WAVE"),wp(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),wp(r,36,"data"),i.setUint32(40,t.byteLength,!0),r.set(t,44),r}function wp(t,e,r){for(let i=0;i<r.length;i+=1)t[e+i]=r.charCodeAt(i)}function GF(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")?GF(t.cause,e+1):t.message.length>0?t.message:t.name.length>0?t.name:"network error"}var lw,uw,HF,lre,vp,cw,VF,Are,dre,hre,Aw=D(()=>{"use strict";Nt();Oi();UA();na();lw="http://localhost:8081",uw="large-v3-turbo",HF=1e3,lre=1e4,vp=class{fetchImpl;model;clock;id="openai-compat";partialStability="redecode";baseUrl;key;negotiation={dialect:null};constructor(e,r=lw,i=uw,n,s=new Vi){this.fetchImpl=e,this.model=i,this.clock=s,this.baseUrl=gre(r),this.key=n!==void 0&&n.length>0?n:void 0,this.key!==void 0&&ci(this.key,"openai-compat ASR key")}open(e){return e.biasTerms!==void 0&&e.biasTerms.length>0&&ne.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 cw({fetchImpl:this.fetchImpl,baseUrl:this.baseUrl,model:this.model,key:this.key,negotiation:this.negotiation,clock:this.clock},e)}},cw=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&&hn(e,js)&&(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*(HF/1e3))return;let e=this.ctx.clock.now();e-this.lastDecodeAtMs<HF||(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=>{ne.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=mre(pre(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=ure(o)&&typeof o.text=="string"?o.text:"";return fre(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 aw(o),ow(o.status);return o}let n=await this.post("standard",e,r);if(n.ok)return this.ctx.negotiation.dialect="standard",n;if(aw(n),n.status!==404)throw ow(n.status);let s=await this.post("inference",e,r);if(s.ok)return this.ctx.negotiation.dialect="inference",s;throw aw(s),ow(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: ${GF(o)}`,{cause:o})}}decodeReplyTimeoutMs(){let e=this.bufferedBytes/2/this.opts.sampleRate*1e3;return lre+Math.ceil(e)}teardown(){this.closed||(this.closed=!0,this.inFlightAbort?.abort(),this.inFlightAbort=null)}};VF=" ",Are="\r",dre=`
75
75
  `,hre=new RegExp(`[ ${VF}]*[${Are}${dre}]+[ ${VF}]*`,"g")});var fn,PA=D(()=>{"use strict";fn=class extends Error{category;constructor(e,r){super(e),this.category=r,this.name="ASRTerminalError"}}});function zs(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function HA(t){return typeof t=="string"?t:""}function Xc(t){let e=t.message_type;return typeof e=="string"&&(Ere.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function YF(t){return Buffer.from(t).toString("base64")}function Sp(t){return new Uint8Array(Buffer.from(t,"base64"))}function VA(t,e){return new Error(`${t} connection error: ${e.message}`)}function qF(t){return Ire[t]??null}function jF(t,e){if(e instanceof fn)return new fn(`${t} connection error: ${e.message}`,e.category);let r=yre.exec(e.message)?.[1];return r!==void 0?new fn(`${t} connection error: rejected credential (HTTP ${r})`,"auth"):VA(t,e)}var Ere,Ire,yre,GA=D(()=>{"use strict";PA();Ere=new Set(["error","auth_error","quota_exceeded","rate_limited"]);Ire={quota_exceeded:"quota",auth_error:"auth"};yre=/^Unexpected server response: (401|403)\b/});function JF(t,e){let r=new Uint8Array(e),i=0;for(let n of t)r.set(n,i),i+=n.byteLength;return r}function Bre(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 xre(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 Dp,zF,WF,Cre,YA,dw,_p=D(()=>{"use strict";Nt();UA();na();GA();Dp="ws://localhost:6007",zF=1e3,WF=10240,Cre=1e4,YA=class{socketFactory;url;clock;id="sherpa-onnx";partialStability="redecode";constructor(e,r=Dp,i=new Vi){this.socketFactory=e,this.url=r,this.clock=i}open(e){return e.biasTerms!==void 0&&e.biasTerms.length>0&&ne.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 dw(this.socketFactory,this.url,this.clock,e)}},dw=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&&hn(e,js)&&(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=zs(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(HA(r.text))}}}handleError(e){if(this.closed)return;let r=VA("sherpa ASR",new Error(Bre(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*(zF/1e3))return;let e=this.clock.now();e-this.lastDecodeAtMs<zF||(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=xre(JF(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=JF([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+=WF)this.socket.send(s.subarray(a,Math.min(a+WF,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 Cre+Math.ceil(e)}teardown(){this.closed||(this.closed=!0,this.rejectPendingReply(new Error("sherpa ASR stream closed")),this.socket.close())}}});var ZF,kp,bre,Qre,wre,qA,hw,Tp=D(()=>{"use strict";GA();ZF="wss://api.elevenlabs.io/v1/text-to-dialogue/stream-input",kp=["eleven_v3","eleven_v3_conversational"],bre=1e4,Qre=1e4,wre=6e4,qA=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-v3";constructor(e,r,i,n=ZF){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 hw(this.apiKey,this.socketFactory,i.toString(),r.voiceId)}},hw=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")),bre),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}),Qre),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")),wre),this.finalTimer.unref()}handleMessage(e){if(this.terminal()||!this.opened)return;let r=zs(e);if(r){if(typeof r.error=="string"||Xc(r)!==null){this.fail(new Error("ElevenLabs v3 TTS stream error"));return}if(typeof r.audio=="string"&&r.audio.length>0){let i=Sp(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 Gi=b((C2e,eU)=>{"use strict";var XF=["nodebuffer","arraybuffer","fragments"],KF=typeof Blob<"u";KF&&XF.push("blob");eU.exports={BINARY_TYPES:XF,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:KF,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var jA=b((B2e,Np)=>{"use strict";var{EMPTY_BUFFER:vre}=Gi(),fw=Buffer[Symbol.species];function Sre(t,e){if(t.length===0)return vre;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 fw(r.buffer,r.byteOffset,i):r}function tU(t,e,r,i,n){for(let s=0;s<n;s++)r[i+s]=t[s]^e[s&3]}function rU(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Dre(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function gw(t){if(gw.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new fw(t):ArrayBuffer.isView(t)?e=new fw(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),gw.readOnly=!1),e}Np.exports={concat:Sre,mask:tU,toArrayBuffer:Dre,toBuffer:gw,unmask:rU};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=R("bufferutil");Np.exports.mask=function(e,r,i,n,s){s<48?tU(e,r,i,n,s):t.mask(e,r,i,n,s)},Np.exports.unmask=function(e,r){e.length<32?rU(e,r):t.unmask(e,r)}}catch{}});var sU=b((x2e,iU)=>{"use strict";var nU=Symbol("kDone"),pw=Symbol("kRun"),mw=class{constructor(e){this[nU]=()=>{this.pending--,this[pw]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[pw]()}[pw](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[nU])}}};iU.exports=mw});var tl=b((b2e,lU)=>{"use strict";var zA=R("zlib"),oU=jA(),_re=sU(),{kStatusCode:aU}=Gi(),kre=Buffer[Symbol.species],Tre=Buffer.from([0,0,255,255]),Mp=Symbol("permessage-deflate"),Yi=Symbol("total-length"),Kc=Symbol("callback"),Ws=Symbol("buffers"),el=Symbol("error"),Rp,Ew=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,!Rp){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Rp=new _re(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[Kc];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){Rp.add(n=>{this._decompress(e,r,(s,o)=>{n(),i(s,o)})})}compress(e,r,i){Rp.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"?zA.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=zA.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Mp]=this,this._inflate[Yi]=0,this._inflate[Ws]=[],this._inflate.on("error",Rre),this._inflate.on("data",cU)}this._inflate[Kc]=i,this._inflate.write(e),r&&this._inflate.write(Tre),this._inflate.flush(()=>{let s=this._inflate[el];if(s){this._inflate.close(),this._inflate=null,i(s);return}let o=oU.concat(this._inflate[Ws],this._inflate[Yi]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Yi]=0,this._inflate[Ws]=[],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"?zA.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=zA.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Yi]=0,this._deflate[Ws]=[],this._deflate.on("data",Nre)}this._deflate[Kc]=i,this._deflate.write(e),this._deflate.flush(zA.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=oU.concat(this._deflate[Ws],this._deflate[Yi]);r&&(s=new kre(s.buffer,s.byteOffset,s.length-4)),this._deflate[Kc]=null,this._deflate[Yi]=0,this._deflate[Ws]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,s)})}};lU.exports=Ew;function Nre(t){this[Ws].push(t),this[Yi]+=t.length}function cU(t){if(this[Yi]+=t.length,this[Mp]._maxPayload<1||this[Yi]<=this[Mp]._maxPayload){this[Ws].push(t);return}this[el]=new RangeError("Max payload size exceeded"),this[el].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[el][aU]=1009,this.removeListener("data",cU),this.reset()}function Rre(t){if(this[Mp]._inflate=null,this[el]){this[Kc](this[el]);return}t[aU]=1007,this[Kc](t)}});var rl=b((Q2e,Lp)=>{"use strict";var{isUtf8:uU}=R("buffer"),{hasBlob:Mre}=Gi(),Lre=[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 Fre(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 Ure(t){return Mre&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Lp.exports={isBlob:Ure,isValidStatusCode:Fre,isValidUTF8:Iw,tokenChars:Lre};if(uU)Lp.exports.isValidUTF8=function(t){return t.length<24?Iw(t):uU(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=R("utf-8-validate");Lp.exports.isValidUTF8=function(e){return e.length<32?Iw(e):t(e)}}catch{}});var bw=b((w2e,mU)=>{"use strict";var{Writable:Ore}=R("stream"),AU=tl(),{BINARY_TYPES:$re,EMPTY_BUFFER:dU,kStatusCode:Pre,kWebSocket:Hre}=Gi(),{concat:yw,toArrayBuffer:Vre,unmask:Gre}=jA(),{isValidStatusCode:Yre,isValidUTF8:hU}=rl(),Fp=Buffer[Symbol.species],gn=0,fU=1,gU=2,pU=3,Cw=4,Bw=5,Up=6,xw=class extends Ore{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||$re[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[Hre]=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=gn}_write(e,r,i){if(this._opcode===8&&this._state==gn)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 Fp(i.buffer,i.byteOffset+e,i.length-e),new Fp(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 Fp(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 gn:this.getInfo(e);break;case fU:this.getPayloadLength16(e);break;case gU:this.getPayloadLength64(e);break;case pU:this.getMask();break;case Cw:this.getData(e);break;case Bw:case Up: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[AU.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=fU:this._payloadLength===127?this._state=gU: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=pU:this._state=Cw}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Cw}getData(e){let r=dU;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&&Gre(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Bw,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[AU.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===gn&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=gn;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=yw(i,r):this._binaryType==="arraybuffer"?n=Vre(yw(i,r)):this._binaryType==="blob"?n=new Blob(i):n=i,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=gn):(this._state=Up,setImmediate(()=>{this.emit("message",n,!0),this._state=gn,this.startLoop(e)}))}else{let n=yw(i,r);if(!this._skipUTF8Validation&&!hU(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Bw||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=gn):(this._state=Up,setImmediate(()=>{this.emit("message",n,!1),this._state=gn,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,dU),this.end();else{let i=e.readUInt16BE(0);if(!Yre(i)){let s=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let n=new Fp(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!hU(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=gn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=gn):(this._state=Up,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=gn,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[Pre]=n,o}};mU.exports=xw});var vw=b((S2e,yU)=>{"use strict";var{Duplex:v2e}=R("stream"),{randomFillSync:qre}=R("crypto"),{types:{isUint8Array:jre}}=R("util"),EU=tl(),{EMPTY_BUFFER:zre,kWebSocket:Wre,NOOP:Jre}=Gi(),{isBlob:nl,isValidStatusCode:Zre}=rl(),{mask:IU,toBuffer:ia}=jA(),pn=Symbol("kByteLength"),Xre=Buffer.alloc(4),Op=8*1024,sa,il=Op,Un=0,Kre=1,ene=2,Qw=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=Un,this.onerror=Jre,this[Wre]=void 0}static frame(e,r){let i,n=!1,s=2,o=!1;r.mask&&(i=r.maskBuffer||Xre,r.generateMask?r.generateMask(i):(il===Op&&(sa===void 0&&(sa=Buffer.alloc(Op)),qre(sa,0,Op),il=0),i[0]=sa[il++],i[1]=sa[il++],i[2]=sa[il++],i[3]=sa[il++]),o=(i[0]|i[1]|i[2]|i[3])===0,s=6);let a;typeof e=="string"?(!r.mask||o)&&r[pn]!==void 0?a=r[pn]:(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?(IU(e,i,l,s,a),[l]):(IU(e,i,e,0,a),[l,e])):[l,e]}close(e,r,i,n){let s;if(e===void 0)s=zre;else{if(typeof e!="number"||!Zre(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(jre(r))s.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[pn]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Un?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):nl(e)?(n=e.size,s=!1):(e=ia(e),n=e.length,s=ia.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[pn]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};nl(e)?this._state!==Un?this.enqueue([this.getBlobData,e,!1,o,i]):this.getBlobData(e,!1,o,i):this._state!==Un?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):nl(e)?(n=e.size,s=!1):(e=ia(e),n=e.length,s=ia.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[pn]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};nl(e)?this._state!==Un?this.enqueue([this.getBlobData,e,!1,o,i]):this.getBlobData(e,!1,o,i):this._state!==Un?this.enqueue([this.dispatch,e,!1,o,i]):this.sendFrame(t.frame(e,o),i)}send(e,r,i){let n=this._extensions[EU.extensionName],s=r.binary?2:1,o=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):nl(e)?(a=e.size,c=!1):(e=ia(e),a=e.length,c=ia.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={[pn]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};nl(e)?this._state!==Un?this.enqueue([this.getBlobData,e,this._compress,l,i]):this.getBlobData(e,this._compress,l,i):this._state!==Un?this.enqueue([this.dispatch,e,this._compress,l,i]):this.dispatch(e,this._compress,l,i)}getBlobData(e,r,i,n){this._bufferedBytes+=i[pn],this._state=ene,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ww,this,a,n);return}this._bufferedBytes-=i[pn];let o=ia(s);r?this.dispatch(o,r,i,n):(this._state=Un,this.sendFrame(t.frame(o,i),n),this.dequeue())}).catch(s=>{process.nextTick(tne,this,s,n)})}dispatch(e,r,i,n){if(!r){this.sendFrame(t.frame(e,i),n);return}let s=this._extensions[EU.extensionName];this._bufferedBytes+=i[pn],this._state=Kre,s.compress(e,i.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ww(this,c,n);return}this._bufferedBytes-=i[pn],this._state=Un,i.readOnly=!1,this.sendFrame(t.frame(a,i),n),this.dequeue()})}dequeue(){for(;this._state===Un&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][pn],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][pn],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)}};yU.exports=Qw;function ww(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 tne(t,e,r){ww(t,e,r),t.onerror(e)}});var DU=b((D2e,SU)=>{"use strict";var{kForOnEventAttribute:WA,kListener:Sw}=Gi(),CU=Symbol("kCode"),BU=Symbol("kData"),xU=Symbol("kError"),bU=Symbol("kMessage"),QU=Symbol("kReason"),sl=Symbol("kTarget"),wU=Symbol("kType"),vU=Symbol("kWasClean"),qi=class{constructor(e){this[sl]=null,this[wU]=e}get target(){return this[sl]}get type(){return this[wU]}};Object.defineProperty(qi.prototype,"target",{enumerable:!0});Object.defineProperty(qi.prototype,"type",{enumerable:!0});var oa=class extends qi{constructor(e,r={}){super(e),this[CU]=r.code===void 0?0:r.code,this[QU]=r.reason===void 0?"":r.reason,this[vU]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[CU]}get reason(){return this[QU]}get wasClean(){return this[vU]}};Object.defineProperty(oa.prototype,"code",{enumerable:!0});Object.defineProperty(oa.prototype,"reason",{enumerable:!0});Object.defineProperty(oa.prototype,"wasClean",{enumerable:!0});var ol=class extends qi{constructor(e,r={}){super(e),this[xU]=r.error===void 0?null:r.error,this[bU]=r.message===void 0?"":r.message}get error(){return this[xU]}get message(){return this[bU]}};Object.defineProperty(ol.prototype,"error",{enumerable:!0});Object.defineProperty(ol.prototype,"message",{enumerable:!0});var JA=class extends qi{constructor(e,r={}){super(e),this[BU]=r.data===void 0?null:r.data}get data(){return this[BU]}};Object.defineProperty(JA.prototype,"data",{enumerable:!0});var rne={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[WA]&&n[Sw]===e&&!n[WA])return;let i;if(t==="message")i=function(s,o){let a=new JA("message",{data:o?s:s.toString()});a[sl]=this,$p(e,this,a)};else if(t==="close")i=function(s,o){let a=new oa("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[sl]=this,$p(e,this,a)};else if(t==="error")i=function(s){let o=new ol("error",{error:s,message:s.message});o[sl]=this,$p(e,this,o)};else if(t==="open")i=function(){let s=new qi("open");s[sl]=this,$p(e,this,s)};else return;i[WA]=!!r[WA],i[Sw]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Sw]===e&&!r[WA]){this.removeListener(t,r);break}}};SU.exports={CloseEvent:oa,ErrorEvent:ol,Event:qi,EventTarget:rne,MessageEvent:JA};function $p(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Pp=b((_2e,_U)=>{"use strict";var{tokenChars:ZA}=rl();function li(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function nne(t){let e=Object.create(null),r=Object.create(null),i=!1,n=!1,s=!1,o,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),o===void 0)if(u===-1&&ZA[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let A=t.slice(c,u);l===44?(li(e,A,r),r=Object.create(null)):o=A,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&ZA[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),li(r,t.slice(c,u),!0),l===44&&(li(e,o,r),r=Object.create(null),o=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(n){if(ZA[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:i||(i=!0),n=!1}else if(s)if(ZA[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)s=!1,u=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(u===-1&&ZA[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let A=t.slice(c,u);i&&(A=A.replace(/\\/g,""),i=!1),li(r,a,A),l===44&&(li(e,o,r),r=Object.create(null),o=void 0),a=void 0,c=u=-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");u===-1&&(u=d);let h=t.slice(c,u);return o===void 0?li(e,h,r):(a===void 0?li(r,h,!0):i?li(r,a,h.replace(/\\/g,"")):li(r,a,h),li(e,o,r)),e}function ine(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(", ")}_U.exports={format:ine,parse:nne}});var Yp=b((N2e,HU)=>{"use strict";var sne=R("events"),one=R("https"),ane=R("http"),NU=R("net"),cne=R("tls"),{randomBytes:lne,createHash:une}=R("crypto"),{Duplex:k2e,Readable:T2e}=R("stream"),{URL:Dw}=R("url"),Js=tl(),Ane=bw(),dne=vw(),{isBlob:hne}=rl(),{BINARY_TYPES:kU,CLOSE_TIMEOUT:fne,EMPTY_BUFFER:Hp,GUID:gne,kForOnEventAttribute:_w,kListener:pne,kStatusCode:mne,kWebSocket:Lt,NOOP:RU}=Gi(),{EventTarget:{addEventListener:Ene,removeEventListener:Ine}}=DU(),{format:yne,parse:Cne}=Pp(),{toBuffer:Bne}=jA(),MU=Symbol("kAborted"),kw=[8,13],ji=["CONNECTING","OPEN","CLOSING","CLOSED"],xne=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ht=class t extends sne{constructor(e,r,i){super(),this._binaryType=kU[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Hp,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]),LU(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){kU.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 Ane({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 dne(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",wne),n.on("drain",vne),n.on("error",Sne),n.on("message",Dne),n.on("ping",_ne),n.on("pong",kne),s.onerror=Tne,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",OU),e.on("data",Gp),e.on("end",$U),e.on("error",PU),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[Js.extensionName]&&this._extensions[Js.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){Gr(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){Tw(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Hp,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){Tw(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Hp,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){Tw(this,e,i);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Js.extensionName]||(n.compress=!1),this._sender.send(e||Hp,n,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Gr(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ht,"CONNECTING",{enumerable:!0,value:ji.indexOf("CONNECTING")});Object.defineProperty(ht.prototype,"CONNECTING",{enumerable:!0,value:ji.indexOf("CONNECTING")});Object.defineProperty(ht,"OPEN",{enumerable:!0,value:ji.indexOf("OPEN")});Object.defineProperty(ht.prototype,"OPEN",{enumerable:!0,value:ji.indexOf("OPEN")});Object.defineProperty(ht,"CLOSING",{enumerable:!0,value:ji.indexOf("CLOSING")});Object.defineProperty(ht.prototype,"CLOSING",{enumerable:!0,value:ji.indexOf("CLOSING")});Object.defineProperty(ht,"CLOSED",{enumerable:!0,value:ji.indexOf("CLOSED")});Object.defineProperty(ht.prototype,"CLOSED",{enumerable:!0,value:ji.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ht.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ht.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[_w])return e[pne];return null},set(e){for(let r of this.listeners(t))if(r[_w]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[_w]:!0})}})});ht.prototype.addEventListener=Ene;ht.prototype.removeEventListener=Ine;HU.exports=ht;function LU(t,e,r,i){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:fne,protocolVersion:kw[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,!kw.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${kw.join(", ")})`);let s;if(e instanceof Dw)s=e;else try{s=new Dw(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;Vp(t,m);return}let l=o?443:80,u=lne(16).toString("base64"),d=o?one.request:ane.request,h=new Set,A;if(n.createConnection=n.createConnection||(o?Qne:bne),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":u,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(A=new Js({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=yne({[Js.extensionName]:A.offer()})),r.length){for(let m of r){if(typeof m!="string"||!xne.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",()=>{Gr(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[MU]||(f=t._req=null,Vp(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){Gr(t,f,"Maximum redirects exceeded");return}f.abort();let y;try{y=new Dw(E,e)}catch{let v=new SyntaxError(`Invalid URL: ${E}`);Vp(t,v);return}LU(t,y,r,i)}else t.emit("unexpected-response",f,m)||Gr(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,E,I)=>{if(t.emit("upgrade",m),t.readyState!==ht.CONNECTING)return;f=t._req=null;let y=m.headers.upgrade;if(y===void 0||y.toLowerCase()!=="websocket"){Gr(t,E,"Invalid Upgrade header");return}let Q=une("sha1").update(u+gne).digest("base64");if(m.headers["sec-websocket-accept"]!==Q){Gr(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){Gr(t,E,S);return}v&&(t._protocol=v);let F=m.headers["sec-websocket-extensions"];if(F!==void 0){if(!A){Gr(t,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=Cne(F)}catch{Gr(t,E,"Invalid Sec-WebSocket-Extensions header");return}let $=Object.keys(M);if($.length!==1||$[0]!==Js.extensionName){Gr(t,E,"Server indicated an extension that was not requested");return}try{A.accept(M[Js.extensionName])}catch{Gr(t,E,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Js.extensionName]=A}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 Vp(t,e){t._readyState=ht.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function bne(t){return t.path=t.socketPath,NU.connect(t)}function Qne(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=NU.isIP(t.host)?"":t.host),cne.connect(t)}function Gr(t,e,r){t._readyState=ht.CLOSING;let i=new Error(r);Error.captureStackTrace(i,Gr),e.setHeader?(e[MU]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Vp,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Tw(t,e,r){if(e){let i=hne(e)?e.size:Bne(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${ji[t.readyState]})`);process.nextTick(r,i)}}function wne(t,e){let r=this[Lt];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Lt]!==void 0&&(r._socket.removeListener("data",Gp),process.nextTick(FU,r._socket),t===1005?r.close():r.close(t,e))}function vne(){let t=this[Lt];t.isPaused||t._socket.resume()}function Sne(t){let e=this[Lt];e._socket[Lt]!==void 0&&(e._socket.removeListener("data",Gp),process.nextTick(FU,e._socket),e.close(t[mne])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function TU(){this[Lt].emitClose()}function Dne(t,e){this[Lt].emit("message",t,e)}function _ne(t){let e=this[Lt];e._autoPong&&e.pong(t,!this._isServer,RU),e.emit("ping",t)}function kne(t){this[Lt].emit("pong",t)}function FU(t){t.resume()}function Tne(t){let e=this[Lt];e.readyState!==ht.CLOSED&&(e.readyState===ht.OPEN&&(e._readyState=ht.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 OU(){let t=this[Lt];if(this.removeListener("close",OU),this.removeListener("data",Gp),this.removeListener("end",$U),t._readyState=ht.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",TU),t._receiver.on("finish",TU))}function Gp(t){this[Lt]._receiver.write(t)||this.pause()}function $U(){let t=this[Lt];t._readyState=ht.CLOSING,t._receiver.end(),this.end()}function PU(){let t=this[Lt];this.removeListener("error",PU),this.on("error",RU),t&&(t._readyState=ht.CLOSING,this.destroy())}});var qU=b((M2e,YU)=>{"use strict";var R2e=Yp(),{Duplex:Nne}=R("stream");function VU(t){t.emit("close")}function Rne(){!this.destroyed&&this._writableState.finished&&this.destroy()}function GU(t){this.removeListener("error",GU),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Mne(t,e){let r=!0,i=new Nne({...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(VU,i);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(n),process.nextTick(VU,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",GU),i}YU.exports=Mne});var Nw=b((L2e,jU)=>{"use strict";var{tokenChars:Lne}=rl();function Fne(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&&Lne[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}jU.exports={parse:Fne}});var eO=b((U2e,KU)=>{"use strict";var Une=R("events"),qp=R("http"),{Duplex:F2e}=R("stream"),{createHash:One}=R("crypto"),zU=Pp(),aa=tl(),$ne=Nw(),Pne=Yp(),{CLOSE_TIMEOUT:Hne,GUID:Vne,kWebSocket:Gne}=Gi(),Yne=/^[+/0-9A-Za-z]{22}==$/,WU=0,JU=1,XU=2,Rw=class extends Une{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:Hne,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Pne,...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=qp.createServer((i,n)=>{let s=qp.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=qne(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=WU}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===XU){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(XA,this);return}if(e&&this.once("close",e),this._state!==JU)if(this._state=JU,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(XA,this):process.nextTick(XA,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{XA(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",ZU);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ca(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ca(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!Yne.test(s)){ca(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ca(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){KA(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=$ne.parse(c)}catch{ca(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let h=new aa({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let A=zU.parse(u);A[aa.extensionName]&&(h.accept(A[aa.extensionName]),d[aa.extensionName]=h)}catch{ca(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,(A,f,m,E)=>{if(!A)return KA(r,f||401,m,E);this.completeUpgrade(d,s,l,e,r,i,n)});return}if(!this.options.verifyClient(h))return KA(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[Gne])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>WU)return KA(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${One("sha1").update(r+Vne).digest("base64")}`],u=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}`),u._protocol=d)}if(e[aa.extensionName]){let d=e[aa.extensionName].params,h=zU.format({[aa.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${h}`),u._extensions=e}this.emit("headers",l,n),s.write(l.concat(`\r
76
76
  `).join(`\r
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neuvybe/jarvis",
3
- "version": "0.50.1",
3
+ "version": "0.50.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {