@applica-software-guru/persona-sdk 0.1.63 → 0.1.65

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.
package/README.md CHANGED
@@ -304,53 +304,69 @@ In this example:
304
304
 
305
305
  ### Using the `tools` Prop in PersonaRuntimeProvider
306
306
 
307
- **⚠️ Important:** Defined tools must be configured inside the `persona-core` as external tools. If this step is skipped, the tools you declare will never be called. Please ensure that all tools are properly registered in `persona-core` before using them in your application.
307
+ The `tools` prop allows you to define custom tools that the Transaction Protocol can invoke in response to function calls. As of vNEXT, you can provide tools in two ways:
308
308
 
309
- Instead of handling transactions manually, you can use the `tools` prop inside the `PersonaRuntimeProvider` to define and manage tools. This simplifies the process by allowing you to directly pass a set of tools to the provider.
309
+ #### 1. As an Object (Legacy, Backward Compatible)
310
310
 
311
- #### Example Usage
311
+ > **Important:** When using the legacy object format, your agent configuration must also include the tool schema for each tool. If the schema is missing, the configured tools will not work as expected. This is not required when using the array format with `createTool`.
312
312
 
313
- Here’s how you can use the `tools` prop:
313
+ You can define tools as an object where each key is the tool's name and the value is the function to execute:
314
314
 
315
315
  ```tsx
316
316
  <PersonaRuntimeProvider
317
- dev
318
- logger={logger}
319
- protocols={{
320
- transaction: true, // Enable the transaction protocol
321
- }}
322
317
  tools={{
323
318
  get_user_agent: () => navigator.userAgent || 'unknown',
324
319
  get_client_date: () => ({ date: new Date().toISOString() }),
325
320
  }}
326
- session="your-session-id"
327
- apiKey="your-api-key"
328
- agentId="your-agent-id"
329
- >
330
- <YourComponent />
331
- </PersonaRuntimeProvider>
321
+ ...otherProps
322
+ />
332
323
  ```
333
324
 
334
- #### How It Works
325
+ #### 2. As an Array of Tool Instances (Recommended)
335
326
 
336
- - The `tools` prop is an object where each key is the name of a tool, and the value is the function to execute.
337
- - When a transaction is received, the Transaction Protocol automatically invokes the appropriate tool based on the function call.
338
- - This eliminates the need to manually handle transactions and invoke tools.
327
+ For better type safety, schema support, and documentation, you can define tools using the `createTool` utility and pass an array of tool instances:
339
328
 
340
- #### Benefits
329
+ ```tsx
330
+ import { createTool } from '@applica-software-guru/persona-sdk';
331
+
332
+ const tools = [
333
+ createTool({
334
+ name: 'sum',
335
+ title: 'Sum two numbers',
336
+ description: 'Sums two numbers and returns the result.',
337
+ parameters: {
338
+ a: { type: 'number', description: 'First number to sum', required: true },
339
+ b: { type: 'number', description: 'Second number to sum', required: true },
340
+ },
341
+ output: {
342
+ result: { type: 'number', description: 'Sum of the two numbers' },
343
+ },
344
+ implementation: async (a: number, b: number) => {
345
+ return { result: a + b };
346
+ },
347
+ }),
348
+ // Add more tools as needed
349
+ ];
350
+
351
+ <PersonaRuntimeProvider
352
+ tools={tools}
353
+ ...otherProps
354
+ />
355
+ ```
341
356
 
342
- 1. **Simplified Code**: No need to manually handle transactions or invoke tools.
343
- 2. **Centralized Management**: All tools are defined in one place, making them easier to manage and update.
344
- 3. **Improved Readability**: The code is cleaner and more intuitive.
357
+ **Recommended:** Use the array format with `createTool` for new projects. This enables better validation, documentation, and future extensibility.
345
358
 
346
- #### Best Practices
359
+ #### How It Works
360
+
361
+ - The SDK will automatically normalize the tools you provide, regardless of the format.
362
+ - When a transaction is received, the Transaction Protocol invokes the appropriate tool by name.
363
+ - Both synchronous and asynchronous tool functions are supported.
347
364
 
348
- - Use descriptive names for tools to make them easy to identify.
349
- - Ensure tools handle errors gracefully to avoid unexpected failures.
350
- - Test tools thoroughly to ensure they work as expected in different scenarios.
351
- - Avoid exposing sensitive data or performing unsafe operations in tools.
365
+ #### Best Practices
352
366
 
353
- By using the `tools` prop, you can streamline the integration of custom tools into your application, making it easier to extend and maintain.
367
+ - Prefer the array format with `createTool` for new codebases.
368
+ - Use descriptive names and provide parameter/output schemas for each tool.
369
+ - Handle errors gracefully in your tool implementations.
354
370
 
355
371
  ---
356
372
 
