@applica-software-guru/persona-sdk 0.1.45 → 0.1.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.es.js CHANGED
@@ -1,7 +1,7 @@
1
- var U = Object.defineProperty;
2
- var J = (i, t, e) => t in i ? U(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
- var o = (i, t, e) => J(i, typeof t != "symbol" ? t + "" : t, e);
4
- import { createContext as q, useContext as N, useState as b, useRef as K, useMemo as _, useEffect as B, useCallback as v } from "react";
1
+ var F = Object.defineProperty;
2
+ var J = (a, t, e) => t in a ? F(a, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : a[t] = e;
3
+ var o = (a, t, e) => J(a, typeof t != "symbol" ? t + "" : t, e);
4
+ import { createContext as K, useContext as R, useState as S, useRef as q, useMemo as _, useEffect as B, useCallback as v } from "react";
5
5
  import { useExternalStoreRuntime as Y, AssistantRuntimeProvider as G } from "@assistant-ui/react";
6
6
  var z = { exports: {} }, w = {};
7
7
  /**
@@ -13,71 +13,78 @@ var z = { exports: {} }, w = {};
13
13
  * This source code is licensed under the MIT license found in the
14
14
  * LICENSE file in the root directory of this source tree.
15
15
  */
16
- var M;
16
+ var $;
17
17
  function V() {
18
- if (M) return w;
19
- M = 1;
20
- var i = Symbol.for("react.transitional.element"), t = Symbol.for("react.fragment");
21
- function e(s, n, a) {
22
- var c = null;
23
- if (a !== void 0 && (c = "" + a), n.key !== void 0 && (c = "" + n.key), "key" in n) {
24
- a = {};
25
- for (var r in n)
26
- r !== "key" && (a[r] = n[r]);
27
- } else a = n;
28
- return n = a.ref, {
29
- $$typeof: i,
30
- type: s,
31
- key: c,
32
- ref: n !== void 0 ? n : null,
33
- props: a
18
+ if ($) return w;
19
+ $ = 1;
20
+ var a = Symbol.for("react.transitional.element"), t = Symbol.for("react.fragment");
21
+ function e(n, s, i) {
22
+ var r = null;
23
+ if (i !== void 0 && (r = "" + i), s.key !== void 0 && (r = "" + s.key), "key" in s) {
24
+ i = {};
25
+ for (var c in s)
26
+ c !== "key" && (i[c] = s[c]);
27
+ } else i = s;
28
+ return s = i.ref, {
29
+ $$typeof: a,
30
+ type: n,
31
+ key: r,
32
+ ref: s !== void 0 ? s : null,
33
+ props: i
34
34
  };
35
35
  }
36
36
  return w.Fragment = t, w.jsx = e, w.jsxs = e, w;
37
37
  }
38
38
  z.exports = V();
39
- var k = z.exports;
40
- function H(i) {
41
- return i.filter((t) => {
39
+ var x = z.exports;
40
+ function H(a) {
41
+ return a.filter((t) => {
42
42
  var e;
43
43
  return t.finishReason === "stop" ? t.text !== null && ((e = t.text) == null ? void 0 : e.trim()) !== "" : !0;
44
44
  });
45
45
  }
46
- function Q(i) {
46
+ function Q(a) {
47
47
  const t = [];
48
48
  let e = null;
49
- for (const s of i)
50
- s.type === "reasoning" ? (e != null && (t.push(e), e = null), t.push(s)) : s.functionCalls ? (e && t.push(e), t.push(s), e = null) : s.functionResponse ? t[t.length - 1] = {
49
+ for (const s of a)
50
+ s.type !== "transaction" && (s.type === "reasoning" ? (e != null && (t.push(e), e = null), t.push(s)) : s.functionCalls ? (e && t.push(e), t.push(s), e = null) : s.functionResponse ? t[t.length - 1] = {
51
51
  ...t[t.length - 1],
52
52
  functionResponse: s.functionResponse
53
- } : e && s.protocol === e.protocol && (e.role === s.role || s.finishReason === "stop") ? e.text += s.text : (e && t.push(e), e = {
53
+ } : e && s.protocol === e.protocol && (e.role === s.role || s.finishReason === "stop") ? (e.text += s.text, e.files = [...e.files ?? [], ...s.files ?? []]) : (e && t.push(e), e = {
54
54
  ...s
55
- });
55
+ }));
56
56
  return e && t.push(e), H(t);
57
57
  }
58
- function X(i) {
59
- var t;
60
- return i.role === "function" ? {
61
- id: i.id,
58
+ function X(a) {
59
+ var e, n;
60
+ const t = ((e = a.files) == null ? void 0 : e.map(
61
+ (s) => ({
62
+ type: "file",
63
+ data: s.url,
64
+ mimeType: s.contentType
65
+ })
66
+ )) ?? [];
67
+ return a.role === "function" ? {
68
+ id: a.id,
62
69
  role: "assistant",
63
- status: (i == null ? void 0 : i.functionResponse) === null ? { type: "running" } : { type: "complete", reason: "stop" },
64
- content: ((t = i.functionCalls) == null ? void 0 : t.map((e) => {
65
- var s;
70
+ status: (a == null ? void 0 : a.functionResponse) === null ? { type: "running" } : { type: "complete", reason: "stop" },
71
+ content: ((n = a.functionCalls) == null ? void 0 : n.map((s) => {
72
+ var i;
66
73
  return {
67
74
  type: "tool-call",
68
- toolName: e.name,
69
- toolCallId: e.id,
70
- args: e.args,
71
- result: (s = i.functionResponse) == null ? void 0 : s.result
75
+ toolName: s.name,
76
+ toolCallId: s.id,
77
+ args: s.args,
78
+ result: (i = a.functionResponse) == null ? void 0 : i.result
72
79
  };
73
80
  })) ?? []
74
81
  } : {
75
- id: i.id,
76
- role: i.role,
77
- content: i.type === "reasoning" ? [{ type: "reasoning", text: i.text }] : [{ type: "text", text: i.text }]
82
+ id: a.id,
83
+ role: a.role,
84
+ content: a.type === "reasoning" ? [{ type: "reasoning", text: a.text }, ...t] : [{ type: "text", text: a.text }, ...t]
78
85
  };
79
86
  }
80
- class x {
87
+ class k {
81
88
  constructor() {
82
89
  o(this, "statusChangeCallbacks", []);
83
90
  o(this, "messageCallbacks", []);
@@ -96,7 +103,7 @@ class x {
96
103
  }
97
104
  async notifyMessages(t) {
98
105
  t.forEach((e) => {
99
- this.messageCallbacks.forEach((s) => s(e));
106
+ this.messageCallbacks.forEach((n) => n(e));
100
107
  });
101
108
  }
102
109
  async setSession(t) {
@@ -104,13 +111,15 @@ class x {
104
111
  }
105
112
  async setStatus(t) {
106
113
  const e = this.status !== t;
107
- this.status = t, e && this.statusChangeCallbacks.forEach((s) => s(t));
114
+ this.status = t, e && this.statusChangeCallbacks.forEach((n) => n(t));
108
115
  }
109
116
  clearListeners() {
110
117
  this.statusChangeCallbacks = [], this.messageCallbacks = [];
111
118
  }
119
+ onTransaction(t) {
120
+ }
112
121
  }
113
- class T extends x {
122
+ class M extends k {
114
123
  constructor(e) {
115
124
  super();
116
125
  o(this, "status");
@@ -136,19 +145,24 @@ class T extends x {
136
145
  this.session = e;
137
146
  }
138
147
  async send(e) {
139
- const { apiUrl: s, apiKey: n, agentId: a } = this.config, c = this.session ?? "new", r = e, h = await (await fetch(`${s}/agents/${a}/sessions/${c}/messages`, {
140
- body: JSON.stringify({ userMessage: r }),
148
+ const { apiUrl: n, apiKey: s, agentId: i } = this.config, r = this.session ?? "new", c = e, h = await (await fetch(`${n}/agents/${i}/sessions/${r}/messages`, {
149
+ body: JSON.stringify({ userMessage: c }),
141
150
  method: "POST",
142
151
  headers: {
143
152
  "Content-Type": "application/json",
144
- "x-fox-apikey": n,
145
- "x-persona-apikey": n
153
+ "x-fox-apikey": s,
154
+ "x-persona-apikey": s
146
155
  }
147
156
  })).json();
148
- this.notifyMessages(h.response.messages);
157
+ this.notifyMessages(
158
+ h.response.messages.map((m) => ({
159
+ type: "message",
160
+ payload: m
161
+ }))
162
+ );
149
163
  }
150
164
  }
151
- class $ extends x {
165
+ class I extends k {
152
166
  constructor(e) {
153
167
  super();
154
168
  o(this, "status");
@@ -165,31 +179,28 @@ class $ extends x {
165
179
  return 1;
166
180
  }
167
181
  async syncSession(e) {
168
- var s;
169
- (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));
182
+ var n;
183
+ (n = this.config.logger) == null || n.debug("Syncing session with WebSocket protocol:", e), this.session = e, this.webSocket && this.status === "connected" && (this.disconnect(), this.connect(e));
170
184
  }
171
185
  connect(e) {
172
- var r;
186
+ var c;
173
187
  if (this.webSocket !== null && this.status === "connected")
174
188
  return Promise.resolve(this.session);
175
- const s = e || this.session || "new";
176
- (r = this.config.logger) == null || r.debug("Connecting to WebSocket with sessionId:", s);
177
- const n = encodeURIComponent(this.config.apiKey), a = this.config.agentId, c = `${this.config.webSocketUrl}?sessionCode=${s}&agentId=${a}&apiKey=${n}`;
178
- return this.setStatus("connecting"), this.webSocket = new WebSocket(c), this.webSocket.addEventListener("open", () => {
189
+ const n = e || this.session || "new";
190
+ (c = this.config.logger) == null || c.debug("Connecting to WebSocket with sessionId:", n);
191
+ const s = encodeURIComponent(this.config.apiKey), i = this.config.agentId, r = `${this.config.webSocketUrl}?sessionCode=${n}&agentId=${i}&apiKey=${s}`;
192
+ return this.setStatus("connecting"), this.webSocket = new WebSocket(r), this.webSocket.addEventListener("open", () => {
179
193
  this.setStatus("connected");
180
194
  }), this.webSocket.addEventListener("message", (u) => {
181
195
  const h = JSON.parse(u.data);
182
- if (h.type !== "message")
183
- return;
184
- const f = h.payload;
185
- this.notifyMessage(f != null && f.thought ? { role: "assistant", type: "reasoning", text: f.thought } : f);
196
+ this.notifyMessage(h);
186
197
  }), this.webSocket.addEventListener("close", () => {
187
198
  var u;
188
199
  this.setStatus("disconnected"), this.webSocket = null, (u = this.config.logger) == null || u.warn("WebSocket connection closed");
189
200
  }), this.webSocket.addEventListener("error", (u) => {
190
201
  var h;
191
202
  this.setStatus("disconnected"), this.webSocket = null, (h = this.config.logger) == null || h.error("WebSocket error", u);
192
- }), Promise.resolve(s);
203
+ }), Promise.resolve(n);
193
204
  }
194
205
  disconnect() {
195
206
  var e;
@@ -217,13 +228,13 @@ class Z {
217
228
  this.config = t;
218
229
  }
219
230
  async connect(t) {
220
- var s;
231
+ var n;
221
232
  if (this.isConnected) return;
222
233
  this.isConnected = !0;
223
234
  try {
224
235
  this.localStream = await navigator.mediaDevices.getUserMedia({ audio: !0 });
225
- } catch (n) {
226
- (s = this.config.logger) == null || s.error("Error accessing microphone:", n);
236
+ } catch (s) {
237
+ (n = this.config.logger) == null || n.error("Error accessing microphone:", s);
227
238
  return;
228
239
  }
229
240
  this.pc = new RTCPeerConnection({
@@ -237,68 +248,68 @@ class Z {
237
248
  credential: "webrtc"
238
249
  }
239
250
  ]
240
- }), this.localStream.getTracks().forEach((n) => {
241
- this.pc.addTrack(n, this.localStream);
242
- }), this.pc.ontrack = (n) => {
243
- n.streams[0].getTracks().forEach((c) => {
244
- this.remoteStream.addTrack(c);
251
+ }), this.localStream.getTracks().forEach((s) => {
252
+ this.pc.addTrack(s, this.localStream);
253
+ }), this.pc.ontrack = (s) => {
254
+ s.streams[0].getTracks().forEach((r) => {
255
+ this.remoteStream.addTrack(r);
245
256
  }), this.audioCtx || this._startAnalyzers();
246
- const a = new Audio();
247
- a.srcObject = this.remoteStream, a.play().catch((c) => {
248
- var r;
249
- (r = this.config.logger) == null || r.error("Error playing remote audio:", c);
257
+ const i = new Audio();
258
+ i.srcObject = this.remoteStream, i.play().catch((r) => {
259
+ var c;
260
+ (c = this.config.logger) == null || c.error("Error playing remote audio:", r);
250
261
  });
251
- }, this.pc.onicecandidate = (n) => {
252
- var a;
253
- n.candidate && ((a = this.ws) == null ? void 0 : a.readyState) === WebSocket.OPEN && this.ws.send(
262
+ }, this.pc.onicecandidate = (s) => {
263
+ var i;
264
+ s.candidate && ((i = this.ws) == null ? void 0 : i.readyState) === WebSocket.OPEN && this.ws.send(
254
265
  JSON.stringify({
255
266
  type: "CANDIDATE",
256
267
  src: "client",
257
- payload: { candidate: n.candidate }
268
+ payload: { candidate: s.candidate }
258
269
  })
259
270
  );
260
- }, this.pc.ondatachannel = (n) => {
261
- const a = n.channel;
262
- a.onmessage = (c) => {
263
- this.messageCallbacks.forEach((r) => {
264
- r(c);
271
+ }, this.pc.ondatachannel = (s) => {
272
+ const i = s.channel;
273
+ i.onmessage = (r) => {
274
+ this.messageCallbacks.forEach((c) => {
275
+ c(r);
265
276
  });
266
277
  };
267
278
  };
268
279
  const e = this.config.webrtcUrl || "wss://persona.applica.guru/api/webrtc";
269
280
  this.ws = new WebSocket(`${e}?apiKey=${encodeURIComponent(this.config.apiKey)}`), this.ws.onopen = async () => {
270
- var r, u;
271
- const n = await this.pc.createOffer();
272
- await this.pc.setLocalDescription(n);
273
- const a = {
281
+ var c, u;
282
+ const s = await this.pc.createOffer();
283
+ await this.pc.setLocalDescription(s);
284
+ const i = {
274
285
  apiKey: this.config.apiKey,
275
286
  agentId: this.config.agentId,
276
287
  sessionCode: t
277
288
  };
278
- (r = this.config.logger) == null || r.debug("Opening connection to WebRTC server: ", a);
279
- const c = {
289
+ (c = this.config.logger) == null || c.debug("Opening connection to WebRTC server: ", i);
290
+ const r = {
280
291
  type: "OFFER",
281
292
  src: ((u = crypto.randomUUID) == null ? void 0 : u.call(crypto)) || "client_" + Date.now(),
282
293
  payload: {
283
294
  sdp: {
284
- sdp: n.sdp,
285
- type: n.type
295
+ sdp: s.sdp,
296
+ type: s.type
286
297
  },
287
298
  connectionId: (Date.now() % 1e6).toString(),
288
- metadata: a
299
+ metadata: i
289
300
  }
290
301
  };
291
- this.ws.send(JSON.stringify(c));
292
- }, this.ws.onmessage = async (n) => {
293
- var c;
294
- const a = JSON.parse(n.data);
295
- if (a.type === "ANSWER")
296
- await this.pc.setRemoteDescription(new RTCSessionDescription(a.payload.sdp));
297
- else if (a.type === "CANDIDATE")
302
+ this.ws.send(JSON.stringify(r));
303
+ }, this.ws.onmessage = async (s) => {
304
+ var r;
305
+ const i = JSON.parse(s.data);
306
+ if (i.type === "ANSWER")
307
+ await this.pc.setRemoteDescription(new RTCSessionDescription(i.payload.sdp));
308
+ else if (i.type === "CANDIDATE")
298
309
  try {
299
- await this.pc.addIceCandidate(new RTCIceCandidate(a.payload.candidate));
300
- } catch (r) {
301
- (c = this.config.logger) == null || c.error("Error adding ICE candidate:", r);
310
+ await this.pc.addIceCandidate(new RTCIceCandidate(i.payload.candidate));
311
+ } catch (c) {
312
+ (r = this.config.logger) == null || r.error("Error adding ICE candidate:", c);
302
313
  }
303
314
  }, this.ws.onclose = () => {
304
315
  this._stopAnalyzers();
@@ -319,18 +330,18 @@ class Z {
319
330
  var e;
320
331
  return (e = this.config.logger) == null ? void 0 : e.info("Data channel opened");
321
332
  }, this.dataChannel.onmessage = (e) => {
322
- this.messageCallbacks.forEach((s) => {
323
- s(e);
333
+ this.messageCallbacks.forEach((n) => {
334
+ n(e);
324
335
  });
325
336
  });
326
337
  }
327
338
  sendMessage(t) {
328
- var e, s;
339
+ var e, n;
329
340
  if (!this.dataChannel) {
330
341
  (e = this.config.logger) == null || e.warn("Data channel is not open, cannot send message");
331
342
  return;
332
343
  }
333
- this.dataChannel.send(t), (s = this.config.logger) == null || s.info("Sent message:", t);
344
+ this.dataChannel.send(t), (n = this.config.logger) == null || n.info("Sent message:", t);
334
345
  }
335
346
  _startAnalyzers() {
336
347
  if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0)
@@ -338,26 +349,26 @@ class Z {
338
349
  this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
339
350
  const t = this.audioCtx.createMediaStreamSource(this.localStream), e = this.audioCtx.createMediaStreamSource(this.remoteStream);
340
351
  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);
341
- const s = () => {
352
+ const n = () => {
342
353
  if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0)
343
354
  return;
344
- const n = new Uint8Array(this.localAnalyser.frequencyBinCount), a = new Uint8Array(this.remoteAnalyser.frequencyBinCount);
345
- this.localAnalyser.getByteFrequencyData(n), this.remoteAnalyser.getByteFrequencyData(a);
346
- const c = n.reduce((u, h) => u + h, 0) / n.length, r = a.reduce((u, h) => u + h, 0) / a.length;
355
+ const s = new Uint8Array(this.localAnalyser.frequencyBinCount), i = new Uint8Array(this.remoteAnalyser.frequencyBinCount);
356
+ this.localAnalyser.getByteFrequencyData(s), this.remoteAnalyser.getByteFrequencyData(i);
357
+ const r = s.reduce((u, h) => u + h, 0) / s.length, c = i.reduce((u, h) => u + h, 0) / i.length;
347
358
  this.visualizerCallbacks.length > 0 && this.visualizerCallbacks.forEach((u) => {
348
359
  u({
349
- localAmplitude: c,
350
- remoteAmplitude: r
360
+ localAmplitude: r,
361
+ remoteAmplitude: c
351
362
  });
352
- }), this.analyzerFrame = requestAnimationFrame(s);
363
+ }), this.analyzerFrame = requestAnimationFrame(n);
353
364
  };
354
- this.analyzerFrame = requestAnimationFrame(s);
365
+ this.analyzerFrame = requestAnimationFrame(n);
355
366
  }
356
367
  _stopAnalyzers() {
357
368
  this.analyzerFrame && (cancelAnimationFrame(this.analyzerFrame), this.analyzerFrame = null), this.localAnalyser = null, this.remoteAnalyser = null;
358
369
  }
359
370
  }
360
- class I extends x {
371
+ class N extends k {
361
372
  constructor(e) {
362
373
  super();
363
374
  o(this, "status");
@@ -365,11 +376,9 @@ class I extends x {
365
376
  o(this, "autostart");
366
377
  o(this, "config");
367
378
  o(this, "webRTCClient");
368
- this.config = e, this.status = "disconnected", this.session = null, this.autostart = (e == null ? void 0 : e.autostart) ?? !1, this.webRTCClient = new Z(e), this.webRTCClient.addMessageCallback((s) => {
369
- var a;
370
- (a = e.logger) == null || a.debug("Received data message:", s.data);
371
- const n = JSON.parse(s.data);
372
- n.type === "message" && this.notifyMessage(n.payload);
379
+ this.config = e, this.status = "disconnected", this.session = null, this.autostart = (e == null ? void 0 : e.autostart) ?? !1, this.webRTCClient = new Z(e), this.webRTCClient.addMessageCallback((n) => {
380
+ const s = JSON.parse(n.data);
381
+ this.notifyMessage(s);
373
382
  });
374
383
  }
375
384
  getName() {
@@ -382,112 +391,226 @@ class I extends x {
382
391
  super.syncSession(e), this.status === "connected" && (await this.disconnect(), await this.connect(e));
383
392
  }
384
393
  async connect(e) {
385
- var s;
386
- 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);
394
+ var n;
395
+ return this.status === "connected" ? Promise.resolve(this.session) : (this.session = e || this.session || "new", this.setStatus("connecting"), (n = this.config.logger) == null || n.debug("Connecting to WebRTC with sessionId:", this.session), await this.webRTCClient.connect(this.session), this.setStatus("connected"), await this.webRTCClient.createDataChannel(), this.session);
387
396
  }
388
397
  async disconnect() {
389
- var e, s, n;
398
+ var e, n, s;
390
399
  if (this.status === "disconnected")
391
400
  return (e = this.config.logger) == null || e.warn("Already disconnected"), Promise.resolve();
392
- await this.webRTCClient.disconnect(), this.setStatus("disconnected"), (n = (s = this.config) == null ? void 0 : s.logger) == null || n.debug("Disconnected from WebRTC");
401
+ await this.webRTCClient.disconnect(), this.setStatus("disconnected"), (s = (n = this.config) == null ? void 0 : n.logger) == null || s.debug("Disconnected from WebRTC");
393
402
  }
394
403
  send(e) {
395
404
  return this.status !== "connected" ? Promise.reject(new Error("Not connected")) : (this.webRTCClient.sendMessage(e), Promise.resolve());
396
405
  }
397
406
  }
398
- const P = q(void 0);
399
- function ee({
400
- dev: i = !1,
407
+ class ee {
408
+ constructor(t) {
409
+ o(this, "config");
410
+ this.config = t;
411
+ }
412
+ async complete(t, e) {
413
+ var n;
414
+ await this.persist(t, { ...e, success: !0 }), (n = this.config.logger) == null || n.debug("Transaction completed:", t);
415
+ }
416
+ async fail(t, e) {
417
+ var n;
418
+ await this.persist(t, { ...e, success: !1 }), (n = this.config.logger) == null || n.debug("Transaction failed:", { ...t, ...e });
419
+ }
420
+ async persist(t, e) {
421
+ await fetch(`${this.config.apiUrl}/transactions/${t.id}`, {
422
+ body: JSON.stringify(e),
423
+ method: "POST",
424
+ headers: {
425
+ "Content-Type": "application/json",
426
+ Accept: "application/json",
427
+ "x-persona-apikey": this.config.apiKey
428
+ }
429
+ });
430
+ }
431
+ }
432
+ class te {
433
+ constructor(t, e) {
434
+ o(this, "transaction");
435
+ o(this, "manager");
436
+ this.transaction = t, this.manager = e;
437
+ }
438
+ getFunctionCall() {
439
+ return this.transaction.functionCall;
440
+ }
441
+ async invoke(t) {
442
+ const e = this.transaction.functionCall;
443
+ if (!e) {
444
+ await this.fail("No function call found");
445
+ return;
446
+ }
447
+ const n = e.name, s = e.args, i = t[n];
448
+ if (!i) {
449
+ await this.fail(`Tool ${n} not found`);
450
+ return;
451
+ }
452
+ try {
453
+ const r = await i(s);
454
+ await this.complete({ date: (/* @__PURE__ */ new Date()).toISOString(), result: r });
455
+ } catch (r) {
456
+ await this.fail(`Error executing tool ${n}: ${r}`);
457
+ }
458
+ }
459
+ async complete(t) {
460
+ await this.manager.complete(this.transaction, { success: !0, output: t, error: null });
461
+ }
462
+ async fail(t) {
463
+ await this.manager.fail(this.transaction, { success: !1, output: null, error: t });
464
+ }
465
+ }
466
+ class se extends k {
467
+ constructor(e) {
468
+ super();
469
+ o(this, "status");
470
+ o(this, "autostart");
471
+ o(this, "session");
472
+ o(this, "config");
473
+ o(this, "notify", !0);
474
+ this.config = e, this.status = "disconnected", this.autostart = !0;
475
+ }
476
+ getName() {
477
+ return "transaction";
478
+ }
479
+ getPriority() {
480
+ return 0;
481
+ }
482
+ async connect(e) {
483
+ return this.setStatus("connected"), e;
484
+ }
485
+ async disconnect() {
486
+ this.setStatus("disconnected"), this.session = null;
487
+ }
488
+ async syncSession(e) {
489
+ this.session = e;
490
+ }
491
+ async send(e) {
492
+ var n;
493
+ throw (n = this.config.logger) == null || n.debug("Sending message:", e), new Error("Not implemented");
494
+ }
495
+ onTransaction(e) {
496
+ var i;
497
+ if (!this.config.onTransaction) {
498
+ (i = this.config.logger) == null || i.error("Transaction protocol config is not set");
499
+ return;
500
+ }
501
+ const n = new ee(this.config), s = new te(e, n);
502
+ this.config.onTransaction(s);
503
+ }
504
+ }
505
+ const P = K(void 0);
506
+ function ne({
507
+ dev: a = !1,
401
508
  protocols: t,
402
509
  logger: e,
403
- children: s,
404
- session: n = "new",
405
- ...a
510
+ children: n,
511
+ session: s = "new",
512
+ ...i
406
513
  }) {
407
- const [c, r] = b(!1), [u, h] = b([]), [f, D] = b(n), [m, W] = b(/* @__PURE__ */ new Map()), R = K(!1), y = _(() => {
514
+ const [r, c] = S(!1), [u, h] = S([]), [m, D] = S(s), [C, O] = S(/* @__PURE__ */ new Map()), E = q(!1), y = _(() => {
408
515
  if (Array.isArray(t))
409
516
  return t;
410
517
  if (typeof t == "object" && t !== null) {
411
- const l = i ? "localhost:8000" : "persona.applica.guru/api", p = i ? "http" : "https", g = i ? "ws" : "wss";
412
- return Object.keys(t).map((d) => {
413
- switch (d) {
518
+ const l = a ? "localhost:8000" : "persona.applica.guru/api", d = a ? "http" : "https", p = a ? "ws" : "wss";
519
+ let g = Object.keys(t).map((f) => {
520
+ switch (f) {
414
521
  case "rest":
415
- const C = t[d];
416
- return C === !0 ? new T({
417
- apiUrl: `${p}://${l}`,
418
- apiKey: a.apiKey,
419
- agentId: a.agentId,
522
+ const b = t[f];
523
+ return b === !0 ? new M({
524
+ apiUrl: `${d}://${l}`,
525
+ apiKey: i.apiKey,
526
+ agentId: i.agentId,
420
527
  logger: e
421
- }) : new T(C);
528
+ }) : new M(b);
422
529
  case "webrtc":
423
- const A = t[d];
424
- return A === !0 ? new I({
425
- webrtcUrl: `${g}://${l}/webrtc`,
426
- apiKey: a.apiKey,
427
- agentId: a.agentId,
530
+ const A = t[f];
531
+ return A === !0 ? new N({
532
+ webrtcUrl: `${p}://${l}/webrtc`,
533
+ apiKey: i.apiKey,
534
+ agentId: i.agentId,
428
535
  logger: e
429
- }) : new I(A);
536
+ }) : new N(A);
430
537
  case "websocket":
431
- const E = t[d];
432
- return E === !0 ? new $({
433
- webSocketUrl: `${g}://${l}/websocket`,
434
- apiKey: a.apiKey,
435
- agentId: a.agentId,
538
+ const T = t[f];
539
+ return T === !0 ? new I({
540
+ webSocketUrl: `${p}://${l}/websocket`,
541
+ apiKey: i.apiKey,
542
+ agentId: i.agentId,
436
543
  logger: e
437
- }) : new $(E);
544
+ }) : new I(T);
438
545
  default:
439
- throw new Error(`Unknown protocol: ${d}`);
546
+ throw new Error(`Unknown protocol: ${f}`);
440
547
  }
441
548
  });
549
+ return i.tools && g.push(
550
+ new se({
551
+ apiUrl: `${d}://${l}`,
552
+ apiKey: i.apiKey,
553
+ agentId: i.agentId,
554
+ onTransaction: async (f) => {
555
+ await f.invoke(i.tools);
556
+ },
557
+ logger: e
558
+ })
559
+ ), g;
442
560
  }
443
561
  throw new Error("Invalid protocols configuration");
444
562
  }, []);
445
563
  B(() => {
446
- R.current || (R.current = !0, e == null || e.debug(
564
+ E.current || (E.current = !0, e == null || e.debug(
447
565
  "Initializing protocols: ",
448
566
  y.map((l) => l.getName())
449
567
  ), y.forEach((l) => {
450
- l.setSession(f), l.clearListeners(), l.addStatusChangeListener((p) => {
451
- e == null || e.debug(`${l.getName()} has notified new status: ${p}`), m.set(l.getName(), p), W(new Map(m));
452
- }), l.addMessageListener((p) => {
453
- h((g) => Q([...g, { ...p, protocol: l.getName() }]));
454
- }), l.autostart && l.status === "disconnected" && (e == null || e.debug(`Connecting to protocol: ${l.getName()}`), l.connect(f));
568
+ l.setSession(m), l.clearListeners(), l.addStatusChangeListener((d) => {
569
+ e == null || e.debug(`${l.getName()} has notified new status: ${d}`), C.set(l.getName(), d), O(new Map(C));
570
+ }), l.addMessageListener((d) => {
571
+ if (d.type === "message") {
572
+ const p = d.payload;
573
+ h(
574
+ (g) => Q([...g, { ...p, protocol: l.getName() }])
575
+ );
576
+ } else d.type === "transaction" && y.filter((p) => p !== l).forEach((p) => p.onTransaction(d.payload));
577
+ }), l.autostart && l.status === "disconnected" && (e == null || e.debug(`Connecting to protocol: ${l.getName()}`), l.connect(m));
455
578
  }));
456
- }, [f, y, e, m]);
457
- const L = async (l) => {
458
- var S;
459
- if (((S = l.content[0]) == null ? void 0 : S.type) !== "text") throw new Error("Only text messages are supported");
460
- const p = l.content[0].text;
461
- h((d) => [...d, { role: "user", type: "text", text: p }]), r(!0);
462
- const g = y.sort((d, C) => C.getPriority() - d.getPriority()).find((d) => d.status === "connected");
463
- await (g == null ? void 0 : g.send(p)), r(!1);
464
- }, O = v(() => (r(!1), h([]), D("new"), Promise.resolve()), []), j = v(() => Promise.resolve(), []), F = Y({
465
- isRunning: c,
579
+ }, [m, y, e, C]);
580
+ const W = async (l) => {
581
+ var g;
582
+ if (((g = l.content[0]) == null ? void 0 : g.type) !== "text") throw new Error("Only text messages are supported");
583
+ const d = l.content[0].text;
584
+ h((f) => [...f, { role: "user", type: "text", text: d }]), c(!0);
585
+ const p = y.sort((f, b) => b.getPriority() - f.getPriority()).find((f) => f.status === "connected");
586
+ await (p == null ? void 0 : p.send(d)), c(!1);
587
+ }, U = v(() => (c(!1), h([]), D("new"), Promise.resolve()), []), j = v(() => Promise.resolve(), []), L = Y({
588
+ isRunning: r,
466
589
  messages: u,
467
590
  convertMessage: X,
468
- onNew: L,
469
- onCancel: O,
591
+ onNew: W,
592
+ onCancel: U,
470
593
  onReload: j
471
594
  });
472
- return /* @__PURE__ */ k.jsx(P.Provider, { value: { protocols: y, protocolsStatus: m }, children: /* @__PURE__ */ k.jsx(G, { runtime: F, children: s }) });
595
+ return /* @__PURE__ */ x.jsx(P.Provider, { value: { protocols: y, protocolsStatus: C }, children: /* @__PURE__ */ x.jsx(G, { runtime: L, children: n }) });
473
596
  }
474
- function ae({ children: i, ...t }) {
475
- return /* @__PURE__ */ k.jsx(ee, { ...t, children: i });
597
+ function ce({ children: a, ...t }) {
598
+ return /* @__PURE__ */ x.jsx(ne, { ...t, children: a });
476
599
  }
477
- function oe() {
478
- const i = N(P);
479
- if (!i)
600
+ function le() {
601
+ const a = R(P);
602
+ if (!a)
480
603
  throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");
481
- return i;
604
+ return a;
482
605
  }
483
- function te(i) {
484
- const t = N(P);
606
+ function ie(a) {
607
+ const t = R(P);
485
608
  if (!t)
486
609
  throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");
487
- const e = t.protocols.find((n) => n.getName() === i);
610
+ const e = t.protocols.find((s) => s.getName() === a);
488
611
  if (!e)
489
612
  return null;
490
- const s = t.protocolsStatus.get(e.getName());
613
+ const n = t.protocolsStatus.get(e.getName());
491
614
  return {
492
615
  ...e,
493
616
  connect: e.connect.bind(e),
@@ -498,13 +621,22 @@ function te(i) {
498
621
  addMessageListener: e.addMessageListener.bind(e),
499
622
  getName: e.getName.bind(e),
500
623
  getPriority: e.getPriority.bind(e),
501
- status: s || e.status
624
+ status: n || e.status
502
625
  };
503
626
  }
504
- function re() {
505
- return te("webrtc");
627
+ function ue() {
628
+ const a = R(P);
629
+ if (!a)
630
+ throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");
631
+ for (const t of a.protocols)
632
+ if (t.getName() === "rest")
633
+ return t.config.apiUrl;
634
+ throw new Error("REST protocol not found");
635
+ }
636
+ function he() {
637
+ return ie("webrtc");
506
638
  }
507
- class ce {
639
+ class de {
508
640
  constructor() {
509
641
  o(this, "prefix", "[Persona]");
510
642
  }
@@ -525,14 +657,16 @@ class ce {
525
657
  }
526
658
  }
527
659
  export {
528
- ce as PersonaConsoleLogger,
529
- x as PersonaProtocolBase,
530
- T as PersonaRESTProtocol,
531
- ae as PersonaRuntimeProvider,
532
- I as PersonaWebRTCProtocol,
533
- $ as PersonaWebSocketProtocol,
534
- oe as usePersonaRuntime,
535
- te as usePersonaRuntimeProtocol,
536
- re as usePersonaRuntimeWebRTCProtocol
660
+ de as PersonaConsoleLogger,
661
+ k as PersonaProtocolBase,
662
+ M as PersonaRESTProtocol,
663
+ ce as PersonaRuntimeProvider,
664
+ se as PersonaTransactionProtocol,
665
+ N as PersonaWebRTCProtocol,
666
+ I as PersonaWebSocketProtocol,
667
+ le as usePersonaRuntime,
668
+ ue as usePersonaRuntimeEndpoint,
669
+ ie as usePersonaRuntimeProtocol,
670
+ he as usePersonaRuntimeWebRTCProtocol
537
671
  };
538
672
  //# sourceMappingURL=bundle.es.js.map