@applica-software-guru/persona-sdk 0.1.61 → 0.1.62

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
- var K = Object.defineProperty;
2
- var q = (i, t, e) => t in i ? K(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
- var o = (i, t, e) => q(i, typeof t != "symbol" ? t + "" : t, e);
4
- import { createContext as _, useContext as R, useState as x, useRef as B, useMemo as Y, useEffect as G, useCallback as E } from "react";
1
+ var J = Object.defineProperty;
2
+ var K = (a, e, t) => e in a ? J(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
+ var o = (a, e, t) => K(a, typeof e != "symbol" ? e + "" : e, t);
4
+ import { createContext as q, useContext as A, useState as R, useRef as B, useMemo as Y, useEffect as G, useCallback as T } from "react";
5
5
  import { useExternalStoreRuntime as V, CompositeAttachmentAdapter as H, SimpleImageAttachmentAdapter as Q, AssistantRuntimeProvider as X } from "@assistant-ui/react";
6
- var D = { exports: {} }, C = {};
6
+ var U = { exports: {} }, S = {};
7
7
  /**
8
8
  * @license React
9
9
  * react-jsx-runtime.production.js
@@ -13,121 +13,122 @@ var D = { exports: {} }, C = {};
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 N;
17
17
  function Z() {
18
- if (M) return C;
19
- M = 1;
20
- var i = Symbol.for("react.transitional.element"), t = Symbol.for("react.fragment");
21
- function e(n, s, a) {
18
+ if (N) return S;
19
+ N = 1;
20
+ var a = Symbol.for("react.transitional.element"), e = Symbol.for("react.fragment");
21
+ function t(n, s, i) {
22
22
  var c = null;
23
- if (a !== void 0 && (c = "" + a), s.key !== void 0 && (c = "" + s.key), "key" in s) {
24
- a = {};
23
+ if (i !== void 0 && (c = "" + i), s.key !== void 0 && (c = "" + s.key), "key" in s) {
24
+ i = {};
25
25
  for (var l in s)
26
- l !== "key" && (a[l] = s[l]);
27
- } else a = s;
28
- return s = a.ref, {
29
- $$typeof: i,
26
+ l !== "key" && (i[l] = s[l]);
27
+ } else i = s;
28
+ return s = i.ref, {
29
+ $$typeof: a,
30
30
  type: n,
31
31
  key: c,
32
32
  ref: s !== void 0 ? s : null,
33
- props: a
33
+ props: i
34
34
  };
35
35
  }
36
- return C.Fragment = t, C.jsx = e, C.jsxs = e, C;
36
+ return S.Fragment = e, S.jsx = t, S.jsxs = t, S;
37
37
  }
38
- D.exports = Z();
39
- var T = D.exports;
40
- function ee(i) {
41
- return i.filter((t) => {
42
- var e;
43
- return t.finishReason === "stop" ? t.text !== null && ((e = t.text) == null ? void 0 : e.trim()) !== "" : !0;
38
+ U.exports = Z();
39
+ var v = U.exports;
40
+ function tt(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 $(i) {
47
- const t = [];
48
- let e = null;
49
- for (const s of i)
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],
46
+ function I(a) {
47
+ const e = [];
48
+ let t = null;
49
+ for (const s of a)
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), ee(t);
56
+ return t && e.push(t), tt(e);
57
57
  }
58
- function te(i) {
59
- var e, n;
60
- const t = ((e = i.files) == null ? void 0 : e.map(
58
+ function et(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,
64
64
  mimeType: s.contentType
65
65
  })
66
66
  )) ?? [];
67
- return i.role === "function" ? {
68
- id: i.id,
67
+ return a.role === "function" ? {
68
+ id: a.id,
69
69
  role: "assistant",
70
- status: (i == null ? void 0 : i.functionResponse) === null ? { type: "running" } : { type: "complete", reason: "stop" },
71
- content: ((n = i.functionCalls) == null ? void 0 : n.map((s) => {
72
- var a;
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;
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: (a = i.functionResponse) == null ? void 0 : a.result
78
+ result: (i = a.functionResponse) == null ? void 0 : i.result
79
79
  };
80
80
  })) ?? []
81
81
  } : {
82
- id: i.id,
83
- role: i.role,
84
- content: i.type === "reasoning" ? [{ type: "reasoning", text: i.text }, ...t] : [{ type: "text", text: i.text }, ...t]
82
+ id: a.id,
83
+ role: a.role,
84
+ content: a.type === "reasoning" ? [{ type: "reasoning", text: a.text }, ...e] : [{ type: "text", text: a.text }, ...e]
85
85
  };
86
86
  }
87
- class A {
87
+ class E {
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
+ addPacketListener(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 notifyPacket(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 notifyPackets(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 N extends A {
123
- constructor(e) {
122
+ class M extends E {
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
+ o(this, "context", {});
131
+ this.config = t, this.status = "disconnected", this.autostart = !0;
131
132
  }
132
133
  getName() {
133
134
  return "rest";
@@ -135,42 +136,47 @@ class N extends A {
135
136
  getPriority() {
136
137
  return 100;
137
138
  }
138
- async connect(e) {
139
- return this.setStatus("connected"), e;
139
+ async connect(t) {
140
+ return this.setStatus("connected"), t;
140
141
  }
141
142
  async disconnect() {
142
143
  this.setStatus("disconnected"), this.session = null;
143
144
  }
144
- async syncSession(e) {
145
- this.session = e;
145
+ async syncSession(t) {
146
+ this.session = t;
146
147
  }
147
- async send(e) {
148
- const { apiUrl: n, apiKey: s, agentId: a } = this.config, c = this.session ?? "new", l = e, f = await (await fetch(`${n}/agents/${a}/sessions/${c}/messages`, {
149
- body: JSON.stringify({ userMessage: l }),
148
+ async sendPacket(t) {
149
+ var g, k;
150
+ const { apiUrl: n, apiKey: s, agentId: i } = this.config, c = this.session ?? "new";
151
+ if (t.type === "command" && ((g = t == null ? void 0 : t.payload) == null ? void 0 : g.command) == "set_initial_context") {
152
+ this.context = (k = t == null ? void 0 : t.payload) == null ? void 0 : k.arguments;
153
+ return;
154
+ }
155
+ const l = t.payload, f = await (await fetch(`${n}/sessions/${c}/messages`, {
156
+ body: JSON.stringify({ agentId: i, userMessage: l, initial_context: this.context }),
150
157
  method: "POST",
151
158
  headers: {
152
159
  "Content-Type": "application/json",
153
- "x-fox-apikey": s,
154
160
  "x-persona-apikey": s
155
161
  }
156
162
  })).json();
157
- this.notifyMessages(
158
- f.response.messages.map((b) => ({
163
+ this.notifyPackets(
164
+ f.response.messages.map((w) => ({
159
165
  type: "message",
160
- payload: b
166
+ payload: w
161
167
  }))
162
168
  );
163
169
  }
164
170
  }
165
- class I extends A {
166
- constructor(e) {
171
+ class z extends E {
172
+ constructor(t) {
167
173
  super();
168
174
  o(this, "status");
169
175
  o(this, "autostart");
170
176
  o(this, "session");
171
177
  o(this, "config");
172
178
  o(this, "webSocket");
173
- this.config = e, this.status = "disconnected", this.autostart = !0, this.session = null, this.webSocket = null;
179
+ this.config = t, this.status = "disconnected", this.autostart = !0, this.session = null, this.webSocket = null;
174
180
  }
175
181
  getName() {
176
182
  return "websocket";
@@ -178,22 +184,22 @@ class I extends A {
178
184
  getPriority() {
179
185
  return 500;
180
186
  }
181
- async syncSession(e) {
187
+ async syncSession(t) {
182
188
  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));
189
+ (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
190
  }
185
- connect(e) {
191
+ connect(t) {
186
192
  var l;
187
193
  if (this.webSocket !== null && this.status === "connected")
188
194
  return Promise.resolve(this.session);
189
- const n = e || this.session || "new";
195
+ const n = t || this.session || "new";
190
196
  (l = this.config.logger) == null || l.debug("Connecting to WebSocket with sessionId:", n);
191
- const s = encodeURIComponent(this.config.apiKey), a = this.config.agentId, c = `${this.config.webSocketUrl}?sessionCode=${n}&agentId=${a}&apiKey=${s}`;
197
+ const s = encodeURIComponent(this.config.apiKey), i = this.config.agentId, c = `${this.config.webSocketUrl}?sessionCode=${n}&agentId=${i}&apiKey=${s}`;
192
198
  return this.setStatus("connecting"), this.webSocket = new WebSocket(c), this.webSocket.addEventListener("open", () => {
193
199
  this.setStatus("connected");
194
200
  }), this.webSocket.addEventListener("message", (u) => {
195
201
  const f = JSON.parse(u.data);
196
- this.notifyMessage(f);
202
+ this.notifyPacket(f);
197
203
  }), this.webSocket.addEventListener("close", () => {
198
204
  var u;
199
205
  this.setStatus("disconnected"), this.webSocket = null, (u = this.config.logger) == null || u.warn("WebSocket connection closed");
@@ -203,15 +209,15 @@ class I extends A {
203
209
  }), Promise.resolve(n);
204
210
  }
205
211
  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();
212
+ var t;
213
+ 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
214
  }
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"));
215
+ sendPacket(t) {
216
+ return this.webSocket && this.status === "connected" ? (this.webSocket.send(JSON.stringify(t)), Promise.resolve()) : Promise.reject(new Error("WebSocket is not connected"));
211
217
  }
212
218
  }
213
- class se {
214
- constructor(t) {
219
+ class st {
220
+ constructor(e) {
215
221
  o(this, "config");
216
222
  o(this, "pc", null);
217
223
  o(this, "ws", null);
@@ -225,9 +231,9 @@ class se {
225
231
  o(this, "isConnected", !1);
226
232
  o(this, "visualizerCallbacks", []);
227
233
  o(this, "messageCallbacks", []);
228
- this.config = t;
234
+ this.config = e;
229
235
  }
230
- async connect(t) {
236
+ async connect(e) {
231
237
  var n;
232
238
  if (this.isConnected) return;
233
239
  this.isConnected = !0;
@@ -254,14 +260,14 @@ class se {
254
260
  s.streams[0].getTracks().forEach((c) => {
255
261
  this.remoteStream.addTrack(c);
256
262
  }), this.audioCtx || this._startAnalyzers();
257
- const a = new Audio();
258
- a.srcObject = this.remoteStream, a.play().catch((c) => {
263
+ const i = new Audio();
264
+ i.srcObject = this.remoteStream, i.play().catch((c) => {
259
265
  var l;
260
266
  (l = this.config.logger) == null || l.error("Error playing remote audio:", c);
261
267
  });
262
268
  }, this.pc.onicecandidate = (s) => {
263
- var a;
264
- s.candidate && ((a = this.ws) == null ? void 0 : a.readyState) === WebSocket.OPEN && this.ws.send(
269
+ var i;
270
+ s.candidate && ((i = this.ws) == null ? void 0 : i.readyState) === WebSocket.OPEN && this.ws.send(
265
271
  JSON.stringify({
266
272
  type: "CANDIDATE",
267
273
  src: "client",
@@ -269,24 +275,24 @@ class se {
269
275
  })
270
276
  );
271
277
  }, this.pc.ondatachannel = (s) => {
272
- const a = s.channel;
273
- a.onmessage = (c) => {
278
+ const i = s.channel;
279
+ i.onmessage = (c) => {
274
280
  this.messageCallbacks.forEach((l) => {
275
281
  l(c);
276
282
  });
277
283
  };
278
284
  };
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 () => {
285
+ const t = this.config.webrtcUrl || "wss://persona.applica.guru/api/webrtc";
286
+ this.ws = new WebSocket(`${t}?apiKey=${encodeURIComponent(this.config.apiKey)}`), this.ws.onopen = async () => {
281
287
  var l, u;
282
288
  const s = await this.pc.createOffer();
283
289
  await this.pc.setLocalDescription(s);
284
- const a = {
290
+ const i = {
285
291
  apiKey: this.config.apiKey,
286
292
  agentId: this.config.agentId,
287
- sessionCode: t
293
+ sessionCode: e
288
294
  };
289
- (l = this.config.logger) == null || l.debug("Opening connection to WebRTC server: ", a);
295
+ (l = this.config.logger) == null || l.debug("Opening connection to WebRTC server: ", i);
290
296
  const c = {
291
297
  type: "OFFER",
292
298
  src: ((u = crypto.randomUUID) == null ? void 0 : u.call(crypto)) || "client_" + Date.now(),
@@ -296,18 +302,18 @@ class se {
296
302
  type: s.type
297
303
  },
298
304
  connectionId: (Date.now() % 1e6).toString(),
299
- metadata: a
305
+ metadata: i
300
306
  }
301
307
  };
302
308
  this.ws.send(JSON.stringify(c));
303
309
  }, this.ws.onmessage = async (s) => {
304
310
  var c;
305
- const a = JSON.parse(s.data);
306
- if (a.type === "ANSWER")
307
- await this.pc.setRemoteDescription(new RTCSessionDescription(a.payload.sdp));
308
- else if (a.type === "CANDIDATE")
311
+ const i = JSON.parse(s.data);
312
+ if (i.type === "ANSWER")
313
+ await this.pc.setRemoteDescription(new RTCSessionDescription(i.payload.sdp));
314
+ else if (i.type === "CANDIDATE")
309
315
  try {
310
- await this.pc.addIceCandidate(new RTCIceCandidate(a.payload.candidate));
316
+ await this.pc.addIceCandidate(new RTCIceCandidate(i.payload.candidate));
311
317
  } catch (l) {
312
318
  (c = this.config.logger) == null || c.error("Error adding ICE candidate:", l);
313
319
  }
@@ -316,45 +322,45 @@ class se {
316
322
  };
317
323
  }
318
324
  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());
325
+ var e;
326
+ 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
327
  }
322
- addVisualizerCallback(t) {
323
- this.visualizerCallbacks.push(t);
328
+ addVisualizerCallback(e) {
329
+ this.visualizerCallbacks.push(e);
324
330
  }
325
- addMessageCallback(t) {
326
- this.messageCallbacks.push(t);
331
+ addMessageCallback(e) {
332
+ this.messageCallbacks.push(e);
327
333
  }
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) => {
334
+ createDataChannel(e = "messages") {
335
+ this.pc && (this.dataChannel = this.pc.createDataChannel(e), this.dataChannel.onopen = () => {
336
+ var t;
337
+ return (t = this.config.logger) == null ? void 0 : t.info("Data channel opened");
338
+ }, this.dataChannel.onmessage = (t) => {
333
339
  this.messageCallbacks.forEach((n) => {
334
- n(e);
340
+ n(t);
335
341
  });
336
342
  });
337
343
  }
338
- sendMessage(t) {
339
- var e, n;
344
+ sendPacket(e) {
345
+ var t, n;
340
346
  if (!this.dataChannel) {
341
- (e = this.config.logger) == null || e.warn("Data channel is not open, cannot send message");
347
+ (t = this.config.logger) == null || t.warn("Data channel is not open, cannot send message");
342
348
  return;
343
349
  }
344
- this.dataChannel.send(JSON.stringify({ type: "request", payload: t })), (n = this.config.logger) == null || n.info("Sent message:", t);
350
+ this.dataChannel.send(JSON.stringify(e)), (n = this.config.logger) == null || n.info("Sent message:", e);
345
351
  }
346
352
  _startAnalyzers() {
347
353
  if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0)
348
354
  return;
349
355
  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);
356
+ const e = this.audioCtx.createMediaStreamSource(this.localStream), t = this.audioCtx.createMediaStreamSource(this.remoteStream);
357
+ 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
358
  const n = () => {
353
359
  if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0)
354
360
  return;
355
- const s = new Uint8Array(this.localAnalyser.frequencyBinCount), a = new Uint8Array(this.remoteAnalyser.frequencyBinCount);
356
- this.localAnalyser.getByteFrequencyData(s), this.remoteAnalyser.getByteFrequencyData(a);
357
- const c = s.reduce((u, f) => u + f, 0) / s.length, l = a.reduce((u, f) => u + f, 0) / a.length;
361
+ const s = new Uint8Array(this.localAnalyser.frequencyBinCount), i = new Uint8Array(this.remoteAnalyser.frequencyBinCount);
362
+ this.localAnalyser.getByteFrequencyData(s), this.remoteAnalyser.getByteFrequencyData(i);
363
+ const c = s.reduce((u, f) => u + f, 0) / s.length, l = i.reduce((u, f) => u + f, 0) / i.length;
358
364
  this.visualizerCallbacks.length > 0 && this.visualizerCallbacks.forEach((u) => {
359
365
  u({
360
366
  localAmplitude: c,
@@ -368,17 +374,17 @@ class se {
368
374
  this.analyzerFrame && (cancelAnimationFrame(this.analyzerFrame), this.analyzerFrame = null), this.localAnalyser = null, this.remoteAnalyser = null;
369
375
  }
370
376
  }
371
- class z extends A {
372
- constructor(e) {
377
+ class D extends E {
378
+ constructor(t) {
373
379
  super();
374
380
  o(this, "status");
375
381
  o(this, "session");
376
382
  o(this, "autostart");
377
383
  o(this, "config");
378
384
  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 se(e), this.webRTCClient.addMessageCallback((n) => {
385
+ this.config = t, this.status = "disconnected", this.session = null, this.autostart = (t == null ? void 0 : t.autostart) ?? !1, this.webRTCClient = new st(t), this.webRTCClient.addMessageCallback((n) => {
380
386
  const s = JSON.parse(n.data);
381
- this.notifyMessage(s);
387
+ this.notifyPacket(s);
382
388
  });
383
389
  }
384
390
  getName() {
@@ -387,39 +393,39 @@ class z extends A {
387
393
  getPriority() {
388
394
  return 1e3;
389
395
  }
390
- async syncSession(e) {
391
- super.syncSession(e), this.status === "connected" && (await this.disconnect(), await this.connect(e));
396
+ async syncSession(t) {
397
+ super.syncSession(t), this.status === "connected" && (await this.disconnect(), await this.connect(t));
392
398
  }
393
- async connect(e) {
399
+ async connect(t) {
394
400
  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);
401
+ 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
402
  }
397
403
  async disconnect() {
398
- var e, n, s;
404
+ var t, n, s;
399
405
  if (this.status === "disconnected")
400
- return (e = this.config.logger) == null || e.warn("Already disconnected"), Promise.resolve();
406
+ return (t = this.config.logger) == null || t.warn("Already disconnected"), Promise.resolve();
401
407
  await this.webRTCClient.disconnect(), this.setStatus("disconnected"), (s = (n = this.config) == null ? void 0 : n.logger) == null || s.debug("Disconnected from WebRTC");
402
408
  }
403
- send(e) {
404
- return this.status !== "connected" ? Promise.reject(new Error("Not connected")) : (this.webRTCClient.sendMessage(e), Promise.resolve());
409
+ sendPacket(t) {
410
+ return this.status !== "connected" ? Promise.reject(new Error("Not connected")) : (this.webRTCClient.sendPacket(t), Promise.resolve());
405
411
  }
406
412
  }
407
- class ne {
408
- constructor(t) {
413
+ class nt {
414
+ constructor(e) {
409
415
  o(this, "config");
410
- this.config = t;
416
+ this.config = e;
411
417
  }
412
- async complete(t, e) {
418
+ async complete(e, t) {
413
419
  var n;
414
- await this.persist(t, { ...e, success: !0 }), (n = this.config.logger) == null || n.debug("Transaction completed:", t);
420
+ await this.persist(e, { ...t, success: !0 }), (n = this.config.logger) == null || n.debug("Transaction completed:", e);
415
421
  }
416
- async fail(t, e) {
422
+ async fail(e, t) {
417
423
  var n;
418
- await this.persist(t, { ...e, success: !1 }), (n = this.config.logger) == null || n.debug("Transaction failed:", { ...t, ...e });
424
+ await this.persist(e, { ...t, success: !1 }), (n = this.config.logger) == null || n.debug("Transaction failed:", { ...e, ...t });
419
425
  }
420
- async persist(t, e) {
421
- await fetch(`${this.config.apiUrl}/transactions/${t.id}`, {
422
- body: JSON.stringify(e),
426
+ async persist(e, t) {
427
+ await fetch(`${this.config.apiUrl}/transactions/${e.id}`, {
428
+ body: JSON.stringify(t),
423
429
  method: "POST",
424
430
  headers: {
425
431
  "Content-Type": "application/json",
@@ -429,49 +435,49 @@ class ne {
429
435
  });
430
436
  }
431
437
  }
432
- class ie {
433
- constructor(t, e) {
438
+ class it {
439
+ constructor(e, t) {
434
440
  o(this, "transaction");
435
441
  o(this, "manager");
436
- this.transaction = t, this.manager = e;
442
+ this.transaction = e, this.manager = t;
437
443
  }
438
444
  getFunctionCall() {
439
445
  return this.transaction.functionCall;
440
446
  }
441
- async invoke(t) {
442
- const e = this.transaction.functionCall;
443
- if (!e) {
447
+ async invoke(e) {
448
+ const t = this.transaction.functionCall;
449
+ if (!t) {
444
450
  await this.fail("No function call found");
445
451
  return;
446
452
  }
447
- const n = e.name, s = e.args, a = t[n];
448
- if (!a) {
453
+ const n = t.name, s = t.args, i = e[n];
454
+ if (!i) {
449
455
  await this.fail(`Tool ${n} not found`);
450
456
  return;
451
457
  }
452
458
  try {
453
- const c = await a(s);
459
+ const c = await i(s);
454
460
  await this.complete(c);
455
461
  } catch (c) {
456
462
  await this.fail(`Error executing tool ${n}: ${c}`);
457
463
  }
458
464
  }
459
- async complete(t) {
460
- await this.manager.complete(this.transaction, { success: !0, output: t, error: null });
465
+ async complete(e) {
466
+ await this.manager.complete(this.transaction, { success: !0, output: e, error: null });
461
467
  }
462
- async fail(t) {
463
- await this.manager.fail(this.transaction, { success: !1, output: null, error: t });
468
+ async fail(e) {
469
+ await this.manager.fail(this.transaction, { success: !1, output: null, error: e });
464
470
  }
465
471
  }
466
- class ae extends A {
467
- constructor(e) {
472
+ class at extends E {
473
+ constructor(t) {
468
474
  super();
469
475
  o(this, "status");
470
476
  o(this, "autostart");
471
477
  o(this, "session");
472
478
  o(this, "config");
473
479
  o(this, "notify", !0);
474
- this.config = e, this.status = "disconnected", this.autostart = !0;
480
+ this.config = t, this.status = "disconnected", this.autostart = !0;
475
481
  }
476
482
  getName() {
477
483
  return "transaction";
@@ -479,151 +485,155 @@ class ae extends A {
479
485
  getPriority() {
480
486
  return 0;
481
487
  }
482
- async connect(e) {
483
- return this.setStatus("connected"), e;
488
+ async connect(t) {
489
+ return this.setStatus("connected"), t;
484
490
  }
485
491
  async disconnect() {
486
492
  this.setStatus("disconnected"), this.session = null;
487
493
  }
488
- async syncSession(e) {
489
- this.session = e;
494
+ async syncSession(t) {
495
+ this.session = t;
490
496
  }
491
- async send(e) {
492
- var n;
493
- throw (n = this.config.logger) == null || n.debug("Sending message:", e), new Error("Not implemented");
497
+ async sendPacket(t) {
494
498
  }
495
- onTransaction(e) {
496
- var a;
499
+ onTransaction(t) {
500
+ var i;
497
501
  if (!this.config.onTransaction) {
498
- (a = this.config.logger) == null || a.error("Transaction protocol config is not set");
502
+ (i = this.config.logger) == null || i.error("Transaction protocol config is not set");
499
503
  return;
500
504
  }
501
- const n = new ne(this.config), s = new ie(e, n);
505
+ const n = new nt(this.config), s = new it(t, n);
502
506
  this.config.onTransaction(s);
503
507
  }
504
508
  }
505
- const S = _(void 0);
506
- function oe(i) {
507
- return new Promise((t, e) => {
509
+ const P = q(void 0);
510
+ function ot(a) {
511
+ return new Promise((e, t) => {
508
512
  const n = new FileReader();
509
- n.readAsDataURL(i), n.onload = () => {
510
- const a = n.result.split(";base64,")[1];
511
- t(a);
513
+ n.readAsDataURL(a), n.onload = () => {
514
+ const i = n.result.split(";base64,")[1];
515
+ e(i);
512
516
  }, n.onerror = (s) => {
513
- e(s);
517
+ t(s);
514
518
  };
515
519
  });
516
520
  }
517
- function re({
518
- dev: i = !1,
519
- protocols: t,
520
- logger: e,
521
+ function rt({
522
+ dev: a = !1,
523
+ protocols: e,
524
+ logger: t,
521
525
  children: n,
522
526
  session: s = "new",
523
- ...a
527
+ ...i
524
528
  }) {
525
- const [c, l] = x(!1), [u, f] = x([]), [b, U] = x(s), [P, W] = x(/* @__PURE__ */ new Map()), v = B(!1), m = Y(() => {
526
- if (Array.isArray(t))
527
- return t;
528
- if (typeof t == "object" && t !== null) {
529
- const r = i ? "localhost:8000" : "persona.applica.guru/api", p = i ? "http" : "https", d = i ? "ws" : "wss";
530
- let y = Object.keys(t).map((g) => {
531
- switch (g) {
529
+ const [c, l] = R(!1), [u, f] = R([]), [g, k] = R(s), [w, W] = R(/* @__PURE__ */ new Map()), $ = B(!1), b = Y(() => {
530
+ if (Array.isArray(e))
531
+ return e;
532
+ if (typeof e == "object" && e !== null) {
533
+ const r = a ? "localhost:8000" : "persona.applica.guru/api", p = a ? "http" : "https", d = a ? "ws" : "wss";
534
+ let m = Object.keys(e).map((y) => {
535
+ switch (y) {
532
536
  case "rest":
533
- const h = t[g];
534
- return h === !0 ? new N({
537
+ const h = e[y];
538
+ return h === !0 ? new M({
535
539
  apiUrl: `${p}://${r}`,
536
- apiKey: a.apiKey,
537
- agentId: a.agentId,
538
- logger: e
539
- }) : typeof h == "object" && h !== null ? new N(h) : null;
540
+ apiKey: i.apiKey,
541
+ agentId: i.agentId,
542
+ logger: t
543
+ }) : typeof h == "object" && h !== null ? new M(h) : null;
540
544
  case "webrtc":
541
- const w = t[g];
542
- return w === !0 ? new z({
545
+ const C = e[y];
546
+ return C === !0 ? new D({
543
547
  webrtcUrl: `${d}://${r}/webrtc`,
544
- apiKey: a.apiKey,
545
- agentId: a.agentId,
546
- logger: e
547
- }) : typeof w == "object" && w !== null ? new z(w) : null;
548
+ apiKey: i.apiKey,
549
+ agentId: i.agentId,
550
+ logger: t
551
+ }) : typeof C == "object" && C !== null ? new D(C) : null;
548
552
  case "websocket":
549
- const k = t[g];
550
- return k === !0 ? new I({
553
+ const x = e[y];
554
+ return x === !0 ? new z({
551
555
  webSocketUrl: `${d}://${r}/websocket`,
552
- apiKey: a.apiKey,
553
- agentId: a.agentId,
554
- logger: e
555
- }) : typeof k == "object" && k !== null ? new I(k) : null;
556
+ apiKey: i.apiKey,
557
+ agentId: i.agentId,
558
+ logger: t
559
+ }) : typeof x == "object" && x !== null ? new z(x) : null;
556
560
  default:
557
- throw new Error(`Unknown protocol: ${g}`);
561
+ throw new Error(`Unknown protocol: ${y}`);
558
562
  }
559
- }).filter((g) => g !== null);
560
- return a.tools && y.push(
561
- new ae({
563
+ }).filter((y) => y !== null);
564
+ return i.tools && m.push(
565
+ new at({
562
566
  apiUrl: `${p}://${r}`,
563
- apiKey: a.apiKey,
564
- agentId: a.agentId,
565
- onTransaction: async (g) => {
566
- await g.invoke(a.tools);
567
+ apiKey: i.apiKey,
568
+ agentId: i.agentId,
569
+ onTransaction: async (y) => {
570
+ await y.invoke(i.tools);
567
571
  },
568
- logger: e
572
+ logger: t
569
573
  })
570
- ), y;
574
+ ), m;
571
575
  }
572
576
  throw new Error("Invalid protocols configuration");
573
577
  }, []);
574
578
  G(() => {
575
- v.current || (v.current = !0, e == null || e.debug(
579
+ $.current || ($.current = !0, t == null || t.debug(
576
580
  "Initializing protocols: ",
577
- m.map((r) => r.getName())
578
- ), m.forEach((r) => {
579
- r.setSession(b), r.clearListeners(), r.addStatusChangeListener((p) => {
580
- e == null || e.debug(`${r.getName()} has notified new status: ${p}`), P.set(r.getName(), p), W(new Map(P));
581
- }), r.addMessageListener((p) => {
581
+ b.map((r) => r.getName())
582
+ ), b.forEach((r) => {
583
+ r.setSession(g), r.clearListeners(), r.addStatusChangeListener((p) => {
584
+ t == null || t.debug(`${r.getName()} has notified new status: ${p}`), w.set(r.getName(), p), p === "connected" && i.context && r.sendPacket({
585
+ type: "command",
586
+ payload: {
587
+ command: "set_initial_context",
588
+ arguments: i.context
589
+ }
590
+ }), W(new Map(w));
591
+ }), r.addPacketListener((p) => {
582
592
  if (p.type === "message") {
583
593
  const d = p.payload;
584
594
  f(
585
- (y) => $([...y, { ...d, protocol: r.getName() }])
595
+ (m) => I([...m, { ...d, protocol: r.getName() }])
586
596
  );
587
597
  } else if (p.type === "reasoning") {
588
598
  const d = p.payload;
589
- let y = d.thought;
590
- d.imageUrl && (y += `
599
+ let m = d.thought;
600
+ d.imageUrl && (m += `
591
601
 
592
602
  ![image](https://persona.applica.guru/api/files/${d.imageUrl})`);
593
- const g = { type: "reasoning", text: y, role: "assistant", finishReason: "stop" };
603
+ const y = { type: "reasoning", text: m, role: "assistant", finishReason: "stop" };
594
604
  f(
595
- (h) => $([...h, { ...g, protocol: r.getName() }])
605
+ (h) => I([...h, { ...y, protocol: r.getName() }])
596
606
  );
597
- } else p.type === "transaction" && m.filter((d) => d !== r).forEach((d) => d.onTransaction(p.payload));
598
- }), r.autostart && r.status === "disconnected" && (e == null || e.debug(`Connecting to protocol: ${r.getName()}`), r.connect(b));
607
+ } else p.type === "transaction" && b.filter((d) => d !== r).forEach((d) => d.onTransaction(p.payload));
608
+ }), r.autostart && r.status === "disconnected" && (t == null || t.debug(`Connecting to protocol: ${r.getName()}`), r.connect(g));
599
609
  }));
600
- }, [b, m, e, P]);
610
+ }, [g, b, t, w]);
601
611
  const j = async (r) => {
602
- var g;
603
- if (((g = r.content[0]) == null ? void 0 : g.type) !== "text") throw new Error("Only text messages are supported");
612
+ var y;
613
+ if (((y = r.content[0]) == null ? void 0 : y.type) !== "text") throw new Error("Only text messages are supported");
604
614
  const p = r.content[0].text;
605
615
  f((h) => [...h, { role: "user", type: "text", text: p }]), l(!0);
606
- const d = m.sort((h, w) => w.getPriority() - h.getPriority()).find((h) => h.status === "connected"), y = [];
616
+ const d = b.sort((h, C) => C.getPriority() - h.getPriority()).find((h) => h.status === "connected"), m = [];
607
617
  if (r.attachments)
608
618
  for (const h of r.attachments)
609
- h.contentType.startsWith("image/") && h.file && y.push({
619
+ h.contentType.startsWith("image/") && h.file && m.push({
610
620
  role: "user",
611
621
  image: {
612
622
  contentType: h.contentType,
613
- content: await oe(h.file)
623
+ content: await ot(h.file)
614
624
  },
615
625
  text: "",
616
626
  type: "text"
617
627
  });
618
- r.content && y.push({
628
+ r.content && m.push({
619
629
  role: "user",
620
630
  text: r.content[0].text,
621
631
  type: "text"
622
- }), e == null || e.debug("Sending message:", y), await (d == null ? void 0 : d.send(y)), l(!1);
623
- }, O = E(() => (l(!1), f([]), U("new"), Promise.resolve()), []), L = E(() => Promise.resolve(), []), F = E(() => u, [u]), J = V({
632
+ }), t == null || t.debug("Sending message:", m), await (d == null ? void 0 : d.sendPacket({ type: "request", payload: m })), l(!1);
633
+ }, O = T(() => (l(!1), f([]), k("new"), Promise.resolve()), []), L = T(() => Promise.resolve(), []), F = T(() => u, [u]), _ = V({
624
634
  isRunning: c,
625
635
  messages: u,
626
- convertMessage: te,
636
+ convertMessage: et,
627
637
  onNew: j,
628
638
  onCancel: O,
629
639
  onReload: L,
@@ -631,88 +641,88 @@ function re({
631
641
  attachments: new H([new Q()])
632
642
  }
633
643
  });
634
- return /* @__PURE__ */ T.jsx(S.Provider, { value: { protocols: m, protocolsStatus: P, getMessages: F }, children: /* @__PURE__ */ T.jsx(X, { runtime: J, children: n }) });
644
+ return /* @__PURE__ */ v.jsx(P.Provider, { value: { protocols: b, protocolsStatus: w, getMessages: F }, children: /* @__PURE__ */ v.jsx(X, { runtime: _, children: n }) });
635
645
  }
636
- function de({ children: i, ...t }) {
637
- return /* @__PURE__ */ T.jsx(re, { ...t, children: i });
646
+ function dt({ children: a, ...e }) {
647
+ return /* @__PURE__ */ v.jsx(rt, { ...e, children: a });
638
648
  }
639
- function fe() {
640
- const i = R(S);
641
- if (!i)
649
+ function ft() {
650
+ const a = A(P);
651
+ if (!a)
642
652
  throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");
643
- return i;
653
+ return a;
644
654
  }
645
- function ce(i) {
646
- const t = R(S);
647
- if (!t)
648
- throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");
649
- const e = t.protocols.find((s) => s.getName() === i);
655
+ function ct(a) {
656
+ const e = A(P);
650
657
  if (!e)
658
+ throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");
659
+ const t = e.protocols.find((s) => s.getName() === a);
660
+ if (!t)
651
661
  return null;
652
- const n = t.protocolsStatus.get(e.getName());
662
+ const n = e.protocolsStatus.get(t.getName());
653
663
  return {
654
- ...e,
655
- connect: e.connect.bind(e),
656
- disconnect: e.disconnect.bind(e),
657
- send: e.send.bind(e),
658
- setSession: e.setSession.bind(e),
659
- addStatusChangeListener: e.addStatusChangeListener.bind(e),
660
- addMessageListener: e.addMessageListener.bind(e),
661
- getName: e.getName.bind(e),
662
- getPriority: e.getPriority.bind(e),
663
- status: n || e.status
664
+ ...t,
665
+ connect: t.connect.bind(t),
666
+ disconnect: t.disconnect.bind(t),
667
+ sendPacket: t.sendPacket.bind(t),
668
+ setSession: t.setSession.bind(t),
669
+ addStatusChangeListener: t.addStatusChangeListener.bind(t),
670
+ addPacketListener: t.addPacketListener.bind(t),
671
+ getName: t.getName.bind(t),
672
+ getPriority: t.getPriority.bind(t),
673
+ status: n || t.status
664
674
  };
665
675
  }
666
- function pe() {
667
- const i = R(S);
668
- if (!i)
676
+ function pt() {
677
+ const a = A(P);
678
+ if (!a)
669
679
  throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");
670
- for (const t of i.protocols)
671
- if (t.getName() === "rest")
672
- return t.config.apiUrl;
680
+ for (const e of a.protocols)
681
+ if (e.getName() === "rest")
682
+ return e.config.apiUrl;
673
683
  throw new Error("REST protocol not found");
674
684
  }
675
- function ge() {
676
- return ce("webrtc");
685
+ function yt() {
686
+ return ct("webrtc");
677
687
  }
678
- function ye() {
679
- const i = R(S);
680
- if (!i)
688
+ function mt() {
689
+ const a = A(P);
690
+ if (!a)
681
691
  throw new Error("usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider");
682
- return i.getMessages();
692
+ return a.getMessages();
683
693
  }
684
- class me {
694
+ class gt {
685
695
  constructor() {
686
696
  o(this, "prefix", "[Persona]");
687
697
  }
688
- log(t, ...e) {
689
- console.log(`${this.prefix} - ${t}`, ...e);
698
+ log(e, ...t) {
699
+ console.log(`${this.prefix} - ${e}`, ...t);
690
700
  }
691
- info(t, ...e) {
692
- console.info(`${this.prefix} - ${t}`, ...e);
701
+ info(e, ...t) {
702
+ console.info(`${this.prefix} - ${e}`, ...t);
693
703
  }
694
- warn(t, ...e) {
695
- console.warn(`${this.prefix} - ${t}`, ...e);
704
+ warn(e, ...t) {
705
+ console.warn(`${this.prefix} - ${e}`, ...t);
696
706
  }
697
- error(t, ...e) {
698
- console.error(`${this.prefix} - ${t}`, ...e);
707
+ error(e, ...t) {
708
+ console.error(`${this.prefix} - ${e}`, ...t);
699
709
  }
700
- debug(t, ...e) {
701
- console.debug(`${this.prefix} - ${t}`, ...e);
710
+ debug(e, ...t) {
711
+ console.debug(`${this.prefix} - ${e}`, ...t);
702
712
  }
703
713
  }
704
714
  export {
705
- me as PersonaConsoleLogger,
706
- A as PersonaProtocolBase,
707
- N as PersonaRESTProtocol,
708
- de as PersonaRuntimeProvider,
709
- ae as PersonaTransactionProtocol,
710
- z as PersonaWebRTCProtocol,
711
- I as PersonaWebSocketProtocol,
712
- fe as usePersonaRuntime,
713
- pe as usePersonaRuntimeEndpoint,
714
- ye as usePersonaRuntimeMessages,
715
- ce as usePersonaRuntimeProtocol,
716
- ge as usePersonaRuntimeWebRTCProtocol
715
+ gt as PersonaConsoleLogger,
716
+ E as PersonaProtocolBase,
717
+ M as PersonaRESTProtocol,
718
+ dt as PersonaRuntimeProvider,
719
+ at as PersonaTransactionProtocol,
720
+ D as PersonaWebRTCProtocol,
721
+ z as PersonaWebSocketProtocol,
722
+ ft as usePersonaRuntime,
723
+ pt as usePersonaRuntimeEndpoint,
724
+ mt as usePersonaRuntimeMessages,
725
+ ct as usePersonaRuntimeProtocol,
726
+ yt as usePersonaRuntimeWebRTCProtocol
717
727
  };
718
728
  //# sourceMappingURL=bundle.es.js.map