@@ -1,4 +1,4 @@
1
- "use strict";var K=Object.defineProperty;var B=(o,t,e)=>t in o?K(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var a=(o,t,e)=>B(o,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react"),A=require("@assistant-ui/react");var z={exports:{}},P={};/**
1
+ "use strict";var G=Object.defineProperty;var H=(o,t,e)=>t in o?G(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var i=(o,t,e)=>H(o,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("react"),v=require("@assistant-ui/react");var F={exports:{}},x={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.js
4
4
  *
@@ -6,7 +6,7 @@
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 W;function Y(){if(W)return P;W=1;var o=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,n,i){var r=null;if(i!==void 0&&(r=""+i),n.key!==void 0&&(r=""+n.key),"key"in n){i={};for(var l in n)l!=="key"&&(i[l]=n[l])}else i=n;return n=i.ref,{$$typeof:o,type:s,key:r,ref:n!==void 0?n:null,props:i}}return P.Fragment=t,P.jsx=e,P.jsxs=e,P}z.exports=Y();var v=z.exports;function G(o){return o.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function j(o){const t=[];let e=null;for(const n of o)n.type!=="transaction"&&(n.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(n)):n.functionCalls?(e&&t.push(e),t.push(n),e=null):n.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:n.functionResponse}:e&&n.protocol===e.protocol&&(e.role===n.role||n.finishReason==="stop")?(e.text+=n.text,e.files=[...e.files??[],...n.files??[]]):(e&&t.push(e),e={...n}));return e&&t.push(e),G(t)}function V(o){var e,s;const t=((e=o.files)==null?void 0:e.map(n=>({type:"file",data:n.url,mimeType:n.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:((s=o.functionCalls)==null?void 0:s.map(n=>{var i;return{type:"tool-call",toolName:n.name,toolCallId:n.id,args:n.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 k{constructor(){a(this,"statusChangeCallbacks",[]);a(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addPacketListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyPacket(t){this.messageCallbacks.forEach(e=>e(t))}async notifyPackets(t){t.forEach(e=>{this.messageCallbacks.forEach(s=>s(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(s=>s(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(t){}}class $ extends k{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"notify",!0);a(this,"context",{});this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 100}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async sendPacket(e){var w,b;const{apiUrl:s,apiKey:n,agentId:i}=this.config,r=this.session??"new";if(e.type==="command"&&((w=e==null?void 0:e.payload)==null?void 0:w.command)=="set_initial_context"){this.context=(b=e==null?void 0:e.payload)==null?void 0:b.arguments;return}const l=e.payload,y=await(await fetch(`${s}/sessions/${r}/messages`,{body:JSON.stringify({agentId:i,userMessage:l,initial_context:this.context}),method:"POST",headers:{"Content-Type":"application/json","x-persona-apikey":n}})).json();this.notifyPackets(y.response.messages.map(E=>({type:"message",payload:E})))}}class N extends k{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 500}async syncSession(e){var s;(s=this.config.logger)==null||s.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var l;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const s=e||this.session||"new";(l=this.config.logger)==null||l.debug("Connecting to WebSocket with sessionId:",s);const n=encodeURIComponent(this.config.apiKey),i=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${s}&agentId=${i}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",u=>{const y=JSON.parse(u.data);this.notifyPacket(y)}),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 y;this.setStatus("disconnected"),this.webSocket=null,(y=this.config.logger)==null||y.error("WebSocket error",u)}),Promise.resolve(s)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}sendPacket(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify(e)),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class H{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 s;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(n){(s=this.config.logger)==null||s.error("Error accessing microphone:",n);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(n=>{this.pc.addTrack(n,this.localStream)}),this.pc.ontrack=n=>{n.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=n=>{var i;n.candidate&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:n.candidate}}))},this.pc.ondatachannel=n=>{const i=n.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 n=await this.pc.createOffer();await this.pc.setLocalDescription(n);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:n.sdp,type:n.type},connectionId:(Date.now()%1e6).toString(),metadata:i}};this.ws.send(JSON.stringify(r))},this.ws.onmessage=async n=>{var r;const i=JSON.parse(n.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(s=>{s(e)})})}sendPacket(t){var e,s;if(!this.dataChannel){(e=this.config.logger)==null||e.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(JSON.stringify(t)),(s=this.config.logger)==null||s.info("Sent message:",t)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const t=this.audioCtx.createMediaStreamSource(this.localStream),e=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,t.connect(this.localAnalyser),e.connect(this.remoteAnalyser);const s=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(i);const r=n.reduce((u,y)=>u+y,0)/n.length,l=i.reduce((u,y)=>u+y,0)/i.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(u=>{u({localAmplitude:r,remoteAmplitude:l})}),this.analyzerFrame=requestAnimationFrame(s)};this.analyzerFrame=requestAnimationFrame(s)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class I extends k{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 H(e),this.webRTCClient.addMessageCallback(s=>{const n=JSON.parse(s.data);this.notifyPacket(n)})}getName(){return"webrtc"}getPriority(){return 1e3}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var s;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(s=this.config.logger)==null||s.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var e,s,n;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(s=this.config)==null?void 0:s.logger)==null||n.debug("Disconnected from WebRTC")}sendPacket(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendPacket(e),Promise.resolve())}}class Q{constructor(t){a(this,"config");this.config=t}async complete(t,e){var s;await this.persist(t,{...e,success:!0}),(s=this.config.logger)==null||s.debug("Transaction completed:",t)}async fail(t,e){var s;await this.persist(t,{...e,success:!1}),(s=this.config.logger)==null||s.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 X{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 s=e.name,n=e.args,i=t[s];if(!i){await this.fail(`Tool ${s} not found`);return}try{const r=await i(n);await this.complete(r)}catch(r){await this.fail(`Error executing tool ${s}: ${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 D extends k{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 sendPacket(e){}onTransaction(e){var i;if(!this.config.onTransaction){(i=this.config.logger)==null||i.error("Transaction protocol config is not set");return}const s=new Q(this.config),n=new X(e,s);this.config.onTransaction(n)}}const x=p.createContext(void 0);function Z(o){return new Promise((t,e)=>{const s=new FileReader;s.readAsDataURL(o),s.onload=()=>{const i=s.result.split(";base64,")[1];t(i)},s.onerror=n=>{e(n)}})}function ee({dev:o=!1,baseUrl:t,protocols:e,logger:s,children:n,session:i="new",...r}){const[l,u]=p.useState(!1),[y,w]=p.useState([]),[b,E]=p.useState(i),[R,O]=p.useState(new Map),M=p.useRef(!1),C=p.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const c=o?"localhost:8000":t||"persona.applica.guru/api",f=o?"http":"https",d=o?"ws":"wss";let g=Object.keys(e).map(m=>{switch(m){case"rest":const h=e[m];return h===!0?new $({apiUrl:`${f}://${c}`,apiKey:r.apiKey,agentId:r.agentId,logger:s}):typeof h=="object"&&h!==null?new $(h):null;case"webrtc":const S=e[m];return S===!0?new I({webrtcUrl:`${d}://${c}/webrtc`,apiKey:r.apiKey,agentId:r.agentId,logger:s}):typeof S=="object"&&S!==null?new I(S):null;case"websocket":const T=e[m];return T===!0?new N({webSocketUrl:`${d}://${c}/websocket`,apiKey:r.apiKey,agentId:r.agentId,logger:s}):typeof T=="object"&&T!==null?new N(T):null;default:throw new Error(`Unknown protocol: ${m}`)}}).filter(m=>m!==null);return r.tools&&g.push(new D({apiUrl:`${f}://${c}`,apiKey:r.apiKey,agentId:r.agentId,onTransaction:async m=>{await m.invoke(r.tools)},logger:s})),g}throw new Error("Invalid protocols configuration")},[]);p.useEffect(()=>{M.current||(M.current=!0,s==null||s.debug("Initializing protocols: ",C.map(c=>c.getName())),C.forEach(c=>{c.setSession(b),c.clearListeners(),c.addStatusChangeListener(f=>{s==null||s.debug(`${c.getName()} has notified new status: ${f}`),R.set(c.getName(),f),f==="connected"&&r.context&&c.sendPacket({type:"command",payload:{command:"set_initial_context",arguments:r.context}}),O(new Map(R))}),c.addPacketListener(f=>{if(f.type==="message"){const d=f.payload;w(g=>j([...g,{...d,protocol:c.getName()}]))}else if(f.type==="reasoning"){const d=f.payload;let g=d.thought;d.imageUrl&&(g+=`
9
+ */var W;function Q(){if(W)return x;W=1;var o=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,n,a){var r=null;if(a!==void 0&&(r=""+a),n.key!==void 0&&(r=""+n.key),"key"in n){a={};for(var l in n)l!=="key"&&(a[l]=n[l])}else a=n;return n=a.ref,{$$typeof:o,type:s,key:r,ref:n!==void 0?n:null,props:a}}return x.Fragment=t,x.jsx=e,x.jsxs=e,x}F.exports=Q();var N=F.exports;function X(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 n of o)n.type!=="transaction"&&(n.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(n)):n.functionCalls?(e&&t.push(e),t.push(n),e=null):n.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:n.functionResponse}:e&&n.protocol===e.protocol&&(e.role===n.role||n.finishReason==="stop")?(e.text+=n.text,e.files=[...e.files??[],...n.files??[]]):(e&&t.push(e),e={...n}));return e&&t.push(e),X(t)}function Z(o){var e,s;const t=((e=o.files)==null?void 0:e.map(n=>({type:"file",data:n.url,mimeType:n.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:((s=o.functionCalls)==null?void 0:s.map(n=>{var a;return{type:"tool-call",toolName:n.name,toolCallId:n.id,args:n.args,result:(a=o.functionResponse)==null?void 0:a.result}}))??[]}:{id:o.id,role:o.role,content:o.type==="reasoning"?[{type:"reasoning",text:o.text},...t]:[{type:"text",text:o.text},...t]}}class R{constructor(){i(this,"statusChangeCallbacks",[]);i(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addPacketListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyPacket(t){this.messageCallbacks.forEach(e=>e(t))}async notifyPackets(t){t.forEach(e=>{this.messageCallbacks.forEach(s=>s(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(s=>s(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(t){}}class I extends R{constructor(e){super();i(this,"status");i(this,"autostart");i(this,"session");i(this,"config");i(this,"notify",!0);i(this,"context",{});i(this,"tools",[]);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 100}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async sendPacket(e){var u,m,w,C;const{apiUrl:s,apiKey:n,agentId:a}=this.config,r=this.session??"new";if(e.type==="command"&&((u=e==null?void 0:e.payload)==null?void 0:u.command)=="set_initial_context"){this.context=(m=e==null?void 0:e.payload)==null?void 0:m.arguments;return}else if(e.type==="command"&&((w=e==null?void 0:e.payload)==null?void 0:w.command)=="set_local_tools"){this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:"Local tools with rest protocol are not supported."}});return}const l=e.payload;try{const S=await(await fetch(`${s}/sessions/${r}/messages`,{body:JSON.stringify({agentId:a,userMessage:l,initialContext:this.context,tools:this.tools}),method:"POST",headers:{"Content-Type":"application/json","x-persona-apikey":n}})).json();this.notifyPackets(S.response.messages.map(M=>({type:"message",payload:M})))}catch(E){this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"An error occurred while processing your request. Please try again later."}}),(C=this.config.logger)==null||C.error("Error sending packet:",E)}}}class q extends R{constructor(e){super();i(this,"status");i(this,"autostart");i(this,"session");i(this,"config");i(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 500}async syncSession(e){var s;(s=this.config.logger)==null||s.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var l;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const s=e||this.session||"new";(l=this.config.logger)==null||l.debug("Connecting to WebSocket with sessionId:",s);const n=encodeURIComponent(this.config.apiKey),a=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${s}&agentId=${a}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",u=>{const m=JSON.parse(u.data);this.notifyPacket(m)}),this.webSocket.addEventListener("close",u=>{var m;this.setStatus("disconnected"),this.webSocket=null,u.code!==1e3&&(this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"Oops! The connection to the server was lost. Please try again later."}}),(m=this.config.logger)==null||m.warn("WebSocket connection closed"))}),this.webSocket.addEventListener("error",()=>{var u;this.setStatus("disconnected"),this.webSocket=null,(u=this.config.logger)==null||u.error("WebSocket connection error")}),Promise.resolve(s)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}sendPacket(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify(e)),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class ee{constructor(t){i(this,"config");i(this,"pc",null);i(this,"ws",null);i(this,"localStream",null);i(this,"remoteStream",new MediaStream);i(this,"audioCtx",null);i(this,"localAnalyser",null);i(this,"remoteAnalyser",null);i(this,"analyzerFrame",null);i(this,"dataChannel",null);i(this,"isConnected",!1);i(this,"visualizerCallbacks",[]);i(this,"messageCallbacks",[]);i(this,"errorCallbacks",[]);i(this,"queuedMessages",[]);this.config=t}async connect(t){var s;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(n){(s=this.config.logger)==null||s.error("Error accessing microphone:",n);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(n=>{this.pc.addTrack(n,this.localStream)}),this.pc.ontrack=n=>{n.streams[0].getTracks().forEach(r=>{this.remoteStream.addTrack(r)}),this.audioCtx||this._startAnalyzers();const a=new Audio;a.srcObject=this.remoteStream,a.play().catch(r=>{var l;(l=this.config.logger)==null||l.error("Error playing remote audio:",r)})},this.pc.onicecandidate=n=>{var a;n.candidate&&((a=this.ws)==null?void 0:a.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:n.candidate}}))},this.pc.ondatachannel=n=>{const a=n.channel;a.onmessage=r=>{this.messageCallbacks.forEach(l=>{l(r)})},a.onopen=()=>{var r;for(;this.queuedMessages.length>0;){const l=this.queuedMessages.shift();l&&(a.send(JSON.stringify(l)),(r=this.config.logger)==null||r.info("Sent queued message:",l))}}};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 n=await this.pc.createOffer();await this.pc.setLocalDescription(n);const a={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(l=this.config.logger)==null||l.debug("Opening connection to WebRTC server: ",a);const r={type:"OFFER",src:((u=crypto.randomUUID)==null?void 0:u.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:n.sdp,type:n.type},connectionId:(Date.now()%1e6).toString(),metadata:a}};this.ws.send(JSON.stringify(r))},this.ws.onmessage=async n=>{var r;const a=JSON.parse(n.data);if(a.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(a.payload.sdp));else if(a.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(a.payload.candidate))}catch(l){(r=this.config.logger)==null||r.error("Error adding ICE candidate:",l)}},this.ws.onclose=n=>{n.code!==1e3&&this.errorCallbacks.forEach(a=>{a("Oops! The connection to the server was lost. Please try again later.")}),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)}addErrorCallback(t){this.errorCallbacks.push(t)}createDataChannel(t="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(t),this.dataChannel.onopen=()=>{var e,s;for((e=this.config.logger)==null||e.info("Data channel opened");this.queuedMessages.length>0;){const n=this.queuedMessages.shift();n&&(this.dataChannel.send(JSON.stringify(n)),(s=this.config.logger)==null||s.info("Sent queued message:",n))}},this.dataChannel.onmessage=e=>{this.messageCallbacks.forEach(s=>{s(e)})})}sendPacket(t){var e;if(!this.dataChannel||this.dataChannel.readyState!=="open"){this.queuedMessages.push(t);return}this.dataChannel.send(JSON.stringify(t)),(e=this.config.logger)==null||e.info("Sent message:",t)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const t=this.audioCtx.createMediaStreamSource(this.localStream),e=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,t.connect(this.localAnalyser),e.connect(this.remoteAnalyser);const s=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),a=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(a);const r=n.reduce((u,m)=>u+m,0)/n.length,l=a.reduce((u,m)=>u+m,0)/a.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(u=>{u({localAmplitude:r,remoteAmplitude:l})}),this.analyzerFrame=requestAnimationFrame(s)};this.analyzerFrame=requestAnimationFrame(s)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class O extends R{constructor(e){super();i(this,"status");i(this,"session");i(this,"autostart");i(this,"config");i(this,"webRTCClient");this.config=e,this.status="disconnected",this.session=null,this.autostart=(e==null?void 0:e.autostart)??!1,this.webRTCClient=new ee(e),this.webRTCClient.addMessageCallback(s=>{const n=JSON.parse(s.data);this.notifyPacket(n)}),this.webRTCClient.addErrorCallback(s=>{var n;(n=this.config.logger)==null||n.error("WebRTC error:",s),this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:s}})})}getName(){return"webrtc"}getPriority(){return 1e3}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var s;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(s=this.config.logger)==null||s.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var e,s,n;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(s=this.config)==null?void 0:s.logger)==null||n.debug("Disconnected from WebRTC")}sendPacket(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendPacket(e),Promise.resolve())}}class te{constructor(t){i(this,"config");this.config=t}async complete(t,e){var s;await this.persist(t,{...e,success:!0}),(s=this.config.logger)==null||s.debug("Transaction completed:",t)}async fail(t,e){var s;await this.persist(t,{...e,success:!1}),(s=this.config.logger)==null||s.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 se{constructor(t,e){i(this,"transaction");i(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 s=e.name,n=e.args,a=t[s];if(!a){await this.fail(`Tool ${s} not found`);return}try{const r=await a.apply(null,Object.values(n));await this.complete(r)}catch(r){await this.fail(`Error executing tool ${s}: ${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 z extends R{constructor(e){super();i(this,"status");i(this,"autostart");i(this,"session");i(this,"config");i(this,"notify",!0);i(this,"_tools");if(this.config=e,this.status="disconnected",this.autostart=!0,Array.isArray(e.tools)){this._tools={};for(const s of e.tools)s.schema&&s.implementation&&(this._tools[s.schema.name]=s.implementation)}else this._tools=e.tools}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 sendPacket(e){}onTransaction(e){console.log("transaction received:",e);const s=new te(this.config),n=new se(e,s);this.config.onTransaction?this.config.onTransaction(n):n.invoke(this._tools)}getTools(){return this._tools}}const T=f.createContext(void 0);function ne(o){return new Promise((t,e)=>{const s=new FileReader;s.readAsDataURL(o),s.onload=()=>{const a=s.result.split(";base64,")[1];t(a)},s.onerror=n=>{e(n)}})}function oe({dev:o=!1,baseUrl:t,protocols:e,logger:s,children:n,session:a="new",...r}){const[l,u]=f.useState(!1),[m,w]=f.useState([]),[C,E]=f.useState(a),[S,M]=f.useState(new Map),j=f.useRef(!1),P=f.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const c=o?"localhost:8000":t||"persona.applica.guru/api",p=o?"http":"https",h=o?"ws":"wss";let y=Object.keys(e).map(g=>{switch(g){case"rest":const d=e[g];return d===!0?new I({apiUrl:`${p}://${c}`,apiKey:r.apiKey,agentId:r.agentId,logger:s}):typeof d=="object"&&d!==null?new I(d):null;case"webrtc":const k=e[g];return k===!0?new O({webrtcUrl:`${h}://${c}/webrtc`,apiKey:r.apiKey,agentId:r.agentId,logger:s}):typeof k=="object"&&k!==null?new O(k):null;case"websocket":const A=e[g];return A===!0?new q({webSocketUrl:`${h}://${c}/websocket`,apiKey:r.apiKey,agentId:r.agentId,logger:s}):typeof A=="object"&&A!==null?new q(A):null;default:throw new Error(`Unknown protocol: ${g}`)}}).filter(g=>g!==null);return r.tools&&y.push(new z({apiUrl:`${p}://${c}`,apiKey:r.apiKey,agentId:r.agentId,tools:r.tools,logger:s})),y}throw new Error("Invalid protocols configuration")},[]);f.useEffect(()=>{j.current||(j.current=!0,s==null||s.debug("Initializing protocols: ",P.map(c=>c.getName())),P.forEach(c=>{c.setSession(C),c.clearListeners(),c.addStatusChangeListener(p=>{s==null||s.debug(`${c.getName()} has notified new status: ${p}`),S.set(c.getName(),p),p==="connected"&&(r.context&&c.sendPacket({type:"command",payload:{command:"set_initial_context",arguments:r.context}}),r.tools&&Array.isArray(r.tools)&&c.sendPacket({type:"command",payload:{command:"set_local_tools",arguments:{tools:r.tools.map(h=>h.schema)}}})),M(new Map(S))}),c.addPacketListener(p=>{if(p.type==="message"){const h=p.payload;w(y=>_([...y,{...h,protocol:c.getName()}]))}else if(p.type==="reasoning"){const h=p.payload;let y=h.thought;h.imageUrl&&(y+=`
10
10
 
11
- ![image](https://persona.applica.guru/api/files/${d.imageUrl})`);const m={type:"reasoning",text:g,role:"assistant",finishReason:"stop"};w(h=>j([...h,{...m,protocol:c.getName()}]))}else f.type==="transaction"&&C.filter(d=>d!==c).forEach(d=>d.onTransaction(f.payload))}),c.autostart&&c.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${c.getName()}`),c.connect(b))}))},[b,C,s,R]);const L=async c=>{var m;if(((m=c.content[0])==null?void 0:m.type)!=="text")throw new Error("Only text messages are supported");const f=c.content[0].text;w(h=>[...h,{role:"user",type:"text",text:f}]),u(!0);const d=C.sort((h,S)=>S.getPriority()-h.getPriority()).find(h=>h.status==="connected"),g=[];if(c.attachments)for(const h of c.attachments)h.contentType.startsWith("image/")&&h.file&&g.push({role:"user",image:{contentType:h.contentType,content:await Z(h.file)},text:"",type:"text"});c.content&&g.push({role:"user",text:c.content[0].text,type:"text"}),s==null||s.debug("Sending message:",g),await(d==null?void 0:d.sendPacket({type:"request",payload:g})),u(!1)},F=p.useCallback(()=>(u(!1),w([]),E("new"),Promise.resolve()),[]),_=p.useCallback(()=>Promise.resolve(),[]),J=p.useCallback(()=>y,[y]),q=A.useExternalStoreRuntime({isRunning:l,messages:y,convertMessage:V,onNew:L,onCancel:F,onReload:_,adapters:{attachments:new A.CompositeAttachmentAdapter([new A.SimpleImageAttachmentAdapter])}});return v.jsx(x.Provider,{value:{protocols:C,protocolsStatus:R,getMessages:J},children:v.jsx(A.AssistantRuntimeProvider,{runtime:q,children:n})})}function te({children:o,...t}){return v.jsx(ee,{...t,children:o})}function se(){const o=p.useContext(x);if(!o)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return o}function U(o){const t=p.useContext(x);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(n=>n.getName()===o);if(!e)return null;const s=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),sendPacket:e.sendPacket.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addPacketListener:e.addPacketListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:s||e.status}}function ne(){const o=p.useContext(x);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 oe(){return U("webrtc")}function ie(){const o=p.useContext(x);if(!o)throw new Error("usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider");return o.getMessages()}class ae{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=ae;exports.PersonaProtocolBase=k;exports.PersonaRESTProtocol=$;exports.PersonaRuntimeProvider=te;exports.PersonaTransactionProtocol=D;exports.PersonaWebRTCProtocol=I;exports.PersonaWebSocketProtocol=N;exports.usePersonaRuntime=se;exports.usePersonaRuntimeEndpoint=ne;exports.usePersonaRuntimeMessages=ie;exports.usePersonaRuntimeProtocol=U;exports.usePersonaRuntimeWebRTCProtocol=oe;
11
+ ![image](https://persona.applica.guru/api/files/${h.imageUrl})`);const g={type:"reasoning",text:y,role:"assistant",finishReason:"stop"};w(d=>_([...d,{...g,protocol:c.getName()}]))}else p.type==="transaction"&&P.filter(h=>h!==c).forEach(h=>h.onTransaction(p.payload))}),c.autostart&&c.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${c.getName()}`),c.connect(C))}))},[C,P,s,S]);const J=async c=>{var g;if(((g=c.content[0])==null?void 0:g.type)!=="text")throw new Error("Only text messages are supported");const p=c.content[0].text;w(d=>[...d,{role:"user",type:"text",text:p}]),u(!0);const h=P.sort((d,k)=>k.getPriority()-d.getPriority()).find(d=>d.status==="connected"),y=[];if(c.attachments)for(const d of c.attachments)d.contentType.startsWith("image/")&&d.file&&y.push({role:"user",image:{contentType:d.contentType,content:await ne(d.file)},text:"",type:"text"});c.content&&y.push({role:"user",text:c.content[0].text,type:"text"}),s==null||s.debug("Sending message:",y),await(h==null?void 0:h.sendPacket({type:"request",payload:y})),u(!1)},K=f.useCallback(()=>(u(!1),w([]),E("new"),Promise.resolve()),[]),B=f.useCallback(()=>Promise.resolve(),[]),V=f.useCallback(()=>m,[m]),Y=v.useExternalStoreRuntime({isRunning:l,messages:m,convertMessage:Z,onNew:J,onCancel:K,onReload:B,adapters:{attachments:new v.CompositeAttachmentAdapter([new v.SimpleImageAttachmentAdapter])}});return N.jsx(T.Provider,{value:{protocols:P,protocolsStatus:S,getMessages:V},children:N.jsx(v.AssistantRuntimeProvider,{runtime:Y,children:n})})}function ae({children:o,...t}){return N.jsx(oe,{...t,children:o})}function re(){const o=f.useContext(T);if(!o)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return o}function U(o){const t=f.useContext(T);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(n=>n.getName()===o);if(!e)return null;const s=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),sendPacket:e.sendPacket.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addPacketListener:e.addPacketListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:s||e.status}}function ie(){const o=f.useContext(T);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 ce(){return U("webrtc")}function le(){const o=f.useContext(T);if(!o)throw new Error("usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider");return o.getMessages()}class ue{constructor(){i(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)}}function b(o,t,e){return{type:o,description:t,...e}}function D(o){const t=Object.entries(o.parameters).filter(([e,s])=>s.required).map(([e])=>e);return{type:"local",name:o.name,description:o.description,config:{timeout:o.timeout||60,parameters:{type:"object",title:o.title||`${o.name} parameters`,required:t,properties:o.parameters},output:{type:"object",title:`${o.name} output`,properties:o.output}}}}function $(o){return{schema:D(o),implementation:o.implementation}}function L(o,t,e,s,n,a){const r={name:o,description:t,title:a==null?void 0:a.title,timeout:a==null?void 0:a.timeout,parameters:s,output:n,implementation:e};return $(r)}const he=L("sum","Sum two numbers",function(t,e){return{result:t+e}},{a:b("number","First number to sum",{required:!0}),b:b("number","Second number to sum",{required:!0})},{result:b("number","Sum of two numbers")}),de=$({name:"navigate_to",description:"Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that",title:"Sum two numbers",timeout:60,parameters:{a:b("number","First number to sum"),b:b("number","Seconth number to sum")},output:{result:b("number","Sum of two numbers")},implementation:function(t,e){return{result:t+e}}});function me(o){const t=[],e={};return o.forEach(s=>{const{schema:n,implementation:a}=$(s);t.push(n),e[s.name]=a}),{schemas:t,implementations:e}}function pe(o,t){const{required:e,properties:s}=t.config.parameters;for(const n of e)if(!(n in o))throw new Error(`Missing required parameter: ${n}`);for(const[n,a]of Object.entries(o)){const r=s[n];if(r){if(r.type==="number"&&typeof a!="number")throw new Error(`Parameter ${n} should be a number`);if(r.type==="string"&&typeof a!="string")throw new Error(`Parameter ${n} should be a string`);if(r.type==="boolean"&&typeof a!="boolean")throw new Error(`Parameter ${n} should be a boolean`)}}return!0}exports.PersonaConsoleLogger=ue;exports.PersonaProtocolBase=R;exports.PersonaRESTProtocol=I;exports.PersonaRuntimeProvider=ae;exports.PersonaTransactionProtocol=z;exports.PersonaWebRTCProtocol=O;exports.PersonaWebSocketProtocol=q;exports.createParameter=b;exports.createTool=$;exports.createToolFromFunction=L;exports.createToolRegistry=me;exports.generateToolSchema=D;exports.navigateToToolExample=de;exports.sumTool=he;exports.usePersonaRuntime=re;exports.usePersonaRuntimeEndpoint=ie;exports.usePersonaRuntimeMessages=le;exports.usePersonaRuntimeProtocol=U;exports.usePersonaRuntimeWebRTCProtocol=ce;exports.validateToolParameters=pe;
12
12
  //# 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 PersonaPacket,\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 addPacketListener(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 notifyPacket(message: PersonaPacket): Promise<void> {\n this.messageCallbacks.forEach((callback) => callback(message));\n }\n public async notifyPackets(messages: PersonaPacket[]): 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 sendPacket(packet: PersonaPacket): Promise<void>;\n\n public onTransaction(_: PersonaTransaction) {}\n}\n\nexport { PersonaProtocolBase };\n","import { PersonaProtocolBase } from './base';\nimport {\n PersonaResponse,\n Session,\n ProtocolStatus,\n PersonaProtocolBaseConfig,\n PersonaMessage,\n PersonaPacket,\n PersonaCommand,\n} 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 context: Record<string, any> = {};\n\n constructor(config: PersonaRESTProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'rest';\n }\n\n public getPriority(): number {\n return 100;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async sendPacket(packet: PersonaPacket): Promise<void> {\n const { apiUrl, apiKey, agentId } = this.config;\n const sessionId = this.session ?? 'new';\n if (packet.type === 'command' && (packet?.payload as PersonaCommand)?.command == 'set_initial_context') {\n this.context = (packet?.payload as PersonaCommand)?.arguments;\n return;\n }\n const input = packet.payload as PersonaMessage;\n const response = await fetch(`${apiUrl}/sessions/${sessionId}/messages`, {\n body: JSON.stringify({ agentId, userMessage: input, initial_context: this.context }),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-persona-apikey': apiKey,\n },\n });\n const personaResponse = (await response.json()) as PersonaResponse;\n this.notifyPackets(\n personaResponse.response.messages.map((payload) => ({\n type: 'message',\n payload,\n })),\n );\n }\n}\n\nexport { PersonaRESTProtocol };\nexport type { PersonaRESTProtocolConfig };\n","import { PersonaPacket, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\nimport { PersonaProtocolBase } from './base';\n\ntype PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {\n webSocketUrl: string;\n};\n\nclass PersonaWebSocketProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaWebSocketProtocolConfig;\n webSocket: WebSocket | null;\n\n constructor(config: PersonaWebSocketProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n this.session = null;\n this.webSocket = null;\n }\n\n public getName(): string {\n return 'websocket';\n }\n\n public getPriority(): number {\n return 500;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.config.logger?.debug('Syncing session with WebSocket protocol:', session);\n this.session = session;\n if (this.webSocket && this.status === 'connected') {\n this.disconnect();\n this.connect(session);\n }\n }\n\n public connect(session?: Session): Promise<Session> {\n if (this.webSocket !== null && this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n\n const sid = session || this.session || 'new';\n\n this.config.logger?.debug('Connecting to WebSocket with sessionId:', sid);\n\n const apiKey = encodeURIComponent(this.config.apiKey);\n const agentId = this.config.agentId;\n const webSocketUrl = `${this.config.webSocketUrl}?sessionCode=${sid}&agentId=${agentId}&apiKey=${apiKey}`;\n this.setStatus('connecting');\n this.webSocket = new WebSocket(webSocketUrl);\n this.webSocket.addEventListener('open', () => {\n this.setStatus('connected');\n });\n this.webSocket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data) as PersonaPacket;\n this.notifyPacket(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 sendPacket(packet: PersonaPacket): Promise<void> {\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.send(JSON.stringify(packet));\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 { PersonaPacket, 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 sendPacket(packet: PersonaPacket): 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(packet));\n this.config.logger?.info('Sent message:', packet);\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 PersonaPacket;\n this.notifyPacket(data);\n });\n }\n\n public getName(): string {\n return 'webrtc';\n }\n public getPriority(): number {\n return 1000;\n }\n\n public async syncSession(session: Session): Promise<void> {\n super.syncSession(session);\n if (this.status === 'connected') {\n await this.disconnect();\n await this.connect(session);\n }\n }\n\n public async connect(session?: Session): Promise<Session> {\n if (this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n this.session = session || this.session || 'new';\n this.setStatus('connecting');\n\n this.config.logger?.debug('Connecting to WebRTC with sessionId:', this.session);\n await this.webRTCClient.connect(this.session);\n this.setStatus('connected');\n\n await this.webRTCClient.createDataChannel();\n\n return this.session;\n }\n\n public async disconnect(): Promise<void> {\n if (this.status === 'disconnected') {\n this.config.logger?.warn('Already disconnected');\n return Promise.resolve();\n }\n\n await this.webRTCClient.disconnect();\n\n this.setStatus('disconnected');\n this.config?.logger?.debug('Disconnected from WebRTC');\n }\n\n public sendPacket(packet: PersonaPacket): Promise<void> {\n if (this.status !== 'connected') {\n return Promise.reject(new Error('Not connected'));\n }\n\n this.webRTCClient.sendPacket(packet);\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 PersonaPacket,\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 sendPacket(_: PersonaPacket): Promise<void> {}\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 PersonaPacket,\n PersonaProtocol,\n PersonaProtocolBaseConfig,\n PersonaReasoning,\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 getMessages: () => PersonaMessage[];\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 baseUrl,\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' : baseUrl || 'persona.applica.guru/api';\n const baseEndpointProtocol = dev ? 'http' : 'https';\n const baseWebSocketProtocol = dev ? 'ws' : 'wss';\n let availableProtocols = Object.keys(_protocols)\n .map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (restConfig === true) {\n return new PersonaRESTProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof restConfig === 'object' && restConfig !== null) {\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n } else {\n return null;\n }\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (webrtcConfig === true) {\n return new PersonaWebRTCProtocol({\n webrtcUrl: `${baseWebSocketProtocol}://${baseEndpoint}/webrtc`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof webrtcConfig === 'object' && webrtcConfig !== null) {\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n } else {\n return null;\n }\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (websocketConfig === true) {\n return new PersonaWebSocketProtocol({\n webSocketUrl: `${baseWebSocketProtocol}://${baseEndpoint}/websocket`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof websocketConfig === 'object' && websocketConfig !== null) {\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n } else {\n return null;\n }\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n })\n .filter((protocol) => protocol !== null) as PersonaProtocol[];\n\n if (config.tools) {\n availableProtocols.push(\n new PersonaTransactionProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n onTransaction: async (transaction: PersonaPersistableTransaction) => {\n await transaction.invoke(config.tools!);\n },\n logger,\n }),\n );\n }\n return availableProtocols;\n }\n throw new Error('Invalid protocols configuration');\n }, []);\n\n useEffect(() => {\n if (didMount.current) return;\n\n didMount.current = true;\n logger?.debug(\n 'Initializing protocols: ',\n protocols.map((protocol) => protocol.getName()),\n );\n protocols.forEach((protocol) => {\n protocol.setSession(session);\n protocol.clearListeners();\n protocol.addStatusChangeListener((status: ProtocolStatus) => {\n logger?.debug(`${protocol.getName()} has notified new status: ${status}`);\n protocolsStatus.set(protocol.getName(), status);\n if (status === 'connected' && config.context) {\n protocol.sendPacket({\n type: 'command',\n payload: {\n command: 'set_initial_context',\n arguments: config.context,\n },\n });\n }\n setProtocolsStatus(new Map(protocolsStatus));\n });\n protocol.addPacketListener((message: PersonaPacket) => {\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 === 'reasoning') {\n const personaReasoning = message.payload as PersonaReasoning;\n\n let text = personaReasoning.thought;\n if (personaReasoning.imageUrl) {\n // add markdown image\n text += `\\n\\n![image](https://persona.applica.guru/api/files/${personaReasoning.imageUrl})`;\n }\n const personaMessage: PersonaMessage = { type: 'reasoning', text: text, role: 'assistant', finishReason: 'stop' };\n\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?.sendPacket({ type: 'request', payload: 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 getMessages = useCallback(() => {\n return messages;\n }, [messages]);\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, getMessages }}>\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 sendPacket: protocolInstance.sendPacket.bind(protocolInstance),\n setSession: protocolInstance.setSession.bind(protocolInstance),\n addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),\n addPacketListener: protocolInstance.addPacketListener.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\nfunction usePersonaRuntimeMessages(): PersonaMessage[] {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider');\n }\n return context.getMessages();\n}\n\nexport {\n PersonaRuntimeProvider,\n usePersonaRuntimeEndpoint,\n usePersonaRuntime,\n usePersonaRuntimeProtocol,\n usePersonaRuntimeWebRTCProtocol,\n usePersonaRuntimeMessages,\n};\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","packet","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","baseUrl","_protocols","logger","children","defaultSession","isRunning","setIsRunning","useState","setMessages","setSession","protocolsStatus","setProtocolsStatus","didMount","useRef","protocols","useMemo","baseEndpoint","baseEndpointProtocol","baseWebSocketProtocol","availableProtocols","restConfig","webrtcConfig","websocketConfig","protocol","useEffect","personaMessage","currentConversation","personaReasoning","text","p","onNew","content","attachment","onCancel","useCallback","onReload","getMessages","runtime","useExternalStoreRuntime","CompositeAttachmentAdapter","SimpleImageAttachmentAdapter","jsx","AssistantRuntimeProvider","PersonaRuntimeProvider","usePersonaRuntime","context","useContext","usePersonaRuntimeProtocol","protocolInstance","usePersonaRuntimeEndpoint","usePersonaRuntimeWebRTCProtocol","usePersonaRuntimeMessages","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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AAG,KAAK,MAAM,MAAMnI,CAAO,GAAI,GAAGmI,CAAI,CAAA,CAGtD,MAAMnI,KAAoBmI,EAAiB,CACjC,QAAA,MAAM,GAAG,KAAK,MAAM,MAAMnI,CAAO,GAAI,GAAGmI,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","../src/tools.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 PersonaPacket,\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 addPacketListener(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 notifyPacket(message: PersonaPacket): Promise<void> {\n this.messageCallbacks.forEach((callback) => callback(message));\n }\n public async notifyPackets(messages: PersonaPacket[]): 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 sendPacket(packet: PersonaPacket): Promise<void>;\n\n public onTransaction(_: PersonaTransaction) {}\n}\n\nexport { PersonaProtocolBase };\n","import { PersonaProtocolBase } from './base';\nimport {\n PersonaResponse,\n Session,\n ProtocolStatus,\n PersonaProtocolBaseConfig,\n PersonaMessage,\n PersonaPacket,\n PersonaCommand,\n} from '../types';\nimport { ToolInstance } from '../tools';\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 context: Record<string, any> = {};\n tools: ToolInstance[] = [];\n\n constructor(config: PersonaRESTProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'rest';\n }\n\n public getPriority(): number {\n return 100;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async sendPacket(packet: PersonaPacket): Promise<void> {\n const { apiUrl, apiKey, agentId } = this.config;\n const sessionId = this.session ?? 'new';\n if (packet.type === 'command' && (packet?.payload as PersonaCommand)?.command == 'set_initial_context') {\n this.context = (packet?.payload as PersonaCommand)?.arguments;\n return;\n } else if (packet.type === 'command' && (packet?.payload as PersonaCommand)?.command == 'set_local_tools') {\n this.notifyPacket({\n type: 'message',\n payload: {\n type: 'text',\n role: 'assistant',\n text: 'Local tools with rest protocol are not supported.',\n },\n });\n return;\n }\n const input = packet.payload as PersonaMessage;\n try {\n const response = await fetch(`${apiUrl}/sessions/${sessionId}/messages`, {\n body: JSON.stringify({ agentId, userMessage: input, initialContext: this.context, tools: this.tools }),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-persona-apikey': apiKey,\n },\n });\n const personaResponse = (await response.json()) as PersonaResponse;\n this.notifyPackets(\n personaResponse.response.messages.map((payload) => ({\n type: 'message',\n payload,\n })),\n );\n } catch (error) {\n this.notifyPacket({\n type: 'message',\n payload: {\n role: 'assistant',\n type: 'text',\n text: 'An error occurred while processing your request. Please try again later.',\n },\n });\n this.config.logger?.error('Error sending packet:', error);\n }\n }\n}\n\nexport { PersonaRESTProtocol };\nexport type { PersonaRESTProtocolConfig };\n","import { PersonaPacket, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\nimport { PersonaProtocolBase } from './base';\n\ntype PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {\n webSocketUrl: string;\n};\n\nclass PersonaWebSocketProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaWebSocketProtocolConfig;\n webSocket: WebSocket | null;\n\n constructor(config: PersonaWebSocketProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n this.session = null;\n this.webSocket = null;\n }\n\n public getName(): string {\n return 'websocket';\n }\n\n public getPriority(): number {\n return 500;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.config.logger?.debug('Syncing session with WebSocket protocol:', session);\n this.session = session;\n if (this.webSocket && this.status === 'connected') {\n this.disconnect();\n this.connect(session);\n }\n }\n\n public connect(session?: Session): Promise<Session> {\n if (this.webSocket !== null && this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n\n const sid = session || this.session || 'new';\n\n this.config.logger?.debug('Connecting to WebSocket with sessionId:', sid);\n\n const apiKey = encodeURIComponent(this.config.apiKey);\n const agentId = this.config.agentId;\n const webSocketUrl = `${this.config.webSocketUrl}?sessionCode=${sid}&agentId=${agentId}&apiKey=${apiKey}`;\n this.setStatus('connecting');\n this.webSocket = new WebSocket(webSocketUrl);\n this.webSocket.addEventListener('open', () => {\n this.setStatus('connected');\n });\n this.webSocket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data) as PersonaPacket;\n this.notifyPacket(data);\n });\n this.webSocket.addEventListener('close', (event: CloseEvent) => {\n this.setStatus('disconnected');\n this.webSocket = null;\n if (event.code !== 1000) {\n this.notifyPacket({\n type: 'message',\n payload: {\n role: 'assistant',\n type: 'text',\n text: 'Oops! The connection to the server was lost. Please try again later.',\n },\n });\n this.config.logger?.warn('WebSocket connection closed');\n }\n });\n\n this.webSocket.addEventListener('error', () => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.error('WebSocket connection error');\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 sendPacket(packet: PersonaPacket): Promise<void> {\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.send(JSON.stringify(packet));\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 { PersonaPacket, 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 PersonaWebRTCErrorCallback = (error: string) => 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 private errorCallbacks: PersonaWebRTCErrorCallback[] = [];\n private queuedMessages: PersonaPacket[] = [];\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 channel.onopen = () => {\n while (this.queuedMessages.length > 0) {\n const packet = this.queuedMessages.shift();\n if (packet) {\n channel.send(JSON.stringify(packet));\n this.config.logger?.info('Sent queued message:', packet);\n }\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 = (event: CloseEvent) => {\n if (event.code !== 1000) {\n this.errorCallbacks.forEach((callback) => {\n callback('Oops! The connection to the server was lost. Please try again later.');\n });\n }\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 addErrorCallback(callback: PersonaWebRTCErrorCallback): void {\n this.errorCallbacks.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 = () => {\n this.config.logger?.info('Data channel opened');\n while (this.queuedMessages.length > 0) {\n const packet = this.queuedMessages.shift();\n if (packet) {\n this.dataChannel!.send(JSON.stringify(packet));\n this.config.logger?.info('Sent queued message:', packet);\n }\n }\n };\n this.dataChannel.onmessage = (msg: MessageEvent) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n }\n\n public sendPacket(packet: PersonaPacket): void {\n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n this.queuedMessages.push(packet);\n return;\n }\n\n this.dataChannel.send(JSON.stringify(packet));\n this.config.logger?.info('Sent message:', packet);\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 PersonaPacket;\n this.notifyPacket(data);\n });\n this.webRTCClient.addErrorCallback((error: string) => {\n this.config.logger?.error('WebRTC error:', error);\n this.notifyPacket({\n type: 'message',\n payload: {\n type: 'text',\n role: 'assistant',\n text: error,\n },\n });\n });\n }\n\n public getName(): string {\n return 'webrtc';\n }\n public getPriority(): number {\n return 1000;\n }\n\n public async syncSession(session: Session): Promise<void> {\n super.syncSession(session);\n if (this.status === 'connected') {\n await this.disconnect();\n await this.connect(session);\n }\n }\n\n public async connect(session?: Session): Promise<Session> {\n if (this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n this.session = session || this.session || 'new';\n this.setStatus('connecting');\n\n this.config.logger?.debug('Connecting to WebRTC with sessionId:', this.session);\n await this.webRTCClient.connect(this.session);\n this.setStatus('connected');\n\n await this.webRTCClient.createDataChannel();\n\n return this.session;\n }\n\n public async disconnect(): Promise<void> {\n if (this.status === 'disconnected') {\n this.config.logger?.warn('Already disconnected');\n return Promise.resolve();\n }\n\n await this.webRTCClient.disconnect();\n\n this.setStatus('disconnected');\n this.config?.logger?.debug('Disconnected from WebRTC');\n }\n\n public sendPacket(packet: PersonaPacket): Promise<void> {\n if (this.status !== 'connected') {\n return Promise.reject(new Error('Not connected'));\n }\n\n this.webRTCClient.sendPacket(packet);\n return Promise.resolve();\n }\n}\n\nexport { PersonaWebRTCProtocol };\nexport type { PersonaWebRTCProtocolConfig, AudioVisualizerCallback, AudioAnalysisData };\n","import { PersonaProtocolBase } from './base';\nimport { Session, ProtocolStatus, PersonaProtocolBaseConfig, PersonaTransaction, FunctionCall, PersonaPacket } from '../types';\nimport { ToolInstance } from '../tools';\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: any[]) => void | Record<string, any> | Promise<void | Record<string, any>>;\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.apply(null, Object.values(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 tools: PersonaTools | ToolInstance[];\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 private _tools: PersonaTools;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n if (Array.isArray(config.tools)) {\n this._tools = {};\n for (const tool of config.tools as ToolInstance[]) {\n if (tool.schema && tool.implementation) {\n this._tools[tool.schema.name] = tool.implementation;\n }\n }\n } else {\n this._tools = config.tools as PersonaTools;\n }\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 sendPacket(_: PersonaPacket): Promise<void> {}\n\n public onTransaction(transaction: PersonaTransaction): void {\n console.log('transaction received:', transaction);\n const manager = new PersonaTransactionsManager(this.config);\n const persistable = new PersonaPersistableTransaction(transaction, manager);\n if (this.config.onTransaction) {\n this.config.onTransaction(persistable);\n } else {\n persistable.invoke(this._tools);\n }\n }\n\n public getTools(): PersonaTools {\n return this._tools;\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 PersonaPacket,\n PersonaProtocol,\n PersonaProtocolBaseConfig,\n PersonaReasoning,\n PersonaResponse,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n} from './types';\nimport { parseMessages, convertMessage } from './messages';\nimport {\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 getMessages: () => PersonaMessage[];\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 baseUrl,\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' : baseUrl || 'persona.applica.guru/api';\n const baseEndpointProtocol = dev ? 'http' : 'https';\n const baseWebSocketProtocol = dev ? 'ws' : 'wss';\n let availableProtocols = Object.keys(_protocols)\n .map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (restConfig === true) {\n return new PersonaRESTProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof restConfig === 'object' && restConfig !== null) {\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n } else {\n return null;\n }\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (webrtcConfig === true) {\n return new PersonaWebRTCProtocol({\n webrtcUrl: `${baseWebSocketProtocol}://${baseEndpoint}/webrtc`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof webrtcConfig === 'object' && webrtcConfig !== null) {\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n } else {\n return null;\n }\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (websocketConfig === true) {\n return new PersonaWebSocketProtocol({\n webSocketUrl: `${baseWebSocketProtocol}://${baseEndpoint}/websocket`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof websocketConfig === 'object' && websocketConfig !== null) {\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n } else {\n return null;\n }\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n })\n .filter((protocol) => protocol !== null) as PersonaProtocol[];\n\n if (config.tools) {\n availableProtocols.push(\n new PersonaTransactionProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n tools: config.tools, // Pass raw tools\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 if (status === 'connected') {\n if (config.context) {\n protocol.sendPacket({\n type: 'command',\n payload: {\n command: 'set_initial_context',\n arguments: config.context,\n },\n });\n }\n if (config.tools && Array.isArray(config.tools)) {\n protocol.sendPacket({\n type: 'command',\n payload: {\n command: 'set_local_tools',\n arguments: {\n tools: config.tools.map((tool) => tool.schema),\n },\n },\n });\n }\n }\n setProtocolsStatus(new Map(protocolsStatus));\n });\n protocol.addPacketListener((message: PersonaPacket) => {\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 === 'reasoning') {\n const personaReasoning = message.payload as PersonaReasoning;\n\n let text = personaReasoning.thought;\n if (personaReasoning.imageUrl) {\n // add markdown image\n text += `\\n\\n![image](https://persona.applica.guru/api/files/${personaReasoning.imageUrl})`;\n }\n const personaMessage: PersonaMessage = { type: 'reasoning', text: text, role: 'assistant', finishReason: 'stop' };\n\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?.sendPacket({ type: 'request', payload: 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 getMessages = useCallback(() => {\n return messages;\n }, [messages]);\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, getMessages }}>\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 sendPacket: protocolInstance.sendPacket.bind(protocolInstance),\n setSession: protocolInstance.setSession.bind(protocolInstance),\n addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),\n addPacketListener: protocolInstance.addPacketListener.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\nfunction usePersonaRuntimeMessages(): PersonaMessage[] {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider');\n }\n return context.getMessages();\n}\n\nexport {\n PersonaRuntimeProvider,\n usePersonaRuntimeEndpoint,\n usePersonaRuntime,\n usePersonaRuntimeProtocol,\n usePersonaRuntimeWebRTCProtocol,\n usePersonaRuntimeMessages,\n};\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","export type ToolParameterType = 'string' | 'number' | 'boolean' | 'object' | 'array';\n\nexport interface ToolParameter {\n type: ToolParameterType;\n description: string;\n required?: boolean;\n properties?: Record<string, ToolParameter>;\n items?: ToolParameter;\n}\n\nexport interface ToolSchema {\n type: 'local';\n name: string;\n description: string;\n config: {\n timeout: number;\n parameters: {\n type: 'object';\n title: string;\n required: string[];\n properties: Record<string, ToolParameter>;\n };\n output: {\n type: 'object';\n title: string;\n properties: Record<string, ToolParameter>;\n };\n };\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n title?: string;\n timeout?: number;\n parameters: Record<string, ToolParameter>;\n output: Record<string, ToolParameter>;\n implementation: (...args: any[]) => any;\n}\n\n/**\n * Create a tool parameter definition\n */\nexport function createParameter(\n type: ToolParameterType,\n description: string,\n options?: {\n required?: boolean;\n properties?: Record<string, ToolParameter>;\n items?: ToolParameter;\n },\n): ToolParameter {\n return {\n type,\n description,\n ...options,\n };\n}\n\n/**\n * Generate a tool schema from a tool definition\n */\nexport function generateToolSchema(definition: ToolDefinition): ToolSchema {\n const requiredParams = Object.entries(definition.parameters)\n .filter(([_, param]) => param.required)\n .map(([name]) => name);\n\n return {\n type: 'local',\n name: definition.name,\n description: definition.description,\n config: {\n timeout: definition.timeout || 60,\n parameters: {\n type: 'object',\n title: definition.title || `${definition.name} parameters`,\n required: requiredParams,\n properties: definition.parameters,\n },\n output: {\n type: 'object',\n title: `${definition.name} output`,\n properties: definition.output,\n },\n },\n };\n}\n\nexport type ToolInstance = { schema: ToolSchema; implementation: (...args: any[]) => any };\n\n/**\n * Create a complete tool definition with schema and implementation\n */\nexport function createTool(definition: ToolDefinition): ToolInstance {\n return {\n schema: generateToolSchema(definition),\n implementation: definition.implementation,\n };\n}\n\n/**\n * Extract function signature and generate schema from a JavaScript function\n * This is a utility to help convert existing functions to tool schemas\n */\nexport function createToolFromFunction(\n name: string,\n description: string,\n fn: (...args: any[]) => any,\n parameterTypes: Record<string, ToolParameter>,\n outputTypes: Record<string, ToolParameter>,\n options?: {\n title?: string;\n timeout?: number;\n },\n): ToolInstance {\n const definition: ToolDefinition = {\n name,\n description,\n title: options?.title,\n timeout: options?.timeout,\n parameters: parameterTypes,\n output: outputTypes,\n implementation: fn,\n };\n\n return createTool(definition);\n}\n\n// Example usage for the sum function you provided:\nexport const sumTool = createToolFromFunction(\n 'sum',\n 'Sum two numbers',\n function sum(a: number, b: number) {\n const result = a + b;\n return { result };\n },\n {\n a: createParameter('number', 'First number to sum', { required: true }),\n b: createParameter('number', 'Second number to sum', { required: true }),\n },\n {\n result: createParameter('number', 'Sum of two numbers'),\n },\n);\n\n// Example for the navigate_to function as shown in the user's request:\nexport const navigateToToolExample = createTool({\n name: 'navigate_to',\n description: 'Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that',\n title: 'Sum two numbers', // As per the user's example\n timeout: 60,\n parameters: {\n a: createParameter('number', 'First number to sum'),\n b: createParameter('number', 'Seconth number to sum'), // Keeping the typo as in the original\n },\n output: {\n result: createParameter('number', 'Sum of two numbers'),\n },\n implementation: function navigateTo(a: number, b: number) {\n // This is just an example - you would implement actual navigation logic here\n const result = a + b;\n return { result };\n },\n});\n\n// Helper function to create multiple tools at once\nexport function createToolRegistry(tools: ToolDefinition[]): {\n schemas: ToolSchema[];\n implementations: Record<string, (...args: any[]) => any>;\n} {\n const schemas: ToolSchema[] = [];\n const implementations: Record<string, (...args: any[]) => any> = {};\n\n tools.forEach((tool) => {\n const { schema, implementation } = createTool(tool);\n schemas.push(schema);\n implementations[tool.name] = implementation;\n });\n\n return { schemas, implementations };\n}\n\n// Utility to validate tool parameters at runtime\nexport function validateToolParameters(parameters: Record<string, any>, schema: ToolSchema): boolean {\n const { required, properties } = schema.config.parameters;\n\n // Check required parameters\n for (const requiredParam of required) {\n if (!(requiredParam in parameters)) {\n throw new Error(`Missing required parameter: ${requiredParam}`);\n }\n }\n\n // Type checking (basic)\n for (const [paramName, paramValue] of Object.entries(parameters)) {\n const paramSchema = properties[paramName];\n if (paramSchema) {\n if (paramSchema.type === 'number' && typeof paramValue !== 'number') {\n throw new Error(`Parameter ${paramName} should be a number`);\n }\n if (paramSchema.type === 'string' && typeof paramValue !== 'string') {\n throw new Error(`Parameter ${paramName} should be a string`);\n }\n if (paramSchema.type === 'boolean' && typeof paramValue !== 'boolean') {\n throw new Error(`Parameter ${paramName} should be a boolean`);\n }\n }\n }\n\n return true;\n}\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","packet","apiUrl","apiKey","agentId","sessionId","_c","input","personaResponse","payload","error","_d","PersonaWebSocketProtocol","sid","webSocketUrl","event","data","PersonaWebRTCClient","err","track","remoteAudio","e","channel","msg","url","offer","metadata","offerMessage","label","localSource","remoteSource","loop","localArray","remoteArray","localAmp","a","b","remoteAmp","PersonaWebRTCProtocol","PersonaTransactionsManager","transaction","request","PersonaPersistableTransaction","manager","tools","functionCall","functionName","functionArgs","tool","result","output","PersonaTransactionProtocol","persistable","PersonaRuntimeContext","createContext","fileToBase64","resolve","reject","reader","base64WithoutPrefix","PersonaRuntimeProviderInner","dev","baseUrl","_protocols","logger","children","defaultSession","isRunning","setIsRunning","useState","setMessages","setSession","protocolsStatus","setProtocolsStatus","didMount","useRef","protocols","useMemo","baseEndpoint","baseEndpointProtocol","baseWebSocketProtocol","availableProtocols","restConfig","webrtcConfig","websocketConfig","protocol","useEffect","personaMessage","currentConversation","personaReasoning","text","p","onNew","content","attachment","onCancel","useCallback","onReload","getMessages","runtime","useExternalStoreRuntime","CompositeAttachmentAdapter","SimpleImageAttachmentAdapter","jsx","AssistantRuntimeProvider","PersonaRuntimeProvider","usePersonaRuntime","context","useContext","usePersonaRuntimeProtocol","protocolInstance","usePersonaRuntimeEndpoint","usePersonaRuntimeWebRTCProtocol","usePersonaRuntimeMessages","PersonaConsoleLogger","args","createParameter","description","options","generateToolSchema","definition","requiredParams","param","name","createTool","createToolFromFunction","fn","parameterTypes","outputTypes","sumTool","navigateToToolExample","createToolRegistry","schemas","implementations","schema","implementation","validateToolParameters","parameters","required","properties","requiredParam","paramName","paramValue","paramSchema"],"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,IAAgB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