@applica-software-guru/persona-sdk 0.1.87 → 0.1.89

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.
@@ -1,4 +1,4 @@
1
- "use strict";var xg=Object.defineProperty;var Sg=(h,f,i)=>f in h?xg(h,f,{enumerable:!0,configurable:!0,writable:!0,value:i}):h[f]=i;var W=(h,f,i)=>Sg(h,typeof f!="symbol"?f+"":f,i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Zi=require("react/jsx-runtime"),j=require("react"),xr=require("@assistant-ui/react");let Ag=0;function bg(){return`msg_${Date.now()}_${Ag++}`}function Cg(h){return h.thought&&(h={...h,type:"reasoning"}),h.id?h.createdAt?h:{...h,createdAt:new Date}:{...h,id:bg(),createdAt:h.createdAt||new Date}}function Ig(h){return h.filter(f=>f.finishReason==="stop"?f.text!==null&&f.text.trim()!=="":!0)}function ee(h){const f=[];let i=null;for(let _ of h)if(_=Cg(_),_.type!=="transaction")if(_.file){i&&(f.push(i),i=null),f.push(_);continue}else _.functionCalls?(i&&f.push(i),f.push(_),i=null):_.functionResponse?f[f.length-1]={...f[f.length-1],functionResponse:_.functionResponse}:i&&_.type===i.type&&_.protocol===i.protocol&&i.role===_.role&&(_.id===i.id||!i.finishReason)?(i.text+=_.text,i.file=i.file||_.file,i.finishReason=_.finishReason||i.finishReason,i.id=i.id||_.id):(i&&f.push(i),i={..._,text:_.file?"":_.text,finishReason:_.file?void 0:_.finishReason});return i&&f.push(i),Ig(f)}function Rg(h){var _,v,x;const f=h.file?[{type:"file",data:h.file.url,mimeType:h.file.contentType}]:[];let i;if((h.role==="assistant"||h.role==="function")&&(h.status?i=h.status:h.finishReason==="stop"?i={type:"complete",reason:"stop"}:h.finishReason==="function_call"?i={type:"complete",reason:"stop"}:h.finishReason||(i=void 0)),h.role==="function"){const T={id:h.id,role:"assistant",createdAt:h.createdAt,content:((_=h.functionCalls)==null?void 0:_.map(b=>{var B;return{type:"tool-call",toolName:b.name,toolCallId:b.id||`tool_${Date.now()}`,args:b.args,result:(B=h.functionResponse)==null?void 0:B.result}}))??[],metadata:{...h.metadata,custom:{protocol:h.protocol,sessionId:h.sessionId,sources:h.sources,...(v=h.metadata)==null?void 0:v.custom}}};return i?{...T,status:i}:T}const p={id:h.id,role:h.role,createdAt:h.createdAt,content:h.type==="reasoning"?[{type:"reasoning",text:h.text},...f]:[{type:"text",text:h.text},...f],metadata:{...h.metadata,custom:{protocol:h.protocol,sessionId:h.sessionId,sources:h.sources,type:h.type,...(x=h.metadata)==null?void 0:x.custom}}};return h.role==="assistant"&&i?{...p,status:i}:p}class Ce{constructor(){W(this,"statusChangeCallbacks",[]);W(this,"messageCallbacks",[])}addStatusChangeListener(f){this.statusChangeCallbacks.push(f)}addPacketListener(f){this.messageCallbacks.push(f)}async syncSession(f){this.session=f}async notifyPacket(f){this.messageCallbacks.forEach(i=>i(f))}async notifyPackets(f){f.forEach(i=>{this.messageCallbacks.forEach(p=>p(i))})}async setSession(f){this.session=f}async setStatus(f){const i=this.status!==f;this.status=f,i&&this.statusChangeCallbacks.forEach(p=>p(f))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(f){}}class Yi extends Ce{constructor(i){super();W(this,"status");W(this,"autostart");W(this,"session");W(this,"config");W(this,"notify",!0);W(this,"context",{});W(this,"tools",[]);this.config=i,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 100}async connect(i){return this.setStatus("connected"),i}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(i){this.session=i}async sendPacket(i){var b,B,C,k,P;const{apiUrl:p,apiKey:_,agentId:v}=this.config,x=this.session??"new";if(i.type==="command"&&((b=i==null?void 0:i.payload)==null?void 0:b.command)=="set_initial_context"){this.context=(B=i==null?void 0:i.payload)==null?void 0:B.arguments;return}else if(i.type==="command"&&((C=i==null?void 0:i.payload)==null?void 0:C.command)=="set_local_tools"){const G=(k=i==null?void 0:i.payload)==null?void 0:k.arguments.tools;(G==null?void 0:G.length)>0&&this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:"Local tools with rest protocol are not supported."}});return}const T=i.payload;try{const J=await(await fetch(`${p}/sessions/${x}/messages`,{body:JSON.stringify({agentId:v,userMessage:T,initialContext:this.context,tools:this.tools}),method:"POST",headers:{"Content-Type":"application/json","x-persona-apikey":_}})).json();this.notifyPackets(J.response.messages.map($=>({type:"message",payload:$})))}catch(G){this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"An error occurred while processing your request. Please try again later."}}),(P=this.config.logger)==null||P.error("Error sending packet:",G)}}}class Xi extends Ce{constructor(i){super();W(this,"status");W(this,"autostart");W(this,"session");W(this,"config");W(this,"webSocket");this.config=i,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 500}async syncSession(i){var p;(p=this.config.logger)==null||p.debug("Syncing session with WebSocket protocol:",i),this.session=i,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(i))}connect(i){var b;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const p=i||this.session||"new";(b=this.config.logger)==null||b.debug("Connecting to WebSocket with sessionId:",p);const _=encodeURIComponent(this.config.apiKey),v=this.config.agentId,x=this.config.userId||"anonymous",T=`${this.config.webSocketUrl}?sessionCode=${p}&agentId=${v}&apiKey=${_}&userId=${encodeURIComponent(x)}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(T),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",B=>{const C=JSON.parse(B.data);this.notifyPacket(C)}),this.webSocket.addEventListener("close",B=>{var C;this.setStatus("disconnected"),this.webSocket=null,B.code!==1e3&&(this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"Oops! The connection to the server was lost. Please try again later."}}),(C=this.config.logger)==null||C.warn("WebSocket connection closed"))}),this.webSocket.addEventListener("error",()=>{var B;this.setStatus("disconnected"),this.webSocket=null,(B=this.config.logger)==null||B.error("WebSocket connection error")}),Promise.resolve(p)}disconnect(){var i;return(i=this.config.logger)==null||i.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(1e3,"Normal closure"),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}sendPacket(i){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify(i)),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class Pg{constructor(f){W(this,"config");W(this,"pc",null);W(this,"ws",null);W(this,"localStream",null);W(this,"remoteStream",new MediaStream);W(this,"audioCtx",null);W(this,"localAnalyser",null);W(this,"remoteAnalyser",null);W(this,"analyzerFrame",null);W(this,"dataChannel",null);W(this,"isConnected",!1);W(this,"visualizerCallbacks",[]);W(this,"messageCallbacks",[]);W(this,"errorCallbacks",[]);W(this,"queuedMessages",[]);this.config=f}async connect(f){var p;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(_){(p=this.config.logger)==null||p.error("Error accessing microphone:",_);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(_=>{this.pc.addTrack(_,this.localStream)}),this.pc.ontrack=_=>{_.streams[0].getTracks().forEach(x=>{this.remoteStream.addTrack(x)}),this.audioCtx||this._startAnalyzers();const v=new Audio;v.srcObject=this.remoteStream,v.play().catch(x=>{var T;(T=this.config.logger)==null||T.error("Error playing remote audio:",x)})},this.pc.onicecandidate=_=>{var v;_.candidate&&((v=this.ws)==null?void 0:v.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:_.candidate}}))},this.pc.ondatachannel=_=>{const v=_.channel;v.onmessage=x=>{this.messageCallbacks.forEach(T=>{T(x)})},v.onopen=()=>{var x;for(;this.queuedMessages.length>0;){const T=this.queuedMessages.shift();T&&(v.send(JSON.stringify(T)),(x=this.config.logger)==null||x.info("Sent queued message:",T))}}};const i=this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc";this.ws=new WebSocket(`${i}?apiKey=${encodeURIComponent(this.config.apiKey)}`),this.ws.onopen=async()=>{var T,b;const _=await this.pc.createOffer();await this.pc.setLocalDescription(_);const v={apiKey:this.config.apiKey,agentId:this.config.agentId,userId:this.config.userId||"anonymous",sessionCode:f};(T=this.config.logger)==null||T.debug("Opening connection to WebRTC server: ",v);const x={type:"OFFER",src:((b=crypto.randomUUID)==null?void 0:b.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:_.sdp,type:_.type},connectionId:(Date.now()%1e6).toString(),metadata:v}};this.ws.send(JSON.stringify(x))},this.ws.onmessage=async _=>{var x;const v=JSON.parse(_.data);if(v.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(v.payload.sdp));else if(v.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(v.payload.candidate))}catch(T){(x=this.config.logger)==null||x.error("Error adding ICE candidate:",T)}},this.ws.onclose=_=>{_.code!==1e3&&this.errorCallbacks.forEach(v=>{v("Oops! The connection to the server was lost. Please try again later.")}),this._stopAnalyzers()}}async disconnect(){var f;this.isConnected&&(this.isConnected=!1,((f=this.ws)==null?void 0:f.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(i=>i.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(f){this.visualizerCallbacks.push(f)}addMessageCallback(f){this.messageCallbacks.push(f)}addErrorCallback(f){this.errorCallbacks.push(f)}createDataChannel(f="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(f),this.dataChannel.onopen=()=>{var i,p;for((i=this.config.logger)==null||i.info("Data channel opened");this.queuedMessages.length>0;){const _=this.queuedMessages.shift();_&&(this.dataChannel.send(JSON.stringify(_)),(p=this.config.logger)==null||p.info("Sent queued message:",_))}},this.dataChannel.onmessage=i=>{this.messageCallbacks.forEach(p=>{p(i)})})}sendPacket(f){var i;if(!this.dataChannel||this.dataChannel.readyState!=="open"){this.queuedMessages.push(f);return}this.dataChannel.send(JSON.stringify(f)),(i=this.config.logger)==null||i.info("Sent message:",f)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const f=this.audioCtx.createMediaStreamSource(this.localStream),i=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,f.connect(this.localAnalyser),i.connect(this.remoteAnalyser);const p=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const _=new Uint8Array(this.localAnalyser.frequencyBinCount),v=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(_),this.remoteAnalyser.getByteFrequencyData(v);const x=_.reduce((b,B)=>b+B,0)/_.length,T=v.reduce((b,B)=>b+B,0)/v.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(b=>{b({localAmplitude:x,remoteAmplitude:T})}),this.analyzerFrame=requestAnimationFrame(p)};this.analyzerFrame=requestAnimationFrame(p)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class Qi extends Ce{constructor(i){super();W(this,"status");W(this,"session");W(this,"autostart");W(this,"config");W(this,"webRTCClient");this.config=i,this.status="disconnected",this.session=null,this.autostart=(i==null?void 0:i.autostart)??!1,this.webRTCClient=new Pg(i),this.webRTCClient.addMessageCallback(p=>{const _=JSON.parse(p.data);this.notifyPacket(_)}),this.webRTCClient.addErrorCallback(p=>{var _;(_=this.config.logger)==null||_.error("WebRTC error:",p),this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:p}})})}getName(){return"webrtc"}getPriority(){return 1e3}async syncSession(i){super.syncSession(i),this.status==="connected"&&(await this.disconnect(),await this.connect(i))}async connect(i){var p;return this.status==="connected"?Promise.resolve(this.session):(this.session=i||this.session||"new",this.setStatus("connecting"),(p=this.config.logger)==null||p.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var i,p,_;if(this.status==="disconnected")return(i=this.config.logger)==null||i.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(_=(p=this.config)==null?void 0:p.logger)==null||_.debug("Disconnected from WebRTC")}sendPacket(i){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendPacket(i),Promise.resolve())}}var be=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Eg(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}var Sr={exports:{}};/**
1
+ "use strict";var xg=Object.defineProperty;var Sg=(h,f,i)=>f in h?xg(h,f,{enumerable:!0,configurable:!0,writable:!0,value:i}):h[f]=i;var W=(h,f,i)=>Sg(h,typeof f!="symbol"?f+"":f,i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Zi=require("react/jsx-runtime"),j=require("react"),xr=require("@assistant-ui/react");let Ag=0;function bg(){return`msg_${Date.now()}_${Ag++}`}function Cg(h){return h.thought&&(h={...h,type:"reasoning"}),h.id?h.createdAt?h:{...h,createdAt:new Date}:{...h,id:bg(),createdAt:h.createdAt||new Date}}function Ig(h){return h.filter(f=>f.finishReason==="stop"?f.text!==null&&f.text.trim()!=="":!0)}function ee(h){const f=[];let i=null;for(let _ of h)if(_=Cg(_),_.type!=="transaction")if(_.file){i&&(f.push(i),i=null),f.push(_);continue}else _.functionCalls?(i&&f.push(i),f.push(_),i=null):_.functionResponse?f[f.length-1]={...f[f.length-1],functionResponse:_.functionResponse}:i&&_.type===i.type&&_.protocol===i.protocol&&i.role===_.role&&(_.id===i.id||!i.finishReason)?(i.text+=_.text,i.file=i.file||_.file,i.finishReason=_.finishReason||i.finishReason,i.id=i.id||_.id,i.sources=i.sources?[...i.sources||[],..._.sources||[]]:_.sources):(i&&f.push(i),i={..._,text:_.file?"":_.text,finishReason:_.file?void 0:_.finishReason});i&&f.push(i);const p=Ig(f);return console.log({before:h,after:p}),p}function Rg(h){var _,v,x;const f=h.file?[{type:"file",data:h.file.url,mimeType:h.file.contentType}]:[];let i;if((h.role==="assistant"||h.role==="function")&&(h.status?i=h.status:h.finishReason==="stop"?i={type:"complete",reason:"stop"}:h.finishReason==="function_call"?i={type:"complete",reason:"stop"}:h.finishReason||(i=void 0)),h.role==="function"){const T={id:h.id,role:"assistant",createdAt:h.createdAt,content:((_=h.functionCalls)==null?void 0:_.map(b=>{var B;return{type:"tool-call",toolName:b.name,toolCallId:b.id||`tool_${Date.now()}`,args:b.args,result:(B=h.functionResponse)==null?void 0:B.result}}))??[],metadata:{...h.metadata,custom:{protocol:h.protocol,sessionId:h.sessionId,sources:h.sources,...(v=h.metadata)==null?void 0:v.custom}}};return i?{...T,status:i}:T}const p={id:h.id,role:h.role,createdAt:h.createdAt,content:h.type==="reasoning"?[{type:"reasoning",text:h.text},...f]:[{type:"text",text:h.text},...f],metadata:{...h.metadata,custom:{protocol:h.protocol,sessionId:h.sessionId,sources:h.sources,type:h.type,...(x=h.metadata)==null?void 0:x.custom}}};return h.role==="assistant"&&i?{...p,status:i}:p}class Ce{constructor(){W(this,"statusChangeCallbacks",[]);W(this,"messageCallbacks",[])}addStatusChangeListener(f){this.statusChangeCallbacks.push(f)}addPacketListener(f){this.messageCallbacks.push(f)}async syncSession(f){this.session=f}async notifyPacket(f){this.messageCallbacks.forEach(i=>i(f))}async notifyPackets(f){f.forEach(i=>{this.messageCallbacks.forEach(p=>p(i))})}async setSession(f){this.session=f}async setStatus(f){const i=this.status!==f;this.status=f,i&&this.statusChangeCallbacks.forEach(p=>p(f))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(f){}}class Yi extends Ce{constructor(i){super();W(this,"status");W(this,"autostart");W(this,"session");W(this,"config");W(this,"notify",!0);W(this,"context",{});W(this,"tools",[]);this.config=i,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 100}async connect(i){return this.setStatus("connected"),i}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(i){this.session=i}async sendPacket(i){var b,B,C,k,P;const{apiUrl:p,apiKey:_,agentId:v}=this.config,x=this.session??"new";if(i.type==="command"&&((b=i==null?void 0:i.payload)==null?void 0:b.command)=="set_initial_context"){this.context=(B=i==null?void 0:i.payload)==null?void 0:B.arguments;return}else if(i.type==="command"&&((C=i==null?void 0:i.payload)==null?void 0:C.command)=="set_local_tools"){const G=(k=i==null?void 0:i.payload)==null?void 0:k.arguments.tools;(G==null?void 0:G.length)>0&&this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:"Local tools with rest protocol are not supported."}});return}const T=i.payload;try{const J=await(await fetch(`${p}/sessions/${x}/messages`,{body:JSON.stringify({agentId:v,userMessage:T,initialContext:this.context,tools:this.tools}),method:"POST",headers:{"Content-Type":"application/json","x-persona-apikey":_}})).json();this.notifyPackets(J.response.messages.map($=>({type:"message",payload:$})))}catch(G){this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"An error occurred while processing your request. Please try again later."}}),(P=this.config.logger)==null||P.error("Error sending packet:",G)}}}class Xi extends Ce{constructor(i){super();W(this,"status");W(this,"autostart");W(this,"session");W(this,"config");W(this,"webSocket");this.config=i,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 500}async syncSession(i){var p;(p=this.config.logger)==null||p.debug("Syncing session with WebSocket protocol:",i),this.session=i,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(i))}connect(i){var b;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const p=i||this.session||"new";(b=this.config.logger)==null||b.debug("Connecting to WebSocket with sessionId:",p);const _=encodeURIComponent(this.config.apiKey),v=this.config.agentId,x=this.config.userId||"anonymous",T=`${this.config.webSocketUrl}?sessionCode=${p}&agentId=${v}&apiKey=${_}&userId=${encodeURIComponent(x)}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(T),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",B=>{const C=JSON.parse(B.data);this.notifyPacket(C)}),this.webSocket.addEventListener("close",B=>{var C;this.setStatus("disconnected"),this.webSocket=null,B.code!==1e3&&(this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"Oops! The connection to the server was lost. Please try again later."}}),(C=this.config.logger)==null||C.warn("WebSocket connection closed"))}),this.webSocket.addEventListener("error",()=>{var B;this.setStatus("disconnected"),this.webSocket=null,(B=this.config.logger)==null||B.error("WebSocket connection error")}),Promise.resolve(p)}disconnect(){var i;return(i=this.config.logger)==null||i.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(1e3,"Normal closure"),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}sendPacket(i){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify(i)),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class Pg{constructor(f){W(this,"config");W(this,"pc",null);W(this,"ws",null);W(this,"localStream",null);W(this,"remoteStream",new MediaStream);W(this,"audioCtx",null);W(this,"localAnalyser",null);W(this,"remoteAnalyser",null);W(this,"analyzerFrame",null);W(this,"dataChannel",null);W(this,"isConnected",!1);W(this,"visualizerCallbacks",[]);W(this,"messageCallbacks",[]);W(this,"errorCallbacks",[]);W(this,"queuedMessages",[]);this.config=f}async connect(f){var p;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(_){(p=this.config.logger)==null||p.error("Error accessing microphone:",_);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(_=>{this.pc.addTrack(_,this.localStream)}),this.pc.ontrack=_=>{_.streams[0].getTracks().forEach(x=>{this.remoteStream.addTrack(x)}),this.audioCtx||this._startAnalyzers();const v=new Audio;v.srcObject=this.remoteStream,v.play().catch(x=>{var T;(T=this.config.logger)==null||T.error("Error playing remote audio:",x)})},this.pc.onicecandidate=_=>{var v;_.candidate&&((v=this.ws)==null?void 0:v.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:_.candidate}}))},this.pc.ondatachannel=_=>{const v=_.channel;v.onmessage=x=>{this.messageCallbacks.forEach(T=>{T(x)})},v.onopen=()=>{var x;for(;this.queuedMessages.length>0;){const T=this.queuedMessages.shift();T&&(v.send(JSON.stringify(T)),(x=this.config.logger)==null||x.info("Sent queued message:",T))}}};const i=this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc";this.ws=new WebSocket(`${i}?apiKey=${encodeURIComponent(this.config.apiKey)}`),this.ws.onopen=async()=>{var T,b;const _=await this.pc.createOffer();await this.pc.setLocalDescription(_);const v={apiKey:this.config.apiKey,agentId:this.config.agentId,userId:this.config.userId||"anonymous",sessionCode:f};(T=this.config.logger)==null||T.debug("Opening connection to WebRTC server: ",v);const x={type:"OFFER",src:((b=crypto.randomUUID)==null?void 0:b.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:_.sdp,type:_.type},connectionId:(Date.now()%1e6).toString(),metadata:v}};this.ws.send(JSON.stringify(x))},this.ws.onmessage=async _=>{var x;const v=JSON.parse(_.data);if(v.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(v.payload.sdp));else if(v.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(v.payload.candidate))}catch(T){(x=this.config.logger)==null||x.error("Error adding ICE candidate:",T)}},this.ws.onclose=_=>{_.code!==1e3&&this.errorCallbacks.forEach(v=>{v("Oops! The connection to the server was lost. Please try again later.")}),this._stopAnalyzers()}}async disconnect(){var f;this.isConnected&&(this.isConnected=!1,((f=this.ws)==null?void 0:f.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(i=>i.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(f){this.visualizerCallbacks.push(f)}addMessageCallback(f){this.messageCallbacks.push(f)}addErrorCallback(f){this.errorCallbacks.push(f)}createDataChannel(f="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(f),this.dataChannel.onopen=()=>{var i,p;for((i=this.config.logger)==null||i.info("Data channel opened");this.queuedMessages.length>0;){const _=this.queuedMessages.shift();_&&(this.dataChannel.send(JSON.stringify(_)),(p=this.config.logger)==null||p.info("Sent queued message:",_))}},this.dataChannel.onmessage=i=>{this.messageCallbacks.forEach(p=>{p(i)})})}sendPacket(f){var i;if(!this.dataChannel||this.dataChannel.readyState!=="open"){this.queuedMessages.push(f);return}this.dataChannel.send(JSON.stringify(f)),(i=this.config.logger)==null||i.info("Sent message:",f)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const f=this.audioCtx.createMediaStreamSource(this.localStream),i=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,f.connect(this.localAnalyser),i.connect(this.remoteAnalyser);const p=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const _=new Uint8Array(this.localAnalyser.frequencyBinCount),v=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(_),this.remoteAnalyser.getByteFrequencyData(v);const x=_.reduce((b,B)=>b+B,0)/_.length,T=v.reduce((b,B)=>b+B,0)/v.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(b=>{b({localAmplitude:x,remoteAmplitude:T})}),this.analyzerFrame=requestAnimationFrame(p)};this.analyzerFrame=requestAnimationFrame(p)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class Qi extends Ce{constructor(i){super();W(this,"status");W(this,"session");W(this,"autostart");W(this,"config");W(this,"webRTCClient");this.config=i,this.status="disconnected",this.session=null,this.autostart=(i==null?void 0:i.autostart)??!1,this.webRTCClient=new Pg(i),this.webRTCClient.addMessageCallback(p=>{const _=JSON.parse(p.data);this.notifyPacket(_)}),this.webRTCClient.addErrorCallback(p=>{var _;(_=this.config.logger)==null||_.error("WebRTC error:",p),this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:p}})})}getName(){return"webrtc"}getPriority(){return 1e3}async syncSession(i){super.syncSession(i),this.status==="connected"&&(await this.disconnect(),await this.connect(i))}async connect(i){var p;return this.status==="connected"?Promise.resolve(this.session):(this.session=i||this.session||"new",this.setStatus("connecting"),(p=this.config.logger)==null||p.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var i,p,_;if(this.status==="disconnected")return(i=this.config.logger)==null||i.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(_=(p=this.config)==null?void 0:p.logger)==null||_.debug("Disconnected from WebRTC")}sendPacket(i){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendPacket(i),Promise.resolve())}}var be=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Eg(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}var Sr={exports:{}};/**
2
2
  * @license
3
3
  * Lodash <https://lodash.com/>
4
4
  * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>