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

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.
Files changed (38) hide show
  1. package/.nvmrc +1 -1
  2. package/bitbucket-pipelines.yml +1 -1
  3. package/components.json +21 -0
  4. package/dist/bundle.cjs.js +2 -2
  5. package/dist/bundle.cjs.js.map +1 -1
  6. package/dist/bundle.es.js +280 -251
  7. package/dist/bundle.es.js.map +1 -1
  8. package/dist/bundle.iife.js +2 -2
  9. package/dist/bundle.iife.js.map +1 -1
  10. package/dist/bundle.umd.js +2 -2
  11. package/dist/bundle.umd.js.map +1 -1
  12. package/dist/protocol/base.d.ts +2 -2
  13. package/dist/protocol/base.d.ts.map +1 -1
  14. package/dist/protocol/rest.d.ts +2 -2
  15. package/dist/protocol/rest.d.ts.map +1 -1
  16. package/dist/protocol/transaction.d.ts +2 -2
  17. package/dist/protocol/transaction.d.ts.map +1 -1
  18. package/dist/protocol/webrtc.d.ts +3 -3
  19. package/dist/protocol/webrtc.d.ts.map +1 -1
  20. package/dist/protocol/websocket.d.ts +2 -2
  21. package/dist/protocol/websocket.d.ts.map +1 -1
  22. package/dist/runtime.d.ts.map +1 -1
  23. package/dist/types.d.ts +6 -2
  24. package/dist/types.d.ts.map +1 -1
  25. package/package.json +12 -6
  26. package/playground/src/chat.tsx +4 -1
  27. package/playground/src/components/assistant-ui/attachment.tsx +214 -0
  28. package/playground/src/components/assistant-ui/thread.tsx +5 -1
  29. package/playground/src/components/ui/dialog.tsx +133 -0
  30. package/playground/src/lib/utils.ts +3 -3
  31. package/playground/src/styles.css +119 -0
  32. package/src/protocol/base.ts +2 -2
  33. package/src/protocol/rest.ts +2 -2
  34. package/src/protocol/transaction.ts +2 -2
  35. package/src/protocol/webrtc.ts +5 -5
  36. package/src/protocol/websocket.ts +2 -2
  37. package/src/runtime.tsx +53 -2
  38. package/src/types.ts +8 -3
