@applica-software-guru/persona-sdk 0.1.52 → 0.1.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var q=Object.defineProperty;var J=(o,t,e)=>t in o?q(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var a=(o,t,e)=>J(o,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("react"),x=require("@assistant-ui/react");var N={exports:{}},S={};/**
1
+ "use strict";var q=Object.defineProperty;var J=(o,t,e)=>t in o?q(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var a=(o,t,e)=>J(o,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("react"),x=require("@assistant-ui/react");var I={exports:{}},C={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.js
4
4
  *
@@ -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 I;function K(){if(I)return S;I=1;var o=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(n,s,i){var r=null;if(i!==void 0&&(r=""+i),s.key!==void 0&&(r=""+s.key),"key"in s){i={};for(var l in s)l!=="key"&&(i[l]=s[l])}else i=s;return s=i.ref,{$$typeof:o,type:n,key:r,ref:s!==void 0?s:null,props:i}}return S.Fragment=t,S.jsx=e,S.jsxs=e,S}N.exports=K();var T=N.exports;function B(o){return o.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function _(o){const t=[];let e=null;for(const s of o)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(o){var e,n;const t=((e=o.files)==null?void 0:e.map(s=>({type:"file",data:s.url,mimeType:s.contentType})))??[];return o.role==="function"?{id:o.id,role:"assistant",status:(o==null?void 0:o.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((n=o.functionCalls)==null?void 0:n.map(s=>{var i;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(i=o.functionResponse)==null?void 0:i.result}}))??[]}:{id:o.id,role:o.role,content:o.type==="reasoning"?[{type:"reasoning",text:o.text},...t]:[{type:"text",text:o.text},...t]}}class C{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 A extends C{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:i}=this.config,r=this.session??"new",l=e,h=await(await fetch(`${n}/agents/${i}/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(h.response.messages.map(b=>({type:"message",payload:b})))}}class E extends C{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),i=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${n}&agentId=${i}&apiKey=${s}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",u=>{const h=JSON.parse(u.data);this.notifyMessage(h)}),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 h;this.setStatus("disconnected"),this.webSocket=null,(h=this.config.logger)==null||h.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 i=new Audio;i.srcObject=this.remoteStream,i.play().catch(r=>{var l;(l=this.config.logger)==null||l.error("Error playing remote audio:",r)})},this.pc.onicecandidate=s=>{var i;s.candidate&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:s.candidate}}))},this.pc.ondatachannel=s=>{const i=s.channel;i.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 i={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(l=this.config.logger)==null||l.debug("Opening connection to WebRTC server: ",i);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:i}};this.ws.send(JSON.stringify(r))},this.ws.onmessage=async s=>{var r;const i=JSON.parse(s.data);if(i.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(i.payload.sdp));else if(i.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(i.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),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(s),this.remoteAnalyser.getByteFrequencyData(i);const r=s.reduce((u,h)=>u+h,0)/s.length,l=i.reduce((u,h)=>u+h,0)/i.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 v extends C{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,i=t[n];if(!i){await this.fail(`Tool ${n} not found`);return}try{const r=await i(s);await this.complete({date:new Date().toISOString(),result: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 C{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 i;if(!this.config.onTransaction){(i=this.config.logger)==null||i.error("Transaction protocol config is not set");return}const n=new V(this.config),s=new H(e,n);this.config.onTransaction(s)}}const R=f.createContext(void 0);function Q(o){return new Promise((t,e)=>{const n=new FileReader;n.readAsDataURL(o),n.onload=()=>{const i=n.result.split(";base64,")[1];t(i)},n.onerror=s=>{e(s)}})}function X({dev:o=!1,protocols:t,logger:e,children:n,session:s="new",...i}){const[r,l]=f.useState(!1),[u,h]=f.useState([]),[b,z]=f.useState(s),[P,O]=f.useState(new Map),$=f.useRef(!1),w=f.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const c=o?"localhost:8000":"persona.applica.guru/api",p=o?"http":"https",g=o?"ws":"wss";let m=Object.keys(t).map(y=>{switch(y){case"rest":const d=t[y];return d===!0?new A({apiUrl:`${p}://${c}`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new A(d);case"webrtc":const k=t[y];return k===!0?new v({webrtcUrl:`${g}://${c}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new v(k);case"websocket":const M=t[y];return M===!0?new E({webSocketUrl:`${g}://${c}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new E(M);default:throw new Error(`Unknown protocol: ${y}`)}});return i.tools&&m.push(new W({apiUrl:`${p}://${c}`,apiKey:i.apiKey,agentId:i.agentId,onTransaction:async y=>{await y.invoke(i.tools)},logger:e})),m}throw new Error("Invalid protocols configuration")},[]);f.useEffect(()=>{$.current||($.current=!0,e==null||e.debug("Initializing protocols: ",w.map(c=>c.getName())),w.forEach(c=>{c.setSession(b),c.clearListeners(),c.addStatusChangeListener(p=>{e==null||e.debug(`${c.getName()} has notified new status: ${p}`),P.set(c.getName(),p),O(new Map(P))}),c.addMessageListener(p=>{if(p.type==="message"){const g=p.payload;h(m=>_([...m,{...g,protocol:c.getName()}]))}else p.type==="transaction"&&w.filter(g=>g!==c).forEach(g=>g.onTransaction(p.payload))}),c.autostart&&c.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${c.getName()}`),c.connect(b))}))},[b,w,e,P]);const L=async c=>{var y;if(((y=c.content[0])==null?void 0:y.type)!=="text")throw new Error("Only text messages are supported");const p=c.content[0].text;h(d=>[...d,{role:"user",type:"text",text:p}]),l(!0);const g=w.sort((d,k)=>k.getPriority()-d.getPriority()).find(d=>d.status==="connected"),m=[];if(c.attachments)for(const d of c.attachments)d.contentType.startsWith("image/")&&d.file&&m.push({role:"user",image:{contentType:d.contentType,content:await Q(d.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(g==null?void 0:g.send(m)),l(!1)},U=f.useCallback(()=>(l(!1),h([]),z("new"),Promise.resolve()),[]),j=f.useCallback(()=>Promise.resolve(),[]),F=x.useExternalStoreRuntime({isRunning:r,messages:u,convertMessage:Y,onNew:L,onCancel:U,onReload:j,adapters:{attachments:new x.CompositeAttachmentAdapter([new x.SimpleImageAttachmentAdapter])}});return T.jsx(R.Provider,{value:{protocols:w,protocolsStatus:P},children:T.jsx(x.AssistantRuntimeProvider,{runtime:F,children:n})})}function Z({children:o,...t}){return T.jsx(X,{...t,children:o})}function ee(){const o=f.useContext(R);if(!o)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return o}function D(o){const t=f.useContext(R);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(s=>s.getName()===o);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 o=f.useContext(R);if(!o)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");for(const t of o.protocols)if(t.getName()==="rest")return t.config.apiUrl;throw new Error("REST protocol not found")}function se(){return D("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=C;exports.PersonaRESTProtocol=A;exports.PersonaRuntimeProvider=Z;exports.PersonaTransactionProtocol=W;exports.PersonaWebRTCProtocol=v;exports.PersonaWebSocketProtocol=E;exports.usePersonaRuntime=ee;exports.usePersonaRuntimeEndpoint=te;exports.usePersonaRuntimeProtocol=D;exports.usePersonaRuntimeWebRTCProtocol=se;
9
+ */var N;function K(){if(N)return C;N=1;var o=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(n,s,i){var r=null;if(i!==void 0&&(r=""+i),s.key!==void 0&&(r=""+s.key),"key"in s){i={};for(var l in s)l!=="key"&&(i[l]=s[l])}else i=s;return s=i.ref,{$$typeof:o,type:n,key:r,ref:s!==void 0?s:null,props:i}}return C.Fragment=t,C.jsx=e,C.jsxs=e,C}I.exports=K();var T=I.exports;function B(o){return o.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function _(o){const t=[];let e=null;for(const s of o)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(o){var e,n;const t=((e=o.files)==null?void 0:e.map(s=>({type:"file",data:s.url,mimeType:s.contentType})))??[];return o.role==="function"?{id:o.id,role:"assistant",status:(o==null?void 0:o.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((n=o.functionCalls)==null?void 0:n.map(s=>{var i;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(i=o.functionResponse)==null?void 0:i.result}}))??[]}:{id:o.id,role:o.role,content:o.type==="reasoning"?[{type:"reasoning",text:o.text},...t]:[{type:"text",text:o.text},...t]}}class S{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 A extends S{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:i}=this.config,r=this.session??"new",l=e,h=await(await fetch(`${n}/agents/${i}/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(h.response.messages.map(b=>({type:"message",payload:b})))}}class E extends S{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),i=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${n}&agentId=${i}&apiKey=${s}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",u=>{const h=JSON.parse(u.data);this.notifyMessage(h)}),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 h;this.setStatus("disconnected"),this.webSocket=null,(h=this.config.logger)==null||h.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 i=new Audio;i.srcObject=this.remoteStream,i.play().catch(r=>{var l;(l=this.config.logger)==null||l.error("Error playing remote audio:",r)})},this.pc.onicecandidate=s=>{var i;s.candidate&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:s.candidate}}))},this.pc.ondatachannel=s=>{const i=s.channel;i.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 i={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(l=this.config.logger)==null||l.debug("Opening connection to WebRTC server: ",i);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:i}};this.ws.send(JSON.stringify(r))},this.ws.onmessage=async s=>{var r;const i=JSON.parse(s.data);if(i.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(i.payload.sdp));else if(i.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(i.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),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(s),this.remoteAnalyser.getByteFrequencyData(i);const r=s.reduce((u,h)=>u+h,0)/s.length,l=i.reduce((u,h)=>u+h,0)/i.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 v extends S{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,i=t[n];if(!i){await this.fail(`Tool ${n} not found`);return}try{const r=await i(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 S{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 i;if(!this.config.onTransaction){(i=this.config.logger)==null||i.error("Transaction protocol config is not set");return}const n=new V(this.config),s=new H(e,n);this.config.onTransaction(s)}}const R=f.createContext(void 0);function Q(o){return new Promise((t,e)=>{const n=new FileReader;n.readAsDataURL(o),n.onload=()=>{const i=n.result.split(";base64,")[1];t(i)},n.onerror=s=>{e(s)}})}function X({dev:o=!1,protocols:t,logger:e,children:n,session:s="new",...i}){const[r,l]=f.useState(!1),[u,h]=f.useState([]),[b,D]=f.useState(s),[P,O]=f.useState(new Map),$=f.useRef(!1),w=f.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const c=o?"localhost:8000":"persona.applica.guru/api",p=o?"http":"https",g=o?"ws":"wss";let m=Object.keys(t).map(y=>{switch(y){case"rest":const d=t[y];return d===!0?new A({apiUrl:`${p}://${c}`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new A(d);case"webrtc":const k=t[y];return k===!0?new v({webrtcUrl:`${g}://${c}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new v(k);case"websocket":const M=t[y];return M===!0?new E({webSocketUrl:`${g}://${c}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new E(M);default:throw new Error(`Unknown protocol: ${y}`)}});return i.tools&&m.push(new W({apiUrl:`${p}://${c}`,apiKey:i.apiKey,agentId:i.agentId,onTransaction:async y=>{await y.invoke(i.tools)},logger:e})),m}throw new Error("Invalid protocols configuration")},[]);f.useEffect(()=>{$.current||($.current=!0,e==null||e.debug("Initializing protocols: ",w.map(c=>c.getName())),w.forEach(c=>{c.setSession(b),c.clearListeners(),c.addStatusChangeListener(p=>{e==null||e.debug(`${c.getName()} has notified new status: ${p}`),P.set(c.getName(),p),O(new Map(P))}),c.addMessageListener(p=>{if(p.type==="message"){const g=p.payload;h(m=>_([...m,{...g,protocol:c.getName()}]))}else p.type==="transaction"&&w.filter(g=>g!==c).forEach(g=>g.onTransaction(p.payload))}),c.autostart&&c.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${c.getName()}`),c.connect(b))}))},[b,w,e,P]);const L=async c=>{var y;if(((y=c.content[0])==null?void 0:y.type)!=="text")throw new Error("Only text messages are supported");const p=c.content[0].text;h(d=>[...d,{role:"user",type:"text",text:p}]),l(!0);const g=w.sort((d,k)=>k.getPriority()-d.getPriority()).find(d=>d.status==="connected"),m=[];if(c.attachments)for(const d of c.attachments)d.contentType.startsWith("image/")&&d.file&&m.push({role:"user",image:{contentType:d.contentType,content:await Q(d.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(g==null?void 0:g.send(m)),l(!1)},U=f.useCallback(()=>(l(!1),h([]),D("new"),Promise.resolve()),[]),j=f.useCallback(()=>Promise.resolve(),[]),F=x.useExternalStoreRuntime({isRunning:r,messages:u,convertMessage:Y,onNew:L,onCancel:U,onReload:j,adapters:{attachments:new x.CompositeAttachmentAdapter([new x.SimpleImageAttachmentAdapter])}});return T.jsx(R.Provider,{value:{protocols:w,protocolsStatus:P},children:T.jsx(x.AssistantRuntimeProvider,{runtime:F,children:n})})}function Z({children:o,...t}){return T.jsx(X,{...t,children:o})}function ee(){const o=f.useContext(R);if(!o)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return o}function z(o){const t=f.useContext(R);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(s=>s.getName()===o);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 o=f.useContext(R);if(!o)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");for(const t of o.protocols)if(t.getName()==="rest")return t.config.apiUrl;throw new Error("REST protocol not found")}function se(){return z("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=S;exports.PersonaRESTProtocol=A;exports.PersonaRuntimeProvider=Z;exports.PersonaTransactionProtocol=W;exports.PersonaWebRTCProtocol=v;exports.PersonaWebSocketProtocol=E;exports.usePersonaRuntime=ee;exports.usePersonaRuntimeEndpoint=te;exports.usePersonaRuntimeProtocol=z;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({ date: new Date().toISOString(), 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).map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | true | 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 }\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | true | 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 }\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | true | 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 }\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n });\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","useEffect","protocol","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,EACh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AI,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]}
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 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).map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | true | 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 }\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | true | 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 }\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | true | 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 }\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n });\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","useEffect","protocol","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,EACd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AASuB,IAAgE,CACvE,OAAOH,EAA0B,QAAQ,CAC3C,CCnSA,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
@@ -3,7 +3,7 @@ var J = (a, e, t) => e in a ? F(a, e, { enumerable: !0, configurable: !0, writab
3
3
  var o = (a, e, t) => J(a, typeof e != "symbol" ? e + "" : e, t);
4
4
  import { createContext as K, useContext as A, useState as k, useRef as q, useMemo as _, useEffect as B, useCallback as v } from "react";
5
5
  import { useExternalStoreRuntime as Y, CompositeAttachmentAdapter as G, SimpleImageAttachmentAdapter as V, AssistantRuntimeProvider as H } from "@assistant-ui/react";
6
- var D = { exports: {} }, b = {};
6
+ var z = { exports: {} }, b = {};
7
7
  /**
8
8
  * @license React
9
9
  * react-jsx-runtime.production.js
@@ -35,8 +35,8 @@ function Q() {
35
35
  }
36
36
  return b.Fragment = e, b.jsx = t, b.jsxs = t, b;
37
37
  }
38
- D.exports = Q();
39
- var R = D.exports;
38
+ z.exports = Q();
39
+ var R = z.exports;
40
40
  function X(a) {
41
41
  return a.filter((e) => {
42
42
  var t;
@@ -162,7 +162,7 @@ class M extends P {
162
162
  );
163
163
  }
164
164
  }
165
- class I extends P {
165
+ class N extends P {
166
166
  constructor(t) {
167
167
  super();
168
168
  o(this, "status");
@@ -368,7 +368,7 @@ class et {
368
368
  this.analyzerFrame && (cancelAnimationFrame(this.analyzerFrame), this.analyzerFrame = null), this.localAnalyser = null, this.remoteAnalyser = null;
369
369
  }
370
370
  }
371
- class N extends P {
371
+ class I extends P {
372
372
  constructor(t) {
373
373
  super();
374
374
  o(this, "status");
@@ -451,7 +451,7 @@ class nt {
451
451
  }
452
452
  try {
453
453
  const r = await i(s);
454
- await this.complete({ date: (/* @__PURE__ */ new Date()).toISOString(), result: r });
454
+ await this.complete(r);
455
455
  } catch (r) {
456
456
  await this.fail(`Error executing tool ${n}: ${r}`);
457
457
  }
