@applica-software-guru/persona-sdk 0.1.46 → 0.1.48

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