@useago/sdk 1.0.10 → 1.1.0
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-QcTtrN7u.js → AgoClient-Cwx_eYSu.js} +182 -131
- package/dist/AgoClient-CzSmJQxl.cjs +6 -0
- package/dist/angular.cjs +1 -1
- package/dist/angular.d.cts +23 -0
- package/dist/angular.d.ts +23 -0
- package/dist/angular.js +1 -1
- package/dist/{createConversationSession-CR-71aLR.js → createConversationSession-B3h567tt.js} +1 -1
- package/dist/{createConversationSession-C0diFTUk.cjs → createConversationSession-DV0Xp_3O.cjs} +1 -1
- package/dist/{createFormCollector-BI3DXaew.cjs → createFormCollector-BB3Uscuo.cjs} +1 -1
- package/dist/{createFormCollector-CFt1_QSL.js → createFormCollector-CyWisAkI.js} +1 -1
- package/dist/devtools.d.cts +23 -0
- package/dist/devtools.d.ts +23 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +43 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +58 -55
- package/dist/react.cjs +3 -3
- package/dist/react.d.cts +23 -0
- package/dist/react.d.ts +23 -0
- package/dist/react.js +482 -367
- package/dist/testing.d.cts +23 -0
- package/dist/testing.d.ts +23 -0
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +119 -0
- package/dist/vue.d.ts +119 -0
- package/dist/vue.js +1 -1
- package/dist/widget.cjs +4 -4
- package/dist/widget.d.cts +48 -2
- package/dist/widget.d.ts +48 -2
- package/dist/widget.js +538 -417
- package/package.json +1 -1
- package/dist/AgoClient-B3-WGVne.cjs +0 -6
|
@@ -3,12 +3,12 @@ var h = class extends Error {
|
|
|
3
3
|
super(e), this.code = t, this.statusCode = s, this.name = "AgoError";
|
|
4
4
|
}
|
|
5
5
|
}, d = class C extends h {
|
|
6
|
-
constructor(t, s,
|
|
7
|
-
super(t, s,
|
|
6
|
+
constructor(t, s, i, n, r, a) {
|
|
7
|
+
super(t, s, i), this.type = n, this.param = r, this.docUrl = a, this.name = "AgoApiError";
|
|
8
8
|
}
|
|
9
9
|
static fromResponse(t, s) {
|
|
10
|
-
const
|
|
11
|
-
return new C(
|
|
10
|
+
const i = t.error;
|
|
11
|
+
return new C(i.doc_url ? `${i.message} See ${i.doc_url}` : i.message, i.code, s, i.type, i.param, i.doc_url);
|
|
12
12
|
}
|
|
13
13
|
}, u = class extends h {
|
|
14
14
|
constructor(e, t) {
|
|
@@ -22,7 +22,7 @@ var h = class extends Error {
|
|
|
22
22
|
constructor(e, t, s) {
|
|
23
23
|
super(e, "function_error"), this.functionName = t, this.originalError = s, this.name = "AgoFunctionError";
|
|
24
24
|
}
|
|
25
|
-
},
|
|
25
|
+
}, E = class {
|
|
26
26
|
constructor(e = !1) {
|
|
27
27
|
this.enabled = e;
|
|
28
28
|
}
|
|
@@ -44,7 +44,7 @@ var h = class extends Error {
|
|
|
44
44
|
debug(...e) {
|
|
45
45
|
this.enabled && console.debug("[AGO SDK]", ...e);
|
|
46
46
|
}
|
|
47
|
-
}, o = new
|
|
47
|
+
}, o = new E(), p = "ago_widget_id";
|
|
48
48
|
function S() {
|
|
49
49
|
if (typeof localStorage < "u") {
|
|
50
50
|
const t = localStorage.getItem(p);
|
|
@@ -74,7 +74,7 @@ var k = class {
|
|
|
74
74
|
const s = `${this.baseUrl}${e}`;
|
|
75
75
|
o.debug("POST (stream)", s, t);
|
|
76
76
|
try {
|
|
77
|
-
const
|
|
77
|
+
const i = await fetch(s, {
|
|
78
78
|
method: "POST",
|
|
79
79
|
headers: {
|
|
80
80
|
...this.headers,
|
|
@@ -82,31 +82,31 @@ var k = class {
|
|
|
82
82
|
},
|
|
83
83
|
body: t ? JSON.stringify(t) : void 0
|
|
84
84
|
});
|
|
85
|
-
return
|
|
86
|
-
} catch (
|
|
87
|
-
throw
|
|
85
|
+
return i.ok || await this.handleErrorResponse(i), i;
|
|
86
|
+
} catch (i) {
|
|
87
|
+
throw i instanceof d ? i : new u(`Network error: ${i instanceof Error ? i.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, i instanceof Error ? i : void 0);
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
90
|
async postFormData(e, t) {
|
|
91
91
|
const s = `${this.baseUrl}${e}`;
|
|
92
92
|
o.debug("POST (formData)", s);
|
|
93
|
-
const
|
|
93
|
+
const i = { ...this.headers };
|
|
94
94
|
try {
|
|
95
|
-
const
|
|
95
|
+
const n = await fetch(s, {
|
|
96
96
|
method: "POST",
|
|
97
|
-
headers:
|
|
97
|
+
headers: i,
|
|
98
98
|
body: t
|
|
99
99
|
});
|
|
100
|
-
return
|
|
101
|
-
} catch (
|
|
102
|
-
throw
|
|
100
|
+
return n.ok || await this.handleErrorResponse(n), n;
|
|
101
|
+
} catch (n) {
|
|
102
|
+
throw n instanceof d ? n : new u(`Network error: ${n instanceof Error ? n.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, n instanceof Error ? n : void 0);
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
105
|
async request(e, t, s) {
|
|
106
|
-
const
|
|
107
|
-
o.debug(e,
|
|
106
|
+
const i = `${this.baseUrl}${t}`;
|
|
107
|
+
o.debug(e, i, s);
|
|
108
108
|
try {
|
|
109
|
-
const
|
|
109
|
+
const n = await fetch(i, {
|
|
110
110
|
method: e,
|
|
111
111
|
headers: {
|
|
112
112
|
...this.headers,
|
|
@@ -114,9 +114,9 @@ var k = class {
|
|
|
114
114
|
},
|
|
115
115
|
body: s ? JSON.stringify(s) : void 0
|
|
116
116
|
});
|
|
117
|
-
return
|
|
118
|
-
} catch (
|
|
119
|
-
throw
|
|
117
|
+
return n.ok || await this.handleErrorResponse(n), n.status === 204 ? void 0 : n.json();
|
|
118
|
+
} catch (n) {
|
|
119
|
+
throw n instanceof d ? n : new u(`Network error: ${n instanceof Error ? n.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, n instanceof Error ? n : void 0);
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
122
|
async handleErrorResponse(e) {
|
|
@@ -135,21 +135,21 @@ var k = class {
|
|
|
135
135
|
}
|
|
136
136
|
register(e, t, s) {
|
|
137
137
|
if (typeof e == "object") {
|
|
138
|
-
const { name:
|
|
139
|
-
return this.register(
|
|
138
|
+
const { name: n, handler: r, description: a, parameters: l } = e;
|
|
139
|
+
return this.register(n, r, {
|
|
140
140
|
description: a,
|
|
141
141
|
parameters: l
|
|
142
142
|
});
|
|
143
143
|
}
|
|
144
|
-
const
|
|
145
|
-
if (!t || !s) throw new h(`registerFunction("${
|
|
146
|
-
this.functions.has(
|
|
144
|
+
const i = e;
|
|
145
|
+
if (!t || !s) throw new h(`registerFunction("${i}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`, "function_invalid_registration");
|
|
146
|
+
this.functions.has(i) && o.warn(`Function "${i}" is being overwritten`), this.functions.set(i, {
|
|
147
147
|
schema: {
|
|
148
148
|
...s,
|
|
149
|
-
name:
|
|
149
|
+
name: i
|
|
150
150
|
},
|
|
151
151
|
handler: t
|
|
152
|
-
}), o.log(`Registered function: ${
|
|
152
|
+
}), o.log(`Registered function: ${i}`);
|
|
153
153
|
}
|
|
154
154
|
unregister(e) {
|
|
155
155
|
const t = this.functions.delete(e);
|
|
@@ -169,10 +169,10 @@ var k = class {
|
|
|
169
169
|
if (!s) throw new f(`Function "${e}" is not registered`, e);
|
|
170
170
|
o.log(`Executing function: ${e}`, t);
|
|
171
171
|
try {
|
|
172
|
-
const
|
|
173
|
-
return o.log(`Function ${e} completed:`,
|
|
174
|
-
} catch (
|
|
175
|
-
throw o.error(`Function ${e} failed:`,
|
|
172
|
+
const i = await s.handler(t);
|
|
173
|
+
return o.log(`Function ${e} completed:`, i), i;
|
|
174
|
+
} catch (i) {
|
|
175
|
+
throw o.error(`Function ${e} failed:`, i), new f(`Function "${e}" execution failed: ${i instanceof Error ? i.message : "Unknown error"}`, e, i instanceof Error ? i : void 0);
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
178
|
clear() {
|
|
@@ -204,10 +204,10 @@ var k = class {
|
|
|
204
204
|
const e = {};
|
|
205
205
|
for (const [t, s] of this.entries) e[t] = s;
|
|
206
206
|
for (const [t, s] of this.dynamicProviders) try {
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
} catch (
|
|
210
|
-
o.error(`DynamicContext provider "${t}" threw:`,
|
|
207
|
+
const i = s();
|
|
208
|
+
i && (e[t] = i);
|
|
209
|
+
} catch (i) {
|
|
210
|
+
o.error(`DynamicContext provider "${t}" threw:`, i);
|
|
211
211
|
}
|
|
212
212
|
return Object.keys(e).length === 0 ? null : { entries: e };
|
|
213
213
|
}
|
|
@@ -218,7 +218,7 @@ var k = class {
|
|
|
218
218
|
function m(e) {
|
|
219
219
|
return e === null || typeof e != "object" ? JSON.stringify(e) ?? "null" : Array.isArray(e) ? `[${e.map(m).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${m(e[t])}`).join(",")}}`;
|
|
220
220
|
}
|
|
221
|
-
var
|
|
221
|
+
var R = class {
|
|
222
222
|
constructor(e) {
|
|
223
223
|
this.callbacks = e, this.buffer = "", this.message = {}, this.toolCalls = [], this.sources = [], this.followUpReplies = [], this.isFirstChunk = !0, this.answerCompleteEmitted = !1, this.firedClientFunctions = /* @__PURE__ */ new Set();
|
|
224
224
|
}
|
|
@@ -227,15 +227,15 @@ var x = class {
|
|
|
227
227
|
const t = e.body.getReader(), s = new TextDecoder();
|
|
228
228
|
try {
|
|
229
229
|
for (; ; ) {
|
|
230
|
-
const { done:
|
|
231
|
-
if (
|
|
232
|
-
const r = s.decode(
|
|
230
|
+
const { done: i, value: n } = await t.read();
|
|
231
|
+
if (i) break;
|
|
232
|
+
const r = s.decode(n, { stream: !0 });
|
|
233
233
|
this.buffer += r, this.processBuffer();
|
|
234
234
|
}
|
|
235
235
|
return this.buffer.trim() && this.processBuffer(), this.buildFinalMessage();
|
|
236
|
-
} catch (
|
|
237
|
-
const
|
|
238
|
-
throw this.callbacks.onError?.(
|
|
236
|
+
} catch (i) {
|
|
237
|
+
const n = i instanceof Error ? i : new g("Stream processing failed mid-flight. The connection may have dropped; retry the message.");
|
|
238
|
+
throw this.callbacks.onError?.(n), n;
|
|
239
239
|
} finally {
|
|
240
240
|
t.releaseLock();
|
|
241
241
|
}
|
|
@@ -249,14 +249,14 @@ var x = class {
|
|
|
249
249
|
if (!t.trim()) continue;
|
|
250
250
|
const s = t.split(`
|
|
251
251
|
`);
|
|
252
|
-
for (const
|
|
253
|
-
if (!
|
|
254
|
-
const
|
|
252
|
+
for (const i of s)
|
|
253
|
+
if (!i.startsWith(": ") && i.startsWith("data: ")) {
|
|
254
|
+
const n = i.slice(6);
|
|
255
255
|
try {
|
|
256
|
-
const r = JSON.parse(
|
|
256
|
+
const r = JSON.parse(n);
|
|
257
257
|
this.handleChunk(r);
|
|
258
258
|
} catch (r) {
|
|
259
|
-
o.warn("Failed to parse SSE data:",
|
|
259
|
+
o.warn("Failed to parse SSE data:", n, r);
|
|
260
260
|
}
|
|
261
261
|
}
|
|
262
262
|
}
|
|
@@ -292,7 +292,7 @@ var x = class {
|
|
|
292
292
|
if (e.tool_call_data && e.type && e.type !== "client_function") {
|
|
293
293
|
const t = this.parseToolCall(e);
|
|
294
294
|
this.callbacks.onToolCall?.(t);
|
|
295
|
-
const s = this.toolCalls.findIndex((
|
|
295
|
+
const s = this.toolCalls.findIndex((i) => i.id === t.id);
|
|
296
296
|
s >= 0 ? this.toolCalls[s] = t : this.toolCalls.push(t);
|
|
297
297
|
}
|
|
298
298
|
e.follow_up_replies && (this.followUpReplies = e.follow_up_replies), this.message.status === "DONE" && !this.answerCompleteEmitted && this.message.id && (this.answerCompleteEmitted = !0, this.callbacks.onAnswerComplete?.(this.buildMessage()));
|
|
@@ -330,11 +330,57 @@ var x = class {
|
|
|
330
330
|
return this.callbacks.onComplete?.(e), e;
|
|
331
331
|
}
|
|
332
332
|
};
|
|
333
|
-
function
|
|
333
|
+
function D(e) {
|
|
334
334
|
const t = e.message.toLowerCase();
|
|
335
335
|
return t.includes("load failed") || t.includes("failed to fetch") || t.includes("network") || t.includes("abort");
|
|
336
336
|
}
|
|
337
|
-
var
|
|
337
|
+
var x = /* @__PURE__ */ new Set([
|
|
338
|
+
"image/jpeg",
|
|
339
|
+
"image/png",
|
|
340
|
+
"image/gif",
|
|
341
|
+
"image/webp",
|
|
342
|
+
"image/bmp",
|
|
343
|
+
"image/tiff"
|
|
344
|
+
]);
|
|
345
|
+
function I(e) {
|
|
346
|
+
if (!e) return;
|
|
347
|
+
const t = typeof window < "u" && window.location ? window.location.href : "https://ago.local/";
|
|
348
|
+
try {
|
|
349
|
+
const s = new URL(e, t);
|
|
350
|
+
if (s.protocol === "http:" || s.protocol === "https:" || s.protocol === "blob:") return e;
|
|
351
|
+
} catch {
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function N(e) {
|
|
355
|
+
return e.isSafeImage === !0 && typeof e.contentType == "string" && e.contentType.startsWith("image/") && I(e.url) !== void 0;
|
|
356
|
+
}
|
|
357
|
+
function O(e) {
|
|
358
|
+
if (e == null || e < 0) return "";
|
|
359
|
+
if (e < 1024) return `${e} B`;
|
|
360
|
+
const t = e / 1024;
|
|
361
|
+
return t < 1024 ? `${t.toFixed(1)} KB` : `${(t / 1024).toFixed(1)} MB`;
|
|
362
|
+
}
|
|
363
|
+
function U(e) {
|
|
364
|
+
return {
|
|
365
|
+
id: String(e.id ?? ""),
|
|
366
|
+
name: typeof e.name == "string" && e.name ? e.name : "file",
|
|
367
|
+
contentType: typeof e.content_type == "string" ? e.content_type : void 0,
|
|
368
|
+
fileSize: typeof e.file_size == "number" ? e.file_size : void 0,
|
|
369
|
+
url: typeof e.file_url == "string" ? e.file_url : void 0,
|
|
370
|
+
isSafeImage: e.is_safe_image === !0
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
function P(e) {
|
|
374
|
+
return e.map((t, s) => ({
|
|
375
|
+
id: `local-${s}-${t.name}`,
|
|
376
|
+
name: t.name,
|
|
377
|
+
contentType: t.type || void 0,
|
|
378
|
+
fileSize: t.size,
|
|
379
|
+
url: typeof URL < "u" && URL.createObjectURL ? URL.createObjectURL(t) : void 0,
|
|
380
|
+
isSafeImage: x.has(t.type)
|
|
381
|
+
}));
|
|
382
|
+
}
|
|
383
|
+
var F = class {
|
|
338
384
|
constructor() {
|
|
339
385
|
this.handlers = /* @__PURE__ */ new Map();
|
|
340
386
|
}
|
|
@@ -347,93 +393,93 @@ var R = class {
|
|
|
347
393
|
}
|
|
348
394
|
emit(e, t) {
|
|
349
395
|
const s = this.handlers.get(e);
|
|
350
|
-
s && s.forEach((
|
|
396
|
+
s && s.forEach((i) => {
|
|
351
397
|
try {
|
|
352
|
-
|
|
353
|
-
} catch (
|
|
354
|
-
console.error(`Error in event handler for ${String(e)}:`,
|
|
398
|
+
i(t);
|
|
399
|
+
} catch (n) {
|
|
400
|
+
console.error(`Error in event handler for ${String(e)}:`, n);
|
|
355
401
|
}
|
|
356
402
|
});
|
|
357
403
|
}
|
|
358
404
|
once(e, t) {
|
|
359
|
-
const s = ((
|
|
360
|
-
this.off(e, s), t(
|
|
405
|
+
const s = ((i) => {
|
|
406
|
+
this.off(e, s), t(i);
|
|
361
407
|
});
|
|
362
408
|
this.on(e, s);
|
|
363
409
|
}
|
|
364
410
|
waitFor(e, t) {
|
|
365
|
-
return new Promise((s,
|
|
366
|
-
let
|
|
411
|
+
return new Promise((s, i) => {
|
|
412
|
+
let n;
|
|
367
413
|
const r = ((a) => {
|
|
368
|
-
|
|
414
|
+
n && clearTimeout(n), s(a);
|
|
369
415
|
});
|
|
370
|
-
this.once(e, r), t?.timeout && (
|
|
371
|
-
this.off(e, r),
|
|
416
|
+
this.once(e, r), t?.timeout && (n = setTimeout(() => {
|
|
417
|
+
this.off(e, r), i(/* @__PURE__ */ new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`));
|
|
372
418
|
}, t.timeout));
|
|
373
419
|
});
|
|
374
420
|
}
|
|
375
421
|
removeAllListeners(e) {
|
|
376
422
|
e ? this.handlers.delete(e) : this.handlers.clear();
|
|
377
423
|
}
|
|
378
|
-
}, y = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).',
|
|
424
|
+
}, y = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).', T = /^[a-z][a-z0-9+.-]*:\/\//i, w = !1;
|
|
379
425
|
function v(e, t = "AgoClient") {
|
|
380
426
|
if (typeof e != "object" || e === null) throw new h(`${t}: ${y}`, "config_missing_base_url");
|
|
381
427
|
const s = e.baseUrl;
|
|
382
428
|
if (typeof s != "string" || s.trim() === "") throw new h(`${t}: ${y}`, "config_missing_base_url");
|
|
383
|
-
!s.startsWith("/") && !
|
|
429
|
+
!s.startsWith("/") && !T.test(s) && (w || (w = !0, console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)));
|
|
384
430
|
}
|
|
385
|
-
var
|
|
431
|
+
var j = class b {
|
|
386
432
|
constructor(t) {
|
|
387
|
-
this.warnedEmptyConversations = /* @__PURE__ */ new Set(), v(t, "AgoClient"), this.config = t, this.httpClient = new k(t), this.functionRegistry = new $(), this.contextRegistry = new A(), this.eventEmitter = new
|
|
433
|
+
this.warnedEmptyConversations = /* @__PURE__ */ new Set(), v(t, "AgoClient"), this.config = t, this.httpClient = new k(t), this.functionRegistry = new $(), this.contextRegistry = new A(), this.eventEmitter = new F(), t.debug && o.enable(), o.log("AgoClient initialized");
|
|
388
434
|
}
|
|
389
435
|
async sendMessage(t, s) {
|
|
390
|
-
const
|
|
436
|
+
const i = this.functionRegistry.getSchemas(), n = this.contextRegistry.getSnapshot(), r = this.config.agent || this.config.defaultAgentId, a = {
|
|
391
437
|
content: t,
|
|
392
438
|
conversation_id: s?.conversationId,
|
|
393
439
|
agent_id: s?.agentId || r
|
|
394
440
|
};
|
|
395
|
-
|
|
441
|
+
i.length > 0 && (a.client_functions = i), n && (a.client_context = n);
|
|
396
442
|
let l;
|
|
397
443
|
if (s?.files && s.files.length > 0) {
|
|
398
444
|
const c = new FormData();
|
|
399
|
-
c.append("content", t), s.conversationId && c.append("conversation_id", s.conversationId), (s.agentId || r) && c.append("agent_id", s.agentId || r || ""),
|
|
400
|
-
for (const
|
|
445
|
+
c.append("content", t), s.conversationId && c.append("conversation_id", s.conversationId), (s.agentId || r) && c.append("agent_id", s.agentId || r || ""), i.length > 0 && c.append("client_functions", JSON.stringify(i)), n && c.append("client_context", JSON.stringify(n));
|
|
446
|
+
for (const _ of s.files) c.append("files", _);
|
|
401
447
|
l = await this.httpClient.postFormData("/api/sdk/v1/messages", c);
|
|
402
448
|
} else l = await this.httpClient.postStream("/api/sdk/v1/messages", a);
|
|
403
449
|
return this.processSSEResponse(l);
|
|
404
450
|
}
|
|
405
451
|
async processSSEResponse(t) {
|
|
406
452
|
let s = !1;
|
|
407
|
-
const
|
|
408
|
-
onRawChunk: (
|
|
409
|
-
this.eventEmitter.emit("stream:message",
|
|
453
|
+
const i = await new R({
|
|
454
|
+
onRawChunk: (n) => {
|
|
455
|
+
this.eventEmitter.emit("stream:message", n);
|
|
410
456
|
},
|
|
411
|
-
onStart: (
|
|
412
|
-
this.eventEmitter.emit("message:start",
|
|
457
|
+
onStart: (n) => {
|
|
458
|
+
this.eventEmitter.emit("message:start", n);
|
|
413
459
|
},
|
|
414
|
-
onChunk: (
|
|
415
|
-
this.eventEmitter.emit("message:chunk",
|
|
460
|
+
onChunk: (n) => {
|
|
461
|
+
this.eventEmitter.emit("message:chunk", n);
|
|
416
462
|
},
|
|
417
|
-
onToolCall: (
|
|
418
|
-
this.eventEmitter.emit("toolCall:received",
|
|
463
|
+
onToolCall: (n) => {
|
|
464
|
+
this.eventEmitter.emit("toolCall:received", n), n.type === "form" && this.eventEmitter.emit("toolCall:form", n);
|
|
419
465
|
},
|
|
420
|
-
onClientFunction: async (
|
|
421
|
-
s = !0, this.eventEmitter.emit("function:invoke",
|
|
466
|
+
onClientFunction: async (n) => {
|
|
467
|
+
s = !0, this.eventEmitter.emit("function:invoke", n), await this.handleClientFunctionInvocation(n);
|
|
422
468
|
},
|
|
423
|
-
onAnswerComplete: (
|
|
424
|
-
this.eventEmitter.emit("message:answer-complete",
|
|
469
|
+
onAnswerComplete: (n) => {
|
|
470
|
+
this.eventEmitter.emit("message:answer-complete", n);
|
|
425
471
|
},
|
|
426
|
-
onComplete: (
|
|
427
|
-
this.eventEmitter.emit("message:complete",
|
|
472
|
+
onComplete: (n) => {
|
|
473
|
+
this.eventEmitter.emit("message:complete", n);
|
|
428
474
|
},
|
|
429
|
-
onError: (
|
|
475
|
+
onError: (n) => {
|
|
430
476
|
this.eventEmitter.emit("message:error", {
|
|
431
|
-
error:
|
|
432
|
-
code:
|
|
477
|
+
error: n.message,
|
|
478
|
+
code: n instanceof h ? n.code : void 0
|
|
433
479
|
});
|
|
434
480
|
}
|
|
435
481
|
}).processStream(t);
|
|
436
|
-
return this.maybeFlagEmptyReply(
|
|
482
|
+
return this.maybeFlagEmptyReply(i, s), i;
|
|
437
483
|
}
|
|
438
484
|
maybeFlagEmptyReply(t, s) {
|
|
439
485
|
t.status === "DONE" && (t.content ?? "").trim() === "" && !s && !(t.toolCalls && t.toolCalls.length > 0) && !(t.followUpReplies && t.followUpReplies.length > 0) && setTimeout(() => {
|
|
@@ -441,33 +487,33 @@ var F = class b {
|
|
|
441
487
|
conversationId: t.conversationId ?? "",
|
|
442
488
|
messageId: t.id ?? ""
|
|
443
489
|
}), this.config.warnOnEmptyReply === !1) return;
|
|
444
|
-
const
|
|
445
|
-
if (this.warnedEmptyConversations.has(
|
|
446
|
-
this.warnedEmptyConversations.add(
|
|
447
|
-
const
|
|
448
|
-
t.id ? console.warn("[AGO] Reply completed with empty content. Possible causes: " + (
|
|
490
|
+
const i = t.conversationId || "(no conversation)";
|
|
491
|
+
if (this.warnedEmptyConversations.has(i)) return;
|
|
492
|
+
this.warnedEmptyConversations.add(i);
|
|
493
|
+
const n = this.config.agent || this.config.defaultAgentId;
|
|
494
|
+
t.id ? console.warn("[AGO] Reply completed with empty content. Possible causes: " + (n ? `the agent "${n}" may not exist for this tenant, ` : "an unknown `agent` slug, ") + "or the agent replied with no text. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.") : console.warn("[AGO] The stream completed without any message data. Possible causes: " + (n ? `the agent "${n}" may not exist for this tenant, or ` : "") + "`baseUrl` does not point at an AGO endpoint that returns server-sent events. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.");
|
|
449
495
|
}, 0);
|
|
450
496
|
}
|
|
451
497
|
async handleClientFunctionInvocation(t) {
|
|
452
|
-
let s,
|
|
498
|
+
let s, i;
|
|
453
499
|
try {
|
|
454
500
|
s = await this.functionRegistry.execute(t.functionName, t.arguments);
|
|
455
|
-
} catch (
|
|
456
|
-
|
|
501
|
+
} catch (n) {
|
|
502
|
+
i = n instanceof Error ? n.message : "Unknown error", o.error("Client function execution failed:", n);
|
|
457
503
|
}
|
|
458
504
|
if (t.invocationId) try {
|
|
459
505
|
await this.submitToolCallForm(t.invocationId, {
|
|
460
506
|
result: s,
|
|
461
|
-
error:
|
|
507
|
+
error: i,
|
|
462
508
|
_type: "client_function_result"
|
|
463
509
|
});
|
|
464
|
-
} catch (
|
|
465
|
-
o.error("Failed to submit function result:",
|
|
510
|
+
} catch (n) {
|
|
511
|
+
o.error("Failed to submit function result:", n);
|
|
466
512
|
}
|
|
467
513
|
this.eventEmitter.emit("function:result", {
|
|
468
514
|
invocationId: t.invocationId,
|
|
469
515
|
result: s,
|
|
470
|
-
error:
|
|
516
|
+
error: i
|
|
471
517
|
});
|
|
472
518
|
}
|
|
473
519
|
async getConversations() {
|
|
@@ -478,21 +524,22 @@ var F = class b {
|
|
|
478
524
|
}));
|
|
479
525
|
}
|
|
480
526
|
async getConversation(t) {
|
|
481
|
-
const s = await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),
|
|
527
|
+
const s = await this.httpClient.get(`/api/sdk/v1/conversations/${t}`), i = {
|
|
482
528
|
id: s.id,
|
|
483
529
|
title: s.title,
|
|
484
530
|
lastMessageDate: new Date(s.last_message_date),
|
|
485
|
-
messages: s.messages.map((
|
|
486
|
-
id:
|
|
531
|
+
messages: s.messages.map((n) => ({
|
|
532
|
+
id: n.id,
|
|
487
533
|
conversationId: s.id,
|
|
488
|
-
content:
|
|
489
|
-
role:
|
|
490
|
-
status:
|
|
491
|
-
createdAt: new Date(
|
|
492
|
-
toolCalls: b.mapPersistedToolCalls(
|
|
534
|
+
content: n.content,
|
|
535
|
+
role: n.role,
|
|
536
|
+
status: n.status,
|
|
537
|
+
createdAt: new Date(n.created_at),
|
|
538
|
+
toolCalls: b.mapPersistedToolCalls(n.tool_call_data),
|
|
539
|
+
attachments: n.attachments && n.attachments.length > 0 ? n.attachments.map(U) : void 0
|
|
493
540
|
}))
|
|
494
541
|
};
|
|
495
|
-
return this.eventEmitter.emit("conversation:loaded",
|
|
542
|
+
return this.eventEmitter.emit("conversation:loaded", i), i;
|
|
496
543
|
}
|
|
497
544
|
static mapPersistedToolCalls(t) {
|
|
498
545
|
if (!(!t || t.length === 0))
|
|
@@ -539,8 +586,8 @@ var F = class b {
|
|
|
539
586
|
async submitFeedback(t, s) {
|
|
540
587
|
await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`, { rating: s });
|
|
541
588
|
}
|
|
542
|
-
registerFunction(t, s,
|
|
543
|
-
typeof t == "object" ? this.functionRegistry.register(t) : this.functionRegistry.register(t, s,
|
|
589
|
+
registerFunction(t, s, i) {
|
|
590
|
+
typeof t == "object" ? this.functionRegistry.register(t) : this.functionRegistry.register(t, s, i);
|
|
544
591
|
}
|
|
545
592
|
register(t) {
|
|
546
593
|
if (Array.isArray(t)) for (const s of t) this.functionRegistry.register(s);
|
|
@@ -553,7 +600,7 @@ var F = class b {
|
|
|
553
600
|
return this.functionRegistry.getSchemas();
|
|
554
601
|
}
|
|
555
602
|
registerNavigationFunction(t, s) {
|
|
556
|
-
const
|
|
603
|
+
const i = s.map((r) => r.name), n = s.map((r) => `- "${r.name}": ${r.description}`).join(`
|
|
557
604
|
`);
|
|
558
605
|
this.registerFunction("navigateToPage", async (r) => {
|
|
559
606
|
const a = r.page, l = s.find((c) => c.name === a);
|
|
@@ -566,13 +613,13 @@ var F = class b {
|
|
|
566
613
|
};
|
|
567
614
|
}, {
|
|
568
615
|
description: `Navigate the user to a page in the application. Available pages:
|
|
569
|
-
${
|
|
616
|
+
${n}`,
|
|
570
617
|
parameters: {
|
|
571
618
|
type: "object",
|
|
572
619
|
properties: { page: {
|
|
573
620
|
type: "string",
|
|
574
621
|
description: "The page to navigate to",
|
|
575
|
-
enum:
|
|
622
|
+
enum: i
|
|
576
623
|
} },
|
|
577
624
|
required: ["page"]
|
|
578
625
|
}
|
|
@@ -628,29 +675,33 @@ ${i}`,
|
|
|
628
675
|
}
|
|
629
676
|
updateConfig(t) {
|
|
630
677
|
const s = {};
|
|
631
|
-
for (const [
|
|
632
|
-
const
|
|
678
|
+
for (const [n, r] of Object.entries(t)) r !== void 0 && (s[n] = r);
|
|
679
|
+
const i = {
|
|
633
680
|
...this.config,
|
|
634
681
|
...s
|
|
635
682
|
};
|
|
636
|
-
v(
|
|
683
|
+
v(i, "AgoClient.updateConfig"), this.config = i, this.httpClient.updateConfig(s), s.debug !== void 0 && (s.debug ? o.enable() : o.disable());
|
|
637
684
|
}
|
|
638
685
|
destroy() {
|
|
639
686
|
this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), o.log("AgoClient destroyed");
|
|
640
687
|
}
|
|
641
688
|
};
|
|
642
689
|
export {
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
690
|
+
g as _,
|
|
691
|
+
N as a,
|
|
692
|
+
R as c,
|
|
693
|
+
$ as d,
|
|
694
|
+
o as f,
|
|
695
|
+
u as g,
|
|
696
|
+
f as h,
|
|
697
|
+
P as i,
|
|
698
|
+
D as l,
|
|
699
|
+
h as m,
|
|
649
700
|
v as n,
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
701
|
+
O as o,
|
|
702
|
+
d as p,
|
|
703
|
+
F as r,
|
|
704
|
+
I as s,
|
|
705
|
+
j as t,
|
|
706
|
+
A as u
|
|
656
707
|
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
var h=class extends Error{constructor(e,t,n){super(e),this.code=t,this.statusCode=n,this.name="AgoError"}},u=class b extends h{constructor(t,n,r,s,i,a){super(t,n,r),this.type=s,this.param=i,this.docUrl=a,this.name="AgoApiError"}static fromResponse(t,n){const r=t.error;return new b(r.doc_url?`${r.message} See ${r.doc_url}`:r.message,r.code,n,r.type,r.param,r.doc_url)}},d=class extends h{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},m=class extends h{constructor(e,t="stream_error"){super(e,t),this.name="AgoStreamError"}},f=class extends h{constructor(e,t,n){super(e,"function_error"),this.functionName=t,this.originalError=n,this.name="AgoFunctionError"}},R=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)}},o=new R,y="ago_widget_id";function I(){if(typeof localStorage<"u"){const t=localStorage.getItem(y);if(t)return t}const e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`;if(typeof localStorage<"u")try{localStorage.setItem(y,e)}catch{}return e}var x=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||I()},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-User-Anon-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 n=`${this.baseUrl}${e}`;o.debug("POST (stream)",n,t);try{const r=await fetch(n,{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 u?r:new d(`Network error: ${r instanceof Error?r.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,r instanceof Error?r:void 0)}}async postFormData(e,t){const n=`${this.baseUrl}${e}`;o.debug("POST (formData)",n);const r={...this.headers};try{const s=await fetch(n,{method:"POST",headers:r,body:t});return s.ok||await this.handleErrorResponse(s),s}catch(s){throw s instanceof u?s:new d(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async request(e,t,n){const r=`${this.baseUrl}${t}`;o.debug(e,r,n);try{const s=await fetch(r,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0});return s.ok||await this.handleErrorResponse(s),s.status===204?void 0:s.json()}catch(s){throw s instanceof u?s:new d(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw u.fromResponse(t,e.status);let n="";throw e.status===401||e.status===403?n=" Check `userJwt` (and that it has not expired).":e.status===404&&(n=" Check that `baseUrl` points at your AGO API root."),new u(`HTTP ${e.status}: ${e.statusText}.${n}`,"http_error",e.status,"api_error")}},C=class{constructor(){this.functions=new Map}register(e,t,n){if(typeof e=="object"){const{name:s,handler:i,description:a,parameters:c}=e;return this.register(s,i,{description:a,parameters:c})}const r=e;if(!t||!n)throw new h(`registerFunction("${r}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`,"function_invalid_registration");this.functions.has(r)&&o.warn(`Function "${r}" is being overwritten`),this.functions.set(r,{schema:{...n,name:r},handler:t}),o.log(`Registered function: ${r}`)}unregister(e){const t=this.functions.delete(e);return t&&o.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 n=this.functions.get(e);if(!n)throw new f(`Function "${e}" is not registered`,e);o.log(`Executing function: ${e}`,t);try{const r=await n.handler(t);return o.log(`Function ${e} completed:`,r),r}catch(r){throw o.error(`Function ${e} failed:`,r),new f(`Function "${e}" execution failed: ${r instanceof Error?r.message:"Unknown error"}`,e,r instanceof Error?r:void 0)}}clear(){this.functions.clear(),o.log("Cleared all registered functions")}get size(){return this.functions.size}},E=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),o.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&o.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),o.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&o.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,n]of this.entries)e[t]=n;for(const[t,n]of this.dynamicProviders)try{const r=n();r&&(e[t]=r)}catch(r){o.error(`DynamicContext provider "${t}" threw:`,r)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),o.log("ClientContext cleared")}};function g(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(g).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${g(e[t])}`).join(",")}}`}var _=class{constructor(e){this.callbacks=e,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.firedClientFunctions=new Set}async processStream(e){if(!e.body)throw new m("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.","stream_no_body");const t=e.body.getReader(),n=new TextDecoder;try{for(;;){const{done:r,value:s}=await t.read();if(r)break;const i=n.decode(s,{stream:!0});this.buffer+=i,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(r){const s=r instanceof Error?r:new m("Stream processing failed mid-flight. The connection may have dropped; retry the message.");throw this.callbacks.onError?.(s),s}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 n=t.split(`
|
|
4
|
+
`);for(const r of n)if(!r.startsWith(": ")&&r.startsWith("data: ")){const s=r.slice(6);try{const i=JSON.parse(s);this.handleChunk(i)}catch(i){o.warn("Failed to parse SSE data:",s,i)}}}}handleChunk(e){if(this.callbacks.onRawChunk?.(e),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 n=t.knowledge_document;return{id:n.id,title:n.title,url:n.use_external_link?n.external_link_url:n.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${g(e.arguments??{})}`;this.firedClientFunctions.has(t)||(this.firedClientFunctions.add(t),this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}))}if(e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const n=this.toolCalls.findIndex(r=>r.id===t.id);n>=0?this.toolCalls[n]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies),this.message.status==="DONE"&&!this.answerCompleteEmitted&&this.message.id&&(this.answerCompleteEmitted=!0,this.callbacks.onAnswerComplete?.(this.buildMessage()))}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}}buildMessage(){return{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}}buildFinalMessage(){const e=this.buildMessage();return this.callbacks.onComplete?.(e),e}};function F(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var U=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function S(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const n=new URL(e,t);if(n.protocol==="http:"||n.protocol==="https:"||n.protocol==="blob:")return e}catch{}}function O(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&S(e.url)!==void 0}function P(e){if(e==null||e<0)return"";if(e<1024)return`${e} B`;const t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function j(e){return{id:String(e.id??""),name:typeof e.name=="string"&&e.name?e.name:"file",contentType:typeof e.content_type=="string"?e.content_type:void 0,fileSize:typeof e.file_size=="number"?e.file_size:void 0,url:typeof e.file_url=="string"?e.file_url:void 0,isSafeImage:e.is_safe_image===!0}}function T(e){return e.map((t,n)=>({id:`local-${n}-${t.name}`,name:t.name,contentType:t.type||void 0,fileSize:t.size,url:typeof URL<"u"&&URL.createObjectURL?URL.createObjectURL(t):void 0,isSafeImage:U.has(t.type)}))}var A=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 n=this.handlers.get(e);n&&n.delete(t)}emit(e,t){const n=this.handlers.get(e);n&&n.forEach(r=>{try{r(t)}catch(s){console.error(`Error in event handler for ${String(e)}:`,s)}})}once(e,t){const n=(r=>{this.off(e,n),t(r)});this.on(e,n)}waitFor(e,t){return new Promise((n,r)=>{let s;const i=(a=>{s&&clearTimeout(s),n(a)});this.once(e,i),t?.timeout&&(s=setTimeout(()=>{this.off(e,i),r(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},w='`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).',D=/^[a-z][a-z0-9+.-]*:\/\//i,v=!1;function p(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new h(`${t}: ${w}`,"config_missing_base_url");const n=e.baseUrl;if(typeof n!="string"||n.trim()==="")throw new h(`${t}: ${w}`,"config_missing_base_url");!n.startsWith("/")&&!D.test(n)&&(v||(v=!0,console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)))}var N=class k{constructor(t){this.warnedEmptyConversations=new Set,p(t,"AgoClient"),this.config=t,this.httpClient=new x(t),this.functionRegistry=new C,this.contextRegistry=new E,this.eventEmitter=new A,t.debug&&o.enable(),o.log("AgoClient initialized")}async sendMessage(t,n){const r=this.functionRegistry.getSchemas(),s=this.contextRegistry.getSnapshot(),i=this.config.agent||this.config.defaultAgentId,a={content:t,conversation_id:n?.conversationId,agent_id:n?.agentId||i};r.length>0&&(a.client_functions=r),s&&(a.client_context=s);let c;if(n?.files&&n.files.length>0){const l=new FormData;l.append("content",t),n.conversationId&&l.append("conversation_id",n.conversationId),(n.agentId||i)&&l.append("agent_id",n.agentId||i||""),r.length>0&&l.append("client_functions",JSON.stringify(r)),s&&l.append("client_context",JSON.stringify(s));for(const $ of n.files)l.append("files",$);c=await this.httpClient.postFormData("/api/sdk/v1/messages",l)}else c=await this.httpClient.postStream("/api/sdk/v1/messages",a);return this.processSSEResponse(c)}async processSSEResponse(t){let n=!1;const r=await new _({onRawChunk:s=>{this.eventEmitter.emit("stream:message",s)},onStart:s=>{this.eventEmitter.emit("message:start",s)},onChunk:s=>{this.eventEmitter.emit("message:chunk",s)},onToolCall:s=>{this.eventEmitter.emit("toolCall:received",s),s.type==="form"&&this.eventEmitter.emit("toolCall:form",s)},onClientFunction:async s=>{n=!0,this.eventEmitter.emit("function:invoke",s),await this.handleClientFunctionInvocation(s)},onAnswerComplete:s=>{this.eventEmitter.emit("message:answer-complete",s)},onComplete:s=>{this.eventEmitter.emit("message:complete",s)},onError:s=>{this.eventEmitter.emit("message:error",{error:s.message,code:s instanceof h?s.code:void 0})}}).processStream(t);return this.maybeFlagEmptyReply(r,n),r}maybeFlagEmptyReply(t,n){t.status==="DONE"&&(t.content??"").trim()===""&&!n&&!(t.toolCalls&&t.toolCalls.length>0)&&!(t.followUpReplies&&t.followUpReplies.length>0)&&setTimeout(()=>{if(this.eventEmitter.emit("message:empty",{conversationId:t.conversationId??"",messageId:t.id??""}),this.config.warnOnEmptyReply===!1)return;const r=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(r))return;this.warnedEmptyConversations.add(r);const s=this.config.agent||this.config.defaultAgentId;t.id?console.warn("[AGO] Reply completed with empty content. Possible causes: "+(s?`the agent "${s}" may not exist for this tenant, `:"an unknown `agent` slug, ")+"or the agent replied with no text. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`."):console.warn("[AGO] The stream completed without any message data. Possible causes: "+(s?`the agent "${s}" may not exist for this tenant, or `:"")+"`baseUrl` does not point at an AGO endpoint that returns server-sent events. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.")},0)}async handleClientFunctionInvocation(t){let n,r;try{n=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(s){r=s instanceof Error?s.message:"Unknown error",o.error("Client function execution failed:",s)}if(t.invocationId)try{await this.submitToolCallForm(t.invocationId,{result:n,error:r,_type:"client_function_result"})}catch(s){o.error("Failed to submit function result:",s)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:n,error:r})}async getConversations(){return(await this.httpClient.get("/api/sdk/v1/conversations")).items.map(t=>({id:t.id,title:t.title,lastMessageDate:new Date(t.last_message_date)}))}async getConversation(t){const n=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),r={id:n.id,title:n.title,lastMessageDate:new Date(n.last_message_date),messages:n.messages.map(s=>({id:s.id,conversationId:n.id,content:s.content,role:s.role,status:s.status,createdAt:new Date(s.created_at),toolCalls:k.mapPersistedToolCalls(s.tool_call_data),attachments:s.attachments&&s.attachments.length>0?s.attachments.map(j):void 0}))};return this.eventEmitter.emit("conversation:loaded",r),r}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(n=>({id:String(n.id??""),type:n.type??"status_message",status:String(n.status??"unknown"),toolName:n.tool_name??"",toolDisplayName:n.tool_display_name,message:n.message,formSchema:n.form_schema,data:n.data,functionName:n.function_name,arguments:n.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async submitToolCallForm(t,n){await this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:n})}async confirmToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/confirm/`)}async rejectToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/reject/`)}async getFormCollector(t){const n=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:n.name,description:n.description,schema:n.schema,submit:n.submit??void 0}}async submitFormCollector(t,n){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:n})}async submitFeedback(t,n){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:n})}registerFunction(t,n,r){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,n,r)}register(t){if(Array.isArray(t))for(const n of t)this.functionRegistry.register(n);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}registerNavigationFunction(t,n){const r=n.map(i=>i.name),s=n.map(i=>`- "${i.name}": ${i.description}`).join(`
|
|
5
|
+
`);this.registerFunction("navigateToPage",async i=>{const a=i.page,c=n.find(l=>l.name===a);return c?(t(c.path),{success:!0,navigatedTo:c.path}):{success:!1,error:`Unknown page: ${a}`}},{description:`Navigate the user to a page in the application. Available pages:
|
|
6
|
+
${s}`,parameters:{type:"object",properties:{page:{type:"string",description:"The page to navigate to",enum:r}},required:["page"]}})}setContext(t,n){this.contextRegistry.set(t,n),this.notifyContextChanged()}removeContext(t){const n=this.contextRegistry.remove(t);return n&&this.notifyContextChanged(),n}addDynamicContext(t,n){this.contextRegistry.addDynamicProvider(t,n),this.notifyContextChanged()}removeDynamicContext(t){const n=this.contextRegistry.removeDynamicProvider(t);return n&&this.notifyContextChanged(),n}notifyContextChanged(){this.eventEmitter.emit("context:changed",this.contextRegistry.getSnapshot())}emitFormEvent(t,n){this.eventEmitter.emit(t,n)}enableAutoPageContext(){this.addDynamicContext("browser-page",()=>{const t=typeof window<"u"?window.location.href:void 0,n=typeof document<"u"?document.title:void 0;return!t&&!n?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:t,title:n}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}on(t,n){this.eventEmitter.on(t,n)}off(t,n){this.eventEmitter.off(t,n)}once(t,n){this.eventEmitter.once(t,n)}waitFor(t,n){return this.eventEmitter.waitFor(t,n)}updateConfig(t){const n={};for(const[s,i]of Object.entries(t))i!==void 0&&(n[s]=i);const r={...this.config,...n};p(r,"AgoClient.updateConfig"),this.config=r,this.httpClient.updateConfig(n),n.debug!==void 0&&(n.debug?o.enable():o.disable())}destroy(){this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.contextRegistry.clear(),o.log("AgoClient destroyed")}};Object.defineProperty(exports,"AgoApiError",{enumerable:!0,get:function(){return u}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return N}});Object.defineProperty(exports,"AgoError",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"AgoFunctionError",{enumerable:!0,get:function(){return f}});Object.defineProperty(exports,"AgoNetworkError",{enumerable:!0,get:function(){return d}});Object.defineProperty(exports,"AgoStreamError",{enumerable:!0,get:function(){return m}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return E}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return A}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return C}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return _}});Object.defineProperty(exports,"attachmentsFromFiles",{enumerable:!0,get:function(){return T}});Object.defineProperty(exports,"canInlineImage",{enumerable:!0,get:function(){return O}});Object.defineProperty(exports,"formatFileSize",{enumerable:!0,get:function(){return P}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return F}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return o}});Object.defineProperty(exports,"safeAttachmentUrl",{enumerable:!0,get:function(){return S}});Object.defineProperty(exports,"validateConfig",{enumerable:!0,get:function(){return p}});
|
package/dist/angular.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-CzSmJQxl.cjs");var n=class{constructor(e){this.client=new o.AgoClient(e),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(e){const t=this.client;return{subscribe(i){const s=r=>{i.next?.(r)};return t.on(e,s),{unsubscribe:()=>t.off(e,s)}}}}sendMessage(e,t){return this.client.sendMessage(e,t)}getConversations(){return this.client.getConversations()}getConversation(e){return this.client.getConversation(e)}getMessages(e){return this.client.getMessages(e)}submitToolCallForm(e,t){return this.client.submitToolCallForm(e,t)}confirmToolCall(e){return this.client.confirmToolCall(e)}rejectToolCall(e){return this.client.rejectToolCall(e)}submitFeedback(e,t){return this.client.submitFeedback(e,t)}registerFunction(e,t,i){typeof e=="object"?this.client.registerFunction(e):this.client.registerFunction(e,t,i)}unregisterFunction(e){return this.client.unregisterFunction(e)}registerNavigationFunction(e,t){this.client.registerNavigationFunction(e,t)}on(e,t){this.client.on(e,t)}off(e,t){this.client.off(e,t)}updateConfig(e){this.client.updateConfig(e)}getClient(){return this.client}destroy(){this.client.destroy()}};function c(e){return{provide:n,useValue:new n(e)}}exports.AgoService=n;exports.provideAgo=c;
|