@applica-software-guru/persona-sdk 0.1.55 → 0.1.56

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 @@
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 N;function K(){if(N)return S;N=1;var i=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(n,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var l in s)l!=="key"&&(o[l]=s[l])}else o=s;return s=o.ref,{$$typeof:i,type:n,key:r,ref:s!==void 0?s:null,props:o}}return S.Fragment=t,S.jsx=e,S.jsxs=e,S}I.exports=K();var A=I.exports;function B(i){return i.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function _(i){const t=[];let e=null;for(const s of i)s.type!=="transaction"&&(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.files=[...e.files??[],...s.files??[]]):(e&&t.push(e),e={...s}));return e&&t.push(e),B(t)}function Y(i){var e,n;const t=((e=i.files)==null?void 0:e.map(s=>({type:"file",data:s.url,mimeType:s.contentType})))??[];return i.role==="function"?{id:i.id,role:"assistant",status:(i==null?void 0:i.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((n=i.functionCalls)==null?void 0:n.map(s=>{var o;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(o=i.functionResponse)==null?void 0:o.result}}))??[]}:{id:i.id,role:i.role,content:i.type==="reasoning"?[{type:"reasoning",text:i.text},...t]:[{type:"text",text:i.text},...t]}}class P{constructor(){a(this,"statusChangeCallbacks",[]);a(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(n=>n(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(n=>n(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(t){}}class E extends P{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(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:n,apiKey:s,agentId:o}=this.config,r=this.session??"new",l=e,d=await(await fetch(`${n}/agents/${o}/sessions/${r}/messages`,{body:JSON.stringify({userMessage:l}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":s,"x-persona-apikey":s}})).json();this.notifyMessages(d.response.messages.map(C=>({type:"message",payload:C})))}}class v extends P{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(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 n;(n=this.config.logger)==null||n.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var l;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const n=e||this.session||"new";(l=this.config.logger)==null||l.debug("Connecting to WebSocket with sessionId:",n);const s=encodeURIComponent(this.config.apiKey),o=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${n}&agentId=${o}&apiKey=${s}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",u=>{const d=JSON.parse(u.data);this.notifyMessage(d)}),this.webSocket.addEventListener("close",()=>{var u;this.setStatus("disconnected"),this.webSocket=null,(u=this.config.logger)==null||u.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",u=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.error("WebSocket error",u)}),Promise.resolve(n)}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 G{constructor(t){a(this,"config");a(this,"pc",null);a(this,"ws",null);a(this,"localStream",null);a(this,"remoteStream",new MediaStream);a(this,"audioCtx",null);a(this,"localAnalyser",null);a(this,"remoteAnalyser",null);a(this,"analyzerFrame",null);a(this,"dataChannel",null);a(this,"isConnected",!1);a(this,"visualizerCallbacks",[]);a(this,"messageCallbacks",[]);this.config=t}async connect(t){var n;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(s){(n=this.config.logger)==null||n.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(r=>{this.remoteStream.addTrack(r)}),this.audioCtx||this._startAnalyzers();const o=new Audio;o.srcObject=this.remoteStream,o.play().catch(r=>{var l;(l=this.config.logger)==null||l.error("Error playing remote audio:",r)})},this.pc.onicecandidate=s=>{var o;s.candidate&&((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:s.candidate}}))},this.pc.ondatachannel=s=>{const o=s.channel;o.onmessage=r=>{this.messageCallbacks.forEach(l=>{l(r)})}};const e=this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc";this.ws=new WebSocket(`${e}?apiKey=${encodeURIComponent(this.config.apiKey)}`),this.ws.onopen=async()=>{var l,u;const s=await this.pc.createOffer();await this.pc.setLocalDescription(s);const o={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(l=this.config.logger)==null||l.debug("Opening connection to WebRTC server: ",o);const r={type:"OFFER",src:((u=crypto.randomUUID)==null?void 0:u.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:s.sdp,type:s.type},connectionId:(Date.now()%1e6).toString(),metadata:o}};this.ws.send(JSON.stringify(r))},this.ws.onmessage=async s=>{var r;const o=JSON.parse(s.data);if(o.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(o.payload.sdp));else if(o.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(o.payload.candidate))}catch(l){(r=this.config.logger)==null||r.error("Error adding ICE candidate:",l)}},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(n=>{n(e)})})}sendMessage(t){var e,n;if(!this.dataChannel){(e=this.config.logger)==null||e.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(JSON.stringify({type:"request",payload:t})),(n=this.config.logger)==null||n.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 n=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const s=new Uint8Array(this.localAnalyser.frequencyBinCount),o=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(s),this.remoteAnalyser.getByteFrequencyData(o);const r=s.reduce((u,d)=>u+d,0)/s.length,l=o.reduce((u,d)=>u+d,0)/o.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(u=>{u({localAmplitude:r,remoteAmplitude:l})}),this.analyzerFrame=requestAnimationFrame(n)};this.analyzerFrame=requestAnimationFrame(n)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class $ extends P{constructor(e){super();a(this,"status");a(this,"session");a(this,"autostart");a(this,"config");a(this,"webRTCClient");this.config=e,this.status="disconnected",this.session=null,this.autostart=(e==null?void 0:e.autostart)??!1,this.webRTCClient=new G(e),this.webRTCClient.addMessageCallback(n=>{const s=JSON.parse(n.data);this.notifyMessage(s)})}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 n;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(n=this.config.logger)==null||n.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,n,s;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(s=(n=this.config)==null?void 0:n.logger)==null||s.debug("Disconnected from WebRTC")}send(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(e),Promise.resolve())}}class V{constructor(t){a(this,"config");this.config=t}async complete(t,e){var n;await this.persist(t,{...e,success:!0}),(n=this.config.logger)==null||n.debug("Transaction completed:",t)}async fail(t,e){var n;await this.persist(t,{...e,success:!1}),(n=this.config.logger)==null||n.debug("Transaction failed:",{...t,...e})}async persist(t,e){await fetch(`${this.config.apiUrl}/transactions/${t.id}`,{body:JSON.stringify(e),method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-persona-apikey":this.config.apiKey}})}}class H{constructor(t,e){a(this,"transaction");a(this,"manager");this.transaction=t,this.manager=e}getFunctionCall(){return this.transaction.functionCall}async invoke(t){const e=this.transaction.functionCall;if(!e){await this.fail("No function call found");return}const n=e.name,s=e.args,o=t[n];if(!o){await this.fail(`Tool ${n} not found`);return}try{const r=await o(s);await this.complete(r)}catch(r){await this.fail(`Error executing tool ${n}: ${r}`)}}async complete(t){await this.manager.complete(this.transaction,{success:!0,output:t,error:null})}async fail(t){await this.manager.fail(this.transaction,{success:!1,output:null,error:t})}}class W extends P{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"transaction"}getPriority(){return 1e3}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){var n;throw(n=this.config.logger)==null||n.debug("Sending message:",e),new Error("Not implemented")}onTransaction(e){var o;if(!this.config.onTransaction){(o=this.config.logger)==null||o.error("Transaction protocol config is not set");return}const n=new V(this.config),s=new H(e,n);this.config.onTransaction(s)}}const T=f.createContext(void 0);function Q(i){return new Promise((t,e)=>{const n=new FileReader;n.readAsDataURL(i),n.onload=()=>{const o=n.result.split(";base64,")[1];t(o)},n.onerror=s=>{e(s)}})}function X({dev:i=!1,protocols:t,logger:e,children:n,session:s="new",...o}){const[r,l]=f.useState(!1),[u,d]=f.useState([]),[C,z]=f.useState(s),[k,D]=f.useState(new Map),M=f.useRef(!1),w=f.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const c=i?"localhost:8000":"persona.applica.guru/api",p=i?"http":"https",y=i?"ws":"wss";let m=Object.keys(t).map(g=>{switch(g){case"rest":const h=t[g];return h===!0?new E({apiUrl:`${p}://${c}`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):typeof h=="object"&&h!==null?new E(h):null;case"webrtc":const b=t[g];return b===!0?new $({webrtcUrl:`${y}://${c}/webrtc`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):typeof b=="object"&&b!==null?new $(b):null;case"websocket":const x=t[g];return x===!0?new v({webSocketUrl:`${y}://${c}/websocket`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):typeof x=="object"&&x!==null?new v(x):null;default:throw new Error(`Unknown protocol: ${g}`)}}).filter(g=>g!==null);return o.tools&&m.push(new W({apiUrl:`${p}://${c}`,apiKey:o.apiKey,agentId:o.agentId,onTransaction:async g=>{await g.invoke(o.tools)},logger:e})),m}throw new Error("Invalid protocols configuration")},[]);f.useEffect(()=>{M.current||(M.current=!0,e==null||e.debug("Initializing protocols: ",w.map(c=>c.getName())),w.forEach(c=>{c.setSession(C),c.clearListeners(),c.addStatusChangeListener(p=>{e==null||e.debug(`${c.getName()} has notified new status: ${p}`),k.set(c.getName(),p),D(new Map(k))}),c.addMessageListener(p=>{if(p.type==="message"){const y=p.payload;d(m=>_([...m,{...y,protocol:c.getName()}]))}else p.type==="transaction"&&w.filter(y=>y!==c).forEach(y=>y.onTransaction(p.payload))}),c.autostart&&c.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${c.getName()}`),c.connect(C))}))},[C,w,e,k]);const O=async c=>{var g;if(((g=c.content[0])==null?void 0:g.type)!=="text")throw new Error("Only text messages are supported");const p=c.content[0].text;d(h=>[...h,{role:"user",type:"text",text:p}]),l(!0);const y=w.sort((h,b)=>b.getPriority()-h.getPriority()).find(h=>h.status==="connected"),m=[];if(c.attachments)for(const h of c.attachments)h.contentType.startsWith("image/")&&h.file&&m.push({role:"user",image:{contentType:h.contentType,content:await Q(h.file)},text:"",type:"text"});c.content&&m.push({role:"user",text:c.content[0].text,type:"text"}),e==null||e.debug("Sending message:",m),await(y==null?void 0:y.send(m)),l(!1)},L=f.useCallback(()=>(l(!1),d([]),z("new"),Promise.resolve()),[]),U=f.useCallback(()=>Promise.resolve(),[]),F=R.useExternalStoreRuntime({isRunning:r,messages:u,convertMessage:Y,onNew:O,onCancel:L,onReload:U,adapters:{attachments:new R.CompositeAttachmentAdapter([new R.SimpleImageAttachmentAdapter])}});return A.jsx(T.Provider,{value:{protocols:w,protocolsStatus:k},children:A.jsx(R.AssistantRuntimeProvider,{runtime:F,children:n})})}function Z({children:i,...t}){return A.jsx(X,{...t,children:i})}function ee(){const i=f.useContext(T);if(!i)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return i}function j(i){const t=f.useContext(T);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(s=>s.getName()===i);if(!e)return null;const n=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:n||e.status}}function te(){const i=f.useContext(T);if(!i)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");for(const t of i.protocols)if(t.getName()==="rest")return t.config.apiUrl;throw new Error("REST protocol not found")}function se(){return j("webrtc")}class ne{constructor(){a(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)}}exports.PersonaConsoleLogger=ne;exports.PersonaProtocolBase=P;exports.PersonaRESTProtocol=E;exports.PersonaRuntimeProvider=Z;exports.PersonaTransactionProtocol=W;exports.PersonaWebRTCProtocol=$;exports.PersonaWebSocketProtocol=v;exports.usePersonaRuntime=ee;exports.usePersonaRuntimeEndpoint=te;exports.usePersonaRuntimeProtocol=j;exports.usePersonaRuntimeWebRTCProtocol=se;
9
+ */var N;function K(){if(N)return S;N=1;var i=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(n,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var l in s)l!=="key"&&(o[l]=s[l])}else o=s;return s=o.ref,{$$typeof:i,type:n,key:r,ref:s!==void 0?s:null,props:o}}return S.Fragment=t,S.jsx=e,S.jsxs=e,S}I.exports=K();var A=I.exports;function B(i){return i.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function _(i){const t=[];let e=null;for(const s of i)s.type!=="transaction"&&(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.files=[...e.files??[],...s.files??[]]):(e&&t.push(e),e={...s}));return e&&t.push(e),B(t)}function Y(i){var e,n;const t=((e=i.files)==null?void 0:e.map(s=>({type:"file",data:s.url,mimeType:s.contentType})))??[];return i.role==="function"?{id:i.id,role:"assistant",status:(i==null?void 0:i.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((n=i.functionCalls)==null?void 0:n.map(s=>{var o;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(o=i.functionResponse)==null?void 0:o.result}}))??[]}:{id:i.id,role:i.role,content:i.type==="reasoning"?[{type:"reasoning",text:i.text},...t]:[{type:"text",text:i.text},...t]}}class P{constructor(){a(this,"statusChangeCallbacks",[]);a(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(n=>n(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(n=>n(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(t){}}class E extends P{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 100}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:n,apiKey:s,agentId:o}=this.config,r=this.session??"new",l=e,d=await(await fetch(`${n}/agents/${o}/sessions/${r}/messages`,{body:JSON.stringify({userMessage:l}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":s,"x-persona-apikey":s}})).json();this.notifyMessages(d.response.messages.map(C=>({type:"message",payload:C})))}}class v extends P{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 500}async syncSession(e){var n;(n=this.config.logger)==null||n.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var l;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const n=e||this.session||"new";(l=this.config.logger)==null||l.debug("Connecting to WebSocket with sessionId:",n);const s=encodeURIComponent(this.config.apiKey),o=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${n}&agentId=${o}&apiKey=${s}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",u=>{const d=JSON.parse(u.data);this.notifyMessage(d)}),this.webSocket.addEventListener("close",()=>{var u;this.setStatus("disconnected"),this.webSocket=null,(u=this.config.logger)==null||u.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",u=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.error("WebSocket error",u)}),Promise.resolve(n)}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 G{constructor(t){a(this,"config");a(this,"pc",null);a(this,"ws",null);a(this,"localStream",null);a(this,"remoteStream",new MediaStream);a(this,"audioCtx",null);a(this,"localAnalyser",null);a(this,"remoteAnalyser",null);a(this,"analyzerFrame",null);a(this,"dataChannel",null);a(this,"isConnected",!1);a(this,"visualizerCallbacks",[]);a(this,"messageCallbacks",[]);this.config=t}async connect(t){var n;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(s){(n=this.config.logger)==null||n.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(r=>{this.remoteStream.addTrack(r)}),this.audioCtx||this._startAnalyzers();const o=new Audio;o.srcObject=this.remoteStream,o.play().catch(r=>{var l;(l=this.config.logger)==null||l.error("Error playing remote audio:",r)})},this.pc.onicecandidate=s=>{var o;s.candidate&&((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:s.candidate}}))},this.pc.ondatachannel=s=>{const o=s.channel;o.onmessage=r=>{this.messageCallbacks.forEach(l=>{l(r)})}};const e=this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc";this.ws=new WebSocket(`${e}?apiKey=${encodeURIComponent(this.config.apiKey)}`),this.ws.onopen=async()=>{var l,u;const s=await this.pc.createOffer();await this.pc.setLocalDescription(s);const o={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(l=this.config.logger)==null||l.debug("Opening connection to WebRTC server: ",o);const r={type:"OFFER",src:((u=crypto.randomUUID)==null?void 0:u.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:s.sdp,type:s.type},connectionId:(Date.now()%1e6).toString(),metadata:o}};this.ws.send(JSON.stringify(r))},this.ws.onmessage=async s=>{var r;const o=JSON.parse(s.data);if(o.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(o.payload.sdp));else if(o.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(o.payload.candidate))}catch(l){(r=this.config.logger)==null||r.error("Error adding ICE candidate:",l)}},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(n=>{n(e)})})}sendMessage(t){var e,n;if(!this.dataChannel){(e=this.config.logger)==null||e.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(JSON.stringify({type:"request",payload:t})),(n=this.config.logger)==null||n.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 n=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const s=new Uint8Array(this.localAnalyser.frequencyBinCount),o=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(s),this.remoteAnalyser.getByteFrequencyData(o);const r=s.reduce((u,d)=>u+d,0)/s.length,l=o.reduce((u,d)=>u+d,0)/o.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(u=>{u({localAmplitude:r,remoteAmplitude:l})}),this.analyzerFrame=requestAnimationFrame(n)};this.analyzerFrame=requestAnimationFrame(n)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class $ extends P{constructor(e){super();a(this,"status");a(this,"session");a(this,"autostart");a(this,"config");a(this,"webRTCClient");this.config=e,this.status="disconnected",this.session=null,this.autostart=(e==null?void 0:e.autostart)??!1,this.webRTCClient=new G(e),this.webRTCClient.addMessageCallback(n=>{const s=JSON.parse(n.data);this.notifyMessage(s)})}getName(){return"webrtc"}getPriority(){return 1e3}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var n;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(n=this.config.logger)==null||n.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,n,s;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(s=(n=this.config)==null?void 0:n.logger)==null||s.debug("Disconnected from WebRTC")}send(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(e),Promise.resolve())}}class V{constructor(t){a(this,"config");this.config=t}async complete(t,e){var n;await this.persist(t,{...e,success:!0}),(n=this.config.logger)==null||n.debug("Transaction completed:",t)}async fail(t,e){var n;await this.persist(t,{...e,success:!1}),(n=this.config.logger)==null||n.debug("Transaction failed:",{...t,...e})}async persist(t,e){await fetch(`${this.config.apiUrl}/transactions/${t.id}`,{body:JSON.stringify(e),method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-persona-apikey":this.config.apiKey}})}}class H{constructor(t,e){a(this,"transaction");a(this,"manager");this.transaction=t,this.manager=e}getFunctionCall(){return this.transaction.functionCall}async invoke(t){const e=this.transaction.functionCall;if(!e){await this.fail("No function call found");return}const n=e.name,s=e.args,o=t[n];if(!o){await this.fail(`Tool ${n} not found`);return}try{const r=await o(s);await this.complete(r)}catch(r){await this.fail(`Error executing tool ${n}: ${r}`)}}async complete(t){await this.manager.complete(this.transaction,{success:!0,output:t,error:null})}async fail(t){await this.manager.fail(this.transaction,{success:!1,output:null,error:t})}}class W extends P{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"transaction"}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){var n;throw(n=this.config.logger)==null||n.debug("Sending message:",e),new Error("Not implemented")}onTransaction(e){var o;if(!this.config.onTransaction){(o=this.config.logger)==null||o.error("Transaction protocol config is not set");return}const n=new V(this.config),s=new H(e,n);this.config.onTransaction(s)}}const T=f.createContext(void 0);function Q(i){return new Promise((t,e)=>{const n=new FileReader;n.readAsDataURL(i),n.onload=()=>{const o=n.result.split(";base64,")[1];t(o)},n.onerror=s=>{e(s)}})}function X({dev:i=!1,protocols:t,logger:e,children:n,session:s="new",...o}){const[r,l]=f.useState(!1),[u,d]=f.useState([]),[C,z]=f.useState(s),[k,D]=f.useState(new Map),M=f.useRef(!1),w=f.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const c=i?"localhost:8000":"persona.applica.guru/api",p=i?"http":"https",y=i?"ws":"wss";let m=Object.keys(t).map(g=>{switch(g){case"rest":const h=t[g];return h===!0?new E({apiUrl:`${p}://${c}`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):typeof h=="object"&&h!==null?new E(h):null;case"webrtc":const b=t[g];return b===!0?new $({webrtcUrl:`${y}://${c}/webrtc`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):typeof b=="object"&&b!==null?new $(b):null;case"websocket":const x=t[g];return x===!0?new v({webSocketUrl:`${y}://${c}/websocket`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):typeof x=="object"&&x!==null?new v(x):null;default:throw new Error(`Unknown protocol: ${g}`)}}).filter(g=>g!==null);return o.tools&&m.push(new W({apiUrl:`${p}://${c}`,apiKey:o.apiKey,agentId:o.agentId,onTransaction:async g=>{await g.invoke(o.tools)},logger:e})),m}throw new Error("Invalid protocols configuration")},[]);f.useEffect(()=>{M.current||(M.current=!0,e==null||e.debug("Initializing protocols: ",w.map(c=>c.getName())),w.forEach(c=>{c.setSession(C),c.clearListeners(),c.addStatusChangeListener(p=>{e==null||e.debug(`${c.getName()} has notified new status: ${p}`),k.set(c.getName(),p),D(new Map(k))}),c.addMessageListener(p=>{if(p.type==="message"){const y=p.payload;d(m=>_([...m,{...y,protocol:c.getName()}]))}else p.type==="transaction"&&w.filter(y=>y!==c).forEach(y=>y.onTransaction(p.payload))}),c.autostart&&c.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${c.getName()}`),c.connect(C))}))},[C,w,e,k]);const O=async c=>{var g;if(((g=c.content[0])==null?void 0:g.type)!=="text")throw new Error("Only text messages are supported");const p=c.content[0].text;d(h=>[...h,{role:"user",type:"text",text:p}]),l(!0);const y=w.sort((h,b)=>b.getPriority()-h.getPriority()).find(h=>h.status==="connected"),m=[];if(c.attachments)for(const h of c.attachments)h.contentType.startsWith("image/")&&h.file&&m.push({role:"user",image:{contentType:h.contentType,content:await Q(h.file)},text:"",type:"text"});c.content&&m.push({role:"user",text:c.content[0].text,type:"text"}),e==null||e.debug("Sending message:",m),await(y==null?void 0:y.send(m)),l(!1)},L=f.useCallback(()=>(l(!1),d([]),z("new"),Promise.resolve()),[]),U=f.useCallback(()=>Promise.resolve(),[]),F=R.useExternalStoreRuntime({isRunning:r,messages:u,convertMessage:Y,onNew:O,onCancel:L,onReload:U,adapters:{attachments:new R.CompositeAttachmentAdapter([new R.SimpleImageAttachmentAdapter])}});return A.jsx(T.Provider,{value:{protocols:w,protocolsStatus:k},children:A.jsx(R.AssistantRuntimeProvider,{runtime:F,children:n})})}function Z({children:i,...t}){return A.jsx(X,{...t,children:i})}function ee(){const i=f.useContext(T);if(!i)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return i}function j(i){const t=f.useContext(T);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(s=>s.getName()===i);if(!e)return null;const n=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:n||e.status}}function te(){const i=f.useContext(T);if(!i)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");for(const t of i.protocols)if(t.getName()==="rest")return t.config.apiUrl;throw new Error("REST protocol not found")}function se(){return j("webrtc")}class ne{constructor(){a(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)}}exports.PersonaConsoleLogger=ne;exports.PersonaProtocolBase=P;exports.PersonaRESTProtocol=E;exports.PersonaRuntimeProvider=Z;exports.PersonaTransactionProtocol=W;exports.PersonaWebRTCProtocol=$;exports.PersonaWebSocketProtocol=v;exports.usePersonaRuntime=ee;exports.usePersonaRuntimeEndpoint=te;exports.usePersonaRuntimeProtocol=j;exports.usePersonaRuntimeWebRTCProtocol=se;
10
10
  //# sourceMappingURL=bundle.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.cjs.js","sources":["../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/jsx-runtime.js","../src/messages.ts","../src/protocol/base.ts","../src/protocol/rest.ts","../src/protocol/websocket.ts","../src/protocol/webrtc.ts","../src/protocol/transaction.ts","../src/runtime.tsx","../src/logging.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import { PersonaMessage } from './types';\nimport { FileContentPart, ThreadMessageLike } from '@assistant-ui/react';\n\nfunction removeEmptyMessages(messages: PersonaMessage[]): PersonaMessage[] {\n return messages.filter((message) => {\n if (message.finishReason === 'stop') {\n return message.text !== null && message.text?.trim() !== '';\n }\n return true;\n });\n}\nfunction parseMessages(messages: PersonaMessage[]): PersonaMessage[] {\n const outputMessages: PersonaMessage[] = [];\n let currentMessage: PersonaMessage | null = null;\n\n for (const message of messages) {\n if (message.type === 'transaction') {\n continue;\n }\n if (message.type === 'reasoning') {\n if (currentMessage != null) {\n outputMessages.push(currentMessage);\n currentMessage = null;\n }\n outputMessages.push(message);\n } else if (message.functionCalls) {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n outputMessages.push(message);\n currentMessage = null;\n } else if (message.functionResponse) {\n outputMessages[outputMessages.length - 1] = {\n ...outputMessages[outputMessages.length - 1],\n functionResponse: message.functionResponse,\n };\n } else if (\n currentMessage &&\n message.protocol === currentMessage.protocol &&\n (currentMessage.role === message.role || message.finishReason === 'stop')\n ) {\n currentMessage.text += message.text;\n currentMessage.files = [...(currentMessage.files ?? []), ...(message.files ?? [])];\n } else {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n currentMessage = {\n ...message,\n };\n }\n }\n\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n const cleanMessages = removeEmptyMessages(outputMessages);\n return cleanMessages;\n}\n\nfunction convertMessage(message: PersonaMessage): ThreadMessageLike {\n const files =\n message.files?.map(\n (file) =>\n ({\n type: 'file',\n data: file.url,\n mimeType: file.contentType,\n } as FileContentPart),\n ) ?? [];\n if (message.role === 'function') {\n return {\n id: message.id!,\n role: 'assistant',\n status: message?.functionResponse === null ? { type: 'running' } : { type: 'complete', reason: 'stop' },\n content:\n message.functionCalls?.map((call) => ({\n type: 'tool-call',\n toolName: call.name,\n toolCallId: call.id,\n args: call.args,\n result: message.functionResponse?.result,\n })) ?? [],\n };\n }\n return {\n id: message.id!,\n role: message.role,\n content:\n message.type === 'reasoning'\n ? [{ type: 'reasoning', text: message.text }, ...files]\n : [{ type: 'text', text: message.text }, ...files],\n };\n}\n\nexport { parseMessages, convertMessage, removeEmptyMessages };\n","import {\n MessageListenerCallback,\n PersonaMessage,\n PersonaPayload,\n PersonaProtocol,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n StatusChangeCallback,\n} from '../types';\n\nabstract class PersonaProtocolBase implements PersonaProtocol {\n abstract status: ProtocolStatus;\n abstract session: Session;\n abstract autostart: boolean;\n\n private statusChangeCallbacks: StatusChangeCallback[] = [];\n private messageCallbacks: MessageListenerCallback[] = [];\n\n public addStatusChangeListener(callback: StatusChangeCallback) {\n this.statusChangeCallbacks.push(callback);\n }\n\n public addMessageListener(callback: MessageListenerCallback) {\n this.messageCallbacks.push(callback);\n }\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async notifyMessage(message: PersonaPayload): Promise<void> {\n this.messageCallbacks.forEach((callback) => callback(message));\n }\n public async notifyMessages(messages: PersonaPayload[]): Promise<void> {\n messages.forEach((message) => {\n this.messageCallbacks.forEach((callback) => callback(message));\n });\n }\n\n public async setSession(session: Session): Promise<void> {\n this.session = session;\n }\n public async setStatus(status: ProtocolStatus): Promise<void> {\n const notify = this.status !== status;\n this.status = status;\n if (!notify) {\n return;\n }\n this.statusChangeCallbacks.forEach((callback) => callback(status));\n }\n\n public clearListeners(): void {\n this.statusChangeCallbacks = [];\n this.messageCallbacks = [];\n }\n\n abstract getName(): string;\n abstract getPriority(): number;\n abstract connect(session?: Session): Promise<Session>;\n abstract disconnect(): Promise<void>;\n abstract send(message: Array<PersonaMessage> | PersonaMessage): Promise<void>;\n\n public onTransaction(_: PersonaTransaction) {}\n}\n\nexport { PersonaProtocolBase };\n","import { PersonaProtocolBase } from './base';\nimport { PersonaResponse, Session, ProtocolStatus, PersonaProtocolBaseConfig, PersonaMessage } from '../types';\n\ntype PersonaRESTProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n};\n\nclass PersonaRESTProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaRESTProtocolConfig;\n notify: boolean = true;\n\n constructor(config: PersonaRESTProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'rest';\n }\n\n public getPriority(): number {\n return 0;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {\n const { apiUrl, apiKey, agentId } = this.config;\n const sessionId = this.session ?? 'new';\n const input = message;\n\n const response = await fetch(`${apiUrl}/agents/${agentId}/sessions/${sessionId}/messages`, {\n body: JSON.stringify({ userMessage: input }),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-fox-apikey': apiKey,\n 'x-persona-apikey': apiKey,\n },\n });\n const personaResponse = (await response.json()) as PersonaResponse;\n this.notifyMessages(\n personaResponse.response.messages.map((payload) => ({\n type: 'message',\n payload,\n })),\n );\n }\n}\n\nexport { PersonaRESTProtocol };\nexport type { PersonaRESTProtocolConfig };\n","import { PersonaMessage, PersonaPayload, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\nimport { PersonaProtocolBase } from './base';\n\ntype PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {\n webSocketUrl: string;\n};\n\nclass PersonaWebSocketProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaWebSocketProtocolConfig;\n webSocket: WebSocket | null;\n\n constructor(config: PersonaWebSocketProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n this.session = null;\n this.webSocket = null;\n }\n\n public getName(): string {\n return 'websocket';\n }\n\n public getPriority(): number {\n return 1;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.config.logger?.debug('Syncing session with WebSocket protocol:', session);\n this.session = session;\n if (this.webSocket && this.status === 'connected') {\n this.disconnect();\n this.connect(session);\n }\n }\n\n public connect(session?: Session): Promise<Session> {\n if (this.webSocket !== null && this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n\n const sid = session || this.session || 'new';\n\n this.config.logger?.debug('Connecting to WebSocket with sessionId:', sid);\n\n const apiKey = encodeURIComponent(this.config.apiKey);\n const agentId = this.config.agentId;\n const webSocketUrl = `${this.config.webSocketUrl}?sessionCode=${sid}&agentId=${agentId}&apiKey=${apiKey}`;\n this.setStatus('connecting');\n this.webSocket = new WebSocket(webSocketUrl);\n this.webSocket.addEventListener('open', () => {\n this.setStatus('connected');\n });\n this.webSocket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data) as PersonaPayload;\n this.notifyMessage(data);\n });\n this.webSocket.addEventListener('close', () => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.warn('WebSocket connection closed');\n });\n\n this.webSocket.addEventListener('error', (error) => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.error('WebSocket error', error);\n\n // TODO: Implement reconnection logic\n });\n\n return Promise.resolve(sid);\n }\n\n public disconnect(): Promise<void> {\n this.config.logger?.debug('Disconnecting WebSocket');\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.close();\n this.setStatus('disconnected');\n this.webSocket = null;\n }\n return Promise.resolve();\n }\n\n public send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.send(JSON.stringify({ type: 'request', payload: message }));\n return Promise.resolve();\n } else {\n return Promise.reject(new Error('WebSocket is not connected'));\n }\n }\n}\n\nexport { PersonaWebSocketProtocol };\nexport type { PersonaWebSocketProtocolConfig };\n","import { PersonaProtocolBase } from './base';\nimport { PersonaMessage, PersonaPayload, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\n\ntype AudioAnalysisData = {\n localAmplitude: number;\n remoteAmplitude: number;\n};\n\ntype AudioVisualizerCallback = (data: AudioAnalysisData) => void;\n\ntype PersonaWebRTCMessageCallback = (data: MessageEvent) => void;\n\ntype PersonaWebRTCConfig = PersonaProtocolBaseConfig & {\n webrtcUrl: string;\n iceServers?: RTCIceServer[];\n};\n\nclass PersonaWebRTCClient {\n private config: PersonaWebRTCConfig;\n private pc: RTCPeerConnection | null = null;\n private ws: WebSocket | null = null;\n private localStream: MediaStream | null = null;\n private remoteStream: MediaStream = new MediaStream();\n private audioCtx: AudioContext | null = null;\n\n private localAnalyser: AnalyserNode | null = null;\n private remoteAnalyser: AnalyserNode | null = null;\n private analyzerFrame: number | null = null;\n private dataChannel: RTCDataChannel | null = null;\n\n private isConnected: boolean = false;\n private visualizerCallbacks: AudioVisualizerCallback[] = [];\n private messageCallbacks: PersonaWebRTCMessageCallback[] = [];\n\n constructor(config: PersonaWebRTCConfig) {\n this.config = config;\n }\n\n public async connect(session: Session): Promise<Session> {\n if (this.isConnected) return;\n\n this.isConnected = true;\n\n try {\n this.localStream = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch (err) {\n this.config.logger?.error('Error accessing microphone:', err);\n return;\n }\n\n this.pc = new RTCPeerConnection({\n iceServers: this.config.iceServers || [\n {\n urls: 'stun:34.38.108.251:3478',\n },\n {\n urls: 'turn:34.38.108.251:3478',\n username: 'webrtc',\n credential: 'webrtc',\n },\n ],\n });\n\n this.localStream.getTracks().forEach((track) => {\n this.pc!.addTrack(track, this.localStream!);\n });\n\n this.pc.ontrack = (event) => {\n event.streams[0].getTracks().forEach((track) => {\n this.remoteStream.addTrack(track);\n });\n\n if (!this.audioCtx) {\n this._startAnalyzers();\n }\n\n const remoteAudio = new Audio();\n remoteAudio.srcObject = this.remoteStream;\n remoteAudio.play().catch((e) => {\n this.config.logger?.error('Error playing remote audio:', e);\n });\n };\n\n this.pc.onicecandidate = (event) => {\n if (event.candidate && this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(\n JSON.stringify({\n type: 'CANDIDATE',\n src: 'client',\n payload: { candidate: event.candidate },\n }),\n );\n }\n };\n\n this.pc.ondatachannel = (event) => {\n const channel = event.channel;\n channel.onmessage = (msg) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n };\n\n const url = this.config.webrtcUrl || 'wss://persona.applica.guru/api/webrtc';\n this.ws = new WebSocket(`${url}?apiKey=${encodeURIComponent(this.config.apiKey)}`);\n this.ws.onopen = async () => {\n const offer = await this.pc!.createOffer();\n await this.pc!.setLocalDescription(offer);\n\n const metadata = {\n apiKey: this.config.apiKey,\n agentId: this.config.agentId,\n sessionCode: session as string,\n };\n this.config.logger?.debug('Opening connection to WebRTC server: ', metadata);\n\n const offerMessage = {\n type: 'OFFER',\n src: crypto.randomUUID?.() || 'client_' + Date.now(),\n payload: {\n sdp: {\n sdp: offer.sdp,\n type: offer.type,\n },\n connectionId: (Date.now() % 1000000).toString(),\n metadata,\n },\n };\n\n this.ws!.send(JSON.stringify(offerMessage));\n };\n\n this.ws.onmessage = async (event) => {\n const data = JSON.parse(event.data);\n if (data.type === 'ANSWER') {\n await this.pc!.setRemoteDescription(new RTCSessionDescription(data.payload.sdp));\n } else if (data.type === 'CANDIDATE') {\n try {\n await this.pc!.addIceCandidate(new RTCIceCandidate(data.payload.candidate));\n } catch (err) {\n this.config.logger?.error('Error adding ICE candidate:', err);\n }\n }\n };\n\n this.ws.onclose = () => {\n this._stopAnalyzers();\n };\n }\n\n public async disconnect(): Promise<void> {\n if (!this.isConnected) return;\n\n this.isConnected = false;\n\n if (this.ws?.readyState === WebSocket.OPEN) this.ws.close();\n if (this.pc) this.pc.close();\n if (this.localStream) {\n this.localStream.getTracks().forEach((track) => track.stop());\n }\n\n this.remoteStream = new MediaStream();\n if (this.audioCtx) {\n await this.audioCtx.close();\n this.audioCtx = null;\n }\n\n this._stopAnalyzers();\n }\n\n public addVisualizerCallback(callback: AudioVisualizerCallback): void {\n this.visualizerCallbacks.push(callback);\n }\n public addMessageCallback(callback: PersonaWebRTCMessageCallback): void {\n this.messageCallbacks.push(callback);\n }\n\n public createDataChannel(label = 'messages'): void {\n if (!this.pc) return;\n this.dataChannel = this.pc.createDataChannel(label);\n this.dataChannel.onopen = () => this.config.logger?.info('Data channel opened');\n this.dataChannel.onmessage = (msg: MessageEvent) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n }\n\n public sendMessage(message: Array<PersonaMessage> | PersonaMessage): void {\n if (!this.dataChannel) {\n this.config.logger?.warn('Data channel is not open, cannot send message');\n return;\n }\n\n this.dataChannel.send(JSON.stringify({ type: 'request', payload: message }));\n this.config.logger?.info('Sent message:', message);\n }\n\n private _startAnalyzers(): void {\n if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();\n\n const localSource = this.audioCtx.createMediaStreamSource(this.localStream);\n const remoteSource = this.audioCtx.createMediaStreamSource(this.remoteStream);\n\n this.localAnalyser = this.audioCtx.createAnalyser();\n this.remoteAnalyser = this.audioCtx.createAnalyser();\n this.localAnalyser.fftSize = 256;\n this.remoteAnalyser.fftSize = 256;\n\n localSource.connect(this.localAnalyser);\n remoteSource.connect(this.remoteAnalyser);\n\n const loop = () => {\n if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n const localArray = new Uint8Array(this.localAnalyser.frequencyBinCount);\n const remoteArray = new Uint8Array(this.remoteAnalyser.frequencyBinCount);\n\n this.localAnalyser.getByteFrequencyData(localArray);\n this.remoteAnalyser.getByteFrequencyData(remoteArray);\n\n const localAmp = localArray.reduce((a, b) => a + b, 0) / localArray.length;\n const remoteAmp = remoteArray.reduce((a, b) => a + b, 0) / remoteArray.length;\n\n if (this.visualizerCallbacks.length > 0) {\n this.visualizerCallbacks.forEach((callback) => {\n callback({\n localAmplitude: localAmp,\n remoteAmplitude: remoteAmp,\n });\n });\n }\n\n this.analyzerFrame = requestAnimationFrame(loop);\n };\n\n this.analyzerFrame = requestAnimationFrame(loop);\n }\n\n private _stopAnalyzers(): void {\n if (this.analyzerFrame) {\n cancelAnimationFrame(this.analyzerFrame);\n this.analyzerFrame = null;\n }\n this.localAnalyser = null;\n this.remoteAnalyser = null;\n }\n}\n\ntype PersonaWebRTCProtocolConfig = PersonaWebRTCConfig & {\n autostart?: boolean;\n};\n\nclass PersonaWebRTCProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n session: Session;\n autostart: boolean;\n config: PersonaWebRTCProtocolConfig;\n webRTCClient: PersonaWebRTCClient;\n\n constructor(config: PersonaWebRTCProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.session = null;\n this.autostart = config?.autostart ?? false;\n this.webRTCClient = new PersonaWebRTCClient(config);\n this.webRTCClient.addMessageCallback((msg: MessageEvent) => {\n const data = JSON.parse(msg.data) as PersonaPayload;\n this.notifyMessage(data);\n });\n }\n\n public getName(): string {\n return 'webrtc';\n }\n public getPriority(): number {\n return 10;\n }\n\n public async syncSession(session: Session): Promise<void> {\n super.syncSession(session);\n if (this.status === 'connected') {\n await this.disconnect();\n await this.connect(session);\n }\n }\n\n public async connect(session?: Session): Promise<Session> {\n if (this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n this.session = session || this.session || 'new';\n this.setStatus('connecting');\n\n this.config.logger?.debug('Connecting to WebRTC with sessionId:', this.session);\n await this.webRTCClient.connect(this.session);\n this.setStatus('connected');\n\n await this.webRTCClient.createDataChannel();\n\n return this.session;\n }\n\n public async disconnect(): Promise<void> {\n if (this.status === 'disconnected') {\n this.config.logger?.warn('Already disconnected');\n return Promise.resolve();\n }\n\n await this.webRTCClient.disconnect();\n\n this.setStatus('disconnected');\n this.config?.logger?.debug('Disconnected from WebRTC');\n }\n\n public send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {\n if (this.status !== 'connected') {\n return Promise.reject(new Error('Not connected'));\n }\n\n this.webRTCClient.sendMessage(message);\n return Promise.resolve();\n }\n}\n\nexport { PersonaWebRTCProtocol };\nexport type { PersonaWebRTCProtocolConfig, AudioVisualizerCallback, AudioAnalysisData };\n","import { PersonaProtocolBase } from './base';\nimport {\n Session,\n ProtocolStatus,\n PersonaProtocolBaseConfig,\n PersonaTransaction,\n FunctionCall,\n ReadonlyJSONObject,\n PersonaMessage,\n} from '../types';\n\ntype FinishTransactionRequest = {\n success: boolean;\n output: any;\n error: string | null;\n};\n\nclass PersonaTransactionsManager {\n private config: PersonaTransactionProtocolConfig;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n this.config = config;\n }\n\n async complete(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: true });\n this.config.logger?.debug('Transaction completed:', transaction);\n }\n\n async fail(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: false });\n this.config.logger?.debug('Transaction failed:', { ...transaction, ...request });\n }\n\n async persist(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await fetch(`${this.config.apiUrl}/transactions/${transaction.id}`, {\n body: JSON.stringify(request),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-persona-apikey': this.config.apiKey,\n },\n });\n }\n}\n\nexport type PersonaToolCallback = (args: ReadonlyJSONObject | undefined) => void;\nexport type PersonaTools = {\n [key: string]: PersonaToolCallback;\n};\n\nclass PersonaPersistableTransaction {\n private transaction: PersonaTransaction;\n private manager: PersonaTransactionsManager;\n\n constructor(transaction: PersonaTransaction, manager: PersonaTransactionsManager) {\n this.transaction = transaction;\n this.manager = manager;\n }\n\n public getFunctionCall(): FunctionCall | null {\n return this.transaction.functionCall;\n }\n\n async invoke(tools: PersonaTools): Promise<void> {\n const functionCall = this.transaction.functionCall;\n if (!functionCall) {\n await this.fail('No function call found');\n return;\n }\n const functionName = functionCall.name;\n const functionArgs = functionCall.args;\n const tool = tools[functionName];\n if (!tool) {\n await this.fail(`Tool ${functionName} not found`);\n return;\n }\n try {\n const result = await tool(functionArgs);\n await this.complete(result);\n } catch (error) {\n await this.fail(`Error executing tool ${functionName}: ${error}`);\n }\n }\n async complete(output: any): Promise<void> {\n await this.manager.complete(this.transaction, { success: true, output, error: null });\n }\n async fail(error: string): Promise<void> {\n await this.manager.fail(this.transaction, { success: false, output: null, error });\n }\n}\n\ntype PersonaTransactionCallback = (transaction: PersonaPersistableTransaction) => void;\n\ntype PersonaTransactionProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n onTransaction: PersonaTransactionCallback;\n};\n\nclass PersonaTransactionProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaTransactionProtocolConfig;\n notify: boolean = true;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'transaction';\n }\n\n public getPriority(): number {\n return 1000;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {\n this.config.logger?.debug('Sending message:', message);\n throw new Error('Not implemented');\n }\n\n public onTransaction(transaction: PersonaTransaction): void {\n if (!this.config.onTransaction) {\n this.config.logger?.error('Transaction protocol config is not set');\n return;\n }\n const manager = new PersonaTransactionsManager(this.config);\n const persistable = new PersonaPersistableTransaction(transaction, manager);\n this.config.onTransaction(persistable);\n }\n}\n\nexport { PersonaTransactionProtocol };\nexport type { PersonaTransactionProtocolConfig, FinishTransactionRequest, PersonaPersistableTransaction, PersonaTransactionCallback };\n","import { useState, useEffect, useCallback, PropsWithChildren, createContext, useContext, useMemo, useRef } from 'react';\nimport {\n useExternalStoreRuntime,\n AppendMessage,\n AssistantRuntimeProvider,\n CompositeAttachmentAdapter,\n SimpleImageAttachmentAdapter,\n} from '@assistant-ui/react';\nimport {\n PersonaConfig,\n PersonaMessage,\n PersonaPayload,\n PersonaProtocol,\n PersonaProtocolBaseConfig,\n PersonaResponse,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n} from './types';\nimport { parseMessages, convertMessage } from './messages';\nimport {\n PersonaPersistableTransaction,\n PersonaRESTProtocol,\n PersonaRESTProtocolConfig,\n PersonaTransactionProtocol,\n PersonaWebRTCProtocol,\n PersonaWebRTCProtocolConfig,\n PersonaWebSocketProtocol,\n PersonaWebSocketProtocolConfig,\n} from './protocol';\n\ntype PersonaRuntimeContextType = {\n protocols: PersonaProtocol[];\n protocolsStatus: Map<string, ProtocolStatus>;\n};\n\nconst PersonaRuntimeContext = createContext<PersonaRuntimeContextType | undefined>(undefined);\n\nfunction fileToBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.readAsDataURL(file); // Converte il file in Data URL (base64)\n\n reader.onload = () => {\n //remove data url using ;base64, to split\n const base64 = reader.result as string;\n const base64WithoutPrefix = base64.split(';base64,')[1];\n resolve(base64WithoutPrefix);\n };\n\n reader.onerror = (error) => {\n reject(error);\n };\n });\n}\n\nfunction PersonaRuntimeProviderInner({\n dev = false,\n protocols: _protocols,\n logger,\n children,\n session: defaultSession = 'new',\n ...config\n}: Readonly<PersonaConfig>) {\n const [isRunning, setIsRunning] = useState(false);\n const [messages, setMessages] = useState<PersonaMessage[]>([]);\n const [session, setSession] = useState<Session>(defaultSession);\n const [protocolsStatus, setProtocolsStatus] = useState<Map<string, ProtocolStatus>>(new Map());\n const didMount = useRef(false);\n\n const protocols = useMemo<PersonaProtocol[]>(() => {\n if (Array.isArray(_protocols)) {\n return _protocols;\n }\n\n if (typeof _protocols === 'object' && _protocols !== null) {\n const baseEndpoint = dev ? 'localhost:8000' : 'persona.applica.guru/api';\n const baseEndpointProtocol = dev ? 'http' : 'https';\n const baseWebSocketProtocol = dev ? 'ws' : 'wss';\n let availableProtocols = Object.keys(_protocols)\n .map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (restConfig === true) {\n return new PersonaRESTProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof restConfig === 'object' && restConfig !== null) {\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n } else {\n return null;\n }\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (webrtcConfig === true) {\n return new PersonaWebRTCProtocol({\n webrtcUrl: `${baseWebSocketProtocol}://${baseEndpoint}/webrtc`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof webrtcConfig === 'object' && webrtcConfig !== null) {\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n } else {\n return null;\n }\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (websocketConfig === true) {\n return new PersonaWebSocketProtocol({\n webSocketUrl: `${baseWebSocketProtocol}://${baseEndpoint}/websocket`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof websocketConfig === 'object' && websocketConfig !== null) {\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n } else {\n return null;\n }\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n })\n .filter((protocol) => protocol !== null) as PersonaProtocol[];\n\n if (config.tools) {\n availableProtocols.push(\n new PersonaTransactionProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n onTransaction: async (transaction: PersonaPersistableTransaction) => {\n await transaction.invoke(config.tools!);\n },\n logger,\n }),\n );\n }\n return availableProtocols;\n }\n throw new Error('Invalid protocols configuration');\n }, []);\n\n useEffect(() => {\n if (didMount.current) return;\n\n didMount.current = true;\n logger?.debug(\n 'Initializing protocols: ',\n protocols.map((protocol) => protocol.getName()),\n );\n protocols.forEach((protocol) => {\n protocol.setSession(session);\n protocol.clearListeners();\n protocol.addStatusChangeListener((status: ProtocolStatus) => {\n logger?.debug(`${protocol.getName()} has notified new status: ${status}`);\n protocolsStatus.set(protocol.getName(), status);\n setProtocolsStatus(new Map(protocolsStatus));\n });\n protocol.addMessageListener((message: PersonaPayload) => {\n if (message.type === 'message') {\n const personaMessage = message.payload as PersonaMessage;\n setMessages((currentConversation) =>\n parseMessages([...currentConversation, ...[{ ...personaMessage, protocol: protocol.getName() }]]),\n );\n } else if (message.type === 'transaction') {\n protocols.filter((p) => p !== protocol).forEach((p) => p.onTransaction(message.payload as PersonaTransaction));\n }\n });\n if (protocol.autostart && protocol.status === 'disconnected') {\n logger?.debug(`Connecting to protocol: ${protocol.getName()}`);\n protocol.connect(session);\n }\n });\n }, [session, protocols, logger, protocolsStatus]);\n\n const onNew = async (message: AppendMessage) => {\n if (message.content[0]?.type !== 'text') throw new Error('Only text messages are supported');\n\n const input = message.content[0].text;\n setMessages((currentConversation) => [...currentConversation, { role: 'user', type: 'text', text: input }]);\n setIsRunning(true);\n\n const protocol = protocols.sort((a, b) => b.getPriority() - a.getPriority()).find((protocol) => protocol.status === 'connected');\n const content: Array<PersonaMessage> = [];\n if (message.attachments) {\n for (const attachment of message.attachments) {\n if (attachment.contentType.startsWith('image/') && attachment.file) {\n content.push({\n role: 'user',\n image: {\n contentType: attachment.contentType,\n content: await fileToBase64(attachment.file),\n },\n text: '',\n type: 'text',\n });\n }\n }\n }\n\n if (message.content) {\n content.push({\n role: 'user',\n text: message.content[0].text,\n type: 'text',\n });\n }\n logger?.debug('Sending message:', content);\n await protocol?.send(content);\n\n setIsRunning(false);\n };\n\n const onCancel = useCallback(() => {\n setIsRunning(false);\n setMessages([]);\n setSession('new');\n return Promise.resolve();\n }, []);\n\n const onReload = useCallback(() => {\n return Promise.resolve();\n }, []);\n\n const runtime = useExternalStoreRuntime({\n isRunning,\n messages,\n convertMessage,\n onNew,\n onCancel,\n onReload,\n adapters: {\n attachments: new CompositeAttachmentAdapter([new SimpleImageAttachmentAdapter()]),\n },\n });\n\n return (\n <PersonaRuntimeContext.Provider value={{ protocols, protocolsStatus }}>\n <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>\n </PersonaRuntimeContext.Provider>\n );\n}\n\nfunction PersonaRuntimeProvider({ children, ...config }: PropsWithChildren<PersonaConfig>) {\n return <PersonaRuntimeProviderInner {...config}>{children}</PersonaRuntimeProviderInner>;\n}\n\nfunction usePersonaRuntime(): PersonaRuntimeContextType {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntime must be used within a PersonaRuntimeProvider');\n }\n return context;\n}\n\n/**\n * Retrieves a specific protocol instance from the PersonaRuntimeContext.\n *\n * @param protocol - The name of the protocol to use.\n * @returns {PersonaProtocol | null} - The protocol instance or null if not found.\n * @throws {Error} - If the hook is used outside of a PersonaRuntimeProvider.\n */\nfunction usePersonaRuntimeProtocol(protocol: string): PersonaProtocol | null {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider');\n }\n\n const protocolInstance = context.protocols.find((p) => p.getName() === protocol);\n if (!protocolInstance) {\n return null;\n }\n\n const status = context.protocolsStatus.get(protocolInstance.getName());\n\n return {\n ...protocolInstance,\n connect: protocolInstance.connect.bind(protocolInstance),\n disconnect: protocolInstance.disconnect.bind(protocolInstance),\n send: protocolInstance.send.bind(protocolInstance),\n setSession: protocolInstance.setSession.bind(protocolInstance),\n addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),\n addMessageListener: protocolInstance.addMessageListener.bind(protocolInstance),\n getName: protocolInstance.getName.bind(protocolInstance),\n getPriority: protocolInstance.getPriority.bind(protocolInstance),\n status: status || protocolInstance.status,\n };\n}\n\nfunction usePersonaRuntimeEndpoint(): string {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider');\n }\n for (const protocol of context.protocols) {\n if (protocol.getName() === 'rest') {\n return (protocol as PersonaRESTProtocol).config.apiUrl;\n }\n }\n throw new Error('REST protocol not found');\n}\n\nfunction usePersonaRuntimeWebRTCProtocol(): PersonaWebRTCProtocol | null {\n return usePersonaRuntimeProtocol('webrtc') as PersonaWebRTCProtocol;\n}\n\nexport { PersonaRuntimeProvider, usePersonaRuntimeEndpoint, usePersonaRuntime, usePersonaRuntimeProtocol, usePersonaRuntimeWebRTCProtocol };\nexport type { PersonaMessage, PersonaResponse };\n","interface PersonaLogger {\n log: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n}\n\nclass PersonaConsoleLogger implements PersonaLogger {\n prefix = '[Persona]';\n\n log(message: string, ...args: unknown[]) {\n console.log(`${this.prefix} - ${message}`, ...args);\n }\n\n info(message: string, ...args: unknown[]) {\n console.info(`${this.prefix} - ${message}`, ...args);\n }\n\n warn(message: string, ...args: unknown[]) {\n console.warn(`${this.prefix} - ${message}`, ...args);\n }\n\n error(message: string, ...args: unknown[]) {\n console.error(`${this.prefix} - ${message}`, ...args);\n }\n\n debug(message: string, ...args: unknown[]) {\n console.debug(`${this.prefix} - ${message}`, ...args);\n }\n}\n\nexport { PersonaConsoleLogger };\nexport type { PersonaLogger };\n"],"names":["REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","reactJsxRuntime_production","jsxRuntimeModule","require$$0","removeEmptyMessages","messages","message","_a","parseMessages","outputMessages","currentMessage","convertMessage","files","file","_b","call","PersonaProtocolBase","__publicField","callback","session","status","notify","_","PersonaRESTProtocol","apiUrl","apiKey","agentId","sessionId","input","personaResponse","payload","PersonaWebSocketProtocol","sid","webSocketUrl","event","data","error","PersonaWebRTCClient","err","track","remoteAudio","e","channel","msg","url","offer","metadata","offerMessage","label","localSource","remoteSource","loop","localArray","remoteArray","localAmp","a","b","remoteAmp","PersonaWebRTCProtocol","_c","PersonaTransactionsManager","transaction","request","PersonaPersistableTransaction","manager","tools","functionCall","functionName","functionArgs","tool","result","output","PersonaTransactionProtocol","persistable","PersonaRuntimeContext","createContext","fileToBase64","resolve","reject","reader","base64WithoutPrefix","PersonaRuntimeProviderInner","dev","_protocols","logger","children","defaultSession","isRunning","setIsRunning","useState","setMessages","setSession","protocolsStatus","setProtocolsStatus","didMount","useRef","protocols","useMemo","baseEndpoint","baseEndpointProtocol","baseWebSocketProtocol","availableProtocols","restConfig","webrtcConfig","websocketConfig","protocol","useEffect","personaMessage","currentConversation","p","onNew","content","attachment","onCancel","useCallback","onReload","runtime","useExternalStoreRuntime","CompositeAttachmentAdapter","SimpleImageAttachmentAdapter","jsx","AssistantRuntimeProvider","PersonaRuntimeProvider","usePersonaRuntime","context","useContext","usePersonaRuntimeProtocol","protocolInstance","usePersonaRuntimeEndpoint","usePersonaRuntimeWebRTCProtocol","PersonaConsoleLogger","args"],"mappings":";;;;;;;;wCAWA,IAAIA,EAAqB,OAAO,IAAI,4BAA4B,EAC9DC,EAAsB,OAAO,IAAI,gBAAgB,EACnD,SAASC,EAAQC,EAAMC,EAAQC,EAAU,CACvC,IAAIC,EAAM,KAGV,GAFWD,IAAX,SAAwBC,EAAM,GAAKD,GACxBD,EAAO,MAAlB,SAA0BE,EAAM,GAAKF,EAAO,KACxC,QAASA,EAAQ,CACnBC,EAAW,CAAE,EACb,QAASE,KAAYH,EACTG,IAAV,QAAuBF,EAASE,CAAQ,EAAIH,EAAOG,CAAQ,EAC9D,MAAMF,EAAWD,EAClB,OAAAA,EAASC,EAAS,IACX,CACL,SAAUL,EACV,KAAMG,EACN,IAAKG,EACL,IAAgBF,IAAX,OAAoBA,EAAS,KAClC,MAAOC,CACR,EAEa,OAAAG,EAAA,SAAGP,EACRO,EAAA,IAAGN,EACdM,EAAA,KAAeN,IC9BNO,EAAA,QAAUC,EAA+C,kBCAlE,SAASC,EAAoBC,EAA8C,CAClE,OAAAA,EAAS,OAAQC,GAAY,OAC9B,OAAAA,EAAQ,eAAiB,OACpBA,EAAQ,OAAS,QAAQC,EAAAD,EAAQ,OAAR,YAAAC,EAAc,UAAW,GAEpD,EAAA,CACR,CACH,CACA,SAASC,EAAcH,EAA8C,CACnE,MAAMI,EAAmC,CAAC,EAC1C,IAAIC,EAAwC,KAE5C,UAAWJ,KAAWD,EAChBC,EAAQ,OAAS,gBAGjBA,EAAQ,OAAS,aACfI,GAAkB,OACpBD,EAAe,KAAKC,CAAc,EACjBA,EAAA,MAEnBD,EAAe,KAAKH,CAAO,GAClBA,EAAQ,eACbI,GACFD,EAAe,KAAKC,CAAc,EAEp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oB6H,EAAiB,CAChC,QAAA,KAAK,GAAG,KAAK,MAAM,MAAM7H,CAAO,GAAI,GAAG6H,CAAI,CAAA,CAGrD,MAAM7H,KAAoB6H,EAAiB,CACjC,QAAA,MAAM,GAAG,KAAK,MAAM,MAAM7H,CAAO,GAAI,GAAG6H,CAAI,CAAA,CAGtD,MAAM7H,KAAoB6H,EAAiB,CACjC,QAAA,MAAM,GAAG,KAAK,MAAM,MAAM7H,CAAO,GAAI,GAAG6H,CAAI,CAAA,CAExD","x_google_ignoreList":[0,1]}
1
+ {"version":3,"file":"bundle.cjs.js","sources":["../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/jsx-runtime.js","../src/messages.ts","../src/protocol/base.ts","../src/protocol/rest.ts","../src/protocol/websocket.ts","../src/protocol/webrtc.ts","../src/protocol/transaction.ts","../src/runtime.tsx","../src/logging.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import { PersonaMessage } from './types';\nimport { FileContentPart, ThreadMessageLike } from '@assistant-ui/react';\n\nfunction removeEmptyMessages(messages: PersonaMessage[]): PersonaMessage[] {\n return messages.filter((message) => {\n if (message.finishReason === 'stop') {\n return message.text !== null && message.text?.trim() !== '';\n }\n return true;\n });\n}\nfunction parseMessages(messages: PersonaMessage[]): PersonaMessage[] {\n const outputMessages: PersonaMessage[] = [];\n let currentMessage: PersonaMessage | null = null;\n\n for (const message of messages) {\n if (message.type === 'transaction') {\n continue;\n }\n if (message.type === 'reasoning') {\n if (currentMessage != null) {\n outputMessages.push(currentMessage);\n currentMessage = null;\n }\n outputMessages.push(message);\n } else if (message.functionCalls) {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n outputMessages.push(message);\n currentMessage = null;\n } else if (message.functionResponse) {\n outputMessages[outputMessages.length - 1] = {\n ...outputMessages[outputMessages.length - 1],\n functionResponse: message.functionResponse,\n };\n } else if (\n currentMessage &&\n message.protocol === currentMessage.protocol &&\n (currentMessage.role === message.role || message.finishReason === 'stop')\n ) {\n currentMessage.text += message.text;\n currentMessage.files = [...(currentMessage.files ?? []), ...(message.files ?? [])];\n } else {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n currentMessage = {\n ...message,\n };\n }\n }\n\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n const cleanMessages = removeEmptyMessages(outputMessages);\n return cleanMessages;\n}\n\nfunction convertMessage(message: PersonaMessage): ThreadMessageLike {\n const files =\n message.files?.map(\n (file) =>\n ({\n type: 'file',\n data: file.url,\n mimeType: file.contentType,\n } as FileContentPart),\n ) ?? [];\n if (message.role === 'function') {\n return {\n id: message.id!,\n role: 'assistant',\n status: message?.functionResponse === null ? { type: 'running' } : { type: 'complete', reason: 'stop' },\n content:\n message.functionCalls?.map((call) => ({\n type: 'tool-call',\n toolName: call.name,\n toolCallId: call.id,\n args: call.args,\n result: message.functionResponse?.result,\n })) ?? [],\n };\n }\n return {\n id: message.id!,\n role: message.role,\n content:\n message.type === 'reasoning'\n ? [{ type: 'reasoning', text: message.text }, ...files]\n : [{ type: 'text', text: message.text }, ...files],\n };\n}\n\nexport { parseMessages, convertMessage, removeEmptyMessages };\n","import {\n MessageListenerCallback,\n PersonaMessage,\n PersonaPayload,\n PersonaProtocol,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n StatusChangeCallback,\n} from '../types';\n\nabstract class PersonaProtocolBase implements PersonaProtocol {\n abstract status: ProtocolStatus;\n abstract session: Session;\n abstract autostart: boolean;\n\n private statusChangeCallbacks: StatusChangeCallback[] = [];\n private messageCallbacks: MessageListenerCallback[] = [];\n\n public addStatusChangeListener(callback: StatusChangeCallback) {\n this.statusChangeCallbacks.push(callback);\n }\n\n public addMessageListener(callback: MessageListenerCallback) {\n this.messageCallbacks.push(callback);\n }\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async notifyMessage(message: PersonaPayload): Promise<void> {\n this.messageCallbacks.forEach((callback) => callback(message));\n }\n public async notifyMessages(messages: PersonaPayload[]): Promise<void> {\n messages.forEach((message) => {\n this.messageCallbacks.forEach((callback) => callback(message));\n });\n }\n\n public async setSession(session: Session): Promise<void> {\n this.session = session;\n }\n public async setStatus(status: ProtocolStatus): Promise<void> {\n const notify = this.status !== status;\n this.status = status;\n if (!notify) {\n return;\n }\n this.statusChangeCallbacks.forEach((callback) => callback(status));\n }\n\n public clearListeners(): void {\n this.statusChangeCallbacks = [];\n this.messageCallbacks = [];\n }\n\n abstract getName(): string;\n abstract getPriority(): number;\n abstract connect(session?: Session): Promise<Session>;\n abstract disconnect(): Promise<void>;\n abstract send(message: Array<PersonaMessage> | PersonaMessage): Promise<void>;\n\n public onTransaction(_: PersonaTransaction) {}\n}\n\nexport { PersonaProtocolBase };\n","import { PersonaProtocolBase } from './base';\nimport { PersonaResponse, Session, ProtocolStatus, PersonaProtocolBaseConfig, PersonaMessage } from '../types';\n\ntype PersonaRESTProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n};\n\nclass PersonaRESTProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaRESTProtocolConfig;\n notify: boolean = true;\n\n constructor(config: PersonaRESTProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'rest';\n }\n\n public getPriority(): number {\n return 100;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {\n const { apiUrl, apiKey, agentId } = this.config;\n const sessionId = this.session ?? 'new';\n const input = message;\n\n const response = await fetch(`${apiUrl}/agents/${agentId}/sessions/${sessionId}/messages`, {\n body: JSON.stringify({ userMessage: input }),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-fox-apikey': apiKey,\n 'x-persona-apikey': apiKey,\n },\n });\n const personaResponse = (await response.json()) as PersonaResponse;\n this.notifyMessages(\n personaResponse.response.messages.map((payload) => ({\n type: 'message',\n payload,\n })),\n );\n }\n}\n\nexport { PersonaRESTProtocol };\nexport type { PersonaRESTProtocolConfig };\n","import { PersonaMessage, PersonaPayload, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\nimport { PersonaProtocolBase } from './base';\n\ntype PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {\n webSocketUrl: string;\n};\n\nclass PersonaWebSocketProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaWebSocketProtocolConfig;\n webSocket: WebSocket | null;\n\n constructor(config: PersonaWebSocketProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n this.session = null;\n this.webSocket = null;\n }\n\n public getName(): string {\n return 'websocket';\n }\n\n public getPriority(): number {\n return 500;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.config.logger?.debug('Syncing session with WebSocket protocol:', session);\n this.session = session;\n if (this.webSocket && this.status === 'connected') {\n this.disconnect();\n this.connect(session);\n }\n }\n\n public connect(session?: Session): Promise<Session> {\n if (this.webSocket !== null && this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n\n const sid = session || this.session || 'new';\n\n this.config.logger?.debug('Connecting to WebSocket with sessionId:', sid);\n\n const apiKey = encodeURIComponent(this.config.apiKey);\n const agentId = this.config.agentId;\n const webSocketUrl = `${this.config.webSocketUrl}?sessionCode=${sid}&agentId=${agentId}&apiKey=${apiKey}`;\n this.setStatus('connecting');\n this.webSocket = new WebSocket(webSocketUrl);\n this.webSocket.addEventListener('open', () => {\n this.setStatus('connected');\n });\n this.webSocket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data) as PersonaPayload;\n this.notifyMessage(data);\n });\n this.webSocket.addEventListener('close', () => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.warn('WebSocket connection closed');\n });\n\n this.webSocket.addEventListener('error', (error) => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.error('WebSocket error', error);\n\n // TODO: Implement reconnection logic\n });\n\n return Promise.resolve(sid);\n }\n\n public disconnect(): Promise<void> {\n this.config.logger?.debug('Disconnecting WebSocket');\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.close();\n this.setStatus('disconnected');\n this.webSocket = null;\n }\n return Promise.resolve();\n }\n\n public send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.send(JSON.stringify({ type: 'request', payload: message }));\n return Promise.resolve();\n } else {\n return Promise.reject(new Error('WebSocket is not connected'));\n }\n }\n}\n\nexport { PersonaWebSocketProtocol };\nexport type { PersonaWebSocketProtocolConfig };\n","import { PersonaProtocolBase } from './base';\nimport { PersonaMessage, PersonaPayload, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\n\ntype AudioAnalysisData = {\n localAmplitude: number;\n remoteAmplitude: number;\n};\n\ntype AudioVisualizerCallback = (data: AudioAnalysisData) => void;\n\ntype PersonaWebRTCMessageCallback = (data: MessageEvent) => void;\n\ntype PersonaWebRTCConfig = PersonaProtocolBaseConfig & {\n webrtcUrl: string;\n iceServers?: RTCIceServer[];\n};\n\nclass PersonaWebRTCClient {\n private config: PersonaWebRTCConfig;\n private pc: RTCPeerConnection | null = null;\n private ws: WebSocket | null = null;\n private localStream: MediaStream | null = null;\n private remoteStream: MediaStream = new MediaStream();\n private audioCtx: AudioContext | null = null;\n\n private localAnalyser: AnalyserNode | null = null;\n private remoteAnalyser: AnalyserNode | null = null;\n private analyzerFrame: number | null = null;\n private dataChannel: RTCDataChannel | null = null;\n\n private isConnected: boolean = false;\n private visualizerCallbacks: AudioVisualizerCallback[] = [];\n private messageCallbacks: PersonaWebRTCMessageCallback[] = [];\n\n constructor(config: PersonaWebRTCConfig) {\n this.config = config;\n }\n\n public async connect(session: Session): Promise<Session> {\n if (this.isConnected) return;\n\n this.isConnected = true;\n\n try {\n this.localStream = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch (err) {\n this.config.logger?.error('Error accessing microphone:', err);\n return;\n }\n\n this.pc = new RTCPeerConnection({\n iceServers: this.config.iceServers || [\n {\n urls: 'stun:34.38.108.251:3478',\n },\n {\n urls: 'turn:34.38.108.251:3478',\n username: 'webrtc',\n credential: 'webrtc',\n },\n ],\n });\n\n this.localStream.getTracks().forEach((track) => {\n this.pc!.addTrack(track, this.localStream!);\n });\n\n this.pc.ontrack = (event) => {\n event.streams[0].getTracks().forEach((track) => {\n this.remoteStream.addTrack(track);\n });\n\n if (!this.audioCtx) {\n this._startAnalyzers();\n }\n\n const remoteAudio = new Audio();\n remoteAudio.srcObject = this.remoteStream;\n remoteAudio.play().catch((e) => {\n this.config.logger?.error('Error playing remote audio:', e);\n });\n };\n\n this.pc.onicecandidate = (event) => {\n if (event.candidate && this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(\n JSON.stringify({\n type: 'CANDIDATE',\n src: 'client',\n payload: { candidate: event.candidate },\n }),\n );\n }\n };\n\n this.pc.ondatachannel = (event) => {\n const channel = event.channel;\n channel.onmessage = (msg) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n };\n\n const url = this.config.webrtcUrl || 'wss://persona.applica.guru/api/webrtc';\n this.ws = new WebSocket(`${url}?apiKey=${encodeURIComponent(this.config.apiKey)}`);\n this.ws.onopen = async () => {\n const offer = await this.pc!.createOffer();\n await this.pc!.setLocalDescription(offer);\n\n const metadata = {\n apiKey: this.config.apiKey,\n agentId: this.config.agentId,\n sessionCode: session as string,\n };\n this.config.logger?.debug('Opening connection to WebRTC server: ', metadata);\n\n const offerMessage = {\n type: 'OFFER',\n src: crypto.randomUUID?.() || 'client_' + Date.now(),\n payload: {\n sdp: {\n sdp: offer.sdp,\n type: offer.type,\n },\n connectionId: (Date.now() % 1000000).toString(),\n metadata,\n },\n };\n\n this.ws!.send(JSON.stringify(offerMessage));\n };\n\n this.ws.onmessage = async (event) => {\n const data = JSON.parse(event.data);\n if (data.type === 'ANSWER') {\n await this.pc!.setRemoteDescription(new RTCSessionDescription(data.payload.sdp));\n } else if (data.type === 'CANDIDATE') {\n try {\n await this.pc!.addIceCandidate(new RTCIceCandidate(data.payload.candidate));\n } catch (err) {\n this.config.logger?.error('Error adding ICE candidate:', err);\n }\n }\n };\n\n this.ws.onclose = () => {\n this._stopAnalyzers();\n };\n }\n\n public async disconnect(): Promise<void> {\n if (!this.isConnected) return;\n\n this.isConnected = false;\n\n if (this.ws?.readyState === WebSocket.OPEN) this.ws.close();\n if (this.pc) this.pc.close();\n if (this.localStream) {\n this.localStream.getTracks().forEach((track) => track.stop());\n }\n\n this.remoteStream = new MediaStream();\n if (this.audioCtx) {\n await this.audioCtx.close();\n this.audioCtx = null;\n }\n\n this._stopAnalyzers();\n }\n\n public addVisualizerCallback(callback: AudioVisualizerCallback): void {\n this.visualizerCallbacks.push(callback);\n }\n public addMessageCallback(callback: PersonaWebRTCMessageCallback): void {\n this.messageCallbacks.push(callback);\n }\n\n public createDataChannel(label = 'messages'): void {\n if (!this.pc) return;\n this.dataChannel = this.pc.createDataChannel(label);\n this.dataChannel.onopen = () => this.config.logger?.info('Data channel opened');\n this.dataChannel.onmessage = (msg: MessageEvent) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n }\n\n public sendMessage(message: Array<PersonaMessage> | PersonaMessage): void {\n if (!this.dataChannel) {\n this.config.logger?.warn('Data channel is not open, cannot send message');\n return;\n }\n\n this.dataChannel.send(JSON.stringify({ type: 'request', payload: message }));\n this.config.logger?.info('Sent message:', message);\n }\n\n private _startAnalyzers(): void {\n if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();\n\n const localSource = this.audioCtx.createMediaStreamSource(this.localStream);\n const remoteSource = this.audioCtx.createMediaStreamSource(this.remoteStream);\n\n this.localAnalyser = this.audioCtx.createAnalyser();\n this.remoteAnalyser = this.audioCtx.createAnalyser();\n this.localAnalyser.fftSize = 256;\n this.remoteAnalyser.fftSize = 256;\n\n localSource.connect(this.localAnalyser);\n remoteSource.connect(this.remoteAnalyser);\n\n const loop = () => {\n if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n const localArray = new Uint8Array(this.localAnalyser.frequencyBinCount);\n const remoteArray = new Uint8Array(this.remoteAnalyser.frequencyBinCount);\n\n this.localAnalyser.getByteFrequencyData(localArray);\n this.remoteAnalyser.getByteFrequencyData(remoteArray);\n\n const localAmp = localArray.reduce((a, b) => a + b, 0) / localArray.length;\n const remoteAmp = remoteArray.reduce((a, b) => a + b, 0) / remoteArray.length;\n\n if (this.visualizerCallbacks.length > 0) {\n this.visualizerCallbacks.forEach((callback) => {\n callback({\n localAmplitude: localAmp,\n remoteAmplitude: remoteAmp,\n });\n });\n }\n\n this.analyzerFrame = requestAnimationFrame(loop);\n };\n\n this.analyzerFrame = requestAnimationFrame(loop);\n }\n\n private _stopAnalyzers(): void {\n if (this.analyzerFrame) {\n cancelAnimationFrame(this.analyzerFrame);\n this.analyzerFrame = null;\n }\n this.localAnalyser = null;\n this.remoteAnalyser = null;\n }\n}\n\ntype PersonaWebRTCProtocolConfig = PersonaWebRTCConfig & {\n autostart?: boolean;\n};\n\nclass PersonaWebRTCProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n session: Session;\n autostart: boolean;\n config: PersonaWebRTCProtocolConfig;\n webRTCClient: PersonaWebRTCClient;\n\n constructor(config: PersonaWebRTCProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.session = null;\n this.autostart = config?.autostart ?? false;\n this.webRTCClient = new PersonaWebRTCClient(config);\n this.webRTCClient.addMessageCallback((msg: MessageEvent) => {\n const data = JSON.parse(msg.data) as PersonaPayload;\n this.notifyMessage(data);\n });\n }\n\n public getName(): string {\n return 'webrtc';\n }\n public getPriority(): number {\n return 1000;\n }\n\n public async syncSession(session: Session): Promise<void> {\n super.syncSession(session);\n if (this.status === 'connected') {\n await this.disconnect();\n await this.connect(session);\n }\n }\n\n public async connect(session?: Session): Promise<Session> {\n if (this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n this.session = session || this.session || 'new';\n this.setStatus('connecting');\n\n this.config.logger?.debug('Connecting to WebRTC with sessionId:', this.session);\n await this.webRTCClient.connect(this.session);\n this.setStatus('connected');\n\n await this.webRTCClient.createDataChannel();\n\n return this.session;\n }\n\n public async disconnect(): Promise<void> {\n if (this.status === 'disconnected') {\n this.config.logger?.warn('Already disconnected');\n return Promise.resolve();\n }\n\n await this.webRTCClient.disconnect();\n\n this.setStatus('disconnected');\n this.config?.logger?.debug('Disconnected from WebRTC');\n }\n\n public send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {\n if (this.status !== 'connected') {\n return Promise.reject(new Error('Not connected'));\n }\n\n this.webRTCClient.sendMessage(message);\n return Promise.resolve();\n }\n}\n\nexport { PersonaWebRTCProtocol };\nexport type { PersonaWebRTCProtocolConfig, AudioVisualizerCallback, AudioAnalysisData };\n","import { PersonaProtocolBase } from './base';\nimport {\n Session,\n ProtocolStatus,\n PersonaProtocolBaseConfig,\n PersonaTransaction,\n FunctionCall,\n ReadonlyJSONObject,\n PersonaMessage,\n} from '../types';\n\ntype FinishTransactionRequest = {\n success: boolean;\n output: any;\n error: string | null;\n};\n\nclass PersonaTransactionsManager {\n private config: PersonaTransactionProtocolConfig;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n this.config = config;\n }\n\n async complete(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: true });\n this.config.logger?.debug('Transaction completed:', transaction);\n }\n\n async fail(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: false });\n this.config.logger?.debug('Transaction failed:', { ...transaction, ...request });\n }\n\n async persist(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await fetch(`${this.config.apiUrl}/transactions/${transaction.id}`, {\n body: JSON.stringify(request),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-persona-apikey': this.config.apiKey,\n },\n });\n }\n}\n\nexport type PersonaToolCallback = (args: ReadonlyJSONObject | undefined) => void;\nexport type PersonaTools = {\n [key: string]: PersonaToolCallback;\n};\n\nclass PersonaPersistableTransaction {\n private transaction: PersonaTransaction;\n private manager: PersonaTransactionsManager;\n\n constructor(transaction: PersonaTransaction, manager: PersonaTransactionsManager) {\n this.transaction = transaction;\n this.manager = manager;\n }\n\n public getFunctionCall(): FunctionCall | null {\n return this.transaction.functionCall;\n }\n\n async invoke(tools: PersonaTools): Promise<void> {\n const functionCall = this.transaction.functionCall;\n if (!functionCall) {\n await this.fail('No function call found');\n return;\n }\n const functionName = functionCall.name;\n const functionArgs = functionCall.args;\n const tool = tools[functionName];\n if (!tool) {\n await this.fail(`Tool ${functionName} not found`);\n return;\n }\n try {\n const result = await tool(functionArgs);\n await this.complete(result);\n } catch (error) {\n await this.fail(`Error executing tool ${functionName}: ${error}`);\n }\n }\n async complete(output: any): Promise<void> {\n await this.manager.complete(this.transaction, { success: true, output, error: null });\n }\n async fail(error: string): Promise<void> {\n await this.manager.fail(this.transaction, { success: false, output: null, error });\n }\n}\n\ntype PersonaTransactionCallback = (transaction: PersonaPersistableTransaction) => void;\n\ntype PersonaTransactionProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n onTransaction: PersonaTransactionCallback;\n};\n\nclass PersonaTransactionProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaTransactionProtocolConfig;\n notify: boolean = true;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'transaction';\n }\n\n public getPriority(): number {\n return 0;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {\n this.config.logger?.debug('Sending message:', message);\n throw new Error('Not implemented');\n }\n\n public onTransaction(transaction: PersonaTransaction): void {\n if (!this.config.onTransaction) {\n this.config.logger?.error('Transaction protocol config is not set');\n return;\n }\n const manager = new PersonaTransactionsManager(this.config);\n const persistable = new PersonaPersistableTransaction(transaction, manager);\n this.config.onTransaction(persistable);\n }\n}\n\nexport { PersonaTransactionProtocol };\nexport type { PersonaTransactionProtocolConfig, FinishTransactionRequest, PersonaPersistableTransaction, PersonaTransactionCallback };\n","import { useState, useEffect, useCallback, PropsWithChildren, createContext, useContext, useMemo, useRef } from 'react';\nimport {\n useExternalStoreRuntime,\n AppendMessage,\n AssistantRuntimeProvider,\n CompositeAttachmentAdapter,\n SimpleImageAttachmentAdapter,\n} from '@assistant-ui/react';\nimport {\n PersonaConfig,\n PersonaMessage,\n PersonaPayload,\n PersonaProtocol,\n PersonaProtocolBaseConfig,\n PersonaResponse,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n} from './types';\nimport { parseMessages, convertMessage } from './messages';\nimport {\n PersonaPersistableTransaction,\n PersonaRESTProtocol,\n PersonaRESTProtocolConfig,\n PersonaTransactionProtocol,\n PersonaWebRTCProtocol,\n PersonaWebRTCProtocolConfig,\n PersonaWebSocketProtocol,\n PersonaWebSocketProtocolConfig,\n} from './protocol';\n\ntype PersonaRuntimeContextType = {\n protocols: PersonaProtocol[];\n protocolsStatus: Map<string, ProtocolStatus>;\n};\n\nconst PersonaRuntimeContext = createContext<PersonaRuntimeContextType | undefined>(undefined);\n\nfunction fileToBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.readAsDataURL(file); // Converte il file in Data URL (base64)\n\n reader.onload = () => {\n //remove data url using ;base64, to split\n const base64 = reader.result as string;\n const base64WithoutPrefix = base64.split(';base64,')[1];\n resolve(base64WithoutPrefix);\n };\n\n reader.onerror = (error) => {\n reject(error);\n };\n });\n}\n\nfunction PersonaRuntimeProviderInner({\n dev = false,\n protocols: _protocols,\n logger,\n children,\n session: defaultSession = 'new',\n ...config\n}: Readonly<PersonaConfig>) {\n const [isRunning, setIsRunning] = useState(false);\n const [messages, setMessages] = useState<PersonaMessage[]>([]);\n const [session, setSession] = useState<Session>(defaultSession);\n const [protocolsStatus, setProtocolsStatus] = useState<Map<string, ProtocolStatus>>(new Map());\n const didMount = useRef(false);\n\n const protocols = useMemo<PersonaProtocol[]>(() => {\n if (Array.isArray(_protocols)) {\n return _protocols;\n }\n\n if (typeof _protocols === 'object' && _protocols !== null) {\n const baseEndpoint = dev ? 'localhost:8000' : 'persona.applica.guru/api';\n const baseEndpointProtocol = dev ? 'http' : 'https';\n const baseWebSocketProtocol = dev ? 'ws' : 'wss';\n let availableProtocols = Object.keys(_protocols)\n .map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (restConfig === true) {\n return new PersonaRESTProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof restConfig === 'object' && restConfig !== null) {\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n } else {\n return null;\n }\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (webrtcConfig === true) {\n return new PersonaWebRTCProtocol({\n webrtcUrl: `${baseWebSocketProtocol}://${baseEndpoint}/webrtc`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof webrtcConfig === 'object' && webrtcConfig !== null) {\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n } else {\n return null;\n }\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (websocketConfig === true) {\n return new PersonaWebSocketProtocol({\n webSocketUrl: `${baseWebSocketProtocol}://${baseEndpoint}/websocket`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof websocketConfig === 'object' && websocketConfig !== null) {\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n } else {\n return null;\n }\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n })\n .filter((protocol) => protocol !== null) as PersonaProtocol[];\n\n if (config.tools) {\n availableProtocols.push(\n new PersonaTransactionProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n onTransaction: async (transaction: PersonaPersistableTransaction) => {\n await transaction.invoke(config.tools!);\n },\n logger,\n }),\n );\n }\n return availableProtocols;\n }\n throw new Error('Invalid protocols configuration');\n }, []);\n\n useEffect(() => {\n if (didMount.current) return;\n\n didMount.current = true;\n logger?.debug(\n 'Initializing protocols: ',\n protocols.map((protocol) => protocol.getName()),\n );\n protocols.forEach((protocol) => {\n protocol.setSession(session);\n protocol.clearListeners();\n protocol.addStatusChangeListener((status: ProtocolStatus) => {\n logger?.debug(`${protocol.getName()} has notified new status: ${status}`);\n protocolsStatus.set(protocol.getName(), status);\n setProtocolsStatus(new Map(protocolsStatus));\n });\n protocol.addMessageListener((message: PersonaPayload) => {\n if (message.type === 'message') {\n const personaMessage = message.payload as PersonaMessage;\n setMessages((currentConversation) =>\n parseMessages([...currentConversation, ...[{ ...personaMessage, protocol: protocol.getName() }]]),\n );\n } else if (message.type === 'transaction') {\n protocols.filter((p) => p !== protocol).forEach((p) => p.onTransaction(message.payload as PersonaTransaction));\n }\n });\n if (protocol.autostart && protocol.status === 'disconnected') {\n logger?.debug(`Connecting to protocol: ${protocol.getName()}`);\n protocol.connect(session);\n }\n });\n }, [session, protocols, logger, protocolsStatus]);\n\n const onNew = async (message: AppendMessage) => {\n if (message.content[0]?.type !== 'text') throw new Error('Only text messages are supported');\n\n const input = message.content[0].text;\n setMessages((currentConversation) => [...currentConversation, { role: 'user', type: 'text', text: input }]);\n setIsRunning(true);\n\n const protocol = protocols.sort((a, b) => b.getPriority() - a.getPriority()).find((protocol) => protocol.status === 'connected');\n const content: Array<PersonaMessage> = [];\n if (message.attachments) {\n for (const attachment of message.attachments) {\n if (attachment.contentType.startsWith('image/') && attachment.file) {\n content.push({\n role: 'user',\n image: {\n contentType: attachment.contentType,\n content: await fileToBase64(attachment.file),\n },\n text: '',\n type: 'text',\n });\n }\n }\n }\n\n if (message.content) {\n content.push({\n role: 'user',\n text: message.content[0].text,\n type: 'text',\n });\n }\n logger?.debug('Sending message:', content);\n await protocol?.send(content);\n\n setIsRunning(false);\n };\n\n const onCancel = useCallback(() => {\n setIsRunning(false);\n setMessages([]);\n setSession('new');\n return Promise.resolve();\n }, []);\n\n const onReload = useCallback(() => {\n return Promise.resolve();\n }, []);\n\n const runtime = useExternalStoreRuntime({\n isRunning,\n messages,\n convertMessage,\n onNew,\n onCancel,\n onReload,\n adapters: {\n attachments: new CompositeAttachmentAdapter([new SimpleImageAttachmentAdapter()]),\n },\n });\n\n return (\n <PersonaRuntimeContext.Provider value={{ protocols, protocolsStatus }}>\n <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>\n </PersonaRuntimeContext.Provider>\n );\n}\n\nfunction PersonaRuntimeProvider({ children, ...config }: PropsWithChildren<PersonaConfig>) {\n return <PersonaRuntimeProviderInner {...config}>{children}</PersonaRuntimeProviderInner>;\n}\n\nfunction usePersonaRuntime(): PersonaRuntimeContextType {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntime must be used within a PersonaRuntimeProvider');\n }\n return context;\n}\n\n/**\n * Retrieves a specific protocol instance from the PersonaRuntimeContext.\n *\n * @param protocol - The name of the protocol to use.\n * @returns {PersonaProtocol | null} - The protocol instance or null if not found.\n * @throws {Error} - If the hook is used outside of a PersonaRuntimeProvider.\n */\nfunction usePersonaRuntimeProtocol(protocol: string): PersonaProtocol | null {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider');\n }\n\n const protocolInstance = context.protocols.find((p) => p.getName() === protocol);\n if (!protocolInstance) {\n return null;\n }\n\n const status = context.protocolsStatus.get(protocolInstance.getName());\n\n return {\n ...protocolInstance,\n connect: protocolInstance.connect.bind(protocolInstance),\n disconnect: protocolInstance.disconnect.bind(protocolInstance),\n send: protocolInstance.send.bind(protocolInstance),\n setSession: protocolInstance.setSession.bind(protocolInstance),\n addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),\n addMessageListener: protocolInstance.addMessageListener.bind(protocolInstance),\n getName: protocolInstance.getName.bind(protocolInstance),\n getPriority: protocolInstance.getPriority.bind(protocolInstance),\n status: status || protocolInstance.status,\n };\n}\n\nfunction usePersonaRuntimeEndpoint(): string {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider');\n }\n for (const protocol of context.protocols) {\n if (protocol.getName() === 'rest') {\n return (protocol as PersonaRESTProtocol).config.apiUrl;\n }\n }\n throw new Error('REST protocol not found');\n}\n\nfunction usePersonaRuntimeWebRTCProtocol(): PersonaWebRTCProtocol | null {\n return usePersonaRuntimeProtocol('webrtc') as PersonaWebRTCProtocol;\n}\n\nexport { PersonaRuntimeProvider, usePersonaRuntimeEndpoint, usePersonaRuntime, usePersonaRuntimeProtocol, usePersonaRuntimeWebRTCProtocol };\nexport type { PersonaMessage, PersonaResponse };\n","interface PersonaLogger {\n log: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n}\n\nclass PersonaConsoleLogger implements PersonaLogger {\n prefix = '[Persona]';\n\n log(message: string, ...args: unknown[]) {\n console.log(`${this.prefix} - ${message}`, ...args);\n }\n\n info(message: string, ...args: unknown[]) {\n console.info(`${this.prefix} - ${message}`, ...args);\n }\n\n warn(message: string, ...args: unknown[]) {\n console.warn(`${this.prefix} - ${message}`, ...args);\n }\n\n error(message: string, ...args: unknown[]) {\n console.error(`${this.prefix} - ${message}`, ...args);\n }\n\n debug(message: string, ...args: unknown[]) {\n console.debug(`${this.prefix} - ${message}`, ...args);\n }\n}\n\nexport { PersonaConsoleLogger };\nexport type { PersonaLogger };\n"],"names":["REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","reactJsxRuntime_production","jsxRuntimeModule","require$$0","removeEmptyMessages","messages","message","_a","parseMessages","outputMessages","currentMessage","convertMessage","files","file","_b","call","PersonaProtocolBase","__publicField","callback","session","status","notify","_","PersonaRESTProtocol","apiUrl","apiKey","agentId","sessionId","input","personaResponse","payload","PersonaWebSocketProtocol","sid","webSocketUrl","event","data","error","PersonaWebRTCClient","err","track","remoteAudio","e","channel","msg","url","offer","metadata","offerMessage","label","localSource","remoteSource","loop","localArray","remoteArray","localAmp","a","b","remoteAmp","PersonaWebRTCProtocol","_c","PersonaTransactionsManager","transaction","request","PersonaPersistableTransaction","manager","tools","functionCall","functionName","functionArgs","tool","result","output","PersonaTransactionProtocol","persistable","PersonaRuntimeContext","createContext","fileToBase64","resolve","reject","reader","base64WithoutPrefix","PersonaRuntimeProviderInner","dev","_protocols","logger","children","defaultSession","isRunning","setIsRunning","useState","setMessages","setSession","protocolsStatus","setProtocolsStatus","didMount","useRef","protocols","useMemo","baseEndpoint","baseEndpointProtocol","baseWebSocketProtocol","availableProtocols","restConfig","webrtcConfig","websocketConfig","protocol","useEffect","personaMessage","currentConversation","p","onNew","content","attachment","onCancel","useCallback","onReload","runtime","useExternalStoreRuntime","CompositeAttachmentAdapter","SimpleImageAttachmentAdapter","jsx","AssistantRuntimeProvider","PersonaRuntimeProvider","usePersonaRuntime","context","useContext","usePersonaRuntimeProtocol","protocolInstance","usePersonaRuntimeEndpoint","usePersonaRuntimeWebRTCProtocol","PersonaConsoleLogger","args"],"mappings":";;;;;;;;wCAWA,IAAIA,EAAqB,OAAO,IAAI,4BAA4B,EAC9DC,EAAsB,OAAO,IAAI,gBAAgB,EACnD,SAASC,EAAQC,EAAMC,EAAQC,EAAU,CACvC,IAAIC,EAAM,KAGV,GAFWD,IAAX,SAAwBC,EAAM,GAAKD,GACxBD,EAAO,MAAlB,SAA0BE,EAAM,GAAKF,EAAO,KACxC,QAASA,EAAQ,CACnBC,EAAW,CAAE,EACb,QAASE,KAAYH,EACTG,IAAV,QAAuBF,EAASE,CAAQ,EAAIH,EAAOG,CAAQ,EAC9D,MAAMF,EAAWD,EAClB,OAAAA,E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,EAAiB,YAAY,KAAKA,CAAgB,EAC/D,OAAQ3G,GAAU2G,EAAiB,MACrC,CACF,CAEA,SAASC,IAAoC,CACrC,MAAAJ,EAAUC,aAAWnD,CAAqB,EAChD,GAAI,CAACkD,EACG,MAAA,IAAI,MAAM,wEAAwE,EAE/E,UAAAnB,KAAYmB,EAAQ,UACzB,GAAAnB,EAAS,QAAQ,IAAM,OACzB,OAAQA,EAAiC,OAAO,OAG9C,MAAA,IAAI,MAAM,yBAAyB,CAC3C,CAEA,SAASwB,IAAgE,CACvE,OAAOH,EAA0B,QAAQ,CAC3C,CC9SA,MAAMI,EAA8C,CAApD,cACEjH,EAAA,cAAS,aAET,IAAIX,KAAoB6H,EAAiB,CAC/B,QAAA,IAAI,GAAG,KAAK,MAAM,MAAM7H,CAAO,GAAI,GAAG6H,CAAI,CAAA,CAGpD,KAAK7H,KAAoB6H,EAAiB,CAChC,QAAA,KAAK,GAAG,KAAK,MAAM,MAAM7H,CAAO,GAAI,GAAG6H,CAAI,CAAA,CAGrD,KAAK7H,KAAoB6H,EAAiB,CAChC,QAAA,KAAK,GAAG,KAAK,MAAM,MAAM7H,CAAO,GAAI,GAAG6H,CAAI,CAAA,CAGrD,MAAM7H,KAAoB6H,EAAiB,CACjC,QAAA,MAAM,GAAG,KAAK,MAAM,MAAM7H,CAAO,GAAI,GAAG6H,CAAI,CAAA,CAGtD,MAAM7H,KAAoB6H,EAAiB,CACjC,QAAA,MAAM,GAAG,KAAK,MAAM,MAAM7H,CAAO,GAAI,GAAG6H,CAAI,CAAA,CAExD","x_google_ignoreList":[0,1]}
package/dist/bundle.es.js CHANGED
@@ -133,7 +133,7 @@ class M extends x {
133
133
  return "rest";
134
134
  }
135
135
  getPriority() {
136
- return 0;
136
+ return 100;
137
137
  }
138
138
  async connect(e) {
139
139
  return this.setStatus("connected"), e;
@@ -176,7 +176,7 @@ class N extends x {
176
176
  return "websocket";
177
177
  }
178
178
  getPriority() {
179
- return 1;
179
+ return 500;
180
180
  }
181
181
  async syncSession(e) {
182
182
  var n;
@@ -385,7 +385,7 @@ class I extends x {
385
385
  return "webrtc";
386
386
  }
387
387
  getPriority() {
388
- return 10;
388
+ return 1e3;
389
389
  }
390
390
  async syncSession(e) {
391
391
  super.syncSession(e), this.status === "connected" && (await this.disconnect(), await this.connect(e));
@@ -477,7 +477,7 @@ class ie extends x {
477
477
  return "transaction";
478
478
  }
479
479
  getPriority() {
480
- return 1e3;
480
+ return 0;
481
481
  }
482
482
  async connect(e) {
483
483
  return this.setStatus("connected"), e;