@@ -522,7 +522,7 @@ function ot({
522
522
  session: s = "new",
523
523
  ...i
524
524
  }) {
525
- const [r, l] = k(!1), [u, h] = k([]), [w, z] = k(s), [S, W] = k(/* @__PURE__ */ new Map()), E = q(!1), m = _(() => {
525
+ const [r, l] = k(!1), [u, h] = k([]), [w, D] = k(s), [C, W] = k(/* @__PURE__ */ new Map()), E = q(!1), m = _(() => {
526
526
  if (Array.isArray(e))
527
527
  return e;
528
528
  if (typeof e == "object" && e !== null) {
@@ -538,21 +538,21 @@ function ot({
538
538
  logger: t
539
539
  }) : new M(d);
540
540
  case "webrtc":
541
- const C = e[g];
542
- return C === !0 ? new N({
541
+ const S = e[g];
542
+ return S === !0 ? new I({
543
543
  webrtcUrl: `${p}://${c}/webrtc`,
544
544
  apiKey: i.apiKey,
545
545
  agentId: i.agentId,
546
546
  logger: t
547
- }) : new N(C);
547
+ }) : new I(S);
548
548
  case "websocket":
549
549
  const T = e[g];
550
- return T === !0 ? new I({
550
+ return T === !0 ? new N({
551
551
  webSocketUrl: `${p}://${c}/websocket`,
552
552
  apiKey: i.apiKey,
553
553
  agentId: i.agentId,
554
554
  logger: t
555
- }) : new I(T);
555
+ }) : new N(T);
556
556
  default:
557
557
  throw new Error(`Unknown protocol: ${g}`);
558
558
  }
@@ -577,7 +577,7 @@ function ot({
577
577
  m.map((c) => c.getName())
578
578
  ), m.forEach((c) => {
579
579
  c.setSession(w), c.clearListeners(), c.addStatusChangeListener((f) => {
580
- t == null || t.debug(`${c.getName()} has notified new status: ${f}`), S.set(c.getName(), f), W(new Map(S));
580
+ t == null || t.debug(`${c.getName()} has notified new status: ${f}`), C.set(c.getName(), f), W(new Map(C));
581
581
  }), c.addMessageListener((f) => {
582
582
  if (f.type === "message") {
583
583
  const p = f.payload;
@@ -587,13 +587,13 @@ function ot({
587
587
  } else f.type === "transaction" && m.filter((p) => p !== c).forEach((p) => p.onTransaction(f.payload));
588
588
  }), c.autostart && c.status === "disconnected" && (t == null || t.debug(`Connecting to protocol: ${c.getName()}`), c.connect(w));
589
589
  }));
590
- }, [w, m, t, S]);
590
+ }, [w, m, t, C]);
591
591
  const O = async (c) => {
592
592
  var g;
593
593
  if (((g = c.content[0]) == null ? void 0 : g.type) !== "text") throw new Error("Only text messages are supported");
594
594
  const f = c.content[0].text;
595
595
  h((d) => [...d, { role: "user", type: "text", text: f }]), l(!0);
596
- const p = m.sort((d, C) => C.getPriority() - d.getPriority()).find((d) => d.status === "connected"), y = [];
596
+ const p = m.sort((d, S) => S.getPriority() - d.getPriority()).find((d) => d.status === "connected"), y = [];
597
597
  if (c.attachments)
598
598
  for (const d of c.attachments)
599
599
  d.contentType.startsWith("image/") && d.file && y.push({
@@ -610,7 +610,7 @@ function ot({
610
610
  text: c.content[0].text,
611
611
  type: "text"
612
612
  }), t == null || t.debug("Sending message:", y), await (p == null ? void 0 : p.send(y)), l(!1);
613
- }, U = v(() => (l(!1), h([]), z("new"), Promise.resolve()), []), L = v(() => Promise.resolve(), []), j = Y({
613
+ }, U = v(() => (l(!1), h([]), D("new"), Promise.resolve()), []), L = v(() => Promise.resolve(), []), j = Y({
614
614
  isRunning: r,
615
615
  messages: u,
616
616
  convertMessage: tt,
@@ -621,7 +621,7 @@ function ot({
621
621
  attachments: new G([new V()])
622
622
  }
623
623
  });
624
- return /* @__PURE__ */ R.jsx(x.Provider, { value: { protocols: m, protocolsStatus: S }, children: /* @__PURE__ */ R.jsx(H, { runtime: j, children: n }) });
624
+ return /* @__PURE__ */ R.jsx(x.Provider, { value: { protocols: m, protocolsStatus: C }, children: /* @__PURE__ */ R.jsx(H, { runtime: j, children: n }) });
625
625
  }
626
626
  function ht({ children: a, ...e }) {
627
627
  return /* @__PURE__ */ R.jsx(ot, { ...e, children: a });
@@ -691,8 +691,8 @@ export {
691
691
  M as PersonaRESTProtocol,
692
692
  ht as PersonaRuntimeProvider,
693
693
  it as PersonaTransactionProtocol,
694
- N as PersonaWebRTCProtocol,
695
- I as PersonaWebSocketProtocol,
694
+ I as PersonaWebRTCProtocol,
695
+ N as PersonaWebSocketProtocol,
696
696
  dt as usePersonaRuntime,
697
697
  ft as usePersonaRuntimeEndpoint,
698
698
  rt as usePersonaRuntimeProtocol,