package/dist/bundle.es.js CHANGED
@@ -1,9 +1,9 @@
1
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
- import { useExternalStoreRuntime as Y, AssistantRuntimeProvider as G } from "@assistant-ui/react";
6
- var z = { exports: {} }, w = {};
2
+ var J = (a, e, t) => e in a ? F(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
+ var o = (a, e, t) => J(a, typeof e != "symbol" ? e + "" : e, t);
4
+ import { createContext as K, useContext as A, useState as k, useRef as q, useMemo as _, useEffect as B, useCallback as v } from "react";
5
+ import { useExternalStoreRuntime as Y, CompositeAttachmentAdapter as G, SimpleImageAttachmentAdapter as V, AssistantRuntimeProvider as H } from "@assistant-ui/react";
6
+ var D = { exports: {} }, b = {};
7
7
  /**
8
8
  * @license React
9
9
  * react-jsx-runtime.production.js
@@ -14,16 +14,16 @@ var z = { exports: {} }, w = {};
14
14
  * LICENSE file in the root directory of this source tree.
15
15
  */
16
16
  var $;
17
- function V() {
18
- if ($) return w;
17
+ function Q() {
18
+ if ($) return b;
19
19
  $ = 1;
20
- var a = Symbol.for("react.transitional.element"), t = Symbol.for("react.fragment");
21
- function e(n, s, i) {
20
+ var a = Symbol.for("react.transitional.element"), e = Symbol.for("react.fragment");
21
+ function t(n, s, i) {
22
22
  var r = null;
23
23
  if (i !== void 0 && (r = "" + i), s.key !== void 0 && (r = "" + s.key), "key" in s) {
24
24
  i = {};
25
- for (var c in s)
26
- c !== "key" && (i[c] = s[c]);
25
+ for (var l in s)
26
+ l !== "key" && (i[l] = s[l]);
27
27
  } else i = s;
28
28
  return s = i.ref, {
29
29
  $$typeof: a,
@@ -33,31 +33,31 @@ function V() {
33
33
  props: i
34
34
  };
35
35
  }
36
- return w.Fragment = t, w.jsx = e, w.jsxs = e, w;
36
+ return b.Fragment = e, b.jsx = t, b.jsxs = t, b;
37
37
  }
38
- z.exports = V();
39
- var x = z.exports;
40
- function H(a) {
41
- return a.filter((t) => {
42
- var e;
43
- return t.finishReason === "stop" ? t.text !== null && ((e = t.text) == null ? void 0 : e.trim()) !== "" : !0;
38
+ D.exports = Q();
39
+ var R = D.exports;
40
+ function X(a) {
41
+ return a.filter((e) => {
42
+ var t;
43
+ return e.finishReason === "stop" ? e.text !== null && ((t = e.text) == null ? void 0 : t.trim()) !== "" : !0;
44
44
  });
45
45
  }
46
- function Q(a) {
47
- const t = [];
48
- let e = null;
46
+ function Z(a) {
47
+ const e = [];
48
+ let t = null;
49
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
- ...t[t.length - 1],
50
+ s.type !== "transaction" && (s.type === "reasoning" ? (t != null && (e.push(t), t = null), e.push(s)) : s.functionCalls ? (t && e.push(t), e.push(s), t = null) : s.functionResponse ? e[e.length - 1] = {
51
+ ...e[e.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.files = [...e.files ?? [], ...s.files ?? []]) : (e && t.push(e), e = {
53
+ } : t && s.protocol === t.protocol && (t.role === s.role || s.finishReason === "stop") ? (t.text += s.text, t.files = [...t.files ?? [], ...s.files ?? []]) : (t && e.push(t), t = {
54
54
  ...s
55
55
  }));
56
- return e && t.push(e), H(t);
56
+ return t && e.push(t), X(e);
57
57
  }
58
- function X(a) {
59
- var e, n;
60
- const t = ((e = a.files) == null ? void 0 : e.map(
58
+ function tt(a) {
59
+ var t, n;
60
+ const e = ((t = a.files) == null ? void 0 : t.map(
61
61
  (s) => ({
62
62
  type: "file",
63
63
  data: s.url,
@@ -81,53 +81,53 @@ function X(a) {
81
81
  } : {
82
82
  id: a.id,
83
83
  role: a.role,
84
- content: a.type === "reasoning" ? [{ type: "reasoning", text: a.text }, ...t] : [{ type: "text", text: a.text }, ...t]
84
+ content: a.type === "reasoning" ? [{ type: "reasoning", text: a.text }, ...e] : [{ type: "text", text: a.text }, ...e]
85
85
  };
86
86
  }
87
- class k {
87
+ class P {
88
88
  constructor() {
89
89
  o(this, "statusChangeCallbacks", []);
90
90
  o(this, "messageCallbacks", []);
91
91
  }
92
- addStatusChangeListener(t) {
93
- this.statusChangeCallbacks.push(t);
92
+ addStatusChangeListener(e) {
93
+ this.statusChangeCallbacks.push(e);
94
94
  }
95
- addMessageListener(t) {
96
- this.messageCallbacks.push(t);
95
+ addMessageListener(e) {
96
+ this.messageCallbacks.push(e);
97
97
  }
98
- async syncSession(t) {
99
- this.session = t;
98
+ async syncSession(e) {
99
+ this.session = e;
100
100
  }
101
- async notifyMessage(t) {
102
- this.messageCallbacks.forEach((e) => e(t));
101
+ async notifyMessage(e) {
102
+ this.messageCallbacks.forEach((t) => t(e));
103
103
  }
104
- async notifyMessages(t) {
105
- t.forEach((e) => {
106
- this.messageCallbacks.forEach((n) => n(e));
104
+ async notifyMessages(e) {
105
+ e.forEach((t) => {
106
+ this.messageCallbacks.forEach((n) => n(t));
107
107
  });
108
108
  }
109
- async setSession(t) {
110
- this.session = t;
109
+ async setSession(e) {
110
+ this.session = e;
111
111
  }
112
- async setStatus(t) {
113
- const e = this.status !== t;
114
- this.status = t, e && this.statusChangeCallbacks.forEach((n) => n(t));
112
+ async setStatus(e) {
113
+ const t = this.status !== e;
114
+ this.status = e, t && this.statusChangeCallbacks.forEach((n) => n(e));
115
115
  }
116
116
  clearListeners() {
117
117
  this.statusChangeCallbacks = [], this.messageCallbacks = [];
118
118
  }
119
- onTransaction(t) {
119
+ onTransaction(e) {
120
120
  }
121
121
  }
122
- class M extends k {
123
- constructor(e) {
122
+ class M extends P {
123
+ constructor(t) {
124
124
  super();
125
125
  o(this, "status");
126
126
  o(this, "autostart");
127
127
  o(this, "session");
128
128
  o(this, "config");
129
129
  o(this, "notify", !0);
130
- this.config = e, this.status = "disconnected", this.autostart = !0;
130
+ this.config = t, this.status = "disconnected", this.autostart = !0;
131
131
  }
132
132
  getName() {
133
133
  return "rest";
@@ -135,18 +135,18 @@ class M extends k {
135
135
  getPriority() {
136
136
  return 0;
137
137
  }
138
- async connect(e) {
139
- return this.setStatus("connected"), e;
138
+ async connect(t) {
139
+ return this.setStatus("connected"), t;
140
140
  }
141
141
  async disconnect() {
142
142
  this.setStatus("disconnected"), this.session = null;
143
143
  }
144
- async syncSession(e) {
145
- this.session = e;
144
+ async syncSession(t) {
145
+ this.session = t;
146
146
  }
147
- async send(e) {
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 }),
147
+ async send(t) {
148
+ const { apiUrl: n, apiKey: s, agentId: i } = this.config, r = this.session ?? "new", l = t, h = await (await fetch(`${n}/agents/${i}/sessions/${r}/messages`, {
149
+ body: JSON.stringify({ userMessage: l }),
150
150
  method: "POST",
151
151
  headers: {
152
152
  "Content-Type": "application/json",
@@ -155,22 +155,22 @@ class M extends k {
155
155
  }
156
156
  })).json();
157
157
  this.notifyMessages(
158
- h.response.messages.map((m) => ({
158
+ h.response.messages.map((w) => ({
159
159
  type: "message",
160
- payload: m
160
+ payload: w
161
161
  }))
162
162
  );
163
163
  }
164
164
  }
165
- class I extends k {
166
- constructor(e) {
165
+ class I extends P {
166
+ constructor(t) {
167
167
  super();
168
168
  o(this, "status");
169
169
  o(this, "autostart");
170
170
  o(this, "session");
171
171
  o(this, "config");
172
172
  o(this, "webSocket");
173
- this.config = e, this.status = "disconnected", this.autostart = !0, this.session = null, this.webSocket = null;
173
+ this.config = t, this.status = "disconnected", this.autostart = !0, this.session = null, this.webSocket = null;
174
174
  }
175
175
  getName() {
176
176
  return "websocket";
@@ -178,16 +178,16 @@ class I extends k {
178
178
  getPriority() {
179
179
  return 1;
180
180
  }
181
- async syncSession(e) {
181
+ async syncSession(t) {
182
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));
183
+ (n = this.config.logger) == null || n.debug("Syncing session with WebSocket protocol:", t), this.session = t, this.webSocket && this.status === "connected" && (this.disconnect(), this.connect(t));
184
184
  }
185
- connect(e) {
186
- var c;
185
+ connect(t) {
186
+ var l;
187
187
  if (this.webSocket !== null && this.status === "connected")
188
188
  return Promise.resolve(this.session);
189
- const n = e || this.session || "new";
190
- (c = this.config.logger) == null || c.debug("Connecting to WebSocket with sessionId:", n);
189
+ const n = t || this.session || "new";
190
+ (l = this.config.logger) == null || l.debug("Connecting to WebSocket with sessionId:", n);
191
191
  const s = encodeURIComponent(this.config.apiKey), i = this.config.agentId, r = `${this.config.webSocketUrl}?sessionCode=${n}&agentId=${i}&apiKey=${s}`;
192
192
  return this.setStatus("connecting"), this.webSocket = new WebSocket(r), this.webSocket.addEventListener("open", () => {
193
193
  this.setStatus("connected");
@@ -203,15 +203,15 @@ class I extends k {
203
203
  }), Promise.resolve(n);
204
204
  }
205
205
  disconnect() {
206
- var e;
207
- 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();
206
+ var t;
207
+ return (t = this.config.logger) == null || t.debug("Disconnecting WebSocket"), this.webSocket && this.status === "connected" && (this.webSocket.close(), this.setStatus("disconnected"), this.webSocket = null), Promise.resolve();
208
208
  }
209
- send(e) {
210
- return this.webSocket && this.status === "connected" ? (this.webSocket.send(JSON.stringify({ type: "request", payload: e })), Promise.resolve()) : Promise.reject(new Error("WebSocket is not connected"));
209
+ send(t) {
210
+ return this.webSocket && this.status === "connected" ? (this.webSocket.send(JSON.stringify({ type: "request", payload: t })), Promise.resolve()) : Promise.reject(new Error("WebSocket is not connected"));
211
211
  }
212
212
  }
213
- class Z {
214
- constructor(t) {
213
+ class et {
214
+ constructor(e) {
215
215
  o(this, "config");
216
216
  o(this, "pc", null);
217
217
  o(this, "ws", null);
@@ -225,9 +225,9 @@ class Z {
225
225
  o(this, "isConnected", !1);
226
226
  o(this, "visualizerCallbacks", []);
227
227
  o(this, "messageCallbacks", []);
228
- this.config = t;
228
+ this.config = e;
229
229
  }
230
- async connect(t) {
230
+ async connect(e) {
231
231
  var n;
232
232
  if (this.isConnected) return;
233
233
  this.isConnected = !0;
@@ -256,8 +256,8 @@ class Z {
256
256
  }), this.audioCtx || this._startAnalyzers();
257
257
  const i = new Audio();
258
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);
259
+ var l;
260
+ (l = this.config.logger) == null || l.error("Error playing remote audio:", r);
261
261
  });
262
262
  }, this.pc.onicecandidate = (s) => {
263
263
  var i;
@@ -271,22 +271,22 @@ class Z {
271
271
  }, this.pc.ondatachannel = (s) => {
272
272
  const i = s.channel;
273
273
  i.onmessage = (r) => {
274
- this.messageCallbacks.forEach((c) => {
275
- c(r);
274
+ this.messageCallbacks.forEach((l) => {
275
+ l(r);
276
276
  });
277
277
  };
278
278
  };
279
- const e = this.config.webrtcUrl || "wss://persona.applica.guru/api/webrtc";
280
- this.ws = new WebSocket(`${e}?apiKey=${encodeURIComponent(this.config.apiKey)}`), this.ws.onopen = async () => {
281
- var c, u;
279
+ const t = this.config.webrtcUrl || "wss://persona.applica.guru/api/webrtc";
280
+ this.ws = new WebSocket(`${t}?apiKey=${encodeURIComponent(this.config.apiKey)}`), this.ws.onopen = async () => {
281
+ var l, u;
282
282
  const s = await this.pc.createOffer();
283
283
  await this.pc.setLocalDescription(s);
284
284
  const i = {
285
285
  apiKey: this.config.apiKey,
286
286
  agentId: this.config.agentId,
287
- sessionCode: t
287
+ sessionCode: e
288
288
  };
289
- (c = this.config.logger) == null || c.debug("Opening connection to WebRTC server: ", i);
289
+ (l = this.config.logger) == null || l.debug("Opening connection to WebRTC server: ", i);
290
290
  const r = {
291
291
  type: "OFFER",
292
292
  src: ((u = crypto.randomUUID) == null ? void 0 : u.call(crypto)) || "client_" + Date.now(),
@@ -308,57 +308,57 @@ class Z {
308
308
  else if (i.type === "CANDIDATE")
309
309
  try {
310
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);
311
+ } catch (l) {
312
+ (r = this.config.logger) == null || r.error("Error adding ICE candidate:", l);
313
313
  }
314
314
  }, this.ws.onclose = () => {
315
315
  this._stopAnalyzers();
316
316
  };
317
317
  }
318
318
  async disconnect() {
319
- var t;
320
- 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());
319
+ var e;
320
+ this.isConnected && (this.isConnected = !1, ((e = this.ws) == null ? void 0 : e.readyState) === WebSocket.OPEN && this.ws.close(), this.pc && this.pc.close(), this.localStream && this.localStream.getTracks().forEach((t) => t.stop()), this.remoteStream = new MediaStream(), this.audioCtx && (await this.audioCtx.close(), this.audioCtx = null), this._stopAnalyzers());
321
321
  }
322
- addVisualizerCallback(t) {
323
- this.visualizerCallbacks.push(t);
322
+ addVisualizerCallback(e) {
323
+ this.visualizerCallbacks.push(e);
324
324
  }
325
- addMessageCallback(t) {
326
- this.messageCallbacks.push(t);
325
+ addMessageCallback(e) {
326
+ this.messageCallbacks.push(e);
327
327
  }
328
- createDataChannel(t = "messages") {
329
- this.pc && (this.dataChannel = this.pc.createDataChannel(t), this.dataChannel.onopen = () => {
330
- var e;
331
- return (e = this.config.logger) == null ? void 0 : e.info("Data channel opened");
332
- }, this.dataChannel.onmessage = (e) => {
328
+ createDataChannel(e = "messages") {
329
+ this.pc && (this.dataChannel = this.pc.createDataChannel(e), this.dataChannel.onopen = () => {
330
+ var t;
331
+ return (t = this.config.logger) == null ? void 0 : t.info("Data channel opened");
332
+ }, this.dataChannel.onmessage = (t) => {
333
333
  this.messageCallbacks.forEach((n) => {
334
- n(e);
334
+ n(t);
335
335
  });
336
336
  });
337
337
  }
338
- sendMessage(t) {
339
- var e, n;
338
+ sendMessage(e) {
339
+ var t, n;
340
340
  if (!this.dataChannel) {
341
- (e = this.config.logger) == null || e.warn("Data channel is not open, cannot send message");
341
+ (t = this.config.logger) == null || t.warn("Data channel is not open, cannot send message");
342
342
  return;
343
343
  }
344
- this.dataChannel.send(t), (n = this.config.logger) == null || n.info("Sent message:", t);
344
+ this.dataChannel.send(JSON.stringify({ type: "request", payload: e })), (n = this.config.logger) == null || n.info("Sent message:", e);
345
345
  }
346
346
  _startAnalyzers() {
347
347
  if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0)
348
348
  return;
349
349
  this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
350
- const t = this.audioCtx.createMediaStreamSource(this.localStream), e = this.audioCtx.createMediaStreamSource(this.remoteStream);
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);
350
+ const e = this.audioCtx.createMediaStreamSource(this.localStream), t = this.audioCtx.createMediaStreamSource(this.remoteStream);
351
+ this.localAnalyser = this.audioCtx.createAnalyser(), this.remoteAnalyser = this.audioCtx.createAnalyser(), this.localAnalyser.fftSize = 256, this.remoteAnalyser.fftSize = 256, e.connect(this.localAnalyser), t.connect(this.remoteAnalyser);
352
352
  const n = () => {
353
353
  if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0)
354
354
  return;
355
355
  const s = new Uint8Array(this.localAnalyser.frequencyBinCount), i = new Uint8Array(this.remoteAnalyser.frequencyBinCount);
356
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;
357
+ const r = s.reduce((u, h) => u + h, 0) / s.length, l = i.reduce((u, h) => u + h, 0) / i.length;
358
358
  this.visualizerCallbacks.length > 0 && this.visualizerCallbacks.forEach((u) => {
359
359
  u({
360
360
  localAmplitude: r,
361
- remoteAmplitude: c
361
+ remoteAmplitude: l
362
362
  });
363
363
  }), this.analyzerFrame = requestAnimationFrame(n);
364
364
  };
@@ -368,15 +368,15 @@ class Z {
368
368
  this.analyzerFrame && (cancelAnimationFrame(this.analyzerFrame), this.analyzerFrame = null), this.localAnalyser = null, this.remoteAnalyser = null;
369
369
  }
370
370
  }
371
- class N extends k {
372
- constructor(e) {
371
+ class N extends P {
372
+ constructor(t) {
373
373
  super();
374
374
  o(this, "status");
375
375
  o(this, "session");
376
376
  o(this, "autostart");
377
377
  o(this, "config");
378
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) => {
379
+ this.config = t, this.status = "disconnected", this.session = null, this.autostart = (t == null ? void 0 : t.autostart) ?? !1, this.webRTCClient = new et(t), this.webRTCClient.addMessageCallback((n) => {
380
380
  const s = JSON.parse(n.data);
381
381
  this.notifyMessage(s);
382
382
  });
@@ -387,39 +387,39 @@ class N extends k {
387
387
  getPriority() {
388
388
  return 10;
389
389
  }
390
- async syncSession(e) {
391
- super.syncSession(e), this.status === "connected" && (await this.disconnect(), await this.connect(e));
390
+ async syncSession(t) {
391
+ super.syncSession(t), this.status === "connected" && (await this.disconnect(), await this.connect(t));
392
392
  }
393
- async connect(e) {
393
+ async connect(t) {
394
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);
395
+ return this.status === "connected" ? Promise.resolve(this.session) : (this.session = t || 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);
396
396
  }
397
397
  async disconnect() {
398
- var e, n, s;
398
+ var t, n, s;
399
399
  if (this.status === "disconnected")
400
- return (e = this.config.logger) == null || e.warn("Already disconnected"), Promise.resolve();
400
+ return (t = this.config.logger) == null || t.warn("Already disconnected"), Promise.resolve();
401
401
  await this.webRTCClient.disconnect(), this.setStatus("disconnected"), (s = (n = this.config) == null ? void 0 : n.logger) == null || s.debug("Disconnected from WebRTC");
402
402
  }
403
- send(e) {
404
- return this.status !== "connected" ? Promise.reject(new Error("Not connected")) : (this.webRTCClient.sendMessage(e), Promise.resolve());
403
+ send(t) {
404
+ return this.status !== "connected" ? Promise.reject(new Error("Not connected")) : (this.webRTCClient.sendMessage(t), Promise.resolve());
405
405
  }
406
406
  }
407
- class ee {
408
- constructor(t) {
407
+ class st {
408
+ constructor(e) {
409
409
  o(this, "config");
410
- this.config = t;
410
+ this.config = e;
411
411
  }
412
- async complete(t, e) {
412
+ async complete(e, t) {
413
413
  var n;
414
- await this.persist(t, { ...e, success: !0 }), (n = this.config.logger) == null || n.debug("Transaction completed:", t);
414
+ await this.persist(e, { ...t, success: !0 }), (n = this.config.logger) == null || n.debug("Transaction completed:", e);
415
415
  }
416
- async fail(t, e) {
416
+ async fail(e, t) {
417
417
  var n;
418
- await this.persist(t, { ...e, success: !1 }), (n = this.config.logger) == null || n.debug("Transaction failed:", { ...t, ...e });
418
+ await this.persist(e, { ...t, success: !1 }), (n = this.config.logger) == null || n.debug("Transaction failed:", { ...e, ...t });
419
419
  }
420
- async persist(t, e) {
421
- await fetch(`${this.config.apiUrl}/transactions/${t.id}`, {
422
- body: JSON.stringify(e),
420
+ async persist(e, t) {
421
+ await fetch(`${this.config.apiUrl}/transactions/${e.id}`, {
422
+ body: JSON.stringify(t),
423
423
  method: "POST",
424
424
  headers: {
425
425
  "Content-Type": "application/json",
@@ -429,22 +429,22 @@ class ee {
429
429
  });
430
430
  }
431
431
  }
432
- class te {
433
- constructor(t, e) {
432
+ class nt {
433
+ constructor(e, t) {
434
434
  o(this, "transaction");
435
435
  o(this, "manager");
436
- this.transaction = t, this.manager = e;
436
+ this.transaction = e, this.manager = t;
437
437
  }
438
438
  getFunctionCall() {
439
439
  return this.transaction.functionCall;
440
440
  }
441
- async invoke(t) {
442
- const e = this.transaction.functionCall;
443
- if (!e) {
441
+ async invoke(e) {
442
+ const t = this.transaction.functionCall;
443
+ if (!t) {
444
444
  await this.fail("No function call found");
445
445
  return;
446
446
  }
447
- const n = e.name, s = e.args, i = t[n];
447
+ const n = t.name, s = t.args, i = e[n];
448
448
  if (!i) {
449
449
  await this.fail(`Tool ${n} not found`);
450
450
  return;
@@ -456,22 +456,22 @@ class te {
456
456
  await this.fail(`Error executing tool ${n}: ${r}`);
457
457
  }
458
458
  }
459
- async complete(t) {
460
- await this.manager.complete(this.transaction, { success: !0, output: t, error: null });
459
+ async complete(e) {
460
+ await this.manager.complete(this.transaction, { success: !0, output: e, error: null });
461
461
  }
462
- async fail(t) {
463
- await this.manager.fail(this.transaction, { success: !1, output: null, error: t });
462
+ async fail(e) {
463
+ await this.manager.fail(this.transaction, { success: !1, output: null, error: e });
464
464
  }
465
465
  }
466
- class se extends k {
467
- constructor(e) {
466
+ class it extends P {
467
+ constructor(t) {
468
468
  super();
469
469
  o(this, "status");
470
470
  o(this, "autostart");
471
471
  o(this, "session");
472
472
  o(this, "config");
473
473
  o(this, "notify", !0);
474
- this.config = e, this.status = "disconnected", this.autostart = !0;
474
+ this.config = t, this.status = "disconnected", this.autostart = !0;
475
475
  }
476
476
  getName() {
477
477
  return "transaction";
@@ -479,194 +479,223 @@ class se extends k {
479
479
  getPriority() {
480
480
  return 0;
481
481
  }
482
- async connect(e) {
483
- return this.setStatus("connected"), e;
482
+ async connect(t) {
483
+ return this.setStatus("connected"), t;
484
484
  }
485
485
  async disconnect() {
486
486
  this.setStatus("disconnected"), this.session = null;
487
487
  }
488
- async syncSession(e) {
489
- this.session = e;
488
+ async syncSession(t) {
489
+ this.session = t;
490
490
  }
491
- async send(e) {
491
+ async send(t) {
492
492
  var n;
493
- throw (n = this.config.logger) == null || n.debug("Sending message:", e), new Error("Not implemented");
493
+ throw (n = this.config.logger) == null || n.debug("Sending message:", t), new Error("Not implemented");
494
494
  }
495
- onTransaction(e) {
495
+ onTransaction(t) {
496
496
  var i;
497
497
  if (!this.config.onTransaction) {
498
498
  (i = this.config.logger) == null || i.error("Transaction protocol config is not set");
499
499
  return;
500
500
  }
501
- const n = new ee(this.config), s = new te(e, n);
501
+ const n = new st(this.config), s = new nt(t, n);
502
502
  this.config.onTransaction(s);
503
503
  }
504
504
  }
505
- const P = K(void 0);
506
- function ne({
505
+ const x = K(void 0);
506
+ function at(a) {
507
+ return new Promise((e, t) => {
508
+ const n = new FileReader();
509
+ n.readAsDataURL(a), n.onload = () => {
510
+ const i = n.result.split(";base64,")[1];
511
+ e(i);
512
+ }, n.onerror = (s) => {
513
+ t(s);
514
+ };
515
+ });
516
+ }
517
+ function ot({
507
518
  dev: a = !1,
508
- protocols: t,
509
- logger: e,
519
+ protocols: e,
520
+ logger: t,
510
521
  children: n,
511
522
  session: s = "new",
512
523
  ...i
513
524
  }) {
514
- const [r, c] = S(!1), [u, h] = S([]), [m, D] = S(s), [C, O] = S(/* @__PURE__ */ new Map()), E = q(!1), y = _(() => {
515
- if (Array.isArray(t))
516
- return t;
517
- if (typeof t == "object" && t !== null) {
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) {
525
+ const [r, l] = k(!1), [u, h] = k([]), [w, z] = k(s), [S, W] = k(/* @__PURE__ */ new Map()), E = q(!1), m = _(() => {
526
+ if (Array.isArray(e))
527
+ return e;
528
+ if (typeof e == "object" && e !== null) {
529
+ const c = a ? "localhost:8000" : "persona.applica.guru/api", f = a ? "http" : "https", p = a ? "ws" : "wss";
530
+ let y = Object.keys(e).map((g) => {
531
+ switch (g) {
521
532
  case "rest":
522
- const b = t[f];
523
- return b === !0 ? new M({
524
- apiUrl: `${d}://${l}`,
533
+ const d = e[g];
534
+ return d === !0 ? new M({
535
+ apiUrl: `${f}://${c}`,
525
536
  apiKey: i.apiKey,
526
537
  agentId: i.agentId,
527
- logger: e
528
- }) : new M(b);
538
+ logger: t
539
+ }) : new M(d);
529
540
  case "webrtc":
530
- const A = t[f];
531
- return A === !0 ? new N({
532
- webrtcUrl: `${p}://${l}/webrtc`,
541
+ const C = e[g];
542
+ return C === !0 ? new N({
543
+ webrtcUrl: `${p}://${c}/webrtc`,
533
544
  apiKey: i.apiKey,
534
545
  agentId: i.agentId,
535
- logger: e
536
- }) : new N(A);
546
+ logger: t
547
+ }) : new N(C);
537
548
  case "websocket":
538
- const T = t[f];
549
+ const T = e[g];
539
550
  return T === !0 ? new I({
540
- webSocketUrl: `${p}://${l}/websocket`,
551
+ webSocketUrl: `${p}://${c}/websocket`,
541
552
  apiKey: i.apiKey,
542
553
  agentId: i.agentId,
543
- logger: e
554
+ logger: t
544
555
  }) : new I(T);
545
556
  default:
546
- throw new Error(`Unknown protocol: ${f}`);
557
+ throw new Error(`Unknown protocol: ${g}`);
547
558
  }
548
559
  });
549
- return i.tools && g.push(
550
- new se({
551
- apiUrl: `${d}://${l}`,
560
+ return i.tools && y.push(
561
+ new it({
562
+ apiUrl: `${f}://${c}`,
552
563
  apiKey: i.apiKey,
553
564
  agentId: i.agentId,
554
- onTransaction: async (f) => {
555
- await f.invoke(i.tools);
565
+ onTransaction: async (g) => {
566
+ await g.invoke(i.tools);
556
567
  },
557
- logger: e
568
+ logger: t
558
569
  })
559
- ), g;
570
+ ), y;
560
571
  }
561
572
  throw new Error("Invalid protocols configuration");
562
573
  }, []);
563
574
  B(() => {
564
- E.current || (E.current = !0, e == null || e.debug(
575
+ E.current || (E.current = !0, t == null || t.debug(
565
576
  "Initializing protocols: ",
566
- y.map((l) => l.getName())
567
- ), y.forEach((l) => {
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;
577
+ m.map((c) => c.getName())
578
+ ), m.forEach((c) => {
579
+ c.setSession(w), c.clearListeners(), c.addStatusChangeListener((f) => {
580
+ t == null || t.debug(`${c.getName()} has notified new status: ${f}`), S.set(c.getName(), f), W(new Map(S));
581
+ }), c.addMessageListener((f) => {
582
+ if (f.type === "message") {
583
+ const p = f.payload;
573
584
  h(
574
- (g) => Q([...g, { ...p, protocol: l.getName() }])
585
+ (y) => Z([...y, { ...p, protocol: c.getName() }])
575
586
  );
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));
587
+ } else f.type === "transaction" && m.filter((p) => p !== c).forEach((p) => p.onTransaction(f.payload));
588
+ }), c.autostart && c.status === "disconnected" && (t == null || t.debug(`Connecting to protocol: ${c.getName()}`), c.connect(w));
578
589
  }));
579
- }, [m, y, e, C]);
580
- const W = async (l) => {
590
+ }, [w, m, t, S]);
591
+ const O = async (c) => {
581
592
  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({
593
+ if (((g = c.content[0]) == null ? void 0 : g.type) !== "text") throw new Error("Only text messages are supported");
594
+ const f = c.content[0].text;
595
+ h((d) => [...d, { role: "user", type: "text", text: f }]), l(!0);
596
+ const p = m.sort((d, C) => C.getPriority() - d.getPriority()).find((d) => d.status === "connected"), y = [];
597
+ if (c.attachments)
598
+ for (const d of c.attachments)
599
+ d.contentType.startsWith("image/") && d.file && y.push({
600
+ role: "user",
601
+ image: {
602
+ contentType: d.contentType,
603
+ content: await at(d.file)
604
+ },
605
+ text: "",
606
+ type: "text"
607
+ });
608
+ c.content && y.push({
609
+ role: "user",
610
+ text: c.content[0].text,
611
+ type: "text"
612
+ }), t == null || t.debug("Sending message:", y), await (p == null ? void 0 : p.send(y)), l(!1);
613
+ }, U = v(() => (l(!1), h([]), z("new"), Promise.resolve()), []), L = v(() => Promise.resolve(), []), j = Y({
588
614
  isRunning: r,
589
615
  messages: u,
590
- convertMessage: X,
591
- onNew: W,
616
+ convertMessage: tt,
617
+ onNew: O,
592
618
  onCancel: U,
593
- onReload: j
619
+ onReload: L,
620
+ adapters: {
621
+ attachments: new G([new V()])
622
+ }
594
623
  });
595
- return /* @__PURE__ */ x.jsx(P.Provider, { value: { protocols: y, protocolsStatus: C }, children: /* @__PURE__ */ x.jsx(G, { runtime: L, children: n }) });
624
+ return /* @__PURE__ */ R.jsx(x.Provider, { value: { protocols: m, protocolsStatus: S }, children: /* @__PURE__ */ R.jsx(H, { runtime: j, children: n }) });
596
625
  }
597
- function ce({ children: a, ...t }) {
598
- return /* @__PURE__ */ x.jsx(ne, { ...t, children: a });
626
+ function ht({ children: a, ...e }) {
627
+ return /* @__PURE__ */ R.jsx(ot, { ...e, children: a });
599
628
  }
600
- function le() {
601
- const a = R(P);
629
+ function dt() {
630
+ const a = A(x);
602
631
  if (!a)
603
632
  throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");
604
633
  return a;
605
634
  }
606
- function ie(a) {
607
- const t = R(P);
608
- if (!t)
609
- throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");
610
- const e = t.protocols.find((s) => s.getName() === a);
635
+ function rt(a) {
636
+ const e = A(x);
611
637
  if (!e)
638
+ throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");
639
+ const t = e.protocols.find((s) => s.getName() === a);
640
+ if (!t)
612
641
  return null;
613
- const n = t.protocolsStatus.get(e.getName());
642
+ const n = e.protocolsStatus.get(t.getName());
614
643
  return {
615
- ...e,
616
- connect: e.connect.bind(e),
617
- disconnect: e.disconnect.bind(e),
618
- send: e.send.bind(e),
619
- setSession: e.setSession.bind(e),
620
- addStatusChangeListener: e.addStatusChangeListener.bind(e),
621
- addMessageListener: e.addMessageListener.bind(e),
622
- getName: e.getName.bind(e),
623
- getPriority: e.getPriority.bind(e),
624
- status: n || e.status
644
+ ...t,
645
+ connect: t.connect.bind(t),
646
+ disconnect: t.disconnect.bind(t),
647
+ send: t.send.bind(t),
648
+ setSession: t.setSession.bind(t),
649
+ addStatusChangeListener: t.addStatusChangeListener.bind(t),
650
+ addMessageListener: t.addMessageListener.bind(t),
651
+ getName: t.getName.bind(t),
652
+ getPriority: t.getPriority.bind(t),
653
+ status: n || t.status
625
654
  };
626
655
  }
627
- function ue() {
628
- const a = R(P);
656
+ function ft() {
657
+ const a = A(x);
629
658
  if (!a)
630
659
  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;
660
+ for (const e of a.protocols)
661
+ if (e.getName() === "rest")
662
+ return e.config.apiUrl;
634
663
  throw new Error("REST protocol not found");
635
664
  }
636
- function he() {
637
- return ie("webrtc");
665
+ function pt() {
666
+ return rt("webrtc");
638
667
  }
639
- class de {
668
+ class gt {
640
669
  constructor() {
641
670
  o(this, "prefix", "[Persona]");
642
671
  }
643
- log(t, ...e) {
644
- console.log(`${this.prefix} - ${t}`, ...e);
672
+ log(e, ...t) {
673
+ console.log(`${this.prefix} - ${e}`, ...t);
645
674
  }
646
- info(t, ...e) {
647
- console.info(`${this.prefix} - ${t}`, ...e);
675
+ info(e, ...t) {
676
+ console.info(`${this.prefix} - ${e}`, ...t);
648
677
  }
649
- warn(t, ...e) {
650
- console.warn(`${this.prefix} - ${t}`, ...e);
678
+ warn(e, ...t) {
679
+ console.warn(`${this.prefix} - ${e}`, ...t);
651
680
  }
652
- error(t, ...e) {
653
- console.error(`${this.prefix} - ${t}`, ...e);
681
+ error(e, ...t) {
682
+ console.error(`${this.prefix} - ${e}`, ...t);
654
683
  }
655
- debug(t, ...e) {
656
- console.debug(`${this.prefix} - ${t}`, ...e);
684
+ debug(e, ...t) {
685
+ console.debug(`${this.prefix} - ${e}`, ...t);
657
686
  }
658
687
  }
659
688
  export {
660
- de as PersonaConsoleLogger,
661
- k as PersonaProtocolBase,
689
+ gt as PersonaConsoleLogger,
690
+ P as PersonaProtocolBase,
662
691
  M as PersonaRESTProtocol,
663
- ce as PersonaRuntimeProvider,
664
- se as PersonaTransactionProtocol,
692
+ ht as PersonaRuntimeProvider,
693
+ it as PersonaTransactionProtocol,
665
694
  N as PersonaWebRTCProtocol,
666
695
  I as PersonaWebSocketProtocol,
667
- le as usePersonaRuntime,
668
- ue as usePersonaRuntimeEndpoint,
669
- ie as usePersonaRuntimeProtocol,
670
- he as usePersonaRuntimeWebRTCProtocol
696
+ dt as usePersonaRuntime,
697
+ ft as usePersonaRuntimeEndpoint,
698
+ rt as usePersonaRuntimeProtocol,
699
+ pt as usePersonaRuntimeWebRTCProtocol
671
700
  };
672
701
  //# sourceMappingURL=bundle.es.js.map