@applica-software-guru/persona-sdk 0.1.44-preview10 → 0.1.44-preview11

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.
@@ -6,5 +6,5 @@ var personaSDK=function(u,c,m){"use strict";var Z=Object.defineProperty;var q=(u
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var I;function L(){if(I)return b;I=1;var i=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,n,a){var r=null;if(a!==void 0&&(r=""+a),n.key!==void 0&&(r=""+n.key),"key"in n){a={};for(var h in n)h!=="key"&&(a[h]=n[h])}else a=n;return n=a.ref,{$$typeof:i,type:s,key:r,ref:n!==void 0?n:null,props:a}}return b.Fragment=t,b.jsx=e,b.jsxs=e,b}M.exports=L();var R=M.exports;function O(i){return i.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function j(i){const t=[];let e=null;for(const s of i)s.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(s)):s.functionCalls?(e&&t.push(e),t.push(s),e=null):s.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:s.functionResponse}:e&&s.protocol===e.protocol&&(e.role===s.role||s.finishReason==="stop")?e.text+=s.text:(e&&t.push(e),e={...s});return e&&t.push(e),O(t)}function F(i){var t;return i.role==="function"?{id:i.id,role:"assistant",status:(i==null?void 0:i.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((t=i.functionCalls)==null?void 0:t.map(e=>{var s;return{type:"tool-call",toolName:e.name,toolCallId:e.id,args:e.args,result:(s=i.functionResponse)==null?void 0:s.result}}))??[]}:{id:i.id,role:i.role,content:i.type==="reasoning"?[{type:"reasoning",text:i.text}]:[{type:"text",text:i.text}]}}class S{constructor(){o(this,"statusChangeCallbacks",[]);o(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addMessageListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyMessage(t){this.messageCallbacks.forEach(e=>e(t))}async notifyMessages(t){t.forEach(e=>{this.messageCallbacks.forEach(s=>s(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(s=>s(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class x extends S{constructor(e){super();o(this,"status");o(this,"autostart");o(this,"session");o(this,"config");o(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async send(e){const{apiUrl:s,apiKey:n,agentId:a}=this.config,r=this.session??"new",h=e,f=await(await fetch(`${s}/agents/${a}/sessions/${r}/messages`,{body:JSON.stringify({userMessage:h}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":n,"x-persona-apikey":n}})).json();this.notifyMessages(f.response.messages)}}class A extends S{constructor(e){super();o(this,"status");o(this,"autostart");o(this,"session");o(this,"config");o(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(e){var s;(s=this.config.logger)==null||s.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var h;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const s=e||this.session||"new";(h=this.config.logger)==null||h.debug("Connecting to WebSocket with sessionId:",s);const n=encodeURIComponent(this.config.apiKey),a=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${s}&agentId=${a}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",d=>{const f=JSON.parse(d.data);if(f.type!=="message")return;const p=f.payload;this.notifyMessage(p!=null&&p.thought?{role:"assistant",type:"reasoning",text:p.thought}:p)}),this.webSocket.addEventListener("close",()=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",d=>{var f;this.setStatus("disconnected"),this.webSocket=null,(f=this.config.logger)==null||f.error("WebSocket error",d)}),Promise.resolve(s)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:e})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class U{constructor(t){o(this,"config");o(this,"pc",null);o(this,"ws",null);o(this,"localStream",null);o(this,"remoteStream",new MediaStream);o(this,"audioCtx",null);o(this,"localAnalyser",null);o(this,"remoteAnalyser",null);o(this,"analyzerFrame",null);o(this,"dataChannel",null);o(this,"isConnected",!1);o(this,"visualizerCallbacks",[]);o(this,"messageCallbacks",[]);this.config=t}async connect(t){var e;if(!this.isConnected){this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(s){(e=this.config.logger)==null||e.error("Error accessing microphone:",s);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(s=>{this.pc.addTrack(s,this.localStream)}),this.pc.ontrack=s=>{s.streams[0].getTracks().forEach(a=>{this.remoteStream.addTrack(a)}),this.audioCtx||this._startAnalyzers();const n=new Audio;n.srcObject=this.remoteStream,n.play().catch(a=>{var r;(r=this.config.logger)==null||r.error("Error playing remote audio:",a)})},this.pc.onicecandidate=s=>{var n;s.candidate&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:s.candidate}}))},this.pc.ondatachannel=s=>{const n=s.channel;n.onmessage=a=>{this.messageCallbacks.forEach(r=>{r(a)})}},this.ws=new WebSocket(this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc"),this.ws.onopen=async()=>{var r,h;const s=await this.pc.createOffer();await this.pc.setLocalDescription(s);const n={agentId:this.config.agentId,sessionCode:t};(r=this.config.logger)==null||r.debug("Opening connection to WebRTC server: ",n);const a={type:"OFFER",src:((h=crypto.randomUUID)==null?void 0:h.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:s.sdp,type:s.type},connectionId:(Date.now()%1e6).toString(),metadata:n}};this.ws.send(JSON.stringify(a))},this.ws.onmessage=async s=>{var a;const n=JSON.parse(s.data);if(n.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(n.payload.sdp));else if(n.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(n.payload.candidate))}catch(r){(a=this.config.logger)==null||a.error("Error adding ICE candidate:",r)}},this.ws.onclose=()=>{this._stopAnalyzers()}}}async disconnect(){var t;this.isConnected&&(this.isConnected=!1,((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(e=>e.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(t){this.visualizerCallbacks.push(t)}addMessageCallback(t){this.messageCallbacks.push(t)}createDataChannel(t="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(t),this.dataChannel.onopen=()=>{var e;return(e=this.config.logger)==null?void 0:e.info("Data channel opened")},this.dataChannel.onmessage=e=>{this.messageCallbacks.forEach(s=>{s(e)})})}sendMessage(t){var e,s;if(!this.dataChannel){(e=this.config.logger)==null||e.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(t),(s=this.config.logger)==null||s.info("Sent message:",t)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const t=this.audioCtx.createMediaStreamSource(this.localStream),e=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,t.connect(this.localAnalyser),e.connect(this.remoteAnalyser);const s=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),a=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(a);const r=n.reduce((d,f)=>d+f,0)/n.length,h=a.reduce((d,f)=>d+f,0)/a.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(d=>{d({localAmplitude:r,remoteAmplitude:h})}),this.analyzerFrame=requestAnimationFrame(s)};this.analyzerFrame=requestAnimationFrame(s)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class v extends S{constructor(e){super();o(this,"status");o(this,"session");o(this,"autostart");o(this,"config");o(this,"webRTCClient");this.config=e,this.status="disconnected",this.session=null,this.autostart=(e==null?void 0:e.autostart)??!1,this.webRTCClient=new U(e),this.webRTCClient.addMessageCallback(s=>{var a;(a=e.logger)==null||a.debug("Received data message:",s.data);const n=JSON.parse(s.data);n.type==="message"&&this.notifyMessage(n.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var s;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(s=this.config.logger)==null||s.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 e,s,n;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(s=this.config)==null?void 0:s.logger)==null||n.debug("Disconnected from WebRTC")}send(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(e),Promise.resolve())}}const E=c.createContext(void 0);function J({dev:i=!1,protocols:t,logger:e,children:s,session:n="new",...a}){const[r,h]=c.useState(!1),[d,f]=c.useState([]),[p,Y]=c.useState(n),[P,G]=c.useState(new Map),W=c.useRef(!1),C=c.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const l=i?"localhost:8000":"persona.applica.guru/api",y=i?"http":"https",w=i?"ws":"wss";return Object.keys(t).map(g=>{switch(g){case"rest":const k=t[g];return k===!0?new x({apiUrl:`${y}://${l}`,apiKey:a.apiKey,agentId:a.agentId,logger:e}):new x(k);case"webrtc":const z=t[g];return z===!0?new v({webrtcUrl:`${w}://${l}/webrtc`,apiKey:a.apiKey,agentId:a.agentId,logger:e}):new v(z);case"websocket":const D=t[g];return D===!0?new A({webSocketUrl:`${w}://${l}/websocket`,apiKey:a.apiKey,agentId:a.agentId,logger:e}):new A(D);default:throw new Error(`Unknown protocol: ${g}`)}})}throw new Error("Invalid protocols configuration")},[]);c.useEffect(()=>{W.current||(W.current=!0,e==null||e.debug("Initializing protocols: ",C.map(l=>l.getName())),C.forEach(l=>{l.setSession(p),l.clearListeners(),l.addStatusChangeListener(y=>{e==null||e.debug(`${l.getName()} has notified new status: ${y}`),P.set(l.getName(),y),G(new Map(P))}),l.addMessageListener(y=>{f(w=>j([...w,{...y,protocol:l.getName()}]))}),l.autostart&&l.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${l.getName()}`),l.connect(p))}))},[p,C,e,P]);const V=async l=>{var T;if(((T=l.content[0])==null?void 0:T.type)!=="text")throw new Error("Only text messages are supported");const y=l.content[0].text;f(g=>[...g,{role:"user",type:"text",text:y}]),h(!0);const w=C.sort((g,k)=>k.getPriority()-g.getPriority()).find(g=>g.status==="connected");await(w==null?void 0:w.send(y)),h(!1)},H=c.useCallback(()=>(h(!1),f([]),Y("new"),Promise.resolve()),[]),Q=c.useCallback(()=>Promise.resolve(),[]),X=m.useExternalStoreRuntime({isRunning:r,messages:d,convertMessage:F,onNew:V,onCancel:H,onReload:Q});return R.jsx(E.Provider,{value:{protocols:C,protocolsStatus:P},children:R.jsx(m.AssistantRuntimeProvider,{runtime:X,children:s})})}function $({children:i,...t}){return R.jsx(J,{...t,children:i})}function B(){const i=c.useContext(E);if(!i)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return i}function N(i){const t=c.useContext(E);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(n=>n.getName()===i);if(!e)return null;const s=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),send:e.send.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addMessageListener:e.addMessageListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:s||e.status}}function _(){return N("webrtc")}class K{constructor(){o(this,"prefix","[Persona]")}log(t,...e){console.log(`${this.prefix} - ${t}`,...e)}info(t,...e){console.info(`${this.prefix} - ${t}`,...e)}warn(t,...e){console.warn(`${this.prefix} - ${t}`,...e)}error(t,...e){console.error(`${this.prefix} - ${t}`,...e)}debug(t,...e){console.debug(`${this.prefix} - ${t}`,...e)}}return u.PersonaConsoleLogger=K,u.PersonaProtocolBase=S,u.PersonaRESTProtocol=x,u.PersonaRuntimeProvider=$,u.PersonaWebRTCProtocol=v,u.PersonaWebSocketProtocol=A,u.usePersonaRuntime=B,u.usePersonaRuntimeProtocol=N,u.usePersonaRuntimeWebRTCProtocol=_,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),u}({},React,react);
9
+ */var I;function L(){if(I)return b;I=1;var i=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,n,a){var r=null;if(a!==void 0&&(r=""+a),n.key!==void 0&&(r=""+n.key),"key"in n){a={};for(var h in n)h!=="key"&&(a[h]=n[h])}else a=n;return n=a.ref,{$$typeof:i,type:s,key:r,ref:n!==void 0?n:null,props:a}}return b.Fragment=t,b.jsx=e,b.jsxs=e,b}M.exports=L();var R=M.exports;function O(i){return i.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function j(i){const t=[];let e=null;for(const s of i)s.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(s)):s.functionCalls?(e&&t.push(e),t.push(s),e=null):s.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:s.functionResponse}:e&&s.protocol===e.protocol&&(e.role===s.role||s.finishReason==="stop")?e.text+=s.text:(e&&t.push(e),e={...s});return e&&t.push(e),O(t)}function F(i){var t;return i.role==="function"?{id:i.id,role:"assistant",status:(i==null?void 0:i.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((t=i.functionCalls)==null?void 0:t.map(e=>{var s;return{type:"tool-call",toolName:e.name,toolCallId:e.id,args:e.args,result:(s=i.functionResponse)==null?void 0:s.result}}))??[]}:{id:i.id,role:i.role,content:i.type==="reasoning"?[{type:"reasoning",text:i.text}]:[{type:"text",text:i.text}]}}class S{constructor(){o(this,"statusChangeCallbacks",[]);o(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addMessageListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyMessage(t){this.messageCallbacks.forEach(e=>e(t))}async notifyMessages(t){t.forEach(e=>{this.messageCallbacks.forEach(s=>s(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(s=>s(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class x extends S{constructor(e){super();o(this,"status");o(this,"autostart");o(this,"session");o(this,"config");o(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async send(e){const{apiUrl:s,apiKey:n,agentId:a}=this.config,r=this.session??"new",h=e,f=await(await fetch(`${s}/agents/${a}/sessions/${r}/messages`,{body:JSON.stringify({userMessage:h}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":n,"x-persona-apikey":n}})).json();this.notifyMessages(f.response.messages)}}class A extends S{constructor(e){super();o(this,"status");o(this,"autostart");o(this,"session");o(this,"config");o(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(e){var s;(s=this.config.logger)==null||s.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var h;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const s=e||this.session||"new";(h=this.config.logger)==null||h.debug("Connecting to WebSocket with sessionId:",s);const n=encodeURIComponent(this.config.apiKey),a=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${s}&agentId=${a}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",d=>{const f=JSON.parse(d.data);if(f.type!=="message")return;const p=f.payload;this.notifyMessage(p!=null&&p.thought?{role:"assistant",type:"reasoning",text:p.thought}:p)}),this.webSocket.addEventListener("close",()=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",d=>{var f;this.setStatus("disconnected"),this.webSocket=null,(f=this.config.logger)==null||f.error("WebSocket error",d)}),Promise.resolve(s)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:e})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class U{constructor(t){o(this,"config");o(this,"pc",null);o(this,"ws",null);o(this,"localStream",null);o(this,"remoteStream",new MediaStream);o(this,"audioCtx",null);o(this,"localAnalyser",null);o(this,"remoteAnalyser",null);o(this,"analyzerFrame",null);o(this,"dataChannel",null);o(this,"isConnected",!1);o(this,"visualizerCallbacks",[]);o(this,"messageCallbacks",[]);this.config=t}async connect(t){var e;if(!this.isConnected){this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(s){(e=this.config.logger)==null||e.error("Error accessing microphone:",s);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(s=>{this.pc.addTrack(s,this.localStream)}),this.pc.ontrack=s=>{s.streams[0].getTracks().forEach(a=>{this.remoteStream.addTrack(a)}),this.audioCtx||this._startAnalyzers();const n=new Audio;n.srcObject=this.remoteStream,n.play().catch(a=>{var r;(r=this.config.logger)==null||r.error("Error playing remote audio:",a)})},this.pc.onicecandidate=s=>{var n;s.candidate&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:s.candidate}}))},this.pc.ondatachannel=s=>{const n=s.channel;n.onmessage=a=>{this.messageCallbacks.forEach(r=>{r(a)})}},this.ws=new WebSocket(this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc"),this.ws.onopen=async()=>{var r,h;const s=await this.pc.createOffer();await this.pc.setLocalDescription(s);const n={agentId:this.config.agentId,sessionCode:t};(r=this.config.logger)==null||r.debug("Opening connection to WebRTC server: ",n);const a={type:"OFFER",src:((h=crypto.randomUUID)==null?void 0:h.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:s.sdp,type:s.type},connectionId:(Date.now()%1e6).toString(),metadata:n}};this.ws.send(JSON.stringify(a))},this.ws.onmessage=async s=>{var a;const n=JSON.parse(s.data);if(n.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(n.payload.sdp));else if(n.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(n.payload.candidate))}catch(r){(a=this.config.logger)==null||a.error("Error adding ICE candidate:",r)}},this.ws.onclose=()=>{this._stopAnalyzers()}}}async disconnect(){var t;this.isConnected&&(this.isConnected=!1,((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(e=>e.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(t){this.visualizerCallbacks.push(t)}addMessageCallback(t){this.messageCallbacks.push(t)}createDataChannel(t="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(t),this.dataChannel.onopen=()=>{var e;return(e=this.config.logger)==null?void 0:e.info("Data channel opened")},this.dataChannel.onmessage=e=>{this.messageCallbacks.forEach(s=>{s(e)})})}sendMessage(t){var e,s;if(!this.dataChannel){(e=this.config.logger)==null||e.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(t),(s=this.config.logger)==null||s.info("Sent message:",t)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const t=this.audioCtx.createMediaStreamSource(this.localStream),e=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,t.connect(this.localAnalyser),e.connect(this.remoteAnalyser);const s=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),a=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(a);const r=n.reduce((d,f)=>d+f,0)/n.length,h=a.reduce((d,f)=>d+f,0)/a.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(d=>{d({localAmplitude:r,remoteAmplitude:h})}),this.analyzerFrame=requestAnimationFrame(s)};this.analyzerFrame=requestAnimationFrame(s)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class v extends S{constructor(e){super();o(this,"status");o(this,"session");o(this,"autostart");o(this,"config");o(this,"webRTCClient");this.config=e,this.status="disconnected",this.session=null,this.autostart=(e==null?void 0:e.autostart)??!1,this.webRTCClient=new U(e),this.webRTCClient.addMessageCallback(s=>{var a;(a=e.logger)==null||a.debug("Received data message:",s.data);const n=JSON.parse(s.data);n.type==="message"&&this.notifyMessage(n.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var s;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(s=this.config.logger)==null||s.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 e,s,n;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(s=this.config)==null?void 0:s.logger)==null||n.debug("Disconnected from WebRTC")}send(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(e),Promise.resolve())}}const E=c.createContext(void 0);function J({dev:i=!1,protocols:t,logger:e,children:s,session:n="new",...a}){const[r,h]=c.useState(!1),[d,f]=c.useState([]),[p,Y]=c.useState(n),[P,G]=c.useState(new Map),W=c.useRef(!1),C=c.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const l=i?"localhost:8000":"persona.applica.guru/api",y=i?"http":"https",w=i?"ws":"wss";return Object.keys(t).map(g=>{switch(g){case"rest":const k=t[g];return k===!0?new x({apiUrl:`${y}://${l}`,apiKey:a.apiKey,agentId:a.agentId,logger:e}):new x(k);case"webrtc":const z=t[g];return z===!0?new v({webrtcUrl:`${w}://${l}/webrtc`,apiKey:a.apiKey,agentId:a.agentId,logger:e}):new v(z);case"websocket":const D=t[g];return D===!0?new A({webSocketUrl:`${w}://${l}/websocket`,apiKey:a.apiKey,agentId:a.agentId,logger:e}):new A(D);default:throw new Error(`Unknown protocol: ${g}`)}})}throw new Error("Invalid protocols configuration")},[]);c.useEffect(()=>{W.current||(W.current=!0,e==null||e.debug("Initializing protocols: ",C.map(l=>l.getName())),C.forEach(l=>{l.setSession(p),l.clearListeners(),l.addStatusChangeListener(y=>{e==null||e.debug(`${l.getName()} has notified new status: ${y}`),P.set(l.getName(),y),G(new Map(P))}),l.addMessageListener(y=>{f(w=>j([...w,{...y,protocol:l.getName()}]))}),l.autostart&&l.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${l.getName()}`),l.connect(p))}))},[p,C,e,P]);const V=async l=>{var T;if(((T=l.content[0])==null?void 0:T.type)!=="text")throw new Error("Only text messages are supported");const y=l.content[0].text;f(g=>[...g,{role:"user",type:"text",text:y}]),h(!0);const w=C.sort((g,k)=>k.getPriority()-g.getPriority()).find(g=>g.status==="connected");await(w==null?void 0:w.send(y)),h(!1)},H=c.useCallback(()=>(h(!1),f([]),Y("new"),Promise.resolve()),[]),Q=c.useCallback(()=>Promise.resolve(),[]),X=m.useExternalStoreRuntime({isRunning:r,messages:d,convertMessage:F,onNew:V,onCancel:H,onReload:Q});return R.jsx(E.Provider,{value:{protocols:C,protocolsStatus:P},children:R.jsx(m.AssistantRuntimeProvider,{runtime:X,children:s})})}function $({children:i,...t}){return R.jsx(J,{...t,children:i})}function B(){const i=c.useContext(E);if(!i)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return i}function N(i){const t=c.useContext(E);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(n=>n.getName()===i);if(!e)return null;const s=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),send:e.send.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addMessageListener:e.addMessageListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:s||e.status}}function _(){return N("webrtc")}class K{constructor(){o(this,"prefix","[Persona]")}log(t,...e){console.log(`${this.prefix} - ${t}`,...e)}info(t,...e){console.info(`${this.prefix} - ${t}`,...e)}warn(t,...e){console.warn(`${this.prefix} - ${t}`,...e)}error(t,...e){console.error(`${this.prefix} - ${t}`,...e)}debug(t,...e){console.debug(`${this.prefix} - ${t}`,...e)}}return u.PersonaConsoleLogger=K,u.PersonaProtocolBase=S,u.PersonaRESTProtocol=x,u.PersonaRuntimeProvider=$,u.PersonaWebRTCProtocol=v,u.PersonaWebSocketProtocol=A,u.usePersonaRuntime=B,u.usePersonaRuntimeProtocol=N,u.usePersonaRuntimeWebRTCProtocol=_,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),u}({},React,AssistantUI);
10
10
  //# sourceMappingURL=bundle.iife.js.map
@@ -1,4 +1,4 @@
1
- (function(c,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("react"),require("@assistant-ui/react")):typeof define=="function"&&define.amd?define(["exports","react","@assistant-ui/react"],r):(c=typeof globalThis<"u"?globalThis:c||self,r(c.personaSDK={},c.React,c.react))})(this,function(c,r,w){"use strict";var X=Object.defineProperty;var Z=(c,r,w)=>r in c?X(c,r,{enumerable:!0,configurable:!0,writable:!0,value:w}):c[r]=w;var o=(c,r,w)=>Z(c,typeof r!="symbol"?r+"":r,w);var M={exports:{}},b={};/**
1
+ (function(c,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("react"),require("@assistant-ui/react")):typeof define=="function"&&define.amd?define(["exports","react","@assistant-ui/react"],r):(c=typeof globalThis<"u"?globalThis:c||self,r(c.personaSDK={},c.React,c.AssistantUI))})(this,function(c,r,w){"use strict";var X=Object.defineProperty;var Z=(c,r,w)=>r in c?X(c,r,{enumerable:!0,configurable:!0,writable:!0,value:w}):c[r]=w;var o=(c,r,w)=>Z(c,typeof r!="symbol"?r+"":r,w);var M={exports:{}},b={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.js
4
4
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@applica-software-guru/persona-sdk",
3
3
  "private": false,
4
- "version": "0.1.44-preview10",
4
+ "version": "0.1.44-preview11",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "dev": "vite",
package/vite.config.ts CHANGED
@@ -26,6 +26,7 @@ export default defineConfig((configEnv: ConfigEnv) => {
26
26
  react: 'React',
27
27
  'react/jsx-runtime': 'React',
28
28
  'react/jsx-dev-runtime': 'React',
29
+ '@assistant-ui/react': 'AssistantUI',
29
30
  },
30
31
  },
31
32
  },