@applica-software-guru/persona-sdk 0.1.46 → 0.1.48
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 +217 -0
- package/dist/bundle.cjs.js +2 -2
- package/dist/bundle.cjs.js.map +1 -1
- package/dist/bundle.es.js +304 -187
- package/dist/bundle.es.js.map +1 -1
- package/dist/bundle.iife.js +2 -2
- package/dist/bundle.iife.js.map +1 -1
- package/dist/bundle.umd.js +2 -2
- package/dist/bundle.umd.js.map +1 -1
- package/dist/messages.d.ts.map +1 -1
- package/dist/protocol/base.d.ts +4 -3
- package/dist/protocol/base.d.ts.map +1 -1
- package/dist/protocol/index.d.ts +1 -0
- package/dist/protocol/index.d.ts.map +1 -1
- package/dist/protocol/rest.d.ts.map +1 -1
- package/dist/protocol/transaction.d.ts +50 -0
- package/dist/protocol/transaction.d.ts.map +1 -0
- package/dist/protocol/webrtc.d.ts.map +1 -1
- package/dist/protocol/websocket.d.ts.map +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/types.d.ts +36 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/playground/src/chat.tsx +10 -1
- package/src/messages.ts +3 -0
- package/src/protocol/base.ts +14 -3
- package/src/protocol/index.ts +1 -0
- package/src/protocol/rest.ts +6 -1
- package/src/protocol/transaction.ts +154 -0
- package/src/protocol/webrtc.ts +3 -6
- package/src/protocol/websocket.ts +3 -9
- package/src/runtime.tsx +28 -3
- package/src/types.ts +42 -2
package/README.md
CHANGED
|
@@ -218,6 +218,223 @@ class CustomLogger implements PersonaLogger {
|
|
|
218
218
|
|
|
219
219
|
---
|
|
220
220
|
|
|
221
|
+
## Transaction Protocol
|
|
222
|
+
|
|
223
|
+
The Transaction Protocol in the Persona SDK is designed to handle structured interactions between the client and the Persona API. It allows you to define and execute specific operations (tools) in response to function calls.
|
|
224
|
+
|
|
225
|
+
### How It Works
|
|
226
|
+
|
|
227
|
+
1. **Transaction Handling**: The protocol listens for incoming transactions and invokes the appropriate tool based on the function call.
|
|
228
|
+
2. **Session Management**: It shares the same session as other protocols, ensuring consistency.
|
|
229
|
+
3. **Custom Logic**: You can define custom tools to handle specific function calls.
|
|
230
|
+
|
|
231
|
+
### Usage Example
|
|
232
|
+
|
|
233
|
+
To enable the Transaction Protocol, include it in the `protocols` configuration of the `PersonaRuntimeProvider`:
|
|
234
|
+
|
|
235
|
+
```tsx
|
|
236
|
+
<PersonaRuntimeProvider
|
|
237
|
+
dev
|
|
238
|
+
logger={logger}
|
|
239
|
+
protocols={{
|
|
240
|
+
transaction: async (transaction) => {
|
|
241
|
+
await transaction.invoke({
|
|
242
|
+
get_user_agent: () => navigator.userAgent || 'unknown',
|
|
243
|
+
get_client_date: () => ({ date: new Date().toISOString() }),
|
|
244
|
+
});
|
|
245
|
+
},
|
|
246
|
+
}}
|
|
247
|
+
session="your-session-id"
|
|
248
|
+
apiKey="your-api-key"
|
|
249
|
+
agentId="your-agent-id"
|
|
250
|
+
>
|
|
251
|
+
<YourComponent />
|
|
252
|
+
</PersonaRuntimeProvider>
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
In this example:
|
|
256
|
+
|
|
257
|
+
- The `transaction` protocol is configured with a callback function.
|
|
258
|
+
- The callback defines tools (`get_user_agent` and `get_client_date`) that the protocol can invoke.
|
|
259
|
+
|
|
260
|
+
### Using the `tools` Prop in PersonaRuntimeProvider
|
|
261
|
+
|
|
262
|
+
**⚠️ 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.
|
|
263
|
+
|
|
264
|
+
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.
|
|
265
|
+
|
|
266
|
+
#### Example Usage
|
|
267
|
+
|
|
268
|
+
Here’s how you can use the `tools` prop:
|
|
269
|
+
|
|
270
|
+
```tsx
|
|
271
|
+
<PersonaRuntimeProvider
|
|
272
|
+
dev
|
|
273
|
+
logger={logger}
|
|
274
|
+
protocols={{
|
|
275
|
+
transaction: true, // Enable the transaction protocol
|
|
276
|
+
}}
|
|
277
|
+
tools={{
|
|
278
|
+
get_user_agent: () => navigator.userAgent || 'unknown',
|
|
279
|
+
get_client_date: () => ({ date: new Date().toISOString() }),
|
|
280
|
+
}}
|
|
281
|
+
session="your-session-id"
|
|
282
|
+
apiKey="your-api-key"
|
|
283
|
+
agentId="your-agent-id"
|
|
284
|
+
>
|
|
285
|
+
<YourComponent />
|
|
286
|
+
</PersonaRuntimeProvider>
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
#### How It Works
|
|
290
|
+
|
|
291
|
+
- The `tools` prop is an object where each key is the name of a tool, and the value is the function to execute.
|
|
292
|
+
- When a transaction is received, the Transaction Protocol automatically invokes the appropriate tool based on the function call.
|
|
293
|
+
- This eliminates the need to manually handle transactions and invoke tools.
|
|
294
|
+
|
|
295
|
+
#### Benefits
|
|
296
|
+
|
|
297
|
+
1. **Simplified Code**: No need to manually handle transactions or invoke tools.
|
|
298
|
+
2. **Centralized Management**: All tools are defined in one place, making them easier to manage and update.
|
|
299
|
+
3. **Improved Readability**: The code is cleaner and more intuitive.
|
|
300
|
+
|
|
301
|
+
#### Best Practices
|
|
302
|
+
|
|
303
|
+
- Use descriptive names for tools to make them easy to identify.
|
|
304
|
+
- Ensure tools handle errors gracefully to avoid unexpected failures.
|
|
305
|
+
- Test tools thoroughly to ensure they work as expected in different scenarios.
|
|
306
|
+
- Avoid exposing sensitive data or performing unsafe operations in tools.
|
|
307
|
+
|
|
308
|
+
By using the `tools` prop, you can streamline the integration of custom tools into your application, making it easier to extend and maintain.
|
|
309
|
+
|
|
310
|
+
---
|
|
311
|
+
|
|
312
|
+
## Managing Tools
|
|
313
|
+
|
|
314
|
+
Tools are custom functions that the Transaction Protocol can invoke in response to specific function calls. They allow you to extend the SDK's functionality by defining your own operations.
|
|
315
|
+
|
|
316
|
+
### Defining Tools
|
|
317
|
+
|
|
318
|
+
Tools are defined as key-value pairs, where the key is the tool's name, and the value is the function to execute.
|
|
319
|
+
|
|
320
|
+
Example:
|
|
321
|
+
|
|
322
|
+
```typescript
|
|
323
|
+
const tools = {
|
|
324
|
+
get_user_agent: () => navigator.userAgent || 'unknown',
|
|
325
|
+
get_client_date: () => ({ date: new Date().toISOString() }),
|
|
326
|
+
};
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
### Using Tools in Transactions
|
|
330
|
+
|
|
331
|
+
When a transaction is received, the protocol matches the function call's name with the tool's name and executes the corresponding function.
|
|
332
|
+
|
|
333
|
+
Example:
|
|
334
|
+
|
|
335
|
+
```typescript
|
|
336
|
+
transaction.invoke(tools);
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
### Error Handling
|
|
340
|
+
|
|
341
|
+
If a tool is not found or an error occurs during execution, the transaction will fail. You can handle these scenarios by implementing error handling in your tools.
|
|
342
|
+
|
|
343
|
+
Example:
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
const tools = {
|
|
347
|
+
risky_tool: () => {
|
|
348
|
+
try {
|
|
349
|
+
// Perform some operation
|
|
350
|
+
return { success: true };
|
|
351
|
+
} catch (error) {
|
|
352
|
+
throw new Error('Tool execution failed');
|
|
353
|
+
}
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
---
|
|
359
|
+
|
|
360
|
+
### Best Practices
|
|
361
|
+
|
|
362
|
+
1. **Tool Naming**: Use descriptive names for tools to make them easy to identify.
|
|
363
|
+
2. **Error Handling**: Ensure tools handle errors gracefully to avoid unexpected failures.
|
|
364
|
+
3. **Testing**: Test tools thoroughly to ensure they work as expected in different scenarios.
|
|
365
|
+
4. **Security**: Avoid exposing sensitive data or performing unsafe operations in tools.
|
|
366
|
+
|
|
367
|
+
By leveraging the Transaction Protocol and tools, you can create a highly customizable and extensible integration with the Persona SDK.
|
|
368
|
+
|
|
369
|
+
---
|
|
370
|
+
|
|
371
|
+
## Advanced Transaction Handling
|
|
372
|
+
|
|
373
|
+
In addition to using the `tools` prop for automatic transaction handling, you can manage transactions manually by inspecting the function call and executing the `complete` or `fail` methods of the persistable entity passed to the transaction handler.
|
|
374
|
+
|
|
375
|
+
#### Manual Transaction Handling
|
|
376
|
+
|
|
377
|
+
When handling transactions manually, you gain full control over the transaction lifecycle. This allows you to inspect the function call, perform custom logic, and explicitly mark the transaction as complete or failed.
|
|
378
|
+
|
|
379
|
+
#### Example Usage
|
|
380
|
+
|
|
381
|
+
Here’s an example of how to handle transactions manually:
|
|
382
|
+
|
|
383
|
+
```tsx
|
|
384
|
+
<PersonaRuntimeProvider
|
|
385
|
+
dev
|
|
386
|
+
logger={logger}
|
|
387
|
+
protocols={{
|
|
388
|
+
transaction: async (transaction) => {
|
|
389
|
+
const { functionCall, persistable } = transaction;
|
|
390
|
+
|
|
391
|
+
try {
|
|
392
|
+
// Inspect the function call
|
|
393
|
+
if (functionCall.name === 'get_user_agent') {
|
|
394
|
+
const result = navigator.userAgent || 'unknown';
|
|
395
|
+
await persistable.complete(result);
|
|
396
|
+
} else if (functionCall.name === 'get_client_date') {
|
|
397
|
+
const result = { date: new Date().toISOString() };
|
|
398
|
+
await persistable.complete(result);
|
|
399
|
+
} else {
|
|
400
|
+
// Handle unknown function calls
|
|
401
|
+
throw new Error(`Unknown function call: ${functionCall.name}`);
|
|
402
|
+
}
|
|
403
|
+
} catch (error) {
|
|
404
|
+
// Mark the transaction as failed
|
|
405
|
+
await persistable.fail({ error: error.message });
|
|
406
|
+
}
|
|
407
|
+
},
|
|
408
|
+
}}
|
|
409
|
+
session="your-session-id"
|
|
410
|
+
apiKey="your-api-key"
|
|
411
|
+
agentId="your-agent-id"
|
|
412
|
+
>
|
|
413
|
+
<YourComponent />
|
|
414
|
+
</PersonaRuntimeProvider>
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
#### How It Works
|
|
418
|
+
|
|
419
|
+
1. **Inspect Function Call**: The `functionCall` object contains details about the function being invoked, such as its name and arguments.
|
|
420
|
+
2. **Custom Logic**: Based on the function call, you can perform custom logic to determine the appropriate response.
|
|
421
|
+
3. **Complete or Fail**: Use the `complete` method to return a successful result or the `fail` method to indicate an error.
|
|
422
|
+
|
|
423
|
+
#### Benefits
|
|
424
|
+
|
|
425
|
+
- **Flexibility**: Allows you to handle complex scenarios that may not be possible with predefined tools.
|
|
426
|
+
- **Error Handling**: Provides a mechanism to gracefully handle errors and unknown function calls.
|
|
427
|
+
|
|
428
|
+
#### Best Practices
|
|
429
|
+
|
|
430
|
+
- Always inspect the `functionCall` object to ensure you are handling the correct function.
|
|
431
|
+
- Use descriptive error messages when calling the `fail` method to make debugging easier.
|
|
432
|
+
- Test your transaction handler thoroughly to ensure it works as expected in all scenarios.
|
|
433
|
+
|
|
434
|
+
By combining manual transaction handling with the `tools` prop, you can create a robust and flexible integration with the Persona SDK.
|
|
435
|
+
|
|
436
|
+
---
|
|
437
|
+
|
|
221
438
|
## Contributing
|
|
222
439
|
|
|
223
440
|
We welcome contributions! To get started:
|
package/dist/bundle.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var q=Object.defineProperty;var J=(o,t,e)=>t in o?q(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var a=(o,t,e)=>J(o,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react"),M=require("@assistant-ui/react");var N={exports:{}},C={};/**
|
|
2
2
|
* @license React
|
|
3
3
|
* react-jsx-runtime.production.js
|
|
4
4
|
*
|
|
@@ -6,5 +6,5 @@
|
|
|
6
6
|
*
|
|
7
7
|
* This source code is licensed under the MIT license found in the
|
|
8
8
|
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var I;function J(){if(I)return w;I=1;var n=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(i,s,o){var c=null;if(o!==void 0&&(c=""+o),s.key!==void 0&&(c=""+s.key),"key"in s){o={};for(var r in s)r!=="key"&&(o[r]=s[r])}else o=s;return s=o.ref,{$$typeof:n,type:i,key:c,ref:s!==void 0?s:null,props:o}}return w.Fragment=t,w.jsx=e,w.jsxs=e,w}N.exports=J();var R=N.exports;function K(n){return n.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function B(n){const t=[];let e=null;for(const s of n)s.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(s)):s.functionCalls?(e&&t.push(e),t.push(s),e=null):s.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:s.functionResponse}:e&&s.protocol===e.protocol&&(e.role===s.role||s.finishReason==="stop")?(e.text+=s.text,e.files=[...e.files??[],...s.files??[]]):(e&&t.push(e),e={...s});return e&&t.push(e),K(t)}function _(n){var e,i;const t=((e=n.files)==null?void 0:e.map(s=>({type:"file",data:s.url,mimeType:s.contentType})))??[];return n.role==="function"?{id:n.id,role:"assistant",status:(n==null?void 0:n.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((i=n.functionCalls)==null?void 0:i.map(s=>{var o;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(o=n.functionResponse)==null?void 0:o.result}}))??[]}:{id:n.id,role:n.role,content:n.type==="reasoning"?[{type:"reasoning",text:n.text},...t]:[{type:"text",text:n.text},...t]}}class S{constructor(){a(this,"statusChangeCallbacks",[]);a(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addMessageListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyMessage(t){this.messageCallbacks.forEach(e=>e(t))}async notifyMessages(t){t.forEach(e=>{this.messageCallbacks.forEach(i=>i(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(i=>i(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class x extends S{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async send(e){const{apiUrl:i,apiKey:s,agentId:o}=this.config,c=this.session??"new",r=e,h=await(await fetch(`${i}/agents/${o}/sessions/${c}/messages`,{body:JSON.stringify({userMessage:r}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":s,"x-persona-apikey":s}})).json();this.notifyMessages(h.response.messages)}}class E extends S{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(e){var i;(i=this.config.logger)==null||i.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var r;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const i=e||this.session||"new";(r=this.config.logger)==null||r.debug("Connecting to WebSocket with sessionId:",i);const s=encodeURIComponent(this.config.apiKey),o=this.config.agentId,c=`${this.config.webSocketUrl}?sessionCode=${i}&agentId=${o}&apiKey=${s}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(c),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",u=>{const h=JSON.parse(u.data);if(h.type!=="message")return;const p=h.payload;this.notifyMessage(p!=null&&p.thought?{role:"assistant",type:"reasoning",text:p.thought}:p)}),this.webSocket.addEventListener("close",()=>{var u;this.setStatus("disconnected"),this.webSocket=null,(u=this.config.logger)==null||u.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",u=>{var h;this.setStatus("disconnected"),this.webSocket=null,(h=this.config.logger)==null||h.error("WebSocket error",u)}),Promise.resolve(i)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:e})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class Y{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 i;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(s){(i=this.config.logger)==null||i.error("Error accessing microphone:",s);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(s=>{this.pc.addTrack(s,this.localStream)}),this.pc.ontrack=s=>{s.streams[0].getTracks().forEach(c=>{this.remoteStream.addTrack(c)}),this.audioCtx||this._startAnalyzers();const o=new Audio;o.srcObject=this.remoteStream,o.play().catch(c=>{var r;(r=this.config.logger)==null||r.error("Error playing remote audio:",c)})},this.pc.onicecandidate=s=>{var o;s.candidate&&((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:s.candidate}}))},this.pc.ondatachannel=s=>{const o=s.channel;o.onmessage=c=>{this.messageCallbacks.forEach(r=>{r(c)})}};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 r,u;const s=await this.pc.createOffer();await this.pc.setLocalDescription(s);const o={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(r=this.config.logger)==null||r.debug("Opening connection to WebRTC server: ",o);const c={type:"OFFER",src:((u=crypto.randomUUID)==null?void 0:u.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:s.sdp,type:s.type},connectionId:(Date.now()%1e6).toString(),metadata:o}};this.ws.send(JSON.stringify(c))},this.ws.onmessage=async s=>{var c;const o=JSON.parse(s.data);if(o.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(o.payload.sdp));else if(o.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(o.payload.candidate))}catch(r){(c=this.config.logger)==null||c.error("Error adding ICE candidate:",r)}},this.ws.onclose=()=>{this._stopAnalyzers()}}async disconnect(){var t;this.isConnected&&(this.isConnected=!1,((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(e=>e.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(t){this.visualizerCallbacks.push(t)}addMessageCallback(t){this.messageCallbacks.push(t)}createDataChannel(t="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(t),this.dataChannel.onopen=()=>{var e;return(e=this.config.logger)==null?void 0:e.info("Data channel opened")},this.dataChannel.onmessage=e=>{this.messageCallbacks.forEach(i=>{i(e)})})}sendMessage(t){var e,i;if(!this.dataChannel){(e=this.config.logger)==null||e.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(t),(i=this.config.logger)==null||i.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 i=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const s=new Uint8Array(this.localAnalyser.frequencyBinCount),o=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(s),this.remoteAnalyser.getByteFrequencyData(o);const c=s.reduce((u,h)=>u+h,0)/s.length,r=o.reduce((u,h)=>u+h,0)/o.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(u=>{u({localAmplitude:c,remoteAmplitude:r})}),this.analyzerFrame=requestAnimationFrame(i)};this.analyzerFrame=requestAnimationFrame(i)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class A extends S{constructor(e){super();a(this,"status");a(this,"session");a(this,"autostart");a(this,"config");a(this,"webRTCClient");this.config=e,this.status="disconnected",this.session=null,this.autostart=(e==null?void 0:e.autostart)??!1,this.webRTCClient=new Y(e),this.webRTCClient.addMessageCallback(i=>{var o;(o=e.logger)==null||o.debug("Received data message:",i.data);const s=JSON.parse(i.data);s.type==="message"&&this.notifyMessage(s.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var i;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(i=this.config.logger)==null||i.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,i,s;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(s=(i=this.config)==null?void 0:i.logger)==null||s.debug("Disconnected from WebRTC")}send(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(e),Promise.resolve())}}const P=d.createContext(void 0);function G({dev:n=!1,protocols:t,logger:e,children:i,session:s="new",...o}){const[c,r]=d.useState(!1),[u,h]=d.useState([]),[p,z]=d.useState(s),[b,D]=d.useState(new Map),v=d.useRef(!1),m=d.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const l=n?"localhost:8000":"persona.applica.guru/api",g=n?"http":"https",y=n?"ws":"wss";return Object.keys(t).map(f=>{switch(f){case"rest":const C=t[f];return C===!0?new x({apiUrl:`${g}://${l}`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):new x(C);case"webrtc":const T=t[f];return T===!0?new A({webrtcUrl:`${y}://${l}/webrtc`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):new A(T);case"websocket":const M=t[f];return M===!0?new E({webSocketUrl:`${y}://${l}/websocket`,apiKey:o.apiKey,agentId:o.agentId,logger:e}):new E(M);default:throw new Error(`Unknown protocol: ${f}`)}})}throw new Error("Invalid protocols configuration")},[]);d.useEffect(()=>{v.current||(v.current=!0,e==null||e.debug("Initializing protocols: ",m.map(l=>l.getName())),m.forEach(l=>{l.setSession(p),l.clearListeners(),l.addStatusChangeListener(g=>{e==null||e.debug(`${l.getName()} has notified new status: ${g}`),b.set(l.getName(),g),D(new Map(b))}),l.addMessageListener(g=>{h(y=>B([...y,{...g,protocol:l.getName()}]))}),l.autostart&&l.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${l.getName()}`),l.connect(p))}))},[p,m,e,b]);const L=async l=>{var k;if(((k=l.content[0])==null?void 0:k.type)!=="text")throw new Error("Only text messages are supported");const g=l.content[0].text;h(f=>[...f,{role:"user",type:"text",text:g}]),r(!0);const y=m.sort((f,C)=>C.getPriority()-f.getPriority()).find(f=>f.status==="connected");await(y==null?void 0:y.send(g)),r(!1)},O=d.useCallback(()=>(r(!1),h([]),z("new"),Promise.resolve()),[]),j=d.useCallback(()=>Promise.resolve(),[]),U=$.useExternalStoreRuntime({isRunning:c,messages:u,convertMessage:_,onNew:L,onCancel:O,onReload:j});return R.jsx(P.Provider,{value:{protocols:m,protocolsStatus:b},children:R.jsx($.AssistantRuntimeProvider,{runtime:U,children:i})})}function V({children:n,...t}){return R.jsx(G,{...t,children:n})}function H(){const n=d.useContext(P);if(!n)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return n}function W(n){const t=d.useContext(P);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(s=>s.getName()===n);if(!e)return null;const i=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),send:e.send.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addMessageListener:e.addMessageListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:i||e.status}}function Q(){const n=d.useContext(P);if(!n)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");for(const t of n.protocols)if(t.getName()==="rest")return t.config.apiUrl;throw new Error("REST protocol not found")}function X(){return W("webrtc")}class Z{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=Z;exports.PersonaProtocolBase=S;exports.PersonaRESTProtocol=x;exports.PersonaRuntimeProvider=V;exports.PersonaWebRTCProtocol=A;exports.PersonaWebSocketProtocol=E;exports.usePersonaRuntime=H;exports.usePersonaRuntimeEndpoint=Q;exports.usePersonaRuntimeProtocol=W;exports.usePersonaRuntimeWebRTCProtocol=X;
|
|
9
|
+
*/var I;function K(){if(I)return C;I=1;var o=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(n,s,i){var r=null;if(i!==void 0&&(r=""+i),s.key!==void 0&&(r=""+s.key),"key"in s){i={};for(var c in s)c!=="key"&&(i[c]=s[c])}else i=s;return s=i.ref,{$$typeof:o,type:n,key:r,ref:s!==void 0?s:null,props:i}}return C.Fragment=t,C.jsx=e,C.jsxs=e,C}N.exports=K();var R=N.exports;function _(o){return o.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function B(o){const t=[];let e=null;for(const s of o)s.type!=="transaction"&&(s.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(s)):s.functionCalls?(e&&t.push(e),t.push(s),e=null):s.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:s.functionResponse}:e&&s.protocol===e.protocol&&(e.role===s.role||s.finishReason==="stop")?(e.text+=s.text,e.files=[...e.files??[],...s.files??[]]):(e&&t.push(e),e={...s}));return e&&t.push(e),_(t)}function Y(o){var e,n;const t=((e=o.files)==null?void 0:e.map(s=>({type:"file",data:s.url,mimeType:s.contentType})))??[];return o.role==="function"?{id:o.id,role:"assistant",status:(o==null?void 0:o.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((n=o.functionCalls)==null?void 0:n.map(s=>{var i;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(i=o.functionResponse)==null?void 0:i.result}}))??[]}:{id:o.id,role:o.role,content:o.type==="reasoning"?[{type:"reasoning",text:o.text},...t]:[{type:"text",text:o.text},...t]}}class S{constructor(){a(this,"statusChangeCallbacks",[]);a(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addMessageListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyMessage(t){this.messageCallbacks.forEach(e=>e(t))}async notifyMessages(t){t.forEach(e=>{this.messageCallbacks.forEach(n=>n(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(n=>n(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(t){}}class x extends S{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async send(e){const{apiUrl:n,apiKey:s,agentId:i}=this.config,r=this.session??"new",c=e,h=await(await fetch(`${n}/agents/${i}/sessions/${r}/messages`,{body:JSON.stringify({userMessage:c}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":s,"x-persona-apikey":s}})).json();this.notifyMessages(h.response.messages.map(w=>({type:"message",payload:w})))}}class E extends S{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(e){var n;(n=this.config.logger)==null||n.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var c;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const n=e||this.session||"new";(c=this.config.logger)==null||c.debug("Connecting to WebSocket with sessionId:",n);const s=encodeURIComponent(this.config.apiKey),i=this.config.agentId,r=`${this.config.webSocketUrl}?sessionCode=${n}&agentId=${i}&apiKey=${s}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(r),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",u=>{const h=JSON.parse(u.data);this.notifyMessage(h)}),this.webSocket.addEventListener("close",()=>{var u;this.setStatus("disconnected"),this.webSocket=null,(u=this.config.logger)==null||u.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",u=>{var h;this.setStatus("disconnected"),this.webSocket=null,(h=this.config.logger)==null||h.error("WebSocket error",u)}),Promise.resolve(n)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:e})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class G{constructor(t){a(this,"config");a(this,"pc",null);a(this,"ws",null);a(this,"localStream",null);a(this,"remoteStream",new MediaStream);a(this,"audioCtx",null);a(this,"localAnalyser",null);a(this,"remoteAnalyser",null);a(this,"analyzerFrame",null);a(this,"dataChannel",null);a(this,"isConnected",!1);a(this,"visualizerCallbacks",[]);a(this,"messageCallbacks",[]);this.config=t}async connect(t){var n;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(s){(n=this.config.logger)==null||n.error("Error accessing microphone:",s);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(s=>{this.pc.addTrack(s,this.localStream)}),this.pc.ontrack=s=>{s.streams[0].getTracks().forEach(r=>{this.remoteStream.addTrack(r)}),this.audioCtx||this._startAnalyzers();const i=new Audio;i.srcObject=this.remoteStream,i.play().catch(r=>{var c;(c=this.config.logger)==null||c.error("Error playing remote audio:",r)})},this.pc.onicecandidate=s=>{var i;s.candidate&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:s.candidate}}))},this.pc.ondatachannel=s=>{const i=s.channel;i.onmessage=r=>{this.messageCallbacks.forEach(c=>{c(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 c,u;const s=await this.pc.createOffer();await this.pc.setLocalDescription(s);const i={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(c=this.config.logger)==null||c.debug("Opening connection to WebRTC server: ",i);const r={type:"OFFER",src:((u=crypto.randomUUID)==null?void 0:u.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:s.sdp,type:s.type},connectionId:(Date.now()%1e6).toString(),metadata:i}};this.ws.send(JSON.stringify(r))},this.ws.onmessage=async s=>{var r;const i=JSON.parse(s.data);if(i.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(i.payload.sdp));else if(i.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(i.payload.candidate))}catch(c){(r=this.config.logger)==null||r.error("Error adding ICE candidate:",c)}},this.ws.onclose=()=>{this._stopAnalyzers()}}async disconnect(){var t;this.isConnected&&(this.isConnected=!1,((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(e=>e.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(t){this.visualizerCallbacks.push(t)}addMessageCallback(t){this.messageCallbacks.push(t)}createDataChannel(t="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(t),this.dataChannel.onopen=()=>{var e;return(e=this.config.logger)==null?void 0:e.info("Data channel opened")},this.dataChannel.onmessage=e=>{this.messageCallbacks.forEach(n=>{n(e)})})}sendMessage(t){var e,n;if(!this.dataChannel){(e=this.config.logger)==null||e.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(t),(n=this.config.logger)==null||n.info("Sent message:",t)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const t=this.audioCtx.createMediaStreamSource(this.localStream),e=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,t.connect(this.localAnalyser),e.connect(this.remoteAnalyser);const n=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const s=new Uint8Array(this.localAnalyser.frequencyBinCount),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(s),this.remoteAnalyser.getByteFrequencyData(i);const r=s.reduce((u,h)=>u+h,0)/s.length,c=i.reduce((u,h)=>u+h,0)/i.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(u=>{u({localAmplitude:r,remoteAmplitude:c})}),this.analyzerFrame=requestAnimationFrame(n)};this.analyzerFrame=requestAnimationFrame(n)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class T extends S{constructor(e){super();a(this,"status");a(this,"session");a(this,"autostart");a(this,"config");a(this,"webRTCClient");this.config=e,this.status="disconnected",this.session=null,this.autostart=(e==null?void 0:e.autostart)??!1,this.webRTCClient=new G(e),this.webRTCClient.addMessageCallback(n=>{const s=JSON.parse(n.data);this.notifyMessage(s)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var n;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(n=this.config.logger)==null||n.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var e,n,s;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(s=(n=this.config)==null?void 0:n.logger)==null||s.debug("Disconnected from WebRTC")}send(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(e),Promise.resolve())}}class V{constructor(t){a(this,"config");this.config=t}async complete(t,e){var n;await this.persist(t,{...e,success:!0}),(n=this.config.logger)==null||n.debug("Transaction completed:",t)}async fail(t,e){var n;await this.persist(t,{...e,success:!1}),(n=this.config.logger)==null||n.debug("Transaction failed:",{...t,...e})}async persist(t,e){await fetch(`${this.config.apiUrl}/transactions/${t.id}`,{body:JSON.stringify(e),method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-persona-apikey":this.config.apiKey}})}}class H{constructor(t,e){a(this,"transaction");a(this,"manager");this.transaction=t,this.manager=e}getFunctionCall(){return this.transaction.functionCall}async invoke(t){const e=this.transaction.functionCall;if(!e){await this.fail("No function call found");return}const n=e.name,s=e.args,i=t[n];if(!i){await this.fail(`Tool ${n} not found`);return}try{const r=await i(s);await this.complete({date:new Date().toISOString(),result:r})}catch(r){await this.fail(`Error executing tool ${n}: ${r}`)}}async complete(t){await this.manager.complete(this.transaction,{success:!0,output:t,error:null})}async fail(t){await this.manager.fail(this.transaction,{success:!1,output:null,error:t})}}class W extends S{constructor(e){super();a(this,"status");a(this,"autostart");a(this,"session");a(this,"config");a(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"transaction"}getPriority(){return 0}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async send(e){var n;throw(n=this.config.logger)==null||n.debug("Sending message:",e),new Error("Not implemented")}onTransaction(e){var i;if(!this.config.onTransaction){(i=this.config.logger)==null||i.error("Transaction protocol config is not set");return}const n=new V(this.config),s=new H(e,n);this.config.onTransaction(s)}}const k=p.createContext(void 0);function Q({dev:o=!1,protocols:t,logger:e,children:n,session:s="new",...i}){const[r,c]=p.useState(!1),[u,h]=p.useState([]),[w,D]=p.useState(s),[b,O]=p.useState(new Map),A=p.useRef(!1),m=p.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const l=o?"localhost:8000":"persona.applica.guru/api",d=o?"http":"https",g=o?"ws":"wss";let y=Object.keys(t).map(f=>{switch(f){case"rest":const P=t[f];return P===!0?new x({apiUrl:`${d}://${l}`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new x(P);case"webrtc":const v=t[f];return v===!0?new T({webrtcUrl:`${g}://${l}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new T(v);case"websocket":const $=t[f];return $===!0?new E({webSocketUrl:`${g}://${l}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:e}):new E($);default:throw new Error(`Unknown protocol: ${f}`)}});return i.tools&&y.push(new W({apiUrl:`${d}://${l}`,apiKey:i.apiKey,agentId:i.agentId,onTransaction:async f=>{await f.invoke(i.tools)},logger:e})),y}throw new Error("Invalid protocols configuration")},[]);p.useEffect(()=>{A.current||(A.current=!0,e==null||e.debug("Initializing protocols: ",m.map(l=>l.getName())),m.forEach(l=>{l.setSession(w),l.clearListeners(),l.addStatusChangeListener(d=>{e==null||e.debug(`${l.getName()} has notified new status: ${d}`),b.set(l.getName(),d),O(new Map(b))}),l.addMessageListener(d=>{if(d.type==="message"){const g=d.payload;h(y=>B([...y,{...g,protocol:l.getName()}]))}else d.type==="transaction"&&m.filter(g=>g!==l).forEach(g=>g.onTransaction(d.payload))}),l.autostart&&l.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${l.getName()}`),l.connect(w))}))},[w,m,e,b]);const j=async l=>{var y;if(((y=l.content[0])==null?void 0:y.type)!=="text")throw new Error("Only text messages are supported");const d=l.content[0].text;h(f=>[...f,{role:"user",type:"text",text:d}]),c(!0);const g=m.sort((f,P)=>P.getPriority()-f.getPriority()).find(f=>f.status==="connected");await(g==null?void 0:g.send(d)),c(!1)},L=p.useCallback(()=>(c(!1),h([]),D("new"),Promise.resolve()),[]),U=p.useCallback(()=>Promise.resolve(),[]),F=M.useExternalStoreRuntime({isRunning:r,messages:u,convertMessage:Y,onNew:j,onCancel:L,onReload:U});return R.jsx(k.Provider,{value:{protocols:m,protocolsStatus:b},children:R.jsx(M.AssistantRuntimeProvider,{runtime:F,children:n})})}function X({children:o,...t}){return R.jsx(Q,{...t,children:o})}function Z(){const o=p.useContext(k);if(!o)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return o}function z(o){const t=p.useContext(k);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(s=>s.getName()===o);if(!e)return null;const n=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),send:e.send.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addMessageListener:e.addMessageListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:n||e.status}}function ee(){const o=p.useContext(k);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 te(){return z("webrtc")}class se{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=se;exports.PersonaProtocolBase=S;exports.PersonaRESTProtocol=x;exports.PersonaRuntimeProvider=X;exports.PersonaTransactionProtocol=W;exports.PersonaWebRTCProtocol=T;exports.PersonaWebSocketProtocol=E;exports.usePersonaRuntime=Z;exports.usePersonaRuntimeEndpoint=ee;exports.usePersonaRuntimeProtocol=z;exports.usePersonaRuntimeWebRTCProtocol=te;
|
|
10
10
|
//# sourceMappingURL=bundle.cjs.js.map
|
package/dist/bundle.cjs.js.map
CHANGED
|
@@ -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/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 === '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 { Message, MessageListenerCallback, PersonaMessage, PersonaProtocol, ProtocolStatus, Session, StatusChangeCallback } from '../types';\n\nabstract class PersonaProtocolBase implements PersonaProtocol {\n abstract status: ProtocolStatus;\n abstract session: Session;\n abstract autostart: boolean;\n\n private statusChangeCallbacks: StatusChangeCallback[] = [];\n private messageCallbacks: MessageListenerCallback[] = [];\n\n public addStatusChangeListener(callback: StatusChangeCallback) {\n this.statusChangeCallbacks.push(callback);\n }\n\n public addMessageListener(callback: MessageListenerCallback) {\n this.messageCallbacks.push(callback);\n }\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async notifyMessage(message: PersonaMessage): Promise<void> {\n this.messageCallbacks.forEach((callback) => callback(message));\n }\n public async notifyMessages(messages: PersonaMessage[]): Promise<void> {\n messages.forEach((message) => {\n this.messageCallbacks.forEach((callback) => callback(message));\n });\n }\n\n public async setSession(session: Session): Promise<void> {\n this.session = session;\n }\n public async setStatus(status: ProtocolStatus): Promise<void> {\n const notify = this.status !== status;\n this.status = status;\n if (!notify) {\n return;\n }\n this.statusChangeCallbacks.forEach((callback) => callback(status));\n }\n\n public clearListeners(): void {\n this.statusChangeCallbacks = [];\n this.messageCallbacks = [];\n }\n\n abstract getName(): string;\n abstract getPriority(): number;\n abstract connect(session?: Session): Promise<Session>;\n abstract disconnect(): Promise<void>;\n abstract send(message: Message): Promise<void>;\n}\n\nexport { PersonaProtocolBase };\n","import { PersonaProtocolBase } from './base';\nimport { Message, PersonaResponse, Session, ProtocolStatus, PersonaProtocolBaseConfig } from '../types';\n\ntype PersonaRESTProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n};\n\nclass PersonaRESTProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaRESTProtocolConfig;\n notify: boolean = true;\n\n constructor(config: PersonaRESTProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'rest';\n }\n\n public getPriority(): number {\n return 0;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async send(message: Message): Promise<void> {\n const { apiUrl, apiKey, agentId } = this.config;\n const sessionId = this.session ?? 'new';\n const input = message;\n\n const response = await fetch(`${apiUrl}/agents/${agentId}/sessions/${sessionId}/messages`, {\n body: JSON.stringify({ userMessage: input }),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-fox-apikey': apiKey,\n 'x-persona-apikey': apiKey,\n },\n });\n const personaResponse = (await response.json()) as PersonaResponse;\n this.notifyMessages(personaResponse.response.messages);\n }\n}\n\nexport { PersonaRESTProtocol };\nexport type { PersonaRESTProtocolConfig };\n","import { Message, PersonaMessage, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\nimport { PersonaProtocolBase } from './base';\n\ntype PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {\n webSocketUrl: string;\n};\n\nclass PersonaWebSocketProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaWebSocketProtocolConfig;\n webSocket: WebSocket | null;\n\n constructor(config: PersonaWebSocketProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n this.session = null;\n this.webSocket = null;\n }\n\n public getName(): string {\n return 'websocket';\n }\n\n public getPriority(): number {\n return 1;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.config.logger?.debug('Syncing session with WebSocket protocol:', session);\n this.session = session;\n if (this.webSocket && this.status === 'connected') {\n this.disconnect();\n this.connect(session);\n }\n }\n\n public connect(session?: Session): Promise<Session> {\n if (this.webSocket !== null && this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n\n const sid = session || this.session || 'new';\n\n this.config.logger?.debug('Connecting to WebSocket with sessionId:', sid);\n\n const apiKey = encodeURIComponent(this.config.apiKey);\n const agentId = this.config.agentId;\n const webSocketUrl = `${this.config.webSocketUrl}?sessionCode=${sid}&agentId=${agentId}&apiKey=${apiKey}`;\n this.setStatus('connecting');\n this.webSocket = new WebSocket(webSocketUrl);\n this.webSocket.addEventListener('open', () => {\n this.setStatus('connected');\n });\n this.webSocket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data) as { type: 'message' | unknown; payload: PersonaMessage | unknown };\n\n if (data.type !== 'message') {\n return;\n }\n const message = data.payload as PersonaMessage & { thought?: string };\n\n this.notifyMessage(message?.thought ? { role: 'assistant', type: 'reasoning', text: message.thought } : message);\n });\n this.webSocket.addEventListener('close', () => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.warn('WebSocket connection closed');\n });\n\n this.webSocket.addEventListener('error', (error) => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.error('WebSocket error', error);\n\n // TODO: Implement reconnection logic\n });\n\n return Promise.resolve(sid);\n }\n\n public disconnect(): Promise<void> {\n this.config.logger?.debug('Disconnecting WebSocket');\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.close();\n this.setStatus('disconnected');\n this.webSocket = null;\n }\n return Promise.resolve();\n }\n\n public send(message: Message): Promise<void> {\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.send(JSON.stringify({ type: 'request', payload: message }));\n return Promise.resolve();\n } else {\n return Promise.reject(new Error('WebSocket is not connected'));\n }\n }\n}\n\nexport { PersonaWebSocketProtocol };\nexport type { PersonaWebSocketProtocolConfig };\n","import { PersonaProtocolBase } from './base';\nimport { Message, PersonaMessage, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\n\ntype AudioAnalysisData = {\n localAmplitude: number;\n remoteAmplitude: number;\n};\n\ntype AudioVisualizerCallback = (data: AudioAnalysisData) => void;\n\ntype PersonaWebRTCMessageCallback = (data: MessageEvent) => void;\n\ntype PersonaWebRTCConfig = PersonaProtocolBaseConfig & {\n webrtcUrl: string;\n iceServers?: RTCIceServer[];\n};\n\nclass PersonaWebRTCClient {\n private config: PersonaWebRTCConfig;\n private pc: RTCPeerConnection | null = null;\n private ws: WebSocket | null = null;\n private localStream: MediaStream | null = null;\n private remoteStream: MediaStream = new MediaStream();\n private audioCtx: AudioContext | null = null;\n\n private localAnalyser: AnalyserNode | null = null;\n private remoteAnalyser: AnalyserNode | null = null;\n private analyzerFrame: number | null = null;\n private dataChannel: RTCDataChannel | null = null;\n\n private isConnected: boolean = false;\n private visualizerCallbacks: AudioVisualizerCallback[] = [];\n private messageCallbacks: PersonaWebRTCMessageCallback[] = [];\n\n constructor(config: PersonaWebRTCConfig) {\n this.config = config;\n }\n\n public async connect(session: Session): Promise<Session> {\n if (this.isConnected) return;\n\n this.isConnected = true;\n\n try {\n this.localStream = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch (err) {\n this.config.logger?.error('Error accessing microphone:', err);\n return;\n }\n\n this.pc = new RTCPeerConnection({\n iceServers: this.config.iceServers || [\n {\n urls: 'stun:34.38.108.251:3478',\n },\n {\n urls: 'turn:34.38.108.251:3478',\n username: 'webrtc',\n credential: 'webrtc',\n },\n ],\n });\n\n this.localStream.getTracks().forEach((track) => {\n this.pc!.addTrack(track, this.localStream!);\n });\n\n this.pc.ontrack = (event) => {\n event.streams[0].getTracks().forEach((track) => {\n this.remoteStream.addTrack(track);\n });\n\n if (!this.audioCtx) {\n this._startAnalyzers();\n }\n\n const remoteAudio = new Audio();\n remoteAudio.srcObject = this.remoteStream;\n remoteAudio.play().catch((e) => {\n this.config.logger?.error('Error playing remote audio:', e);\n });\n };\n\n this.pc.onicecandidate = (event) => {\n if (event.candidate && this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(\n JSON.stringify({\n type: 'CANDIDATE',\n src: 'client',\n payload: { candidate: event.candidate },\n }),\n );\n }\n };\n\n this.pc.ondatachannel = (event) => {\n const channel = event.channel;\n channel.onmessage = (msg) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n };\n\n const url = this.config.webrtcUrl || 'wss://persona.applica.guru/api/webrtc';\n this.ws = new WebSocket(`${url}?apiKey=${encodeURIComponent(this.config.apiKey)}`);\n this.ws.onopen = async () => {\n const offer = await this.pc!.createOffer();\n await this.pc!.setLocalDescription(offer);\n\n const metadata = {\n apiKey: this.config.apiKey,\n agentId: this.config.agentId,\n sessionCode: session as string,\n };\n this.config.logger?.debug('Opening connection to WebRTC server: ', metadata);\n\n const offerMessage = {\n type: 'OFFER',\n src: crypto.randomUUID?.() || 'client_' + Date.now(),\n payload: {\n sdp: {\n sdp: offer.sdp,\n type: offer.type,\n },\n connectionId: (Date.now() % 1000000).toString(),\n metadata,\n },\n };\n\n this.ws!.send(JSON.stringify(offerMessage));\n };\n\n this.ws.onmessage = async (event) => {\n const data = JSON.parse(event.data);\n if (data.type === 'ANSWER') {\n await this.pc!.setRemoteDescription(new RTCSessionDescription(data.payload.sdp));\n } else if (data.type === 'CANDIDATE') {\n try {\n await this.pc!.addIceCandidate(new RTCIceCandidate(data.payload.candidate));\n } catch (err) {\n this.config.logger?.error('Error adding ICE candidate:', err);\n }\n }\n };\n\n this.ws.onclose = () => {\n this._stopAnalyzers();\n };\n }\n\n public async disconnect(): Promise<void> {\n if (!this.isConnected) return;\n\n this.isConnected = false;\n\n if (this.ws?.readyState === WebSocket.OPEN) this.ws.close();\n if (this.pc) this.pc.close();\n if (this.localStream) {\n this.localStream.getTracks().forEach((track) => track.stop());\n }\n\n this.remoteStream = new MediaStream();\n if (this.audioCtx) {\n await this.audioCtx.close();\n this.audioCtx = null;\n }\n\n this._stopAnalyzers();\n }\n\n public addVisualizerCallback(callback: AudioVisualizerCallback): void {\n this.visualizerCallbacks.push(callback);\n }\n public addMessageCallback(callback: PersonaWebRTCMessageCallback): void {\n this.messageCallbacks.push(callback);\n }\n\n public createDataChannel(label = 'messages'): void {\n if (!this.pc) return;\n this.dataChannel = this.pc.createDataChannel(label);\n this.dataChannel.onopen = () => this.config.logger?.info('Data channel opened');\n this.dataChannel.onmessage = (msg: MessageEvent) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n }\n\n public sendMessage(message: string): 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(message);\n this.config.logger?.info('Sent message:', message);\n }\n\n private _startAnalyzers(): void {\n if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();\n\n const localSource = this.audioCtx.createMediaStreamSource(this.localStream);\n const remoteSource = this.audioCtx.createMediaStreamSource(this.remoteStream);\n\n this.localAnalyser = this.audioCtx.createAnalyser();\n this.remoteAnalyser = this.audioCtx.createAnalyser();\n this.localAnalyser.fftSize = 256;\n this.remoteAnalyser.fftSize = 256;\n\n localSource.connect(this.localAnalyser);\n remoteSource.connect(this.remoteAnalyser);\n\n const loop = () => {\n if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n const localArray = new Uint8Array(this.localAnalyser.frequencyBinCount);\n const remoteArray = new Uint8Array(this.remoteAnalyser.frequencyBinCount);\n\n this.localAnalyser.getByteFrequencyData(localArray);\n this.remoteAnalyser.getByteFrequencyData(remoteArray);\n\n const localAmp = localArray.reduce((a, b) => a + b, 0) / localArray.length;\n const remoteAmp = remoteArray.reduce((a, b) => a + b, 0) / remoteArray.length;\n\n if (this.visualizerCallbacks.length > 0) {\n this.visualizerCallbacks.forEach((callback) => {\n callback({\n localAmplitude: localAmp,\n remoteAmplitude: remoteAmp,\n });\n });\n }\n\n this.analyzerFrame = requestAnimationFrame(loop);\n };\n\n this.analyzerFrame = requestAnimationFrame(loop);\n }\n\n private _stopAnalyzers(): void {\n if (this.analyzerFrame) {\n cancelAnimationFrame(this.analyzerFrame);\n this.analyzerFrame = null;\n }\n this.localAnalyser = null;\n this.remoteAnalyser = null;\n }\n}\n\ntype PersonaWebRTCProtocolConfig = PersonaWebRTCConfig & {\n autostart?: boolean;\n};\n\nclass PersonaWebRTCProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n session: Session;\n autostart: boolean;\n config: PersonaWebRTCProtocolConfig;\n webRTCClient: PersonaWebRTCClient;\n\n constructor(config: PersonaWebRTCProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.session = null;\n this.autostart = config?.autostart ?? false;\n this.webRTCClient = new PersonaWebRTCClient(config);\n this.webRTCClient.addMessageCallback((msg: MessageEvent) => {\n config.logger?.debug('Received data message:', msg.data);\n const data = JSON.parse(msg.data) as { type: 'message' | unknown; payload: PersonaMessage | unknown };\n if (data.type === 'message') {\n this.notifyMessage(data.payload as PersonaMessage);\n }\n });\n }\n\n public getName(): string {\n return 'webrtc';\n }\n public getPriority(): number {\n return 10;\n }\n\n public async syncSession(session: Session): Promise<void> {\n super.syncSession(session);\n if (this.status === 'connected') {\n await this.disconnect();\n await this.connect(session);\n }\n }\n\n public async connect(session?: Session): Promise<Session> {\n if (this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n this.session = session || this.session || 'new';\n this.setStatus('connecting');\n\n this.config.logger?.debug('Connecting to WebRTC with sessionId:', this.session);\n await this.webRTCClient.connect(this.session);\n this.setStatus('connected');\n\n await this.webRTCClient.createDataChannel();\n\n return this.session;\n }\n\n public async disconnect(): Promise<void> {\n if (this.status === 'disconnected') {\n this.config.logger?.warn('Already disconnected');\n return Promise.resolve();\n }\n\n await this.webRTCClient.disconnect();\n\n this.setStatus('disconnected');\n this.config?.logger?.debug('Disconnected from WebRTC');\n }\n\n public send(message: Message): Promise<void> {\n if (this.status !== 'connected') {\n return Promise.reject(new Error('Not connected'));\n }\n\n this.webRTCClient.sendMessage(message as string);\n return Promise.resolve();\n }\n}\n\nexport { PersonaWebRTCProtocol };\nexport type { PersonaWebRTCProtocolConfig, AudioVisualizerCallback, AudioAnalysisData };\n","import { useState, useEffect, useCallback, PropsWithChildren, createContext, useContext, useMemo, useRef } from 'react';\nimport { useExternalStoreRuntime, AppendMessage, AssistantRuntimeProvider } from '@assistant-ui/react';\nimport {\n PersonaConfig,\n PersonaMessage,\n PersonaProtocol,\n PersonaProtocolBaseConfig,\n PersonaResponse,\n ProtocolStatus,\n Session,\n} from './types';\nimport { parseMessages, convertMessage } from './messages';\nimport {\n PersonaRESTProtocol,\n PersonaRESTProtocolConfig,\n PersonaWebRTCProtocol,\n PersonaWebRTCProtocolConfig,\n PersonaWebSocketProtocol,\n PersonaWebSocketProtocolConfig,\n} from './protocol';\n\ntype PersonaRuntimeContextType = {\n protocols: PersonaProtocol[];\n protocolsStatus: Map<string, ProtocolStatus>;\n};\n\nconst PersonaRuntimeContext = createContext<PersonaRuntimeContextType | undefined>(undefined);\n\nfunction PersonaRuntimeProviderInner({\n dev = false,\n protocols: _protocols,\n logger,\n children,\n session: defaultSession = 'new',\n ...config\n}: Readonly<PersonaConfig>) {\n const [isRunning, setIsRunning] = useState(false);\n const [messages, setMessages] = useState<PersonaMessage[]>([]);\n const [session, setSession] = useState<Session>(defaultSession);\n const [protocolsStatus, setProtocolsStatus] = useState<Map<string, ProtocolStatus>>(new Map());\n const didMount = useRef(false);\n\n const protocols = useMemo<PersonaProtocol[]>(() => {\n if (Array.isArray(_protocols)) {\n return _protocols;\n }\n\n if (typeof _protocols === 'object' && _protocols !== null) {\n const baseEndpoint = dev ? 'localhost:8000' : 'persona.applica.guru/api';\n const baseEndpointProtocol = dev ? 'http' : 'https';\n const baseWebSocketProtocol = dev ? 'ws' : 'wss';\n const availableProtocols = Object.keys(_protocols).map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | true | undefined = _protocols[key];\n if (restConfig === true) {\n return new PersonaRESTProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n }\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | true | undefined = _protocols[key];\n if (webrtcConfig === true) {\n return new PersonaWebRTCProtocol({\n webrtcUrl: `${baseWebSocketProtocol}://${baseEndpoint}/webrtc`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n }\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | true | undefined = _protocols[key];\n if (websocketConfig === true) {\n return new PersonaWebSocketProtocol({\n webSocketUrl: `${baseWebSocketProtocol}://${baseEndpoint}/websocket`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n }\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n });\n return availableProtocols;\n }\n throw new Error('Invalid protocols configuration');\n }, []);\n\n useEffect(() => {\n if (didMount.current) return;\n\n didMount.current = true;\n logger?.debug(\n 'Initializing protocols: ',\n protocols.map((protocol) => protocol.getName()),\n );\n protocols.forEach((protocol) => {\n protocol.setSession(session);\n protocol.clearListeners();\n protocol.addStatusChangeListener((status: ProtocolStatus) => {\n logger?.debug(`${protocol.getName()} has notified new status: ${status}`);\n protocolsStatus.set(protocol.getName(), status);\n setProtocolsStatus(new Map(protocolsStatus));\n });\n protocol.addMessageListener((message: PersonaMessage) => {\n setMessages((currentConversation) => parseMessages([...currentConversation, ...[{ ...message, protocol: protocol.getName() }]]));\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\n await protocol?.send(input);\n\n setIsRunning(false);\n };\n\n const onCancel = useCallback(() => {\n setIsRunning(false);\n setMessages([]);\n setSession('new');\n return Promise.resolve();\n }, []);\n\n const onReload = useCallback(() => {\n return Promise.resolve();\n }, []);\n\n const runtime = useExternalStoreRuntime({\n isRunning,\n messages,\n convertMessage,\n onNew,\n onCancel,\n onReload,\n });\n\n return (\n <PersonaRuntimeContext.Provider value={{ protocols, protocolsStatus }}>\n <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>\n </PersonaRuntimeContext.Provider>\n );\n}\n\nfunction PersonaRuntimeProvider({ children, ...config }: PropsWithChildren<PersonaConfig>) {\n return <PersonaRuntimeProviderInner {...config}>{children}</PersonaRuntimeProviderInner>;\n}\n\nfunction usePersonaRuntime(): PersonaRuntimeContextType {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntime must be used within a PersonaRuntimeProvider');\n }\n return context;\n}\n\n/**\n * Retrieves a specific protocol instance from the PersonaRuntimeContext.\n *\n * @param protocol - The name of the protocol to use.\n * @returns {PersonaProtocol | null} - The protocol instance or null if not found.\n * @throws {Error} - If the hook is used outside of a PersonaRuntimeProvider.\n */\nfunction usePersonaRuntimeProtocol(protocol: string): PersonaProtocol | null {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider');\n }\n\n const protocolInstance = context.protocols.find((p) => p.getName() === protocol);\n if (!protocolInstance) {\n return null;\n }\n\n const status = context.protocolsStatus.get(protocolInstance.getName());\n\n return {\n ...protocolInstance,\n connect: protocolInstance.connect.bind(protocolInstance),\n disconnect: protocolInstance.disconnect.bind(protocolInstance),\n send: protocolInstance.send.bind(protocolInstance),\n setSession: protocolInstance.setSession.bind(protocolInstance),\n addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),\n addMessageListener: protocolInstance.addMessageListener.bind(protocolInstance),\n getName: protocolInstance.getName.bind(protocolInstance),\n getPriority: protocolInstance.getPriority.bind(protocolInstance),\n status: status || protocolInstance.status,\n };\n}\n\nfunction usePersonaRuntimeEndpoint(): string {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider');\n }\n for (const protocol of context.protocols) {\n if (protocol.getName() === 'rest') {\n return (protocol as PersonaRESTProtocol).config.apiUrl;\n }\n }\n throw new Error('REST protocol not found');\n}\n\nfunction usePersonaRuntimeWebRTCProtocol(): PersonaWebRTCProtocol | null {\n return usePersonaRuntimeProtocol('webrtc') as PersonaWebRTCProtocol;\n}\n\nexport { PersonaRuntimeProvider, usePersonaRuntimeEndpoint, usePersonaRuntime, usePersonaRuntimeProtocol, usePersonaRuntimeWebRTCProtocol };\nexport type { PersonaMessage, PersonaResponse };\n","interface PersonaLogger {\n log: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n}\n\nclass PersonaConsoleLogger implements PersonaLogger {\n prefix = '[Persona]';\n\n log(message: string, ...args: unknown[]) {\n console.log(`${this.prefix} - ${message}`, ...args);\n }\n\n info(message: string, ...args: unknown[]) {\n console.info(`${this.prefix} - ${message}`, ...args);\n }\n\n warn(message: string, ...args: unknown[]) {\n console.warn(`${this.prefix} - ${message}`, ...args);\n }\n\n error(message: string, ...args: unknown[]) {\n console.error(`${this.prefix} - ${message}`, ...args);\n }\n\n debug(message: string, ...args: unknown[]) {\n console.debug(`${this.prefix} - ${message}`, ...args);\n }\n}\n\nexport { PersonaConsoleLogger };\nexport type { PersonaLogger };\n"],"names":["REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","reactJsxRuntime_production","jsxRuntimeModule","require$$0","removeEmptyMessages","messages","message","_a","parseMessages","outputMessages","currentMessage","convertMessage","files","file","_b","call","PersonaProtocolBase","__publicField","callback","session","status","notify","PersonaRESTProtocol","apiUrl","apiKey","agentId","sessionId","input","personaResponse","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","PersonaRuntimeContext","createContext","PersonaRuntimeProviderInner","dev","_protocols","logger","children","defaultSession","isRunning","setIsRunning","useState","setMessages","setSession","protocolsStatus","setProtocolsStatus","didMount","useRef","protocols","useMemo","baseEndpoint","baseEndpointProtocol","baseWebSocketProtocol","restConfig","webrtcConfig","websocketConfig","useEffect","protocol","currentConversation","onNew","onCancel","useCallback","onReload","runtime","useExternalStoreRuntime","jsx","AssistantRuntimeProvider","PersonaRuntimeProvider","usePersonaRuntime","context","useContext","usePersonaRuntimeProtocol","protocolInstance","p","usePersonaRuntimeEndpoint","usePersonaRuntimeWebRTCProtocol","PersonaConsoleLogger","args"],"mappings":";;;;;;;;wCAWA,IAAIA,EAAqB,OAAO,IAAI,4BAA4B,EAC9DC,EAAsB,OAAO,IAAI,gBAAgB,EACnD,SAASC,EAAQC,EAAMC,EAAQC,EAAU,CACvC,IAAIC,EAAM,KAGV,GAFWD,IAAX,SAAwBC,EAAM,GAAKD,GACxBD,EAAO,MAAlB,SAA0BE,EAAM,GAAKF,EAAO,KACxC,QAASA,EAAQ,CACnBC,EAAW,CAAE,EACb,QAASE,KAAYH,EACTG,IAAV,QAAuBF,EAASE,CAAQ,EAAIH,EAAOG,CAAQ,EAC9D,MAAMF,EAAWD,EAClB,OAAAA,EAASC,EAAS,IACX,CACL,SAAUL,EACV,KAAMG,EACN,IAAKG,EACL,IAAgBF,IAAX,OAAoBA,EAAS,KAClC,MAAOC,CACR,EAEa,OAAAG,EAAA,SAAGP,EACRO,EAAA,IAAGN,EACdM,EAAA,KAAeN,IC9BNO,EAAA,QAAUC,EAA+C,kBCAlE,SAASC,EAAoBC,EAA8C,CAClE,OAAAA,EAAS,OAAQC,GAAY,OAC9B,OAAAA,EAAQ,eAAiB,OACpBA,EAAQ,OAAS,QAAQC,EAAAD,EAAQ,OAAR,YAAAC,EAAc,UAAW,GAEpD,EAAA,CACR,CACH,CACA,SA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G,EAAiB,CAC/B,QAAA,IAAI,GAAG,KAAK,MAAM,MAAMlG,CAAO,GAAI,GAAGkG,CAAI,CAAA,CAGpD,KAAKlG,KAAoBkG,EAAiB,CAChC,QAAA,KAAK,GAAG,KAAK,MAAM,MAAMlG,CAAO,GAAI,GAAGkG,CAAI,CAAA,CAGrD,KAAKlG,KAAoBkG,EAAiB,CAChC,QAAA,KAAK,GAAG,KAAK,MAAM,MAAMlG,CAAO,GAAI,GAAGkG,CAAI,CAAA,CAGrD,MAAMlG,KAAoBkG,EAAiB,CACjC,QAAA,MAAM,GAAG,KAAK,MAAM,MAAMlG,CAAO,GAAI,GAAGkG,CAAI,CAAA,CAGtD,MAAMlG,KAAoBkG,EAAiB,CACjC,QAAA,MAAM,GAAG,KAAK,MAAM,MAAMlG,CAAO,GAAI,GAAGkG,CAAI,CAAA,CAExD","x_google_ignoreList":[0,1]}
|
|
1
|
+
{"version":3,"file":"bundle.cjs.js","sources":["../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/jsx-runtime.js","../src/messages.ts","../src/protocol/base.ts","../src/protocol/rest.ts","../src/protocol/websocket.ts","../src/protocol/webrtc.ts","../src/protocol/transaction.ts","../src/runtime.tsx","../src/logging.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import { PersonaMessage } from './types';\nimport { FileContentPart, ThreadMessageLike } from '@assistant-ui/react';\n\nfunction removeEmptyMessages(messages: PersonaMessage[]): PersonaMessage[] {\n return messages.filter((message) => {\n if (message.finishReason === 'stop') {\n return message.text !== null && message.text?.trim() !== '';\n }\n return true;\n });\n}\nfunction parseMessages(messages: PersonaMessage[]): PersonaMessage[] {\n const outputMessages: PersonaMessage[] = [];\n let currentMessage: PersonaMessage | null = null;\n\n for (const message of messages) {\n if (message.type === 'transaction') {\n continue;\n }\n if (message.type === 'reasoning') {\n if (currentMessage != null) {\n outputMessages.push(currentMessage);\n currentMessage = null;\n }\n outputMessages.push(message);\n } else if (message.functionCalls) {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n outputMessages.push(message);\n currentMessage = null;\n } else if (message.functionResponse) {\n outputMessages[outputMessages.length - 1] = {\n ...outputMessages[outputMessages.length - 1],\n functionResponse: message.functionResponse,\n };\n } else if (\n currentMessage &&\n message.protocol === currentMessage.protocol &&\n (currentMessage.role === message.role || message.finishReason === 'stop')\n ) {\n currentMessage.text += message.text;\n currentMessage.files = [...(currentMessage.files ?? []), ...(message.files ?? [])];\n } else {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n currentMessage = {\n ...message,\n };\n }\n }\n\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n const cleanMessages = removeEmptyMessages(outputMessages);\n return cleanMessages;\n}\n\nfunction convertMessage(message: PersonaMessage): ThreadMessageLike {\n const files =\n message.files?.map(\n (file) =>\n ({\n type: 'file',\n data: file.url,\n mimeType: file.contentType,\n } as FileContentPart),\n ) ?? [];\n if (message.role === 'function') {\n return {\n id: message.id!,\n role: 'assistant',\n status: message?.functionResponse === null ? { type: 'running' } : { type: 'complete', reason: 'stop' },\n content:\n message.functionCalls?.map((call) => ({\n type: 'tool-call',\n toolName: call.name,\n toolCallId: call.id,\n args: call.args,\n result: message.functionResponse?.result,\n })) ?? [],\n };\n }\n return {\n id: message.id!,\n role: message.role,\n content:\n message.type === 'reasoning'\n ? [{ type: 'reasoning', text: message.text }, ...files]\n : [{ type: 'text', text: message.text }, ...files],\n };\n}\n\nexport { parseMessages, convertMessage, removeEmptyMessages };\n","import {\n Message,\n MessageListenerCallback,\n PersonaPayload,\n PersonaProtocol,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n StatusChangeCallback,\n} from '../types';\n\nabstract class PersonaProtocolBase implements PersonaProtocol {\n abstract status: ProtocolStatus;\n abstract session: Session;\n abstract autostart: boolean;\n\n private statusChangeCallbacks: StatusChangeCallback[] = [];\n private messageCallbacks: MessageListenerCallback[] = [];\n\n public addStatusChangeListener(callback: StatusChangeCallback) {\n this.statusChangeCallbacks.push(callback);\n }\n\n public addMessageListener(callback: MessageListenerCallback) {\n this.messageCallbacks.push(callback);\n }\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async notifyMessage(message: PersonaPayload): Promise<void> {\n this.messageCallbacks.forEach((callback) => callback(message));\n }\n public async notifyMessages(messages: PersonaPayload[]): Promise<void> {\n messages.forEach((message) => {\n this.messageCallbacks.forEach((callback) => callback(message));\n });\n }\n\n public async setSession(session: Session): Promise<void> {\n this.session = session;\n }\n public async setStatus(status: ProtocolStatus): Promise<void> {\n const notify = this.status !== status;\n this.status = status;\n if (!notify) {\n return;\n }\n this.statusChangeCallbacks.forEach((callback) => callback(status));\n }\n\n public clearListeners(): void {\n this.statusChangeCallbacks = [];\n this.messageCallbacks = [];\n }\n\n abstract getName(): string;\n abstract getPriority(): number;\n abstract connect(session?: Session): Promise<Session>;\n abstract disconnect(): Promise<void>;\n abstract send(message: Message): Promise<void>;\n\n public onTransaction(_: PersonaTransaction) {}\n}\n\nexport { PersonaProtocolBase };\n","import { PersonaProtocolBase } from './base';\nimport { Message, PersonaResponse, Session, ProtocolStatus, PersonaProtocolBaseConfig } from '../types';\n\ntype PersonaRESTProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n};\n\nclass PersonaRESTProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaRESTProtocolConfig;\n notify: boolean = true;\n\n constructor(config: PersonaRESTProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'rest';\n }\n\n public getPriority(): number {\n return 0;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async send(message: Message): Promise<void> {\n const { apiUrl, apiKey, agentId } = this.config;\n const sessionId = this.session ?? 'new';\n const input = message;\n\n const response = await fetch(`${apiUrl}/agents/${agentId}/sessions/${sessionId}/messages`, {\n body: JSON.stringify({ userMessage: input }),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-fox-apikey': apiKey,\n 'x-persona-apikey': apiKey,\n },\n });\n const personaResponse = (await response.json()) as PersonaResponse;\n this.notifyMessages(\n personaResponse.response.messages.map((payload) => ({\n type: 'message',\n payload,\n })),\n );\n }\n}\n\nexport { PersonaRESTProtocol };\nexport type { PersonaRESTProtocolConfig };\n","import { Message, PersonaPayload, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\nimport { PersonaProtocolBase } from './base';\n\ntype PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {\n webSocketUrl: string;\n};\n\nclass PersonaWebSocketProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaWebSocketProtocolConfig;\n webSocket: WebSocket | null;\n\n constructor(config: PersonaWebSocketProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n this.session = null;\n this.webSocket = null;\n }\n\n public getName(): string {\n return 'websocket';\n }\n\n public getPriority(): number {\n return 1;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.config.logger?.debug('Syncing session with WebSocket protocol:', session);\n this.session = session;\n if (this.webSocket && this.status === 'connected') {\n this.disconnect();\n this.connect(session);\n }\n }\n\n public connect(session?: Session): Promise<Session> {\n if (this.webSocket !== null && this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n\n const sid = session || this.session || 'new';\n\n this.config.logger?.debug('Connecting to WebSocket with sessionId:', sid);\n\n const apiKey = encodeURIComponent(this.config.apiKey);\n const agentId = this.config.agentId;\n const webSocketUrl = `${this.config.webSocketUrl}?sessionCode=${sid}&agentId=${agentId}&apiKey=${apiKey}`;\n this.setStatus('connecting');\n this.webSocket = new WebSocket(webSocketUrl);\n this.webSocket.addEventListener('open', () => {\n this.setStatus('connected');\n });\n this.webSocket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data) as PersonaPayload;\n this.notifyMessage(data);\n });\n this.webSocket.addEventListener('close', () => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.warn('WebSocket connection closed');\n });\n\n this.webSocket.addEventListener('error', (error) => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.error('WebSocket error', error);\n\n // TODO: Implement reconnection logic\n });\n\n return Promise.resolve(sid);\n }\n\n public disconnect(): Promise<void> {\n this.config.logger?.debug('Disconnecting WebSocket');\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.close();\n this.setStatus('disconnected');\n this.webSocket = null;\n }\n return Promise.resolve();\n }\n\n public send(message: Message): Promise<void> {\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.send(JSON.stringify({ type: 'request', payload: message }));\n return Promise.resolve();\n } else {\n return Promise.reject(new Error('WebSocket is not connected'));\n }\n }\n}\n\nexport { PersonaWebSocketProtocol };\nexport type { PersonaWebSocketProtocolConfig };\n","import { PersonaProtocolBase } from './base';\nimport { Message, PersonaPayload, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\n\ntype AudioAnalysisData = {\n localAmplitude: number;\n remoteAmplitude: number;\n};\n\ntype AudioVisualizerCallback = (data: AudioAnalysisData) => void;\n\ntype PersonaWebRTCMessageCallback = (data: MessageEvent) => void;\n\ntype PersonaWebRTCConfig = PersonaProtocolBaseConfig & {\n webrtcUrl: string;\n iceServers?: RTCIceServer[];\n};\n\nclass PersonaWebRTCClient {\n private config: PersonaWebRTCConfig;\n private pc: RTCPeerConnection | null = null;\n private ws: WebSocket | null = null;\n private localStream: MediaStream | null = null;\n private remoteStream: MediaStream = new MediaStream();\n private audioCtx: AudioContext | null = null;\n\n private localAnalyser: AnalyserNode | null = null;\n private remoteAnalyser: AnalyserNode | null = null;\n private analyzerFrame: number | null = null;\n private dataChannel: RTCDataChannel | null = null;\n\n private isConnected: boolean = false;\n private visualizerCallbacks: AudioVisualizerCallback[] = [];\n private messageCallbacks: PersonaWebRTCMessageCallback[] = [];\n\n constructor(config: PersonaWebRTCConfig) {\n this.config = config;\n }\n\n public async connect(session: Session): Promise<Session> {\n if (this.isConnected) return;\n\n this.isConnected = true;\n\n try {\n this.localStream = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch (err) {\n this.config.logger?.error('Error accessing microphone:', err);\n return;\n }\n\n this.pc = new RTCPeerConnection({\n iceServers: this.config.iceServers || [\n {\n urls: 'stun:34.38.108.251:3478',\n },\n {\n urls: 'turn:34.38.108.251:3478',\n username: 'webrtc',\n credential: 'webrtc',\n },\n ],\n });\n\n this.localStream.getTracks().forEach((track) => {\n this.pc!.addTrack(track, this.localStream!);\n });\n\n this.pc.ontrack = (event) => {\n event.streams[0].getTracks().forEach((track) => {\n this.remoteStream.addTrack(track);\n });\n\n if (!this.audioCtx) {\n this._startAnalyzers();\n }\n\n const remoteAudio = new Audio();\n remoteAudio.srcObject = this.remoteStream;\n remoteAudio.play().catch((e) => {\n this.config.logger?.error('Error playing remote audio:', e);\n });\n };\n\n this.pc.onicecandidate = (event) => {\n if (event.candidate && this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(\n JSON.stringify({\n type: 'CANDIDATE',\n src: 'client',\n payload: { candidate: event.candidate },\n }),\n );\n }\n };\n\n this.pc.ondatachannel = (event) => {\n const channel = event.channel;\n channel.onmessage = (msg) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n };\n\n const url = this.config.webrtcUrl || 'wss://persona.applica.guru/api/webrtc';\n this.ws = new WebSocket(`${url}?apiKey=${encodeURIComponent(this.config.apiKey)}`);\n this.ws.onopen = async () => {\n const offer = await this.pc!.createOffer();\n await this.pc!.setLocalDescription(offer);\n\n const metadata = {\n apiKey: this.config.apiKey,\n agentId: this.config.agentId,\n sessionCode: session as string,\n };\n this.config.logger?.debug('Opening connection to WebRTC server: ', metadata);\n\n const offerMessage = {\n type: 'OFFER',\n src: crypto.randomUUID?.() || 'client_' + Date.now(),\n payload: {\n sdp: {\n sdp: offer.sdp,\n type: offer.type,\n },\n connectionId: (Date.now() % 1000000).toString(),\n metadata,\n },\n };\n\n this.ws!.send(JSON.stringify(offerMessage));\n };\n\n this.ws.onmessage = async (event) => {\n const data = JSON.parse(event.data);\n if (data.type === 'ANSWER') {\n await this.pc!.setRemoteDescription(new RTCSessionDescription(data.payload.sdp));\n } else if (data.type === 'CANDIDATE') {\n try {\n await this.pc!.addIceCandidate(new RTCIceCandidate(data.payload.candidate));\n } catch (err) {\n this.config.logger?.error('Error adding ICE candidate:', err);\n }\n }\n };\n\n this.ws.onclose = () => {\n this._stopAnalyzers();\n };\n }\n\n public async disconnect(): Promise<void> {\n if (!this.isConnected) return;\n\n this.isConnected = false;\n\n if (this.ws?.readyState === WebSocket.OPEN) this.ws.close();\n if (this.pc) this.pc.close();\n if (this.localStream) {\n this.localStream.getTracks().forEach((track) => track.stop());\n }\n\n this.remoteStream = new MediaStream();\n if (this.audioCtx) {\n await this.audioCtx.close();\n this.audioCtx = null;\n }\n\n this._stopAnalyzers();\n }\n\n public addVisualizerCallback(callback: AudioVisualizerCallback): void {\n this.visualizerCallbacks.push(callback);\n }\n public addMessageCallback(callback: PersonaWebRTCMessageCallback): void {\n this.messageCallbacks.push(callback);\n }\n\n public createDataChannel(label = 'messages'): void {\n if (!this.pc) return;\n this.dataChannel = this.pc.createDataChannel(label);\n this.dataChannel.onopen = () => this.config.logger?.info('Data channel opened');\n this.dataChannel.onmessage = (msg: MessageEvent) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n }\n\n public sendMessage(message: string): 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(message);\n this.config.logger?.info('Sent message:', message);\n }\n\n private _startAnalyzers(): void {\n if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();\n\n const localSource = this.audioCtx.createMediaStreamSource(this.localStream);\n const remoteSource = this.audioCtx.createMediaStreamSource(this.remoteStream);\n\n this.localAnalyser = this.audioCtx.createAnalyser();\n this.remoteAnalyser = this.audioCtx.createAnalyser();\n this.localAnalyser.fftSize = 256;\n this.remoteAnalyser.fftSize = 256;\n\n localSource.connect(this.localAnalyser);\n remoteSource.connect(this.remoteAnalyser);\n\n const loop = () => {\n if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n const localArray = new Uint8Array(this.localAnalyser.frequencyBinCount);\n const remoteArray = new Uint8Array(this.remoteAnalyser.frequencyBinCount);\n\n this.localAnalyser.getByteFrequencyData(localArray);\n this.remoteAnalyser.getByteFrequencyData(remoteArray);\n\n const localAmp = localArray.reduce((a, b) => a + b, 0) / localArray.length;\n const remoteAmp = remoteArray.reduce((a, b) => a + b, 0) / remoteArray.length;\n\n if (this.visualizerCallbacks.length > 0) {\n this.visualizerCallbacks.forEach((callback) => {\n callback({\n localAmplitude: localAmp,\n remoteAmplitude: remoteAmp,\n });\n });\n }\n\n this.analyzerFrame = requestAnimationFrame(loop);\n };\n\n this.analyzerFrame = requestAnimationFrame(loop);\n }\n\n private _stopAnalyzers(): void {\n if (this.analyzerFrame) {\n cancelAnimationFrame(this.analyzerFrame);\n this.analyzerFrame = null;\n }\n this.localAnalyser = null;\n this.remoteAnalyser = null;\n }\n}\n\ntype PersonaWebRTCProtocolConfig = PersonaWebRTCConfig & {\n autostart?: boolean;\n};\n\nclass PersonaWebRTCProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n session: Session;\n autostart: boolean;\n config: PersonaWebRTCProtocolConfig;\n webRTCClient: PersonaWebRTCClient;\n\n constructor(config: PersonaWebRTCProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.session = null;\n this.autostart = config?.autostart ?? false;\n this.webRTCClient = new PersonaWebRTCClient(config);\n this.webRTCClient.addMessageCallback((msg: MessageEvent) => {\n const data = JSON.parse(msg.data) as PersonaPayload;\n this.notifyMessage(data);\n });\n }\n\n public getName(): string {\n return 'webrtc';\n }\n public getPriority(): number {\n return 10;\n }\n\n public async syncSession(session: Session): Promise<void> {\n super.syncSession(session);\n if (this.status === 'connected') {\n await this.disconnect();\n await this.connect(session);\n }\n }\n\n public async connect(session?: Session): Promise<Session> {\n if (this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n this.session = session || this.session || 'new';\n this.setStatus('connecting');\n\n this.config.logger?.debug('Connecting to WebRTC with sessionId:', this.session);\n await this.webRTCClient.connect(this.session);\n this.setStatus('connected');\n\n await this.webRTCClient.createDataChannel();\n\n return this.session;\n }\n\n public async disconnect(): Promise<void> {\n if (this.status === 'disconnected') {\n this.config.logger?.warn('Already disconnected');\n return Promise.resolve();\n }\n\n await this.webRTCClient.disconnect();\n\n this.setStatus('disconnected');\n this.config?.logger?.debug('Disconnected from WebRTC');\n }\n\n public send(message: Message): Promise<void> {\n if (this.status !== 'connected') {\n return Promise.reject(new Error('Not connected'));\n }\n\n this.webRTCClient.sendMessage(message as string);\n return Promise.resolve();\n }\n}\n\nexport { PersonaWebRTCProtocol };\nexport type { PersonaWebRTCProtocolConfig, AudioVisualizerCallback, AudioAnalysisData };\n","import { PersonaProtocolBase } from './base';\nimport {\n Message,\n Session,\n ProtocolStatus,\n PersonaProtocolBaseConfig,\n PersonaTransaction,\n FunctionCall,\n ReadonlyJSONObject,\n} from '../types';\n\ntype FinishTransactionRequest = {\n success: boolean;\n output: any;\n error: string | null;\n};\n\nclass PersonaTransactionsManager {\n private config: PersonaTransactionProtocolConfig;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n this.config = config;\n }\n\n async complete(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: true });\n this.config.logger?.debug('Transaction completed:', transaction);\n }\n\n async fail(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: false });\n this.config.logger?.debug('Transaction failed:', { ...transaction, ...request });\n }\n\n async persist(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await fetch(`${this.config.apiUrl}/transactions/${transaction.id}`, {\n body: JSON.stringify(request),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-persona-apikey': this.config.apiKey,\n },\n });\n }\n}\n\nexport type PersonaToolCallback = (args: ReadonlyJSONObject | undefined) => void;\nexport type PersonaTools = {\n [key: string]: PersonaToolCallback;\n};\n\nclass PersonaPersistableTransaction {\n private transaction: PersonaTransaction;\n private manager: PersonaTransactionsManager;\n\n constructor(transaction: PersonaTransaction, manager: PersonaTransactionsManager) {\n this.transaction = transaction;\n this.manager = manager;\n }\n\n public getFunctionCall(): FunctionCall | null {\n return this.transaction.functionCall;\n }\n\n async invoke(tools: PersonaTools): Promise<void> {\n const functionCall = this.transaction.functionCall;\n if (!functionCall) {\n await this.fail('No function call found');\n return;\n }\n const functionName = functionCall.name;\n const functionArgs = functionCall.args;\n const tool = tools[functionName];\n if (!tool) {\n await this.fail(`Tool ${functionName} not found`);\n return;\n }\n try {\n const result = await tool(functionArgs);\n await this.complete({ date: new Date().toISOString(), result });\n } catch (error) {\n await this.fail(`Error executing tool ${functionName}: ${error}`);\n }\n }\n async complete(output: any): Promise<void> {\n await this.manager.complete(this.transaction, { success: true, output, error: null });\n }\n async fail(error: string): Promise<void> {\n await this.manager.fail(this.transaction, { success: false, output: null, error });\n }\n}\n\ntype PersonaTransactionCallback = (transaction: PersonaPersistableTransaction) => void;\n\ntype PersonaTransactionProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n onTransaction: PersonaTransactionCallback;\n};\n\nclass PersonaTransactionProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaTransactionProtocolConfig;\n notify: boolean = true;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'transaction';\n }\n\n public getPriority(): number {\n return 0;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async send(message: Message): Promise<void> {\n this.config.logger?.debug('Sending message:', message);\n throw new Error('Not implemented');\n }\n\n public onTransaction(transaction: PersonaTransaction): void {\n if (!this.config.onTransaction) {\n this.config.logger?.error('Transaction protocol config is not set');\n return;\n }\n const manager = new PersonaTransactionsManager(this.config);\n const persistable = new PersonaPersistableTransaction(transaction, manager);\n this.config.onTransaction(persistable);\n }\n}\n\nexport { PersonaTransactionProtocol };\nexport type { PersonaTransactionProtocolConfig, FinishTransactionRequest, PersonaPersistableTransaction, PersonaTransactionCallback };\n","import { useState, useEffect, useCallback, PropsWithChildren, createContext, useContext, useMemo, useRef } from 'react';\nimport { useExternalStoreRuntime, AppendMessage, AssistantRuntimeProvider } from '@assistant-ui/react';\nimport {\n PersonaConfig,\n PersonaMessage,\n PersonaPayload,\n PersonaProtocol,\n PersonaProtocolBaseConfig,\n PersonaResponse,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n} from './types';\nimport { parseMessages, convertMessage } from './messages';\nimport {\n PersonaPersistableTransaction,\n PersonaRESTProtocol,\n PersonaRESTProtocolConfig,\n PersonaTransactionProtocol,\n PersonaWebRTCProtocol,\n PersonaWebRTCProtocolConfig,\n PersonaWebSocketProtocol,\n PersonaWebSocketProtocolConfig,\n} from './protocol';\n\ntype PersonaRuntimeContextType = {\n protocols: PersonaProtocol[];\n protocolsStatus: Map<string, ProtocolStatus>;\n};\n\nconst PersonaRuntimeContext = createContext<PersonaRuntimeContextType | undefined>(undefined);\n\nfunction PersonaRuntimeProviderInner({\n dev = false,\n protocols: _protocols,\n logger,\n children,\n session: defaultSession = 'new',\n ...config\n}: Readonly<PersonaConfig>) {\n const [isRunning, setIsRunning] = useState(false);\n const [messages, setMessages] = useState<PersonaMessage[]>([]);\n const [session, setSession] = useState<Session>(defaultSession);\n const [protocolsStatus, setProtocolsStatus] = useState<Map<string, ProtocolStatus>>(new Map());\n const didMount = useRef(false);\n\n const protocols = useMemo<PersonaProtocol[]>(() => {\n if (Array.isArray(_protocols)) {\n return _protocols;\n }\n\n if (typeof _protocols === 'object' && _protocols !== null) {\n const baseEndpoint = dev ? 'localhost:8000' : 'persona.applica.guru/api';\n const baseEndpointProtocol = dev ? 'http' : 'https';\n const baseWebSocketProtocol = dev ? 'ws' : 'wss';\n let availableProtocols = Object.keys(_protocols).map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | true | undefined = _protocols[key];\n if (restConfig === true) {\n return new PersonaRESTProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n }\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | true | undefined = _protocols[key];\n if (webrtcConfig === true) {\n return new PersonaWebRTCProtocol({\n webrtcUrl: `${baseWebSocketProtocol}://${baseEndpoint}/webrtc`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n }\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | true | undefined = _protocols[key];\n if (websocketConfig === true) {\n return new PersonaWebSocketProtocol({\n webSocketUrl: `${baseWebSocketProtocol}://${baseEndpoint}/websocket`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n }\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n });\n\n if (config.tools) {\n availableProtocols.push(\n new PersonaTransactionProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n onTransaction: async (transaction: PersonaPersistableTransaction) => {\n await transaction.invoke(config.tools!);\n },\n logger,\n }),\n );\n }\n return availableProtocols;\n }\n throw new Error('Invalid protocols configuration');\n }, []);\n\n useEffect(() => {\n if (didMount.current) return;\n\n didMount.current = true;\n logger?.debug(\n 'Initializing protocols: ',\n protocols.map((protocol) => protocol.getName()),\n );\n protocols.forEach((protocol) => {\n protocol.setSession(session);\n protocol.clearListeners();\n protocol.addStatusChangeListener((status: ProtocolStatus) => {\n logger?.debug(`${protocol.getName()} has notified new status: ${status}`);\n protocolsStatus.set(protocol.getName(), status);\n setProtocolsStatus(new Map(protocolsStatus));\n });\n protocol.addMessageListener((message: PersonaPayload) => {\n if (message.type === 'message') {\n const personaMessage = message.payload as PersonaMessage;\n setMessages((currentConversation) =>\n parseMessages([...currentConversation, ...[{ ...personaMessage, protocol: protocol.getName() }]]),\n );\n } else if (message.type === 'transaction') {\n protocols.filter((p) => p !== protocol).forEach((p) => p.onTransaction(message.payload as PersonaTransaction));\n }\n });\n if (protocol.autostart && protocol.status === 'disconnected') {\n logger?.debug(`Connecting to protocol: ${protocol.getName()}`);\n protocol.connect(session);\n }\n });\n }, [session, protocols, logger, protocolsStatus]);\n\n const onNew = async (message: AppendMessage) => {\n if (message.content[0]?.type !== 'text') throw new Error('Only text messages are supported');\n\n const input = message.content[0].text;\n setMessages((currentConversation) => [...currentConversation, { role: 'user', type: 'text', text: input }]);\n setIsRunning(true);\n\n const protocol = protocols.sort((a, b) => b.getPriority() - a.getPriority()).find((protocol) => protocol.status === 'connected');\n\n await protocol?.send(input);\n\n setIsRunning(false);\n };\n\n const onCancel = useCallback(() => {\n setIsRunning(false);\n setMessages([]);\n setSession('new');\n return Promise.resolve();\n }, []);\n\n const onReload = useCallback(() => {\n return Promise.resolve();\n }, []);\n\n const runtime = useExternalStoreRuntime({\n isRunning,\n messages,\n convertMessage,\n onNew,\n onCancel,\n onReload,\n });\n\n return (\n <PersonaRuntimeContext.Provider value={{ protocols, protocolsStatus }}>\n <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>\n </PersonaRuntimeContext.Provider>\n );\n}\n\nfunction PersonaRuntimeProvider({ children, ...config }: PropsWithChildren<PersonaConfig>) {\n return <PersonaRuntimeProviderInner {...config}>{children}</PersonaRuntimeProviderInner>;\n}\n\nfunction usePersonaRuntime(): PersonaRuntimeContextType {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntime must be used within a PersonaRuntimeProvider');\n }\n return context;\n}\n\n/**\n * Retrieves a specific protocol instance from the PersonaRuntimeContext.\n *\n * @param protocol - The name of the protocol to use.\n * @returns {PersonaProtocol | null} - The protocol instance or null if not found.\n * @throws {Error} - If the hook is used outside of a PersonaRuntimeProvider.\n */\nfunction usePersonaRuntimeProtocol(protocol: string): PersonaProtocol | null {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider');\n }\n\n const protocolInstance = context.protocols.find((p) => p.getName() === protocol);\n if (!protocolInstance) {\n return null;\n }\n\n const status = context.protocolsStatus.get(protocolInstance.getName());\n\n return {\n ...protocolInstance,\n connect: protocolInstance.connect.bind(protocolInstance),\n disconnect: protocolInstance.disconnect.bind(protocolInstance),\n send: protocolInstance.send.bind(protocolInstance),\n setSession: protocolInstance.setSession.bind(protocolInstance),\n addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),\n addMessageListener: protocolInstance.addMessageListener.bind(protocolInstance),\n getName: protocolInstance.getName.bind(protocolInstance),\n getPriority: protocolInstance.getPriority.bind(protocolInstance),\n status: status || protocolInstance.status,\n };\n}\n\nfunction usePersonaRuntimeEndpoint(): string {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider');\n }\n for (const protocol of context.protocols) {\n if (protocol.getName() === 'rest') {\n return (protocol as PersonaRESTProtocol).config.apiUrl;\n }\n }\n throw new Error('REST protocol not found');\n}\n\nfunction usePersonaRuntimeWebRTCProtocol(): PersonaWebRTCProtocol | null {\n return usePersonaRuntimeProtocol('webrtc') as PersonaWebRTCProtocol;\n}\n\nexport { PersonaRuntimeProvider, usePersonaRuntimeEndpoint, usePersonaRuntime, usePersonaRuntimeProtocol, usePersonaRuntimeWebRTCProtocol };\nexport type { PersonaMessage, PersonaResponse };\n","interface PersonaLogger {\n log: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n}\n\nclass PersonaConsoleLogger implements PersonaLogger {\n prefix = '[Persona]';\n\n log(message: string, ...args: unknown[]) {\n console.log(`${this.prefix} - ${message}`, ...args);\n }\n\n info(message: string, ...args: unknown[]) {\n console.info(`${this.prefix} - ${message}`, ...args);\n }\n\n warn(message: string, ...args: unknown[]) {\n console.warn(`${this.prefix} - ${message}`, ...args);\n }\n\n error(message: string, ...args: unknown[]) {\n console.error(`${this.prefix} - ${message}`, ...args);\n }\n\n debug(message: string, ...args: unknown[]) {\n console.debug(`${this.prefix} - ${message}`, ...args);\n }\n}\n\nexport { PersonaConsoleLogger };\nexport type { PersonaLogger };\n"],"names":["REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","reactJsxRuntime_production","jsxRuntimeModule","require$$0","removeEmptyMessages","messages","message","_a","parseMessages","outputMessages","currentMessage","convertMessage","files","file","_b","call","PersonaProtocolBase","__publicField","callback","session","status","notify","_","PersonaRESTProtocol","apiUrl","apiKey","agentId","sessionId","input","personaResponse","payload","PersonaWebSocketProtocol","sid","webSocketUrl","event","data","error","PersonaWebRTCClient","err","track","remoteAudio","e","channel","msg","url","offer","metadata","offerMessage","label","localSource","remoteSource","loop","localArray","remoteArray","localAmp","a","b","remoteAmp","PersonaWebRTCProtocol","_c","PersonaTransactionsManager","transaction","request","PersonaPersistableTransaction","manager","tools","functionCall","functionName","functionArgs","tool","result","output","PersonaTransactionProtocol","persistable","PersonaRuntimeContext","createContext","PersonaRuntimeProviderInner","dev","_protocols","logger","children","defaultSession","isRunning","setIsRunning","useState","setMessages","setSession","protocolsStatus","setProtocolsStatus","didMount","useRef","protocols","useMemo","baseEndpoint","baseEndpointProtocol","baseWebSocketProtocol","availableProtocols","restConfig","webrtcConfig","websocketConfig","useEffect","protocol","personaMessage","currentConversation","p","onNew","onCancel","useCallback","onReload","runtime","useExternalStoreRuntime","jsx","AssistantRuntimeProvider","PersonaRuntimeProvider","usePersonaRuntime","context","useContext","usePersonaRuntimeProtocol","protocolInstance","usePersonaRuntimeEndpoint","usePersonaRuntimeWebRTCProtocol","PersonaCons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