@useago/sdk 0.3.3 → 0.4.1
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/AgoClient-B6PsfMeg.cjs +6 -0
- package/dist/{AgoClient-DF7M2WAz.js → AgoClient-BerJvssl.js} +235 -219
- package/dist/angular.cjs +1 -1
- package/dist/angular.d.cts +12 -0
- package/dist/angular.d.ts +12 -0
- package/dist/angular.js +1 -1
- package/dist/createConversationSession-CLZvxyuu.js +58 -0
- package/dist/createConversationSession-D3K5Gf1k.cjs +1 -0
- package/dist/createFormCollector-CD1rqRG4.js +208 -0
- package/dist/createFormCollector-D1FfiSgA.cjs +1 -0
- package/dist/createMockClient-DMFGIOtc.cjs +1 -0
- package/dist/createMockClient-tVsApEAh.js +72 -0
- package/dist/devtools.cjs +26 -26
- package/dist/devtools.d.cts +16 -26
- package/dist/devtools.d.ts +16 -26
- package/dist/devtools.js +55 -55
- package/dist/helpers.cjs +1 -1
- package/dist/helpers.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +102 -1
- package/dist/index.d.ts +102 -1
- package/dist/index.js +46 -43
- package/dist/react.cjs +19 -19
- package/dist/react.d.cts +67 -8
- package/dist/react.d.ts +67 -8
- package/dist/react.js +1066 -1051
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +12 -0
- package/dist/vue.d.ts +12 -0
- package/dist/vue.js +1 -1
- package/dist/widget.cjs +1 -0
- package/dist/widget.d.cts +635 -0
- package/dist/widget.d.ts +635 -0
- package/dist/widget.js +418 -0
- package/package.json +58 -15
- package/dist/AgoClient-bjN-z2ZQ.cjs +0 -6
- package/dist/createMockClient-D6uVh-B9.js +0 -254
- package/dist/createMockClient-DecMEUcK.cjs +0 -1
- /package/dist/{functions-DdROP6Ui.js → functions-C1-5vadY.js} +0 -0
- /package/dist/{functions-Bz-1Bs3I.cjs → functions-DsmzgHjC.cjs} +0 -0
package/dist/widget.js
CHANGED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { t as re } from "./AgoClient-BerJvssl.js";
|
|
2
|
+
import { t as ae } from "./createFormCollector-CD1rqRG4.js";
|
|
3
|
+
import { t as ie } from "./createConversationSession-CLZvxyuu.js";
|
|
4
|
+
var Y = '"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
|
|
5
|
+
function x(s, n) {
|
|
6
|
+
Object.assign(s.style, n);
|
|
7
|
+
}
|
|
8
|
+
function c(s = {}) {
|
|
9
|
+
const n = document.createElement("div");
|
|
10
|
+
return x(n, s), n;
|
|
11
|
+
}
|
|
12
|
+
var V = "ago-chat-widget-keyframes";
|
|
13
|
+
function se() {
|
|
14
|
+
if (typeof document > "u" || document.getElementById(V)) return;
|
|
15
|
+
const s = document.createElement("style");
|
|
16
|
+
s.id = V, s.textContent = "@keyframes ago-pulse { 0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); } 40% { opacity: 1; transform: scale(1); } }", document.head.appendChild(s);
|
|
17
|
+
}
|
|
18
|
+
function le(s) {
|
|
19
|
+
const n = typeof s == "string" ? document.querySelector(s) : s;
|
|
20
|
+
if (!n) throw new Error(`mountChatWidget: target "${String(s)}" not found.`);
|
|
21
|
+
return n;
|
|
22
|
+
}
|
|
23
|
+
function ue(s, n) {
|
|
24
|
+
const { title: v = "Chat", welcomeMessage: _ = "Hello! How can I help you today?", placeholder: N = "Type a message...", allowFiles: g = !1, height: m = 500, logoUrl: f, showAgentName: b = !1, loadThreads: I = !1, forms: A, onFollowUpClick: R, onMessageSent: i, onMessageReceived: C } = n;
|
|
25
|
+
if (!n.client && !n.config?.baseUrl) throw new Error("mountChatWidget requires either `client` or `config` (with a baseUrl).");
|
|
26
|
+
const l = n.client ?? new re(n.config), L = le(s), y = n.persistConversation, D = y ? ie(y === !0 ? {} : y) : void 0;
|
|
27
|
+
let u = n.conversationId ?? D?.getLastActiveThread() ?? void 0, o = [], k = !1, z = null;
|
|
28
|
+
const T = [], W = c({
|
|
29
|
+
display: "flex",
|
|
30
|
+
flexDirection: "column",
|
|
31
|
+
height: typeof m == "number" ? `${m}px` : m,
|
|
32
|
+
border: "1px solid #dee3e8",
|
|
33
|
+
borderRadius: "16px",
|
|
34
|
+
overflow: "hidden",
|
|
35
|
+
backgroundColor: "#fff",
|
|
36
|
+
fontFamily: Y,
|
|
37
|
+
boxShadow: "rgba(15, 15, 15, 0.08) 0px 2px 16px 0px"
|
|
38
|
+
});
|
|
39
|
+
W.className = "ago-chat-widget";
|
|
40
|
+
const F = c({
|
|
41
|
+
padding: "14px 16px",
|
|
42
|
+
borderBottom: "1px solid #dee3e8",
|
|
43
|
+
backgroundColor: "#03182f",
|
|
44
|
+
color: "#e8f0fe",
|
|
45
|
+
display: "flex",
|
|
46
|
+
alignItems: "center",
|
|
47
|
+
gap: "10px"
|
|
48
|
+
});
|
|
49
|
+
if (F.className = "ago-chat-widget__header", f) {
|
|
50
|
+
const e = document.createElement("img");
|
|
51
|
+
e.src = f, e.alt = "Logo", x(e, {
|
|
52
|
+
height: "24px",
|
|
53
|
+
width: "auto"
|
|
54
|
+
}), F.appendChild(e);
|
|
55
|
+
}
|
|
56
|
+
const M = document.createElement("h3");
|
|
57
|
+
M.textContent = v, x(M, {
|
|
58
|
+
margin: "0",
|
|
59
|
+
fontSize: "15px",
|
|
60
|
+
fontWeight: "600"
|
|
61
|
+
}), F.appendChild(M);
|
|
62
|
+
const E = c({
|
|
63
|
+
flex: "1",
|
|
64
|
+
overflow: "auto",
|
|
65
|
+
padding: "16px",
|
|
66
|
+
backgroundColor: "#fbfbfb"
|
|
67
|
+
});
|
|
68
|
+
E.className = "ago-chat-widget__messages";
|
|
69
|
+
const { inputRow: J, setDisabled: Q, focus: X } = de({
|
|
70
|
+
placeholder: N,
|
|
71
|
+
allowFiles: g,
|
|
72
|
+
onSend: (e, t) => {
|
|
73
|
+
H(e, t);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
se(), W.append(F, E, J), L.appendChild(W);
|
|
77
|
+
const O = R !== !1, $ = R === !1 ? void 0 : R ?? ((e) => {
|
|
78
|
+
H(e);
|
|
79
|
+
});
|
|
80
|
+
function Z(e) {
|
|
81
|
+
const t = e.role === "user", d = c({
|
|
82
|
+
display: "flex",
|
|
83
|
+
flexDirection: "column",
|
|
84
|
+
alignItems: t ? "flex-end" : "flex-start",
|
|
85
|
+
marginBottom: "16px"
|
|
86
|
+
});
|
|
87
|
+
if (d.className = `ago-message ago-message--${e.role}`, !t && b && e.agent) {
|
|
88
|
+
const r = c({
|
|
89
|
+
fontSize: "13px",
|
|
90
|
+
fontWeight: "500",
|
|
91
|
+
color: "#30373e",
|
|
92
|
+
marginBottom: "6px",
|
|
93
|
+
padding: "0 4px"
|
|
94
|
+
});
|
|
95
|
+
r.className = "ago-message__agent", r.textContent = e.agent.displayName || e.agent.name, d.appendChild(r);
|
|
96
|
+
}
|
|
97
|
+
if (!t && e.sources && e.sources.length > 0) {
|
|
98
|
+
const r = c({
|
|
99
|
+
display: "grid",
|
|
100
|
+
gridTemplateColumns: "1fr 1fr",
|
|
101
|
+
gap: "6px",
|
|
102
|
+
marginBottom: "10px",
|
|
103
|
+
width: "100%",
|
|
104
|
+
maxWidth: "85%"
|
|
105
|
+
});
|
|
106
|
+
r.className = "ago-message__sources", e.sources.forEach((p, a) => {
|
|
107
|
+
const w = p.url ? document.createElement("a") : document.createElement("div");
|
|
108
|
+
p.url && w instanceof HTMLAnchorElement && (w.href = p.url, w.target = "_blank", w.rel = "noopener noreferrer"), x(w, {
|
|
109
|
+
display: "flex",
|
|
110
|
+
alignItems: "center",
|
|
111
|
+
gap: "8px",
|
|
112
|
+
padding: "8px 10px",
|
|
113
|
+
border: "1px solid #dee3e8",
|
|
114
|
+
borderRadius: "8px",
|
|
115
|
+
backgroundColor: "#fff",
|
|
116
|
+
textDecoration: "none",
|
|
117
|
+
color: "#30373e",
|
|
118
|
+
fontSize: "12px",
|
|
119
|
+
overflow: "hidden"
|
|
120
|
+
});
|
|
121
|
+
const q = c({
|
|
122
|
+
flexShrink: "0",
|
|
123
|
+
width: "18px",
|
|
124
|
+
height: "18px",
|
|
125
|
+
borderRadius: "3px",
|
|
126
|
+
border: "1px solid #1b5fc4",
|
|
127
|
+
color: "#1b5fc4",
|
|
128
|
+
fontSize: "11px",
|
|
129
|
+
fontWeight: "500",
|
|
130
|
+
display: "flex",
|
|
131
|
+
alignItems: "center",
|
|
132
|
+
justifyContent: "center",
|
|
133
|
+
backgroundColor: "#f0f4ff"
|
|
134
|
+
});
|
|
135
|
+
q.textContent = String(a + 1);
|
|
136
|
+
const B = c({
|
|
137
|
+
overflow: "hidden",
|
|
138
|
+
textOverflow: "ellipsis",
|
|
139
|
+
whiteSpace: "nowrap"
|
|
140
|
+
});
|
|
141
|
+
B.textContent = p.title, B.title = p.title, w.append(q, B), r.appendChild(w);
|
|
142
|
+
}), d.appendChild(r);
|
|
143
|
+
}
|
|
144
|
+
const h = c({
|
|
145
|
+
maxWidth: t ? "75%" : "100%",
|
|
146
|
+
padding: t ? "10px 14px" : "2px 8px",
|
|
147
|
+
borderRadius: t ? "16px" : "0",
|
|
148
|
+
backgroundColor: t ? "#03182f" : "transparent",
|
|
149
|
+
color: t ? "#fff" : "#30373e",
|
|
150
|
+
wordBreak: "break-word",
|
|
151
|
+
fontSize: "14px",
|
|
152
|
+
lineHeight: "1.6",
|
|
153
|
+
whiteSpace: "pre-wrap"
|
|
154
|
+
});
|
|
155
|
+
if (h.className = "ago-message__content", e.content ? h.textContent = e.content : e.status === "IN_PROGRESS" && h.appendChild(oe()), d.appendChild(h), e.followUpReplies && e.followUpReplies.length > 0) {
|
|
156
|
+
const r = c({
|
|
157
|
+
display: "flex",
|
|
158
|
+
flexWrap: "wrap",
|
|
159
|
+
gap: "8px",
|
|
160
|
+
marginTop: "10px"
|
|
161
|
+
});
|
|
162
|
+
r.className = "ago-message__followups";
|
|
163
|
+
for (const p of e.followUpReplies) {
|
|
164
|
+
const a = document.createElement("button");
|
|
165
|
+
a.type = "button", a.className = "ago-message__followup-btn", a.textContent = p, a.disabled = !O, x(a, {
|
|
166
|
+
padding: "6px 14px",
|
|
167
|
+
fontSize: "13px",
|
|
168
|
+
borderRadius: "16px",
|
|
169
|
+
border: "1px solid #dee3e8",
|
|
170
|
+
backgroundColor: "#fff",
|
|
171
|
+
color: "#30373e",
|
|
172
|
+
cursor: O ? "pointer" : "default",
|
|
173
|
+
transition: "border-color 0.15s"
|
|
174
|
+
}), $ && a.addEventListener("click", () => $(p)), a.addEventListener("mouseenter", () => {
|
|
175
|
+
a.style.borderColor = "#1b5fc4";
|
|
176
|
+
}), a.addEventListener("mouseleave", () => {
|
|
177
|
+
a.style.borderColor = "#dee3e8";
|
|
178
|
+
}), r.appendChild(a);
|
|
179
|
+
}
|
|
180
|
+
d.appendChild(r);
|
|
181
|
+
}
|
|
182
|
+
return d;
|
|
183
|
+
}
|
|
184
|
+
function S() {
|
|
185
|
+
if (E.replaceChildren(), o.length === 0) {
|
|
186
|
+
const e = c({
|
|
187
|
+
textAlign: "center",
|
|
188
|
+
color: "#6b6d6f",
|
|
189
|
+
padding: "24px 16px",
|
|
190
|
+
fontSize: "14px",
|
|
191
|
+
lineHeight: "1.5"
|
|
192
|
+
});
|
|
193
|
+
e.textContent = _, E.appendChild(e);
|
|
194
|
+
} else for (const e of o) E.appendChild(Z(e));
|
|
195
|
+
if (z) {
|
|
196
|
+
const e = c({
|
|
197
|
+
padding: "10px 14px",
|
|
198
|
+
backgroundColor: "#fef2f2",
|
|
199
|
+
color: "#dc2626",
|
|
200
|
+
borderRadius: "12px",
|
|
201
|
+
marginTop: "8px",
|
|
202
|
+
fontSize: "13px",
|
|
203
|
+
border: "1px solid #fecaca"
|
|
204
|
+
});
|
|
205
|
+
e.textContent = z, E.appendChild(e);
|
|
206
|
+
}
|
|
207
|
+
E.scrollTop = E.scrollHeight, Q(k);
|
|
208
|
+
}
|
|
209
|
+
function ee() {
|
|
210
|
+
for (let e = o.length - 1; e >= 0; e--) {
|
|
211
|
+
const t = o[e];
|
|
212
|
+
if (t.role === "assistant" && t.status === "IN_PROGRESS") return t;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const P = (e) => {
|
|
216
|
+
u || (u = e.conversationId);
|
|
217
|
+
}, G = (e) => {
|
|
218
|
+
const t = ee();
|
|
219
|
+
t && (t.content += e.content, S());
|
|
220
|
+
}, K = (e) => {
|
|
221
|
+
const t = o.findIndex((d) => d.id === e.id || d.role === "assistant" && d.status === "IN_PROGRESS");
|
|
222
|
+
t >= 0 ? o[t] = e : o.push(e), k = !1, S(), e.status === "DONE" && C?.({
|
|
223
|
+
id: e.id,
|
|
224
|
+
content: e.content
|
|
225
|
+
});
|
|
226
|
+
}, j = (e) => {
|
|
227
|
+
z = e.error, k = !1, o = o.filter((t) => !t.id.startsWith("temp-")), S();
|
|
228
|
+
};
|
|
229
|
+
l.on("message:start", P), l.on("message:chunk", G), l.on("message:complete", K), l.on("message:error", j);
|
|
230
|
+
const te = (A ?? []).map((e) => ae(e).install(l));
|
|
231
|
+
async function H(e, t) {
|
|
232
|
+
const d = e.trim();
|
|
233
|
+
if (!d && !t?.length || k) return;
|
|
234
|
+
i?.(d), k = !0, z = null;
|
|
235
|
+
const h = Date.now();
|
|
236
|
+
o.push({
|
|
237
|
+
id: `temp-user-${h}`,
|
|
238
|
+
conversationId: u || "",
|
|
239
|
+
content: d,
|
|
240
|
+
role: "user",
|
|
241
|
+
status: "DONE",
|
|
242
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
243
|
+
}), o.push({
|
|
244
|
+
id: `temp-assistant-${h}`,
|
|
245
|
+
conversationId: u || "",
|
|
246
|
+
content: "",
|
|
247
|
+
role: "assistant",
|
|
248
|
+
status: "IN_PROGRESS",
|
|
249
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
250
|
+
}), S();
|
|
251
|
+
try {
|
|
252
|
+
const r = await l.sendMessage(d, {
|
|
253
|
+
conversationId: u,
|
|
254
|
+
files: t
|
|
255
|
+
});
|
|
256
|
+
r.conversationId && (u || (u = r.conversationId), D?.setActiveThread(r.conversationId, r.createdAt));
|
|
257
|
+
const p = o.find((a) => a.id === `temp-user-${h}`);
|
|
258
|
+
if (p && (p.id = `user-${h}`, p.conversationId = r.conversationId), !o.some((a) => a.id === r.id)) {
|
|
259
|
+
const a = o.findIndex((w) => w.id === `temp-assistant-${h}`);
|
|
260
|
+
a >= 0 ? o[a] = r : o.push(r);
|
|
261
|
+
}
|
|
262
|
+
o = o.filter((a) => !a.id.startsWith("temp-")), k = !1, S(), I && U();
|
|
263
|
+
} catch (r) {
|
|
264
|
+
z = r instanceof Error ? r.message : "Failed to send message", k = !1, o = o.filter((p) => !p.id.startsWith("temp-")), S();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
async function U() {
|
|
268
|
+
try {
|
|
269
|
+
const e = await l.getConversations();
|
|
270
|
+
T.splice(0, T.length, ...e);
|
|
271
|
+
} catch {
|
|
272
|
+
}
|
|
273
|
+
return T;
|
|
274
|
+
}
|
|
275
|
+
async function ne(e) {
|
|
276
|
+
try {
|
|
277
|
+
const t = (await l.getConversation(e))?.messages ?? [];
|
|
278
|
+
t.length > 0 && o.length === 0 && (o = t, S());
|
|
279
|
+
} catch {
|
|
280
|
+
o.length === 0 && (D?.clear(), u = void 0);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return S(), X(), u && ne(u), I && U(), {
|
|
284
|
+
client: l,
|
|
285
|
+
element: W,
|
|
286
|
+
sendMessage: H,
|
|
287
|
+
session: D,
|
|
288
|
+
threads: T,
|
|
289
|
+
refreshThreads: U,
|
|
290
|
+
destroy() {
|
|
291
|
+
l.off("message:start", P), l.off("message:chunk", G), l.off("message:complete", K), l.off("message:error", j), te.forEach((e) => e()), W.remove(), n.client || l.destroy();
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
function oe() {
|
|
295
|
+
const e = c({
|
|
296
|
+
display: "flex",
|
|
297
|
+
gap: "4px",
|
|
298
|
+
padding: "4px 0"
|
|
299
|
+
});
|
|
300
|
+
for (let t = 0; t < 3; t++) {
|
|
301
|
+
const d = c({
|
|
302
|
+
width: "6px",
|
|
303
|
+
height: "6px",
|
|
304
|
+
borderRadius: "50%",
|
|
305
|
+
backgroundColor: "#b5bfc8",
|
|
306
|
+
animation: "ago-pulse 1.2s ease-in-out infinite",
|
|
307
|
+
animationDelay: `${t * 0.2}s`
|
|
308
|
+
});
|
|
309
|
+
e.appendChild(d);
|
|
310
|
+
}
|
|
311
|
+
return e;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function de(s) {
|
|
315
|
+
let n = [];
|
|
316
|
+
const v = document.createElement("form");
|
|
317
|
+
x(v, {
|
|
318
|
+
display: "flex",
|
|
319
|
+
flexDirection: "column",
|
|
320
|
+
gap: "8px",
|
|
321
|
+
padding: "12px",
|
|
322
|
+
borderTop: "1px solid #dee3e8",
|
|
323
|
+
backgroundColor: "#fff"
|
|
324
|
+
}), v.className = "ago-chat-input";
|
|
325
|
+
const _ = c({
|
|
326
|
+
display: "flex",
|
|
327
|
+
flexWrap: "wrap",
|
|
328
|
+
gap: "6px"
|
|
329
|
+
}), N = c({
|
|
330
|
+
display: "flex",
|
|
331
|
+
gap: "8px",
|
|
332
|
+
alignItems: "flex-end"
|
|
333
|
+
}), g = document.createElement("textarea");
|
|
334
|
+
g.placeholder = s.placeholder, g.rows = 1, x(g, {
|
|
335
|
+
flex: "1",
|
|
336
|
+
resize: "none",
|
|
337
|
+
padding: "10px 12px",
|
|
338
|
+
border: "1px solid #dee3e8",
|
|
339
|
+
borderRadius: "12px",
|
|
340
|
+
fontSize: "14px",
|
|
341
|
+
fontFamily: Y,
|
|
342
|
+
lineHeight: "1.4",
|
|
343
|
+
maxHeight: "120px",
|
|
344
|
+
outline: "none"
|
|
345
|
+
});
|
|
346
|
+
const m = document.createElement("button");
|
|
347
|
+
m.type = "submit", m.textContent = "Send", x(m, {
|
|
348
|
+
padding: "10px 16px",
|
|
349
|
+
border: "none",
|
|
350
|
+
borderRadius: "12px",
|
|
351
|
+
backgroundColor: "#03182f",
|
|
352
|
+
color: "#fff",
|
|
353
|
+
fontSize: "14px",
|
|
354
|
+
fontWeight: "500",
|
|
355
|
+
cursor: "pointer"
|
|
356
|
+
});
|
|
357
|
+
let f = null, b = null;
|
|
358
|
+
s.allowFiles && (f = document.createElement("input"), f.type = "file", f.multiple = !0, x(f, { display: "none" }), b = document.createElement("button"), b.type = "button", b.textContent = "📎", x(b, {
|
|
359
|
+
padding: "10px 12px",
|
|
360
|
+
border: "1px solid #dee3e8",
|
|
361
|
+
borderRadius: "12px",
|
|
362
|
+
backgroundColor: "#fff",
|
|
363
|
+
cursor: "pointer",
|
|
364
|
+
fontSize: "14px"
|
|
365
|
+
}), b.addEventListener("click", () => f?.click()), f.addEventListener("change", () => {
|
|
366
|
+
n = [...n, ...Array.from(f?.files ?? [])], I();
|
|
367
|
+
}));
|
|
368
|
+
function I() {
|
|
369
|
+
_.replaceChildren(), n.forEach((i, C) => {
|
|
370
|
+
const l = c({
|
|
371
|
+
display: "flex",
|
|
372
|
+
alignItems: "center",
|
|
373
|
+
gap: "4px",
|
|
374
|
+
padding: "4px 8px",
|
|
375
|
+
backgroundColor: "#f0f4ff",
|
|
376
|
+
border: "1px solid #dee3e8",
|
|
377
|
+
borderRadius: "8px",
|
|
378
|
+
fontSize: "12px"
|
|
379
|
+
}), L = document.createElement("span");
|
|
380
|
+
L.textContent = i.name;
|
|
381
|
+
const y = document.createElement("button");
|
|
382
|
+
y.type = "button", y.textContent = "×", x(y, {
|
|
383
|
+
border: "none",
|
|
384
|
+
background: "transparent",
|
|
385
|
+
cursor: "pointer",
|
|
386
|
+
fontSize: "14px",
|
|
387
|
+
lineHeight: "1"
|
|
388
|
+
}), y.addEventListener("click", () => {
|
|
389
|
+
n = n.filter((D, u) => u !== C), I();
|
|
390
|
+
}), l.append(L, y), _.appendChild(l);
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
const A = () => {
|
|
394
|
+
const i = g.value, C = n;
|
|
395
|
+
return g.value = "", n = [], I(), {
|
|
396
|
+
content: i,
|
|
397
|
+
files: C
|
|
398
|
+
};
|
|
399
|
+
}, R = () => {
|
|
400
|
+
const { content: i, files: C } = A();
|
|
401
|
+
(i.trim() || C.length > 0) && s.onSend(i.trim(), C.length > 0 ? C : void 0);
|
|
402
|
+
};
|
|
403
|
+
return v.addEventListener("submit", (i) => {
|
|
404
|
+
i.preventDefault(), R();
|
|
405
|
+
}), g.addEventListener("keydown", (i) => {
|
|
406
|
+
i.key === "Enter" && !i.shiftKey && (i.preventDefault(), R());
|
|
407
|
+
}), b && N.appendChild(b), N.append(g, m), f && v.appendChild(f), v.append(_, N), {
|
|
408
|
+
inputRow: v,
|
|
409
|
+
getValueAndClear: A,
|
|
410
|
+
setDisabled: (i) => {
|
|
411
|
+
g.disabled = i, m.disabled = i, m.style.opacity = i ? "0.6" : "1", m.style.cursor = i ? "not-allowed" : "pointer";
|
|
412
|
+
},
|
|
413
|
+
focus: () => g.focus()
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
export {
|
|
417
|
+
ue as mountChatWidget
|
|
418
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@useago/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "JavaScript SDK for AGO Chat integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -9,32 +9,74 @@
|
|
|
9
9
|
"types": "dist/index.d.ts",
|
|
10
10
|
"exports": {
|
|
11
11
|
".": {
|
|
12
|
-
"import": {
|
|
13
|
-
|
|
12
|
+
"import": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"default": "./dist/index.js"
|
|
15
|
+
},
|
|
16
|
+
"require": {
|
|
17
|
+
"types": "./dist/index.d.cts",
|
|
18
|
+
"default": "./dist/index.cjs"
|
|
19
|
+
}
|
|
14
20
|
},
|
|
15
21
|
"./react": {
|
|
16
|
-
"import": {
|
|
17
|
-
|
|
22
|
+
"import": {
|
|
23
|
+
"types": "./dist/react.d.ts",
|
|
24
|
+
"default": "./dist/react.js"
|
|
25
|
+
},
|
|
26
|
+
"require": {
|
|
27
|
+
"types": "./dist/react.d.cts",
|
|
28
|
+
"default": "./dist/react.cjs"
|
|
29
|
+
}
|
|
18
30
|
},
|
|
19
31
|
"./vue": {
|
|
20
|
-
"import": {
|
|
21
|
-
|
|
32
|
+
"import": {
|
|
33
|
+
"types": "./dist/vue.d.ts",
|
|
34
|
+
"default": "./dist/vue.js"
|
|
35
|
+
},
|
|
36
|
+
"require": {
|
|
37
|
+
"types": "./dist/vue.d.cts",
|
|
38
|
+
"default": "./dist/vue.cjs"
|
|
39
|
+
}
|
|
22
40
|
},
|
|
23
41
|
"./angular": {
|
|
24
|
-
"import": {
|
|
25
|
-
|
|
42
|
+
"import": {
|
|
43
|
+
"types": "./dist/angular.d.ts",
|
|
44
|
+
"default": "./dist/angular.js"
|
|
45
|
+
},
|
|
46
|
+
"require": {
|
|
47
|
+
"types": "./dist/angular.d.cts",
|
|
48
|
+
"default": "./dist/angular.cjs"
|
|
49
|
+
}
|
|
26
50
|
},
|
|
27
51
|
"./helpers": {
|
|
28
|
-
"import": {
|
|
29
|
-
|
|
52
|
+
"import": {
|
|
53
|
+
"types": "./dist/helpers.d.ts",
|
|
54
|
+
"default": "./dist/helpers.js"
|
|
55
|
+
},
|
|
56
|
+
"require": {
|
|
57
|
+
"types": "./dist/helpers.d.cts",
|
|
58
|
+
"default": "./dist/helpers.cjs"
|
|
59
|
+
}
|
|
30
60
|
},
|
|
31
61
|
"./widget": {
|
|
32
|
-
"import": {
|
|
33
|
-
|
|
62
|
+
"import": {
|
|
63
|
+
"types": "./dist/widget.d.ts",
|
|
64
|
+
"default": "./dist/widget.js"
|
|
65
|
+
},
|
|
66
|
+
"require": {
|
|
67
|
+
"types": "./dist/widget.d.cts",
|
|
68
|
+
"default": "./dist/widget.cjs"
|
|
69
|
+
}
|
|
34
70
|
},
|
|
35
71
|
"./devtools": {
|
|
36
|
-
"import": {
|
|
37
|
-
|
|
72
|
+
"import": {
|
|
73
|
+
"types": "./dist/devtools.d.ts",
|
|
74
|
+
"default": "./dist/devtools.js"
|
|
75
|
+
},
|
|
76
|
+
"require": {
|
|
77
|
+
"types": "./dist/devtools.d.cts",
|
|
78
|
+
"default": "./dist/devtools.cjs"
|
|
79
|
+
}
|
|
38
80
|
}
|
|
39
81
|
},
|
|
40
82
|
"publishConfig": {
|
|
@@ -94,6 +136,7 @@
|
|
|
94
136
|
"@types/react-dom": "^18.0.0",
|
|
95
137
|
"@typescript-eslint/eslint-plugin": "^7.0.0",
|
|
96
138
|
"@typescript-eslint/parser": "^7.0.0",
|
|
139
|
+
"esbuild": "^0.28.0",
|
|
97
140
|
"eslint": "^8.0.0",
|
|
98
141
|
"eslint-plugin-react-hooks": "^4.6.2",
|
|
99
142
|
"jsdom": "^28.0.0",
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
var u=class extends Error{constructor(e,t,s){super(e),this.code=t,this.statusCode=s,this.name="AgoError"}},l=class m extends u{constructor(t,s,r,n,o,a){super(t,s,r),this.type=n,this.param=o,this.docUrl=a,this.name="AgoApiError"}static fromResponse(t,s){const r=t.error;return new m(r.message,r.code,s,r.type,r.param,r.doc_url)}},h=class extends u{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},d=class extends u{constructor(e){super(e,"stream_error"),this.name="AgoStreamError"}},g=class extends u{constructor(e,t,s){super(e,"function_error"),this.functionName=t,this.originalError=s,this.name="AgoFunctionError"}},C=class{constructor(e=!1){this.enabled=e}enable(){this.enabled=!0}disable(){this.enabled=!1}log(...e){this.enabled&&console.log("[AGO SDK]",...e)}warn(...e){this.enabled&&console.warn("[AGO SDK]",...e)}error(...e){console.error("[AGO SDK]",...e)}debug(...e){this.enabled&&console.debug("[AGO SDK]",...e)}},i=new C,f="ago_widget_id";function E(){if(typeof localStorage<"u"){const t=localStorage.getItem(f);if(t)return t}const e=crypto.randomUUID();if(typeof localStorage<"u")try{localStorage.setItem(f,e)}catch{}return e}var _=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-Widget-Id":e.widgetId||E()},e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission&&(this.headers["X-Widget-Permission"]=e.permission)}updateConfig(e){e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-Widget-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"])}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async postStream(e,t){const s=`${this.baseUrl}${e}`;i.debug("POST (stream)",s,t);try{const r=await fetch(s,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0});return r.ok||await this.handleErrorResponse(r),r}catch(r){throw r instanceof l?r:new h(`Network error: ${r instanceof Error?r.message:"Unknown error"}`,r instanceof Error?r:void 0)}}async postFormData(e,t){const s=`${this.baseUrl}${e}`;i.debug("POST (formData)",s);const r={...this.headers};try{const n=await fetch(s,{method:"POST",headers:r,body:t});return n.ok||await this.handleErrorResponse(n),n}catch(n){throw n instanceof l?n:new h(`Network error: ${n instanceof Error?n.message:"Unknown error"}`,n instanceof Error?n:void 0)}}async request(e,t,s){const r=`${this.baseUrl}${t}`;i.debug(e,r,s);try{const n=await fetch(r,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});return n.ok||await this.handleErrorResponse(n),n.status===204?void 0:n.json()}catch(n){throw n instanceof l?n:new h(`Network error: ${n instanceof Error?n.message:"Unknown error"}`,n instanceof Error?n:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}throw t?.error?l.fromResponse(t,e.status):new l(`HTTP ${e.status}: ${e.statusText}`,"http_error",e.status,"api_error")}},p=class{constructor(){this.functions=new Map}register(e,t,s){if(typeof e=="object"){const{name:n,handler:o,description:a,parameters:c}=e;return this.register(n,o,{description:a,parameters:c})}const r=e;if(!t||!s)throw new Error("handler and schema are required");this.functions.has(r)&&i.warn(`Function "${r}" is being overwritten`),this.functions.set(r,{schema:{...s,name:r},handler:t}),i.log(`Registered function: ${r}`)}unregister(e){const t=this.functions.delete(e);return t&&i.log(`Unregistered function: ${e}`),t}get(e){return this.functions.get(e)}has(e){return this.functions.has(e)}getSchemas(){return Array.from(this.functions.values()).map(e=>e.schema)}async execute(e,t){const s=this.functions.get(e);if(!s)throw new g(`Function "${e}" is not registered`,e);i.log(`Executing function: ${e}`,t);try{const r=await s.handler(t);return i.log(`Function ${e} completed:`,r),r}catch(r){throw i.error(`Function ${e} failed:`,r),new g(`Function "${e}" execution failed: ${r instanceof Error?r.message:"Unknown error"}`,e,r instanceof Error?r:void 0)}}clear(){this.functions.clear(),i.log("Cleared all registered functions")}get size(){return this.functions.size}},y=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),i.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&i.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),i.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&i.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,s]of this.entries)e[t]=s;for(const[t,s]of this.dynamicProviders)try{const r=s();r&&(e[t]=r)}catch(r){i.error(`DynamicContext provider "${t}" threw:`,r)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),i.log("ClientContext cleared")}},w=class{constructor(e){this.callbacks=e,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0}async processStream(e){if(!e.body)throw new d("Response has no body");const t=e.body.getReader(),s=new TextDecoder;try{for(;;){const{done:r,value:n}=await t.read();if(r)break;const o=s.decode(n,{stream:!0});this.buffer+=o,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(r){const n=r instanceof Error?r:new d("Stream processing failed");throw this.callbacks.onError?.(n),n}finally{t.releaseLock()}}processBuffer(){const e=this.buffer.split(`
|
|
2
|
-
|
|
3
|
-
`);this.buffer=e.pop()||"";for(const t of e){if(!t.trim())continue;const s=t.split(`
|
|
4
|
-
`);for(const r of s)if(!r.startsWith(": ")&&r.startsWith("data: ")){const n=r.slice(6);try{const o=JSON.parse(n);this.handleChunk(o)}catch(o){i.warn("Failed to parse SSE data:",n,o)}}}}handleChunk(e){if(e.message_id&&!this.message.id&&(this.message.id=e.message_id),e.thread?.id&&(this.message.conversationId=e.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),e.content!==void 0&&(this.message.content=(this.message.content||"")+e.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:e.content,conversationId:this.message.conversationId,messageId:this.message.id})),e.full_content!==void 0&&(this.message.content=e.full_content),e.status&&(this.message.status=e.status),e.agent&&(this.message.agent={id:e.agent.id,name:e.agent.name,displayName:e.agent.display_name}),e.knowledge_sources&&(this.sources=e.knowledge_sources.map(t=>{const s=t.knowledge_document;return{id:s.id,title:s.title,url:s.use_external_link?s.external_link_url:s.internal_link_url}})),e.type==="client_function"&&e.function_name&&this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}),e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const s=this.toolCalls.findIndex(r=>r.id===t.id);s>=0?this.toolCalls[s]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies)}parseToolCall(e){return{id:e.id||"",type:e.type||"status_message",status:e.status||"unknown",toolName:e.tool_name||"",toolDisplayName:e.tool_display_name,message:e.message,formSchema:e.form_schema,data:e.data,functionName:e.function_name,arguments:e.arguments}}buildFinalMessage(){const e={id:this.message.id||"",conversationId:this.message.conversationId||"",content:this.message.content||"",role:"assistant",status:this.message.status||"DONE",agent:this.message.agent,sources:this.sources.length>0?this.sources:void 0,toolCalls:this.toolCalls.length>0?this.toolCalls:void 0,followUpReplies:this.followUpReplies.length>0?this.followUpReplies:void 0,createdAt:new Date};return this.callbacks.onComplete?.(e),e}};function k(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var v=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){const s=this.handlers.get(e);s&&s.delete(t)}emit(e,t){const s=this.handlers.get(e);s&&s.forEach(r=>{try{r(t)}catch(n){console.error(`Error in event handler for ${String(e)}:`,n)}})}once(e,t){const s=(r=>{this.off(e,s),t(r)});this.on(e,s)}waitFor(e,t){return new Promise((s,r)=>{let n;const o=(a=>{n&&clearTimeout(n),s(a)});this.once(e,o),t?.timeout&&(n=setTimeout(()=>{this.off(e,o),r(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},S=class{constructor(e){this.config=e,this.httpClient=new _(e),this.functionRegistry=new p,this.contextRegistry=new y,this.eventEmitter=new v,e.debug&&i.enable(),i.log("AgoClient initialized")}async sendMessage(e,t){const s=this.functionRegistry.getSchemas(),r=this.contextRegistry.getSnapshot(),n=this.config.agent||this.config.defaultAgentId,o={content:e,conversation_id:t?.conversationId,agent_id:t?.agentId||n};s.length>0&&(o.client_functions=s),r&&(o.client_context=r);let a;if(t?.files&&t.files.length>0){const c=new FormData;c.append("content",e),t.conversationId&&c.append("conversation_id",t.conversationId),(t.agentId||n)&&c.append("agent_id",t.agentId||n||""),s.length>0&&c.append("client_functions",JSON.stringify(s)),r&&c.append("client_context",JSON.stringify(r));for(const b of t.files)c.append("files",b);a=await this.httpClient.postFormData("/api/sdk/v1/messages",c)}else a=await this.httpClient.postStream("/api/sdk/v1/messages",o);return this.processSSEResponse(a)}async processSSEResponse(e){return new w({onStart:t=>{this.eventEmitter.emit("message:start",t)},onChunk:t=>{this.eventEmitter.emit("message:chunk",t)},onToolCall:t=>{this.eventEmitter.emit("toolCall:received",t),t.type==="form"&&this.eventEmitter.emit("toolCall:form",t)},onClientFunction:async t=>{this.eventEmitter.emit("function:invoke",t),await this.handleClientFunctionInvocation(t)},onComplete:t=>{this.eventEmitter.emit("message:complete",t)},onError:t=>{this.eventEmitter.emit("message:error",{error:t.message})}}).processStream(e)}async handleClientFunctionInvocation(e){let t,s;try{t=await this.functionRegistry.execute(e.functionName,e.arguments)}catch(r){s=r instanceof Error?r.message:"Unknown error",i.error("Client function execution failed:",r)}if(e.invocationId)try{await this.submitToolCallForm(e.invocationId,{result:t,error:s,_type:"client_function_result"})}catch(r){i.error("Failed to submit function result:",r)}this.eventEmitter.emit("function:result",{invocationId:e.invocationId,result:t,error:s})}async getConversations(){return(await this.httpClient.get("/api/sdk/v1/conversations")).items.map(e=>({id:e.id,title:e.title,lastMessageDate:new Date(e.last_message_date)}))}async getConversation(e){const t=await this.httpClient.get(`/api/sdk/v1/conversations/${e}`);return{id:t.id,title:t.title,lastMessageDate:new Date(t.last_message_date),messages:t.messages.map(s=>({id:s.id,conversationId:t.id,content:s.content,role:s.role,status:s.status,createdAt:new Date(s.created_at)}))}}async getMessages(e){return(await this.getConversation(e)).messages||[]}async submitToolCallForm(e,t){await this.httpClient.post(`/api/sdk/v1/tool-calls/${e}/submit`,{formData:t})}async confirmToolCall(e){await this.httpClient.post(`/api/tool-calls/${e}/confirm/`)}async rejectToolCall(e){await this.httpClient.post(`/api/tool-calls/${e}/reject/`)}async submitFormCollector(e,t){return this.httpClient.post("/api/sdk/v1/forms/submit",{destination:e,values:t})}async submitFeedback(e,t){await this.httpClient.post(`/api/sdk/v1/messages/${e}/feedback`,{rating:t})}registerFunction(e,t,s){typeof e=="object"?this.functionRegistry.register(e):this.functionRegistry.register(e,t,s)}register(e){if(Array.isArray(e))for(const t of e)this.functionRegistry.register(t);else this.functionRegistry.register(e)}unregisterFunction(e){return this.functionRegistry.unregister(e)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}registerNavigationFunction(e,t){const s=t.map(n=>n.name),r=t.map(n=>`- "${n.name}": ${n.description}`).join(`
|
|
5
|
-
`);this.registerFunction("navigateToPage",async n=>{const o=n.page,a=t.find(c=>c.name===o);return a?(e(a.path),{success:!0,navigatedTo:a.path}):{success:!1,error:`Unknown page: ${o}`}},{description:`Navigate the user to a page in the application. Available pages:
|
|
6
|
-
${r}`,parameters:{type:"object",properties:{page:{type:"string",description:"The page to navigate to",enum:s}},required:["page"]}})}setContext(e,t){this.contextRegistry.set(e,t)}removeContext(e){return this.contextRegistry.remove(e)}addDynamicContext(e,t){this.contextRegistry.addDynamicProvider(e,t)}removeDynamicContext(e){return this.contextRegistry.removeDynamicProvider(e)}enableAutoPageContext(){this.contextRegistry.addDynamicProvider("browser-page",()=>{const e=typeof window<"u"?window.location.href:void 0,t=typeof document<"u"?document.title:void 0;return!e&&!t?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:e,title:t}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}once(e,t){this.eventEmitter.once(e,t)}waitFor(e,t){return this.eventEmitter.waitFor(e,t)}updateConfig(e){this.config={...this.config,...e},this.httpClient.updateConfig(e),e.debug!==void 0&&(e.debug?i.enable():i.disable())}destroy(){this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.contextRegistry.clear(),i.log("AgoClient destroyed")}};Object.defineProperty(exports,"AgoApiError",{enumerable:!0,get:function(){return l}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return S}});Object.defineProperty(exports,"AgoError",{enumerable:!0,get:function(){return u}});Object.defineProperty(exports,"AgoFunctionError",{enumerable:!0,get:function(){return g}});Object.defineProperty(exports,"AgoNetworkError",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"AgoStreamError",{enumerable:!0,get:function(){return d}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return y}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return v}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return p}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return w}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return k}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return i}});
|