@applica-software-guru/persona-sdk 0.1.63 → 0.1.65

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, e, t) => e in i ? K(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
- var o = (i, e, t) => q(i, typeof e != "symbol" ? e + "" : e, t);
4
- import { createContext as B, useContext as A, useState as R, useRef as Y, useMemo as G, useEffect as V, useCallback as v } from "react";
5
- import { useExternalStoreRuntime as H, CompositeAttachmentAdapter as Q, SimpleImageAttachmentAdapter as X, AssistantRuntimeProvider as Z } from "@assistant-ui/react";
6
- var W = { exports: {} }, S = {};
1
+ var B = Object.defineProperty;
2
+ var V = (o, t, e) => t in o ? B(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
+ var r = (o, t, e) => V(o, typeof t != "symbol" ? t + "" : t, e);
4
+ import { createContext as Y, useContext as A, useState as E, useRef as G, useMemo as H, useEffect as Q, useCallback as M } from "react";
5
+ import { useExternalStoreRuntime as X, CompositeAttachmentAdapter as Z, SimpleImageAttachmentAdapter as ee, AssistantRuntimeProvider as te } from "@assistant-ui/react";
6
+ var F = { exports: {} }, k = {};
7
7
  /**
8
8
  * @license React
9
9
  * react-jsx-runtime.production.js
@@ -13,122 +13,123 @@ var W = { exports: {} }, S = {};
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 I;
17
- function tt() {
18
- if (I) return S;
19
- I = 1;
20
- var i = Symbol.for("react.transitional.element"), e = Symbol.for("react.fragment");
21
- function t(s, n, a) {
22
- var r = null;
23
- if (a !== void 0 && (r = "" + a), n.key !== void 0 && (r = "" + n.key), "key" in n) {
16
+ var j;
17
+ function se() {
18
+ if (j) return k;
19
+ j = 1;
20
+ var o = Symbol.for("react.transitional.element"), t = Symbol.for("react.fragment");
21
+ function e(s, n, a) {
22
+ var i = null;
23
+ if (a !== void 0 && (i = "" + a), n.key !== void 0 && (i = "" + n.key), "key" in n) {
24
24
  a = {};
25
25
  for (var l in n)
26
26
  l !== "key" && (a[l] = n[l]);
27
27
  } else a = n;
28
28
  return n = a.ref, {
29
- $$typeof: i,
29
+ $$typeof: o,
30
30
  type: s,
31
- key: r,
31
+ key: i,
32
32
  ref: n !== void 0 ? n : null,
33
33
  props: a
34
34
  };
35
35
  }
36
- return S.Fragment = e, S.jsx = t, S.jsxs = t, S;
36
+ return k.Fragment = t, k.jsx = e, k.jsxs = e, k;
37
37
  }
38
- W.exports = tt();
39
- var $ = W.exports;
40
- function et(i) {
41
- return i.filter((e) => {
42
- var t;
43
- return e.finishReason === "stop" ? e.text !== null && ((t = e.text) == null ? void 0 : t.trim()) !== "" : !0;
38
+ F.exports = se();
39
+ var N = F.exports;
40
+ function ne(o) {
41
+ return o.filter((t) => {
42
+ var e;
43
+ return t.finishReason === "stop" ? t.text !== null && ((e = t.text) == null ? void 0 : e.trim()) !== "" : !0;
44
44
  });
45
45
  }
46
- function M(i) {
47
- const e = [];
48
- let t = null;
49
- for (const n of i)
50
- n.type !== "transaction" && (n.type === "reasoning" ? (t != null && (e.push(t), t = null), e.push(n)) : n.functionCalls ? (t && e.push(t), e.push(n), t = null) : n.functionResponse ? e[e.length - 1] = {
51
- ...e[e.length - 1],
46
+ function q(o) {
47
+ const t = [];
48
+ let e = null;
49
+ for (const n of o)
50
+ n.type !== "transaction" && (n.type === "reasoning" ? (e != null && (t.push(e), e = null), t.push(n)) : n.functionCalls ? (e && t.push(e), t.push(n), e = null) : n.functionResponse ? t[t.length - 1] = {
51
+ ...t[t.length - 1],
52
52
  functionResponse: n.functionResponse
53
- } : t && n.protocol === t.protocol && (t.role === n.role || n.finishReason === "stop") ? (t.text += n.text, t.files = [...t.files ?? [], ...n.files ?? []]) : (t && e.push(t), t = {
53
+ } : e && n.protocol === e.protocol && (e.role === n.role || n.finishReason === "stop") ? (e.text += n.text, e.files = [...e.files ?? [], ...n.files ?? []]) : (e && t.push(e), e = {
54
54
  ...n
55
55
  }));
56
- return t && e.push(t), et(e);
56
+ return e && t.push(e), ne(t);
57
57
  }
58
- function st(i) {
59
- var t, s;
60
- const e = ((t = i.files) == null ? void 0 : t.map(
58
+ function oe(o) {
59
+ var e, s;
60
+ const t = ((e = o.files) == null ? void 0 : e.map(
61
61
  (n) => ({
62
62
  type: "file",
63
63
  data: n.url,
64
64
  mimeType: n.contentType
65
65
  })
66
66
  )) ?? [];
67
- return i.role === "function" ? {
68
- id: i.id,
67
+ return o.role === "function" ? {
68
+ id: o.id,
69
69
  role: "assistant",
70
- status: (i == null ? void 0 : i.functionResponse) === null ? { type: "running" } : { type: "complete", reason: "stop" },
71
- content: ((s = i.functionCalls) == null ? void 0 : s.map((n) => {
70
+ status: (o == null ? void 0 : o.functionResponse) === null ? { type: "running" } : { type: "complete", reason: "stop" },
71
+ content: ((s = o.functionCalls) == null ? void 0 : s.map((n) => {
72
72
  var a;
73
73
  return {
74
74
  type: "tool-call",
75
75
  toolName: n.name,
76
76
  toolCallId: n.id,
77
77
  args: n.args,
78
- result: (a = i.functionResponse) == null ? void 0 : a.result
78
+ result: (a = o.functionResponse) == null ? void 0 : a.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 }, ...e] : [{ type: "text", text: i.text }, ...e]
82
+ id: o.id,
83
+ role: o.role,
84
+ content: o.type === "reasoning" ? [{ type: "reasoning", text: o.text }, ...t] : [{ type: "text", text: o.text }, ...t]
85
85
  };
86
86
  }
87
- class E {
87
+ class v {
88
88
  constructor() {
89
- o(this, "statusChangeCallbacks", []);
90
- o(this, "messageCallbacks", []);
89
+ r(this, "statusChangeCallbacks", []);
90
+ r(this, "messageCallbacks", []);
91
91
  }
92
- addStatusChangeListener(e) {
93
- this.statusChangeCallbacks.push(e);
92
+ addStatusChangeListener(t) {
93
+ this.statusChangeCallbacks.push(t);
94
94
  }
95
- addPacketListener(e) {
96
- this.messageCallbacks.push(e);
95
+ addPacketListener(t) {
96
+ this.messageCallbacks.push(t);
97
97
  }
98
- async syncSession(e) {
99
- this.session = e;
98
+ async syncSession(t) {
99
+ this.session = t;
100
100
  }
101
- async notifyPacket(e) {
102
- this.messageCallbacks.forEach((t) => t(e));
101
+ async notifyPacket(t) {
102
+ this.messageCallbacks.forEach((e) => e(t));
103
103
  }
104
- async notifyPackets(e) {
105
- e.forEach((t) => {
106
- this.messageCallbacks.forEach((s) => s(t));
104
+ async notifyPackets(t) {
105
+ t.forEach((e) => {
106
+ this.messageCallbacks.forEach((s) => s(e));
107
107
  });
108
108
  }
109
- async setSession(e) {
110
- this.session = e;
109
+ async setSession(t) {
110
+ this.session = t;
111
111
  }
112
- async setStatus(e) {
113
- const t = this.status !== e;
114
- this.status = e, t && this.statusChangeCallbacks.forEach((s) => s(e));
112
+ async setStatus(t) {
113
+ const e = this.status !== t;
114
+ this.status = t, e && this.statusChangeCallbacks.forEach((s) => s(t));
115
115
  }
116
116
  clearListeners() {
117
117
  this.statusChangeCallbacks = [], this.messageCallbacks = [];
118
118
  }
119
- onTransaction(e) {
119
+ onTransaction(t) {
120
120
  }
121
121
  }
122
- class z extends E {
123
- constructor(t) {
122
+ class _ extends v {
123
+ constructor(e) {
124
124
  super();
125
- o(this, "status");
126
- o(this, "autostart");
127
- o(this, "session");
128
- o(this, "config");
129
- o(this, "notify", !0);
130
- o(this, "context", {});
131
- this.config = t, this.status = "disconnected", this.autostart = !0;
125
+ r(this, "status");
126
+ r(this, "autostart");
127
+ r(this, "session");
128
+ r(this, "config");
129
+ r(this, "notify", !0);
130
+ r(this, "context", {});
131
+ r(this, "tools", []);
132
+ this.config = e, this.status = "disconnected", this.autostart = !0;
132
133
  }
133
134
  getName() {
134
135
  return "rest";
@@ -136,47 +137,69 @@ class z extends E {
136
137
  getPriority() {
137
138
  return 100;
138
139
  }
139
- async connect(t) {
140
- return this.setStatus("connected"), t;
140
+ async connect(e) {
141
+ return this.setStatus("connected"), e;
141
142
  }
142
143
  async disconnect() {
143
144
  this.setStatus("disconnected"), this.session = null;
144
145
  }
145
- async syncSession(t) {
146
- this.session = t;
146
+ async syncSession(e) {
147
+ this.session = e;
147
148
  }
148
- async sendPacket(t) {
149
- var g, w;
150
- const { apiUrl: s, apiKey: n, agentId: a } = this.config, r = 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 = (w = t == null ? void 0 : t.payload) == null ? void 0 : w.arguments;
149
+ async sendPacket(e) {
150
+ var u, p, g, w;
151
+ const { apiUrl: s, apiKey: n, agentId: a } = this.config, i = this.session ?? "new";
152
+ if (e.type === "command" && ((u = e == null ? void 0 : e.payload) == null ? void 0 : u.command) == "set_initial_context") {
153
+ this.context = (p = e == null ? void 0 : e.payload) == null ? void 0 : p.arguments;
154
+ return;
155
+ } else if (e.type === "command" && ((g = e == null ? void 0 : e.payload) == null ? void 0 : g.command) == "set_local_tools") {
156
+ this.notifyPacket({
157
+ type: "message",
158
+ payload: {
159
+ type: "text",
160
+ role: "assistant",
161
+ text: "Local tools with rest protocol are not supported."
162
+ }
163
+ });
153
164
  return;
154
165
  }
155
- const l = t.payload, p = await (await fetch(`${s}/sessions/${r}/messages`, {
156
- body: JSON.stringify({ agentId: a, userMessage: l, initial_context: this.context }),
157
- method: "POST",
158
- headers: {
159
- "Content-Type": "application/json",
160
- "x-persona-apikey": n
161
- }
162
- })).json();
163
- this.notifyPackets(
164
- p.response.messages.map((T) => ({
166
+ const l = e.payload;
167
+ try {
168
+ const b = await (await fetch(`${s}/sessions/${i}/messages`, {
169
+ body: JSON.stringify({ agentId: a, userMessage: l, initialContext: this.context, tools: this.tools }),
170
+ method: "POST",
171
+ headers: {
172
+ "Content-Type": "application/json",
173
+ "x-persona-apikey": n
174
+ }
175
+ })).json();
176
+ this.notifyPackets(
177
+ b.response.messages.map(($) => ({
178
+ type: "message",
179
+ payload: $
180
+ }))
181
+ );
182
+ } catch (R) {
183
+ this.notifyPacket({
165
184
  type: "message",
166
- payload: T
167
- }))
168
- );
185
+ payload: {
186
+ role: "assistant",
187
+ type: "text",
188
+ text: "An error occurred while processing your request. Please try again later."
189
+ }
190
+ }), (w = this.config.logger) == null || w.error("Error sending packet:", R);
191
+ }
169
192
  }
170
193
  }
171
- class D extends E {
172
- constructor(t) {
194
+ class W extends v {
195
+ constructor(e) {
173
196
  super();
174
- o(this, "status");
175
- o(this, "autostart");
176
- o(this, "session");
177
- o(this, "config");
178
- o(this, "webSocket");
179
- this.config = t, this.status = "disconnected", this.autostart = !0, this.session = null, this.webSocket = null;
197
+ r(this, "status");
198
+ r(this, "autostart");
199
+ r(this, "session");
200
+ r(this, "config");
201
+ r(this, "webSocket");
202
+ this.config = e, this.status = "disconnected", this.autostart = !0, this.session = null, this.webSocket = null;
180
203
  }
181
204
  getName() {
182
205
  return "websocket";
@@ -184,56 +207,65 @@ class D extends E {
184
207
  getPriority() {
185
208
  return 500;
186
209
  }
187
- async syncSession(t) {
210
+ async syncSession(e) {
188
211
  var s;
189
- (s = this.config.logger) == null || s.debug("Syncing session with WebSocket protocol:", t), this.session = t, this.webSocket && this.status === "connected" && (this.disconnect(), this.connect(t));
212
+ (s = this.config.logger) == null || s.debug("Syncing session with WebSocket protocol:", e), this.session = e, this.webSocket && this.status === "connected" && (this.disconnect(), this.connect(e));
190
213
  }
191
- connect(t) {
214
+ connect(e) {
192
215
  var l;
193
216
  if (this.webSocket !== null && this.status === "connected")
194
217
  return Promise.resolve(this.session);
195
- const s = t || this.session || "new";
218
+ const s = e || this.session || "new";
196
219
  (l = this.config.logger) == null || l.debug("Connecting to WebSocket with sessionId:", s);
197
- const n = encodeURIComponent(this.config.apiKey), a = this.config.agentId, r = `${this.config.webSocketUrl}?sessionCode=${s}&agentId=${a}&apiKey=${n}`;
198
- return this.setStatus("connecting"), this.webSocket = new WebSocket(r), this.webSocket.addEventListener("open", () => {
220
+ const n = encodeURIComponent(this.config.apiKey), a = this.config.agentId, i = `${this.config.webSocketUrl}?sessionCode=${s}&agentId=${a}&apiKey=${n}`;
221
+ return this.setStatus("connecting"), this.webSocket = new WebSocket(i), this.webSocket.addEventListener("open", () => {
199
222
  this.setStatus("connected");
200
223
  }), this.webSocket.addEventListener("message", (u) => {
201
224
  const p = JSON.parse(u.data);
202
225
  this.notifyPacket(p);
203
- }), this.webSocket.addEventListener("close", () => {
204
- var u;
205
- this.setStatus("disconnected"), this.webSocket = null, (u = this.config.logger) == null || u.warn("WebSocket connection closed");
206
- }), this.webSocket.addEventListener("error", (u) => {
226
+ }), this.webSocket.addEventListener("close", (u) => {
207
227
  var p;
208
- this.setStatus("disconnected"), this.webSocket = null, (p = this.config.logger) == null || p.error("WebSocket error", u);
228
+ this.setStatus("disconnected"), this.webSocket = null, u.code !== 1e3 && (this.notifyPacket({
229
+ type: "message",
230
+ payload: {
231
+ role: "assistant",
232
+ type: "text",
233
+ text: "Oops! The connection to the server was lost. Please try again later."
234
+ }
235
+ }), (p = this.config.logger) == null || p.warn("WebSocket connection closed"));
236
+ }), this.webSocket.addEventListener("error", () => {
237
+ var u;
238
+ this.setStatus("disconnected"), this.webSocket = null, (u = this.config.logger) == null || u.error("WebSocket connection error");
209
239
  }), Promise.resolve(s);
210
240
  }
211
241
  disconnect() {
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();
242
+ var e;
243
+ 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();
214
244
  }
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"));
245
+ sendPacket(e) {
246
+ return this.webSocket && this.status === "connected" ? (this.webSocket.send(JSON.stringify(e)), Promise.resolve()) : Promise.reject(new Error("WebSocket is not connected"));
217
247
  }
218
248
  }
219
- class nt {
220
- constructor(e) {
221
- o(this, "config");
222
- o(this, "pc", null);
223
- o(this, "ws", null);
224
- o(this, "localStream", null);
225
- o(this, "remoteStream", new MediaStream());
226
- o(this, "audioCtx", null);
227
- o(this, "localAnalyser", null);
228
- o(this, "remoteAnalyser", null);
229
- o(this, "analyzerFrame", null);
230
- o(this, "dataChannel", null);
231
- o(this, "isConnected", !1);
232
- o(this, "visualizerCallbacks", []);
233
- o(this, "messageCallbacks", []);
234
- this.config = e;
249
+ class ae {
250
+ constructor(t) {
251
+ r(this, "config");
252
+ r(this, "pc", null);
253
+ r(this, "ws", null);
254
+ r(this, "localStream", null);
255
+ r(this, "remoteStream", new MediaStream());
256
+ r(this, "audioCtx", null);
257
+ r(this, "localAnalyser", null);
258
+ r(this, "remoteAnalyser", null);
259
+ r(this, "analyzerFrame", null);
260
+ r(this, "dataChannel", null);
261
+ r(this, "isConnected", !1);
262
+ r(this, "visualizerCallbacks", []);
263
+ r(this, "messageCallbacks", []);
264
+ r(this, "errorCallbacks", []);
265
+ r(this, "queuedMessages", []);
266
+ this.config = t;
235
267
  }
236
- async connect(e) {
268
+ async connect(t) {
237
269
  var s;
238
270
  if (this.isConnected) return;
239
271
  this.isConnected = !0;
@@ -257,13 +289,13 @@ class nt {
257
289
  }), this.localStream.getTracks().forEach((n) => {
258
290
  this.pc.addTrack(n, this.localStream);
259
291
  }), this.pc.ontrack = (n) => {
260
- n.streams[0].getTracks().forEach((r) => {
261
- this.remoteStream.addTrack(r);
292
+ n.streams[0].getTracks().forEach((i) => {
293
+ this.remoteStream.addTrack(i);
262
294
  }), this.audioCtx || this._startAnalyzers();
263
295
  const a = new Audio();
264
- a.srcObject = this.remoteStream, a.play().catch((r) => {
296
+ a.srcObject = this.remoteStream, a.play().catch((i) => {
265
297
  var l;
266
- (l = this.config.logger) == null || l.error("Error playing remote audio:", r);
298
+ (l = this.config.logger) == null || l.error("Error playing remote audio:", i);
267
299
  });
268
300
  }, this.pc.onicecandidate = (n) => {
269
301
  var a;
@@ -276,24 +308,30 @@ class nt {
276
308
  );
277
309
  }, this.pc.ondatachannel = (n) => {
278
310
  const a = n.channel;
279
- a.onmessage = (r) => {
311
+ a.onmessage = (i) => {
280
312
  this.messageCallbacks.forEach((l) => {
281
- l(r);
313
+ l(i);
282
314
  });
315
+ }, a.onopen = () => {
316
+ var i;
317
+ for (; this.queuedMessages.length > 0; ) {
318
+ const l = this.queuedMessages.shift();
319
+ l && (a.send(JSON.stringify(l)), (i = this.config.logger) == null || i.info("Sent queued message:", l));
320
+ }
283
321
  };
284
322
  };
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 () => {
323
+ const e = this.config.webrtcUrl || "wss://persona.applica.guru/api/webrtc";
324
+ this.ws = new WebSocket(`${e}?apiKey=${encodeURIComponent(this.config.apiKey)}`), this.ws.onopen = async () => {
287
325
  var l, u;
288
326
  const n = await this.pc.createOffer();
289
327
  await this.pc.setLocalDescription(n);
290
328
  const a = {
291
329
  apiKey: this.config.apiKey,
292
330
  agentId: this.config.agentId,
293
- sessionCode: e
331
+ sessionCode: t
294
332
  };
295
333
  (l = this.config.logger) == null || l.debug("Opening connection to WebRTC server: ", a);
296
- const r = {
334
+ const i = {
297
335
  type: "OFFER",
298
336
  src: ((u = crypto.randomUUID) == null ? void 0 : u.call(crypto)) || "client_" + Date.now(),
299
337
  payload: {
@@ -305,9 +343,9 @@ class nt {
305
343
  metadata: a
306
344
  }
307
345
  };
308
- this.ws.send(JSON.stringify(r));
346
+ this.ws.send(JSON.stringify(i));
309
347
  }, this.ws.onmessage = async (n) => {
310
- var r;
348
+ var i;
311
349
  const a = JSON.parse(n.data);
312
350
  if (a.type === "ANSWER")
313
351
  await this.pc.setRemoteDescription(new RTCSessionDescription(a.payload.sdp));
@@ -315,55 +353,63 @@ class nt {
315
353
  try {
316
354
  await this.pc.addIceCandidate(new RTCIceCandidate(a.payload.candidate));
317
355
  } catch (l) {
318
- (r = this.config.logger) == null || r.error("Error adding ICE candidate:", l);
356
+ (i = this.config.logger) == null || i.error("Error adding ICE candidate:", l);
319
357
  }
320
- }, this.ws.onclose = () => {
321
- this._stopAnalyzers();
358
+ }, this.ws.onclose = (n) => {
359
+ n.code !== 1e3 && this.errorCallbacks.forEach((a) => {
360
+ a("Oops! The connection to the server was lost. Please try again later.");
361
+ }), this._stopAnalyzers();
322
362
  };
323
363
  }
324
364
  async disconnect() {
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());
365
+ var t;
366
+ 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());
367
+ }
368
+ addVisualizerCallback(t) {
369
+ this.visualizerCallbacks.push(t);
327
370
  }
328
- addVisualizerCallback(e) {
329
- this.visualizerCallbacks.push(e);
371
+ addMessageCallback(t) {
372
+ this.messageCallbacks.push(t);
330
373
  }
331
- addMessageCallback(e) {
332
- this.messageCallbacks.push(e);
374
+ addErrorCallback(t) {
375
+ this.errorCallbacks.push(t);
333
376
  }
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) => {
377
+ createDataChannel(t = "messages") {
378
+ this.pc && (this.dataChannel = this.pc.createDataChannel(t), this.dataChannel.onopen = () => {
379
+ var e, s;
380
+ for ((e = this.config.logger) == null || e.info("Data channel opened"); this.queuedMessages.length > 0; ) {
381
+ const n = this.queuedMessages.shift();
382
+ n && (this.dataChannel.send(JSON.stringify(n)), (s = this.config.logger) == null || s.info("Sent queued message:", n));
383
+ }
384
+ }, this.dataChannel.onmessage = (e) => {
339
385
  this.messageCallbacks.forEach((s) => {
340
- s(t);
386
+ s(e);
341
387
  });
342
388
  });
343
389
  }
344
- sendPacket(e) {
345
- var t, s;
346
- if (!this.dataChannel) {
347
- (t = this.config.logger) == null || t.warn("Data channel is not open, cannot send message");
390
+ sendPacket(t) {
391
+ var e;
392
+ if (!this.dataChannel || this.dataChannel.readyState !== "open") {
393
+ this.queuedMessages.push(t);
348
394
  return;
349
395
  }
350
- this.dataChannel.send(JSON.stringify(e)), (s = this.config.logger) == null || s.info("Sent message:", e);
396
+ this.dataChannel.send(JSON.stringify(t)), (e = this.config.logger) == null || e.info("Sent message:", t);
351
397
  }
352
398
  _startAnalyzers() {
353
399
  if (!this.localStream || !this.remoteStream || this.visualizerCallbacks.length === 0)
354
400
  return;
355
401
  this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
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);
402
+ const t = this.audioCtx.createMediaStreamSource(this.localStream), e = this.audioCtx.createMediaStreamSource(this.remoteStream);
403
+ 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);
358
404
  const s = () => {
359
405
  if (!this.localAnalyser || !this.remoteAnalyser || this.visualizerCallbacks.length === 0)
360
406
  return;
361
407
  const n = new Uint8Array(this.localAnalyser.frequencyBinCount), a = new Uint8Array(this.remoteAnalyser.frequencyBinCount);
362
408
  this.localAnalyser.getByteFrequencyData(n), this.remoteAnalyser.getByteFrequencyData(a);
363
- const r = n.reduce((u, p) => u + p, 0) / n.length, l = a.reduce((u, p) => u + p, 0) / a.length;
409
+ const i = n.reduce((u, p) => u + p, 0) / n.length, l = a.reduce((u, p) => u + p, 0) / a.length;
364
410
  this.visualizerCallbacks.length > 0 && this.visualizerCallbacks.forEach((u) => {
365
411
  u({
366
- localAmplitude: r,
412
+ localAmplitude: i,
367
413
  remoteAmplitude: l
368
414
  });
369
415
  }), this.analyzerFrame = requestAnimationFrame(s);
@@ -374,17 +420,27 @@ class nt {
374
420
  this.analyzerFrame && (cancelAnimationFrame(this.analyzerFrame), this.analyzerFrame = null), this.localAnalyser = null, this.remoteAnalyser = null;
375
421
  }
376
422
  }
377
- class U extends E {
378
- constructor(t) {
423
+ class z extends v {
424
+ constructor(e) {
379
425
  super();
380
- o(this, "status");
381
- o(this, "session");
382
- o(this, "autostart");
383
- o(this, "config");
384
- o(this, "webRTCClient");
385
- this.config = t, this.status = "disconnected", this.session = null, this.autostart = (t == null ? void 0 : t.autostart) ?? !1, this.webRTCClient = new nt(t), this.webRTCClient.addMessageCallback((s) => {
426
+ r(this, "status");
427
+ r(this, "session");
428
+ r(this, "autostart");
429
+ r(this, "config");
430
+ r(this, "webRTCClient");
431
+ this.config = e, this.status = "disconnected", this.session = null, this.autostart = (e == null ? void 0 : e.autostart) ?? !1, this.webRTCClient = new ae(e), this.webRTCClient.addMessageCallback((s) => {
386
432
  const n = JSON.parse(s.data);
387
433
  this.notifyPacket(n);
434
+ }), this.webRTCClient.addErrorCallback((s) => {
435
+ var n;
436
+ (n = this.config.logger) == null || n.error("WebRTC error:", s), this.notifyPacket({
437
+ type: "message",
438
+ payload: {
439
+ type: "text",
440
+ role: "assistant",
441
+ text: s
442
+ }
443
+ });
388
444
  });
389
445
  }
390
446
  getName() {
@@ -393,39 +449,39 @@ class U extends E {
393
449
  getPriority() {
394
450
  return 1e3;
395
451
  }
396
- async syncSession(t) {
397
- super.syncSession(t), this.status === "connected" && (await this.disconnect(), await this.connect(t));
452
+ async syncSession(e) {
453
+ super.syncSession(e), this.status === "connected" && (await this.disconnect(), await this.connect(e));
398
454
  }
399
- async connect(t) {
455
+ async connect(e) {
400
456
  var s;
401
- return this.status === "connected" ? Promise.resolve(this.session) : (this.session = t || this.session || "new", this.setStatus("connecting"), (s = this.config.logger) == null || s.debug("Connecting to WebRTC with sessionId:", this.session), await this.webRTCClient.connect(this.session), this.setStatus("connected"), await this.webRTCClient.createDataChannel(), this.session);
457
+ return this.status === "connected" ? Promise.resolve(this.session) : (this.session = e || this.session || "new", this.setStatus("connecting"), (s = this.config.logger) == null || s.debug("Connecting to WebRTC with sessionId:", this.session), await this.webRTCClient.connect(this.session), this.setStatus("connected"), await this.webRTCClient.createDataChannel(), this.session);
402
458
  }
403
459
  async disconnect() {
404
- var t, s, n;
460
+ var e, s, n;
405
461
  if (this.status === "disconnected")
406
- return (t = this.config.logger) == null || t.warn("Already disconnected"), Promise.resolve();
462
+ return (e = this.config.logger) == null || e.warn("Already disconnected"), Promise.resolve();
407
463
  await this.webRTCClient.disconnect(), this.setStatus("disconnected"), (n = (s = this.config) == null ? void 0 : s.logger) == null || n.debug("Disconnected from WebRTC");
408
464
  }
409
- sendPacket(t) {
410
- return this.status !== "connected" ? Promise.reject(new Error("Not connected")) : (this.webRTCClient.sendPacket(t), Promise.resolve());
465
+ sendPacket(e) {
466
+ return this.status !== "connected" ? Promise.reject(new Error("Not connected")) : (this.webRTCClient.sendPacket(e), Promise.resolve());
411
467
  }
412
468
  }
413
- class it {
414
- constructor(e) {
415
- o(this, "config");
416
- this.config = e;
469
+ class ie {
470
+ constructor(t) {
471
+ r(this, "config");
472
+ this.config = t;
417
473
  }
418
- async complete(e, t) {
474
+ async complete(t, e) {
419
475
  var s;
420
- await this.persist(e, { ...t, success: !0 }), (s = this.config.logger) == null || s.debug("Transaction completed:", e);
476
+ await this.persist(t, { ...e, success: !0 }), (s = this.config.logger) == null || s.debug("Transaction completed:", t);
421
477
  }
422
- async fail(e, t) {
478
+ async fail(t, e) {
423
479
  var s;
424
- await this.persist(e, { ...t, success: !1 }), (s = this.config.logger) == null || s.debug("Transaction failed:", { ...e, ...t });
480
+ await this.persist(t, { ...e, success: !1 }), (s = this.config.logger) == null || s.debug("Transaction failed:", { ...t, ...e });
425
481
  }
426
- async persist(e, t) {
427
- await fetch(`${this.config.apiUrl}/transactions/${e.id}`, {
428
- body: JSON.stringify(t),
482
+ async persist(t, e) {
483
+ await fetch(`${this.config.apiUrl}/transactions/${t.id}`, {
484
+ body: JSON.stringify(e),
429
485
  method: "POST",
430
486
  headers: {
431
487
  "Content-Type": "application/json",
@@ -435,49 +491,55 @@ class it {
435
491
  });
436
492
  }
437
493
  }
438
- class at {
439
- constructor(e, t) {
440
- o(this, "transaction");
441
- o(this, "manager");
442
- this.transaction = e, this.manager = t;
494
+ class re {
495
+ constructor(t, e) {
496
+ r(this, "transaction");
497
+ r(this, "manager");
498
+ this.transaction = t, this.manager = e;
443
499
  }
444
500
  getFunctionCall() {
445
501
  return this.transaction.functionCall;
446
502
  }
447
- async invoke(e) {
448
- const t = this.transaction.functionCall;
449
- if (!t) {
503
+ async invoke(t) {
504
+ const e = this.transaction.functionCall;
505
+ if (!e) {
450
506
  await this.fail("No function call found");
451
507
  return;
452
508
  }
453
- const s = t.name, n = t.args, a = e[s];
509
+ const s = e.name, n = e.args, a = t[s];
454
510
  if (!a) {
455
511
  await this.fail(`Tool ${s} not found`);
456
512
  return;
457
513
  }
458
514
  try {
459
- const r = await a(n);
460
- await this.complete(r);
461
- } catch (r) {
462
- await this.fail(`Error executing tool ${s}: ${r}`);
515
+ const i = await a.apply(null, Object.values(n));
516
+ await this.complete(i);
517
+ } catch (i) {
518
+ await this.fail(`Error executing tool ${s}: ${i}`);
463
519
  }
464
520
  }
465
- async complete(e) {
466
- await this.manager.complete(this.transaction, { success: !0, output: e, error: null });
521
+ async complete(t) {
522
+ await this.manager.complete(this.transaction, { success: !0, output: t, error: null });
467
523
  }
468
- async fail(e) {
469
- await this.manager.fail(this.transaction, { success: !1, output: null, error: e });
524
+ async fail(t) {
525
+ await this.manager.fail(this.transaction, { success: !1, output: null, error: t });
470
526
  }
471
527
  }
472
- class ot extends E {
473
- constructor(t) {
528
+ class ce extends v {
529
+ constructor(e) {
474
530
  super();
475
- o(this, "status");
476
- o(this, "autostart");
477
- o(this, "session");
478
- o(this, "config");
479
- o(this, "notify", !0);
480
- this.config = t, this.status = "disconnected", this.autostart = !0;
531
+ r(this, "status");
532
+ r(this, "autostart");
533
+ r(this, "session");
534
+ r(this, "config");
535
+ r(this, "notify", !0);
536
+ r(this, "_tools");
537
+ if (this.config = e, this.status = "disconnected", this.autostart = !0, Array.isArray(e.tools)) {
538
+ this._tools = {};
539
+ for (const s of e.tools)
540
+ s.schema && s.implementation && (this._tools[s.schema.name] = s.implementation);
541
+ } else
542
+ this._tools = e.tools;
481
543
  }
482
544
  getName() {
483
545
  return "transaction";
@@ -485,143 +547,149 @@ class ot extends E {
485
547
  getPriority() {
486
548
  return 0;
487
549
  }
488
- async connect(t) {
489
- return this.setStatus("connected"), t;
550
+ async connect(e) {
551
+ return this.setStatus("connected"), e;
490
552
  }
491
553
  async disconnect() {
492
554
  this.setStatus("disconnected"), this.session = null;
493
555
  }
494
- async syncSession(t) {
495
- this.session = t;
556
+ async syncSession(e) {
557
+ this.session = e;
496
558
  }
497
- async sendPacket(t) {
559
+ async sendPacket(e) {
498
560
  }
499
- onTransaction(t) {
500
- var a;
501
- if (!this.config.onTransaction) {
502
- (a = this.config.logger) == null || a.error("Transaction protocol config is not set");
503
- return;
504
- }
505
- const s = new it(this.config), n = new at(t, s);
506
- this.config.onTransaction(n);
561
+ onTransaction(e) {
562
+ console.log("transaction received:", e);
563
+ const s = new ie(this.config), n = new re(e, s);
564
+ this.config.onTransaction ? this.config.onTransaction(n) : n.invoke(this._tools);
565
+ }
566
+ getTools() {
567
+ return this._tools;
507
568
  }
508
569
  }
509
- const P = B(void 0);
510
- function rt(i) {
511
- return new Promise((e, t) => {
570
+ const x = Y(void 0);
571
+ function le(o) {
572
+ return new Promise((t, e) => {
512
573
  const s = new FileReader();
513
- s.readAsDataURL(i), s.onload = () => {
574
+ s.readAsDataURL(o), s.onload = () => {
514
575
  const a = s.result.split(";base64,")[1];
515
- e(a);
576
+ t(a);
516
577
  }, s.onerror = (n) => {
517
- t(n);
578
+ e(n);
518
579
  };
519
580
  });
520
581
  }
521
- function ct({
522
- dev: i = !1,
523
- baseUrl: e,
524
- protocols: t,
582
+ function ue({
583
+ dev: o = !1,
584
+ baseUrl: t,
585
+ protocols: e,
525
586
  logger: s,
526
587
  children: n,
527
588
  session: a = "new",
528
- ...r
589
+ ...i
529
590
  }) {
530
- const [l, u] = R(!1), [p, g] = R([]), [w, T] = R(a), [k, j] = R(/* @__PURE__ */ new Map()), N = Y(!1), b = G(() => {
531
- if (Array.isArray(t))
532
- return t;
533
- if (typeof t == "object" && t !== null) {
534
- const c = i ? "localhost:8000" : e || "persona.applica.guru/api", f = i ? "http" : "https", d = i ? "ws" : "wss";
535
- let m = Object.keys(t).map((y) => {
591
+ const [l, u] = E(!1), [p, g] = E([]), [w, R] = E(a), [b, $] = E(/* @__PURE__ */ new Map()), O = G(!1), C = H(() => {
592
+ if (Array.isArray(e))
593
+ return e;
594
+ if (typeof e == "object" && e !== null) {
595
+ const c = o ? "localhost:8000" : t || "persona.applica.guru/api", f = o ? "http" : "https", h = o ? "ws" : "wss";
596
+ let m = Object.keys(e).map((y) => {
536
597
  switch (y) {
537
598
  case "rest":
538
- const h = t[y];
539
- return h === !0 ? new z({
599
+ const d = e[y];
600
+ return d === !0 ? new _({
540
601
  apiUrl: `${f}://${c}`,
541
- apiKey: r.apiKey,
542
- agentId: r.agentId,
602
+ apiKey: i.apiKey,
603
+ agentId: i.agentId,
543
604
  logger: s
544
- }) : typeof h == "object" && h !== null ? new z(h) : null;
605
+ }) : typeof d == "object" && d !== null ? new _(d) : null;
545
606
  case "webrtc":
546
- const C = t[y];
547
- return C === !0 ? new U({
548
- webrtcUrl: `${d}://${c}/webrtc`,
549
- apiKey: r.apiKey,
550
- agentId: r.agentId,
607
+ const S = e[y];
608
+ return S === !0 ? new z({
609
+ webrtcUrl: `${h}://${c}/webrtc`,
610
+ apiKey: i.apiKey,
611
+ agentId: i.agentId,
551
612
  logger: s
552
- }) : typeof C == "object" && C !== null ? new U(C) : null;
613
+ }) : typeof S == "object" && S !== null ? new z(S) : null;
553
614
  case "websocket":
554
- const x = t[y];
555
- return x === !0 ? new D({
556
- webSocketUrl: `${d}://${c}/websocket`,
557
- apiKey: r.apiKey,
558
- agentId: r.agentId,
615
+ const T = e[y];
616
+ return T === !0 ? new W({
617
+ webSocketUrl: `${h}://${c}/websocket`,
618
+ apiKey: i.apiKey,
619
+ agentId: i.agentId,
559
620
  logger: s
560
- }) : typeof x == "object" && x !== null ? new D(x) : null;
621
+ }) : typeof T == "object" && T !== null ? new W(T) : null;
561
622
  default:
562
623
  throw new Error(`Unknown protocol: ${y}`);
563
624
  }
564
625
  }).filter((y) => y !== null);
565
- return r.tools && m.push(
566
- new ot({
626
+ return i.tools && m.push(
627
+ new ce({
567
628
  apiUrl: `${f}://${c}`,
568
- apiKey: r.apiKey,
569
- agentId: r.agentId,
570
- onTransaction: async (y) => {
571
- await y.invoke(r.tools);
572
- },
629
+ apiKey: i.apiKey,
630
+ agentId: i.agentId,
631
+ tools: i.tools,
632
+ // Pass raw tools
573
633
  logger: s
574
634
  })
575
635
  ), m;
576
636
  }
577
637
  throw new Error("Invalid protocols configuration");
578
638
  }, []);
579
- V(() => {
580
- N.current || (N.current = !0, s == null || s.debug(
639
+ Q(() => {
640
+ O.current || (O.current = !0, s == null || s.debug(
581
641
  "Initializing protocols: ",
582
- b.map((c) => c.getName())
583
- ), b.forEach((c) => {
642
+ C.map((c) => c.getName())
643
+ ), C.forEach((c) => {
584
644
  c.setSession(w), c.clearListeners(), c.addStatusChangeListener((f) => {
585
- s == null || s.debug(`${c.getName()} has notified new status: ${f}`), k.set(c.getName(), f), f === "connected" && r.context && c.sendPacket({
645
+ s == null || s.debug(`${c.getName()} has notified new status: ${f}`), b.set(c.getName(), f), f === "connected" && (i.context && c.sendPacket({
586
646
  type: "command",
587
647
  payload: {
588
648
  command: "set_initial_context",
589
- arguments: r.context
649
+ arguments: i.context
590
650
  }
591
- }), j(new Map(k));
651
+ }), i.tools && Array.isArray(i.tools) && c.sendPacket({
652
+ type: "command",
653
+ payload: {
654
+ command: "set_local_tools",
655
+ arguments: {
656
+ tools: i.tools.map((h) => h.schema)
657
+ }
658
+ }
659
+ })), $(new Map(b));
592
660
  }), c.addPacketListener((f) => {
593
661
  if (f.type === "message") {
594
- const d = f.payload;
662
+ const h = f.payload;
595
663
  g(
596
- (m) => M([...m, { ...d, protocol: c.getName() }])
664
+ (m) => q([...m, { ...h, protocol: c.getName() }])
597
665
  );
598
666
  } else if (f.type === "reasoning") {
599
- const d = f.payload;
600
- let m = d.thought;
601
- d.imageUrl && (m += `
667
+ const h = f.payload;
668
+ let m = h.thought;
669
+ h.imageUrl && (m += `
602
670
 
603
- ![image](https://persona.applica.guru/api/files/${d.imageUrl})`);
671
+ ![image](https://persona.applica.guru/api/files/${h.imageUrl})`);
604
672
  const y = { type: "reasoning", text: m, role: "assistant", finishReason: "stop" };
605
673
  g(
606
- (h) => M([...h, { ...y, protocol: c.getName() }])
674
+ (d) => q([...d, { ...y, protocol: c.getName() }])
607
675
  );
608
- } else f.type === "transaction" && b.filter((d) => d !== c).forEach((d) => d.onTransaction(f.payload));
676
+ } else f.type === "transaction" && C.filter((h) => h !== c).forEach((h) => h.onTransaction(f.payload));
609
677
  }), c.autostart && c.status === "disconnected" && (s == null || s.debug(`Connecting to protocol: ${c.getName()}`), c.connect(w));
610
678
  }));
611
- }, [w, b, s, k]);
612
- const O = async (c) => {
679
+ }, [w, C, s, b]);
680
+ const U = async (c) => {
613
681
  var y;
614
682
  if (((y = c.content[0]) == null ? void 0 : y.type) !== "text") throw new Error("Only text messages are supported");
615
683
  const f = c.content[0].text;
616
- g((h) => [...h, { role: "user", type: "text", text: f }]), u(!0);
617
- const d = b.sort((h, C) => C.getPriority() - h.getPriority()).find((h) => h.status === "connected"), m = [];
684
+ g((d) => [...d, { role: "user", type: "text", text: f }]), u(!0);
685
+ const h = C.sort((d, S) => S.getPriority() - d.getPriority()).find((d) => d.status === "connected"), m = [];
618
686
  if (c.attachments)
619
- for (const h of c.attachments)
620
- h.contentType.startsWith("image/") && h.file && m.push({
687
+ for (const d of c.attachments)
688
+ d.contentType.startsWith("image/") && d.file && m.push({
621
689
  role: "user",
622
690
  image: {
623
- contentType: h.contentType,
624
- content: await rt(h.file)
691
+ contentType: d.contentType,
692
+ content: await le(d.file)
625
693
  },
626
694
  text: "",
627
695
  type: "text"
@@ -630,100 +698,211 @@ function ct({
630
698
  role: "user",
631
699
  text: c.content[0].text,
632
700
  type: "text"
633
- }), s == null || s.debug("Sending message:", m), await (d == null ? void 0 : d.sendPacket({ type: "request", payload: m })), u(!1);
634
- }, L = v(() => (u(!1), g([]), T("new"), Promise.resolve()), []), F = v(() => Promise.resolve(), []), _ = v(() => p, [p]), J = H({
701
+ }), s == null || s.debug("Sending message:", m), await (h == null ? void 0 : h.sendPacket({ type: "request", payload: m })), u(!1);
702
+ }, D = M(() => (u(!1), g([]), R("new"), Promise.resolve()), []), L = M(() => Promise.resolve(), []), J = M(() => p, [p]), K = X({
635
703
  isRunning: l,
636
704
  messages: p,
637
- convertMessage: st,
638
- onNew: O,
639
- onCancel: L,
640
- onReload: F,
705
+ convertMessage: oe,
706
+ onNew: U,
707
+ onCancel: D,
708
+ onReload: L,
641
709
  adapters: {
642
- attachments: new Q([new X()])
710
+ attachments: new Z([new ee()])
643
711
  }
644
712
  });
645
- return /* @__PURE__ */ $.jsx(P.Provider, { value: { protocols: b, protocolsStatus: k, getMessages: _ }, children: /* @__PURE__ */ $.jsx(Z, { runtime: J, children: n }) });
713
+ return /* @__PURE__ */ N.jsx(x.Provider, { value: { protocols: C, protocolsStatus: b, getMessages: J }, children: /* @__PURE__ */ N.jsx(te, { runtime: K, children: n }) });
646
714
  }
647
- function ft({ children: i, ...e }) {
648
- return /* @__PURE__ */ $.jsx(ct, { ...e, children: i });
715
+ function ge({ children: o, ...t }) {
716
+ return /* @__PURE__ */ N.jsx(ue, { ...t, children: o });
649
717
  }
650
- function pt() {
651
- const i = A(P);
652
- if (!i)
718
+ function we() {
719
+ const o = A(x);
720
+ if (!o)
653
721
  throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");
654
- return i;
722
+ return o;
655
723
  }
656
- function lt(i) {
657
- const e = A(P);
658
- if (!e)
659
- throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");
660
- const t = e.protocols.find((n) => n.getName() === i);
724
+ function he(o) {
725
+ const t = A(x);
661
726
  if (!t)
727
+ throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");
728
+ const e = t.protocols.find((n) => n.getName() === o);
729
+ if (!e)
662
730
  return null;
663
- const s = e.protocolsStatus.get(t.getName());
731
+ const s = t.protocolsStatus.get(e.getName());
664
732
  return {
665
- ...t,
666
- connect: t.connect.bind(t),
667
- disconnect: t.disconnect.bind(t),
668
- sendPacket: t.sendPacket.bind(t),
669
- setSession: t.setSession.bind(t),
670
- addStatusChangeListener: t.addStatusChangeListener.bind(t),
671
- addPacketListener: t.addPacketListener.bind(t),
672
- getName: t.getName.bind(t),
673
- getPriority: t.getPriority.bind(t),
674
- status: s || t.status
733
+ ...e,
734
+ connect: e.connect.bind(e),
735
+ disconnect: e.disconnect.bind(e),
736
+ sendPacket: e.sendPacket.bind(e),
737
+ setSession: e.setSession.bind(e),
738
+ addStatusChangeListener: e.addStatusChangeListener.bind(e),
739
+ addPacketListener: e.addPacketListener.bind(e),
740
+ getName: e.getName.bind(e),
741
+ getPriority: e.getPriority.bind(e),
742
+ status: s || e.status
675
743
  };
676
744
  }
677
- function yt() {
678
- const i = A(P);
679
- if (!i)
745
+ function be() {
746
+ const o = A(x);
747
+ if (!o)
680
748
  throw new Error("usePersonaRuntimeEndpoint must be used within a PersonaRuntimeProvider");
681
- for (const e of i.protocols)
682
- if (e.getName() === "rest")
683
- return e.config.apiUrl;
749
+ for (const t of o.protocols)
750
+ if (t.getName() === "rest")
751
+ return t.config.apiUrl;
684
752
  throw new Error("REST protocol not found");
685
753
  }
686
- function mt() {
687
- return lt("webrtc");
754
+ function Ce() {
755
+ return he("webrtc");
688
756
  }
689
- function gt() {
690
- const i = A(P);
691
- if (!i)
757
+ function Se() {
758
+ const o = A(x);
759
+ if (!o)
692
760
  throw new Error("usePersonaRuntimeMessages must be used within a PersonaRuntimeProvider");
693
- return i.getMessages();
761
+ return o.getMessages();
694
762
  }
695
- class wt {
763
+ class Pe {
696
764
  constructor() {
697
- o(this, "prefix", "[Persona]");
765
+ r(this, "prefix", "[Persona]");
766
+ }
767
+ log(t, ...e) {
768
+ console.log(`${this.prefix} - ${t}`, ...e);
698
769
  }
699
- log(e, ...t) {
700
- console.log(`${this.prefix} - ${e}`, ...t);
770
+ info(t, ...e) {
771
+ console.info(`${this.prefix} - ${t}`, ...e);
701
772
  }
702
- info(e, ...t) {
703
- console.info(`${this.prefix} - ${e}`, ...t);
773
+ warn(t, ...e) {
774
+ console.warn(`${this.prefix} - ${t}`, ...e);
704
775
  }
705
- warn(e, ...t) {
706
- console.warn(`${this.prefix} - ${e}`, ...t);
776
+ error(t, ...e) {
777
+ console.error(`${this.prefix} - ${t}`, ...e);
707
778
  }
708
- error(e, ...t) {
709
- console.error(`${this.prefix} - ${e}`, ...t);
779
+ debug(t, ...e) {
780
+ console.debug(`${this.prefix} - ${t}`, ...e);
710
781
  }
711
- debug(e, ...t) {
712
- console.debug(`${this.prefix} - ${e}`, ...t);
782
+ }
783
+ function P(o, t, e) {
784
+ return {
785
+ type: o,
786
+ description: t,
787
+ ...e
788
+ };
789
+ }
790
+ function de(o) {
791
+ const t = Object.entries(o.parameters).filter(([e, s]) => s.required).map(([e]) => e);
792
+ return {
793
+ type: "local",
794
+ name: o.name,
795
+ description: o.description,
796
+ config: {
797
+ timeout: o.timeout || 60,
798
+ parameters: {
799
+ type: "object",
800
+ title: o.title || `${o.name} parameters`,
801
+ required: t,
802
+ properties: o.parameters
803
+ },
804
+ output: {
805
+ type: "object",
806
+ title: `${o.name} output`,
807
+ properties: o.output
808
+ }
809
+ }
810
+ };
811
+ }
812
+ function I(o) {
813
+ return {
814
+ schema: de(o),
815
+ implementation: o.implementation
816
+ };
817
+ }
818
+ function pe(o, t, e, s, n, a) {
819
+ const i = {
820
+ name: o,
821
+ description: t,
822
+ title: a == null ? void 0 : a.title,
823
+ timeout: a == null ? void 0 : a.timeout,
824
+ parameters: s,
825
+ output: n,
826
+ implementation: e
827
+ };
828
+ return I(i);
829
+ }
830
+ const ke = pe(
831
+ "sum",
832
+ "Sum two numbers",
833
+ function(t, e) {
834
+ return { result: t + e };
835
+ },
836
+ {
837
+ a: P("number", "First number to sum", { required: !0 }),
838
+ b: P("number", "Second number to sum", { required: !0 })
839
+ },
840
+ {
841
+ result: P("number", "Sum of two numbers")
842
+ }
843
+ ), xe = I({
844
+ name: "navigate_to",
845
+ description: "Allow agent to redirect user to specific sub page like /foo or #/foo or anything like that",
846
+ title: "Sum two numbers",
847
+ // As per the user's example
848
+ timeout: 60,
849
+ parameters: {
850
+ a: P("number", "First number to sum"),
851
+ b: P("number", "Seconth number to sum")
852
+ // Keeping the typo as in the original
853
+ },
854
+ output: {
855
+ result: P("number", "Sum of two numbers")
856
+ },
857
+ implementation: function(t, e) {
858
+ return { result: t + e };
859
+ }
860
+ });
861
+ function Re(o) {
862
+ const t = [], e = {};
863
+ return o.forEach((s) => {
864
+ const { schema: n, implementation: a } = I(s);
865
+ t.push(n), e[s.name] = a;
866
+ }), { schemas: t, implementations: e };
867
+ }
868
+ function Te(o, t) {
869
+ const { required: e, properties: s } = t.config.parameters;
870
+ for (const n of e)
871
+ if (!(n in o))
872
+ throw new Error(`Missing required parameter: ${n}`);
873
+ for (const [n, a] of Object.entries(o)) {
874
+ const i = s[n];
875
+ if (i) {
876
+ if (i.type === "number" && typeof a != "number")
877
+ throw new Error(`Parameter ${n} should be a number`);
878
+ if (i.type === "string" && typeof a != "string")
879
+ throw new Error(`Parameter ${n} should be a string`);
880
+ if (i.type === "boolean" && typeof a != "boolean")
881
+ throw new Error(`Parameter ${n} should be a boolean`);
882
+ }
713
883
  }
884
+ return !0;
714
885
  }
715
886
  export {
716
- wt as PersonaConsoleLogger,
717
- E as PersonaProtocolBase,
718
- z as PersonaRESTProtocol,
719
- ft as PersonaRuntimeProvider,
720
- ot as PersonaTransactionProtocol,
721
- U as PersonaWebRTCProtocol,
722
- D as PersonaWebSocketProtocol,
723
- pt as usePersonaRuntime,
724
- yt as usePersonaRuntimeEndpoint,
725
- gt as usePersonaRuntimeMessages,
726
- lt as usePersonaRuntimeProtocol,
727
- mt as usePersonaRuntimeWebRTCProtocol
887
+ Pe as PersonaConsoleLogger,
888
+ v as PersonaProtocolBase,
889
+ _ as PersonaRESTProtocol,
890
+ ge as PersonaRuntimeProvider,
891
+ ce as PersonaTransactionProtocol,
892
+ z as PersonaWebRTCProtocol,
893
+ W as PersonaWebSocketProtocol,
894
+ P as createParameter,
895
+ I as createTool,
896
+ pe as createToolFromFunction,
897
+ Re as createToolRegistry,
898
+ de as generateToolSchema,
899
+ xe as navigateToToolExample,
900
+ ke as sumTool,
901
+ we as usePersonaRuntime,
902
+ be as usePersonaRuntimeEndpoint,
903
+ Se as usePersonaRuntimeMessages,
904
+ he as usePersonaRuntimeProtocol,
905
+ Ce as usePersonaRuntimeWebRTCProtocol,
906
+ Te as validateToolParameters
728
907
  };
729
908
  //# sourceMappingURL=bundle.es.js.map