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

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
- (function(k,wn){typeof exports=="object"&&typeof module<"u"?wn(exports,require("react/jsx-runtime"),require("react"),require("@assistant-ui/react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","@assistant-ui/react"],wn):(k=typeof globalThis<"u"?globalThis:k||self,wn(k.personaSDK={},k.React,k.React,k.AssistantUI))})(this,function(k,wn,G,Ee){"use strict";var s_=Object.defineProperty;var o_=(k,wn,G)=>wn in k?s_(k,wn,{enumerable:!0,configurable:!0,writable:!0,value:G}):k[wn]=G;var W=(k,wn,G)=>o_(k,typeof wn!="symbol"?wn+"":wn,G);let Uo=0;function Bo(){return`msg_${Date.now()}_${Uo++}`}function Mo(d){return d.thought&&(d={...d,type:"reasoning"}),d.id?d.createdAt?d:{...d,createdAt:new Date}:{...d,id:Bo(),createdAt:d.createdAt||new Date}}function $o(d){return d.filter(f=>f.finishReason==="stop"?f.text!==null&&f.text.trim()!=="":!0)}function $t(d){const f=[];let i=null;for(let _ of d)if(_=Mo(_),_.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),$o(f)}function Ko(d){var _,v,x;const f=d.file?[{type:"file",data:d.file.url,mimeType:d.file.contentType}]:[];let i;if((d.role==="assistant"||d.role==="function")&&(d.status?i=d.status:d.finishReason==="stop"?i={type:"complete",reason:"stop"}:d.finishReason==="function_call"?i={type:"complete",reason:"stop"}:d.finishReason||(i=void 0)),d.role==="function"){const T={id:d.id,role:"assistant",createdAt:d.createdAt,content:((_=d.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=d.functionResponse)==null?void 0:B.result}}))??[],metadata:{...d.metadata,custom:{protocol:d.protocol,sessionId:d.sessionId,sources:d.sources,...(v=d.metadata)==null?void 0:v.custom}}};return i?{...T,status:i}:T}const p={id:d.id,role:d.role,createdAt:d.createdAt,content:d.type==="reasoning"?[{type:"reasoning",text:d.text},...f]:[{type:"text",text:d.text},...f],metadata:{...d.metadata,custom:{protocol:d.protocol,sessionId:d.sessionId,sources:d.sources,type:d.type,...(x=d.metadata)==null?void 0:x.custom}}};return d.role==="assistant"&&i?{...p,status:i}:p}class ue{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 Ir extends ue{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,H,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 Z=(H=i==null?void 0:i.payload)==null?void 0:H.arguments.tools;(Z==null?void 0:Z.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 Y=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(Y.response.messages.map($=>({type:"message",payload:$})))}catch(Z){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:",Z)}}}class Rr extends ue{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 qo{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 Pr extends ue{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 qo(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 se=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ko(d){return d&&d.__esModule&&Object.prototype.hasOwnProperty.call(d,"default")?d.default:d}var Te={exports:{}};/**
1
+ (function(k,wn){typeof exports=="object"&&typeof module<"u"?wn(exports,require("react/jsx-runtime"),require("react"),require("@assistant-ui/react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","@assistant-ui/react"],wn):(k=typeof globalThis<"u"?globalThis:k||self,wn(k.personaSDK={},k.React,k.React,k.AssistantUI))})(this,function(k,wn,G,Ee){"use strict";var s_=Object.defineProperty;var o_=(k,wn,G)=>wn in k?s_(k,wn,{enumerable:!0,configurable:!0,writable:!0,value:G}):k[wn]=G;var W=(k,wn,G)=>o_(k,typeof wn!="symbol"?wn+"":wn,G);let Uo=0;function Bo(){return`msg_${Date.now()}_${Uo++}`}function Mo(d){return d.thought&&(d={...d,type:"reasoning"}),d.id?d.createdAt?d:{...d,createdAt:new Date}:{...d,id:Bo(),createdAt:d.createdAt||new Date}}function $o(d){return d.filter(f=>f.finishReason==="stop"?f.text!==null&&f.text.trim()!=="":!0)}function $t(d){const f=[];let i=null;for(let _ of d)if(_=Mo(_),_.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});return i&&f.push(i),$o(f)}function Ko(d){var _,v,x;const f=d.file?[{type:"file",data:d.file.url,mimeType:d.file.contentType}]:[];let i;if((d.role==="assistant"||d.role==="function")&&(d.status?i=d.status:d.finishReason==="stop"?i={type:"complete",reason:"stop"}:d.finishReason==="function_call"?i={type:"complete",reason:"stop"}:d.finishReason||(i=void 0)),d.role==="function"){const T={id:d.id,role:"assistant",createdAt:d.createdAt,content:((_=d.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=d.functionResponse)==null?void 0:B.result}}))??[],metadata:{...d.metadata,custom:{protocol:d.protocol,sessionId:d.sessionId,sources:d.sources,...(v=d.metadata)==null?void 0:v.custom}}};return i?{...T,status:i}:T}const p={id:d.id,role:d.role,createdAt:d.createdAt,content:d.type==="reasoning"?[{type:"reasoning",text:d.text},...f]:[{type:"text",text:d.text},...f],metadata:{...d.metadata,custom:{protocol:d.protocol,sessionId:d.sessionId,sources:d.sources,type:d.type,...(x=d.metadata)==null?void 0:x.custom}}};return d.role==="assistant"&&i?{...p,status:i}:p}class ue{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 Ir extends ue{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,H,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 Z=(H=i==null?void 0:i.payload)==null?void 0:H.arguments.tools;(Z==null?void 0:Z.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 Y=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(Y.response.messages.map($=>({type:"message",payload:$})))}catch(Z){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:",Z)}}}class Rr extends ue{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 qo{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 Pr extends ue{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 qo(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 se=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ko(d){return d&&d.__esModule&&Object.prototype.hasOwnProperty.call(d,"default")?d.default:d}var Te={exports:{}};/**
2
2
  * @license
3
3
  * Lodash <https://lodash.com/>
4
4
  * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>