@rqmii_immersive/agent-react-sdk 5.0.0 → 5.0.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.
- package/dist/{RqmiiCloudAvatarPlayer-D5aXKUuO.js → RqmiiCloudAvatarPlayer-BBA8R0Sl.js} +2 -2
- package/dist/RqmiiCloudAvatarPlayer-BBA8R0Sl.js.map +1 -0
- package/dist/{RqmiiCloudAvatarPlayer-BI7Uz7DP.cjs → RqmiiCloudAvatarPlayer-CFPGKoOq.cjs} +2 -2
- package/dist/RqmiiCloudAvatarPlayer-CFPGKoOq.cjs.map +1 -0
- package/dist/agent-react-sdk.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/ui/RqmiiAgentChat.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-avatar.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-content.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-shared.d.ts +1 -1
- package/dist/ui/chat/chat-box-shared.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-text-and-voice.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-text.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-types.d.ts +1 -0
- package/dist/ui/chat/chat-box-types.d.ts.map +1 -1
- package/dist/ui/chat/chat-box-voice.d.ts.map +1 -1
- package/dist/ui.cjs +36 -36
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.d.ts.map +1 -1
- package/dist/ui.js +1864 -1851
- package/dist/ui.js.map +1 -1
- package/package.json +1 -1
- package/dist/RqmiiCloudAvatarPlayer-BI7Uz7DP.cjs.map +0 -1
- package/dist/RqmiiCloudAvatarPlayer-D5aXKUuO.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const oe=require("react"),Jt=require("react/jsx-runtime"),di={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},_r={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",LANGUAGE_CHANGED:"language_changed",CLIENT_READY:"client_ready",CLIENT_TOOL_REQUEST:"client_tool_request",CLIENT_TOOL_RESULT:"client_tool_result",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete"},ft={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",FAILED:"failed",ENDED:"ended"},Zt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Bs={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},Gp={encoding:"16bitInt",channels:1,sampleRate:16e3},po={connectionState:ft.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:Bs.IDLE,cloudStream:{state:Zt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null,agentConfig:null};function hp(d,r){switch(r.type){case"SET_CONNECTION_STATE":return{...d,connectionState:r.payload,isConnected:r.payload===ft.CONNECTED};case"SET_ERROR":return{...d,error:r.payload};case"SET_CLOUD_STREAM_STATE":return{...d,cloudStream:r.payload};case"SET_SESSION_STATE":return{...d,sessionState:r.payload};case"UPDATE_SESSION":return{...d,session:{...d.session,...r.payload}};case"ADD_MESSAGE":return{...d,messages:[...d.messages,r.payload]};case"SET_AUDIO_PLAYING":return{...d,isAudioPlaying:r.payload};case"SET_AVATAR_SPEAKING":return{...d,isAvatarSpeaking:r.payload};case"SET_CREDIT_EXHAUSTED":return{...d,creditExhausted:r.payload.exhausted,creditError:r.payload.error};case"SET_TRANSCRIPT":return{...d,transcript:r.payload};case"SET_PARTIAL_TRANSCRIPT":return{...d,partialTranscript:r.payload};case"SET_MESSAGES":return{...d,messages:r.payload};case"SET_SESSION_READY":return{...d,isSessionReady:r.payload};case"SET_AGENT_CONFIG":return{...d,agentConfig:r.payload};case"HARD_RESET":return po;case"REPLACE_STATE":return r.payload;default:return d}}function dg(d){return{isSessionTerminated:d===Bs.TERMINATED,isSessionTerminating:d===Bs.TERMINATING,isAgentThinking:d===Bs.AGENT_THINKING,isAgentSpeaking:d===Bs.AGENT_SPEAKING,isToolExecuting:d===Bs.TOOL_EXECUTING}}function cg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,_=`${d.get(a)||""}${s||""}`;return d.set(a,_),{id:a,text:_}},consume(r,s=""){const a=r||`request-${Date.now()}`,f=d.get(a)||s||"";return d.delete(a),{id:a,text:f}},clear(){d.clear()}}}function hg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function Ii(d){if(!d?.ok){let r=`HTTP ${d.status}`;try{const f=await d.json();r=f?.detail||f?.message||r}catch{}const s=new Error(r);throw s.status=d.status,s}return d.json()}function pg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function f({apiKey:b,publicChatId:U,agentId:z,userId:re,language:K="en",timezone:ie,config:J}={}){a();const Y={...b?{api_key:b}:{},...U?{public_chat_id:U}:{},...z?{agent_id:z}:{},...re?{user_id:re}:{},language:K,...ie?{timezone:ie}:{},...J?{config:J}:{}};r("initializeSession — POST /sessions/init",Y);const H=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y),...s?{credentials:"include"}:{}}),se=await Ii(H);if(!se?.session_id||!se?.session_token)throw new Error("Invalid initialize session response");return se}async function _({uniqueId:b}){a(),r("joinDesktopSession — POST /sessions/join",{uniqueId:b});const U=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:b}),...s?{credentials:"include"}:{}}),z=await Ii(U);if(!z?.session_id||!z?.session_token)throw new Error("Invalid join session response");return z}async function C(b){a(),r("fetchAgentConfig — GET /agent/{publicChatId}",{publicChatId:b});const U=await fetch(`${d}/agent/${encodeURIComponent(b)}`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return Ii(U)}async function R({sessionId:b,rating:U,feedback:z,endedBy:re}){if(a(),!b)throw new Error("sessionId is required");const K={...typeof U=="number"?{rating:U}:{},...z?{feedback:z}:{},...re?{ended_by:re}:{}};r("submitFeedback — PATCH /conversations/{sessionId}/feedback",{sessionId:b,payload:K});const ie=await fetch(`${d}/conversations/${encodeURIComponent(b)}/feedback`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(K),...s?{credentials:"include"}:{}});return Ii(ie)}return{initializeSession:f,joinDesktopSession:_,fetchAgentConfig:C,submitFeedback:R}}const Or=Object.create(null);Or.open="0";Or.close="1";Or.ping="2";Or.pong="3";Or.message="4";Or.upgrade="5";Or.noop="6";const Di=Object.create(null);Object.keys(Or).forEach(d=>{Di[Or[d]]=d});const fo={type:"error",data:"parser error"},qp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Wp=typeof ArrayBuffer=="function",Hp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>qp&&r instanceof Blob?s?a(r):pp(r,a):Wp&&(r instanceof ArrayBuffer||Hp(r))?s?a(r):pp(new Blob([r]),a):a(Or[d]+(r||"")),pp=(d,r)=>{const s=new FileReader;return s.onload=function(){const a=s.result.split(",")[1];r("b"+(a||""))},s.readAsDataURL(d)};function fp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let Ya;function fg(d,r){if(qp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Wp&&(d.data instanceof ArrayBuffer||Hp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oi=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)oi[mp.charCodeAt(d)]=d;const mg=d=>{let r=d.length*.75,s=d.length,a,f=0,_,C,R,b;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const U=new ArrayBuffer(r),z=new Uint8Array(U);for(a=0;a<s;a+=4)_=oi[d.charCodeAt(a)],C=oi[d.charCodeAt(a+1)],R=oi[d.charCodeAt(a+2)],b=oi[d.charCodeAt(a+3)],z[f++]=_<<2|C>>4,z[f++]=(C&15)<<4|R>>2,z[f++]=(R&3)<<6|b&63;return U},gg=typeof ArrayBuffer=="function",Co=(d,r)=>{if(typeof d!="string")return{type:"message",data:Kp(d,r)};const s=d.charAt(0);return s==="b"?{type:"message",data:yg(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},yg=(d,r)=>{if(gg){const s=mg(d);return Kp(s,r)}else return{base64:!0,data:d}},Kp=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},jp="",wg=(d,r)=>{const s=d.length,a=new Array(s);let f=0;d.forEach((_,C)=>{xo(_,!1,R=>{a[C]=R,++f===s&&r(a.join(jp))})})},vg=(d,r)=>{const s=d.split(jp),a=[];for(let f=0;f<s.length;f++){const _=Co(s[f],r);if(a.push(_),_.type==="error")break}return a};function _g(){return new TransformStream({transform(d,r){fg(d,s=>{const a=s.length;let f;if(a<126)f=new Uint8Array(1),new DataView(f.buffer).setUint8(0,a);else if(a<65536){f=new Uint8Array(3);const _=new DataView(f.buffer);_.setUint8(0,126),_.setUint16(1,a)}else{f=new Uint8Array(9);const _=new DataView(f.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(s)})}})}let Ja;function Mi(d){return d.reduce((r,s)=>r+s.length,0)}function Pi(d,r){if(d[0].length===r)return d.shift();const s=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)s[f]=d[0][a++],a===d[0].length&&(d.shift(),a=0);return d.length&&a<d[0].length&&(d[0]=d[0].slice(a)),s}function bg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,f=-1,_=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const b=Pi(s,1);_=(b[0]&128)===128,f=b[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(Mi(s)<2)break;const b=Pi(s,2);f=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(Mi(s)<8)break;const b=Pi(s,8),U=new DataView(b.buffer,b.byteOffset,b.length),z=U.getUint32(0);if(z>Math.pow(2,21)-1){R.enqueue(fo);break}f=z*Math.pow(2,32)+U.getUint32(4),a=3}else{if(Mi(s)<f)break;const b=Pi(s,f);R.enqueue(Co(_?b:Ja.decode(b),r)),a=0}if(f===0||f>d){R.enqueue(fo);break}}}})}const Qp=4;function $t(d){if(d)return Sg(d)}function Sg(d){for(var r in $t.prototype)d[r]=$t.prototype[r];return d}$t.prototype.on=$t.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};$t.prototype.once=function(d,r){function s(){this.off(d,s),r.apply(this,arguments)}return s.fn=r,this.on(d,s),this};$t.prototype.off=$t.prototype.removeListener=$t.prototype.removeAllListeners=$t.prototype.removeEventListener=function(d,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var s=this._callbacks["$"+d];if(!s)return this;if(arguments.length==1)return delete this._callbacks["$"+d],this;for(var a,f=0;f<s.length;f++)if(a=s[f],a===r||a.fn===r){s.splice(f,1);break}return s.length===0&&delete this._callbacks["$"+d],this};$t.prototype.emit=function(d){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),s=this._callbacks["$"+d],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(s){s=s.slice(0);for(var a=0,f=s.length;a<f;++a)s[a].apply(this,r)}return this};$t.prototype.emitReserved=$t.prototype.emit;$t.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};$t.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Vi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,s)=>s(r,0),lr=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Tg="arraybuffer";function Xp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const Eg=lr.setTimeout,$g=lr.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=Eg.bind(lr),d.clearTimeoutFn=$g.bind(lr)):(d.setTimeoutFn=lr.setTimeout.bind(lr),d.clearTimeoutFn=lr.clearTimeout.bind(lr))}const xg=1.33;function Cg(d){return typeof d=="string"?kg(d):Math.ceil((d.byteLength||d.size)*xg)}function kg(d){let r=0,s=0;for(let a=0,f=d.length;a<f;a++)r=d.charCodeAt(a),r<128?s+=1:r<2048?s+=2:r<55296||r>=57344?s+=3:(a++,s+=4);return s}function Yp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Rg(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Ag(d){let r={},s=d.split("&");for(let a=0,f=s.length;a<f;a++){let _=s[a].split("=");r[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return r}class Ig extends Error{constructor(r,s,a){super(r),this.description=s,this.context=a,this.type="TransportError"}}class ko extends $t{constructor(r){super(),this.writable=!1,Gi(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,s,a){return super.emitReserved("error",new Ig(r,s,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const s=Co(r,this.socket.binaryType);this.onPacket(s)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,s={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const s=Rg(r);return s.length?"?"+s:""}}class Mg extends ko{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const s=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||s()})),this.writable||(a++,this.once("drain",function(){--a||s()}))}else s()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const s=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};vg(r,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const r=()=>{this.write([{type:"close"}])};this.readyState==="open"?r():this.once("open",r)}write(r){this.writable=!1,wg(r,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Yp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Jp=!1;try{Jp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Pg=Jp;function Og(){}class Dg extends Mg{constructor(r){if(super(r),typeof location<"u"){const s=location.protocol==="https:";let a=location.port;a||(a=s?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,s){const a=this.request({method:"POST",data:r});a.on("success",s),a.on("error",(f,_)=>{this.onError("xhr post error",f,_)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(s,a)=>{this.onError("xhr poll error",s,a)}),this.pollXhr=r}}class Pr extends $t{constructor(r,s,a){super(),this.createRequest=r,Gi(this,a),this._opts=a,this._method=a.method||"GET",this._uri=s,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const s=Xp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(s);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let f in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(f)&&a.setRequestHeader(f,this._opts.extraHeaders[f])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var f;a.readyState===3&&((f=this._opts.cookieJar)===null||f===void 0||f.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(f){this.setTimeoutFn(()=>{this._onError(f)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Og,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const d="onpagehide"in lr?"pagehide":"unload";addEventListener(d,gp,!1)}}function gp(){for(let d in Pr.requests)Pr.requests.hasOwnProperty(d)&&Pr.requests[d].abort()}const zg=(function(){const d=Zp({xdomain:!1});return d&&d.responseType!==null})();class Lg extends Dg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=zg&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(Zp,this.uri(),r)}}function Zp(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Pg))return new XMLHttpRequest}catch{}if(!r)try{return new lr[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ef=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Bg extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=ef?{}:Xp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,s,a)}catch(f){return this.emitReserved("error",f)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;xo(a,this.supportsBinary,_=>{try{this.doWrite(a,_)}catch{}f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Yp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=lr.WebSocket||lr.MozWebSocket;class Ng extends Bg{createSocket(r,s,a){return ef?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Ug extends ko{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const s=bg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),f=_g();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const _=()=>{a.read().then(({done:R,value:b})=>{R||(this.onPacket(b),_())}).catch(R=>{})};_();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;this._writer.write(a).then(()=>{f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const Fg={websocket:Ng,webtransport:Ug,polling:Lg},Vg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Gg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mo(d){if(d.length>8e3)throw"URI too long";const r=d,s=d.indexOf("["),a=d.indexOf("]");s!=-1&&a!=-1&&(d=d.substring(0,s)+d.substring(s,a).replace(/:/g,";")+d.substring(a,d.length));let f=Vg.exec(d||""),_={},C=14;for(;C--;)_[Gg[C]]=f[C]||"";return s!=-1&&a!=-1&&(_.source=r,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=qg(_,_.path),_.queryKey=Wg(_,_.query),_}function qg(d,r){const s=/\/{2,9}/g,a=r.replace(s,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function Wg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,_){f&&(s[f]=_)}),s}const go=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];go&&addEventListener("offline",()=>{zi.forEach(d=>d())},!1);class as extends $t{constructor(r,s){if(super(),this.binaryType=Tg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(s=r,r=null),r){const a=mo(r);s.hostname=a.host,s.secure=a.protocol==="https"||a.protocol==="wss",s.port=a.port,a.query&&(s.query=a.query)}else s.host&&(s.hostname=mo(s.host).host);Gi(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(a=>{const f=a.prototype.name;this.transports.push(f),this._transportsByName[f]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ag(this.opts.query)),go&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const s=Object.assign({},this.opts.query);s.EIO=Qp,s.transport=r,this.id&&(s.sid=this.id);const a=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&as.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const s=this.createTransport(r);s.open(),this.setTransport(s)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){this.readyState="open",as.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const s=new Error("server error");s.code=r.data,this._onError(s);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let a=0;a<this.writeBuffer.length;a++){const f=this.writeBuffer[a].data;if(f&&(s+=Cg(f)),a>0&&s>this._maxPayload)return this.writeBuffer.slice(0,a);s+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Vi(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,s,a){return this._sendPacket("message",r,s,a),this}send(r,s,a){return this._sendPacket("message",r,s,a),this}_sendPacket(r,s,a,f){if(typeof s=="function"&&(f=s,s=void 0),typeof a=="function"&&(f=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const _={type:r,data:s,options:a};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),f&&this.once("flush",f),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},s=()=>{this.off("upgrade",s),this.off("upgradeError",s),r()},a=()=>{this.once("upgrade",s),this.once("upgradeError",s)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(as.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),go&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=zi.indexOf(this._offlineEventListener);a!==-1&&zi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,s),this.writeBuffer=[],this._prevBufferLen=0}}}as.protocol=Qp;class Hg extends as{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let s=this.createTransport(r),a=!1;as.priorWebsocketSuccess=!1;const f=()=>{a||(s.send([{type:"ping",data:"probe"}]),s.once("packet",re=>{if(!a)if(re.type==="pong"&&re.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;as.priorWebsocketSuccess=s.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(z(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{const K=new Error("probe error");K.transport=s.name,this.emitReserved("upgradeError",K)}}))};function _(){a||(a=!0,z(),s.close(),s=null)}const C=re=>{const K=new Error("probe error: "+re);K.transport=s.name,_(),this.emitReserved("upgradeError",K)};function R(){C("transport closed")}function b(){C("socket closed")}function U(re){s&&re.name!==s.name&&_()}const z=()=>{s.removeListener("open",f),s.removeListener("error",C),s.removeListener("close",R),this.off("close",b),this.off("upgrading",U)};s.once("open",f),s.once("error",C),s.once("close",R),this.once("close",b),this.once("upgrading",U),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||s.open()},200):s.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const s=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&s.push(r[a]);return s}}let Kg=class extends Hg{constructor(r,s={}){const a=typeof r=="object"?r:s;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(f=>Fg[f]).filter(f=>!!f)),super(r,a)}};function jg(d,r="",s){let a=d;s=s||typeof location<"u"&&location,d==null&&(d=s.protocol+"//"+s.host),typeof d=="string"&&(d.charAt(0)==="/"&&(d.charAt(1)==="/"?d=s.protocol+d:d=s.host+d),/^(https?|wss?):\/\//.test(d)||(typeof s<"u"?d=s.protocol+"//"+d:d="https://"+d),a=mo(d)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const _=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+_+":"+a.port+r,a.href=a.protocol+"://"+_+(s&&s.port===a.port?"":":"+a.port),a}const Qg=typeof ArrayBuffer=="function",Xg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,tf=Object.prototype.toString,Yg=typeof Blob=="function"||typeof Blob<"u"&&tf.call(Blob)==="[object BlobConstructor]",Jg=typeof File=="function"||typeof File<"u"&&tf.call(File)==="[object FileConstructor]";function Ro(d){return Qg&&(d instanceof ArrayBuffer||Xg(d))||Yg&&d instanceof Blob||Jg&&d instanceof File}function Li(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let s=0,a=d.length;s<a;s++)if(Li(d[s]))return!0;return!1}if(Ro(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Li(d.toJSON(),!0);for(const s in d)if(Object.prototype.hasOwnProperty.call(d,s)&&Li(d[s]))return!0;return!1}function Zg(d){const r=[],s=d.data,a=d;return a.data=yo(s,r),a.attachments=r.length,{packet:a,buffers:r}}function yo(d,r){if(!d)return d;if(Ro(d)){const s={_placeholder:!0,num:r.length};return r.push(d),s}else if(Array.isArray(d)){const s=new Array(d.length);for(let a=0;a<d.length;a++)s[a]=yo(d[a],r);return s}else if(typeof d=="object"&&!(d instanceof Date)){const s={};for(const a in d)Object.prototype.hasOwnProperty.call(d,a)&&(s[a]=yo(d[a],r));return s}return d}function ey(d,r){return d.data=wo(d.data,r),delete d.attachments,d}function wo(d,r){if(!d)return d;if(d&&d._placeholder===!0){if(typeof d.num=="number"&&d.num>=0&&d.num<r.length)return r[d.num];throw new Error("illegal attachments")}else if(Array.isArray(d))for(let s=0;s<d.length;s++)d[s]=wo(d[s],r);else if(typeof d=="object")for(const s in d)Object.prototype.hasOwnProperty.call(d,s)&&(d[s]=wo(d[s],r));return d}const ty=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Ye;(function(d){d[d.CONNECT=0]="CONNECT",d[d.DISCONNECT=1]="DISCONNECT",d[d.EVENT=2]="EVENT",d[d.ACK=3]="ACK",d[d.CONNECT_ERROR=4]="CONNECT_ERROR",d[d.BINARY_EVENT=5]="BINARY_EVENT",d[d.BINARY_ACK=6]="BINARY_ACK"})(Ye||(Ye={}));class ry{constructor(r){this.replacer=r}encode(r){return(r.type===Ye.EVENT||r.type===Ye.ACK)&&Li(r)?this.encodeAsBinary({type:r.type===Ye.EVENT?Ye.BINARY_EVENT:Ye.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let s=""+r.type;return(r.type===Ye.BINARY_EVENT||r.type===Ye.BINARY_ACK)&&(s+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(s+=r.nsp+","),r.id!=null&&(s+=r.id),r.data!=null&&(s+=JSON.stringify(r.data,this.replacer)),s}encodeAsBinary(r){const s=Zg(r),a=this.encodeAsString(s.packet),f=s.buffers;return f.unshift(a),f}}class Ao extends $t{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let s;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(r);const a=s.type===Ye.BINARY_EVENT;a||s.type===Ye.BINARY_ACK?(s.type=a?Ye.EVENT:Ye.ACK,this.reconstructor=new sy(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(Ro(r)||r.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(r),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let s=0;const a={type:Number(r.charAt(0))};if(Ye[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===Ye.BINARY_EVENT||a.type===Ye.BINARY_ACK){const _=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(_,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!ny(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(s+1)==="/"){const _=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(_,s)}else a.nsp="/";const f=r.charAt(s+1);if(f!==""&&Number(f)==f){const _=s+1;for(;++s;){const C=r.charAt(s);if(C==null||Number(C)!=C){--s;break}if(s===r.length)break}a.id=Number(r.substring(_,s+1))}if(r.charAt(++s)){const _=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,_))a.data=_;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,s){switch(r){case Ye.CONNECT:return yp(s);case Ye.DISCONNECT:return s===void 0;case Ye.CONNECT_ERROR:return typeof s=="string"||yp(s);case Ye.EVENT:case Ye.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&ty.indexOf(s[0])===-1);case Ye.ACK:case Ye.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class sy{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const s=ey(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ny=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function yp(d){return Object.prototype.toString.call(d)==="[object Object]"}const iy=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:ry,get PacketType(){return Ye}},Symbol.toStringTag,{value:"Module"}));function br(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const ay=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class rf extends $t{constructor(r,s,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=s,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[br(r,"open",this.onopen.bind(this)),br(r,"packet",this.onpacket.bind(this)),br(r,"error",this.onerror.bind(this)),br(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...s){var a,f,_;if(ay.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(s.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;const C={type:Ye.EVENT,data:s};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){const z=this.ids++,re=s.pop();this._registerAckCallback(z,re),C.id=z}const R=(f=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||f===void 0?void 0:f.writable,b=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!R||(b?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,s){var a;const f=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(f===void 0){this.acks[r]=s;return}const _=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);s.call(this,new Error("operation has timed out"))},f),C=(...R)=>{this.io.clearTimeoutFn(_),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,f)=>{const _=(C,R)=>C?f(C):a(R);_.withError=!0,s.push(_),this.emit(r,...s)})}_addToQueue(r){let s;typeof r[r.length-1]=="function"&&(s=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((f,..._)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(f)):(this._queue.shift(),s&&s(null,..._)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const s=this._queue[0];s.pending&&!r||(s.pending=!0,s.tryCount++,this.flags=s.flags,this.emit.apply(this,s.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Ye.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,s){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Ye.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ye.EVENT:case Ye.BINARY_EVENT:this.onevent(r);break;case Ye.ACK:case Ye.BINARY_ACK:this.onack(r);break;case Ye.DISCONNECT:this.ondisconnect();break;case Ye.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const s=r.data||[];r.id!=null&&s.push(this.ack(r.id)),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const s=this._anyListeners.slice();for(const a of s)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const s=this;let a=!1;return function(...f){a||(a=!0,s.packet({type:Ye.ACK,id:r,data:f}))}}onack(r){const s=this.acks[r.id];typeof s=="function"&&(delete this.acks[r.id],s.withError&&r.data.unshift(null),s.apply(this,r.data))}onconnect(r,s){this.id=r,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ye.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const s=this._anyListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const s=this._anyOutgoingListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const s=this._anyOutgoingListeners.slice();for(const a of s)a.apply(this,r.data)}}}function un(d){d=d||{},this.ms=d.min||100,this.max=d.max||1e4,this.factor=d.factor||2,this.jitter=d.jitter>0&&d.jitter<=1?d.jitter:0,this.attempts=0}un.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),s=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-s:d+s}return Math.min(d,this.max)|0};un.prototype.reset=function(){this.attempts=0};un.prototype.setMin=function(d){this.ms=d};un.prototype.setMax=function(d){this.max=d};un.prototype.setJitter=function(d){this.jitter=d};class vo extends $t{constructor(r,s){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(s=r,r=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,Gi(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((a=s.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new un({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=r;const f=s.parser||iy;this.encoder=new f.Encoder,this.decoder=new f.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var s;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(s=this.backoff)===null||s===void 0||s.setMin(r),this)}randomizationFactor(r){var s;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(s=this.backoff)===null||s===void 0||s.setJitter(r),this)}reconnectionDelayMax(r){var s;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(s=this.backoff)===null||s===void 0||s.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new Kg(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=br(s,"open",function(){a.onopen(),r&&r()}),_=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=br(s,"error",_);if(this._timeout!==!1){const R=this._timeout,b=this.setTimeoutFn(()=>{f(),_(new Error("timeout")),s.close()},R);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(f),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(br(r,"ping",this.onping.bind(this)),br(r,"data",this.ondata.bind(this)),br(r,"error",this.onerror.bind(this)),br(r,"close",this.onclose.bind(this)),br(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(s){this.onclose("parse error",s)}}ondecoded(r){Vi(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,s){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new rf(this,r,s),this.nsps[r]=a),a}_destroy(r){const s=Object.keys(this.nsps);for(const a of s)if(this.nsps[a].active)return;this._close()}_packet(r){const s=this.encoder.encode(r);for(let a=0;a<s.length;a++)this.engine.write(s[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,s){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const s=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(f=>{f?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",f)):r.onreconnect()}))},s);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const Zn={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=jg(d,r.path||"/socket.io"),a=s.source,f=s.id,_=s.path,C=Zn[f]&&_ in Zn[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let b;return R?b=new vo(a,r):(Zn[f]||(Zn[f]=new vo(a,r)),b=Zn[f]),s.query&&!r.query&&(r.query=s.queryKey),b.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:rf,io:Bi,connect:Bi});function oy({wsUrl:d,log:r}){let s=null;function a({authPayload:C,queryToken:R}){const b=Bi(d,{transports:["polling"],timeout:2e4,reconnection:!1,auth:C,query:R?{token:R}:void 0});return s=b,b}function f(){if(s){try{s.removeAllListeners(),s.connected?s.disconnect():s.close()}catch{}s=null}}function _(){return s}return{connectSocketRaw:a,cleanupSocket:f,getSocket:_}}const ly=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(_=>r.addEventListener(_,a,!1));function a(){d.resume().then(f)}function f(){s.forEach(_=>r.removeEventListener(_,a))}};function Ot(d){this.init(d)}Ot.prototype.init=function(d){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,d),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Ot.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),ly(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Ot.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Ot.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Ot.prototype.feed=function(d){if(this.isTypedArray(d)){d=this.getFormatedValue(d);var r=new Float32Array(this.samples.length+d.length);r.set(this.samples,0),r.set(d,this.samples.length),this.samples=r,this.timeout||this.flush()}};Ot.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),s=new Float32Array(r.length),a;for(a=0;a<r.length;a++)s[a]=r[a]/this.maxValue;return s};Ot.prototype.volume=function(d){this.gainNode.gain.value=d};Ot.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Ot.prototype.getTimestamp=function(d){if(this.playingStartTime>=0){if(!d)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=d/1e3,r}return 0};Ot.prototype.setRequestStop=function(){this.flag_request_stop=!0};Ot.prototype.setOnEnd=function(d){this.onEnd=d};Ot.prototype.interrupt=function(d){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Ot.prototype.ensuredSetTimeout=(function(){let d;return function(r,s){d=performance.now();const a=f=>{f-d>=s?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Ot.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Ot.prototype.flush=function(){if(this.samples.length){var d=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,s=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,_,C,R;for(f=0;f<this.option.channels;f++)for(a=s.getChannelData(f),_=f,R=50,C=0;C<r;C++)a[C]=this.samples[_],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),_+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,d.buffer=s,d.connect(this.gainNode),d.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=d,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=s.duration,this.flag_request_stop)this.flag_request_stop=!1,d.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const b=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,b-50)}}};function uy(d,r){const s=new Ot(d),a=s.destroy.bind(s);let f=!1;return s.destroy=()=>{if(!f){f=!0;try{a()}catch{}}},s.setOnEnd(()=>{f||r()}),s._isDestroyed=()=>f,s}function dy({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let f=null,_=null;function C(){if(!d||f)return f;const H={...Gp,...r||{}};return f=uy(H,()=>{a()}),f}function R(){if(f){try{f.interrupt?.(),f.destroy?.()}catch{}f=null}}function b(H){const se=C();if(se)try{se.feed(H)}catch(ve){s("feedAudio: player.feed() failed",ve),a()}}function U(){if(!f){a();return}try{f.setRequestStop(),f.playingBufferNode||f.scheduledBufferNode||a()}catch(H){s("requestStop: setRequestStop() failed",H),a()}}function z(){R()}function re(){if(f)try{const H=f.audioCtx;H?.state==="running"&&H.suspend()}catch(H){s("pauseAudioPlayback: audioCtx.suspend() failed",H)}}async function K(){const H=C();if(H)try{const se=H.audioCtx;se?.state==="suspended"&&await se.resume()}catch(se){s("resumeAudioPlayback: audioCtx.resume() failed",se)}}function ie(H){_=H||null}function J(){return _}function Y(){return f?f._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:C,destroyPcmPlayer:R,feedAudio:b,requestStop:U,interruptPlayback:z,pauseAudioPlayback:re,resumeAudioPlayback:K,attachAudioElement:ie,getAudioElement:J,isDestroyed:Y}}function cy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:C,onPlaybackComplete:R}=d,b=oe.useCallback((...K)=>{_&&console.log("[RqmiiSDK]",...K)},[_]),U=oe.useRef(null),z=oe.useRef(null),re=oe.useRef(null);return U.current||(U.current=oy({wsUrl:r,log:b})),z.current||(z.current=dy({enableAudio:a,pcmOptions:f,log:b,onPlaybackComplete:R})),re.current||(re.current=pg({restUrl:s,log:b,withCredentials:C})),oe.useEffect(()=>()=>{U.current?.cleanupSocket(),z.current?.destroyPcmPlayer()},[]),{socketMgrRef:U,audioMgrRef:z,sessionMgrRef:re,log:b}}function eo(d){return String(d||"").toLowerCase().replaceAll("-","_")}function hy(d){if(!d)return null;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(typeof d=="object"&&d!==null){const r=d;if(r.buffer instanceof ArrayBuffer){const s=d,a=Number.isInteger(s.byteOffset)?s.byteOffset:0,f=Number.isInteger(s.byteLength)?s.byteLength:s.buffer.byteLength-a;return new Uint8Array(s.buffer,a,f)}if(r.type==="Buffer"&&Array.isArray(r.data))return new Uint8Array(r.data)}try{return new Uint8Array(d)}catch{return null}}function py(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:f,sessionAgentTypeRef:_,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:b,clientToolsRef:U,audioMgrRef:z,enableAudio:re,cbRefs:K,eventsEmitter:ie}=d,J=_r,Y=z.current;r.on(J.DISCONNECT,H=>{if(s({type:"SET_CONNECTION_STATE",payload:ft.IDLE}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onDisconnect?.(H),H==="io server disconnect"||H==="io client disconnect"||R.current){s({type:"SET_CONNECTION_STATE",payload:ft.ENDED});return}s({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),s({type:"SET_ERROR",payload:"Connection lost"})}),r.on(J.SESSION_READY,H=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),H?.agentType&&s({type:"UPDATE_SESSION",payload:{agentType:eo(H.agentType)}})}),r.on(J.SESSION_JOINED,()=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null})}),r.on(J.SESSION_TERMINATED,()=>{Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onSessionTerminated?.(),r.disconnect()}),r.on(J.TRANSCRIPT,H=>{const se=H||null;s({type:"SET_TRANSCRIPT",payload:se}),se?.is_final&&se?.text?.trim()&&(s({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:se.text.trim(),timestamp:new Date().toISOString()}}),s({type:"SET_PARTIAL_TRANSCRIPT",payload:null})),ie.emit("transcript",se??void 0),ie.emit("partial_transcript",void 0)}),r.on(J.PARTIAL_TRANSCRIPT,H=>{const se=typeof H=="string"?H:H?.text;if(typeof se=="string"&&se.length===0)return;const ve=H||null;s({type:"SET_PARTIAL_TRANSCRIPT",payload:ve}),ie.emit("partial_transcript",ve??void 0)}),r.on(J.AGENT_RESPONSE_CHUNK,H=>{const{id:se,text:ve}=b.current.addChunk(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==se),{id:se,role:"assistant",text:ve,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(J.AGENT_RESPONSE,H=>{const{id:se,text:ve}=b.current.consume(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==se),{id:se,role:"assistant",text:ve,streaming:!1,timestamp:new Date().toISOString()}]})}),r.on(J.AVATAR_SPEAKING,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!0})}),r.on(J.AVATAR_SPEAKING_DONE,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!1})}),r.on(J.AGENT_AUDIO_CHUNK,H=>{if(!re||C.current)return;const se=eo(_.current);if(se==="cloud_avatar"||se==="desktop_avatar"||se==="text")return;const ve=hy(H?.audio);ve&&(Y.feedAudio(ve),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(J.AGENT_AUDIO_COMPLETE,()=>{if(!re)return;const H=eo(_.current);H==="cloud_avatar"||H==="desktop_avatar"||H==="text"||Y.requestStop()}),r.on(J.INTERRUPTED,()=>{const H=!Y.isDestroyed();C.current=!1,Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),H&&r.connected&&r.emit(J.AUDIO_PLAYBACK_COMPLETE,{session_id:f.current})}),r.on(J.AUTH_ERROR,H=>{s({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),s({type:"SET_ERROR",payload:H?.message||"Authentication error"})}),r.on(J.ERROR,H=>{const se=H?.code;if(!(se==="TTS_ERROR"||se==="STT_ERROR")){if(se==="INSUFFICIENT_CREDITS"){s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:H?.message||"Insufficient credits to process this request."}}),K.current.onError?.(H);return}s({type:"SET_ERROR",payload:H?.message||H?.detail||"Server error"}),K.current.onError?.(H)}}),r.on(J.SESSION_EXPIRED,H=>{s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onSessionExpired?.(H)}),r.on(J.CREDITS_EXHAUSTED,()=>{s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),R.current=!0;try{r.disconnect()}catch{}}),r.on(J.SESSION_STATE_CHANGED,H=>{H?.state&&s({type:"SET_SESSION_STATE",payload:H.state})}),r.on(J.LANGUAGE_CHANGED,H=>{const se=H?.language;se&&ie.emit("language_changed",{language:se})}),r.on(J.CLIENT_TOOL_REQUEST,H=>{const se=H?.executionId,ve=H?.toolName,de=H?.parameters??{},he=H?.waitForResponse!==!1;if(!ve)return;const pe=U.current[ve];pe&&(he&&se?pe(de).then(ce=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:se,result:ce})}).catch(ce=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:se,result:{error:ce instanceof Error?ce.message:String(ce)}})}):pe(de).catch(()=>{}))})}class sf{listeners=new Map;on(r,s){return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(s),()=>this.off(r,s)}once(r,s){const a=((...f)=>{this.off(r,a),s(...f)});return this.on(r,a)}off(r,s){this.listeners.get(r)?.delete(s)}emit(r,s){const a=this.listeners.get(r);if(a)for(const f of a)try{f(s)}catch{}}removeAllListeners(){this.listeners.clear()}}const nf=oe.createContext(null);function af({children:d,wsUrl:r,restUrl:s,enableAudio:a=!0,pcmOptions:f,debug:_=!1,heartbeatIntervalSeconds:C=15,withCredentials:R=!1,onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re}){const[K,ie]=oe.useReducer(hp,po),J=oe.useRef(K),Y=oe.useCallback(xe=>{J.current=hp(J.current,xe),ie(xe)},[]),H=oe.useRef(!1),se=oe.useRef(cg()),ve=oe.useRef(null),de=oe.useRef(po.session.agentType),he=oe.useRef(!1),pe=oe.useRef(new sf),ce=oe.useRef({}),Ke=oe.useRef({onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re});oe.useEffect(()=>{Ke.current={onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re}},[b,U,z,re]),oe.useEffect(()=>{de.current=K.session.agentType},[K.session.agentType]),oe.useEffect(()=>{ve.current=K.session.sessionId},[K.session.sessionId]);const fe=oe.useCallback(()=>{Y({type:"SET_AUDIO_PLAYING",payload:!1});const xe=Je.current?.getSocket();xe?.connected&&xe.emit(_r.AUDIO_PLAYBACK_COMPLETE,{session_id:ve.current})},[]),{socketMgrRef:Je,audioMgrRef:Ge,sessionMgrRef:ot}=cy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:R,onPlaybackComplete:fe}),Ze=oe.useCallback(xe=>{py({socket:xe,dispatch:Y,stateRef:J,sessionIdRef:ve,sessionAgentTypeRef:de,interruptedRef:he,manualDisconnectRef:H,chunkAccumulatorRef:se,clientToolsRef:ce,audioMgrRef:{current:Ge.current},enableAudio:a,cbRefs:Ke,eventsEmitter:pe.current})},[a]),it=oe.useCallback(({authPayload:xe,queryToken:Qe})=>new Promise((Nt,nr)=>{Je.current?.cleanupSocket();const It=Je.current.connectSocketRaw({authPayload:xe,queryToken:Qe});Ze(It),It.once("connect",()=>{Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTED}),Y({type:"SET_ERROR",payload:null}),Nt(It)}),It.once("connect_error",Yr=>{Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Yr?.message||"Connection error"}),nr(Yr)})}),[Ze]),tt=oe.useCallback(({keepManualDisconnect:xe=!1}={})=>{H.current=!0,he.current=!1,se.current.clear(),Ge.current.destroyPcmPlayer(),Je.current.cleanupSocket(),xe||(H.current=!1),Y({type:"HARD_RESET"})},[]),Wt=oe.useCallback(async({apiKey:xe,publicChatId:Qe,agentId:Nt,userId:nr,language:It="en",clientTools:Yr,config:hn}={})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!xe&&!Qe&&!Nt)throw new Error("Provide one of apiKey, publicChatId, or agentId");tt(),ce.current=Yr??{},Y({type:"SET_CONNECTION_STATE",payload:ft.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const ls=hg();let ct;try{ct=await ot.current.initializeSession({apiKey:xe,publicChatId:Qe,agentId:Nt,userId:nr,language:It,timezone:ls,config:hn})}catch($r){const Lt=$r;throw Lt.status===401||Lt.status===403?(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Authentication failed"})):Lt.status===402?(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:Lt.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED})):Lt.status===429?(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Too many requests. Please try again later."})):(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Failed to initialize session"})),$r}const Ut=ct;Y({type:"UPDATE_SESSION",payload:{sessionId:Ut.session_id,agentType:Ut.streaming_url?di.CLOUD_AVATAR:K.session.agentType,streamingUrl:Ut.streaming_url||null,uniqueId:Ut.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Ut.streaming_url?Zt.CONNECTING:Zt.IDLE,error:null}}),H.current=!0;try{await it({authPayload:{token:Ut.session_token},queryToken:Ut.session_token}),H.current=!1}catch($r){throw H.current=!1,$r}return ct},[it,tt,r,K.session.agentType]),xt=oe.useCallback(async({uniqueId:xe})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!xe)throw new Error("uniqueId is required");tt(),Y({type:"SET_CONNECTION_STATE",payload:ft.INITIALIZING}),Y({type:"SET_ERROR",payload:null});let Qe;try{Qe=await ot.current.joinDesktopSession({uniqueId:xe})}catch(nr){const It=nr;throw(It.status===401||It.status===403)&&(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Authentication failed"})),It.status===402&&(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:It.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED})),It.status===429&&(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Too many requests. Please try again later."})),nr}const Nt=Qe;Y({type:"UPDATE_SESSION",payload:{sessionId:Nt.session_id,uniqueId:xe,role:"user",agentType:di.DESKTOP_AVATAR}}),Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Zt.IDLE,error:null}}),H.current=!0;try{await it({authPayload:{token:Nt.session_token},queryToken:Nt.session_token}),H.current=!1}catch(nr){throw H.current=!1,nr}return Qe},[it,tt,r]),je=oe.useCallback(()=>tt({keepManualDisconnect:!0}),[tt]),qe=oe.useCallback(async()=>{const xe=Je.current?.getSocket();return xe&&K.isConnected&&(xe.emit("end_session"),await new Promise(Qe=>setTimeout(Qe,150))),je(),{success:!0}},[je,K.isConnected]),st=oe.useCallback(()=>{const xe=Je.current?.getSocket();xe?.connected?xe.emit("end_session"):(Y({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),Y({type:"SET_SESSION_READY",payload:!1}))},[]),ze=oe.useCallback((xe,Qe={})=>{const Nt=Je.current?.getSocket();return!Nt||!K.isConnected?!1:(Nt.emit(xe,Qe),!0)},[K.isConnected]),At=oe.useCallback(xe=>!xe||!String(xe).trim()?!1:(Y({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(xe),timestamp:new Date().toISOString()}}),ze(_r.USER_MESSAGE,{message:String(xe)})),[ze]),sr=oe.useCallback((xe,Qe)=>{!Qe||!String(Qe).trim()||Y({type:"ADD_MESSAGE",payload:{id:`${xe}-${Date.now()}`,role:xe,text:String(Qe),timestamp:new Date().toISOString()}})},[]),Hr=oe.useCallback(xe=>!xe||!String(xe).trim()?!1:ze(_r.USER_MESSAGE,{message:String(xe)}),[ze]),Us=oe.useCallback(xe=>ze(_r.AUDIO_CHUNK,{audio:xe}),[ze]),Kr=oe.useCallback(()=>ze(_r.AUDIO_END,{}),[ze]),jr=oe.useCallback(()=>(he.current=!0,Ge.current.interruptPlayback(),Y({type:"SET_AUDIO_PLAYING",payload:!1}),ze(_r.INTERRUPT,{})),[ze]),Fs=oe.useCallback(()=>ze(_r.CLEAR_SESSION_HISTORY,{}),[ze]),rt=oe.useCallback(xe=>xe?ze(_r.CHANGE_SESSION_LANGUAGE,{language:xe}):!1,[ze]),Tr=oe.useCallback((xe={})=>ze(_r.CLIENT_READY,xe),[ze]),lt=oe.useCallback(()=>{se.current.clear(),Y({type:"SET_MESSAGES",payload:[]})},[]),Qr=oe.useCallback(()=>Ge.current.resumeAudioPlayback(),[]),er=oe.useCallback(()=>Ge.current.pauseAudioPlayback(),[]),Er=oe.useCallback(xe=>Ge.current.attachAudioElement(xe),[]),gt=oe.useCallback((xe,Qe=null)=>{Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:xe,error:Qe?String(Qe):null}})},[]),yt=oe.useCallback(async xe=>{if(!s)throw new Error("Missing restUrl in RqmiiAgentProvider");try{const Qe=await ot.current.fetchAgentConfig(xe);return Y({type:"SET_AGENT_CONFIG",payload:Qe}),Qe}catch(Qe){throw Y({type:"SET_AGENT_CONFIG",payload:null}),Qe}},[s]),Ct=oe.useCallback(xe=>{ce.current={...ce.current,...xe}},[]),kt=oe.useCallback(xe=>{const Qe=xe.sessionId||ve.current;return Qe?ot.current.submitFeedback({sessionId:Qe,rating:xe.rating,feedback:xe.feedback,endedBy:xe.endedBy}):Promise.reject(new Error("No session id available for feedback"))},[]),Xr=oe.useMemo(()=>dg(K.sessionState),[K.sessionState]),os=oe.useMemo(()=>({...K,...Xr,initializeSession:Wt,joinDesktopSession:xt,disconnect:je,terminateSession:qe,endSession:st,emit:ze,sendTextMessage:At,addLocalMessage:sr,emitUserMessage:Hr,sendAudioChunk:Us,endAudioStream:Kr,interrupt:jr,clearSessionHistory:Fs,changeSessionLanguage:rt,signalClientReady:Tr,clearMessages:lt,resumeAudioPlayback:Qr,pauseAudioPlayback:er,attachAudioElement:Er,fetchAgentConfig:yt,submitFeedback:kt,setCloudStreamState:gt,registerClientTools:Ct,events:pe.current,audioElement:Ge.current?.getAudioElement()??null,socket:Je.current?.getSocket()??null}),[K,Xr,Wt,xt,je,qe,st,ze,At,sr,Hr,Us,Kr,jr,Fs,rt,Tr,lt,Qr,er,Er,gt,Ct,kt]);return Jt.jsx(nf.Provider,{value:os,children:d})}function dn(){const d=oe.useContext(nf);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function of(){const d=dn();return{connectionState:d.connectionState,isConnected:d.isConnected,isSessionReady:d.isSessionReady,error:d.error,session:d.session,creditExhausted:d.creditExhausted,creditError:d.creditError,sessionState:d.sessionState,isSessionTerminated:d.isSessionTerminated,isSessionTerminating:d.isSessionTerminating,isAgentThinking:d.isAgentThinking,isAgentSpeaking:d.isAgentSpeaking,isToolExecuting:d.isToolExecuting,agentConfig:d.agentConfig,initializeSession:d.initializeSession,joinDesktopSession:d.joinDesktopSession,disconnect:d.disconnect,terminateSession:d.terminateSession,endSession:d.endSession,interrupt:d.interrupt,clearSessionHistory:d.clearSessionHistory,changeSessionLanguage:d.changeSessionLanguage,signalClientReady:d.signalClientReady,fetchAgentConfig:d.fetchAgentConfig,submitFeedback:d.submitFeedback,registerClientTools:d.registerClientTools}}function fy(){const d=dn();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function my(){const d=dn();return{sendAudioChunk:d.sendAudioChunk,endAudioStream:d.endAudioStream,isAudioPlaying:d.isAudioPlaying,transcript:d.transcript,partialTranscript:d.partialTranscript,interrupt:d.interrupt,resumeAudioPlayback:d.resumeAudioPlayback,pauseAudioPlayback:d.pauseAudioPlayback,attachAudioElement:d.attachAudioElement}}function lf(){const d=dn(),r=d.cloudStream?.state||Zt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===di.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===di.DESKTOP_AVATAR,cloudStreamState:r,cloudStreamError:d.cloudStream?.error||null,isCloudStreamConnected:r===Zt.CONNECTED,isCloudStreamLoading:r===Zt.CONNECTING||r===Zt.LOADING,setCloudStreamState:d.setCloudStreamState}}var to={},ro={},ei={},wp;function uf(){if(wp)return ei;wp=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let s="/";return r&&(s=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),ei.baseAssetPath=s,ei}var ti={},vp;function Io(){if(vp)return ti;vp=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return ti.defaultModelFetcher=d,ti}var Fr={},ri={},_p;function ci(){if(_p)return ri;_p=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return ri.log={error:d("error"),debug:d("debug"),warn:d("warn")},ri}var si={},bp;function qi(){if(bp)return si;bp=1,Object.defineProperty(si,"__esModule",{value:!0}),si.Message=void 0;var d;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(d||(si.Message=d={})),si}var Sp;function Mo(){if(Sp)return Fr;Sp=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.FrameProcessor=Fr.validateOptions=Fr.defaultFrameProcessorOptions=void 0;const d=ci(),r=qi();Fr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function s(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&d.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&d.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&d.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&d.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&d.log.error("minSpeechMs should be positive")}Fr.validateOptions=s;const a=C=>{const R=C.reduce((U,z)=>(U.push(U.at(-1)+z.length),U),[0]),b=new Float32Array(R.at(-1));return C.forEach((U,z)=>{const re=R[z];b.set(U,re)}),b};function f(C,R){const b=Math.floor(C.redemptionMs/R),U=Math.floor(C.preSpeechPadMs/R),z=Math.floor(C.minSpeechMs/R);return{redemptionFrames:b,preSpeechPadFrames:U,minSpeechFrames:z}}class _{constructor(R,b,U,z){this.modelProcessFunc=R,this.modelResetFunc=b,this.options=U,this.msPerFrame=z,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=J=>{this.options={...this.options,...J};const{redemptionFrames:Y,preSpeechPadFrames:H,minSpeechFrames:se}=f(this.options,this.msPerFrame);this.redemptionFrames=Y,this.preSpeechPadFrames=H,this.minSpeechFrames=se},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=J=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(J):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=J=>{const Y=this.audioBuffer;this.audioBuffer=[];const H=this.speaking;if(this.reset(),H)if(Y.reduce((ve,de)=>de.isSpeech?ve+1:ve,0)>=this.minSpeechFrames){const ve=a(Y.map(de=>de.frame));J({msg:r.Message.SpeechEnd,audio:ve})}else J({msg:r.Message.VADMisfire});return{}},this.process=async(J,Y)=>{if(!this.active)return;const H=await this.modelProcessFunc(J),se=H.isSpeech>=this.options.positiveSpeechThreshold;if(Y({probs:H,msg:r.Message.FrameProcessed,frame:J}),this.audioBuffer.push({frame:J,isSpeech:se}),se&&(this.speechFrameCount++,this.redemptionCounter=0),se&&!this.speaking&&(this.speaking=!0,Y({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,Y({msg:r.Message.SpeechRealStart})),H.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const ve=this.audioBuffer;if(this.audioBuffer=[],ve.reduce((he,pe)=>pe.isSpeech?he+1:he,0)>=this.minSpeechFrames){const he=a(ve.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:he})}else Y({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:re,preSpeechPadFrames:K,minSpeechFrames:ie}=f(this.options,this.msPerFrame);this.redemptionFrames=re,this.preSpeechPadFrames=K,this.minSpeechFrames=ie,this.reset()}}return Fr.FrameProcessor=_,Fr}var Vr={};function ur(d){throw new Error('Could not dynamically require "'+d+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
|
|
1
|
+
"use strict";const oe=require("react"),Jt=require("react/jsx-runtime"),di={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},_r={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",LANGUAGE_CHANGED:"language_changed",CLIENT_READY:"client_ready",CLIENT_TOOL_REQUEST:"client_tool_request",CLIENT_TOOL_RESULT:"client_tool_result",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete"},ft={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",FAILED:"failed",ENDED:"ended"},Zt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Bs={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},Gp={encoding:"16bitInt",channels:1,sampleRate:16e3},po={connectionState:ft.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:Bs.IDLE,cloudStream:{state:Zt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null,agentConfig:null};function hp(d,r){switch(r.type){case"SET_CONNECTION_STATE":return{...d,connectionState:r.payload,isConnected:r.payload===ft.CONNECTED};case"SET_ERROR":return{...d,error:r.payload};case"SET_CLOUD_STREAM_STATE":return{...d,cloudStream:r.payload};case"SET_SESSION_STATE":return{...d,sessionState:r.payload};case"UPDATE_SESSION":return{...d,session:{...d.session,...r.payload}};case"ADD_MESSAGE":return{...d,messages:[...d.messages,r.payload]};case"SET_AUDIO_PLAYING":return{...d,isAudioPlaying:r.payload};case"SET_AVATAR_SPEAKING":return{...d,isAvatarSpeaking:r.payload};case"SET_CREDIT_EXHAUSTED":return{...d,creditExhausted:r.payload.exhausted,creditError:r.payload.error};case"SET_TRANSCRIPT":return{...d,transcript:r.payload};case"SET_PARTIAL_TRANSCRIPT":return{...d,partialTranscript:r.payload};case"SET_MESSAGES":return{...d,messages:r.payload};case"SET_SESSION_READY":return{...d,isSessionReady:r.payload};case"SET_AGENT_CONFIG":return{...d,agentConfig:r.payload};case"HARD_RESET":return po;case"REPLACE_STATE":return r.payload;default:return d}}function dg(d){return{isSessionTerminated:d===Bs.TERMINATED,isSessionTerminating:d===Bs.TERMINATING,isAgentThinking:d===Bs.AGENT_THINKING,isAgentSpeaking:d===Bs.AGENT_SPEAKING,isToolExecuting:d===Bs.TOOL_EXECUTING}}function cg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,_=`${d.get(a)||""}${s||""}`;return d.set(a,_),{id:a,text:_}},consume(r,s=""){const a=r||`request-${Date.now()}`,f=d.get(a)||s||"";return d.delete(a),{id:a,text:f}},clear(){d.clear()}}}function hg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function Ii(d){if(!d?.ok){let r=`HTTP ${d.status}`;try{const f=await d.json();r=f?.detail||f?.message||r}catch{}const s=new Error(r);throw s.status=d.status,s}return d.json()}function pg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function f({apiKey:b,publicChatId:U,agentId:z,userId:re,language:K="en",timezone:ie,config:J}={}){a();const Y={...b?{api_key:b}:{},...U?{public_chat_id:U}:{},...z?{agent_id:z}:{},...re?{user_id:re}:{},language:K,...ie?{timezone:ie}:{},...J?{config:J}:{}};r("initializeSession — POST /sessions/init",Y);const H=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y),...s?{credentials:"include"}:{}}),se=await Ii(H);if(!se?.session_id||!se?.session_token)throw new Error("Invalid initialize session response");return se}async function _({uniqueId:b}){a(),r("joinDesktopSession — POST /sessions/join",{uniqueId:b});const U=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:b}),...s?{credentials:"include"}:{}}),z=await Ii(U);if(!z?.session_id||!z?.session_token)throw new Error("Invalid join session response");return z}async function C(b){a(),r("fetchAgentConfig — GET /agent/{publicChatId}",{publicChatId:b});const U=await fetch(`${d}/agent/${encodeURIComponent(b)}`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return Ii(U)}async function R({sessionId:b,rating:U,feedback:z,endedBy:re}){if(a(),!b)throw new Error("sessionId is required");const K={...typeof U=="number"?{rating:U}:{},...z?{feedback:z}:{},...re?{ended_by:re}:{}};r("submitFeedback — PATCH /conversations/{sessionId}/feedback",{sessionId:b,payload:K});const ie=await fetch(`${d}/conversations/${encodeURIComponent(b)}/feedback`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(K),...s?{credentials:"include"}:{}});return Ii(ie)}return{initializeSession:f,joinDesktopSession:_,fetchAgentConfig:C,submitFeedback:R}}const Or=Object.create(null);Or.open="0";Or.close="1";Or.ping="2";Or.pong="3";Or.message="4";Or.upgrade="5";Or.noop="6";const Di=Object.create(null);Object.keys(Or).forEach(d=>{Di[Or[d]]=d});const fo={type:"error",data:"parser error"},qp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Wp=typeof ArrayBuffer=="function",Hp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>qp&&r instanceof Blob?s?a(r):pp(r,a):Wp&&(r instanceof ArrayBuffer||Hp(r))?s?a(r):pp(new Blob([r]),a):a(Or[d]+(r||"")),pp=(d,r)=>{const s=new FileReader;return s.onload=function(){const a=s.result.split(",")[1];r("b"+(a||""))},s.readAsDataURL(d)};function fp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let Ya;function fg(d,r){if(qp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Wp&&(d.data instanceof ArrayBuffer||Hp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oi=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)oi[mp.charCodeAt(d)]=d;const mg=d=>{let r=d.length*.75,s=d.length,a,f=0,_,C,R,b;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const U=new ArrayBuffer(r),z=new Uint8Array(U);for(a=0;a<s;a+=4)_=oi[d.charCodeAt(a)],C=oi[d.charCodeAt(a+1)],R=oi[d.charCodeAt(a+2)],b=oi[d.charCodeAt(a+3)],z[f++]=_<<2|C>>4,z[f++]=(C&15)<<4|R>>2,z[f++]=(R&3)<<6|b&63;return U},gg=typeof ArrayBuffer=="function",Co=(d,r)=>{if(typeof d!="string")return{type:"message",data:Kp(d,r)};const s=d.charAt(0);return s==="b"?{type:"message",data:yg(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},yg=(d,r)=>{if(gg){const s=mg(d);return Kp(s,r)}else return{base64:!0,data:d}},Kp=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},jp="",wg=(d,r)=>{const s=d.length,a=new Array(s);let f=0;d.forEach((_,C)=>{xo(_,!1,R=>{a[C]=R,++f===s&&r(a.join(jp))})})},vg=(d,r)=>{const s=d.split(jp),a=[];for(let f=0;f<s.length;f++){const _=Co(s[f],r);if(a.push(_),_.type==="error")break}return a};function _g(){return new TransformStream({transform(d,r){fg(d,s=>{const a=s.length;let f;if(a<126)f=new Uint8Array(1),new DataView(f.buffer).setUint8(0,a);else if(a<65536){f=new Uint8Array(3);const _=new DataView(f.buffer);_.setUint8(0,126),_.setUint16(1,a)}else{f=new Uint8Array(9);const _=new DataView(f.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(s)})}})}let Ja;function Mi(d){return d.reduce((r,s)=>r+s.length,0)}function Pi(d,r){if(d[0].length===r)return d.shift();const s=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)s[f]=d[0][a++],a===d[0].length&&(d.shift(),a=0);return d.length&&a<d[0].length&&(d[0]=d[0].slice(a)),s}function bg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,f=-1,_=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const b=Pi(s,1);_=(b[0]&128)===128,f=b[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(Mi(s)<2)break;const b=Pi(s,2);f=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(Mi(s)<8)break;const b=Pi(s,8),U=new DataView(b.buffer,b.byteOffset,b.length),z=U.getUint32(0);if(z>Math.pow(2,21)-1){R.enqueue(fo);break}f=z*Math.pow(2,32)+U.getUint32(4),a=3}else{if(Mi(s)<f)break;const b=Pi(s,f);R.enqueue(Co(_?b:Ja.decode(b),r)),a=0}if(f===0||f>d){R.enqueue(fo);break}}}})}const Qp=4;function $t(d){if(d)return Sg(d)}function Sg(d){for(var r in $t.prototype)d[r]=$t.prototype[r];return d}$t.prototype.on=$t.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};$t.prototype.once=function(d,r){function s(){this.off(d,s),r.apply(this,arguments)}return s.fn=r,this.on(d,s),this};$t.prototype.off=$t.prototype.removeListener=$t.prototype.removeAllListeners=$t.prototype.removeEventListener=function(d,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var s=this._callbacks["$"+d];if(!s)return this;if(arguments.length==1)return delete this._callbacks["$"+d],this;for(var a,f=0;f<s.length;f++)if(a=s[f],a===r||a.fn===r){s.splice(f,1);break}return s.length===0&&delete this._callbacks["$"+d],this};$t.prototype.emit=function(d){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),s=this._callbacks["$"+d],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(s){s=s.slice(0);for(var a=0,f=s.length;a<f;++a)s[a].apply(this,r)}return this};$t.prototype.emitReserved=$t.prototype.emit;$t.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};$t.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Vi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,s)=>s(r,0),lr=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Tg="arraybuffer";function Xp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const Eg=lr.setTimeout,$g=lr.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=Eg.bind(lr),d.clearTimeoutFn=$g.bind(lr)):(d.setTimeoutFn=lr.setTimeout.bind(lr),d.clearTimeoutFn=lr.clearTimeout.bind(lr))}const xg=1.33;function Cg(d){return typeof d=="string"?kg(d):Math.ceil((d.byteLength||d.size)*xg)}function kg(d){let r=0,s=0;for(let a=0,f=d.length;a<f;a++)r=d.charCodeAt(a),r<128?s+=1:r<2048?s+=2:r<55296||r>=57344?s+=3:(a++,s+=4);return s}function Yp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Rg(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Ag(d){let r={},s=d.split("&");for(let a=0,f=s.length;a<f;a++){let _=s[a].split("=");r[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return r}class Ig extends Error{constructor(r,s,a){super(r),this.description=s,this.context=a,this.type="TransportError"}}class ko extends $t{constructor(r){super(),this.writable=!1,Gi(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,s,a){return super.emitReserved("error",new Ig(r,s,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const s=Co(r,this.socket.binaryType);this.onPacket(s)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,s={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const s=Rg(r);return s.length?"?"+s:""}}class Mg extends ko{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const s=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||s()})),this.writable||(a++,this.once("drain",function(){--a||s()}))}else s()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const s=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};vg(r,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const r=()=>{this.write([{type:"close"}])};this.readyState==="open"?r():this.once("open",r)}write(r){this.writable=!1,wg(r,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Yp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Jp=!1;try{Jp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Pg=Jp;function Og(){}class Dg extends Mg{constructor(r){if(super(r),typeof location<"u"){const s=location.protocol==="https:";let a=location.port;a||(a=s?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,s){const a=this.request({method:"POST",data:r});a.on("success",s),a.on("error",(f,_)=>{this.onError("xhr post error",f,_)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(s,a)=>{this.onError("xhr poll error",s,a)}),this.pollXhr=r}}class Pr extends $t{constructor(r,s,a){super(),this.createRequest=r,Gi(this,a),this._opts=a,this._method=a.method||"GET",this._uri=s,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const s=Xp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(s);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let f in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(f)&&a.setRequestHeader(f,this._opts.extraHeaders[f])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var f;a.readyState===3&&((f=this._opts.cookieJar)===null||f===void 0||f.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(f){this.setTimeoutFn(()=>{this._onError(f)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Og,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const d="onpagehide"in lr?"pagehide":"unload";addEventListener(d,gp,!1)}}function gp(){for(let d in Pr.requests)Pr.requests.hasOwnProperty(d)&&Pr.requests[d].abort()}const zg=(function(){const d=Zp({xdomain:!1});return d&&d.responseType!==null})();class Lg extends Dg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=zg&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(Zp,this.uri(),r)}}function Zp(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Pg))return new XMLHttpRequest}catch{}if(!r)try{return new lr[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ef=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Bg extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=ef?{}:Xp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,s,a)}catch(f){return this.emitReserved("error",f)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;xo(a,this.supportsBinary,_=>{try{this.doWrite(a,_)}catch{}f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Yp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=lr.WebSocket||lr.MozWebSocket;class Ng extends Bg{createSocket(r,s,a){return ef?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Ug extends ko{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const s=bg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),f=_g();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const _=()=>{a.read().then(({done:R,value:b})=>{R||(this.onPacket(b),_())}).catch(R=>{})};_();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],f=s===r.length-1;this._writer.write(a).then(()=>{f&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const Fg={websocket:Ng,webtransport:Ug,polling:Lg},Vg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Gg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mo(d){if(d.length>8e3)throw"URI too long";const r=d,s=d.indexOf("["),a=d.indexOf("]");s!=-1&&a!=-1&&(d=d.substring(0,s)+d.substring(s,a).replace(/:/g,";")+d.substring(a,d.length));let f=Vg.exec(d||""),_={},C=14;for(;C--;)_[Gg[C]]=f[C]||"";return s!=-1&&a!=-1&&(_.source=r,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=qg(_,_.path),_.queryKey=Wg(_,_.query),_}function qg(d,r){const s=/\/{2,9}/g,a=r.replace(s,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function Wg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,_){f&&(s[f]=_)}),s}const go=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];go&&addEventListener("offline",()=>{zi.forEach(d=>d())},!1);class as extends $t{constructor(r,s){if(super(),this.binaryType=Tg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(s=r,r=null),r){const a=mo(r);s.hostname=a.host,s.secure=a.protocol==="https"||a.protocol==="wss",s.port=a.port,a.query&&(s.query=a.query)}else s.host&&(s.hostname=mo(s.host).host);Gi(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(a=>{const f=a.prototype.name;this.transports.push(f),this._transportsByName[f]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ag(this.opts.query)),go&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const s=Object.assign({},this.opts.query);s.EIO=Qp,s.transport=r,this.id&&(s.sid=this.id);const a=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&as.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const s=this.createTransport(r);s.open(),this.setTransport(s)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){this.readyState="open",as.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const s=new Error("server error");s.code=r.data,this._onError(s);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let a=0;a<this.writeBuffer.length;a++){const f=this.writeBuffer[a].data;if(f&&(s+=Cg(f)),a>0&&s>this._maxPayload)return this.writeBuffer.slice(0,a);s+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Vi(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,s,a){return this._sendPacket("message",r,s,a),this}send(r,s,a){return this._sendPacket("message",r,s,a),this}_sendPacket(r,s,a,f){if(typeof s=="function"&&(f=s,s=void 0),typeof a=="function"&&(f=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const _={type:r,data:s,options:a};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),f&&this.once("flush",f),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},s=()=>{this.off("upgrade",s),this.off("upgradeError",s),r()},a=()=>{this.once("upgrade",s),this.once("upgradeError",s)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(as.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),go&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=zi.indexOf(this._offlineEventListener);a!==-1&&zi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,s),this.writeBuffer=[],this._prevBufferLen=0}}}as.protocol=Qp;class Hg extends as{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let s=this.createTransport(r),a=!1;as.priorWebsocketSuccess=!1;const f=()=>{a||(s.send([{type:"ping",data:"probe"}]),s.once("packet",re=>{if(!a)if(re.type==="pong"&&re.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;as.priorWebsocketSuccess=s.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(z(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{const K=new Error("probe error");K.transport=s.name,this.emitReserved("upgradeError",K)}}))};function _(){a||(a=!0,z(),s.close(),s=null)}const C=re=>{const K=new Error("probe error: "+re);K.transport=s.name,_(),this.emitReserved("upgradeError",K)};function R(){C("transport closed")}function b(){C("socket closed")}function U(re){s&&re.name!==s.name&&_()}const z=()=>{s.removeListener("open",f),s.removeListener("error",C),s.removeListener("close",R),this.off("close",b),this.off("upgrading",U)};s.once("open",f),s.once("error",C),s.once("close",R),this.once("close",b),this.once("upgrading",U),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||s.open()},200):s.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const s=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&s.push(r[a]);return s}}let Kg=class extends Hg{constructor(r,s={}){const a=typeof r=="object"?r:s;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(f=>Fg[f]).filter(f=>!!f)),super(r,a)}};function jg(d,r="",s){let a=d;s=s||typeof location<"u"&&location,d==null&&(d=s.protocol+"//"+s.host),typeof d=="string"&&(d.charAt(0)==="/"&&(d.charAt(1)==="/"?d=s.protocol+d:d=s.host+d),/^(https?|wss?):\/\//.test(d)||(typeof s<"u"?d=s.protocol+"//"+d:d="https://"+d),a=mo(d)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const _=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+_+":"+a.port+r,a.href=a.protocol+"://"+_+(s&&s.port===a.port?"":":"+a.port),a}const Qg=typeof ArrayBuffer=="function",Xg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,tf=Object.prototype.toString,Yg=typeof Blob=="function"||typeof Blob<"u"&&tf.call(Blob)==="[object BlobConstructor]",Jg=typeof File=="function"||typeof File<"u"&&tf.call(File)==="[object FileConstructor]";function Ro(d){return Qg&&(d instanceof ArrayBuffer||Xg(d))||Yg&&d instanceof Blob||Jg&&d instanceof File}function Li(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let s=0,a=d.length;s<a;s++)if(Li(d[s]))return!0;return!1}if(Ro(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Li(d.toJSON(),!0);for(const s in d)if(Object.prototype.hasOwnProperty.call(d,s)&&Li(d[s]))return!0;return!1}function Zg(d){const r=[],s=d.data,a=d;return a.data=yo(s,r),a.attachments=r.length,{packet:a,buffers:r}}function yo(d,r){if(!d)return d;if(Ro(d)){const s={_placeholder:!0,num:r.length};return r.push(d),s}else if(Array.isArray(d)){const s=new Array(d.length);for(let a=0;a<d.length;a++)s[a]=yo(d[a],r);return s}else if(typeof d=="object"&&!(d instanceof Date)){const s={};for(const a in d)Object.prototype.hasOwnProperty.call(d,a)&&(s[a]=yo(d[a],r));return s}return d}function ey(d,r){return d.data=wo(d.data,r),delete d.attachments,d}function wo(d,r){if(!d)return d;if(d&&d._placeholder===!0){if(typeof d.num=="number"&&d.num>=0&&d.num<r.length)return r[d.num];throw new Error("illegal attachments")}else if(Array.isArray(d))for(let s=0;s<d.length;s++)d[s]=wo(d[s],r);else if(typeof d=="object")for(const s in d)Object.prototype.hasOwnProperty.call(d,s)&&(d[s]=wo(d[s],r));return d}const ty=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Ye;(function(d){d[d.CONNECT=0]="CONNECT",d[d.DISCONNECT=1]="DISCONNECT",d[d.EVENT=2]="EVENT",d[d.ACK=3]="ACK",d[d.CONNECT_ERROR=4]="CONNECT_ERROR",d[d.BINARY_EVENT=5]="BINARY_EVENT",d[d.BINARY_ACK=6]="BINARY_ACK"})(Ye||(Ye={}));class ry{constructor(r){this.replacer=r}encode(r){return(r.type===Ye.EVENT||r.type===Ye.ACK)&&Li(r)?this.encodeAsBinary({type:r.type===Ye.EVENT?Ye.BINARY_EVENT:Ye.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let s=""+r.type;return(r.type===Ye.BINARY_EVENT||r.type===Ye.BINARY_ACK)&&(s+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(s+=r.nsp+","),r.id!=null&&(s+=r.id),r.data!=null&&(s+=JSON.stringify(r.data,this.replacer)),s}encodeAsBinary(r){const s=Zg(r),a=this.encodeAsString(s.packet),f=s.buffers;return f.unshift(a),f}}class Ao extends $t{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let s;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(r);const a=s.type===Ye.BINARY_EVENT;a||s.type===Ye.BINARY_ACK?(s.type=a?Ye.EVENT:Ye.ACK,this.reconstructor=new sy(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(Ro(r)||r.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(r),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let s=0;const a={type:Number(r.charAt(0))};if(Ye[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===Ye.BINARY_EVENT||a.type===Ye.BINARY_ACK){const _=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(_,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!ny(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(s+1)==="/"){const _=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(_,s)}else a.nsp="/";const f=r.charAt(s+1);if(f!==""&&Number(f)==f){const _=s+1;for(;++s;){const C=r.charAt(s);if(C==null||Number(C)!=C){--s;break}if(s===r.length)break}a.id=Number(r.substring(_,s+1))}if(r.charAt(++s)){const _=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,_))a.data=_;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,s){switch(r){case Ye.CONNECT:return yp(s);case Ye.DISCONNECT:return s===void 0;case Ye.CONNECT_ERROR:return typeof s=="string"||yp(s);case Ye.EVENT:case Ye.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&ty.indexOf(s[0])===-1);case Ye.ACK:case Ye.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class sy{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const s=ey(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ny=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function yp(d){return Object.prototype.toString.call(d)==="[object Object]"}const iy=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:ry,get PacketType(){return Ye}},Symbol.toStringTag,{value:"Module"}));function br(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const ay=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class rf extends $t{constructor(r,s,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=s,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[br(r,"open",this.onopen.bind(this)),br(r,"packet",this.onpacket.bind(this)),br(r,"error",this.onerror.bind(this)),br(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...s){var a,f,_;if(ay.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(s.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;const C={type:Ye.EVENT,data:s};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){const z=this.ids++,re=s.pop();this._registerAckCallback(z,re),C.id=z}const R=(f=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||f===void 0?void 0:f.writable,b=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!R||(b?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,s){var a;const f=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(f===void 0){this.acks[r]=s;return}const _=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);s.call(this,new Error("operation has timed out"))},f),C=(...R)=>{this.io.clearTimeoutFn(_),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,f)=>{const _=(C,R)=>C?f(C):a(R);_.withError=!0,s.push(_),this.emit(r,...s)})}_addToQueue(r){let s;typeof r[r.length-1]=="function"&&(s=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((f,..._)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(f)):(this._queue.shift(),s&&s(null,..._)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const s=this._queue[0];s.pending&&!r||(s.pending=!0,s.tryCount++,this.flags=s.flags,this.emit.apply(this,s.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Ye.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,s){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Ye.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ye.EVENT:case Ye.BINARY_EVENT:this.onevent(r);break;case Ye.ACK:case Ye.BINARY_ACK:this.onack(r);break;case Ye.DISCONNECT:this.ondisconnect();break;case Ye.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const s=r.data||[];r.id!=null&&s.push(this.ack(r.id)),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const s=this._anyListeners.slice();for(const a of s)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const s=this;let a=!1;return function(...f){a||(a=!0,s.packet({type:Ye.ACK,id:r,data:f}))}}onack(r){const s=this.acks[r.id];typeof s=="function"&&(delete this.acks[r.id],s.withError&&r.data.unshift(null),s.apply(this,r.data))}onconnect(r,s){this.id=r,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ye.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const s=this._anyListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const s=this._anyOutgoingListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const s=this._anyOutgoingListeners.slice();for(const a of s)a.apply(this,r.data)}}}function un(d){d=d||{},this.ms=d.min||100,this.max=d.max||1e4,this.factor=d.factor||2,this.jitter=d.jitter>0&&d.jitter<=1?d.jitter:0,this.attempts=0}un.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),s=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-s:d+s}return Math.min(d,this.max)|0};un.prototype.reset=function(){this.attempts=0};un.prototype.setMin=function(d){this.ms=d};un.prototype.setMax=function(d){this.max=d};un.prototype.setJitter=function(d){this.jitter=d};class vo extends $t{constructor(r,s){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(s=r,r=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,Gi(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((a=s.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new un({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=r;const f=s.parser||iy;this.encoder=new f.Encoder,this.decoder=new f.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var s;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(s=this.backoff)===null||s===void 0||s.setMin(r),this)}randomizationFactor(r){var s;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(s=this.backoff)===null||s===void 0||s.setJitter(r),this)}reconnectionDelayMax(r){var s;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(s=this.backoff)===null||s===void 0||s.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new Kg(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=br(s,"open",function(){a.onopen(),r&&r()}),_=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=br(s,"error",_);if(this._timeout!==!1){const R=this._timeout,b=this.setTimeoutFn(()=>{f(),_(new Error("timeout")),s.close()},R);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(f),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(br(r,"ping",this.onping.bind(this)),br(r,"data",this.ondata.bind(this)),br(r,"error",this.onerror.bind(this)),br(r,"close",this.onclose.bind(this)),br(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(s){this.onclose("parse error",s)}}ondecoded(r){Vi(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,s){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new rf(this,r,s),this.nsps[r]=a),a}_destroy(r){const s=Object.keys(this.nsps);for(const a of s)if(this.nsps[a].active)return;this._close()}_packet(r){const s=this.encoder.encode(r);for(let a=0;a<s.length;a++)this.engine.write(s[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,s){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const s=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(f=>{f?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",f)):r.onreconnect()}))},s);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const Zn={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=jg(d,r.path||"/socket.io"),a=s.source,f=s.id,_=s.path,C=Zn[f]&&_ in Zn[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let b;return R?b=new vo(a,r):(Zn[f]||(Zn[f]=new vo(a,r)),b=Zn[f]),s.query&&!r.query&&(r.query=s.queryKey),b.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:rf,io:Bi,connect:Bi});function oy({wsUrl:d,log:r}){let s=null;function a({authPayload:C,queryToken:R}){const b=Bi(d,{transports:["polling"],timeout:2e4,reconnection:!1,auth:C,query:R?{token:R}:void 0});return s=b,b}function f(){if(s){try{s.removeAllListeners(),s.connected?s.disconnect():s.close()}catch{}s=null}}function _(){return s}return{connectSocketRaw:a,cleanupSocket:f,getSocket:_}}const ly=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(_=>r.addEventListener(_,a,!1));function a(){d.resume().then(f)}function f(){s.forEach(_=>r.removeEventListener(_,a))}};function Ot(d){this.init(d)}Ot.prototype.init=function(d){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,d),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Ot.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Ot.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),ly(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Ot.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Ot.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Ot.prototype.feed=function(d){if(this.isTypedArray(d)){d=this.getFormatedValue(d);var r=new Float32Array(this.samples.length+d.length);r.set(this.samples,0),r.set(d,this.samples.length),this.samples=r,this.timeout||this.flush()}};Ot.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),s=new Float32Array(r.length),a;for(a=0;a<r.length;a++)s[a]=r[a]/this.maxValue;return s};Ot.prototype.volume=function(d){this.gainNode.gain.value=d};Ot.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Ot.prototype.getTimestamp=function(d){if(this.playingStartTime>=0){if(!d)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=d/1e3,r}return 0};Ot.prototype.setRequestStop=function(){this.flag_request_stop=!0};Ot.prototype.setOnEnd=function(d){this.onEnd=d};Ot.prototype.interrupt=function(d){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Ot.prototype.ensuredSetTimeout=(function(){let d;return function(r,s){d=performance.now();const a=f=>{f-d>=s?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Ot.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Ot.prototype.flush=function(){if(this.samples.length){var d=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,s=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,_,C,R;for(f=0;f<this.option.channels;f++)for(a=s.getChannelData(f),_=f,R=50,C=0;C<r;C++)a[C]=this.samples[_],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),_+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,d.buffer=s,d.connect(this.gainNode),d.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=d,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=s.duration,this.flag_request_stop)this.flag_request_stop=!1,d.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const b=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,b-50)}}};function uy(d,r){const s=new Ot(d),a=s.destroy.bind(s);let f=!1;return s.destroy=()=>{if(!f){f=!0;try{a()}catch{}}},s.setOnEnd(()=>{f||r()}),s._isDestroyed=()=>f,s}function dy({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let f=null,_=null;function C(){if(!d||f)return f;const H={...Gp,...r||{}};return f=uy(H,()=>{a()}),f}function R(){if(f){try{f.interrupt?.(),f.destroy?.()}catch{}f=null}}function b(H){const se=C();if(se)try{se.feed(H)}catch(ve){s("feedAudio: player.feed() failed",ve),a()}}function U(){if(!f){a();return}try{f.setRequestStop(),f.playingBufferNode||f.scheduledBufferNode||a()}catch(H){s("requestStop: setRequestStop() failed",H),a()}}function z(){R()}function re(){if(f)try{const H=f.audioCtx;H?.state==="running"&&H.suspend()}catch(H){s("pauseAudioPlayback: audioCtx.suspend() failed",H)}}async function K(){const H=C();if(H)try{const se=H.audioCtx;se?.state==="suspended"&&await se.resume()}catch(se){s("resumeAudioPlayback: audioCtx.resume() failed",se)}}function ie(H){_=H||null}function J(){return _}function Y(){return f?f._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:C,destroyPcmPlayer:R,feedAudio:b,requestStop:U,interruptPlayback:z,pauseAudioPlayback:re,resumeAudioPlayback:K,attachAudioElement:ie,getAudioElement:J,isDestroyed:Y}}function cy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:C,onPlaybackComplete:R}=d,b=oe.useCallback((...K)=>{_&&console.log("[RqmiiSDK]",...K)},[_]),U=oe.useRef(null),z=oe.useRef(null),re=oe.useRef(null);return U.current||(U.current=oy({wsUrl:r,log:b})),z.current||(z.current=dy({enableAudio:a,pcmOptions:f,log:b,onPlaybackComplete:R})),re.current||(re.current=pg({restUrl:s,log:b,withCredentials:C})),oe.useEffect(()=>()=>{U.current?.cleanupSocket(),z.current?.destroyPcmPlayer()},[]),{socketMgrRef:U,audioMgrRef:z,sessionMgrRef:re,log:b}}function eo(d){return String(d||"").toLowerCase().replaceAll("-","_")}function hy(d){if(!d)return null;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(typeof d=="object"&&d!==null){const r=d;if(r.buffer instanceof ArrayBuffer){const s=d,a=Number.isInteger(s.byteOffset)?s.byteOffset:0,f=Number.isInteger(s.byteLength)?s.byteLength:s.buffer.byteLength-a;return new Uint8Array(s.buffer,a,f)}if(r.type==="Buffer"&&Array.isArray(r.data))return new Uint8Array(r.data)}try{return new Uint8Array(d)}catch{return null}}function py(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:f,sessionAgentTypeRef:_,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:b,clientToolsRef:U,audioMgrRef:z,enableAudio:re,cbRefs:K,eventsEmitter:ie}=d,J=_r,Y=z.current;r.on(J.DISCONNECT,H=>{if(s({type:"SET_CONNECTION_STATE",payload:ft.IDLE}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onDisconnect?.(H),H==="io server disconnect"||H==="io client disconnect"||R.current){s({type:"SET_CONNECTION_STATE",payload:ft.ENDED});return}s({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),s({type:"SET_ERROR",payload:"Connection lost"})}),r.on(J.SESSION_READY,H=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),H?.agentType&&s({type:"UPDATE_SESSION",payload:{agentType:eo(H.agentType)}})}),r.on(J.SESSION_JOINED,()=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null})}),r.on(J.SESSION_TERMINATED,()=>{Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onSessionTerminated?.(),r.disconnect()}),r.on(J.TRANSCRIPT,H=>{const se=H||null;s({type:"SET_TRANSCRIPT",payload:se}),se?.is_final&&se?.text?.trim()&&(s({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:se.text.trim(),timestamp:new Date().toISOString()}}),s({type:"SET_PARTIAL_TRANSCRIPT",payload:null})),ie.emit("transcript",se??void 0),ie.emit("partial_transcript",void 0)}),r.on(J.PARTIAL_TRANSCRIPT,H=>{const se=typeof H=="string"?H:H?.text;if(typeof se=="string"&&se.length===0)return;const ve=H||null;s({type:"SET_PARTIAL_TRANSCRIPT",payload:ve}),ie.emit("partial_transcript",ve??void 0)}),r.on(J.AGENT_RESPONSE_CHUNK,H=>{const{id:se,text:ve}=b.current.addChunk(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==se),{id:se,role:"assistant",text:ve,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(J.AGENT_RESPONSE,H=>{const{id:se,text:ve}=b.current.consume(H?.requestId,H?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==se),{id:se,role:"assistant",text:ve,streaming:!1,timestamp:new Date().toISOString()}]})}),r.on(J.AVATAR_SPEAKING,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!0})}),r.on(J.AVATAR_SPEAKING_DONE,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!1})}),r.on(J.AGENT_AUDIO_CHUNK,H=>{if(!re||C.current)return;const se=eo(_.current);if(se==="cloud_avatar"||se==="desktop_avatar"||se==="text")return;const ve=hy(H?.audio);ve&&(Y.feedAudio(ve),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(J.AGENT_AUDIO_COMPLETE,()=>{if(!re)return;const H=eo(_.current);H==="cloud_avatar"||H==="desktop_avatar"||H==="text"||Y.requestStop()}),r.on(J.INTERRUPTED,()=>{const H=!Y.isDestroyed();C.current=!1,Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),H&&r.connected&&r.emit(J.AUDIO_PLAYBACK_COMPLETE,{session_id:f.current})}),r.on(J.AUTH_ERROR,H=>{s({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),s({type:"SET_ERROR",payload:H?.message||"Authentication error"})}),r.on(J.ERROR,H=>{const se=H?.code;if(!(se==="TTS_ERROR"||se==="STT_ERROR"||se==="LLM_ERROR")){if(se==="INSUFFICIENT_CREDITS"){s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:H?.message||"Insufficient credits to process this request."}}),K.current.onError?.(H);return}s({type:"SET_ERROR",payload:H?.message||H?.detail||"Server error"}),K.current.onError?.(H)}}),r.on(J.SESSION_EXPIRED,H=>{s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),K.current.onSessionExpired?.(H)}),r.on(J.CREDITS_EXHAUSTED,()=>{s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),s({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),R.current=!0;try{r.disconnect()}catch{}}),r.on(J.SESSION_STATE_CHANGED,H=>{H?.state&&s({type:"SET_SESSION_STATE",payload:H.state})}),r.on(J.LANGUAGE_CHANGED,H=>{const se=H?.language;se&&ie.emit("language_changed",{language:se})}),r.on(J.CLIENT_TOOL_REQUEST,H=>{const se=H?.executionId,ve=H?.toolName,de=H?.parameters??{},he=H?.waitForResponse!==!1;if(!ve)return;const pe=U.current[ve];pe&&(he&&se?pe(de).then(ce=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:se,result:ce})}).catch(ce=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:se,result:{error:ce instanceof Error?ce.message:String(ce)}})}):pe(de).catch(()=>{}))})}class sf{listeners=new Map;on(r,s){return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(s),()=>this.off(r,s)}once(r,s){const a=((...f)=>{this.off(r,a),s(...f)});return this.on(r,a)}off(r,s){this.listeners.get(r)?.delete(s)}emit(r,s){const a=this.listeners.get(r);if(a)for(const f of a)try{f(s)}catch{}}removeAllListeners(){this.listeners.clear()}}const nf=oe.createContext(null);function af({children:d,wsUrl:r,restUrl:s,enableAudio:a=!0,pcmOptions:f,debug:_=!1,heartbeatIntervalSeconds:C=15,withCredentials:R=!1,onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re}){const[K,ie]=oe.useReducer(hp,po),J=oe.useRef(K),Y=oe.useCallback(xe=>{J.current=hp(J.current,xe),ie(xe)},[]),H=oe.useRef(!1),se=oe.useRef(cg()),ve=oe.useRef(null),de=oe.useRef(po.session.agentType),he=oe.useRef(!1),pe=oe.useRef(new sf),ce=oe.useRef({}),Ke=oe.useRef({onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re});oe.useEffect(()=>{Ke.current={onSessionExpired:b,onSessionTerminated:U,onError:z,onDisconnect:re}},[b,U,z,re]),oe.useEffect(()=>{de.current=K.session.agentType},[K.session.agentType]),oe.useEffect(()=>{ve.current=K.session.sessionId},[K.session.sessionId]);const fe=oe.useCallback(()=>{Y({type:"SET_AUDIO_PLAYING",payload:!1});const xe=Je.current?.getSocket();xe?.connected&&xe.emit(_r.AUDIO_PLAYBACK_COMPLETE,{session_id:ve.current})},[]),{socketMgrRef:Je,audioMgrRef:Ge,sessionMgrRef:ot}=cy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:f,debug:_,withCredentials:R,onPlaybackComplete:fe}),Ze=oe.useCallback(xe=>{py({socket:xe,dispatch:Y,stateRef:J,sessionIdRef:ve,sessionAgentTypeRef:de,interruptedRef:he,manualDisconnectRef:H,chunkAccumulatorRef:se,clientToolsRef:ce,audioMgrRef:{current:Ge.current},enableAudio:a,cbRefs:Ke,eventsEmitter:pe.current})},[a]),it=oe.useCallback(({authPayload:xe,queryToken:Qe})=>new Promise((Nt,nr)=>{Je.current?.cleanupSocket();const It=Je.current.connectSocketRaw({authPayload:xe,queryToken:Qe});Ze(It),It.once("connect",()=>{Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTED}),Y({type:"SET_ERROR",payload:null}),Nt(It)}),It.once("connect_error",Yr=>{Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Yr?.message||"Connection error"}),nr(Yr)})}),[Ze]),tt=oe.useCallback(({keepManualDisconnect:xe=!1}={})=>{H.current=!0,he.current=!1,se.current.clear(),Ge.current.destroyPcmPlayer(),Je.current.cleanupSocket(),xe||(H.current=!1),Y({type:"HARD_RESET"})},[]),Wt=oe.useCallback(async({apiKey:xe,publicChatId:Qe,agentId:Nt,userId:nr,language:It="en",clientTools:Yr,config:hn}={})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!xe&&!Qe&&!Nt)throw new Error("Provide one of apiKey, publicChatId, or agentId");tt(),ce.current=Yr??{},Y({type:"SET_CONNECTION_STATE",payload:ft.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const ls=hg();let ct;try{ct=await ot.current.initializeSession({apiKey:xe,publicChatId:Qe,agentId:Nt,userId:nr,language:It,timezone:ls,config:hn})}catch($r){const Lt=$r;throw Lt.status===401||Lt.status===403?(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Authentication failed"})):Lt.status===402?(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:Lt.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED})):Lt.status===429?(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Too many requests. Please try again later."})):(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:Lt.message||"Failed to initialize session"})),$r}const Ut=ct;Y({type:"UPDATE_SESSION",payload:{sessionId:Ut.session_id,agentType:Ut.streaming_url?di.CLOUD_AVATAR:K.session.agentType,streamingUrl:Ut.streaming_url||null,uniqueId:Ut.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Ut.streaming_url?Zt.CONNECTING:Zt.IDLE,error:null}}),H.current=!0;try{await it({authPayload:{token:Ut.session_token},queryToken:Ut.session_token}),H.current=!1}catch($r){throw H.current=!1,$r}return ct},[it,tt,r,K.session.agentType]),xt=oe.useCallback(async({uniqueId:xe})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!xe)throw new Error("uniqueId is required");tt(),Y({type:"SET_CONNECTION_STATE",payload:ft.INITIALIZING}),Y({type:"SET_ERROR",payload:null});let Qe;try{Qe=await ot.current.joinDesktopSession({uniqueId:xe})}catch(nr){const It=nr;throw(It.status===401||It.status===403)&&(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Authentication failed"})),It.status===402&&(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:It.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED})),It.status===429&&(Y({type:"SET_CONNECTION_STATE",payload:ft.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Too many requests. Please try again later."})),nr}const Nt=Qe;Y({type:"UPDATE_SESSION",payload:{sessionId:Nt.session_id,uniqueId:xe,role:"user",agentType:di.DESKTOP_AVATAR}}),Y({type:"SET_CONNECTION_STATE",payload:ft.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Zt.IDLE,error:null}}),H.current=!0;try{await it({authPayload:{token:Nt.session_token},queryToken:Nt.session_token}),H.current=!1}catch(nr){throw H.current=!1,nr}return Qe},[it,tt,r]),je=oe.useCallback(()=>tt({keepManualDisconnect:!0}),[tt]),qe=oe.useCallback(async()=>{const xe=Je.current?.getSocket();return xe&&K.isConnected&&(xe.emit("end_session"),await new Promise(Qe=>setTimeout(Qe,150))),je(),{success:!0}},[je,K.isConnected]),st=oe.useCallback(()=>{const xe=Je.current?.getSocket();xe?.connected?xe.emit("end_session"):(Y({type:"SET_CONNECTION_STATE",payload:ft.ENDED}),Y({type:"SET_SESSION_READY",payload:!1}))},[]),ze=oe.useCallback((xe,Qe={})=>{const Nt=Je.current?.getSocket();return!Nt||!K.isConnected?!1:(Nt.emit(xe,Qe),!0)},[K.isConnected]),At=oe.useCallback(xe=>!xe||!String(xe).trim()?!1:(Y({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(xe),timestamp:new Date().toISOString()}}),ze(_r.USER_MESSAGE,{message:String(xe)})),[ze]),sr=oe.useCallback((xe,Qe)=>{!Qe||!String(Qe).trim()||Y({type:"ADD_MESSAGE",payload:{id:`${xe}-${Date.now()}`,role:xe,text:String(Qe),timestamp:new Date().toISOString()}})},[]),Hr=oe.useCallback(xe=>!xe||!String(xe).trim()?!1:ze(_r.USER_MESSAGE,{message:String(xe)}),[ze]),Us=oe.useCallback(xe=>ze(_r.AUDIO_CHUNK,{audio:xe}),[ze]),Kr=oe.useCallback(()=>ze(_r.AUDIO_END,{}),[ze]),jr=oe.useCallback(()=>(he.current=!0,Ge.current.interruptPlayback(),Y({type:"SET_AUDIO_PLAYING",payload:!1}),ze(_r.INTERRUPT,{})),[ze]),Fs=oe.useCallback(()=>ze(_r.CLEAR_SESSION_HISTORY,{}),[ze]),rt=oe.useCallback(xe=>xe?ze(_r.CHANGE_SESSION_LANGUAGE,{language:xe}):!1,[ze]),Tr=oe.useCallback((xe={})=>ze(_r.CLIENT_READY,xe),[ze]),lt=oe.useCallback(()=>{se.current.clear(),Y({type:"SET_MESSAGES",payload:[]})},[]),Qr=oe.useCallback(()=>Ge.current.resumeAudioPlayback(),[]),er=oe.useCallback(()=>Ge.current.pauseAudioPlayback(),[]),Er=oe.useCallback(xe=>Ge.current.attachAudioElement(xe),[]),gt=oe.useCallback((xe,Qe=null)=>{Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:xe,error:Qe?String(Qe):null}})},[]),yt=oe.useCallback(async xe=>{if(!s)throw new Error("Missing restUrl in RqmiiAgentProvider");try{const Qe=await ot.current.fetchAgentConfig(xe);return Y({type:"SET_AGENT_CONFIG",payload:Qe}),Qe}catch(Qe){throw Y({type:"SET_AGENT_CONFIG",payload:null}),Qe}},[s]),Ct=oe.useCallback(xe=>{ce.current={...ce.current,...xe}},[]),kt=oe.useCallback(xe=>{const Qe=xe.sessionId||ve.current;return Qe?ot.current.submitFeedback({sessionId:Qe,rating:xe.rating,feedback:xe.feedback,endedBy:xe.endedBy}):Promise.reject(new Error("No session id available for feedback"))},[]),Xr=oe.useMemo(()=>dg(K.sessionState),[K.sessionState]),os=oe.useMemo(()=>({...K,...Xr,initializeSession:Wt,joinDesktopSession:xt,disconnect:je,terminateSession:qe,endSession:st,emit:ze,sendTextMessage:At,addLocalMessage:sr,emitUserMessage:Hr,sendAudioChunk:Us,endAudioStream:Kr,interrupt:jr,clearSessionHistory:Fs,changeSessionLanguage:rt,signalClientReady:Tr,clearMessages:lt,resumeAudioPlayback:Qr,pauseAudioPlayback:er,attachAudioElement:Er,fetchAgentConfig:yt,submitFeedback:kt,setCloudStreamState:gt,registerClientTools:Ct,events:pe.current,audioElement:Ge.current?.getAudioElement()??null,socket:Je.current?.getSocket()??null}),[K,Xr,Wt,xt,je,qe,st,ze,At,sr,Hr,Us,Kr,jr,Fs,rt,Tr,lt,Qr,er,Er,gt,Ct,kt]);return Jt.jsx(nf.Provider,{value:os,children:d})}function dn(){const d=oe.useContext(nf);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function of(){const d=dn();return{connectionState:d.connectionState,isConnected:d.isConnected,isSessionReady:d.isSessionReady,error:d.error,session:d.session,creditExhausted:d.creditExhausted,creditError:d.creditError,sessionState:d.sessionState,isSessionTerminated:d.isSessionTerminated,isSessionTerminating:d.isSessionTerminating,isAgentThinking:d.isAgentThinking,isAgentSpeaking:d.isAgentSpeaking,isToolExecuting:d.isToolExecuting,agentConfig:d.agentConfig,initializeSession:d.initializeSession,joinDesktopSession:d.joinDesktopSession,disconnect:d.disconnect,terminateSession:d.terminateSession,endSession:d.endSession,interrupt:d.interrupt,clearSessionHistory:d.clearSessionHistory,changeSessionLanguage:d.changeSessionLanguage,signalClientReady:d.signalClientReady,fetchAgentConfig:d.fetchAgentConfig,submitFeedback:d.submitFeedback,registerClientTools:d.registerClientTools}}function fy(){const d=dn();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function my(){const d=dn();return{sendAudioChunk:d.sendAudioChunk,endAudioStream:d.endAudioStream,isAudioPlaying:d.isAudioPlaying,transcript:d.transcript,partialTranscript:d.partialTranscript,interrupt:d.interrupt,resumeAudioPlayback:d.resumeAudioPlayback,pauseAudioPlayback:d.pauseAudioPlayback,attachAudioElement:d.attachAudioElement}}function lf(){const d=dn(),r=d.cloudStream?.state||Zt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===di.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===di.DESKTOP_AVATAR,cloudStreamState:r,cloudStreamError:d.cloudStream?.error||null,isCloudStreamConnected:r===Zt.CONNECTED,isCloudStreamLoading:r===Zt.CONNECTING||r===Zt.LOADING,setCloudStreamState:d.setCloudStreamState}}var to={},ro={},ei={},wp;function uf(){if(wp)return ei;wp=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let s="/";return r&&(s=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),ei.baseAssetPath=s,ei}var ti={},vp;function Io(){if(vp)return ti;vp=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return ti.defaultModelFetcher=d,ti}var Fr={},ri={},_p;function ci(){if(_p)return ri;_p=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return ri.log={error:d("error"),debug:d("debug"),warn:d("warn")},ri}var si={},bp;function qi(){if(bp)return si;bp=1,Object.defineProperty(si,"__esModule",{value:!0}),si.Message=void 0;var d;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(d||(si.Message=d={})),si}var Sp;function Mo(){if(Sp)return Fr;Sp=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.FrameProcessor=Fr.validateOptions=Fr.defaultFrameProcessorOptions=void 0;const d=ci(),r=qi();Fr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function s(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&d.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&d.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&d.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&d.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&d.log.error("minSpeechMs should be positive")}Fr.validateOptions=s;const a=C=>{const R=C.reduce((U,z)=>(U.push(U.at(-1)+z.length),U),[0]),b=new Float32Array(R.at(-1));return C.forEach((U,z)=>{const re=R[z];b.set(U,re)}),b};function f(C,R){const b=Math.floor(C.redemptionMs/R),U=Math.floor(C.preSpeechPadMs/R),z=Math.floor(C.minSpeechMs/R);return{redemptionFrames:b,preSpeechPadFrames:U,minSpeechFrames:z}}class _{constructor(R,b,U,z){this.modelProcessFunc=R,this.modelResetFunc=b,this.options=U,this.msPerFrame=z,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=J=>{this.options={...this.options,...J};const{redemptionFrames:Y,preSpeechPadFrames:H,minSpeechFrames:se}=f(this.options,this.msPerFrame);this.redemptionFrames=Y,this.preSpeechPadFrames=H,this.minSpeechFrames=se},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=J=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(J):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=J=>{const Y=this.audioBuffer;this.audioBuffer=[];const H=this.speaking;if(this.reset(),H)if(Y.reduce((ve,de)=>de.isSpeech?ve+1:ve,0)>=this.minSpeechFrames){const ve=a(Y.map(de=>de.frame));J({msg:r.Message.SpeechEnd,audio:ve})}else J({msg:r.Message.VADMisfire});return{}},this.process=async(J,Y)=>{if(!this.active)return;const H=await this.modelProcessFunc(J),se=H.isSpeech>=this.options.positiveSpeechThreshold;if(Y({probs:H,msg:r.Message.FrameProcessed,frame:J}),this.audioBuffer.push({frame:J,isSpeech:se}),se&&(this.speechFrameCount++,this.redemptionCounter=0),se&&!this.speaking&&(this.speaking=!0,Y({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,Y({msg:r.Message.SpeechRealStart})),H.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const ve=this.audioBuffer;if(this.audioBuffer=[],ve.reduce((he,pe)=>pe.isSpeech?he+1:he,0)>=this.minSpeechFrames){const he=a(ve.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:he})}else Y({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:re,preSpeechPadFrames:K,minSpeechFrames:ie}=f(this.options,this.msPerFrame);this.redemptionFrames=re,this.preSpeechPadFrames=K,this.minSpeechFrames=ie,this.reset()}}return Fr.FrameProcessor=_,Fr}var Vr={};function ur(d){throw new Error('Could not dynamically require "'+d+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
|
|
2
2
|
* ONNX Runtime Web v1.26.0
|
|
3
3
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
4
4
|
* Licensed under the MIT License.
|
|
@@ -2915,4 +2915,4 @@ Msg: ${s}`;console.warn(a)}}T.verboseLogLevel=5,(function(d){d.LIST_STREAMERS="l
|
|
|
2915
2915
|
`),this.gl.compileShader(s);const a=this.gl.createProgram();this.gl.attachShader(a,r),this.gl.attachShader(a,s),this.gl.linkProgram(a),this.gl.useProgram(a),this.positionLocation=this.gl.getAttribLocation(a,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(a,"a_texCoord")}updateVideoTexture(){this.videoTexture||(this.videoTexture=this.gl.createTexture(),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR));let r=this.webRtcController.videoPlayer.getVideoElement().videoHeight,s=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=r||this.prevVideoWidth!=s?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,s,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,s,r,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=r,this.prevVideoWidth=s}initBuffers(){this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,-1,-1,1,1,1,-1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.texcoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texcoordBuffer),this.gl.enableVertexAttribArray(this.texcoordLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.texcoordLocation,2,this.gl.FLOAT,!1,0,0)}onXrSessionStarted(r){T.Log(T.GetStackTrace(),"XR Session started"),this.xrSession=r,this.xrSession.addEventListener("end",(()=>{this.onXrSessionEnded()})),this.initGL(),this.initShaders(),this.initBuffers(),r.requestReferenceSpace("local").then((s=>{if(this.xrRefSpace=s,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let a of this.xrSession.supportedFrameRates)a==90&&r.updateTargetFrameRate(90);this.xrSession.requestAnimationFrame(this.onXrFrame.bind(this))})),this.onSessionStarted.dispatchEvent(new Event("xrSessionStarted"))}sendXRDataToUE(){if(this.leftView==null||this.rightView==null)return;const r=this.leftView.transform.matrix,s=this.leftView.projectionMatrix,a=this.rightView.transform.matrix,f=this.rightView.projectionMatrix;this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([r[0],r[4],r[8],r[12],r[1],r[5],r[9],r[13],r[2],r[6],r[10],r[14],r[3],r[7],r[11],r[15],s[0],s[4],s[8],s[12],s[1],s[5],s[9],s[13],s[2],s[6],s[10],s[14],s[3],s[7],s[11],s[15],a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],f[0],f[4],f[8],f[12],f[1],f[5],f[9],f[13],f[2],f[6],f[10],f[14],f[3],f[7],f[11],f[15]])}onXrFrame(r,s){if(this.xrViewerPose=s.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),this.leftView==null||this.rightView==null)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(X.XRControllerInput)&&this.xrSession.inputSources.forEach(((a,f,_)=>{this.xrGamepadController.updateStatus(a,s,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((a,f)=>this.onXrFrame(a,f))),this.onFrame.dispatchEvent(new Qf({time:r,frame:s}))}updateViews(){if(this.xrViewerPose)for(const r of this.xrViewerPose.views)r.eye==="left"?this.leftView=r:r.eye==="right"&&(this.rightView=r)}render(){if(!this.gl)return;const r=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,r.framebuffer),this.gl.viewport(0,0,r.framebufferWidth,r.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(r){return location.protocol!=="https:"&&T.Info(null,"WebXR requires https, if you want WebXR use https."),navigator.xr?navigator.xr.isSessionSupported(r):new Promise((()=>!1))}}class Sw{constructor(r){this.editTextButton=null,this.hiddenInput=null,"ontouchstart"in document.documentElement&&this.createOnScreenKeyboardHelpers(r)}unquantizeAndDenormalizeUnsigned(r,s){return null}createOnScreenKeyboardHelpers(r){this.hiddenInput||(this.hiddenInput=document.createElement("input"),this.hiddenInput.id="hiddenInput",this.hiddenInput.maxLength=0,this.hiddenInput.style.position="absolute",this.hiddenInput.style.left="-10%",this.hiddenInput.style.width="0px",this.hiddenInput.style.opacity="0",r.appendChild(this.hiddenInput)),this.editTextButton||(this.editTextButton=document.createElement("button"),this.editTextButton.id="editTextButton",this.editTextButton.innerHTML="edit text",r.appendChild(this.editTextButton),this.editTextButton.style.display="none",this.editTextButton.addEventListener("touchend",(s=>{this.hiddenInput.focus(),s.preventDefault()})))}showOnScreenKeyboard(r){if(r.showOnScreenKeyboard){this.editTextButton.style.display="default";const s=this.unquantizeAndDenormalizeUnsigned(r.x,r.y);this.editTextButton.style.top=s.y.toString()+"px",this.editTextButton.style.left=(s.x-40).toString()+"px"}else this.editTextButton.style.display="none",this.hiddenInput.blur()}}class Tw{constructor(r){this.seq=r.Seq,this.playerSentTimestamp=Date.now(),this.requestFillerSize=r.Filler?r.Filler.length:0}update(r){this.playerReceivedTimestamp=Date.now(),this.streamerReceivedTimestamp=r.ReceivedTimestamp,this.streamerSentTimestamp=r.SentTimestamp,this.responseFillerSize=r.Filler?r.Filler.length:0}}class Ew{constructor(r,s){this.sink=r,this.callback=s,this.records=new Map,this.seq=0}start(r){return!this.isRunning()&&(this.startTime=Date.now(),this.records.clear(),this.interval=setInterval((()=>{Date.now()-this.startTime>=r.duration?this.stop():this.sendRequest(r.requestSize,r.responseSize)}).bind(this),Math.floor(1e3/r.rps)),!0)}stop(){this.interval&&(clearInterval(this.interval),this.interval=void 0,this.callback(this.produceResult()))}produceResult(){const r=new Map(this.records);return{records:r,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.playerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.streamerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.playerReceivedTimestamp-a.streamerSentTimestamp)),0)/this.records.size),exportLatencyAsCSV:()=>{let s=`Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;
|
|
2916
2916
|
`;return r.forEach((a=>{s+=a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.streamerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.streamerSentTimestamp+";",s+=`
|
|
2917
2917
|
`})),s}}}isRunning(){return!!this.interval}receive(r){if(!this.isRunning())return;if(!r)return void T.Error(T.GetStackTrace(),"Undefined response from server");let s=this.records.get(r.Seq);s&&s.update(r)}sendRequest(r,s){let a=this.createRequest(r,s),f=new Tw(a);this.records.set(f.seq,f),this.sink(a)}createRequest(r,s){return{Seq:this.seq++,FillResponseSize:s,Filler:r?"A".repeat(r):""}}}class $w{constructor(r,s){this.allowConsoleCommands=!1,this.config=r,s?.videoElementParent&&(this._videoElementParent=s.videoElementParent),this._eventEmitter=new Jf,this.configureSettings(),this.setWebRtcPlayerController(new dm(this.config,this)),this.onScreenKeyboardHelper=new Sw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,f)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,f),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new cm(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(a=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(X.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(X.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(X.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(X.HoveringMouseMode,(r=>{this.config.setFlagLabel(X.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(X.MouseInput))})),this.config._addOnSettingChangedListener(X.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(X.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(X.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(X.TouchInput))})),this.config._addOnSettingChangedListener(X.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(X.GamepadInput,(r=>{this._webRtcController.setGamePadInputEnabled(r)})),this.config._addOnNumericSettingChangedListener(me.MinQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.MaxQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCMinBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCMaxBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(me.WebRTCFPS,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(dt.PreferredCodec,(r=>{this._webRtcController&&this._webRtcController.setPreferredCodec(r)})),this.config._registerOnChangeEvents(this._eventEmitter)}_activateOnScreenKeyboard(r){throw new Error("Method not implemented.")}_onInputControlOwnership(r){this._inputController=r}setWebRtcPlayerController(r){this._webRtcController=r,this._webRtcController.setPreferredCodec(this.config.getSettingOption(dt.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Df),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Lf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new zf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(X.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(r=!1){if(!this.config.isFlagEnabled("UseMic"))return r?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void T.Warning(T.GetStackTrace(),"Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):T.Info(T.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(r){var s,a,f,_;for(const C of(_=(f=(a=(s=this._webRtcController)===null||s===void 0?void 0:s.peerConnectionController)===null||a===void 0?void 0:a.peerConnection)===null||f===void 0?void 0:f.getTransceivers())!==null&&_!==void 0?_:[])im.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new $f)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Ef)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Of)}_onDisconnect(r,s){this._eventEmitter.dispatchEvent(new Rf({eventString:r,allowClickToReconnect:s}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new xf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new kf)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Pf),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new Wf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Hf({response:r}))}_onVideoStats(r){this._videoStartTime&&this._videoStartTime!==void 0||(this._videoStartTime=Date.now()),r.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Vf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new Tf({avgQP:r}))}_onInitialSettings(r){var s;this._eventEmitter.dispatchEvent(new jf({settings:r})),r.PixelStreamingSettings&&(this.allowConsoleCommands=(s=r.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&s!==void 0&&s,this.allowConsoleCommands===!1&&T.Info(T.GetStackTrace(),"-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const a=this.config.useUrlParams,f=new URLSearchParams(window.location.search);T.Info(T.GetStackTrace(),`using URL parameters ${a}`),r.EncoderSettings&&(this.config.setNumericSetting(me.MinQP,a&&f.has(me.MinQP)?Number.parseFloat(f.get(me.MinQP)):r.EncoderSettings.MinQP),this.config.setNumericSetting(me.MaxQP,a&&f.has(me.MaxQP)?Number.parseFloat(f.get(me.MaxQP)):r.EncoderSettings.MaxQP)),r.WebRTCSettings&&(this.config.setNumericSetting(me.WebRTCMinBitrate,a&&f.has(me.WebRTCMinBitrate)?Number.parseFloat(f.get(me.WebRTCMinBitrate)):r.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(me.WebRTCMaxBitrate,a&&f.has(me.WebRTCMaxBitrate)?Number.parseFloat(f.get(me.WebRTCMaxBitrate)):r.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(me.WebRTCFPS,a&&f.has(me.WebRTCFPS)?Number.parseFloat(f.get(me.WebRTCFPS)):r.WebRTCSettings.FPS))}_onQualityControlOwnership(r){this.config.setFlagEnabled(X.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new Xf({count:r}))}_setupWebRtcTCPRelayDetection(r){let s=r.data.aggregatedStats.getActiveCandidatePair();if(s!=null){let a=r.data.aggregatedStats.localCandidates.find((f=>f.id==s.localCandidateId),null);a!=null&&a.candidateType=="relay"&&a.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new Yf),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new Ew(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(s=>{this._eventEmitter.dispatchEvent(new Kf({result:s}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:s}})=>{this._dataChannelLatencyTestController.receive(s)}))),this._dataChannelLatencyTestController.start(r))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(r),!0)}emitCommand(r){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in r||(this._webRtcController.emitCommand(r),0))}emitConsoleCommand(r){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(r),0))}addResponseEventListener(r,s){this._webRtcController.responseController.addResponseEventListener(r,s)}removeResponseEventListener(r){this._webRtcController.responseController.removeResponseEventListener(r)}dispatchEvent(r){return this._eventEmitter.dispatchEvent(r)}addEventListener(r,s){this._eventEmitter.addEventListener(r,s)}removeEventListener(r,s){this._eventEmitter.removeEventListener(r,s)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(r){this._webRtcController.signallingUrlBuilder=r}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(r,s,a){s!==be.FromStreamer||a!==void 0?s===be.ToStreamer&&a===void 0?this._webRtcController.streamMessageController.registerMessageHandler(s,r,(f=>this._webRtcController.sendMessageController.sendMessageToStreamer(r,f))):this._webRtcController.streamMessageController.registerMessageHandler(s,r,(f=>a(f))):T.Warning(T.GetStackTrace(),`Unable to register an undefined handler for ${r}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}class xw{}we.Dz;we.g$;we.Lt;we.Q9;we.qf;we.hV;we.z$;we.J0;var Cw=we.De;we.$C;we.al;we._W;we.Gv;we.m;we.tz;we.Nu;we.zg;we.vp;we.vU;we.wF;we.rv;we.Nh;we.ss;we.qW;we.QL;we.cf;we.eM;we.Yd;we.Tk;we.iM;we.qy;we.ce;we.sK;we.Ok;we.q5;var kw=we.g;we.xl;we.I;we.bx;we.dD;we.Ib;we.Az;we.Iw;we.qY;we.db;we.mR;we.Tn;we.rV;we.gh;we.Mi;we.j;we.YB;we.Yt;we.i5;we.x_;we.Am;we.eR;we.r8;we.u3;we.vd;we.iV;we.jZ;we.SW;we.ZH;we.Ni;we.lh;we.ZP;we.bq;we.$f;we.eu;we.Ax;we.Mc;const hm=({signallingUrl:d,autoConnect:r=!0,width:s,height:a,onConnecting:f,onLoading:_,onConnected:C,onDisconnected:R,onError:b,muted:U=!1})=>{const z=oe.useRef(null),re=oe.useRef(null),K=oe.useRef(!1),[ie,J]=oe.useState(!1),[Y,H]=oe.useState(!1),[se,ve]=oe.useState(null);return oe.useEffect(()=>{if(!(!z.current||!d)){f&&f(),process.env.NODE_ENV==="development"&&console.log("Initializing Epic Pixel Streaming with URL:",d),"mediaDevices"in navigator||Object.defineProperty(navigator,"mediaDevices",{value:{}}),navigator.mediaDevices.getUserMedia||(navigator.mediaDevices.getUserMedia=function(){return Promise.reject(new Error("getUserMedia is not supported"))});try{const de=new Cw({useUrlParams:!1,initialSettings:{ss:d,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:U,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),he=new kw(de,{videoElementParent:z.current});he.addEventListener("webRtcConnected",()=>{K.current=!0,J(!0),H(!1),ve(null),C?.()}),he.addEventListener("webRtcDisconnected",()=>{K.current=!1,J(!1),R?.()}),he.addEventListener("streamLoading",()=>{H(!0),_?.()}),he.addEventListener("playStreamError",()=>{ve("Failed to play stream"),H(!1),b?.("Failed to play stream")}),he.addEventListener("playStream",()=>{H(!1),K.current||(K.current=!0,J(!0),C?.())}),he.addEventListener("videoInitialized",()=>{H(!1)}),re.current=he}catch(de){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",de),ve("Failed to initialize streaming: "+de.message),H(!1),b?.(de.message)}return()=>{if(re.current){try{const de=re.current;de._webSocketController&&de._webSocketController.close(),re.current.disconnect()}catch(de){process.env.NODE_ENV==="development"&&console.error("Error during cleanup:",de)}re.current=null}}}},[d,r,f,_,C,R,b]),oe.useEffect(()=>{if(re.current)try{const he=re.current._webRtcController?.videoPlayer;if(!he)return;let pe=!1;if(he.audioElement){const Ke=he.audioElement.srcObject;if(Ke){const fe=Ke.getAudioTracks();fe.length>0&&(fe.forEach(Je=>{Je.enabled=!U}),pe=!0)}}const ce=he.getVideoElement();if(ce&&ce.srcObject&&ce.srcObject instanceof MediaStream){const fe=ce.srcObject.getAudioTracks();fe.length>0&&(fe.forEach(Je=>{Je.enabled=!U}),pe=!0)}!pe&&ce&&(ce.muted=U)}catch(de){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",de)}},[U]),Jt.jsxs("div",{className:"pixel-streaming-container",style:{width:s||"100%",height:a||"100%",position:"relative",display:"flex",flexDirection:"column",touchAction:"none",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},children:[Jt.jsx("div",{ref:z,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),Y&&Jt.jsxs("div",{className:"loading-overlay",children:[Jt.jsx("div",{className:"loading-spinner"}),Jt.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!ie&&!Y&&se&&Jt.jsx("div",{className:"connection-overlay",children:Jt.jsx("div",{className:"error-message",children:se})})]})};function Rw({className:d,style:r,autoConnect:s=!0,muted:a=!1,onConnected:f,onDisconnected:_,onError:C}){const{streamingUrl:R,setCloudStreamState:b}=lf();if(!R)return null;const U=()=>{b(Zt.CONNECTING)},z=()=>{b(Zt.LOADING)},re=()=>{b(Zt.CONNECTED),f?.()},K=()=>{b(Zt.DISCONNECTED),_?.()},ie=J=>{b(Zt.ERROR,J),C?.(J)};return Jt.jsx("div",{className:d,style:r,children:Jt.jsx(hm,{signallingUrl:R,autoConnect:s,muted:a,onConnecting:U,onLoading:z,onConnected:re,onDisconnected:K,onError:ie})})}exports.AGENT_TYPES=di;exports.CLOUD_STREAM_STATE=Zt;exports.CONNECTION_STATE=ft;exports.DEFAULT_PCM_OPTIONS=Gp;exports.EpicPixelStreamingPlayer=hm;exports.EventEmitter=sf;exports.RqmiiAgentProvider=af;exports.RqmiiAgentRoom=My;exports.RqmiiCloudAvatarPlayer=Rw;exports.SESSION_STATE=Bs;exports.SOCKET_EVENTS=_r;exports.useRqmiiAgentContext=dn;exports.useRqmiiAvatar=lf;exports.useRqmiiConnection=of;exports.useRqmiiMessages=fy;exports.useRqmiiVAD=Ay;exports.useRqmiiVoice=my;
|
|
2918
|
-
//# sourceMappingURL=RqmiiCloudAvatarPlayer-
|
|
2918
|
+
//# sourceMappingURL=RqmiiCloudAvatarPlayer-CFPGKoOq.cjs.map
|