@applica-software-guru/persona-sdk 0.1.67 → 0.1.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.es.js","sources":["../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/jsx-runtime.js","../src/messages.ts","../src/protocol/base.ts","../src/protocol/rest.ts","../src/protocol/websocket.ts","../src/protocol/webrtc.ts","../src/protocol/transaction.ts","../src/runtime.tsx","../src/logging.ts","../src/tools.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import { PersonaMessage } from './types';\nimport { FileContentPart, ThreadMessageLike } from '@assistant-ui/react';\n\nfunction removeEmptyMessages(messages: PersonaMessage[]): PersonaMessage[] {\n return messages.filter((message) => {\n if (message.finishReason === 'stop') {\n return message.text !== null && message.text?.trim() !== '';\n }\n return true;\n });\n}\nfunction parseMessages(messages: PersonaMessage[]): PersonaMessage[] {\n const outputMessages: PersonaMessage[] = [];\n let currentMessage: PersonaMessage | null = null;\n\n for (const message of messages) {\n if (message.type === 'transaction') {\n continue;\n }\n if (message.type === 'reasoning') {\n if (currentMessage != null) {\n outputMessages.push(currentMessage);\n currentMessage = null;\n }\n outputMessages.push(message);\n } else if (message.functionCalls) {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n outputMessages.push(message);\n currentMessage = null;\n } else if (message.functionResponse) {\n outputMessages[outputMessages.length - 1] = {\n ...outputMessages[outputMessages.length - 1],\n functionResponse: message.functionResponse,\n };\n } else if (\n currentMessage &&\n message.protocol === currentMessage.protocol &&\n (currentMessage.role === message.role || message.finishReason === 'stop')\n ) {\n currentMessage.text += message.text;\n currentMessage.files = [...(currentMessage.files ?? []), ...(message.files ?? [])];\n } else {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n currentMessage = {\n ...message,\n };\n }\n }\n\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n const cleanMessages = removeEmptyMessages(outputMessages);\n return cleanMessages;\n}\n\nfunction convertMessage(message: PersonaMessage): ThreadMessageLike {\n const files =\n message.files?.map(\n (file) =>\n ({\n type: 'file',\n data: file.url,\n mimeType: file.contentType,\n } as FileContentPart),\n ) ?? [];\n if (message.role === 'function') {\n return {\n id: message.id!,\n role: 'assistant',\n status: message?.functionResponse === null ? { type: 'running' } : { type: 'complete', reason: 'stop' },\n content:\n message.functionCalls?.map((call) => ({\n type: 'tool-call',\n toolName: call.name,\n toolCallId: call.id,\n args: call.args,\n result: message.functionResponse?.result,\n })) ?? [],\n };\n }\n return {\n id: message.id!,\n role: message.role,\n content:\n message.type === 'reasoning'\n ? [{ type: 'reasoning', text: message.text }, ...files]\n : [{ type: 'text', text: message.text }, ...files],\n };\n}\n\nexport { parseMessages, convertMessage, removeEmptyMessages };\n","import {\n MessageListenerCallback,\n PersonaPacket,\n PersonaProtocol,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n StatusChangeCallback,\n} from '../types';\n\nabstract class PersonaProtocolBase implements PersonaProtocol {\n abstract status: ProtocolStatus;\n abstract session: Session;\n abstract autostart: boolean;\n\n private statusChangeCallbacks: StatusChangeCallback[] = [];\n private messageCallbacks: MessageListenerCallback[] = [];\n\n public addStatusChangeListener(callback: StatusChangeCallback) {\n this.statusChangeCallbacks.push(callback);\n }\n\n public addPacketListener(callback: MessageListenerCallback) {\n this.messageCallbacks.push(callback);\n }\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async notifyPacket(message: PersonaPacket): Promise<void> {\n this.messageCallbacks.forEach((callback) => callback(message));\n }\n public async notifyPackets(messages: PersonaPacket[]): Promise<void> {\n messages.forEach((message) => {\n this.messageCallbacks.forEach((callback) => callback(message));\n });\n }\n\n public async setSession(session: Session): Promise<void> {\n this.session = session;\n }\n public async setStatus(status: ProtocolStatus): Promise<void> {\n const notify = this.status !== status;\n this.status = status;\n if (!notify) {\n return;\n }\n this.statusChangeCallbacks.forEach((callback) => callback(status));\n }\n\n public clearListeners(): void {\n this.statusChangeCallbacks = [];\n this.messageCallbacks = [];\n }\n\n abstract getName(): string;\n abstract getPriority(): number;\n abstract connect(session?: Session): Promise<Session>;\n abstract disconnect(): Promise<void>;\n abstract sendPacket(packet: PersonaPacket): Promise<void>;\n\n public onTransaction(_: PersonaTransaction) {}\n}\n\nexport { PersonaProtocolBase };\n","import { PersonaProtocolBase } from './base';\nimport {\n PersonaResponse,\n Session,\n ProtocolStatus,\n PersonaProtocolBaseConfig,\n PersonaMessage,\n PersonaPacket,\n PersonaCommand,\n} from '../types';\nimport { ToolInstance } from '../tools';\n\ntype PersonaRESTProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n};\n\nclass PersonaRESTProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaRESTProtocolConfig;\n notify: boolean = true;\n context: Record<string, any> = {};\n tools: ToolInstance[] = [];\n\n constructor(config: PersonaRESTProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'rest';\n }\n\n public getPriority(): number {\n return 100;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async sendPacket(packet: PersonaPacket): Promise<void> {\n const { apiUrl, apiKey, agentId } = this.config;\n const sessionId = this.session ?? 'new';\n if (packet.type === 'command' && (packet?.payload as PersonaCommand)?.command == 'set_initial_context') {\n this.context = (packet?.payload as PersonaCommand)?.arguments;\n return;\n } else if (packet.type === 'command' && (packet?.payload as PersonaCommand)?.command == 'set_local_tools') {\n this.notifyPacket({\n type: 'message',\n payload: {\n type: 'text',\n role: 'assistant',\n text: 'Local tools with rest protocol are not supported.',\n },\n });\n return;\n }\n const input = packet.payload as PersonaMessage;\n try {\n const response = await fetch(`${apiUrl}/sessions/${sessionId}/messages`, {\n body: JSON.stringify({ agentId, userMessage: input, initialContext: this.context, tools: this.tools }),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-persona-apikey': apiKey,\n },\n });\n const personaResponse = (await response.json()) as PersonaResponse;\n this.notifyPackets(\n personaResponse.response.messages.map((payload) => ({\n type: 'message',\n payload,\n })),\n );\n } catch (error) {\n this.notifyPacket({\n type: 'message',\n payload: {\n role: 'assistant',\n type: 'text',\n text: 'An error occurred while processing your request. Please try again later.',\n },\n });\n this.config.logger?.error('Error sending packet:', error);\n }\n }\n}\n\nexport { PersonaRESTProtocol };\nexport type { PersonaRESTProtocolConfig };\n","import { PersonaPacket, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\nimport { PersonaProtocolBase } from './base';\n\ntype PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {\n webSocketUrl: string;\n};\n\nclass PersonaWebSocketProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaWebSocketProtocolConfig;\n webSocket: WebSocket | null;\n\n constructor(config: PersonaWebSocketProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n this.session = null;\n this.webSocket = null;\n }\n\n public getName(): string {\n return 'websocket';\n }\n\n public getPriority(): number {\n return 500;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.config.logger?.debug('Syncing session with WebSocket protocol:', session);\n this.session = session;\n if (this.webSocket && this.status === 'connected') {\n this.disconnect();\n this.connect(session);\n }\n }\n\n public connect(session?: Session): Promise<Session> {\n if (this.webSocket !== null && this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n\n const sid = session || this.session || 'new';\n\n this.config.logger?.debug('Connecting to WebSocket with sessionId:', sid);\n\n const apiKey = encodeURIComponent(this.config.apiKey);\n const agentId = this.config.agentId;\n const webSocketUrl = `${this.config.webSocketUrl}?sessionCode=${sid}&agentId=${agentId}&apiKey=${apiKey}`;\n this.setStatus('connecting');\n this.webSocket = new WebSocket(webSocketUrl);\n this.webSocket.addEventListener('open', () => {\n this.setStatus('connected');\n });\n this.webSocket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data) as PersonaPacket;\n this.notifyPacket(data);\n });\n this.webSocket.addEventListener('close', (event: CloseEvent) => {\n this.setStatus('disconnected');\n this.webSocket = null;\n if (event.code !== 1000) {\n this.notifyPacket({\n type: 'message',\n payload: {\n role: 'assistant',\n type: 'text',\n text: 'Oops! The connection to the server was lost. Please try again later.',\n },\n });\n this.config.logger?.warn('WebSocket connection closed');\n }\n });\n\n this.webSocket.addEventListener('error', () => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.error('WebSocket connection error');\n });\n\n return Promise.resolve(sid);\n }\n\n public disconnect(): Promise<void> {\n this.config.logger?.debug('Disconnecting WebSocket');\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.close();\n this.setStatus('disconnected');\n this.webSocket = null;\n }\n return Promise.resolve();\n }\n\n public sendPacket(packet: PersonaPacket): Promise<void> {\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.send(JSON.stringify(packet));\n return Promise.resolve();\n } else {\n return Promise.reject(new Error('WebSocket is not connected'));\n }\n }\n}\n\nexport { PersonaWebSocketProtocol };\nexport type { PersonaWebSocketProtocolConfig };\n","import { PersonaProtocolBase } from './base';\nimport { PersonaPacket, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\n\ntype AudioAnalysisData = {\n localAmplitude: number;\n remoteAmplitude: number;\n};\n\ntype AudioVisualizerCallback = (data: AudioAnalysisData) => void;\n\ntype PersonaWebRTCMessageCallback = (data: MessageEvent) => void;\n\ntype PersonaWebRTCErrorCallback = (error: string) => void;\n\ntype PersonaWebRTCConfig = PersonaProtocolBaseConfig & {\n webrtcUrl: string;\n iceServers?: RTCIceServer[];\n};\n\nclass PersonaWebRTCClient {\n private config: PersonaWebRTCConfig;\n private pc: RTCPeerConnection | null = null;\n private ws: WebSocket | null = null;\n private localStream: MediaStream | null = null;\n private remoteStream: MediaStream = new MediaStream();\n private audioCtx: AudioContext | null = null;\n\n private localAnalyser: AnalyserNode | null = null;\n private remoteAnalyser: AnalyserNode | null = null;\n private analyzerFrame: number | null = null;\n private dataChannel: RTCDataChannel | null = null;\n\n private isConnected: boolean = false;\n private visualizerCallbacks: AudioVisualizerCallback[] = [];\n private messageCallbacks: PersonaWebRTCMessageCallback[] = [];\n private errorCallbacks: PersonaWebRTCErrorCallback[] = [];\n private queuedMessages: PersonaPacket[] = [];\n\n constructor(config: PersonaWebRTCConfig) {\n this.config = config;\n }\n\n public async connect(session: Session): Promise<Session> {\n if (this.isConnected) return;\n\n this.isConnected = true;\n\n try {\n this.localStream = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch (err) {\n this.config.logger?.error('Error accessing microphone:', err);\n return;\n }\n\n this.pc = new RTCPeerConnection({\n iceServers: this.config.iceServers || [\n {\n urls: 'stun:34.38.108.251:3478',\n },\n {\n urls: 'turn:34.38.108.251:3478',\n username: 'webrtc',\n credential: 'webrtc',\n },\n ],\n });\n\n this.localStream.getTracks().forEach((track) => {\n this.pc!.addTrack(track, this.localStream!);\n });\n\n this.pc.ontrack = (event) => {\n event.streams[0].getTracks().forEach((track) => {\n this.remoteStream.addTrack(track);\n });\n\n if (!this.audioCtx) {\n this._startAnalyzers();\n }\n\n const remoteAudio = new Audio();\n remoteAudio.srcObject = this.remoteStream;\n remoteAudio.play().catch((e) => {\n this.config.logger?.error('Error playing remote audio:', e);\n });\n };\n\n this.pc.onicecandidate = (event) => {\n if (event.candidate && this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(\n JSON.stringify({\n type: 'CANDIDATE',\n src: 'client',\n payload: { candidate: event.candidate },\n }),\n );\n }\n };\n\n this.pc.ondatachannel = (event) => {\n const channel = event.channel;\n channel.onmessage = (msg) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n channel.onopen = () => {\n while (this.queuedMessages.length > 0) {\n const packet = this.queuedMessages.shift();\n if (packet) {\n channel.send(JSON.stringify(packet));\n this.config.logger?.info('Sent queued message:', packet);\n }\n }\n };\n };\n\n const url = this.config.webrtcUrl || 'wss://persona.applica.guru/api/webrtc';\n this.ws = new WebSocket(`${url}?apiKey=${encodeURIComponent(this.config.apiKey)}`);\n this.ws.onopen = async () => {\n const offer = await this.pc!.createOffer();\n await this.pc!.setLocalDescription(offer);\n\n const metadata = {\n apiKey: this.config.apiKey,\n agentId: this.config.agentId,\n sessionCode: session as string,\n };\n this.config.logger?.debug('Opening connection to WebRTC server: ', metadata);\n\n const offerMessage = {\n type: 'OFFER',\n src: crypto.randomUUID?.() || 'client_' + Date.now(),\n payload: {\n sdp: {\n sdp: offer.sdp,\n type: offer.type,\n },\n connectionId: (Date.now() % 1000000).toString(),\n metadata,\n },\n };\n\n this.ws!.send(JSON.stringify(offerMessage));\n };\n\n this.ws.onmessage = async (event) => {\n const data = JSON.parse(event.data);\n if (data.type === 'ANSWER') {\n await this.pc!.setRemoteDescription(new RTCSessionDescription(data.payload.sdp));\n } else if (data.type === 'CANDIDATE') {\n try {\n await this.pc!.addIceCandidate(new RTCIceCandidate(data.payload.candidate));\n } catch (err) {\n this.config.logger?.error('Error adding ICE candidate:', err);\n }\n }\n };\n\n this.ws.onclose = (event: CloseEvent) => {\n if (event.code !== 1000) {\n this.errorCallbacks.forEach((callback) => {\n callback('Oops! The connection to the server was lost. Please try again later.');\n });\n }\n this._stopAnalyzers();\n };\n }\n\n public async disconnect(): Promise<void> {\n if (!this.isConnected) return;\n\n this.isConnected = false;\n\n if (this.ws?.readyState === WebSocket.OPEN) this.ws.close();\n if (this.pc) this.pc.close();\n if (this.localStream) {\n this.localStream.getTracks().forEach((track) => track.stop());\n }\n\n this.remoteStream = new MediaStream();\n if (this.audioCtx) {\n await this.audioCtx.close();\n this.audioCtx = null;\n }\n\n this._stopAnalyzers();\n }\n\n public addVisualizerCallback(callback: AudioVisualizerCallback): void {\n this.visualizerCallbacks.push(callback);\n }\n public addMessageCallback(callback: PersonaWebRTCMessageCallback): void {\n this.messageCallbacks.push(callback);\n }\n\n public addErrorCallback(callback: PersonaWebRTCErrorCallback): void {\n this.errorCallbacks.push(callback);\n }\n\n public createDataChannel(label = 'messages'): void {\n if (!this.pc) return;\n this.dataChannel = this.pc.createDataChannel(label);\n this.dataChannel.onopen = () => {\n this.config.logger?.info('Data channel opened');\n while (this.queuedMessages.length > 0) {\n const packet = this.queuedMessages.shift();\n if (packet) {\n this.dataChannel!.send(JSON.stringify(packet));\n this.config.logger?.info('Sent queued message:', packet);\n }\n }\n };\n this.dataChannel.onmessage = (msg: MessageEvent) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n }\n\n public sendPacket(packet: PersonaPacket): void {\n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n this.queuedMessages.push(packet);\n return;\n }\n\n this.dataChannel.send(JSON.stringify(packet));\n this.config.logger?.info('Sent message:', packet);\n }\n\n private _startAnalyzers(): void {\n if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();\n\n const localSource = this.audioCtx.createMediaStreamSource(this.localStream);\n const remoteSource = this.audioCtx.createMediaStreamSource(this.remoteStream);\n\n this.localAnalyser = this.audioCtx.createAnalyser();\n this.remoteAnalyser = this.audioCtx.createAnalyser();\n this.localAnalyser.fftSize = 256;\n this.remoteAnalyser.fftSize = 256;\n\n localSource.connect(this.localAnalyser);\n remoteSource.connect(this.remoteAnalyser);\n\n const loop = () => {\n if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n const localArray = new Uint8Array(this.localAnalyser.frequencyBinCount);\n const remoteArray = new Uint8Array(this.remoteAnalyser.frequencyBinCount);\n\n this.localAnalyser.getByteFrequencyData(localArray);\n this.remoteAnalyser.getByteFrequencyData(remoteArray);\n\n const localAmp = localArray.reduce((a, b) => a + b, 0) / localArray.length;\n const remoteAmp = remoteArray.reduce((a, b) => a + b, 0) / remoteArray.length;\n\n if (this.visualizerCallbacks.length > 0) {\n this.visualizerCallbacks.forEach((callback) => {\n callback({\n localAmplitude: localAmp,\n remoteAmplitude: remoteAmp,\n });\n });\n }\n\n this.analyzerFrame = requestAnimationFrame(loop);\n };\n\n this.analyzerFrame = requestAnimationFrame(loop);\n }\n\n private _stopAnalyzers(): void {\n if (this.analyzerFrame) {\n cancelAnimationFrame(this.analyzerFrame);\n this.analyzerFrame = null;\n }\n this.localAnalyser = null;\n this.remoteAnalyser = null;\n }\n}\n\ntype PersonaWebRTCProtocolConfig = PersonaWebRTCConfig & {\n autostart?: boolean;\n};\n\nclass PersonaWebRTCProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n session: Session;\n autostart: boolean;\n config: PersonaWebRTCProtocolConfig;\n webRTCClient: PersonaWebRTCClient;\n\n constructor(config: PersonaWebRTCProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.session = null;\n this.autostart = config?.autostart ?? false;\n this.webRTCClient = new PersonaWebRTCClient(config);\n this.webRTCClient.addMessageCallback((msg: MessageEvent) => {\n const data = JSON.parse(msg.data) as PersonaPacket;\n this.notifyPacket(data);\n });\n this.webRTCClient.addErrorCallback((error: string) => {\n this.config.logger?.error('WebRTC error:', error);\n this.notifyPacket({\n type: 'message',\n payload: {\n type: 'text',\n role: 'assistant',\n text: error,\n },\n });\n });\n }\n\n public getName(): string {\n return 'webrtc';\n }\n public getPriority(): number {\n return 1000;\n }\n\n public async syncSession(session: Session): Promise<void> {\n super.syncSession(session);\n if (this.status === 'connected') {\n await this.disconnect();\n await this.connect(session);\n }\n }\n\n public async connect(session?: Session): Promise<Session> {\n if (this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n this.session = session || this.session || 'new';\n this.setStatus('connecting');\n\n this.config.logger?.debug('Connecting to WebRTC with sessionId:', this.session);\n await this.webRTCClient.connect(this.session);\n this.setStatus('connected');\n\n await this.webRTCClient.createDataChannel();\n\n return this.session;\n }\n\n public async disconnect(): Promise<void> {\n if (this.status === 'disconnected') {\n this.config.logger?.warn('Already disconnected');\n return Promise.resolve();\n }\n\n await this.webRTCClient.disconnect();\n\n this.setStatus('disconnected');\n this.config?.logger?.debug('Disconnected from WebRTC');\n }\n\n public sendPacket(packet: PersonaPacket): Promise<void> {\n if (this.status !== 'connected') {\n return Promise.reject(new Error('Not connected'));\n }\n\n this.webRTCClient.sendPacket(packet);\n return Promise.resolve();\n }\n}\n\nexport { PersonaWebRTCProtocol };\nexport type { PersonaWebRTCProtocolConfig, AudioVisualizerCallback, AudioAnalysisData };\n","import { PersonaProtocolBase } from './base';\nimport { Session, ProtocolStatus, PersonaProtocolBaseConfig, PersonaTransaction, FunctionCall, PersonaPacket } from '../types';\nimport { ToolInstance } from '../tools';\n\ntype FinishTransactionRequest = {\n success: boolean;\n output: any;\n error: string | null;\n};\n\nclass PersonaTransactionsManager {\n private config: PersonaTransactionProtocolConfig;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n this.config = config;\n }\n\n async complete(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: true });\n this.config.logger?.debug('Transaction completed:', transaction);\n }\n\n async fail(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: false });\n this.config.logger?.debug('Transaction failed:', { ...transaction, ...request });\n }\n\n async persist(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await fetch(`${this.config.apiUrl}/transactions/${transaction.id}`, {\n body: JSON.stringify(request),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-persona-apikey': this.config.apiKey,\n },\n });\n }\n}\n\nexport type PersonaToolCallback = (...args: any[]) => void | Record<string, any> | Promise<void | Record<string, any>>;\nexport type PersonaTools = {\n [key: string]: PersonaToolCallback;\n};\n\nclass PersonaPersistableTransaction {\n private transaction: PersonaTransaction;\n private manager: PersonaTransactionsManager;\n\n constructor(transaction: PersonaTransaction, manager: PersonaTransactionsManager) {\n this.transaction = transaction;\n this.manager = manager;\n }\n\n public getFunctionCall(): FunctionCall | null {\n return this.transaction.functionCall;\n }\n\n async invoke(tools: PersonaTools): Promise<void> {\n const functionCall = this.transaction.functionCall;\n if (!functionCall) {\n await this.fail('No function call found');\n return;\n }\n const functionName = functionCall.name;\n const functionArgs = functionCall.args;\n const tool = tools[functionName];\n if (!tool) {\n await this.fail(`Tool ${functionName} not found`);\n return;\n }\n try {\n // Get parameter names in order\n const paramNames =\n tool\n .toString()\n .replace(/\\n/g, ' ')\n .match(/^[^(]*\\(([^)]*)\\)/)?.[1]\n .split(',')\n .map((p: string) => p.trim())\n .filter(Boolean) || [];\n // Map arguments in order\n const orderedArgs = paramNames.map((name: string) => functionArgs[name]);\n const result = await tool.apply(null, orderedArgs);\n await this.complete(result);\n } catch (error) {\n await this.fail(`Error executing tool ${functionName}: ${error}`);\n }\n }\n async complete(output: any): Promise<void> {\n await this.manager.complete(this.transaction, { success: true, output, error: null });\n }\n async fail(error: string): Promise<void> {\n await this.manager.fail(this.transaction, { success: false, output: null, error });\n }\n}\n\ntype PersonaTransactionCallback = (transaction: PersonaPersistableTransaction) => void;\n\ntype PersonaTransactionProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n tools: PersonaTools | ToolInstance[];\n onTransaction?: PersonaTransactionCallback;\n};\n\nclass PersonaTransactionProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaTransactionProtocolConfig;\n notify: boolean = true;\n private _tools: PersonaTools;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n if (Array.isArray(config.tools)) {\n this._tools = {};\n for (const tool of config.tools as ToolInstance[]) {\n if (tool.schema && tool.implementation) {\n this._tools[tool.schema.name] = tool.implementation;\n }\n }\n } else {\n this._tools = config.tools as PersonaTools;\n }\n }\n\n public getName(): string {\n return 'transaction';\n }\n\n public getPriority(): number {\n return 0;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async sendPacket(_: PersonaPacket): Promise<void> {}\n\n public onTransaction(transaction: PersonaTransaction): void {\n console.log('transaction received:', transaction);\n const manager = new PersonaTransactionsManager(this.config);\n const persistable = new PersonaPersistableTransaction(transaction, manager);\n if (this.config.onTransaction) {\n this.config.onTransaction(persistable);\n } else {\n persistable.invoke(this._tools);\n }\n }\n\n public getTools(): PersonaTools {\n return this._tools;\n }\n}\n\nexport { PersonaTransactionProtocol };\nexport type { PersonaTransactionProtocolConfig, FinishTransactionRequest, PersonaPersistableTransaction, PersonaTransactionCallback };\n","import { useState, useEffect, useCallback, PropsWithChildren, createContext, useContext, useMemo, useRef } from 'react';\nimport {\n useExternalStoreRuntime,\n AppendMessage,\n AssistantRuntimeProvider,\n CompositeAttachmentAdapter,\n SimpleImageAttachmentAdapter,\n} from '@assistant-ui/react';\nimport {\n PersonaConfig,\n PersonaMessage,\n PersonaPacket,\n PersonaProtocol,\n PersonaProtocolBaseConfig,\n PersonaReasoning,\n PersonaResponse,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n} from './types';\nimport { parseMessages, convertMessage } from './messages';\nimport {\n PersonaRESTProtocol,\n PersonaRESTProtocolConfig,\n PersonaTransactionProtocol,\n PersonaWebRTCProtocol,\n PersonaWebRTCProtocolConfig,\n PersonaWebSocketProtocol,\n PersonaWebSocketProtocolConfig,\n} from './protocol';\n\ntype PersonaRuntimeContextType = {\n protocols: PersonaProtocol[];\n protocolsStatus: Map<string, ProtocolStatus>;\n getMessages: () => PersonaMessage[];\n};\n\nconst PersonaRuntimeContext = createContext<PersonaRuntimeContextType | undefined>(undefined);\n\nfunction fileToBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.readAsDataURL(file); // Converte il file in Data URL (base64)\n\n reader.onload = () => {\n //remove data url using ;base64, to split\n const base64 = reader.result as string;\n const base64WithoutPrefix = base64.split(';base64,')[1];\n resolve(base64WithoutPrefix);\n };\n\n reader.onerror = (error) => {\n reject(error);\n };\n });\n}\n\nfunction PersonaRuntimeProviderInner({\n dev = false,\n baseUrl,\n protocols: _protocols,\n logger,\n children,\n session: defaultSession = 'new',\n ...config\n}: Readonly<PersonaConfig>) {\n const [isRunning, setIsRunning] = useState(false);\n const [messages, setMessages] = useState<PersonaMessage[]>([]);\n const [session, setSession] = useState<Session>(defaultSession);\n const [protocolsStatus, setProtocolsStatus] = useState<Map<string, ProtocolStatus>>(new Map());\n const didMount = useRef(false);\n\n const protocols = useMemo<PersonaProtocol[]>(() => {\n if (Array.isArray(_protocols)) {\n return _protocols;\n }\n\n if (typeof _protocols === 'object' && _protocols !== null) {\n const baseEndpoint = dev ? 'localhost:8000' : baseUrl || 'persona.applica.guru/api';\n const baseEndpointProtocol = dev ? 'http' : 'https';\n const baseWebSocketProtocol = dev ? 'ws' : 'wss';\n let availableProtocols = Object.keys(_protocols)\n .map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (restConfig === true) {\n return new PersonaRESTProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof restConfig === 'object' && restConfig !== null) {\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n } else {\n return null;\n }\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (webrtcConfig === true) {\n return new PersonaWebRTCProtocol({\n webrtcUrl: `${baseWebSocketProtocol}://${baseEndpoint}/webrtc`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof webrtcConfig === 'object' && webrtcConfig !== null) {\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n } else {\n return null;\n }\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (websocketConfig === true) {\n return new PersonaWebSocketProtocol({\n webSocketUrl: `${baseWebSocketProtocol}://${baseEndpoint}/websocket`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof websocketConfig === 'object' && websocketConfig !== null) {\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n } else {\n return null;\n }\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n })\n .filter((protocol) => protocol !== null) as PersonaProtocol[];\n\n if (config.tools) {\n availableProtocols.push(\n new PersonaTransactionProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n tools: config.tools, // Pass raw tools\n logger,\n }),\n );\n }\n return availableProtocols;\n }\n throw new Error('Invalid protocols configuration');\n }, []);\n\n useEffect(() => {\n if (didMount.current) return;\n\n didMount.current = true;\n logger?.debug(\n 'Initializing protocols: ',\n protocols.map((protocol) => protocol.getName()),\n );\n protocols.forEach((protocol) => {\n protocol.setSession(session);\n protocol.clearListeners();\n protocol.addStatusChangeListener((status: ProtocolStatus) => {\n logger?.debug(`${protocol.getName()} has notified new status: ${status}`);\n protocolsStatus.set(protocol.getName(), status);\n if (status === 'connected') {\n if (config.context) {\n protocol.sendPacket({\n type: 'command',\n payload: {\n command: 'set_initial_context',\n arguments: config.context,\n },\n });\n }\n if (config.tools && Array.isArray(config.tools)) {\n protocol.sendPacket({\n type: 'command',\n payload: {\n command: 'set_local_tools',\n arguments: {\n tools: config.tools.map((tool) => tool.schema),\n },\n },\n });\n }\n }\n setProtocolsStatus(new Map(protocolsStatus));\n });\n protocol.addPacketListener((message: PersonaPacket) => {\n if (message.type === 'message') {\n const personaMessage = message.payload as PersonaMessage;\n setMessages((currentConversation) =>\n parseMessages([...currentConversation, ...[{ ...personaMessage, protocol: protocol.getName() }]]),\n );\n } else if (message.type === 'reasoning') {\n const personaReasoning = message.payload as PersonaReasoning;\n\n let text = personaReasoning.thought;\n if (personaReasoning.imageUrl) {\n // add markdown image\n text += `\\n\\n![image](https://persona.applica.guru/api/files/${personaReasoning.imageUrl})`;\n }\n const personaMessage: PersonaMessage = { type: 'reasoning', text: text, role: 'assistant', finishReason: 'stop' };\n\n setMessages((currentConversation) =>\n parseMessages([...currentConversation, ...[{ ...personaMessage, protocol: protocol.getName() }]]),\n );\n } else if (message.type === 'transaction') {\n protocols.filter((p) => p !== protocol).forEach((p) => p.onTransaction(message.payload as PersonaTransaction));\n }\n });\n if (protocol.autostart && protocol.status === 'disconnected') {\n logger?.debug(`Connecting to protocol: ${protocol.getName()}`);\n protocol.connect(session);\n }\n });\n }, [session, protocols, logger, protocolsStatus]);\n\n const onNew = async (message: AppendMessage) => {\n if (message.content[0]?.type !== 'text') throw new Error('Only text messages are supported');\n\n const input = message.content[0].text;\n setMessages((currentConversation) => [...currentConversation, { role: 'user', type: 'text', text: input }]);\n setIsRunning(true);\n\n const protocol = protocols.sort((a, b) => b.getPriority() - a.getPriority()).find((protocol) => protocol.status === 'connected');\n const content: Array<PersonaMessage> = [];\n if (message.attachments) {\n for (const attachment of message.attachments) {\n if (attachment.contentType.startsWith('image/') && attachment.file) {\n content.push({\n role: 'user',\n image: {\n contentType: attachment.contentType,\n content: await fileToBase64(attachment.file),\n },\n text: '',\n type: 'text',\n });\n }\n }\n }\n\n if (message.content) {\n content.push({\n role: 'user',\n text: message.content[0].text,\n type: 'text',\n });\n }\n logger?.debug('Sending message:', content);\n await protocol?.sendPacket({ type: 'request', payload: content });\n\n setIsRunning(false);\n };\n\n const onCancel = useCallback(() => {\n setIsRunning(false);\n setMessages([]);\n setSession('new');\n return Promise.resolve();\n }, []);\n\n const onReload = useCallback(() => {\n return Promise.resolve();\n }, []);\n\n const getMessages = useCallback(() => {\n return messages;\n }, [messages]);\n\n const runtime = useExternalStoreRuntime({\n isRunning,\n messages,\n convertMessage,\n onNew,\n onCancel,\n onReload,\n adapters: {\n attachments: new CompositeAttachmentAdapter([new SimpleImageAttachmentAdapter()]),\n },\n });\n\n return (\n <PersonaRuntimeContext.Provider value={{ protocols, protocolsStatus, getMessages }}>\n <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>\n </PersonaRuntimeContext.Provider>\n );\n}\n\nfunction PersonaRuntimeProvider({ children, ...config }: PropsWithChildren<PersonaConfig>) {\n return <PersonaRuntimeProviderInner {...config}>{children}</PersonaRuntimeProviderInner>;\n}\n\nfunction usePersonaRuntime(): PersonaRuntimeContextType {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntime must be used within a PersonaRuntimeProvider');\n }\n return context;\n}\n\n/**\n * Retrieves a specific protocol instance from the PersonaRuntimeContext.\n *\n * @param protocol - The name of the protocol to use.\n * @returns {PersonaProtocol | null} - The protocol instance or null if not found.\n * @throws {Error} - If the hook is used outside of a PersonaRuntimeProvider.\n */\nfunction usePersonaRuntimeProtocol(protocol: string): PersonaProtocol | null {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider');\n }\n\n const protocolInstance = context.protocols.find((p) => p.getName() === protocol);\n if (!protocolInstance) {\n return null;\n }\n\n const status = context.protocolsStatus.get(protocolInstance.getName());\n\n return {\n ...protocolInstance,\n connect: protocolInstance.connect.bind(protocolInstance),\n disconnect: protocolInstance.disconnect.bind(protocolInstance),\n sendPacket: protocolInstance.sendPacket.bind(protocolInstance),\n setSession: protocolInstance.setSession.bind(protocolInstance),\n addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),\n addPacketListener: protocolInstance.addPacketListener.bind(protocolInstance),\n getName: protocolInstance.getName.bind(protocolInstance),\n getPriority: protocolInstance.getPriority.bind(protocolInstance),\n status: status || protocolInstance.status,\n };\n}\n\nfunction usePersonaRuntimeEndpoint(): string {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider');\n }\n for (const protocol of context.protocols) {\n if (protocol.getName() === 'rest') {\n return (protocol as PersonaRESTProtocol).config.apiUrl;\n }\n }\n throw new Error('REST protocol not found');\n}\n\nfunction usePersonaRuntimeWebRTCProtocol(): PersonaWebRTCProtocol | null {\n return usePersonaRuntimeProtocol('webrtc') as PersonaWebRTCProtocol;\n}\n\nfunction usePersonaRuntimeMessages(): PersonaMessage[] {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider');\n }\n return context.getMessages();\n}\n\nexport {\n PersonaRuntimeProvider,\n usePersonaRuntimeEndpoint,\n usePersonaRuntime,\n usePersonaRuntimeProtocol,\n usePersonaRuntimeWebRTCProtocol,\n usePersonaRuntimeMessages,\n};\nexport type { PersonaMessage, PersonaResponse };\n","interface PersonaLogger {\n log: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n}\n\nclass PersonaConsoleLogger implements PersonaLogger {\n prefix = '[Persona]';\n\n log(message: string, ...args: unknown[]) {\n console.log(`${this.prefix} - ${message}`, ...args);\n }\n\n info(message: string, ...args: unknown[]) {\n console.info(`${this.prefix} - ${message}`, ...args);\n }\n\n warn(message: string, ...args: unknown[]) {\n console.warn(`${this.prefix} - ${message}`, ...args);\n }\n\n error(message: string, ...args: unknown[]) {\n console.error(`${this.prefix} - ${message}`, ...args);\n }\n\n debug(message: string, ...args: unknown[]) {\n console.debug(`${this.prefix} - ${message}`, ...args);\n }\n}\n\nexport { PersonaConsoleLogger };\nexport type { PersonaLogger };\n","export type ToolParameterType = 'string' | 'number' | 'boolean' | 'object' | 'array';\n\nexport interface ToolParameter {\n type: ToolParameterType;\n description: string;\n required?: boolean;\n properties?: Record<string, ToolParameter>;\n items?: ToolParameter;\n}\n\nexport interface ToolSchema {\n type: 'local';\n name: string;\n description: string;\n config: {\n timeout: number;\n parameters: {\n type: 'object';\n title: string;\n required: string[];\n properties: Record<string, ToolParameter>;\n };\n output: {\n type: 'object';\n title: string;\n properties: Record<string, ToolParameter>;\n };\n };\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n title?: string;\n timeout?: number;\n parameters: Record<string, ToolParameter>;\n output: Record<string, ToolParameter>;\n implementation: (...args: any[]) => any;\n}\n\n/**\n * Create a tool parameter definition\n */\nexport function createParameter(\n type: ToolParameterType,\n description: string,\n options?: {\n required?: boolean;\n properties?: Record<string, ToolParameter>;\n items?: ToolParameter;\n },\n): ToolParameter {\n return {\n type,\n description,\n ...options,\n };\n}\n\n/**\n * Generate a tool schema from a tool definition\n */\nexport function generateToolSchema(definition: ToolDefinition): ToolSchema {\n const requiredParams = Object.entries(definition.parameters)\n .filter(([_, param]) => param.required)\n .map(([name]) => name);\n\n return {\n type: 'local',\n name: definition.name,\n description: definition.description,\n config: {\n timeout: definition.timeout || 60,\n parameters: {\n type: 'object',\n title: definition.title || `${definition.name} parameters`,\n required: requiredParams,\n properties: definition.parameters,\n },\n output: {\n type: 'object',\n title: `${definition.name} output`,\n properties: definition.output,\n },\n },\n };\n}\n\nexport type ToolInstance = { schema: ToolSchema; implementation: (...args: any[]) => any };\n\n/**\n * Create a complete tool definition with schema and implementation\n */\nexport function createTool(definition: ToolDefinition): ToolInstance {\n return {\n schema: generateToolSchema(definition),\n implementation: definition.implementation,\n };\n}\n\n/**\n * Extract function signature and generate schema from a JavaScript function\n * This is a utility to help convert existing functions to tool schemas\n */\nexport function createToolFromFunction(\n name: string,\n description: string,\n fn: (...args: any[]) => any,\n parameterTypes: Record<string, ToolParameter>,\n outputTypes: Record<string, ToolParameter>,\n options?: {\n title?: string;\n timeout?: number;\n },\n): ToolInstance {\n const definition: ToolDefinition = {\n name,\n description,\n title: options?.title,\n timeout: options?.timeout,\n parameters: parameterTypes,\n output: outputTypes,\n implementation: fn,\n };\n\n return createTool(definition);\n}\n\n// Example usage for the sum function you provided:\nexport const sumTool = createToolFromFunction(\n 'sum',\n 'Sum two numbers',\n function sum(a: number, b: number) {\n const result = a + b;\n return { result };\n },\n {\n a: createParameter('number', 'First number to sum', { required: true }),\n b: createParameter('number', 'Second number to sum', { required: true }),\n },\n {\n result: createParameter('number', 'Sum of two numbers'),\n },\n);\n\n// Example for the navigate_to function as shown in the user's request:\nexport const navigateToToolExample = createTool({\n name: 'navigate_to',\n description: 'Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that',\n title: 'Sum two numbers', // As per the user's example\n timeout: 60,\n parameters: {\n a: createParameter('number', 'First number to sum'),\n b: createParameter('number', 'Seconth number to sum'), // Keeping the typo as in the original\n },\n output: {\n result: createParameter('number', 'Sum of two numbers'),\n },\n implementation: function navigateTo(a: number, b: number) {\n // This is just an example - you would implement actual navigation logic here\n const result = a + b;\n return { result };\n },\n});\n\n// Helper function to create multiple tools at once\nexport function createToolRegistry(tools: ToolDefinition[]): {\n schemas: ToolSchema[];\n implementations: Record<string, (...args: any[]) => any>;\n} {\n const schemas: ToolSchema[] = [];\n const implementations: Record<string, (...args: any[]) => any> = {};\n\n tools.forEach((tool) => {\n const { schema, implementation } = createTool(tool);\n schemas.push(schema);\n implementations[tool.name] = implementation;\n });\n\n return { schemas, implementations };\n}\n\n// Utility to validate tool parameters at runtime\nexport function validateToolParameters(parameters: Record<string, any>, schema: ToolSchema): boolean {\n const { required, properties } = schema.config.parameters;\n\n // Check required parameters\n for (const requiredParam of required) {\n if (!(requiredParam in parameters)) {\n throw new Error(`Missing required parameter: ${requiredParam}`);\n }\n }\n\n // Type checking (basic)\n for (const [paramName, paramValue] of Object.entries(parameters)) {\n const paramSchema = properties[paramName];\n if (paramSchema) {\n if (paramSchema.type === 'number' && typeof paramValue !== 'number') {\n throw new Error(`Parameter ${paramName} should be a number`);\n }\n if (paramSchema.type === 'string' && typeof paramValue !== 'string') {\n throw new Error(`Parameter ${paramName} should be a string`);\n }\n if (paramSchema.type === 'boolean' && typeof paramValue !== 'boolean') {\n throw new Error(`Parameter ${paramName} should be a boolean`);\n }\n }\n }\n\n return true;\n}\n"],"names":["REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","reactJsxRuntime_production","jsxRuntimeModule","require$$0","removeEmptyMessages","messages","message","_a","parseMessages","outputMessages","currentMessage","convertMessage","files","file","_b","call","PersonaProtocolBase","__publicField","callback","session","status","notify","_","PersonaRESTProtocol","packet","apiUrl","apiKey","agentId","sessionId","_c","input","personaResponse","payload","error","_d","PersonaWebSocketProtocol","sid","webSocketUrl","event","data","PersonaWebRTCClient","err","track","remoteAudio","e","channel","msg","url","offer","metadata","offerMessage","label","localSource","remoteSource","loop","localArray","remoteArray","localAmp","a","b","remoteAmp","PersonaWebRTCProtocol","PersonaTransactionsManager","transaction","request","PersonaPersistableTransaction","manager","tools","functionCall","functionName","functionArgs","tool","orderedArgs","p","name","result","output","PersonaTransactionProtocol","persistable","PersonaRuntimeContext","createContext","fileToBase64","resolve","reject","reader","base64WithoutPrefix","PersonaRuntimeProviderInner","dev","baseUrl","_protocols","logger","children","defaultSession","isRunning","setIsRunning","useState","setMessages","setSession","protocolsStatus","setProtocolsStatus","didMount","useRef","protocols","useMemo","baseEndpoint","baseEndpointProtocol","baseWebSocketProtocol","availableProtocols","restConfig","webrtcConfig","websocketConfig","protocol","useEffect","personaMessage","currentConversation","personaReasoning","text","onNew","content","attachment","onCancel","useCallback","onReload","getMessages","runtime","useExternalStoreRuntime","CompositeAttachmentAdapter","SimpleImageAttachmentAdapter","jsx","AssistantRuntimeProvider","PersonaRuntimeProvider","usePersonaRuntime","context","useContext","usePersonaRuntimeProtocol","protocolInstance","usePersonaRuntimeEndpoint","usePersonaRuntimeWebRTCProtocol","usePersonaRuntimeMessages","PersonaConsoleLogger","args","createParameter","description","options","generateToolSchema","definition","requiredParams","param","createTool","createToolFromFunction","fn","parameterTypes","outputTypes","sumTool","navigateToToolExample","createToolRegistry","schemas","implementations","schema","implementation","validateToolParameters","parameters","required","properties","requiredParam","paramName","paramValue","paramSchema"],"mappings":";;;;;;;;;;;;;;;;;;;AAWA,MAAIA,IAAqB,OAAO,IAAI,4BAA4B,GAC9DC,IAAsB,OAAO,IAAI,gBAAgB;AACnD,WAASC,EAAQC,GAAMC,GAAQC,GAAU;AACvC,QAAIC,IAAM;AAGV,QAFWD,MAAX,WAAwBC,IAAM,KAAKD,IACxBD,EAAO,QAAlB,WAA0BE,IAAM,KAAKF,EAAO,MACxC,SAASA,GAAQ;AACnB,MAAAC,IAAW,CAAE;AACb,eAASE,KAAYH;AACnB,QAAU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["../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/jsx-runtime.js","../src/messages.ts","../src/protocol/base.ts","../src/protocol/rest.ts","../src/protocol/websocket.ts","../src/protocol/webrtc.ts","../src/protocol/transaction.ts","../src/runtime.tsx","../src/logging.ts","../src/tools.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import { PersonaMessage } from './types';\nimport { FileContentPart, ThreadMessageLike } from '@assistant-ui/react';\n\nfunction removeEmptyMessages(messages: PersonaMessage[]): PersonaMessage[] {\n return messages.filter((message) => {\n if (message.finishReason === 'stop') {\n return message.text !== null && message.text?.trim() !== '';\n }\n return true;\n });\n}\nfunction parseMessages(messages: PersonaMessage[]): PersonaMessage[] {\n const outputMessages: PersonaMessage[] = [];\n let currentMessage: PersonaMessage | null = null;\n\n for (const message of messages) {\n if (message.type === 'transaction') {\n continue;\n }\n if (message.type === 'reasoning') {\n if (currentMessage != null) {\n outputMessages.push(currentMessage);\n currentMessage = null;\n }\n outputMessages.push(message);\n } else if (message.functionCalls) {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n outputMessages.push(message);\n currentMessage = null;\n } else if (message.functionResponse) {\n outputMessages[outputMessages.length - 1] = {\n ...outputMessages[outputMessages.length - 1],\n functionResponse: message.functionResponse,\n };\n } else if (\n currentMessage &&\n message.protocol === currentMessage.protocol &&\n (currentMessage.role === message.role || message.finishReason === 'stop')\n ) {\n currentMessage.text += message.text;\n currentMessage.files = [...(currentMessage.files ?? []), ...(message.files ?? [])];\n } else {\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n currentMessage = {\n ...message,\n };\n }\n }\n\n if (currentMessage) {\n outputMessages.push(currentMessage);\n }\n const cleanMessages = removeEmptyMessages(outputMessages);\n return cleanMessages;\n}\n\nfunction convertMessage(message: PersonaMessage): ThreadMessageLike {\n const files =\n message.files?.map(\n (file) =>\n ({\n type: 'file',\n data: file.url,\n mimeType: file.contentType,\n } as FileContentPart),\n ) ?? [];\n if (message.role === 'function') {\n return {\n id: message.id!,\n role: 'assistant',\n status: message?.functionResponse === null ? { type: 'running' } : { type: 'complete', reason: 'stop' },\n content:\n message.functionCalls?.map((call) => ({\n type: 'tool-call',\n toolName: call.name,\n toolCallId: call.id,\n args: call.args,\n result: message.functionResponse?.result,\n })) ?? [],\n };\n }\n return {\n id: message.id!,\n role: message.role,\n content:\n message.type === 'reasoning'\n ? [{ type: 'reasoning', text: message.text }, ...files]\n : [{ type: 'text', text: message.text }, ...files],\n };\n}\n\nexport { parseMessages, convertMessage, removeEmptyMessages };\n","import {\n MessageListenerCallback,\n PersonaPacket,\n PersonaProtocol,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n StatusChangeCallback,\n} from '../types';\n\nabstract class PersonaProtocolBase implements PersonaProtocol {\n abstract status: ProtocolStatus;\n abstract session: Session;\n abstract autostart: boolean;\n\n private statusChangeCallbacks: StatusChangeCallback[] = [];\n private messageCallbacks: MessageListenerCallback[] = [];\n\n public addStatusChangeListener(callback: StatusChangeCallback) {\n this.statusChangeCallbacks.push(callback);\n }\n\n public addPacketListener(callback: MessageListenerCallback) {\n this.messageCallbacks.push(callback);\n }\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async notifyPacket(message: PersonaPacket): Promise<void> {\n this.messageCallbacks.forEach((callback) => callback(message));\n }\n public async notifyPackets(messages: PersonaPacket[]): Promise<void> {\n messages.forEach((message) => {\n this.messageCallbacks.forEach((callback) => callback(message));\n });\n }\n\n public async setSession(session: Session): Promise<void> {\n this.session = session;\n }\n public async setStatus(status: ProtocolStatus): Promise<void> {\n const notify = this.status !== status;\n this.status = status;\n if (!notify) {\n return;\n }\n this.statusChangeCallbacks.forEach((callback) => callback(status));\n }\n\n public clearListeners(): void {\n this.statusChangeCallbacks = [];\n this.messageCallbacks = [];\n }\n\n abstract getName(): string;\n abstract getPriority(): number;\n abstract connect(session?: Session): Promise<Session>;\n abstract disconnect(): Promise<void>;\n abstract sendPacket(packet: PersonaPacket): Promise<void>;\n\n public onTransaction(_: PersonaTransaction) {}\n}\n\nexport { PersonaProtocolBase };\n","import { PersonaProtocolBase } from './base';\nimport {\n PersonaResponse,\n Session,\n ProtocolStatus,\n PersonaProtocolBaseConfig,\n PersonaMessage,\n PersonaPacket,\n PersonaCommand,\n} from '../types';\nimport { ToolInstance } from '../tools';\n\ntype PersonaRESTProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n};\n\nclass PersonaRESTProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaRESTProtocolConfig;\n notify: boolean = true;\n context: Record<string, any> = {};\n tools: ToolInstance[] = [];\n\n constructor(config: PersonaRESTProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n }\n\n public getName(): string {\n return 'rest';\n }\n\n public getPriority(): number {\n return 100;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async sendPacket(packet: PersonaPacket): Promise<void> {\n const { apiUrl, apiKey, agentId } = this.config;\n const sessionId = this.session ?? 'new';\n if (packet.type === 'command' && (packet?.payload as PersonaCommand)?.command == 'set_initial_context') {\n this.context = (packet?.payload as PersonaCommand)?.arguments;\n return;\n } else if (packet.type === 'command' && (packet?.payload as PersonaCommand)?.command == 'set_local_tools') {\n this.notifyPacket({\n type: 'message',\n payload: {\n type: 'text',\n role: 'assistant',\n text: 'Local tools with rest protocol are not supported.',\n },\n });\n return;\n }\n const input = packet.payload as PersonaMessage;\n try {\n const response = await fetch(`${apiUrl}/sessions/${sessionId}/messages`, {\n body: JSON.stringify({ agentId, userMessage: input, initialContext: this.context, tools: this.tools }),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-persona-apikey': apiKey,\n },\n });\n const personaResponse = (await response.json()) as PersonaResponse;\n this.notifyPackets(\n personaResponse.response.messages.map((payload) => ({\n type: 'message',\n payload,\n })),\n );\n } catch (error) {\n this.notifyPacket({\n type: 'message',\n payload: {\n role: 'assistant',\n type: 'text',\n text: 'An error occurred while processing your request. Please try again later.',\n },\n });\n this.config.logger?.error('Error sending packet:', error);\n }\n }\n}\n\nexport { PersonaRESTProtocol };\nexport type { PersonaRESTProtocolConfig };\n","import { PersonaPacket, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\nimport { PersonaProtocolBase } from './base';\n\ntype PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {\n webSocketUrl: string;\n};\n\nclass PersonaWebSocketProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaWebSocketProtocolConfig;\n webSocket: WebSocket | null;\n\n constructor(config: PersonaWebSocketProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n this.session = null;\n this.webSocket = null;\n }\n\n public getName(): string {\n return 'websocket';\n }\n\n public getPriority(): number {\n return 500;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.config.logger?.debug('Syncing session with WebSocket protocol:', session);\n this.session = session;\n if (this.webSocket && this.status === 'connected') {\n this.disconnect();\n this.connect(session);\n }\n }\n\n public connect(session?: Session): Promise<Session> {\n if (this.webSocket !== null && this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n\n const sid = session || this.session || 'new';\n\n this.config.logger?.debug('Connecting to WebSocket with sessionId:', sid);\n\n const apiKey = encodeURIComponent(this.config.apiKey);\n const agentId = this.config.agentId;\n const webSocketUrl = `${this.config.webSocketUrl}?sessionCode=${sid}&agentId=${agentId}&apiKey=${apiKey}`;\n this.setStatus('connecting');\n this.webSocket = new WebSocket(webSocketUrl);\n this.webSocket.addEventListener('open', () => {\n this.setStatus('connected');\n });\n this.webSocket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data) as PersonaPacket;\n this.notifyPacket(data);\n });\n this.webSocket.addEventListener('close', (event: CloseEvent) => {\n this.setStatus('disconnected');\n this.webSocket = null;\n if (event.code !== 1000) {\n this.notifyPacket({\n type: 'message',\n payload: {\n role: 'assistant',\n type: 'text',\n text: 'Oops! The connection to the server was lost. Please try again later.',\n },\n });\n this.config.logger?.warn('WebSocket connection closed');\n }\n });\n\n this.webSocket.addEventListener('error', () => {\n this.setStatus('disconnected');\n this.webSocket = null;\n this.config.logger?.error('WebSocket connection error');\n });\n\n return Promise.resolve(sid);\n }\n\n public disconnect(): Promise<void> {\n this.config.logger?.debug('Disconnecting WebSocket');\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.close();\n this.setStatus('disconnected');\n this.webSocket = null;\n }\n return Promise.resolve();\n }\n\n public sendPacket(packet: PersonaPacket): Promise<void> {\n if (this.webSocket && this.status === 'connected') {\n this.webSocket.send(JSON.stringify(packet));\n return Promise.resolve();\n } else {\n return Promise.reject(new Error('WebSocket is not connected'));\n }\n }\n}\n\nexport { PersonaWebSocketProtocol };\nexport type { PersonaWebSocketProtocolConfig };\n","import { PersonaProtocolBase } from './base';\nimport { PersonaPacket, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';\n\ntype AudioAnalysisData = {\n localAmplitude: number;\n remoteAmplitude: number;\n};\n\ntype AudioVisualizerCallback = (data: AudioAnalysisData) => void;\n\ntype PersonaWebRTCMessageCallback = (data: MessageEvent) => void;\n\ntype PersonaWebRTCErrorCallback = (error: string) => void;\n\ntype PersonaWebRTCConfig = PersonaProtocolBaseConfig & {\n webrtcUrl: string;\n iceServers?: RTCIceServer[];\n};\n\nclass PersonaWebRTCClient {\n private config: PersonaWebRTCConfig;\n private pc: RTCPeerConnection | null = null;\n private ws: WebSocket | null = null;\n private localStream: MediaStream | null = null;\n private remoteStream: MediaStream = new MediaStream();\n private audioCtx: AudioContext | null = null;\n\n private localAnalyser: AnalyserNode | null = null;\n private remoteAnalyser: AnalyserNode | null = null;\n private analyzerFrame: number | null = null;\n private dataChannel: RTCDataChannel | null = null;\n\n private isConnected: boolean = false;\n private visualizerCallbacks: AudioVisualizerCallback[] = [];\n private messageCallbacks: PersonaWebRTCMessageCallback[] = [];\n private errorCallbacks: PersonaWebRTCErrorCallback[] = [];\n private queuedMessages: PersonaPacket[] = [];\n\n constructor(config: PersonaWebRTCConfig) {\n this.config = config;\n }\n\n public async connect(session: Session): Promise<Session> {\n if (this.isConnected) return;\n\n this.isConnected = true;\n\n try {\n this.localStream = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch (err) {\n this.config.logger?.error('Error accessing microphone:', err);\n return;\n }\n\n this.pc = new RTCPeerConnection({\n iceServers: this.config.iceServers || [\n {\n urls: 'stun:34.38.108.251:3478',\n },\n {\n urls: 'turn:34.38.108.251:3478',\n username: 'webrtc',\n credential: 'webrtc',\n },\n ],\n });\n\n this.localStream.getTracks().forEach((track) => {\n this.pc!.addTrack(track, this.localStream!);\n });\n\n this.pc.ontrack = (event) => {\n event.streams[0].getTracks().forEach((track) => {\n this.remoteStream.addTrack(track);\n });\n\n if (!this.audioCtx) {\n this._startAnalyzers();\n }\n\n const remoteAudio = new Audio();\n remoteAudio.srcObject = this.remoteStream;\n remoteAudio.play().catch((e) => {\n this.config.logger?.error('Error playing remote audio:', e);\n });\n };\n\n this.pc.onicecandidate = (event) => {\n if (event.candidate && this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(\n JSON.stringify({\n type: 'CANDIDATE',\n src: 'client',\n payload: { candidate: event.candidate },\n }),\n );\n }\n };\n\n this.pc.ondatachannel = (event) => {\n const channel = event.channel;\n channel.onmessage = (msg) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n channel.onopen = () => {\n while (this.queuedMessages.length > 0) {\n const packet = this.queuedMessages.shift();\n if (packet) {\n channel.send(JSON.stringify(packet));\n this.config.logger?.info('Sent queued message:', packet);\n }\n }\n };\n };\n\n const url = this.config.webrtcUrl || 'wss://persona.applica.guru/api/webrtc';\n this.ws = new WebSocket(`${url}?apiKey=${encodeURIComponent(this.config.apiKey)}`);\n this.ws.onopen = async () => {\n const offer = await this.pc!.createOffer();\n await this.pc!.setLocalDescription(offer);\n\n const metadata = {\n apiKey: this.config.apiKey,\n agentId: this.config.agentId,\n sessionCode: session as string,\n };\n this.config.logger?.debug('Opening connection to WebRTC server: ', metadata);\n\n const offerMessage = {\n type: 'OFFER',\n src: crypto.randomUUID?.() || 'client_' + Date.now(),\n payload: {\n sdp: {\n sdp: offer.sdp,\n type: offer.type,\n },\n connectionId: (Date.now() % 1000000).toString(),\n metadata,\n },\n };\n\n this.ws!.send(JSON.stringify(offerMessage));\n };\n\n this.ws.onmessage = async (event) => {\n const data = JSON.parse(event.data);\n if (data.type === 'ANSWER') {\n await this.pc!.setRemoteDescription(new RTCSessionDescription(data.payload.sdp));\n } else if (data.type === 'CANDIDATE') {\n try {\n await this.pc!.addIceCandidate(new RTCIceCandidate(data.payload.candidate));\n } catch (err) {\n this.config.logger?.error('Error adding ICE candidate:', err);\n }\n }\n };\n\n this.ws.onclose = (event: CloseEvent) => {\n if (event.code !== 1000) {\n this.errorCallbacks.forEach((callback) => {\n callback('Oops! The connection to the server was lost. Please try again later.');\n });\n }\n this._stopAnalyzers();\n };\n }\n\n public async disconnect(): Promise<void> {\n if (!this.isConnected) return;\n\n this.isConnected = false;\n\n if (this.ws?.readyState === WebSocket.OPEN) this.ws.close();\n if (this.pc) this.pc.close();\n if (this.localStream) {\n this.localStream.getTracks().forEach((track) => track.stop());\n }\n\n this.remoteStream = new MediaStream();\n if (this.audioCtx) {\n await this.audioCtx.close();\n this.audioCtx = null;\n }\n\n this._stopAnalyzers();\n }\n\n public addVisualizerCallback(callback: AudioVisualizerCallback): void {\n this.visualizerCallbacks.push(callback);\n }\n public addMessageCallback(callback: PersonaWebRTCMessageCallback): void {\n this.messageCallbacks.push(callback);\n }\n\n public addErrorCallback(callback: PersonaWebRTCErrorCallback): void {\n this.errorCallbacks.push(callback);\n }\n\n public createDataChannel(label = 'messages'): void {\n if (!this.pc) return;\n this.dataChannel = this.pc.createDataChannel(label);\n this.dataChannel.onopen = () => {\n this.config.logger?.info('Data channel opened');\n while (this.queuedMessages.length > 0) {\n const packet = this.queuedMessages.shift();\n if (packet) {\n this.dataChannel!.send(JSON.stringify(packet));\n this.config.logger?.info('Sent queued message:', packet);\n }\n }\n };\n this.dataChannel.onmessage = (msg: MessageEvent) => {\n this.messageCallbacks.forEach((callback) => {\n callback(msg);\n });\n };\n }\n\n public sendPacket(packet: PersonaPacket): void {\n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n this.queuedMessages.push(packet);\n return;\n }\n\n this.dataChannel.send(JSON.stringify(packet));\n this.config.logger?.info('Sent message:', packet);\n }\n\n private _startAnalyzers(): void {\n if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();\n\n const localSource = this.audioCtx.createMediaStreamSource(this.localStream);\n const remoteSource = this.audioCtx.createMediaStreamSource(this.remoteStream);\n\n this.localAnalyser = this.audioCtx.createAnalyser();\n this.remoteAnalyser = this.audioCtx.createAnalyser();\n this.localAnalyser.fftSize = 256;\n this.remoteAnalyser.fftSize = 256;\n\n localSource.connect(this.localAnalyser);\n remoteSource.connect(this.remoteAnalyser);\n\n const loop = () => {\n if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0) {\n return;\n }\n\n const localArray = new Uint8Array(this.localAnalyser.frequencyBinCount);\n const remoteArray = new Uint8Array(this.remoteAnalyser.frequencyBinCount);\n\n this.localAnalyser.getByteFrequencyData(localArray);\n this.remoteAnalyser.getByteFrequencyData(remoteArray);\n\n const localAmp = localArray.reduce((a, b) => a + b, 0) / localArray.length;\n const remoteAmp = remoteArray.reduce((a, b) => a + b, 0) / remoteArray.length;\n\n if (this.visualizerCallbacks.length > 0) {\n this.visualizerCallbacks.forEach((callback) => {\n callback({\n localAmplitude: localAmp,\n remoteAmplitude: remoteAmp,\n });\n });\n }\n\n this.analyzerFrame = requestAnimationFrame(loop);\n };\n\n this.analyzerFrame = requestAnimationFrame(loop);\n }\n\n private _stopAnalyzers(): void {\n if (this.analyzerFrame) {\n cancelAnimationFrame(this.analyzerFrame);\n this.analyzerFrame = null;\n }\n this.localAnalyser = null;\n this.remoteAnalyser = null;\n }\n}\n\ntype PersonaWebRTCProtocolConfig = PersonaWebRTCConfig & {\n autostart?: boolean;\n};\n\nclass PersonaWebRTCProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n session: Session;\n autostart: boolean;\n config: PersonaWebRTCProtocolConfig;\n webRTCClient: PersonaWebRTCClient;\n\n constructor(config: PersonaWebRTCProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.session = null;\n this.autostart = config?.autostart ?? false;\n this.webRTCClient = new PersonaWebRTCClient(config);\n this.webRTCClient.addMessageCallback((msg: MessageEvent) => {\n const data = JSON.parse(msg.data) as PersonaPacket;\n this.notifyPacket(data);\n });\n this.webRTCClient.addErrorCallback((error: string) => {\n this.config.logger?.error('WebRTC error:', error);\n this.notifyPacket({\n type: 'message',\n payload: {\n type: 'text',\n role: 'assistant',\n text: error,\n },\n });\n });\n }\n\n public getName(): string {\n return 'webrtc';\n }\n public getPriority(): number {\n return 1000;\n }\n\n public async syncSession(session: Session): Promise<void> {\n super.syncSession(session);\n if (this.status === 'connected') {\n await this.disconnect();\n await this.connect(session);\n }\n }\n\n public async connect(session?: Session): Promise<Session> {\n if (this.status === 'connected') {\n return Promise.resolve(this.session);\n }\n this.session = session || this.session || 'new';\n this.setStatus('connecting');\n\n this.config.logger?.debug('Connecting to WebRTC with sessionId:', this.session);\n await this.webRTCClient.connect(this.session);\n this.setStatus('connected');\n\n await this.webRTCClient.createDataChannel();\n\n return this.session;\n }\n\n public async disconnect(): Promise<void> {\n if (this.status === 'disconnected') {\n this.config.logger?.warn('Already disconnected');\n return Promise.resolve();\n }\n\n await this.webRTCClient.disconnect();\n\n this.setStatus('disconnected');\n this.config?.logger?.debug('Disconnected from WebRTC');\n }\n\n public sendPacket(packet: PersonaPacket): Promise<void> {\n if (this.status !== 'connected') {\n return Promise.reject(new Error('Not connected'));\n }\n\n this.webRTCClient.sendPacket(packet);\n return Promise.resolve();\n }\n}\n\nexport { PersonaWebRTCProtocol };\nexport type { PersonaWebRTCProtocolConfig, AudioVisualizerCallback, AudioAnalysisData };\n","import { PersonaProtocolBase } from './base';\nimport { Session, ProtocolStatus, PersonaProtocolBaseConfig, PersonaTransaction, FunctionCall, PersonaPacket } from '../types';\nimport { ToolInstance } from '../tools';\n\ntype FinishTransactionRequest = {\n success: boolean;\n output: any;\n error: string | null;\n};\n\nclass PersonaTransactionsManager {\n private config: PersonaTransactionProtocolConfig;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n this.config = config;\n }\n\n async complete(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: true });\n this.config.logger?.debug('Transaction completed:', transaction);\n }\n\n async fail(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await this.persist(transaction, { ...request, success: false });\n this.config.logger?.debug('Transaction failed:', { ...transaction, ...request });\n }\n\n async persist(transaction: PersonaTransaction, request: FinishTransactionRequest): Promise<void> {\n await fetch(`${this.config.apiUrl}/transactions/${transaction.id}`, {\n body: JSON.stringify(request),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-persona-apikey': this.config.apiKey,\n },\n });\n }\n}\n\nexport type PersonaToolCallback = (...args: any[]) => void | Record<string, any> | Promise<void | Record<string, any>>;\nexport type PersonaTools = {\n [key: string]: PersonaToolCallback;\n};\n\nclass PersonaPersistableTransaction {\n private transaction: PersonaTransaction;\n private manager: PersonaTransactionsManager;\n\n constructor(transaction: PersonaTransaction, manager: PersonaTransactionsManager) {\n this.transaction = transaction;\n this.manager = manager;\n }\n\n public getFunctionCall(): FunctionCall | null {\n return this.transaction.functionCall;\n }\n\n async invoke(tools: PersonaTools): Promise<void> {\n const functionCall = this.transaction.functionCall;\n if (!functionCall) {\n await this.fail('No function call found');\n return;\n }\n const functionName = functionCall.name;\n const functionArgs = functionCall.args;\n const tool = tools[functionName];\n if (!tool) {\n await this.fail(`Tool ${functionName} not found`);\n return;\n }\n try {\n // Get parameter names in order\n const paramNames =\n tool\n .toString()\n .replace(/\\n/g, ' ')\n .match(/^[^(]*\\(([^)]*)\\)/)?.[1]\n .split(',')\n .map((p: string) => p.trim())\n .filter(Boolean) || [];\n // Map arguments in order\n const orderedArgs = paramNames.map((name: string) => functionArgs[name]);\n const result = await tool.apply(null, orderedArgs);\n await this.complete(result);\n } catch (error) {\n await this.fail(`Error executing tool ${functionName}: ${error}`);\n }\n }\n async complete(output: any): Promise<void> {\n await this.manager.complete(this.transaction, { success: true, output, error: null });\n }\n async fail(error: string): Promise<void> {\n await this.manager.fail(this.transaction, { success: false, output: null, error });\n }\n}\n\ntype PersonaTransactionCallback = (transaction: PersonaPersistableTransaction) => void;\n\ntype PersonaTransactionProtocolConfig = PersonaProtocolBaseConfig & {\n apiUrl: string;\n tools: PersonaTools | ToolInstance[];\n onTransaction?: PersonaTransactionCallback;\n};\n\nclass PersonaTransactionProtocol extends PersonaProtocolBase {\n status: ProtocolStatus;\n autostart: boolean;\n session: Session;\n config: PersonaTransactionProtocolConfig;\n notify: boolean = true;\n private _tools: PersonaTools;\n\n constructor(config: PersonaTransactionProtocolConfig) {\n super();\n this.config = config;\n this.status = 'disconnected';\n this.autostart = true;\n if (Array.isArray(config.tools)) {\n this._tools = {};\n for (const tool of config.tools as ToolInstance[]) {\n if (tool.schema && tool.implementation) {\n this._tools[tool.schema.name] = tool.implementation;\n }\n }\n } else {\n this._tools = config.tools as PersonaTools;\n }\n }\n\n public getName(): string {\n return 'transaction';\n }\n\n public getPriority(): number {\n return 0;\n }\n\n public async connect(session: Session): Promise<Session> {\n this.setStatus('connected');\n return session;\n }\n\n public async disconnect(): Promise<void> {\n this.setStatus('disconnected');\n this.session = null;\n }\n\n public async syncSession(session: Session): Promise<void> {\n this.session = session;\n }\n\n public async sendPacket(_: PersonaPacket): Promise<void> {}\n\n public onTransaction(transaction: PersonaTransaction): void {\n console.log('transaction received:', transaction);\n const manager = new PersonaTransactionsManager(this.config);\n const persistable = new PersonaPersistableTransaction(transaction, manager);\n if (this.config.onTransaction) {\n this.config.onTransaction(persistable);\n } else {\n persistable.invoke(this._tools);\n }\n }\n\n public getTools(): PersonaTools {\n return this._tools;\n }\n}\n\nexport { PersonaTransactionProtocol };\nexport type { PersonaTransactionProtocolConfig, FinishTransactionRequest, PersonaPersistableTransaction, PersonaTransactionCallback };\n","import { useState, useEffect, useCallback, PropsWithChildren, createContext, useContext, useMemo, useRef } from 'react';\nimport {\n useExternalStoreRuntime,\n AppendMessage,\n AssistantRuntimeProvider,\n CompositeAttachmentAdapter,\n SimpleImageAttachmentAdapter,\n} from '@assistant-ui/react';\nimport {\n PersonaConfig,\n PersonaMessage,\n PersonaPacket,\n PersonaProtocol,\n PersonaProtocolBaseConfig,\n PersonaReasoning,\n PersonaResponse,\n PersonaTransaction,\n ProtocolStatus,\n Session,\n} from './types';\nimport { parseMessages, convertMessage } from './messages';\nimport {\n PersonaRESTProtocol,\n PersonaRESTProtocolConfig,\n PersonaTransactionProtocol,\n PersonaWebRTCProtocol,\n PersonaWebRTCProtocolConfig,\n PersonaWebSocketProtocol,\n PersonaWebSocketProtocolConfig,\n} from './protocol';\n\ntype PersonaRuntimeContextType = {\n protocols: PersonaProtocol[];\n protocolsStatus: Map<string, ProtocolStatus>;\n getMessages: () => PersonaMessage[];\n};\n\nconst PersonaRuntimeContext = createContext<PersonaRuntimeContextType | undefined>(undefined);\n\nfunction fileToBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.readAsDataURL(file); // Converte il file in Data URL (base64)\n\n reader.onload = () => {\n //remove data url using ;base64, to split\n const base64 = reader.result as string;\n const base64WithoutPrefix = base64.split(';base64,')[1];\n resolve(base64WithoutPrefix);\n };\n\n reader.onerror = (error) => {\n reject(error);\n };\n });\n}\n\nfunction PersonaRuntimeProviderInner({\n dev = false,\n baseUrl,\n protocols: _protocols,\n logger,\n children,\n session: defaultSession = 'new',\n ...config\n}: Readonly<PersonaConfig>) {\n const [isRunning, setIsRunning] = useState(false);\n const [messages, setMessages] = useState<PersonaMessage[]>([]);\n const [session, setSession] = useState<Session>(defaultSession);\n const [protocolsStatus, setProtocolsStatus] = useState<Map<string, ProtocolStatus>>(new Map());\n const didMount = useRef(false);\n\n const protocols = useMemo<PersonaProtocol[]>(() => {\n if (Array.isArray(_protocols)) {\n return _protocols;\n }\n\n if (typeof _protocols === 'object' && _protocols !== null) {\n const baseEndpoint = dev ? 'localhost:8000' : baseUrl || 'persona.applica.guru/api';\n const baseEndpointProtocol = dev ? 'http' : 'https';\n const baseWebSocketProtocol = dev ? 'ws' : 'wss';\n let availableProtocols = Object.keys(_protocols)\n .map((key) => {\n switch (key) {\n case 'rest':\n const restConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (restConfig === true) {\n return new PersonaRESTProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof restConfig === 'object' && restConfig !== null) {\n return new PersonaRESTProtocol(restConfig as PersonaRESTProtocolConfig);\n } else {\n return null;\n }\n case 'webrtc':\n const webrtcConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (webrtcConfig === true) {\n return new PersonaWebRTCProtocol({\n webrtcUrl: `${baseWebSocketProtocol}://${baseEndpoint}/webrtc`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof webrtcConfig === 'object' && webrtcConfig !== null) {\n return new PersonaWebRTCProtocol(webrtcConfig as PersonaWebRTCProtocolConfig);\n } else {\n return null;\n }\n case 'websocket':\n const websocketConfig: PersonaProtocolBaseConfig | boolean | undefined = _protocols[key];\n if (websocketConfig === true) {\n return new PersonaWebSocketProtocol({\n webSocketUrl: `${baseWebSocketProtocol}://${baseEndpoint}/websocket`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n logger,\n });\n } else if (typeof websocketConfig === 'object' && websocketConfig !== null) {\n return new PersonaWebSocketProtocol(websocketConfig as PersonaWebSocketProtocolConfig);\n } else {\n return null;\n }\n default:\n throw new Error(`Unknown protocol: ${key}`);\n }\n })\n .filter((protocol) => protocol !== null) as PersonaProtocol[];\n\n if (config.tools) {\n availableProtocols.push(\n new PersonaTransactionProtocol({\n apiUrl: `${baseEndpointProtocol}://${baseEndpoint}`,\n apiKey: config.apiKey,\n agentId: config.agentId,\n tools: config.tools, // Pass raw tools\n logger,\n }),\n );\n }\n return availableProtocols;\n }\n throw new Error('Invalid protocols configuration');\n }, []);\n\n useEffect(() => {\n if (didMount.current) return;\n\n didMount.current = true;\n logger?.debug(\n 'Initializing protocols: ',\n protocols.map((protocol) => protocol.getName()),\n );\n protocols.forEach((protocol) => {\n protocol.setSession(session);\n protocol.clearListeners();\n protocol.addStatusChangeListener((status: ProtocolStatus) => {\n logger?.debug(`${protocol.getName()} has notified new status: ${status}`);\n protocolsStatus.set(protocol.getName(), status);\n if (status === 'connected') {\n if (config.context) {\n protocol.sendPacket({\n type: 'command',\n payload: {\n command: 'set_initial_context',\n arguments: config.context,\n },\n });\n }\n if (config.tools && Array.isArray(config.tools)) {\n protocol.sendPacket({\n type: 'command',\n payload: {\n command: 'set_local_tools',\n arguments: {\n tools: config.tools.map((tool) => tool.schema),\n },\n },\n });\n }\n }\n setProtocolsStatus(new Map(protocolsStatus));\n });\n protocol.addPacketListener((message: PersonaPacket) => {\n if (message.type === 'message') {\n const personaMessage = message.payload as PersonaMessage;\n setMessages((currentConversation) =>\n parseMessages([...currentConversation, ...[{ ...personaMessage, protocol: protocol.getName() }]]),\n );\n } else if (message.type === 'reasoning') {\n const personaReasoning = message.payload as PersonaReasoning;\n\n let text = personaReasoning.thought;\n if (personaReasoning.imageUrl) {\n // add markdown image\n text += `\\n\\n![image](https://persona.applica.guru/api/files/${personaReasoning.imageUrl})`;\n }\n const personaMessage: PersonaMessage = { type: 'reasoning', text: text, role: 'assistant', finishReason: 'stop' };\n\n setMessages((currentConversation) =>\n parseMessages([...currentConversation, ...[{ ...personaMessage, protocol: protocol.getName() }]]),\n );\n } else if (message.type === 'transaction') {\n protocols.filter((p) => p !== protocol).forEach((p) => p.onTransaction(message.payload as PersonaTransaction));\n }\n });\n if (protocol.autostart && protocol.status === 'disconnected') {\n logger?.debug(`Connecting to protocol: ${protocol.getName()}`);\n protocol.connect(session);\n }\n });\n }, [session, protocols, logger, protocolsStatus]);\n\n const onNew = async (message: AppendMessage) => {\n if (message.content[0]?.type !== 'text') throw new Error('Only text messages are supported');\n const ready = protocols.some((protocol) => protocol.getName() !== 'transaction' && protocol.status === 'connected');\n if (!ready) {\n setMessages((currentConversation) => [\n ...currentConversation,\n { role: 'assistant', type: 'text', text: 'No protocol is connected.' },\n ]);\n return;\n }\n\n const input = message.content[0].text;\n setMessages((currentConversation) => [...currentConversation, { role: 'user', type: 'text', text: input }]);\n setIsRunning(true);\n\n const protocol = protocols.sort((a, b) => b.getPriority() - a.getPriority()).find((protocol) => protocol.status === 'connected');\n const content: Array<PersonaMessage> = [];\n if (message.attachments) {\n for (const attachment of message.attachments) {\n if (attachment.contentType.startsWith('image/') && attachment.file) {\n content.push({\n role: 'user',\n image: {\n contentType: attachment.contentType,\n content: await fileToBase64(attachment.file),\n },\n text: '',\n type: 'text',\n });\n }\n }\n }\n\n if (message.content) {\n content.push({\n role: 'user',\n text: message.content[0].text,\n type: 'text',\n });\n }\n logger?.debug('Sending message:', content);\n await protocol?.sendPacket({ type: 'request', payload: content });\n\n setIsRunning(false);\n };\n\n const onCancel = useCallback(() => {\n setIsRunning(false);\n setMessages([]);\n setSession('new');\n return Promise.resolve();\n }, []);\n\n const onReload = useCallback(() => {\n return Promise.resolve();\n }, []);\n\n const getMessages = useCallback(() => {\n return messages;\n }, [messages]);\n\n const runtime = useExternalStoreRuntime({\n isRunning,\n messages,\n convertMessage,\n onNew,\n onCancel,\n onReload,\n adapters: {\n attachments: new CompositeAttachmentAdapter([new SimpleImageAttachmentAdapter()]),\n },\n });\n\n return (\n <PersonaRuntimeContext.Provider value={{ protocols, protocolsStatus, getMessages }}>\n <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>\n </PersonaRuntimeContext.Provider>\n );\n}\n\nfunction PersonaRuntimeProvider({ children, ...config }: PropsWithChildren<PersonaConfig>) {\n return <PersonaRuntimeProviderInner {...config}>{children}</PersonaRuntimeProviderInner>;\n}\n\nfunction usePersonaRuntime(): PersonaRuntimeContextType {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntime must be used within a PersonaRuntimeProvider');\n }\n return context;\n}\n\n/**\n * Retrieves a specific protocol instance from the PersonaRuntimeContext.\n *\n * @param protocol - The name of the protocol to use.\n * @returns {PersonaProtocol | null} - The protocol instance or null if not found.\n * @throws {Error} - If the hook is used outside of a PersonaRuntimeProvider.\n */\nfunction usePersonaRuntimeProtocol(protocol: string): PersonaProtocol | null {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider');\n }\n\n const protocolInstance = context.protocols.find((p) => p.getName() === protocol);\n if (!protocolInstance) {\n return null;\n }\n\n const status = context.protocolsStatus.get(protocolInstance.getName());\n\n return {\n ...protocolInstance,\n connect: protocolInstance.connect.bind(protocolInstance),\n disconnect: protocolInstance.disconnect.bind(protocolInstance),\n sendPacket: protocolInstance.sendPacket.bind(protocolInstance),\n setSession: protocolInstance.setSession.bind(protocolInstance),\n addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),\n addPacketListener: protocolInstance.addPacketListener.bind(protocolInstance),\n getName: protocolInstance.getName.bind(protocolInstance),\n getPriority: protocolInstance.getPriority.bind(protocolInstance),\n status: status || protocolInstance.status,\n };\n}\n\nfunction usePersonaRuntimeEndpoint(): string | null {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider');\n }\n\n const extractors: { [key: string]: (protocol: PersonaProtocol) => string } = {\n rest: (protocol) => (protocol as PersonaRESTProtocol).config.apiUrl,\n webrtc: (protocol) =>\n (protocol as PersonaWebRTCProtocol).config.webrtcUrl.replace('/webrtc', '').replace('ws://', 'http://').replace('wss://', 'https://'),\n websocket: (protocol) =>\n (protocol as PersonaWebSocketProtocol).config.webSocketUrl\n .replace('/websocket', '')\n .replace('ws://', 'http://')\n .replace('wss://', 'https://'),\n };\n\n for (const protocol of context.protocols) {\n const extractor = extractors[protocol.getName()];\n if (extractor) {\n return extractor(protocol);\n }\n }\n return null;\n}\n\nfunction usePersonaRuntimeWebRTCProtocol(): PersonaWebRTCProtocol | null {\n return usePersonaRuntimeProtocol('webrtc') as PersonaWebRTCProtocol;\n}\n\nfunction usePersonaRuntimeMessages(): PersonaMessage[] {\n const context = useContext(PersonaRuntimeContext);\n if (!context) {\n throw new Error('usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider');\n }\n return context.getMessages();\n}\n\nexport {\n PersonaRuntimeProvider,\n usePersonaRuntimeEndpoint,\n usePersonaRuntime,\n usePersonaRuntimeProtocol,\n usePersonaRuntimeWebRTCProtocol,\n usePersonaRuntimeMessages,\n};\nexport type { PersonaMessage, PersonaResponse };\n","interface PersonaLogger {\n log: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n}\n\nclass PersonaConsoleLogger implements PersonaLogger {\n prefix = '[Persona]';\n\n log(message: string, ...args: unknown[]) {\n console.log(`${this.prefix} - ${message}`, ...args);\n }\n\n info(message: string, ...args: unknown[]) {\n console.info(`${this.prefix} - ${message}`, ...args);\n }\n\n warn(message: string, ...args: unknown[]) {\n console.warn(`${this.prefix} - ${message}`, ...args);\n }\n\n error(message: string, ...args: unknown[]) {\n console.error(`${this.prefix} - ${message}`, ...args);\n }\n\n debug(message: string, ...args: unknown[]) {\n console.debug(`${this.prefix} - ${message}`, ...args);\n }\n}\n\nexport { PersonaConsoleLogger };\nexport type { PersonaLogger };\n","export type ToolParameterType = 'string' | 'number' | 'boolean' | 'object' | 'array';\n\nexport interface ToolParameter {\n type: ToolParameterType;\n description: string;\n required?: boolean;\n properties?: Record<string, ToolParameter>;\n items?: ToolParameter;\n}\n\nexport interface ToolSchema {\n type: 'local';\n name: string;\n description: string;\n config: {\n timeout: number;\n parameters: {\n type: 'object';\n title: string;\n required: string[];\n properties: Record<string, ToolParameter>;\n };\n output: {\n type: 'object';\n title: string;\n properties: Record<string, ToolParameter>;\n };\n };\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n title?: string;\n timeout?: number;\n parameters: Record<string, ToolParameter>;\n output: Record<string, ToolParameter>;\n implementation: (...args: any[]) => any;\n}\n\n/**\n * Create a tool parameter definition\n */\nexport function createParameter(\n type: ToolParameterType,\n description: string,\n options?: {\n required?: boolean;\n properties?: Record<string, ToolParameter>;\n items?: ToolParameter;\n },\n): ToolParameter {\n return {\n type,\n description,\n ...options,\n };\n}\n\n/**\n * Generate a tool schema from a tool definition\n */\nexport function generateToolSchema(definition: ToolDefinition): ToolSchema {\n const requiredParams = Object.entries(definition.parameters)\n .filter(([_, param]) => param.required)\n .map(([name]) => name);\n\n return {\n type: 'local',\n name: definition.name,\n description: definition.description,\n config: {\n timeout: definition.timeout || 60,\n parameters: {\n type: 'object',\n title: definition.title || `${definition.name} parameters`,\n required: requiredParams,\n properties: definition.parameters,\n },\n output: {\n type: 'object',\n title: `${definition.name} output`,\n properties: definition.output,\n },\n },\n };\n}\n\nexport type ToolInstance = { schema: ToolSchema; implementation: (...args: any[]) => any };\n\n/**\n * Create a complete tool definition with schema and implementation\n */\nexport function createTool(definition: ToolDefinition): ToolInstance {\n return {\n schema: generateToolSchema(definition),\n implementation: definition.implementation,\n };\n}\n\n/**\n * Extract function signature and generate schema from a JavaScript function\n * This is a utility to help convert existing functions to tool schemas\n */\nexport function createToolFromFunction(\n name: string,\n description: string,\n fn: (...args: any[]) => any,\n parameterTypes: Record<string, ToolParameter>,\n outputTypes: Record<string, ToolParameter>,\n options?: {\n title?: string;\n timeout?: number;\n },\n): ToolInstance {\n const definition: ToolDefinition = {\n name,\n description,\n title: options?.title,\n timeout: options?.timeout,\n parameters: parameterTypes,\n output: outputTypes,\n implementation: fn,\n };\n\n return createTool(definition);\n}\n\n// Example usage for the sum function you provided:\nexport const sumTool = createToolFromFunction(\n 'sum',\n 'Sum two numbers',\n function sum(a: number, b: number) {\n const result = a + b;\n return { result };\n },\n {\n a: createParameter('number', 'First number to sum', { required: true }),\n b: createParameter('number', 'Second number to sum', { required: true }),\n },\n {\n result: createParameter('number', 'Sum of two numbers'),\n },\n);\n\n// Example for the navigate_to function as shown in the user's request:\nexport const navigateToToolExample = createTool({\n name: 'navigate_to',\n description: 'Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that',\n title: 'Sum two numbers', // As per the user's example\n timeout: 60,\n parameters: {\n a: createParameter('number', 'First number to sum'),\n b: createParameter('number', 'Seconth number to sum'), // Keeping the typo as in the original\n },\n output: {\n result: createParameter('number', 'Sum of two numbers'),\n },\n implementation: function navigateTo(a: number, b: number) {\n // This is just an example - you would implement actual navigation logic here\n const result = a + b;\n return { result };\n },\n});\n\n// Helper function to create multiple tools at once\nexport function createToolRegistry(tools: ToolDefinition[]): {\n schemas: ToolSchema[];\n implementations: Record<string, (...args: any[]) => any>;\n} {\n const schemas: ToolSchema[] = [];\n const implementations: Record<string, (...args: any[]) => any> = {};\n\n tools.forEach((tool) => {\n const { schema, implementation } = createTool(tool);\n schemas.push(schema);\n implementations[tool.name] = implementation;\n });\n\n return { schemas, implementations };\n}\n\n// Utility to validate tool parameters at runtime\nexport function validateToolParameters(parameters: Record<string, any>, schema: ToolSchema): boolean {\n const { required, properties } = schema.config.parameters;\n\n // Check required parameters\n for (const requiredParam of required) {\n if (!(requiredParam in parameters)) {\n throw new Error(`Missing required parameter: ${requiredParam}`);\n }\n }\n\n // Type checking (basic)\n for (const [paramName, paramValue] of Object.entries(parameters)) {\n const paramSchema = properties[paramName];\n if (paramSchema) {\n if (paramSchema.type === 'number' && typeof paramValue !== 'number') {\n throw new Error(`Parameter ${paramName} should be a number`);\n }\n if (paramSchema.type === 'string' && typeof paramValue !== 'string') {\n throw new Error(`Parameter ${paramName} should be a string`);\n }\n if (paramSchema.type === 'boolean' && typeof paramValue !== 'boolean') {\n throw new Error(`Parameter ${paramName} should be a boolean`);\n }\n }\n }\n\n return true;\n}\n"],"names":["REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","reactJsxRuntime_production","jsxRuntimeModule","require$$0","removeEmptyMessages","messages","message","_a","parseMessages","outputMessages","currentMessage","convertMessage","files","file","_b","call","PersonaProtocolBase","__publicField","callback","session","status","notify","_","PersonaRESTProtocol","packet","apiUrl","apiKey","agentId","sessionId","_c","input","personaResponse","payload","error","_d","PersonaWebSocketProtocol","sid","webSocketUrl","event","data","PersonaWebRTCClient","err","track","remoteAudio","e","channel","msg","url","offer","metadata","offerMessage","label","localSource","remoteSource","loop","localArray","remoteArray","localAmp","a","b","remoteAmp","PersonaWebRTCProtocol","PersonaTransactionsManager","transaction","request","PersonaPersistableTransaction","manager","tools","functionCall","functionName","functionArgs","tool","orderedArgs","p","name","result","output","PersonaTransactionProtocol","persistable","PersonaRuntimeContext","createContext","fileToBase64","resolve","reject","reader","base64WithoutPrefix","PersonaRuntimeProviderInner","dev","baseUrl","_protocols","logger","children","defaultSession","isRunning","setIsRunning","useState","setMessages","setSession","protocolsStatus","setProtocolsStatus","didMount","useRef","protocols","useMemo","baseEndpoint","baseEndpointProtocol","baseWebSocketProtocol","availableProtocols","restConfig","webrtcConfig","websocketConfig","protocol","useEffect","personaMessage","currentConversation","personaReasoning","text","onNew","content","attachment","onCancel","useCallback","onReload","getMessages","runtime","useExternalStoreRuntime","CompositeAttachmentAdapter","SimpleImageAttachmentAdapter","jsx","AssistantRuntimeProvider","PersonaRuntimeProvider","usePersonaRuntime","context","useContext","usePersonaRuntimeProtocol","protocolInstance","usePersonaRuntimeEndpoint","extractors","extractor","usePersonaRuntimeWebRTCProtocol","usePersonaRuntimeMessages","PersonaConsoleLogger","args","createParameter","description","options","generateToolSchema","definition","requiredParams","param","createTool","createToolFromFunction","fn","parameterTypes","outputTypes","sumTool","navigateToToolExample","createToolRegistry","schemas","implementations","schema","implementation","validateToolParameters","parameters","required","properties","requiredParam","paramName","paramValue","paramSchema"],"mappings":";;;;;;;;;;;;;;;;;;;AAWA,MAAIA,IAAqB,OAAO,IAAI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AAAC,MAAmBX,EAAW/E,CAAI;AAClD,IAAAuF,EAAQ,KAAKE,CAAM,GACHD,EAAAxF,EAAK,IAAI,IAAI0F;AAAA,EAAA,CAC9B,GAEM,EAAE,SAAAH,GAAS,iBAAAC,EAAgB;AACpC;AAGgB,SAAAG,GAAuBC,GAAiCH,GAA6B;AACnG,QAAM,EAAE,UAAAI,GAAU,YAAAC,EAAW,IAAIL,EAAO,OAAO;AAG/C,aAAWM,KAAiBF;AACtB,QAAA,EAAEE,KAAiBH;AACrB,YAAM,IAAI,MAAM,+BAA+BG,CAAa,EAAE;AAKlE,aAAW,CAACC,GAAWC,CAAU,KAAK,OAAO,QAAQL,CAAU,GAAG;AAC1D,UAAAM,IAAcJ,EAAWE,CAAS;AACxC,QAAIE,GAAa;AACf,UAAIA,EAAY,SAAS,YAAY,OAAOD,KAAe;AACzD,cAAM,IAAI,MAAM,aAAaD,CAAS,qBAAqB;AAE7D,UAAIE,EAAY,SAAS,YAAY,OAAOD,KAAe;AACzD,cAAM,IAAI,MAAM,aAAaD,CAAS,qBAAqB;AAE7D,UAAIE,EAAY,SAAS,aAAa,OAAOD,KAAe;AAC1D,cAAM,IAAI,MAAM,aAAaD,CAAS,sBAAsB;AAAA,IAC9D;AAAA,EACF;AAGK,SAAA;AACT;","x_google_ignoreList":[0,1]}
@@ -1,4 +1,4 @@
1
- var personaSDK=function(u,d,S){"use strict";var fe=Object.defineProperty;var pe=(u,d,S)=>d in u?fe(u,d,{enumerable:!0,configurable:!0,writable:!0,value:S}):u[d]=S;var r=(u,d,S)=>pe(u,typeof d!="symbol"?d+"":d,S);var F={exports:{}},x={};/**
1
+ var personaSDK=function(u,d,S){"use strict";var fe=Object.defineProperty;var pe=(u,d,S)=>d in u?fe(u,d,{enumerable:!0,configurable:!0,writable:!0,value:S}):u[d]=S;var r=(u,d,S)=>pe(u,typeof d!="symbol"?d+"":d,S);var _={exports:{}},E={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.js
4
4
  *
@@ -6,7 +6,7 @@ var personaSDK=function(u,d,S){"use strict";var fe=Object.defineProperty;var pe=
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 U;function q(){if(U)return x;U=1;var o=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,n,a){var i=null;if(a!==void 0&&(i=""+a),n.key!==void 0&&(i=""+n.key),"key"in n){a={};for(var c in n)c!=="key"&&(a[c]=n[c])}else a=n;return n=a.ref,{$$typeof:o,type:s,key:i,ref:n!==void 0?n:null,props:a}}return x.Fragment=t,x.jsx=e,x.jsxs=e,x}F.exports=q();var I=F.exports;function B(o){return o.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function z(o){const t=[];let e=null;for(const n of o)n.type!=="transaction"&&(n.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(n)):n.functionCalls?(e&&t.push(e),t.push(n),e=null):n.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:n.functionResponse}:e&&n.protocol===e.protocol&&(e.role===n.role||n.finishReason==="stop")?(e.text+=n.text,e.files=[...e.files??[],...n.files??[]]):(e&&t.push(e),e={...n}));return e&&t.push(e),B(t)}function V(o){var e,s;const t=((e=o.files)==null?void 0:e.map(n=>({type:"file",data:n.url,mimeType:n.contentType})))??[];return o.role==="function"?{id:o.id,role:"assistant",status:(o==null?void 0:o.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((s=o.functionCalls)==null?void 0:s.map(n=>{var a;return{type:"tool-call",toolName:n.name,toolCallId:n.id,args:n.args,result:(a=o.functionResponse)==null?void 0:a.result}}))??[]}:{id:o.id,role:o.role,content:o.type==="reasoning"?[{type:"reasoning",text:o.text},...t]:[{type:"text",text:o.text},...t]}}class E{constructor(){r(this,"statusChangeCallbacks",[]);r(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addPacketListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyPacket(t){this.messageCallbacks.forEach(e=>e(t))}async notifyPackets(t){t.forEach(e=>{this.messageCallbacks.forEach(s=>s(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(s=>s(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(t){}}class O extends E{constructor(e){super();r(this,"status");r(this,"autostart");r(this,"session");r(this,"config");r(this,"notify",!0);r(this,"context",{});r(this,"tools",[]);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 100}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async sendPacket(e){var h,f,b,P;const{apiUrl:s,apiKey:n,agentId:a}=this.config,i=this.session??"new";if(e.type==="command"&&((h=e==null?void 0:e.payload)==null?void 0:h.command)=="set_initial_context"){this.context=(f=e==null?void 0:e.payload)==null?void 0:f.arguments;return}else if(e.type==="command"&&((b=e==null?void 0:e.payload)==null?void 0:b.command)=="set_local_tools"){this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:"Local tools with rest protocol are not supported."}});return}const c=e.payload;try{const k=await(await fetch(`${s}/sessions/${i}/messages`,{body:JSON.stringify({agentId:a,userMessage:c,initialContext:this.context,tools:this.tools}),method:"POST",headers:{"Content-Type":"application/json","x-persona-apikey":n}})).json();this.notifyPackets(k.response.messages.map(_=>({type:"message",payload:_})))}catch(M){this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"An error occurred while processing your request. Please try again later."}}),(P=this.config.logger)==null||P.error("Error sending packet:",M)}}}class j extends E{constructor(e){super();r(this,"status");r(this,"autostart");r(this,"session");r(this,"config");r(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 500}async syncSession(e){var s;(s=this.config.logger)==null||s.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var c;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const s=e||this.session||"new";(c=this.config.logger)==null||c.debug("Connecting to WebSocket with sessionId:",s);const n=encodeURIComponent(this.config.apiKey),a=this.config.agentId,i=`${this.config.webSocketUrl}?sessionCode=${s}&agentId=${a}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(i),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",h=>{const f=JSON.parse(h.data);this.notifyPacket(f)}),this.webSocket.addEventListener("close",h=>{var f;this.setStatus("disconnected"),this.webSocket=null,h.code!==1e3&&(this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"Oops! The connection to the server was lost. Please try again later."}}),(f=this.config.logger)==null||f.warn("WebSocket connection closed"))}),this.webSocket.addEventListener("error",()=>{var h;this.setStatus("disconnected"),this.webSocket=null,(h=this.config.logger)==null||h.error("WebSocket connection error")}),Promise.resolve(s)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}sendPacket(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify(e)),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class Y{constructor(t){r(this,"config");r(this,"pc",null);r(this,"ws",null);r(this,"localStream",null);r(this,"remoteStream",new MediaStream);r(this,"audioCtx",null);r(this,"localAnalyser",null);r(this,"remoteAnalyser",null);r(this,"analyzerFrame",null);r(this,"dataChannel",null);r(this,"isConnected",!1);r(this,"visualizerCallbacks",[]);r(this,"messageCallbacks",[]);r(this,"errorCallbacks",[]);r(this,"queuedMessages",[]);this.config=t}async connect(t){var s;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(n){(s=this.config.logger)==null||s.error("Error accessing microphone:",n);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(n=>{this.pc.addTrack(n,this.localStream)}),this.pc.ontrack=n=>{n.streams[0].getTracks().forEach(i=>{this.remoteStream.addTrack(i)}),this.audioCtx||this._startAnalyzers();const a=new Audio;a.srcObject=this.remoteStream,a.play().catch(i=>{var c;(c=this.config.logger)==null||c.error("Error playing remote audio:",i)})},this.pc.onicecandidate=n=>{var a;n.candidate&&((a=this.ws)==null?void 0:a.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:n.candidate}}))},this.pc.ondatachannel=n=>{const a=n.channel;a.onmessage=i=>{this.messageCallbacks.forEach(c=>{c(i)})},a.onopen=()=>{var i;for(;this.queuedMessages.length>0;){const c=this.queuedMessages.shift();c&&(a.send(JSON.stringify(c)),(i=this.config.logger)==null||i.info("Sent queued message:",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 c,h;const n=await this.pc.createOffer();await this.pc.setLocalDescription(n);const a={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(c=this.config.logger)==null||c.debug("Opening connection to WebRTC server: ",a);const i={type:"OFFER",src:((h=crypto.randomUUID)==null?void 0:h.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:n.sdp,type:n.type},connectionId:(Date.now()%1e6).toString(),metadata:a}};this.ws.send(JSON.stringify(i))},this.ws.onmessage=async n=>{var i;const a=JSON.parse(n.data);if(a.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(a.payload.sdp));else if(a.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(a.payload.candidate))}catch(c){(i=this.config.logger)==null||i.error("Error adding ICE candidate:",c)}},this.ws.onclose=n=>{n.code!==1e3&&this.errorCallbacks.forEach(a=>{a("Oops! The connection to the server was lost. Please try again later.")}),this._stopAnalyzers()}}async disconnect(){var t;this.isConnected&&(this.isConnected=!1,((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(e=>e.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(t){this.visualizerCallbacks.push(t)}addMessageCallback(t){this.messageCallbacks.push(t)}addErrorCallback(t){this.errorCallbacks.push(t)}createDataChannel(t="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(t),this.dataChannel.onopen=()=>{var e,s;for((e=this.config.logger)==null||e.info("Data channel opened");this.queuedMessages.length>0;){const n=this.queuedMessages.shift();n&&(this.dataChannel.send(JSON.stringify(n)),(s=this.config.logger)==null||s.info("Sent queued message:",n))}},this.dataChannel.onmessage=e=>{this.messageCallbacks.forEach(s=>{s(e)})})}sendPacket(t){var e;if(!this.dataChannel||this.dataChannel.readyState!=="open"){this.queuedMessages.push(t);return}this.dataChannel.send(JSON.stringify(t)),(e=this.config.logger)==null||e.info("Sent message:",t)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const t=this.audioCtx.createMediaStreamSource(this.localStream),e=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,t.connect(this.localAnalyser),e.connect(this.remoteAnalyser);const s=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),a=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(a);const i=n.reduce((h,f)=>h+f,0)/n.length,c=a.reduce((h,f)=>h+f,0)/a.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(h=>{h({localAmplitude:i,remoteAmplitude:c})}),this.analyzerFrame=requestAnimationFrame(s)};this.analyzerFrame=requestAnimationFrame(s)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class W extends E{constructor(e){super();r(this,"status");r(this,"session");r(this,"autostart");r(this,"config");r(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(s=>{const n=JSON.parse(s.data);this.notifyPacket(n)}),this.webRTCClient.addErrorCallback(s=>{var n;(n=this.config.logger)==null||n.error("WebRTC error:",s),this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:s}})})}getName(){return"webrtc"}getPriority(){return 1e3}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var s;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(s=this.config.logger)==null||s.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var e,s,n;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(s=this.config)==null?void 0:s.logger)==null||n.debug("Disconnected from WebRTC")}sendPacket(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendPacket(e),Promise.resolve())}}class G{constructor(t){r(this,"config");this.config=t}async complete(t,e){var s;await this.persist(t,{...e,success:!0}),(s=this.config.logger)==null||s.debug("Transaction completed:",t)}async fail(t,e){var s;await this.persist(t,{...e,success:!1}),(s=this.config.logger)==null||s.debug("Transaction failed:",{...t,...e})}async persist(t,e){await fetch(`${this.config.apiUrl}/transactions/${t.id}`,{body:JSON.stringify(e),method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-persona-apikey":this.config.apiKey}})}}class H{constructor(t,e){r(this,"transaction");r(this,"manager");this.transaction=t,this.manager=e}getFunctionCall(){return this.transaction.functionCall}async invoke(t){var i;const e=this.transaction.functionCall;if(!e){await this.fail("No function call found");return}const s=e.name,n=e.args,a=t[s];if(!a){await this.fail(`Tool ${s} not found`);return}try{const h=(((i=a.toString().replace(/\n/g," ").match(/^[^(]*\(([^)]*)\)/))==null?void 0:i[1].split(",").map(b=>b.trim()).filter(Boolean))||[]).map(b=>n[b]),f=await a.apply(null,h);await this.complete(f)}catch(c){await this.fail(`Error executing tool ${s}: ${c}`)}}async complete(t){await this.manager.complete(this.transaction,{success:!0,output:t,error:null})}async fail(t){await this.manager.fail(this.transaction,{success:!1,output:null,error:t})}}class D extends E{constructor(e){super();r(this,"status");r(this,"autostart");r(this,"session");r(this,"config");r(this,"notify",!0);r(this,"_tools");if(this.config=e,this.status="disconnected",this.autostart=!0,Array.isArray(e.tools)){this._tools={};for(const s of e.tools)s.schema&&s.implementation&&(this._tools[s.schema.name]=s.implementation)}else this._tools=e.tools}getName(){return"transaction"}getPriority(){return 0}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async sendPacket(e){}onTransaction(e){console.log("transaction received:",e);const s=new G(this.config),n=new H(e,s);this.config.onTransaction?this.config.onTransaction(n):n.invoke(this._tools)}getTools(){return this._tools}}const A=d.createContext(void 0);function Q(o){return new Promise((t,e)=>{const s=new FileReader;s.readAsDataURL(o),s.onload=()=>{const a=s.result.split(";base64,")[1];t(a)},s.onerror=n=>{e(n)}})}function X({dev:o=!1,baseUrl:t,protocols:e,logger:s,children:n,session:a="new",...i}){const[c,h]=d.useState(!1),[f,b]=d.useState([]),[P,M]=d.useState(a),[k,_]=d.useState(new Map),K=d.useRef(!1),R=d.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const l=o?"localhost:8000":t||"persona.applica.guru/api",y=o?"http":"https",m=o?"ws":"wss";let g=Object.keys(e).map(w=>{switch(w){case"rest":const p=e[w];return p===!0?new O({apiUrl:`${y}://${l}`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):typeof p=="object"&&p!==null?new O(p):null;case"webrtc":const T=e[w];return T===!0?new W({webrtcUrl:`${m}://${l}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):typeof T=="object"&&T!==null?new W(T):null;case"websocket":const N=e[w];return N===!0?new j({webSocketUrl:`${m}://${l}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):typeof N=="object"&&N!==null?new j(N):null;default:throw new Error(`Unknown protocol: ${w}`)}}).filter(w=>w!==null);return i.tools&&g.push(new D({apiUrl:`${y}://${l}`,apiKey:i.apiKey,agentId:i.agentId,tools:i.tools,logger:s})),g}throw new Error("Invalid protocols configuration")},[]);d.useEffect(()=>{K.current||(K.current=!0,s==null||s.debug("Initializing protocols: ",R.map(l=>l.getName())),R.forEach(l=>{l.setSession(P),l.clearListeners(),l.addStatusChangeListener(y=>{s==null||s.debug(`${l.getName()} has notified new status: ${y}`),k.set(l.getName(),y),y==="connected"&&(i.context&&l.sendPacket({type:"command",payload:{command:"set_initial_context",arguments:i.context}}),i.tools&&Array.isArray(i.tools)&&l.sendPacket({type:"command",payload:{command:"set_local_tools",arguments:{tools:i.tools.map(m=>m.schema)}}})),_(new Map(k))}),l.addPacketListener(y=>{if(y.type==="message"){const m=y.payload;b(g=>z([...g,{...m,protocol:l.getName()}]))}else if(y.type==="reasoning"){const m=y.payload;let g=m.thought;m.imageUrl&&(g+=`
9
+ */var F;function q(){if(F)return E;F=1;var a=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,n,o){var i=null;if(o!==void 0&&(i=""+o),n.key!==void 0&&(i=""+n.key),"key"in n){o={};for(var c in n)c!=="key"&&(o[c]=n[c])}else o=n;return n=o.ref,{$$typeof:a,type:s,key:i,ref:n!==void 0?n:null,props:o}}return E.Fragment=t,E.jsx=e,E.jsxs=e,E}_.exports=q();var I=_.exports;function B(a){return a.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function z(a){const t=[];let e=null;for(const n of a)n.type!=="transaction"&&(n.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(n)):n.functionCalls?(e&&t.push(e),t.push(n),e=null):n.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:n.functionResponse}:e&&n.protocol===e.protocol&&(e.role===n.role||n.finishReason==="stop")?(e.text+=n.text,e.files=[...e.files??[],...n.files??[]]):(e&&t.push(e),e={...n}));return e&&t.push(e),B(t)}function V(a){var e,s;const t=((e=a.files)==null?void 0:e.map(n=>({type:"file",data:n.url,mimeType:n.contentType})))??[];return a.role==="function"?{id:a.id,role:"assistant",status:(a==null?void 0:a.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((s=a.functionCalls)==null?void 0:s.map(n=>{var o;return{type:"tool-call",toolName:n.name,toolCallId:n.id,args:n.args,result:(o=a.functionResponse)==null?void 0:o.result}}))??[]}:{id:a.id,role:a.role,content:a.type==="reasoning"?[{type:"reasoning",text:a.text},...t]:[{type:"text",text:a.text},...t]}}class A{constructor(){r(this,"statusChangeCallbacks",[]);r(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addPacketListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyPacket(t){this.messageCallbacks.forEach(e=>e(t))}async notifyPackets(t){t.forEach(e=>{this.messageCallbacks.forEach(s=>s(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(s=>s(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}onTransaction(t){}}class O extends A{constructor(e){super();r(this,"status");r(this,"autostart");r(this,"session");r(this,"config");r(this,"notify",!0);r(this,"context",{});r(this,"tools",[]);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 100}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async sendPacket(e){var h,f,w,R;const{apiUrl:s,apiKey:n,agentId:o}=this.config,i=this.session??"new";if(e.type==="command"&&((h=e==null?void 0:e.payload)==null?void 0:h.command)=="set_initial_context"){this.context=(f=e==null?void 0:e.payload)==null?void 0:f.arguments;return}else if(e.type==="command"&&((w=e==null?void 0:e.payload)==null?void 0:w.command)=="set_local_tools"){this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:"Local tools with rest protocol are not supported."}});return}const c=e.payload;try{const T=await(await fetch(`${s}/sessions/${i}/messages`,{body:JSON.stringify({agentId:o,userMessage:c,initialContext:this.context,tools:this.tools}),method:"POST",headers:{"Content-Type":"application/json","x-persona-apikey":n}})).json();this.notifyPackets(T.response.messages.map(U=>({type:"message",payload:U})))}catch(M){this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"An error occurred while processing your request. Please try again later."}}),(R=this.config.logger)==null||R.error("Error sending packet:",M)}}}class j extends A{constructor(e){super();r(this,"status");r(this,"autostart");r(this,"session");r(this,"config");r(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 500}async syncSession(e){var s;(s=this.config.logger)==null||s.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var c;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const s=e||this.session||"new";(c=this.config.logger)==null||c.debug("Connecting to WebSocket with sessionId:",s);const n=encodeURIComponent(this.config.apiKey),o=this.config.agentId,i=`${this.config.webSocketUrl}?sessionCode=${s}&agentId=${o}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(i),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",h=>{const f=JSON.parse(h.data);this.notifyPacket(f)}),this.webSocket.addEventListener("close",h=>{var f;this.setStatus("disconnected"),this.webSocket=null,h.code!==1e3&&(this.notifyPacket({type:"message",payload:{role:"assistant",type:"text",text:"Oops! The connection to the server was lost. Please try again later."}}),(f=this.config.logger)==null||f.warn("WebSocket connection closed"))}),this.webSocket.addEventListener("error",()=>{var h;this.setStatus("disconnected"),this.webSocket=null,(h=this.config.logger)==null||h.error("WebSocket connection error")}),Promise.resolve(s)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}sendPacket(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify(e)),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class Y{constructor(t){r(this,"config");r(this,"pc",null);r(this,"ws",null);r(this,"localStream",null);r(this,"remoteStream",new MediaStream);r(this,"audioCtx",null);r(this,"localAnalyser",null);r(this,"remoteAnalyser",null);r(this,"analyzerFrame",null);r(this,"dataChannel",null);r(this,"isConnected",!1);r(this,"visualizerCallbacks",[]);r(this,"messageCallbacks",[]);r(this,"errorCallbacks",[]);r(this,"queuedMessages",[]);this.config=t}async connect(t){var s;if(this.isConnected)return;this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(n){(s=this.config.logger)==null||s.error("Error accessing microphone:",n);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(n=>{this.pc.addTrack(n,this.localStream)}),this.pc.ontrack=n=>{n.streams[0].getTracks().forEach(i=>{this.remoteStream.addTrack(i)}),this.audioCtx||this._startAnalyzers();const o=new Audio;o.srcObject=this.remoteStream,o.play().catch(i=>{var c;(c=this.config.logger)==null||c.error("Error playing remote audio:",i)})},this.pc.onicecandidate=n=>{var o;n.candidate&&((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:n.candidate}}))},this.pc.ondatachannel=n=>{const o=n.channel;o.onmessage=i=>{this.messageCallbacks.forEach(c=>{c(i)})},o.onopen=()=>{var i;for(;this.queuedMessages.length>0;){const c=this.queuedMessages.shift();c&&(o.send(JSON.stringify(c)),(i=this.config.logger)==null||i.info("Sent queued message:",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 c,h;const n=await this.pc.createOffer();await this.pc.setLocalDescription(n);const o={apiKey:this.config.apiKey,agentId:this.config.agentId,sessionCode:t};(c=this.config.logger)==null||c.debug("Opening connection to WebRTC server: ",o);const i={type:"OFFER",src:((h=crypto.randomUUID)==null?void 0:h.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:n.sdp,type:n.type},connectionId:(Date.now()%1e6).toString(),metadata:o}};this.ws.send(JSON.stringify(i))},this.ws.onmessage=async n=>{var i;const o=JSON.parse(n.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(c){(i=this.config.logger)==null||i.error("Error adding ICE candidate:",c)}},this.ws.onclose=n=>{n.code!==1e3&&this.errorCallbacks.forEach(o=>{o("Oops! The connection to the server was lost. Please try again later.")}),this._stopAnalyzers()}}async disconnect(){var t;this.isConnected&&(this.isConnected=!1,((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(e=>e.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(t){this.visualizerCallbacks.push(t)}addMessageCallback(t){this.messageCallbacks.push(t)}addErrorCallback(t){this.errorCallbacks.push(t)}createDataChannel(t="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(t),this.dataChannel.onopen=()=>{var e,s;for((e=this.config.logger)==null||e.info("Data channel opened");this.queuedMessages.length>0;){const n=this.queuedMessages.shift();n&&(this.dataChannel.send(JSON.stringify(n)),(s=this.config.logger)==null||s.info("Sent queued message:",n))}},this.dataChannel.onmessage=e=>{this.messageCallbacks.forEach(s=>{s(e)})})}sendPacket(t){var e;if(!this.dataChannel||this.dataChannel.readyState!=="open"){this.queuedMessages.push(t);return}this.dataChannel.send(JSON.stringify(t)),(e=this.config.logger)==null||e.info("Sent message:",t)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const t=this.audioCtx.createMediaStreamSource(this.localStream),e=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,t.connect(this.localAnalyser),e.connect(this.remoteAnalyser);const s=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),o=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(o);const i=n.reduce((h,f)=>h+f,0)/n.length,c=o.reduce((h,f)=>h+f,0)/o.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(h=>{h({localAmplitude:i,remoteAmplitude:c})}),this.analyzerFrame=requestAnimationFrame(s)};this.analyzerFrame=requestAnimationFrame(s)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class W extends A{constructor(e){super();r(this,"status");r(this,"session");r(this,"autostart");r(this,"config");r(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(s=>{const n=JSON.parse(s.data);this.notifyPacket(n)}),this.webRTCClient.addErrorCallback(s=>{var n;(n=this.config.logger)==null||n.error("WebRTC error:",s),this.notifyPacket({type:"message",payload:{type:"text",role:"assistant",text:s}})})}getName(){return"webrtc"}getPriority(){return 1e3}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var s;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(s=this.config.logger)==null||s.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var e,s,n;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(s=this.config)==null?void 0:s.logger)==null||n.debug("Disconnected from WebRTC")}sendPacket(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendPacket(e),Promise.resolve())}}class G{constructor(t){r(this,"config");this.config=t}async complete(t,e){var s;await this.persist(t,{...e,success:!0}),(s=this.config.logger)==null||s.debug("Transaction completed:",t)}async fail(t,e){var s;await this.persist(t,{...e,success:!1}),(s=this.config.logger)==null||s.debug("Transaction failed:",{...t,...e})}async persist(t,e){await fetch(`${this.config.apiUrl}/transactions/${t.id}`,{body:JSON.stringify(e),method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-persona-apikey":this.config.apiKey}})}}class H{constructor(t,e){r(this,"transaction");r(this,"manager");this.transaction=t,this.manager=e}getFunctionCall(){return this.transaction.functionCall}async invoke(t){var i;const e=this.transaction.functionCall;if(!e){await this.fail("No function call found");return}const s=e.name,n=e.args,o=t[s];if(!o){await this.fail(`Tool ${s} not found`);return}try{const h=(((i=o.toString().replace(/\n/g," ").match(/^[^(]*\(([^)]*)\)/))==null?void 0:i[1].split(",").map(w=>w.trim()).filter(Boolean))||[]).map(w=>n[w]),f=await o.apply(null,h);await this.complete(f)}catch(c){await this.fail(`Error executing tool ${s}: ${c}`)}}async complete(t){await this.manager.complete(this.transaction,{success:!0,output:t,error:null})}async fail(t){await this.manager.fail(this.transaction,{success:!1,output:null,error:t})}}class D extends A{constructor(e){super();r(this,"status");r(this,"autostart");r(this,"session");r(this,"config");r(this,"notify",!0);r(this,"_tools");if(this.config=e,this.status="disconnected",this.autostart=!0,Array.isArray(e.tools)){this._tools={};for(const s of e.tools)s.schema&&s.implementation&&(this._tools[s.schema.name]=s.implementation)}else this._tools=e.tools}getName(){return"transaction"}getPriority(){return 0}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async sendPacket(e){}onTransaction(e){console.log("transaction received:",e);const s=new G(this.config),n=new H(e,s);this.config.onTransaction?this.config.onTransaction(n):n.invoke(this._tools)}getTools(){return this._tools}}const v=d.createContext(void 0);function Q(a){return new Promise((t,e)=>{const s=new FileReader;s.readAsDataURL(a),s.onload=()=>{const o=s.result.split(";base64,")[1];t(o)},s.onerror=n=>{e(n)}})}function X({dev:a=!1,baseUrl:t,protocols:e,logger:s,children:n,session:o="new",...i}){const[c,h]=d.useState(!1),[f,w]=d.useState([]),[R,M]=d.useState(o),[T,U]=d.useState(new Map),K=d.useRef(!1),k=d.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const l=a?"localhost:8000":t||"persona.applica.guru/api",y=a?"http":"https",p=a?"ws":"wss";let b=Object.keys(e).map(g=>{switch(g){case"rest":const C=e[g];return C===!0?new O({apiUrl:`${y}://${l}`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):typeof C=="object"&&C!==null?new O(C):null;case"webrtc":const m=e[g];return m===!0?new W({webrtcUrl:`${p}://${l}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):typeof m=="object"&&m!==null?new W(m):null;case"websocket":const x=e[g];return x===!0?new j({webSocketUrl:`${p}://${l}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):typeof x=="object"&&x!==null?new j(x):null;default:throw new Error(`Unknown protocol: ${g}`)}}).filter(g=>g!==null);return i.tools&&b.push(new D({apiUrl:`${y}://${l}`,apiKey:i.apiKey,agentId:i.agentId,tools:i.tools,logger:s})),b}throw new Error("Invalid protocols configuration")},[]);d.useEffect(()=>{K.current||(K.current=!0,s==null||s.debug("Initializing protocols: ",k.map(l=>l.getName())),k.forEach(l=>{l.setSession(R),l.clearListeners(),l.addStatusChangeListener(y=>{s==null||s.debug(`${l.getName()} has notified new status: ${y}`),T.set(l.getName(),y),y==="connected"&&(i.context&&l.sendPacket({type:"command",payload:{command:"set_initial_context",arguments:i.context}}),i.tools&&Array.isArray(i.tools)&&l.sendPacket({type:"command",payload:{command:"set_local_tools",arguments:{tools:i.tools.map(p=>p.schema)}}})),U(new Map(T))}),l.addPacketListener(y=>{if(y.type==="message"){const p=y.payload;w(b=>z([...b,{...p,protocol:l.getName()}]))}else if(y.type==="reasoning"){const p=y.payload;let b=p.thought;p.imageUrl&&(b+=`
10
10
 
11
- ![image](https://persona.applica.guru/api/files/${m.imageUrl})`);const w={type:"reasoning",text:g,role:"assistant",finishReason:"stop"};b(p=>z([...p,{...w,protocol:l.getName()}]))}else y.type==="transaction"&&R.filter(m=>m!==l).forEach(m=>m.onTransaction(y.payload))}),l.autostart&&l.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${l.getName()}`),l.connect(P))}))},[P,R,s,k]);const le=async l=>{var w;if(((w=l.content[0])==null?void 0:w.type)!=="text")throw new Error("Only text messages are supported");const y=l.content[0].text;b(p=>[...p,{role:"user",type:"text",text:y}]),h(!0);const m=R.sort((p,T)=>T.getPriority()-p.getPriority()).find(p=>p.status==="connected"),g=[];if(l.attachments)for(const p of l.attachments)p.contentType.startsWith("image/")&&p.file&&g.push({role:"user",image:{contentType:p.contentType,content:await Q(p.file)},text:"",type:"text"});l.content&&g.push({role:"user",text:l.content[0].text,type:"text"}),s==null||s.debug("Sending message:",g),await(m==null?void 0:m.sendPacket({type:"request",payload:g})),h(!1)},ue=d.useCallback(()=>(h(!1),b([]),M("new"),Promise.resolve()),[]),he=d.useCallback(()=>Promise.resolve(),[]),de=d.useCallback(()=>f,[f]),me=S.useExternalStoreRuntime({isRunning:c,messages:f,convertMessage:V,onNew:le,onCancel:ue,onReload:he,adapters:{attachments:new S.CompositeAttachmentAdapter([new S.SimpleImageAttachmentAdapter])}});return I.jsx(A.Provider,{value:{protocols:R,protocolsStatus:k,getMessages:de},children:I.jsx(S.AssistantRuntimeProvider,{runtime:me,children:n})})}function Z({children:o,...t}){return I.jsx(X,{...t,children:o})}function ee(){const o=d.useContext(A);if(!o)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return o}function L(o){const t=d.useContext(A);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(n=>n.getName()===o);if(!e)return null;const s=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),sendPacket:e.sendPacket.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addPacketListener:e.addPacketListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:s||e.status}}function te(){const o=d.useContext(A);if(!o)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");for(const t of o.protocols)if(t.getName()==="rest")return t.config.apiUrl;throw new Error("REST protocol not found")}function se(){return L("webrtc")}function ne(){const o=d.useContext(A);if(!o)throw new Error("usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider");return o.getMessages()}class oe{constructor(){r(this,"prefix","[Persona]")}log(t,...e){console.log(`${this.prefix} - ${t}`,...e)}info(t,...e){console.info(`${this.prefix} - ${t}`,...e)}warn(t,...e){console.warn(`${this.prefix} - ${t}`,...e)}error(t,...e){console.error(`${this.prefix} - ${t}`,...e)}debug(t,...e){console.debug(`${this.prefix} - ${t}`,...e)}}function C(o,t,e){return{type:o,description:t,...e}}function $(o){const t=Object.entries(o.parameters).filter(([e,s])=>s.required).map(([e])=>e);return{type:"local",name:o.name,description:o.description,config:{timeout:o.timeout||60,parameters:{type:"object",title:o.title||`${o.name} parameters`,required:t,properties:o.parameters},output:{type:"object",title:`${o.name} output`,properties:o.output}}}}function v(o){return{schema:$(o),implementation:o.implementation}}function J(o,t,e,s,n,a){const i={name:o,description:t,title:a==null?void 0:a.title,timeout:a==null?void 0:a.timeout,parameters:s,output:n,implementation:e};return v(i)}const ae=J("sum","Sum two numbers",function(t,e){return{result:t+e}},{a:C("number","First number to sum",{required:!0}),b:C("number","Second number to sum",{required:!0})},{result:C("number","Sum of two numbers")}),ie=v({name:"navigate_to",description:"Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that",title:"Sum two numbers",timeout:60,parameters:{a:C("number","First number to sum"),b:C("number","Seconth number to sum")},output:{result:C("number","Sum of two numbers")},implementation:function(t,e){return{result:t+e}}});function re(o){const t=[],e={};return o.forEach(s=>{const{schema:n,implementation:a}=v(s);t.push(n),e[s.name]=a}),{schemas:t,implementations:e}}function ce(o,t){const{required:e,properties:s}=t.config.parameters;for(const n of e)if(!(n in o))throw new Error(`Missing required parameter: ${n}`);for(const[n,a]of Object.entries(o)){const i=s[n];if(i){if(i.type==="number"&&typeof a!="number")throw new Error(`Parameter ${n} should be a number`);if(i.type==="string"&&typeof a!="string")throw new Error(`Parameter ${n} should be a string`);if(i.type==="boolean"&&typeof a!="boolean")throw new Error(`Parameter ${n} should be a boolean`)}}return!0}return u.PersonaConsoleLogger=oe,u.PersonaProtocolBase=E,u.PersonaRESTProtocol=O,u.PersonaRuntimeProvider=Z,u.PersonaTransactionProtocol=D,u.PersonaWebRTCProtocol=W,u.PersonaWebSocketProtocol=j,u.createParameter=C,u.createTool=v,u.createToolFromFunction=J,u.createToolRegistry=re,u.generateToolSchema=$,u.navigateToToolExample=ie,u.sumTool=ae,u.usePersonaRuntime=ee,u.usePersonaRuntimeEndpoint=te,u.usePersonaRuntimeMessages=ne,u.usePersonaRuntimeProtocol=L,u.usePersonaRuntimeWebRTCProtocol=se,u.validateToolParameters=ce,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),u}({},React,AssistantUI);
11
+ ![image](https://persona.applica.guru/api/files/${p.imageUrl})`);const g={type:"reasoning",text:b,role:"assistant",finishReason:"stop"};w(C=>z([...C,{...g,protocol:l.getName()}]))}else y.type==="transaction"&&k.filter(p=>p!==l).forEach(p=>p.onTransaction(y.payload))}),l.autostart&&l.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${l.getName()}`),l.connect(R))}))},[R,k,s,T]);const le=async l=>{var C;if(((C=l.content[0])==null?void 0:C.type)!=="text")throw new Error("Only text messages are supported");if(!k.some(m=>m.getName()!=="transaction"&&m.status==="connected")){w(m=>[...m,{role:"assistant",type:"text",text:"No protocol is connected."}]);return}const p=l.content[0].text;w(m=>[...m,{role:"user",type:"text",text:p}]),h(!0);const b=k.sort((m,x)=>x.getPriority()-m.getPriority()).find(m=>m.status==="connected"),g=[];if(l.attachments)for(const m of l.attachments)m.contentType.startsWith("image/")&&m.file&&g.push({role:"user",image:{contentType:m.contentType,content:await Q(m.file)},text:"",type:"text"});l.content&&g.push({role:"user",text:l.content[0].text,type:"text"}),s==null||s.debug("Sending message:",g),await(b==null?void 0:b.sendPacket({type:"request",payload:g})),h(!1)},ue=d.useCallback(()=>(h(!1),w([]),M("new"),Promise.resolve()),[]),he=d.useCallback(()=>Promise.resolve(),[]),de=d.useCallback(()=>f,[f]),me=S.useExternalStoreRuntime({isRunning:c,messages:f,convertMessage:V,onNew:le,onCancel:ue,onReload:he,adapters:{attachments:new S.CompositeAttachmentAdapter([new S.SimpleImageAttachmentAdapter])}});return I.jsx(v.Provider,{value:{protocols:k,protocolsStatus:T,getMessages:de},children:I.jsx(S.AssistantRuntimeProvider,{runtime:me,children:n})})}function Z({children:a,...t}){return I.jsx(X,{...t,children:a})}function ee(){const a=d.useContext(v);if(!a)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return a}function L(a){const t=d.useContext(v);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(n=>n.getName()===a);if(!e)return null;const s=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),sendPacket:e.sendPacket.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addPacketListener:e.addPacketListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:s||e.status}}function te(){const a=d.useContext(v);if(!a)throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");const t={rest:e=>e.config.apiUrl,webrtc:e=>e.config.webrtcUrl.replace("/webrtc","").replace("ws://","http://").replace("wss://","https://"),websocket:e=>e.config.webSocketUrl.replace("/websocket","").replace("ws://","http://").replace("wss://","https://")};for(const e of a.protocols){const s=t[e.getName()];if(s)return s(e)}return null}function se(){return L("webrtc")}function ne(){const a=d.useContext(v);if(!a)throw new Error("usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider");return a.getMessages()}class ae{constructor(){r(this,"prefix","[Persona]")}log(t,...e){console.log(`${this.prefix} - ${t}`,...e)}info(t,...e){console.info(`${this.prefix} - ${t}`,...e)}warn(t,...e){console.warn(`${this.prefix} - ${t}`,...e)}error(t,...e){console.error(`${this.prefix} - ${t}`,...e)}debug(t,...e){console.debug(`${this.prefix} - ${t}`,...e)}}function P(a,t,e){return{type:a,description:t,...e}}function $(a){const t=Object.entries(a.parameters).filter(([e,s])=>s.required).map(([e])=>e);return{type:"local",name:a.name,description:a.description,config:{timeout:a.timeout||60,parameters:{type:"object",title:a.title||`${a.name} parameters`,required:t,properties:a.parameters},output:{type:"object",title:`${a.name} output`,properties:a.output}}}}function N(a){return{schema:$(a),implementation:a.implementation}}function J(a,t,e,s,n,o){const i={name:a,description:t,title:o==null?void 0:o.title,timeout:o==null?void 0:o.timeout,parameters:s,output:n,implementation:e};return N(i)}const oe=J("sum","Sum two numbers",function(t,e){return{result:t+e}},{a:P("number","First number to sum",{required:!0}),b:P("number","Second number to sum",{required:!0})},{result:P("number","Sum of two numbers")}),ie=N({name:"navigate_to",description:"Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that",title:"Sum two numbers",timeout:60,parameters:{a:P("number","First number to sum"),b:P("number","Seconth number to sum")},output:{result:P("number","Sum of two numbers")},implementation:function(t,e){return{result:t+e}}});function re(a){const t=[],e={};return a.forEach(s=>{const{schema:n,implementation:o}=N(s);t.push(n),e[s.name]=o}),{schemas:t,implementations:e}}function ce(a,t){const{required:e,properties:s}=t.config.parameters;for(const n of e)if(!(n in a))throw new Error(`Missing required parameter: ${n}`);for(const[n,o]of Object.entries(a)){const i=s[n];if(i){if(i.type==="number"&&typeof o!="number")throw new Error(`Parameter ${n} should be a number`);if(i.type==="string"&&typeof o!="string")throw new Error(`Parameter ${n} should be a string`);if(i.type==="boolean"&&typeof o!="boolean")throw new Error(`Parameter ${n} should be a boolean`)}}return!0}return u.PersonaConsoleLogger=ae,u.PersonaProtocolBase=A,u.PersonaRESTProtocol=O,u.PersonaRuntimeProvider=Z,u.PersonaTransactionProtocol=D,u.PersonaWebRTCProtocol=W,u.PersonaWebSocketProtocol=j,u.createParameter=P,u.createTool=N,u.createToolFromFunction=J,u.createToolRegistry=re,u.generateToolSchema=$,u.navigateToToolExample=ie,u.sumTool=oe,u.usePersonaRuntime=ee,u.usePersonaRuntimeEndpoint=te,u.usePersonaRuntimeMessages=ne,u.usePersonaRuntimeProtocol=L,u.usePersonaRuntimeWebRTCProtocol=se,u.validateToolParameters=ce,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),u}({},React,AssistantUI);
12
12
  //# sourceMappingURL=bundle.iife.js.map