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

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