@useago/sdk 1.9.0 → 1.13.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/CHANGELOG.md +173 -2
- package/README.md +126 -0
- package/dist/angular.cjs +1 -1
- package/dist/angular.d.cts +408 -26
- package/dist/angular.d.ts +408 -26
- package/dist/angular.js +4 -1
- package/dist/{createConversationSession-BaaXBQ5b.js → createConversationSession-BfJg0WyA.js} +1 -1
- package/dist/{createConversationSession-CU0b-t1W.cjs → createConversationSession-CiOXKWl0.cjs} +1 -1
- package/dist/{createFormCollector-Cf7kGhCB.js → createFormCollector-DN1xjAv5.js} +1 -1
- package/dist/{createFormCollector-DfN1xZBy.cjs → createFormCollector-DnQl77Ko.cjs} +1 -1
- package/dist/createMockClient-BPt1gSve.cjs +1 -0
- package/dist/{createMockClient-5YF-ZbVu.js → createMockClient-YoYr3pQr.js} +16 -3
- package/dist/devtools.cjs +4 -4
- package/dist/devtools.d.cts +406 -26
- package/dist/devtools.d.ts +406 -26
- package/dist/devtools.js +87 -84
- package/dist/helpers.d.cts +42 -12
- package/dist/helpers.d.ts +42 -12
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +486 -35
- package/dist/index.d.ts +486 -35
- package/dist/index.js +117 -112
- package/dist/react.cjs +4 -4
- package/dist/react.d.cts +458 -26
- package/dist/react.d.ts +458 -26
- package/dist/react.js +816 -727
- package/dist/speechToText-BV7qxqPF.js +704 -0
- package/dist/speechToText-ZciRyyJE.cjs +1 -0
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +406 -26
- package/dist/testing.d.ts +406 -26
- package/dist/testing.js +1 -1
- package/dist/types-Q7t1peH-.js +2584 -0
- package/dist/types-a7teDBnC.cjs +10 -0
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +608 -26
- package/dist/vue.d.ts +608 -26
- package/dist/vue.js +103 -101
- package/dist/widget.cjs +6 -4
- package/dist/widget.d.cts +710 -28
- package/dist/widget.d.ts +710 -28
- package/dist/widget.js +3911 -976
- package/llms-full.txt +254 -7
- package/package.json +1 -1
- package/dist/createMockClient-BZbOe-23.cjs +0 -1
- package/dist/sheetController-CBUVOroo.js +0 -205
- package/dist/sheetController-DY-sC13T.cjs +0 -1
- package/dist/types-CPga11Of.js +0 -2068
- package/dist/types-D3YQl1jx.cjs +0 -9
|
@@ -0,0 +1,2584 @@
|
|
|
1
|
+
import { a as K, i as T, n as C, r as H, t as _ } from "./errors-BLfjXnLB.js";
|
|
2
|
+
var Gt = 10, X = 1e3;
|
|
3
|
+
function Ee(e) {
|
|
4
|
+
if (typeof e != "object" || e === null) return !1;
|
|
5
|
+
const t = Object.getPrototypeOf(e);
|
|
6
|
+
return t === Object.prototype || t === null;
|
|
7
|
+
}
|
|
8
|
+
function D(e, t) {
|
|
9
|
+
if (typeof e == "string") {
|
|
10
|
+
if (e.length <= 1e3) return e;
|
|
11
|
+
const s = e.length - X;
|
|
12
|
+
return e.slice(0, X) + `…[truncated ${s} chars]`;
|
|
13
|
+
}
|
|
14
|
+
if (Array.isArray(e)) {
|
|
15
|
+
if (t.has(e)) return "…[circular]";
|
|
16
|
+
t.add(e);
|
|
17
|
+
const s = e.slice(0, 50).map((i) => D(i, t));
|
|
18
|
+
return e.length > 50 && s.push(`…[+${e.length - 50} more]`), t.delete(e), s;
|
|
19
|
+
}
|
|
20
|
+
if (Ee(e)) {
|
|
21
|
+
if (t.has(e)) return "…[circular]";
|
|
22
|
+
t.add(e);
|
|
23
|
+
const s = {};
|
|
24
|
+
for (const [i, r] of Object.entries(e)) s[i] = D(r, t);
|
|
25
|
+
return t.delete(e), s;
|
|
26
|
+
}
|
|
27
|
+
return e;
|
|
28
|
+
}
|
|
29
|
+
function de(e) {
|
|
30
|
+
return D(e, /* @__PURE__ */ new WeakSet());
|
|
31
|
+
}
|
|
32
|
+
var be = class {
|
|
33
|
+
constructor(e = 10) {
|
|
34
|
+
this.entries = [];
|
|
35
|
+
const t = Math.floor(e);
|
|
36
|
+
this.maxEntries = Number.isFinite(t) ? Math.max(1, t) : 10;
|
|
37
|
+
}
|
|
38
|
+
add(e) {
|
|
39
|
+
const t = {
|
|
40
|
+
ts: e.ts ?? Date.now(),
|
|
41
|
+
actor: e.actor ?? "user",
|
|
42
|
+
name: e.name,
|
|
43
|
+
summary: e.summary,
|
|
44
|
+
...e.data !== void 0 ? { data: de(e.data) } : {}
|
|
45
|
+
};
|
|
46
|
+
this.entries.push(t);
|
|
47
|
+
const s = this.entries.length - this.maxEntries;
|
|
48
|
+
return s > 0 && this.entries.splice(0, s), t;
|
|
49
|
+
}
|
|
50
|
+
getRecent() {
|
|
51
|
+
return [...this.entries];
|
|
52
|
+
}
|
|
53
|
+
get size() {
|
|
54
|
+
return this.entries.length;
|
|
55
|
+
}
|
|
56
|
+
clear() {
|
|
57
|
+
this.entries = [];
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
function $(e) {
|
|
61
|
+
if (e == null) return null;
|
|
62
|
+
if (typeof e == "string") {
|
|
63
|
+
const t = e.trim().replace(/_/g, "-");
|
|
64
|
+
try {
|
|
65
|
+
const [s] = /^[a-z]{2,3}(?:-[a-z0-9]{1,8})*$/i.test(t) ? Intl.getCanonicalLocales(t) : [];
|
|
66
|
+
if (s) return s;
|
|
67
|
+
} catch {
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
throw new C('Use a language tag such as "fr", "de-DE", or "pt-BR", or null to clear it. See docs/general/configuration.md#language (config_invalid_language).', "config_invalid_language");
|
|
71
|
+
}
|
|
72
|
+
var Se = class {
|
|
73
|
+
constructor(e = !1) {
|
|
74
|
+
this.enabled = e;
|
|
75
|
+
}
|
|
76
|
+
enable() {
|
|
77
|
+
this.enabled = !0;
|
|
78
|
+
}
|
|
79
|
+
disable() {
|
|
80
|
+
this.enabled = !1;
|
|
81
|
+
}
|
|
82
|
+
log(...e) {
|
|
83
|
+
this.enabled && console.log("[AGO SDK]", ...e);
|
|
84
|
+
}
|
|
85
|
+
warn(...e) {
|
|
86
|
+
this.enabled && console.warn("[AGO SDK]", ...e);
|
|
87
|
+
}
|
|
88
|
+
error(...e) {
|
|
89
|
+
console.error("[AGO SDK]", ...e);
|
|
90
|
+
}
|
|
91
|
+
debug(...e) {
|
|
92
|
+
this.enabled && console.debug("[AGO SDK]", ...e);
|
|
93
|
+
}
|
|
94
|
+
}, l = new Se(), z = "ago_widget_id";
|
|
95
|
+
function P(e) {
|
|
96
|
+
return typeof DOMException < "u" && e instanceof DOMException && e.name === "AbortError" || e instanceof Error && e.name === "AbortError";
|
|
97
|
+
}
|
|
98
|
+
function Ce() {
|
|
99
|
+
if (typeof localStorage < "u") {
|
|
100
|
+
const t = localStorage.getItem(z);
|
|
101
|
+
if (t) return t;
|
|
102
|
+
}
|
|
103
|
+
const e = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
|
104
|
+
if (typeof localStorage < "u") try {
|
|
105
|
+
localStorage.setItem(z, e);
|
|
106
|
+
} catch {
|
|
107
|
+
}
|
|
108
|
+
return e;
|
|
109
|
+
}
|
|
110
|
+
var _e = class {
|
|
111
|
+
constructor(e) {
|
|
112
|
+
this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.headers = { "X-User-Anon-Id": e.widgetId || Ce() }, 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);
|
|
113
|
+
const t = $(e.language);
|
|
114
|
+
t && (this.headers["Accept-Language"] = t);
|
|
115
|
+
}
|
|
116
|
+
updateConfig(e) {
|
|
117
|
+
const t = $(e.language);
|
|
118
|
+
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"]), e.language !== void 0 && (t ? this.headers["Accept-Language"] = t : delete this.headers["Accept-Language"]);
|
|
119
|
+
}
|
|
120
|
+
async get(e) {
|
|
121
|
+
return this.request("GET", e);
|
|
122
|
+
}
|
|
123
|
+
async post(e, t, s) {
|
|
124
|
+
return this.request("POST", e, t, s);
|
|
125
|
+
}
|
|
126
|
+
async postStream(e, t, s) {
|
|
127
|
+
const i = `${this.baseUrl}${e}`;
|
|
128
|
+
l.debug("POST (stream)", i, t);
|
|
129
|
+
try {
|
|
130
|
+
const r = await fetch(i, {
|
|
131
|
+
method: "POST",
|
|
132
|
+
headers: {
|
|
133
|
+
...this.headers,
|
|
134
|
+
"Content-Type": "application/json"
|
|
135
|
+
},
|
|
136
|
+
body: t ? JSON.stringify(t) : void 0,
|
|
137
|
+
signal: s?.signal
|
|
138
|
+
});
|
|
139
|
+
return r.ok || await this.handleErrorResponse(r), r;
|
|
140
|
+
} catch (r) {
|
|
141
|
+
throw r instanceof _ || P(r) ? r : new T(`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);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async postFormData(e, t, s) {
|
|
145
|
+
const i = `${this.baseUrl}${e}`;
|
|
146
|
+
l.debug("POST (formData)", i);
|
|
147
|
+
const r = { ...this.headers };
|
|
148
|
+
try {
|
|
149
|
+
const n = await fetch(i, {
|
|
150
|
+
method: "POST",
|
|
151
|
+
headers: r,
|
|
152
|
+
body: t,
|
|
153
|
+
signal: s?.signal
|
|
154
|
+
});
|
|
155
|
+
return n.ok || await this.handleErrorResponse(n), n;
|
|
156
|
+
} catch (n) {
|
|
157
|
+
throw n instanceof _ || P(n) ? n : new T(`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);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async request(e, t, s, i) {
|
|
161
|
+
const r = `${this.baseUrl}${t}`;
|
|
162
|
+
l.debug(e, r, s);
|
|
163
|
+
try {
|
|
164
|
+
const n = await fetch(r, {
|
|
165
|
+
method: e,
|
|
166
|
+
headers: {
|
|
167
|
+
...this.headers,
|
|
168
|
+
"Content-Type": "application/json"
|
|
169
|
+
},
|
|
170
|
+
body: s ? JSON.stringify(s) : void 0,
|
|
171
|
+
...i?.keepalive ? { keepalive: !0 } : {}
|
|
172
|
+
});
|
|
173
|
+
return n.ok || await this.handleErrorResponse(n), n.status === 204 ? void 0 : n.json();
|
|
174
|
+
} catch (n) {
|
|
175
|
+
throw n instanceof _ ? n : new T(`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);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async handleErrorResponse(e) {
|
|
179
|
+
let t;
|
|
180
|
+
try {
|
|
181
|
+
t = await e.json();
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
if (t?.error) throw _.fromResponse(t, e.status);
|
|
185
|
+
let s = "";
|
|
186
|
+
throw e.status === 401 || e.status === 403 ? s = " Check `userJwt` (and that it has not expired)." : e.status === 404 && (s = " Check that `baseUrl` points at your AGO API root."), new _(`HTTP ${e.status}: ${e.statusText}.${s}`, "http_error", e.status, "api_error");
|
|
187
|
+
}
|
|
188
|
+
}, qt = 10, Jt = 6e5;
|
|
189
|
+
var Ae = "[AGO SDK]", ke = 300;
|
|
190
|
+
function N(e, t) {
|
|
191
|
+
return e.length <= t ? e : e.slice(0, t) + `…[truncated ${e.length - t} chars]`;
|
|
192
|
+
}
|
|
193
|
+
function Re(e) {
|
|
194
|
+
const t = e.search(/[?#]/);
|
|
195
|
+
return t === -1 ? e : e.slice(0, t);
|
|
196
|
+
}
|
|
197
|
+
function G(e) {
|
|
198
|
+
return typeof e == "object" && e !== null && typeof e.message == "string";
|
|
199
|
+
}
|
|
200
|
+
function he(e) {
|
|
201
|
+
if (typeof e == "string") return e;
|
|
202
|
+
if (G(e)) return (typeof e.name == "string" && e.name ? `${e.name}: ` : "") + e.message;
|
|
203
|
+
if (typeof e == "object" && e !== null) try {
|
|
204
|
+
return N(JSON.stringify(e), ke);
|
|
205
|
+
} catch {
|
|
206
|
+
return String(e);
|
|
207
|
+
}
|
|
208
|
+
return String(e);
|
|
209
|
+
}
|
|
210
|
+
function I(e) {
|
|
211
|
+
return G(e) ? {
|
|
212
|
+
message: (typeof e.name == "string" && e.name && e.name !== "Error" ? `${e.name}: ` : "") + e.message,
|
|
213
|
+
stack: typeof e.stack == "string" ? e.stack : void 0
|
|
214
|
+
} : { message: he(e) };
|
|
215
|
+
}
|
|
216
|
+
var Te = class {
|
|
217
|
+
constructor(e = {}) {
|
|
218
|
+
this.started = !1, this.teardowns = [], this.errors = [], this.listeners = /* @__PURE__ */ new Set(), this.capturing = !1;
|
|
219
|
+
const t = Math.floor(e.maxErrors ?? 10);
|
|
220
|
+
this.maxErrors = Number.isFinite(t) ? Math.max(1, t) : 10, this.maxAgeMs = e.maxAgeMs ?? 6e5, this.maxStackChars = e.maxStackChars ?? 2e3, this.filter = e.filter;
|
|
221
|
+
}
|
|
222
|
+
start() {
|
|
223
|
+
if (this.started || typeof window > "u") return;
|
|
224
|
+
this.started = !0;
|
|
225
|
+
const e = (s) => this.onErrorEvent(s);
|
|
226
|
+
window.addEventListener("error", e), this.teardowns.push(() => window.removeEventListener("error", e));
|
|
227
|
+
const t = (s) => this.onRejectionEvent(s);
|
|
228
|
+
window.addEventListener("unhandledrejection", t), this.teardowns.push(() => window.removeEventListener("unhandledrejection", t)), this.wrapConsoleError(), l.log("ErrorWatcher started");
|
|
229
|
+
}
|
|
230
|
+
destroy() {
|
|
231
|
+
for (const e of this.teardowns) e();
|
|
232
|
+
this.teardowns = [], this.listeners.clear(), this.started = !1, l.log("ErrorWatcher destroyed");
|
|
233
|
+
}
|
|
234
|
+
report(e, t) {
|
|
235
|
+
const s = I(e);
|
|
236
|
+
this.capture({
|
|
237
|
+
type: "manual",
|
|
238
|
+
message: s.message,
|
|
239
|
+
stack: s.stack,
|
|
240
|
+
...t ? { context: de(t) } : {}
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
subscribe(e) {
|
|
244
|
+
return this.listeners.add(e), () => {
|
|
245
|
+
this.listeners.delete(e);
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
getErrors() {
|
|
249
|
+
return this.prune(), this.errors.map((e) => ({ ...e }));
|
|
250
|
+
}
|
|
251
|
+
clear() {
|
|
252
|
+
this.errors = [];
|
|
253
|
+
}
|
|
254
|
+
onErrorEvent(e) {
|
|
255
|
+
if (typeof e.message != "string" && !e.error) return;
|
|
256
|
+
const t = e.error !== void 0 && e.error !== null ? I(e.error) : { message: e.message ?? "" };
|
|
257
|
+
this.capture({
|
|
258
|
+
type: "error",
|
|
259
|
+
message: t.message || e.message || "Unknown error",
|
|
260
|
+
stack: t.stack,
|
|
261
|
+
source: e.filename ? Re(e.filename) : void 0,
|
|
262
|
+
line: e.lineno || void 0,
|
|
263
|
+
col: e.colno || void 0
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
onRejectionEvent(e) {
|
|
267
|
+
const t = e.reason, s = I(t);
|
|
268
|
+
this.capture({
|
|
269
|
+
type: "unhandledrejection",
|
|
270
|
+
message: s.message || "Unhandled promise rejection",
|
|
271
|
+
stack: s.stack
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
wrapConsoleError() {
|
|
275
|
+
if (typeof console > "u" || typeof console.error != "function") return;
|
|
276
|
+
const e = console.error, t = (...s) => {
|
|
277
|
+
try {
|
|
278
|
+
this.onConsoleError(s);
|
|
279
|
+
} catch {
|
|
280
|
+
}
|
|
281
|
+
return e.apply(console, s);
|
|
282
|
+
};
|
|
283
|
+
console.error = t, this.teardowns.push(() => {
|
|
284
|
+
console.error === t && (console.error = e);
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
onConsoleError(e) {
|
|
288
|
+
if (e.length === 0) return;
|
|
289
|
+
const t = e[0];
|
|
290
|
+
if (typeof t == "string" && t.startsWith(Ae)) return;
|
|
291
|
+
const s = e.find(G), i = e.map(he).join(" ");
|
|
292
|
+
this.capture({
|
|
293
|
+
type: "console",
|
|
294
|
+
message: i,
|
|
295
|
+
stack: s && typeof s.stack == "string" ? s.stack : void 0
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
capture(e) {
|
|
299
|
+
if (!this.capturing) {
|
|
300
|
+
this.capturing = !0;
|
|
301
|
+
try {
|
|
302
|
+
const t = Date.now(), s = e.stack !== void 0 ? this.trimStack(e.stack, e.message) : void 0;
|
|
303
|
+
let i = {
|
|
304
|
+
type: e.type,
|
|
305
|
+
message: N(e.message, 500),
|
|
306
|
+
...e.source !== void 0 ? { source: e.source } : {},
|
|
307
|
+
...e.line !== void 0 ? { line: e.line } : {},
|
|
308
|
+
...e.col !== void 0 ? { col: e.col } : {},
|
|
309
|
+
...s ? { stack: s } : {},
|
|
310
|
+
route: this.currentPathname(),
|
|
311
|
+
firstAt: t,
|
|
312
|
+
lastAt: t,
|
|
313
|
+
count: 1,
|
|
314
|
+
...e.context !== void 0 ? { context: e.context } : {}
|
|
315
|
+
};
|
|
316
|
+
if (this.filter) {
|
|
317
|
+
const o = this.filter(i);
|
|
318
|
+
if (!o) return;
|
|
319
|
+
i = o;
|
|
320
|
+
}
|
|
321
|
+
this.prune(t);
|
|
322
|
+
const r = V(i), n = this.errors.find((o) => V(o) === r);
|
|
323
|
+
if (n) {
|
|
324
|
+
n.count += 1, n.lastAt = t, i.context !== void 0 && (n.context = i.context), this.notify(n);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
this.errors.push(i);
|
|
328
|
+
const a = this.errors.length - this.maxErrors;
|
|
329
|
+
a > 0 && this.errors.splice(0, a), this.notify(i);
|
|
330
|
+
} finally {
|
|
331
|
+
this.capturing = !1;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
notify(e) {
|
|
336
|
+
const t = { ...e };
|
|
337
|
+
for (const s of this.listeners) try {
|
|
338
|
+
s(t);
|
|
339
|
+
} catch (i) {
|
|
340
|
+
l.error("ErrorWatcher listener threw:", i);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
prune(e = Date.now()) {
|
|
344
|
+
Number.isFinite(this.maxAgeMs) && (this.errors = this.errors.filter((t) => e - t.lastAt <= this.maxAgeMs));
|
|
345
|
+
}
|
|
346
|
+
trimStack(e, t) {
|
|
347
|
+
let s = e;
|
|
348
|
+
const i = s.indexOf(`
|
|
349
|
+
`);
|
|
350
|
+
if (i !== -1 && s.slice(0, i).includes(t.slice(0, 80)) && (s = s.slice(i + 1)), s = s.trim(), !!s)
|
|
351
|
+
return N(s, this.maxStackChars);
|
|
352
|
+
}
|
|
353
|
+
currentPathname() {
|
|
354
|
+
return typeof window < "u" && window.location ? window.location.pathname : "";
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
function V(e) {
|
|
358
|
+
return `${e.type}|${e.message}|${e.source ?? ""}|${e.line ?? ""}`;
|
|
359
|
+
}
|
|
360
|
+
var Ie = 5e4, xe = 2e4, Fe = 2e3, Me = class {
|
|
361
|
+
constructor(e) {
|
|
362
|
+
this.functions = /* @__PURE__ */ new Map(), this.changeListeners = /* @__PURE__ */ new Set(), this.defaultMaxResultBytes = e?.maxResultBytes ?? Ie;
|
|
363
|
+
}
|
|
364
|
+
onChange(e) {
|
|
365
|
+
return this.changeListeners.add(e), () => {
|
|
366
|
+
this.changeListeners.delete(e);
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
emitChange() {
|
|
370
|
+
for (const e of this.changeListeners) try {
|
|
371
|
+
e();
|
|
372
|
+
} catch (t) {
|
|
373
|
+
l.error("Function registry change listener failed:", t);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
setDefaultMaxResultBytes(e) {
|
|
377
|
+
this.defaultMaxResultBytes = e;
|
|
378
|
+
}
|
|
379
|
+
getDefaultMaxResultBytes() {
|
|
380
|
+
return this.defaultMaxResultBytes;
|
|
381
|
+
}
|
|
382
|
+
register(e, t, s) {
|
|
383
|
+
if (typeof e == "object") {
|
|
384
|
+
const { name: c, handler: u, description: d, parameters: g, maxResultBytes: m, requiresApproval: v, webmcp: f } = e;
|
|
385
|
+
return this.register(c, u, {
|
|
386
|
+
description: d,
|
|
387
|
+
parameters: g,
|
|
388
|
+
maxResultBytes: m,
|
|
389
|
+
requiresApproval: v,
|
|
390
|
+
webmcp: f
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
const i = e;
|
|
394
|
+
if (!t || !s) throw new C(`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");
|
|
395
|
+
this.functions.has(i) && l.warn(`Function "${i}" is being overwritten`);
|
|
396
|
+
const { maxResultBytes: r, requiresApproval: n, webmcp: a, ...o } = s;
|
|
397
|
+
this.functions.set(i, {
|
|
398
|
+
schema: {
|
|
399
|
+
...o,
|
|
400
|
+
name: i
|
|
401
|
+
},
|
|
402
|
+
handler: t,
|
|
403
|
+
maxResultBytes: r,
|
|
404
|
+
requiresApproval: n,
|
|
405
|
+
webmcp: a
|
|
406
|
+
}), l.log(`Registered function: ${i}`), this.emitChange();
|
|
407
|
+
}
|
|
408
|
+
unregister(e) {
|
|
409
|
+
const t = this.functions.delete(e);
|
|
410
|
+
return t && (l.log(`Unregistered function: ${e}`), this.emitChange()), t;
|
|
411
|
+
}
|
|
412
|
+
get(e) {
|
|
413
|
+
return this.functions.get(e);
|
|
414
|
+
}
|
|
415
|
+
has(e) {
|
|
416
|
+
return this.functions.has(e);
|
|
417
|
+
}
|
|
418
|
+
getSchemas() {
|
|
419
|
+
return Array.from(this.functions.values()).map((e) => e.schema);
|
|
420
|
+
}
|
|
421
|
+
getAll() {
|
|
422
|
+
return Array.from(this.functions.entries()).map(([e, t]) => ({
|
|
423
|
+
...t,
|
|
424
|
+
name: e
|
|
425
|
+
}));
|
|
426
|
+
}
|
|
427
|
+
async execute(e, t) {
|
|
428
|
+
const s = this.functions.get(e);
|
|
429
|
+
if (!s) throw new H(`Function "${e}" is not registered`, e);
|
|
430
|
+
l.log(`Executing function: ${e}`, t);
|
|
431
|
+
try {
|
|
432
|
+
const i = await s.handler(t);
|
|
433
|
+
return l.log(`Function ${e} completed:`, i), this.guardResultSize(e, i, s.maxResultBytes);
|
|
434
|
+
} catch (i) {
|
|
435
|
+
throw l.error(`Function ${e} failed:`, i), new H(`Function "${e}" execution failed: ${i instanceof Error ? i.message : "Unknown error"}`, e, i instanceof Error ? i : void 0);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
guardResultSize(e, t, s) {
|
|
439
|
+
let i;
|
|
440
|
+
try {
|
|
441
|
+
i = JSON.stringify(t);
|
|
442
|
+
} catch {
|
|
443
|
+
return t;
|
|
444
|
+
}
|
|
445
|
+
if (i === void 0) return t;
|
|
446
|
+
const r = new TextEncoder().encode(i).length, n = s ?? this.defaultMaxResultBytes;
|
|
447
|
+
return r > n ? (l.warn(`Function "${e}" result is ${r} bytes, over the ${n}-byte limit; a truncated preview was sent to the agent instead. Return fewer fields, paginate, or raise maxResultBytes for this function.`), {
|
|
448
|
+
truncated: !0,
|
|
449
|
+
originalBytes: r,
|
|
450
|
+
maxBytes: n,
|
|
451
|
+
preview: i.slice(0, Fe),
|
|
452
|
+
hint: `The result of "${e}" exceeded the ${n}-byte limit and was truncated. Request less data (use limit or filter parameters if available), or tell the user the result is too large to process.`
|
|
453
|
+
}) : (r > xe && l.warn(`Function "${e}" returned a large result (${Math.round(r / 1024)} KB). Large results consume LLM context: return fewer fields, paginate, or push the data to the UI and return a summary.`), t);
|
|
454
|
+
}
|
|
455
|
+
clear() {
|
|
456
|
+
const e = this.functions.size > 0;
|
|
457
|
+
this.functions.clear(), l.log("Cleared all registered functions"), e && this.emitChange();
|
|
458
|
+
}
|
|
459
|
+
get size() {
|
|
460
|
+
return this.functions.size;
|
|
461
|
+
}
|
|
462
|
+
}, De = new TextEncoder();
|
|
463
|
+
function E(e) {
|
|
464
|
+
return De.encode(e).length;
|
|
465
|
+
}
|
|
466
|
+
function O(e) {
|
|
467
|
+
return E(JSON.stringify(e)) - 2;
|
|
468
|
+
}
|
|
469
|
+
function fe(e, t) {
|
|
470
|
+
if (t <= 0) return "";
|
|
471
|
+
let s = "", i = 0;
|
|
472
|
+
for (const r of e) {
|
|
473
|
+
const n = O(r);
|
|
474
|
+
if (i + n > t) break;
|
|
475
|
+
s += r, i += n;
|
|
476
|
+
}
|
|
477
|
+
return s;
|
|
478
|
+
}
|
|
479
|
+
var $e = 50, Pe = 2;
|
|
480
|
+
var Ne = 2e3;
|
|
481
|
+
function A(e) {
|
|
482
|
+
try {
|
|
483
|
+
return JSON.stringify(e);
|
|
484
|
+
} catch {
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
var j = /* @__PURE__ */ Symbol("ago.pageData.timeout");
|
|
489
|
+
function Oe(e, t) {
|
|
490
|
+
return t <= 0 ? Promise.resolve(j) : new Promise((s, i) => {
|
|
491
|
+
const r = setTimeout(() => s(j), t);
|
|
492
|
+
e.then((n) => {
|
|
493
|
+
clearTimeout(r), s(n);
|
|
494
|
+
}, (n) => {
|
|
495
|
+
clearTimeout(r), i(n);
|
|
496
|
+
});
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
async function je(e, t) {
|
|
500
|
+
const s = Date.now() + t;
|
|
501
|
+
let i = 0;
|
|
502
|
+
for (; Date.now() < s && i < Pe; )
|
|
503
|
+
i = e().isLoading?.() ? 0 : i + 1, await new Promise((o) => setTimeout(o, $e));
|
|
504
|
+
const r = e().get();
|
|
505
|
+
if (!Y(r)) return r;
|
|
506
|
+
const n = await Oe(Promise.resolve(r), s - Date.now());
|
|
507
|
+
if (n !== j) return n;
|
|
508
|
+
l.warn("Page data did not resolve within the settle timeout; returning what the page has now. Raise settleTimeoutMs if the work legitimately takes longer.");
|
|
509
|
+
const a = e().get();
|
|
510
|
+
if (!Y(a)) return a;
|
|
511
|
+
Promise.resolve(a).catch(() => {
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
function Y(e) {
|
|
515
|
+
return typeof e == "object" && e !== null && typeof e.then == "function";
|
|
516
|
+
}
|
|
517
|
+
function Le(e) {
|
|
518
|
+
if (typeof e != "object" || e === null || Array.isArray(e)) return;
|
|
519
|
+
const t = e;
|
|
520
|
+
let s;
|
|
521
|
+
for (const i of Object.keys(t)) {
|
|
522
|
+
const r = t[i];
|
|
523
|
+
Array.isArray(r) && (s === void 0 || r.length > t[s].length) && (s = i);
|
|
524
|
+
}
|
|
525
|
+
return s;
|
|
526
|
+
}
|
|
527
|
+
function Ue(e, t) {
|
|
528
|
+
let s = 2, i = 0;
|
|
529
|
+
for (const r of e) {
|
|
530
|
+
const n = E(A(r) ?? "null") + (i > 0 ? 1 : 0);
|
|
531
|
+
if (s + n > t) break;
|
|
532
|
+
s += n, i++;
|
|
533
|
+
}
|
|
534
|
+
return i;
|
|
535
|
+
}
|
|
536
|
+
function L(e) {
|
|
537
|
+
return `The page data returned by "${e}" was too large to send in full. Only the first items are included: ask for fewer rows or narrow the filters to see the rest.`;
|
|
538
|
+
}
|
|
539
|
+
function We(e, t, s, i) {
|
|
540
|
+
const r = {
|
|
541
|
+
truncated: !0,
|
|
542
|
+
originalBytes: s,
|
|
543
|
+
maxBytes: i,
|
|
544
|
+
preview: "",
|
|
545
|
+
hint: L(e)
|
|
546
|
+
}, n = E(A(r) ?? "{}");
|
|
547
|
+
return {
|
|
548
|
+
...r,
|
|
549
|
+
preview: fe(t, Math.min(Ne, i - n))
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
function Be(e, t, s, i, r) {
|
|
553
|
+
const n = s === void 0 ? {} : { ...t }, a = s ?? "items", o = E(A({
|
|
554
|
+
...n,
|
|
555
|
+
[a]: [],
|
|
556
|
+
truncation: {
|
|
557
|
+
truncated: !0,
|
|
558
|
+
returnedItems: i.length,
|
|
559
|
+
totalItems: i.length,
|
|
560
|
+
hint: L(e)
|
|
561
|
+
}
|
|
562
|
+
}) ?? "{}") - 2;
|
|
563
|
+
if (o >= r) return;
|
|
564
|
+
const c = i.slice(0, Ue(i, r - o));
|
|
565
|
+
return {
|
|
566
|
+
...n,
|
|
567
|
+
[a]: c,
|
|
568
|
+
truncation: {
|
|
569
|
+
truncated: !0,
|
|
570
|
+
returnedItems: c.length,
|
|
571
|
+
totalItems: i.length,
|
|
572
|
+
hint: L(e)
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
function Q(e, t, s) {
|
|
577
|
+
const i = A(t);
|
|
578
|
+
if (i === void 0) return t;
|
|
579
|
+
const r = E(i);
|
|
580
|
+
if (r <= s) return t;
|
|
581
|
+
l.warn(`Page data for "${e}" is ${r} bytes, over the ${s}-byte limit; it was truncated to the first items that fit. Return fewer fields per item, paginate, or raise maxResultBytes on the data source.`);
|
|
582
|
+
const n = Le(t), a = Array.isArray(t) ? t : n !== void 0 ? t[n] : void 0;
|
|
583
|
+
if (a) {
|
|
584
|
+
const o = Be(e, t, n, a, s), c = E(A(o) ?? "");
|
|
585
|
+
if (o !== void 0 && c <= s) return o;
|
|
586
|
+
}
|
|
587
|
+
return We(e, i, r, s);
|
|
588
|
+
}
|
|
589
|
+
function R(e, t) {
|
|
590
|
+
if (e === t) return !0;
|
|
591
|
+
if (e === null || t === null || typeof e != "object" || typeof t != "object" || Array.isArray(e) !== Array.isArray(t)) return !1;
|
|
592
|
+
if (Array.isArray(e))
|
|
593
|
+
return e.length !== t.length ? !1 : e.every((r, n) => R(r, t[n]));
|
|
594
|
+
const s = Object.keys(e), i = Object.keys(t);
|
|
595
|
+
return s.length !== i.length ? !1 : s.every((r) => r in t && R(e[r], t[r]));
|
|
596
|
+
}
|
|
597
|
+
var Z = 100, x = " … [truncated]", ge = { truncated: !0 }, Ge = E(',"data":' + JSON.stringify(ge));
|
|
598
|
+
function U(e) {
|
|
599
|
+
return E(JSON.stringify(e));
|
|
600
|
+
}
|
|
601
|
+
function ee(e, t) {
|
|
602
|
+
if (U(e) <= t || !e.rejected) return e;
|
|
603
|
+
const s = Object.entries(e.rejected), i = Object.fromEntries(s.map(([o]) => [o, x])), r = {
|
|
604
|
+
...e,
|
|
605
|
+
rejected: i
|
|
606
|
+
};
|
|
607
|
+
let n = U(r);
|
|
608
|
+
if (n > t) return r;
|
|
609
|
+
const a = O(x);
|
|
610
|
+
for (const [o, c] of s) {
|
|
611
|
+
const u = O(c), d = t - n + a;
|
|
612
|
+
if (u <= d) {
|
|
613
|
+
i[o] = c, n += u - a;
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
i[o] = fe(c, d - a) + x;
|
|
617
|
+
break;
|
|
618
|
+
}
|
|
619
|
+
return r;
|
|
620
|
+
}
|
|
621
|
+
function S(e) {
|
|
622
|
+
return Array.isArray(e) ? "array" : typeof e;
|
|
623
|
+
}
|
|
624
|
+
function te(e) {
|
|
625
|
+
return typeof e != "number" ? `Expected type "number", got "${S(e)}".` : Number.isFinite(e) ? null : "Expected a finite number.";
|
|
626
|
+
}
|
|
627
|
+
function me(e) {
|
|
628
|
+
const t = e.slice(0, Z).map((i) => JSON.stringify(i)), s = e.length - Z;
|
|
629
|
+
return s > 0 ? `${t.join(", ")} (${s} more not shown)` : t.join(", ");
|
|
630
|
+
}
|
|
631
|
+
function se(e, t) {
|
|
632
|
+
return t.includes(e) ? null : `${JSON.stringify(e)} is not an allowed value. Allowed values: ${me(t)}.`;
|
|
633
|
+
}
|
|
634
|
+
function qe(e, t) {
|
|
635
|
+
const { schema: s } = t;
|
|
636
|
+
if (s.type === "array") {
|
|
637
|
+
if (!Array.isArray(e)) return `Expected type "array", got "${S(e)}".`;
|
|
638
|
+
for (let r = 0; r < e.length; r++) {
|
|
639
|
+
const n = e[r];
|
|
640
|
+
if (s.items?.type) {
|
|
641
|
+
const a = s.items.type === "number" ? te(n) : S(n) !== s.items.type ? `Expected type "${s.items.type}", got "${S(n)}".` : null;
|
|
642
|
+
if (a) return `Array item at index ${r}: ${a[0].toLowerCase()}${a.slice(1)}`;
|
|
643
|
+
}
|
|
644
|
+
if (s.items?.enum) {
|
|
645
|
+
const a = se(n, s.items.enum);
|
|
646
|
+
if (a) return `Array item ${a}`;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return null;
|
|
650
|
+
}
|
|
651
|
+
if (s.type === "number") {
|
|
652
|
+
const r = te(e);
|
|
653
|
+
if (r) return r;
|
|
654
|
+
} else if (S(e) !== s.type) return `Expected type "${s.type}", got "${S(e)}".`;
|
|
655
|
+
const i = pe(t);
|
|
656
|
+
return i ? se(e, i) : null;
|
|
657
|
+
}
|
|
658
|
+
function q(e) {
|
|
659
|
+
return e.clearable === !0 && e.schema.type === "string";
|
|
660
|
+
}
|
|
661
|
+
function pe(e) {
|
|
662
|
+
const t = e.schema.enum;
|
|
663
|
+
if (t)
|
|
664
|
+
return q(e) && !t.includes("") ? [...t, ""] : t;
|
|
665
|
+
}
|
|
666
|
+
function Je(e) {
|
|
667
|
+
const t = {
|
|
668
|
+
...e.schema,
|
|
669
|
+
description: e.description
|
|
670
|
+
};
|
|
671
|
+
q(e) && (t.description = `${e.description} Pass "" to clear it.`);
|
|
672
|
+
const s = pe(e);
|
|
673
|
+
return s && (t.enum = s), t;
|
|
674
|
+
}
|
|
675
|
+
function Ke(e, t) {
|
|
676
|
+
const s = new Map(e.map((n) => [n.name, n])), i = e.map((n) => n.name), r = e.map((n) => `- "${n.name}": ${n.description}`).join(`
|
|
677
|
+
`);
|
|
678
|
+
return {
|
|
679
|
+
name: t.name,
|
|
680
|
+
handler: async (n) => {
|
|
681
|
+
const a = [], o = [], c = {};
|
|
682
|
+
for (const [h, p] of Object.entries(n)) {
|
|
683
|
+
const y = s.get(h);
|
|
684
|
+
if (!y) {
|
|
685
|
+
c[h] = `"${h}" is not a registered control. Available controls: ${me(i)}.`;
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
if (p == null || p === "" && !q(y)) continue;
|
|
689
|
+
const b = qe(p, y);
|
|
690
|
+
if (b) {
|
|
691
|
+
c[h] = b;
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
if (y.get && R(p, y.get())) {
|
|
695
|
+
o.push(h);
|
|
696
|
+
continue;
|
|
697
|
+
}
|
|
698
|
+
const w = await y.set(p);
|
|
699
|
+
w ? w.result === "rejected" ? c[h] = w.reason || "The page rejected this field's update." : w.result === "unchanged" ? o.push(h) : a.push(h) : a.push(h);
|
|
700
|
+
}
|
|
701
|
+
const u = Object.keys(c).length > 0, d = {
|
|
702
|
+
success: !u,
|
|
703
|
+
applied: a,
|
|
704
|
+
unchanged: o,
|
|
705
|
+
...u ? { rejected: c } : {}
|
|
706
|
+
}, g = t.getResultBudget();
|
|
707
|
+
if (!t.data) return ee(d, g);
|
|
708
|
+
const m = ee(d, g - Ge), v = await t.data.read(m), f = {
|
|
709
|
+
...m,
|
|
710
|
+
data: v
|
|
711
|
+
};
|
|
712
|
+
return U(f) <= g ? f : {
|
|
713
|
+
...m,
|
|
714
|
+
data: ge
|
|
715
|
+
};
|
|
716
|
+
},
|
|
717
|
+
description: (e.length > 0 ? `Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
|
|
718
|
+
${r}` : "The current page has no editable state — nothing to change here.") + (t.data ? `
|
|
719
|
+
Returns the resulting page data once it has loaded: ${t.data.description}` : ""),
|
|
720
|
+
parameters: {
|
|
721
|
+
type: "object",
|
|
722
|
+
properties: Object.fromEntries(e.map((n) => [n.name, Je(n)])),
|
|
723
|
+
required: []
|
|
724
|
+
},
|
|
725
|
+
requiresApproval: t.requiresApproval,
|
|
726
|
+
maxResultBytes: t.data?.maxResultBytes
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
var He = 250, Xe = 3, ze = 1e3, Ve = 24, Ye = 10, Qe = 50, Ze = [
|
|
730
|
+
"mousemove",
|
|
731
|
+
"mousedown",
|
|
732
|
+
"keydown",
|
|
733
|
+
"scroll",
|
|
734
|
+
"touchstart"
|
|
735
|
+
], et = class {
|
|
736
|
+
constructor(e = {}) {
|
|
737
|
+
this.started = !1, this.teardowns = [], this.route = "", this.routeEnteredAt = 0, this.lastActivityAt = 0, this.lastHeavyActivityAt = 0, this.recentRoutes = [], this.routeBounces = 0, this.rageClicks = 0, this.jsErrors = 0, this.fieldErrors = {}, this.recentClicks = [], this.signals = [], this.listeners = /* @__PURE__ */ new Set(), this.getPageState = e.getPageState, this.activityThrottleMs = e.activityThrottleMs ?? He, this.rageClickCount = e.rageClickCount ?? Xe, this.rageClickWindowMs = e.rageClickWindowMs ?? ze, this.rageClickRadiusPx = e.rageClickRadiusPx ?? Ve, this.maxRecentRoutes = e.maxRecentRoutes ?? Ye, this.maxSignals = e.maxSignals ?? Qe;
|
|
738
|
+
}
|
|
739
|
+
start() {
|
|
740
|
+
if (this.started || typeof window > "u" || typeof document > "u") return;
|
|
741
|
+
this.started = !0;
|
|
742
|
+
const e = Date.now();
|
|
743
|
+
this.route = this.currentPathname(), this.routeEnteredAt = e, this.lastActivityAt = e, this.recentRoutes = [this.route];
|
|
744
|
+
const t = (i, r, n) => {
|
|
745
|
+
i.addEventListener(r, n, { passive: !0 }), this.teardowns.push(() => i.removeEventListener(r, n));
|
|
746
|
+
}, s = () => this.recordActivity();
|
|
747
|
+
for (const i of Ze) t(window, i, s);
|
|
748
|
+
t(document, "visibilitychange", () => {
|
|
749
|
+
document.visibilityState === "visible" && this.recordActivity();
|
|
750
|
+
}), t(window, "popstate", () => this.checkRoute()), t(window, "hashchange", () => this.checkRoute()), t(window, "click", (i) => this.onClick(i)), l.log("SignalCollector started");
|
|
751
|
+
}
|
|
752
|
+
destroy() {
|
|
753
|
+
for (const e of this.teardowns) e();
|
|
754
|
+
this.teardowns = [], this.listeners.clear(), this.recentClicks = [], this.started = !1, l.log("SignalCollector destroyed");
|
|
755
|
+
}
|
|
756
|
+
signalFieldError(e) {
|
|
757
|
+
this.checkRoute();
|
|
758
|
+
const t = (this.fieldErrors[e] ?? 0) + 1;
|
|
759
|
+
this.fieldErrors[e] = t, this.pushSignal({
|
|
760
|
+
type: "field_error",
|
|
761
|
+
route: this.route,
|
|
762
|
+
at: Date.now(),
|
|
763
|
+
count: t,
|
|
764
|
+
meta: { field: e }
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
signalJsError(e) {
|
|
768
|
+
this.checkRoute(), this.jsErrors += 1, this.pushSignal({
|
|
769
|
+
type: "js_error",
|
|
770
|
+
route: this.route,
|
|
771
|
+
at: Date.now(),
|
|
772
|
+
count: this.jsErrors,
|
|
773
|
+
meta: { kind: e }
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
subscribe(e) {
|
|
777
|
+
return this.listeners.add(e), () => {
|
|
778
|
+
this.listeners.delete(e);
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
getSignals() {
|
|
782
|
+
return [...this.signals];
|
|
783
|
+
}
|
|
784
|
+
getSnapshot(e) {
|
|
785
|
+
this.checkRoute();
|
|
786
|
+
const t = Date.now();
|
|
787
|
+
return {
|
|
788
|
+
route: this.route,
|
|
789
|
+
dwellMs: this.started ? t - this.routeEnteredAt : 0,
|
|
790
|
+
idleMs: this.started ? t - this.lastActivityAt : 0,
|
|
791
|
+
rageClicks: this.rageClicks,
|
|
792
|
+
jsErrors: this.jsErrors,
|
|
793
|
+
routeBounces: this.routeBounces,
|
|
794
|
+
fieldErrors: { ...this.fieldErrors },
|
|
795
|
+
recentRoutes: [...this.recentRoutes],
|
|
796
|
+
pageState: e?.pageState === !1 ? null : this.readPageState()
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
currentPathname() {
|
|
800
|
+
return typeof window < "u" && window.location ? window.location.pathname : "";
|
|
801
|
+
}
|
|
802
|
+
readPageState() {
|
|
803
|
+
if (!this.getPageState) return null;
|
|
804
|
+
try {
|
|
805
|
+
return this.getPageState() ?? null;
|
|
806
|
+
} catch (e) {
|
|
807
|
+
return l.warn("SignalCollector getPageState threw:", e), null;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
recordActivity() {
|
|
811
|
+
const e = Date.now();
|
|
812
|
+
this.lastActivityAt = e, e - this.lastHeavyActivityAt >= this.activityThrottleMs && (this.lastHeavyActivityAt = e, this.checkRoute());
|
|
813
|
+
}
|
|
814
|
+
checkRoute() {
|
|
815
|
+
if (!this.started) return;
|
|
816
|
+
const e = this.currentPathname();
|
|
817
|
+
if (e === this.route) return;
|
|
818
|
+
const t = Date.now(), s = this.route;
|
|
819
|
+
this.route = e, this.routeEnteredAt = t, this.rageClicks = 0, this.jsErrors = 0, this.fieldErrors = {}, this.recentClicks = [], this.recentRoutes.push(e), this.recentRoutes.length > this.maxRecentRoutes && this.recentRoutes.splice(0, this.recentRoutes.length - this.maxRecentRoutes), this.pushSignal({
|
|
820
|
+
type: "route_change",
|
|
821
|
+
route: e,
|
|
822
|
+
at: t,
|
|
823
|
+
meta: { from: s }
|
|
824
|
+
});
|
|
825
|
+
const i = this.recentRoutes, r = i.length;
|
|
826
|
+
r >= 4 && i[r - 1] === i[r - 3] && i[r - 2] === i[r - 4] && i[r - 1] !== i[r - 2] && (this.routeBounces += 1, this.pushSignal({
|
|
827
|
+
type: "route_bounce",
|
|
828
|
+
route: e,
|
|
829
|
+
at: t,
|
|
830
|
+
count: this.routeBounces,
|
|
831
|
+
meta: { between: `${i[r - 2]}↔${i[r - 1]}` }
|
|
832
|
+
}));
|
|
833
|
+
}
|
|
834
|
+
onClick(e) {
|
|
835
|
+
this.recordActivity();
|
|
836
|
+
const t = Date.now(), s = this.pageStateKey(), i = {
|
|
837
|
+
at: t,
|
|
838
|
+
x: e.clientX,
|
|
839
|
+
y: e.clientY,
|
|
840
|
+
stateKey: s
|
|
841
|
+
};
|
|
842
|
+
this.recentClicks = this.recentClicks.filter((o) => t - o.at <= this.rageClickWindowMs);
|
|
843
|
+
const r = this.recentClicks[0], n = !r || Math.abs(i.x - r.x) <= this.rageClickRadiusPx && Math.abs(i.y - r.y) <= this.rageClickRadiusPx, a = !r || r.stateKey === s;
|
|
844
|
+
if (!n || !a) {
|
|
845
|
+
this.recentClicks = [i];
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
this.recentClicks.push(i), this.recentClicks.length >= this.rageClickCount && (this.rageClicks += 1, this.recentClicks = [], this.pushSignal({
|
|
849
|
+
type: "rage_click",
|
|
850
|
+
route: this.route,
|
|
851
|
+
at: t,
|
|
852
|
+
count: this.rageClicks
|
|
853
|
+
}));
|
|
854
|
+
}
|
|
855
|
+
pageStateKey() {
|
|
856
|
+
const e = this.readPageState();
|
|
857
|
+
if (!e) return "";
|
|
858
|
+
try {
|
|
859
|
+
return JSON.stringify(e);
|
|
860
|
+
} catch {
|
|
861
|
+
return "";
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
pushSignal(e) {
|
|
865
|
+
this.signals.push(e), this.signals.length > this.maxSignals && this.signals.splice(0, this.signals.length - this.maxSignals);
|
|
866
|
+
for (const t of this.listeners) try {
|
|
867
|
+
t(e);
|
|
868
|
+
} catch (s) {
|
|
869
|
+
l.error("Signal listener threw:", s);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
function tt(e, t) {
|
|
874
|
+
const s = t ? t.storage ?? (typeof localStorage < "u" ? localStorage : void 0) : void 0;
|
|
875
|
+
let i = e;
|
|
876
|
+
if (t && s) try {
|
|
877
|
+
const o = s.getItem(t.key);
|
|
878
|
+
o != null && (i = JSON.parse(o));
|
|
879
|
+
} catch {
|
|
880
|
+
}
|
|
881
|
+
const r = /* @__PURE__ */ new Set(), n = () => r.forEach((o) => o(i));
|
|
882
|
+
function a() {
|
|
883
|
+
if (t && s) try {
|
|
884
|
+
s.setItem(t.key, JSON.stringify(i));
|
|
885
|
+
} catch {
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
return {
|
|
889
|
+
get: () => i,
|
|
890
|
+
set: (o) => {
|
|
891
|
+
i = o, a(), n();
|
|
892
|
+
},
|
|
893
|
+
subscribe: (o) => (r.add(o), () => {
|
|
894
|
+
r.delete(o);
|
|
895
|
+
})
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
var st = 6e4, it = 1440 * 60 * 1e3, rt = "ago_proactive";
|
|
899
|
+
function F(e) {
|
|
900
|
+
const t = new Date(e), s = String(t.getMonth() + 1).padStart(2, "0"), i = String(t.getDate()).padStart(2, "0");
|
|
901
|
+
return `${t.getFullYear()}-${s}-${i}`;
|
|
902
|
+
}
|
|
903
|
+
var nt = class {
|
|
904
|
+
constructor(e = {}) {
|
|
905
|
+
this.killSwitchEnabled = !1, this.engaged = !1, this.turnInFlight = !1, this.slotOccupied = !1, this.sessionCount = 0, this.perSessionCap = e.frequencyCap?.perSession, this.perDayCap = e.frequencyCap?.perDay, this.store = tt({
|
|
906
|
+
optOut: !1,
|
|
907
|
+
lastFiredAt: {},
|
|
908
|
+
dismissedAt: {},
|
|
909
|
+
day: {
|
|
910
|
+
date: F(Date.now()),
|
|
911
|
+
count: 0
|
|
912
|
+
}
|
|
913
|
+
}, {
|
|
914
|
+
key: e.storageKey ?? rt,
|
|
915
|
+
storage: e.storage
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
setKillSwitch(e) {
|
|
919
|
+
this.killSwitchEnabled = e;
|
|
920
|
+
}
|
|
921
|
+
optOut() {
|
|
922
|
+
this.store.set({
|
|
923
|
+
...this.store.get(),
|
|
924
|
+
optOut: !0
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
optIn() {
|
|
928
|
+
this.store.set({
|
|
929
|
+
...this.store.get(),
|
|
930
|
+
optOut: !1
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
isOptedOut() {
|
|
934
|
+
return this.store.get().optOut;
|
|
935
|
+
}
|
|
936
|
+
setEngaged(e) {
|
|
937
|
+
this.engaged = e;
|
|
938
|
+
}
|
|
939
|
+
setTurnInFlight(e) {
|
|
940
|
+
this.turnInFlight = e;
|
|
941
|
+
}
|
|
942
|
+
isSlotOccupied() {
|
|
943
|
+
return this.slotOccupied;
|
|
944
|
+
}
|
|
945
|
+
occupySlot() {
|
|
946
|
+
this.slotOccupied = !0;
|
|
947
|
+
}
|
|
948
|
+
releaseSlot() {
|
|
949
|
+
this.slotOccupied = !1;
|
|
950
|
+
}
|
|
951
|
+
canFire(e, t = Date.now()) {
|
|
952
|
+
if (!this.killSwitchEnabled) return this.deny(e, "kill-switch (proactive disabled server-side)");
|
|
953
|
+
const s = this.store.get();
|
|
954
|
+
if (s.optOut) return this.deny(e, "user opted out");
|
|
955
|
+
if (this.engaged) return this.deny(e, "user engaged (widget open)");
|
|
956
|
+
if (this.turnInFlight) return this.deny(e, "message turn in flight");
|
|
957
|
+
if (this.slotOccupied) return this.deny(e, "nudge slot occupied");
|
|
958
|
+
const i = s.lastFiredAt[e.id], r = e.cooldownMs ?? st;
|
|
959
|
+
if (i !== void 0 && t - i < r) return this.deny(e, "cooldown");
|
|
960
|
+
const n = s.dismissedAt[e.id], a = e.resurfaceAfterMs ?? it;
|
|
961
|
+
return n !== void 0 && t - n < a ? this.deny(e, "dismissed recently") : this.perSessionCap !== void 0 && this.sessionCount >= this.perSessionCap ? this.deny(e, "perSession cap") : this.perDayCap !== void 0 && this.dayCount(t) >= this.perDayCap ? this.deny(e, "perDay cap") : !0;
|
|
962
|
+
}
|
|
963
|
+
recordFired(e, t = Date.now()) {
|
|
964
|
+
const s = this.store.get();
|
|
965
|
+
this.store.set({
|
|
966
|
+
...s,
|
|
967
|
+
lastFiredAt: {
|
|
968
|
+
...s.lastFiredAt,
|
|
969
|
+
[e]: t
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
recordNudgeShown(e = Date.now()) {
|
|
974
|
+
this.sessionCount += 1;
|
|
975
|
+
const t = this.store.get(), s = F(e), i = t.day.date === s ? {
|
|
976
|
+
date: s,
|
|
977
|
+
count: t.day.count + 1
|
|
978
|
+
} : {
|
|
979
|
+
date: s,
|
|
980
|
+
count: 1
|
|
981
|
+
};
|
|
982
|
+
this.store.set({
|
|
983
|
+
...t,
|
|
984
|
+
day: i
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
recordDismissed(e, t = Date.now()) {
|
|
988
|
+
const s = this.store.get();
|
|
989
|
+
this.store.set({
|
|
990
|
+
...s,
|
|
991
|
+
dismissedAt: {
|
|
992
|
+
...s.dismissedAt,
|
|
993
|
+
[e]: t
|
|
994
|
+
}
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
dayCount(e) {
|
|
998
|
+
const t = this.store.get();
|
|
999
|
+
return t.day.date === F(e) ? t.day.count : 0;
|
|
1000
|
+
}
|
|
1001
|
+
deny(e, t) {
|
|
1002
|
+
return l.debug(`NudgeGovernor: trigger "${e.id}" blocked — ${t}`), !1;
|
|
1003
|
+
}
|
|
1004
|
+
};
|
|
1005
|
+
function W() {
|
|
1006
|
+
return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
|
|
1007
|
+
const t = Math.floor(Math.random() * 16);
|
|
1008
|
+
return (e === "x" ? t : t & 3 | 8).toString(16);
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
function ot(e) {
|
|
1012
|
+
return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1013
|
+
}
|
|
1014
|
+
function at(e, t) {
|
|
1015
|
+
if (e === "*" || e === t) return !0;
|
|
1016
|
+
const s = e.split("/"), i = s.map((r, n) => {
|
|
1017
|
+
const a = n === s.length - 1;
|
|
1018
|
+
return r === "*" ? a ? "[^/]+(?:/[^/]+)*" : "[^/]+" : r.startsWith(":") ? "[^/]+" : ot(r);
|
|
1019
|
+
});
|
|
1020
|
+
return new RegExp("^" + i.join("/") + "/?$").test(t);
|
|
1021
|
+
}
|
|
1022
|
+
function ye(e, t) {
|
|
1023
|
+
return e === t ? !0 : e === null || t === null ? !1 : Array.isArray(e) ? !Array.isArray(t) || t.length !== e.length ? !1 : e.every((s, i) => R(s, t[i])) : typeof e == "object" ? typeof t != "object" || Array.isArray(t) ? !1 : Object.entries(e).every(([s, i]) => ye(i, t[s])) : !1;
|
|
1024
|
+
}
|
|
1025
|
+
function ct(e, t) {
|
|
1026
|
+
if (e.route !== void 0 && !at(e.route, t.route) || e.idleMs !== void 0 && t.idleMs < e.idleMs || e.dwellMs !== void 0 && t.dwellMs < e.dwellMs || e.rageClicks !== void 0 && t.rageClicks < e.rageClicks || e.jsErrors !== void 0 && (t.jsErrors ?? 0) < e.jsErrors || e.routeBounces !== void 0 && t.routeBounces < e.routeBounces) return !1;
|
|
1027
|
+
if (e.fieldErrors !== void 0) {
|
|
1028
|
+
for (const [s, i] of Object.entries(e.fieldErrors)) if ((t.fieldErrors[s] ?? 0) < i) return !1;
|
|
1029
|
+
}
|
|
1030
|
+
return !(e.pageState !== void 0 && !ye(e.pageState, t.pageState ?? {}));
|
|
1031
|
+
}
|
|
1032
|
+
var lt = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate", ht = class {
|
|
1033
|
+
constructor(e) {
|
|
1034
|
+
this.tickTimer = null, this.teardowns = [], this.started = !1, this.activeNudge = null, this.lastConversationId = null, this.shownIds = /* @__PURE__ */ new Set(), this.resolvedIds = /* @__PURE__ */ new Set(), this.lastEvaluationAt = 0, this.client = e.client, this.collector = e.collector, this.governor = e.governor, this.tracker = e.tracker, this.options = e.options, this.tickMs = e.options.tickMs ?? lt;
|
|
1035
|
+
}
|
|
1036
|
+
start() {
|
|
1037
|
+
if (this.started) return;
|
|
1038
|
+
this.started = !0, this.options.enabledOverride !== void 0 ? this.governor.setKillSwitch(this.options.enabledOverride) : this.loadKillSwitch();
|
|
1039
|
+
const e = (r) => {
|
|
1040
|
+
r.conversationId && (this.lastConversationId = r.conversationId), this.governor.setTurnInFlight(!0);
|
|
1041
|
+
}, t = () => this.governor.setTurnInFlight(!1), s = () => this.governor.setTurnInFlight(!1), i = (r) => {
|
|
1042
|
+
r?.id && (this.lastConversationId = r.id);
|
|
1043
|
+
};
|
|
1044
|
+
this.client.on("message:start", e), this.client.on("message:complete", t), this.client.on("message:error", s), this.client.on("conversation:loaded", i), this.teardowns.push(() => {
|
|
1045
|
+
this.client.off("message:start", e), this.client.off("message:complete", t), this.client.off("message:error", s), this.client.off("conversation:loaded", i);
|
|
1046
|
+
}), this.tickTimer = setInterval(() => this.evaluate(), this.tickMs), this.teardowns.push(this.collector.subscribe(() => {
|
|
1047
|
+
Date.now() - this.lastEvaluationAt >= this.tickMs && this.evaluate();
|
|
1048
|
+
}));
|
|
1049
|
+
}
|
|
1050
|
+
stop() {
|
|
1051
|
+
this.tickTimer !== null && (clearInterval(this.tickTimer), this.tickTimer = null);
|
|
1052
|
+
for (const e of this.teardowns) e();
|
|
1053
|
+
this.teardowns = [], this.started = !1;
|
|
1054
|
+
}
|
|
1055
|
+
getActiveNudge() {
|
|
1056
|
+
return this.activeNudge;
|
|
1057
|
+
}
|
|
1058
|
+
async loadKillSwitch() {
|
|
1059
|
+
try {
|
|
1060
|
+
const e = await this.client.getHttp().get(ut);
|
|
1061
|
+
this.governor.setKillSwitch(e?.proactive?.enabled === !0);
|
|
1062
|
+
} catch (e) {
|
|
1063
|
+
l.debug("Proactive config fetch failed; staying disabled:", e), this.governor.setKillSwitch(!1);
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
evaluate() {
|
|
1067
|
+
if (this.lastEvaluationAt = Date.now(), typeof document < "u" && document.visibilityState === "hidden" || this.governor.isSlotOccupied()) return;
|
|
1068
|
+
const e = this.collector.getSnapshot();
|
|
1069
|
+
for (const t of this.options.triggers)
|
|
1070
|
+
if (ct(t.when, e) && this.governor.canFire(t)) {
|
|
1071
|
+
this.fire(t);
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
fire(e) {
|
|
1076
|
+
if (this.governor.recordFired(e.id), this.governor.occupySlot(), e.intervene === "agent") {
|
|
1077
|
+
this.evaluateWithAgent(e);
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
this.setReady({
|
|
1081
|
+
id: W(),
|
|
1082
|
+
triggerId: e.id,
|
|
1083
|
+
source: "static",
|
|
1084
|
+
message: e.intervene.message,
|
|
1085
|
+
action: e.intervene.action,
|
|
1086
|
+
goal: e.goal,
|
|
1087
|
+
kickoff: e.kickoff,
|
|
1088
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
async evaluateWithAgent(e) {
|
|
1092
|
+
const t = W(), s = {
|
|
1093
|
+
client_nudge_id: t,
|
|
1094
|
+
trigger_id: e.id,
|
|
1095
|
+
goal: e.goal ?? "",
|
|
1096
|
+
agent: this.client.getConfiguredAgent(),
|
|
1097
|
+
signals: this.collector.getSnapshot(),
|
|
1098
|
+
client_context: this.client.getContextSnapshot() ?? { entries: {} },
|
|
1099
|
+
client_functions: this.client.getRegisteredFunctions()
|
|
1100
|
+
};
|
|
1101
|
+
let i;
|
|
1102
|
+
try {
|
|
1103
|
+
i = await this.client.getHttp().post(dt, s);
|
|
1104
|
+
} catch (r) {
|
|
1105
|
+
l.debug("Proactive evaluate failed (treated as no-intervene):", r), this.governor.releaseSlot();
|
|
1106
|
+
return;
|
|
1107
|
+
}
|
|
1108
|
+
if (!i?.intervene || !i.message) {
|
|
1109
|
+
this.governor.releaseSlot();
|
|
1110
|
+
return;
|
|
1111
|
+
}
|
|
1112
|
+
this.setReady({
|
|
1113
|
+
id: t,
|
|
1114
|
+
triggerId: e.id,
|
|
1115
|
+
source: "agent",
|
|
1116
|
+
message: i.message,
|
|
1117
|
+
action: ft(i.action),
|
|
1118
|
+
goal: e.goal,
|
|
1119
|
+
kickoff: e.kickoff,
|
|
1120
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1121
|
+
serverNudgeId: i.nudge_id
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
setReady(e) {
|
|
1125
|
+
this.activeNudge = e, this.client.emitProactiveEvent("nudge:ready", e);
|
|
1126
|
+
}
|
|
1127
|
+
shown(e) {
|
|
1128
|
+
this.shownIds.has(e.id) || (this.shownIds.add(e.id), this.governor.recordNudgeShown(), this.tracker.track({
|
|
1129
|
+
clientNudgeId: e.id,
|
|
1130
|
+
triggerId: e.triggerId,
|
|
1131
|
+
source: e.source,
|
|
1132
|
+
type: "shown",
|
|
1133
|
+
message: e.message,
|
|
1134
|
+
occurredAt: Date.now()
|
|
1135
|
+
}), this.client.emitProactiveEvent("nudge:shown", { nudge: e }));
|
|
1136
|
+
}
|
|
1137
|
+
dismiss(e) {
|
|
1138
|
+
this.resolvedIds.has(e.id) || (this.resolvedIds.add(e.id), this.governor.recordDismissed(e.triggerId), this.tracker.track({
|
|
1139
|
+
clientNudgeId: e.id,
|
|
1140
|
+
triggerId: e.triggerId,
|
|
1141
|
+
source: e.source,
|
|
1142
|
+
type: "dismissed",
|
|
1143
|
+
occurredAt: Date.now()
|
|
1144
|
+
}), this.clearActive(e), this.client.emitProactiveEvent("nudge:dismissed", { nudge: e }));
|
|
1145
|
+
}
|
|
1146
|
+
async accept(e) {
|
|
1147
|
+
this.resolvedIds.has(e.id) || (this.resolvedIds.add(e.id), this.tracker.track({
|
|
1148
|
+
clientNudgeId: e.id,
|
|
1149
|
+
triggerId: e.triggerId,
|
|
1150
|
+
source: e.source,
|
|
1151
|
+
type: "accepted",
|
|
1152
|
+
occurredAt: Date.now()
|
|
1153
|
+
}), this.clearActive(e), this.client.emitProactiveEvent("nudge:accepted", { nudge: e }), (e.source === "agent" || e.goal) && (this.lastConversationId ? this.client.sendMessage(gt(e), {
|
|
1154
|
+
hidden: !0,
|
|
1155
|
+
conversationId: this.lastConversationId
|
|
1156
|
+
}).catch((t) => l.debug("Nudge kickoff message failed:", t)) : e.kickoff ? this.client.sendMessage(e.kickoff).catch((t) => l.debug("Nudge kickoff message failed:", t)) : l.debug("Nudge accepted with no open conversation and no trigger.kickoff; skipping the chat pre-seed (a hidden message cannot open a conversation).")), e.action && await this.runAction(e.action));
|
|
1157
|
+
}
|
|
1158
|
+
markConverted(e) {
|
|
1159
|
+
this.tracker.track({
|
|
1160
|
+
clientNudgeId: e.id,
|
|
1161
|
+
triggerId: e.triggerId,
|
|
1162
|
+
source: e.source,
|
|
1163
|
+
type: "converted",
|
|
1164
|
+
occurredAt: Date.now()
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
clearActive(e) {
|
|
1168
|
+
this.activeNudge?.id === e.id && (this.activeNudge = null), this.governor.releaseSlot();
|
|
1169
|
+
}
|
|
1170
|
+
async runAction(e) {
|
|
1171
|
+
try {
|
|
1172
|
+
"functionName" in e ? await this.client.executeClientFunction(e.functionName, e.arguments ?? {}) : await this.client.executeClientFunction("setPageState", e.setPageState);
|
|
1173
|
+
} catch (t) {
|
|
1174
|
+
l.warn("Nudge action failed:", t);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
};
|
|
1178
|
+
function ft(e) {
|
|
1179
|
+
if (e)
|
|
1180
|
+
return {
|
|
1181
|
+
label: e.label,
|
|
1182
|
+
functionName: e.function_name,
|
|
1183
|
+
arguments: e.arguments
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
function gt(e) {
|
|
1187
|
+
const t = e.goal ? ` Goal: ${e.goal}.` : "";
|
|
1188
|
+
return `The user accepted a proactive nudge that said: "${e.message}".${t} Recent friction signals are in the client context (friction_signals). Start helping with this now: briefly explain what you can do and take the first concrete step.`;
|
|
1189
|
+
}
|
|
1190
|
+
var mt = 5e3, pt = "/api/sdk/v1/proactive/events", yt = class {
|
|
1191
|
+
constructor(e) {
|
|
1192
|
+
if (this.queue = [], this.flushTimer = null, this.teardowns = [], this.destroyed = !1, this.post = e.post, this.agent = e.agent, this.flushIntervalMs = e.flushIntervalMs ?? mt, typeof document < "u") {
|
|
1193
|
+
const t = () => {
|
|
1194
|
+
document.visibilityState === "hidden" && this.flush({ keepalive: !0 });
|
|
1195
|
+
};
|
|
1196
|
+
document.addEventListener("visibilitychange", t), this.teardowns.push(() => document.removeEventListener("visibilitychange", t));
|
|
1197
|
+
}
|
|
1198
|
+
if (typeof window < "u") {
|
|
1199
|
+
const t = () => this.flush({ keepalive: !0 });
|
|
1200
|
+
window.addEventListener("pagehide", t), this.teardowns.push(() => window.removeEventListener("pagehide", t));
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
track(e) {
|
|
1204
|
+
this.destroyed || (this.queue.push(e), this.flushTimer === null && (this.flushTimer = setTimeout(() => this.flush(), this.flushIntervalMs)));
|
|
1205
|
+
}
|
|
1206
|
+
flush(e) {
|
|
1207
|
+
if (this.flushTimer !== null && (clearTimeout(this.flushTimer), this.flushTimer = null), this.queue.length === 0) return;
|
|
1208
|
+
const t = this.queue;
|
|
1209
|
+
this.queue = [];
|
|
1210
|
+
const s = { events: t.map((i) => ({
|
|
1211
|
+
client_nudge_id: i.clientNudgeId,
|
|
1212
|
+
trigger_id: i.triggerId,
|
|
1213
|
+
source: i.source,
|
|
1214
|
+
type: i.type,
|
|
1215
|
+
...i.message !== void 0 ? { message: i.message } : {},
|
|
1216
|
+
...this.agent ? { agent: this.agent } : {},
|
|
1217
|
+
occurred_at: new Date(i.occurredAt).toISOString()
|
|
1218
|
+
})) };
|
|
1219
|
+
this.post(pt, s, e).catch((i) => {
|
|
1220
|
+
l.debug("Proactive event batch failed:", i);
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1223
|
+
destroy() {
|
|
1224
|
+
if (!this.destroyed) {
|
|
1225
|
+
this.flush({ keepalive: !0 }), this.destroyed = !0;
|
|
1226
|
+
for (const e of this.teardowns) e();
|
|
1227
|
+
this.teardowns = [];
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}, ie = "friction_signals";
|
|
1231
|
+
function re(e, t) {
|
|
1232
|
+
e.proactive && (l.warn("createAgoProactive: a proactive controller is already attached; replacing it."), e.proactive.destroy());
|
|
1233
|
+
const s = new et({
|
|
1234
|
+
...t.signals,
|
|
1235
|
+
getPageState: () => {
|
|
1236
|
+
const c = e.getContextSnapshot();
|
|
1237
|
+
if (!c) return null;
|
|
1238
|
+
const u = {};
|
|
1239
|
+
for (const [d, g] of Object.entries(c.entries)) d.startsWith("page-state:") && g.data && Object.assign(u, g.data);
|
|
1240
|
+
return Object.keys(u).length > 0 ? u : null;
|
|
1241
|
+
}
|
|
1242
|
+
});
|
|
1243
|
+
s.start();
|
|
1244
|
+
const i = (c) => {
|
|
1245
|
+
s.signalJsError(c.type);
|
|
1246
|
+
};
|
|
1247
|
+
e.on("error:captured", i), e.addDynamicContext(ie, () => {
|
|
1248
|
+
const { pageState: c, ...u } = s.getSnapshot({ pageState: !1 });
|
|
1249
|
+
return {
|
|
1250
|
+
name: "Friction signals",
|
|
1251
|
+
description: "Behavioral friction observed on the current page: dwell/idle times, rage clicks, route bounces, repeated field errors, JavaScript error count (names and counters only).",
|
|
1252
|
+
data: u
|
|
1253
|
+
};
|
|
1254
|
+
});
|
|
1255
|
+
const r = new nt({
|
|
1256
|
+
frequencyCap: t.frequencyCap,
|
|
1257
|
+
storage: t.storage,
|
|
1258
|
+
storageKey: t.storageKey
|
|
1259
|
+
}), n = new yt({
|
|
1260
|
+
post: (c, u, d) => e.getHttp().post(c, u, d),
|
|
1261
|
+
agent: e.getConfiguredAgent()
|
|
1262
|
+
}), a = new ht({
|
|
1263
|
+
client: e,
|
|
1264
|
+
collector: s,
|
|
1265
|
+
governor: r,
|
|
1266
|
+
tracker: n,
|
|
1267
|
+
options: t
|
|
1268
|
+
});
|
|
1269
|
+
a.start();
|
|
1270
|
+
const o = {
|
|
1271
|
+
optOut: () => r.optOut(),
|
|
1272
|
+
optIn: () => r.optIn(),
|
|
1273
|
+
isOptedOut: () => r.isOptedOut(),
|
|
1274
|
+
setEngaged: (c) => r.setEngaged(c),
|
|
1275
|
+
signalFieldError: (c) => s.signalFieldError(c),
|
|
1276
|
+
getSignalsSnapshot: () => s.getSnapshot(),
|
|
1277
|
+
getActiveNudge: () => a.getActiveNudge(),
|
|
1278
|
+
shown: (c) => a.shown(c),
|
|
1279
|
+
accept: (c) => a.accept(c),
|
|
1280
|
+
dismiss: (c) => a.dismiss(c),
|
|
1281
|
+
markConverted: (c) => a.markConverted(c),
|
|
1282
|
+
destroy: () => {
|
|
1283
|
+
a.stop(), n.destroy(), e.off("error:captured", i), s.destroy(), e.removeDynamicContext(ie), e.proactive === o && (e.proactive = null);
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
return e.proactive = o, o;
|
|
1287
|
+
}
|
|
1288
|
+
var vt = class {
|
|
1289
|
+
constructor() {
|
|
1290
|
+
this.entries = /* @__PURE__ */ new Map(), this.dynamicProviders = /* @__PURE__ */ new Map();
|
|
1291
|
+
}
|
|
1292
|
+
set(e, t) {
|
|
1293
|
+
this.entries.set(e, t), l.log(`ClientContext set: ${e}`);
|
|
1294
|
+
}
|
|
1295
|
+
remove(e) {
|
|
1296
|
+
const t = this.entries.delete(e);
|
|
1297
|
+
return t && l.log(`ClientContext removed: ${e}`), t;
|
|
1298
|
+
}
|
|
1299
|
+
addDynamicProvider(e, t) {
|
|
1300
|
+
this.dynamicProviders.set(e, t), l.log(`DynamicContext provider added: ${e}`);
|
|
1301
|
+
}
|
|
1302
|
+
removeDynamicProvider(e) {
|
|
1303
|
+
const t = this.dynamicProviders.delete(e);
|
|
1304
|
+
return t && l.log(`DynamicContext provider removed: ${e}`), t;
|
|
1305
|
+
}
|
|
1306
|
+
getSnapshot() {
|
|
1307
|
+
if (this.entries.size === 0 && this.dynamicProviders.size === 0) return null;
|
|
1308
|
+
const e = {};
|
|
1309
|
+
for (const [t, s] of this.entries) e[t] = s;
|
|
1310
|
+
for (const [t, s] of this.dynamicProviders) try {
|
|
1311
|
+
const i = s();
|
|
1312
|
+
i && (e[t] = i);
|
|
1313
|
+
} catch (i) {
|
|
1314
|
+
l.error(`DynamicContext provider "${t}" threw:`, i);
|
|
1315
|
+
}
|
|
1316
|
+
return Object.keys(e).length === 0 ? null : { entries: e };
|
|
1317
|
+
}
|
|
1318
|
+
clear() {
|
|
1319
|
+
this.entries.clear(), this.dynamicProviders.clear(), l.log("ClientContext cleared");
|
|
1320
|
+
}
|
|
1321
|
+
}, wt = "page-state:";
|
|
1322
|
+
function Et(e) {
|
|
1323
|
+
const t = {};
|
|
1324
|
+
for (const [s, i] of Object.entries(e)) s.startsWith(wt) && i.data && Object.assign(t, i.data);
|
|
1325
|
+
return t;
|
|
1326
|
+
}
|
|
1327
|
+
function bt(e) {
|
|
1328
|
+
const t = e["current-page"]?.data;
|
|
1329
|
+
return t?.page ? t.page : t?.url ? t.url : e["browser-page"]?.data?.url;
|
|
1330
|
+
}
|
|
1331
|
+
function St(e, t) {
|
|
1332
|
+
return e === t ? !0 : JSON.stringify(e) === JSON.stringify(t);
|
|
1333
|
+
}
|
|
1334
|
+
function Ct(e, t) {
|
|
1335
|
+
const s = [];
|
|
1336
|
+
for (const i of Object.keys(t))
|
|
1337
|
+
i in e && (St(e[i], t[i]) || s.push({
|
|
1338
|
+
field: i,
|
|
1339
|
+
from: e[i],
|
|
1340
|
+
to: t[i]
|
|
1341
|
+
}));
|
|
1342
|
+
return s;
|
|
1343
|
+
}
|
|
1344
|
+
function _t(e, t) {
|
|
1345
|
+
const s = Et(t), i = bt(t);
|
|
1346
|
+
return {
|
|
1347
|
+
changes: e && e.page === i ? Ct(e.state, s) : [],
|
|
1348
|
+
baseline: {
|
|
1349
|
+
page: i,
|
|
1350
|
+
state: s
|
|
1351
|
+
}
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
function B(e) {
|
|
1355
|
+
return e === null || typeof e != "object" ? JSON.stringify(e) ?? "null" : Array.isArray(e) ? `[${e.map(B).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${B(e[t])}`).join(",")}}`;
|
|
1356
|
+
}
|
|
1357
|
+
var ne = "", At = class {
|
|
1358
|
+
constructor(e, t = {}) {
|
|
1359
|
+
this.callbacks = e, this.options = t, this.buffer = "", this.message = {}, this.toolCalls = [], this.sources = [], this.followUpReplies = [], this.isFirstChunk = !0, this.answerCompleteEmitted = !1, this.waitingClientEmitted = !1, this.firedClientFunctions = /* @__PURE__ */ new Map();
|
|
1360
|
+
}
|
|
1361
|
+
async processStream(e) {
|
|
1362
|
+
if (!e.body) throw new K("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");
|
|
1363
|
+
const t = e.body.getReader(), s = new TextDecoder();
|
|
1364
|
+
try {
|
|
1365
|
+
for (; ; ) {
|
|
1366
|
+
const { done: i, value: r } = await t.read();
|
|
1367
|
+
if (i) break;
|
|
1368
|
+
const n = s.decode(r, { stream: !0 });
|
|
1369
|
+
this.buffer += n, this.processBuffer();
|
|
1370
|
+
}
|
|
1371
|
+
return this.buffer.trim() && this.processBuffer(), this.buildFinalMessage();
|
|
1372
|
+
} catch (i) {
|
|
1373
|
+
if (this.options.signal?.aborted)
|
|
1374
|
+
return this.message.status = "CANCELED", this.buildFinalMessage();
|
|
1375
|
+
const r = i instanceof Error ? i : new K("Stream processing failed mid-flight. The connection may have dropped; retry the message.");
|
|
1376
|
+
throw this.callbacks.onError?.(r), r;
|
|
1377
|
+
} finally {
|
|
1378
|
+
t.releaseLock();
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
processBuffer() {
|
|
1382
|
+
const e = this.buffer.split(`
|
|
1383
|
+
|
|
1384
|
+
`);
|
|
1385
|
+
this.buffer = e.pop() || "";
|
|
1386
|
+
for (const t of e) {
|
|
1387
|
+
if (!t.trim()) continue;
|
|
1388
|
+
const s = t.split(`
|
|
1389
|
+
`);
|
|
1390
|
+
for (const i of s)
|
|
1391
|
+
if (!i.startsWith(": ") && i.startsWith("data: ")) {
|
|
1392
|
+
const r = i.slice(6);
|
|
1393
|
+
try {
|
|
1394
|
+
const n = JSON.parse(r);
|
|
1395
|
+
this.handleChunk(n);
|
|
1396
|
+
} catch (n) {
|
|
1397
|
+
l.warn("Failed to parse SSE data:", r, n);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
handleChunk(e) {
|
|
1403
|
+
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?.({
|
|
1404
|
+
conversationId: this.message.conversationId,
|
|
1405
|
+
messageId: this.message.id
|
|
1406
|
+
}))), e.title && this.message.conversationId && this.callbacks.onTitle?.({
|
|
1407
|
+
conversationId: this.message.conversationId,
|
|
1408
|
+
title: e.title
|
|
1409
|
+
}), e.content !== void 0 && (this.message.content = (this.message.content || "") + e.content, this.message.conversationId && this.message.id && this.callbacks.onChunk?.({
|
|
1410
|
+
content: e.content,
|
|
1411
|
+
conversationId: this.message.conversationId,
|
|
1412
|
+
messageId: this.message.id
|
|
1413
|
+
})), e.full_content !== void 0 && (this.message.content = e.full_content), e.status && (this.message.status = e.status), e.agent && (this.message.agent = {
|
|
1414
|
+
id: e.agent.id,
|
|
1415
|
+
name: e.agent.name,
|
|
1416
|
+
displayName: e.agent.display_name
|
|
1417
|
+
}), e.knowledge_sources && (this.sources = e.knowledge_sources.map((t) => {
|
|
1418
|
+
const s = t.knowledge_document;
|
|
1419
|
+
return {
|
|
1420
|
+
id: s.id,
|
|
1421
|
+
title: s.title,
|
|
1422
|
+
url: s.use_external_link ? s.external_link_url : s.internal_link_url
|
|
1423
|
+
};
|
|
1424
|
+
})), e.type === "client_function" && e.function_name) {
|
|
1425
|
+
const t = `${e.function_name}::${B(e.arguments ?? {})}`, s = e.id || "", i = this.firedClientFunctions.get(t);
|
|
1426
|
+
let r = !1;
|
|
1427
|
+
i ? s && !i.has(s) && (i.has(ne) ? (i.delete(ne), i.add(s)) : (i.add(s), r = !0)) : (this.firedClientFunctions.set(t, /* @__PURE__ */ new Set([s])), r = !0), r && this.callbacks.onClientFunction?.({
|
|
1428
|
+
invocationId: s,
|
|
1429
|
+
functionName: e.function_name,
|
|
1430
|
+
arguments: e.arguments || {},
|
|
1431
|
+
conversationId: this.message.conversationId || ""
|
|
1432
|
+
});
|
|
1433
|
+
}
|
|
1434
|
+
if (e.tool_call_data && e.type && e.type !== "client_function") {
|
|
1435
|
+
const t = this.parseToolCall(e);
|
|
1436
|
+
this.callbacks.onToolCall?.(t);
|
|
1437
|
+
const s = this.toolCalls.findIndex((i) => i.id === t.id);
|
|
1438
|
+
s >= 0 ? this.toolCalls[s] = t : this.toolCalls.push(t);
|
|
1439
|
+
}
|
|
1440
|
+
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())), this.message.status === "WAITING_CLIENT" && !this.waitingClientEmitted && this.message.id && (this.waitingClientEmitted = !0, this.callbacks.onWaitingClient?.({
|
|
1441
|
+
conversationId: this.message.conversationId || "",
|
|
1442
|
+
messageId: this.message.id,
|
|
1443
|
+
waitingToolCallIds: e.waiting_tool_call_ids ?? []
|
|
1444
|
+
}));
|
|
1445
|
+
}
|
|
1446
|
+
parseToolCall(e) {
|
|
1447
|
+
return {
|
|
1448
|
+
id: e.id || "",
|
|
1449
|
+
type: e.type || "status_message",
|
|
1450
|
+
status: e.status || "unknown",
|
|
1451
|
+
toolName: e.tool_name || "",
|
|
1452
|
+
toolDisplayName: e.tool_display_name,
|
|
1453
|
+
message: e.message,
|
|
1454
|
+
formSchema: e.form_schema,
|
|
1455
|
+
data: e.data,
|
|
1456
|
+
functionName: e.function_name,
|
|
1457
|
+
arguments: e.arguments,
|
|
1458
|
+
displayMode: e.display_mode,
|
|
1459
|
+
askToTalkToHuman: e.ask_to_talk_to_human,
|
|
1460
|
+
allowedToCreateTicket: e.allowed_to_create_ticket,
|
|
1461
|
+
ticket: e.ticket,
|
|
1462
|
+
mode: e.mode,
|
|
1463
|
+
ticketFormId: e.ticket_form_id,
|
|
1464
|
+
embedHtml: e.embed_html,
|
|
1465
|
+
embedDescription: e.embed_description
|
|
1466
|
+
};
|
|
1467
|
+
}
|
|
1468
|
+
buildMessage() {
|
|
1469
|
+
return {
|
|
1470
|
+
id: this.message.id || "",
|
|
1471
|
+
conversationId: this.message.conversationId || "",
|
|
1472
|
+
content: this.message.content || "",
|
|
1473
|
+
role: "assistant",
|
|
1474
|
+
status: this.message.status || "DONE",
|
|
1475
|
+
agent: this.message.agent,
|
|
1476
|
+
sources: this.sources.length > 0 ? this.sources : void 0,
|
|
1477
|
+
toolCalls: this.toolCalls.length > 0 ? this.toolCalls : void 0,
|
|
1478
|
+
followUpReplies: this.followUpReplies.length > 0 ? this.followUpReplies : void 0,
|
|
1479
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1480
|
+
};
|
|
1481
|
+
}
|
|
1482
|
+
buildFinalMessage() {
|
|
1483
|
+
const e = this.buildMessage();
|
|
1484
|
+
return e.status !== "WAITING_CLIENT" && this.callbacks.onComplete?.(e), e;
|
|
1485
|
+
}
|
|
1486
|
+
};
|
|
1487
|
+
function Kt(e) {
|
|
1488
|
+
const t = e.message.toLowerCase();
|
|
1489
|
+
return t.includes("load failed") || t.includes("failed to fetch") || t.includes("network") || t.includes("abort");
|
|
1490
|
+
}
|
|
1491
|
+
var kt = /* @__PURE__ */ new Set([
|
|
1492
|
+
"image/jpeg",
|
|
1493
|
+
"image/png",
|
|
1494
|
+
"image/gif",
|
|
1495
|
+
"image/webp",
|
|
1496
|
+
"image/bmp",
|
|
1497
|
+
"image/tiff"
|
|
1498
|
+
]);
|
|
1499
|
+
function Rt(e) {
|
|
1500
|
+
if (!e) return;
|
|
1501
|
+
const t = typeof window < "u" && window.location ? window.location.href : "https://ago.local/";
|
|
1502
|
+
try {
|
|
1503
|
+
const s = new URL(e, t);
|
|
1504
|
+
if (s.protocol === "http:" || s.protocol === "https:" || s.protocol === "blob:") return e;
|
|
1505
|
+
} catch {
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
function Ht(e) {
|
|
1509
|
+
return e.isSafeImage === !0 && typeof e.contentType == "string" && e.contentType.startsWith("image/") && Rt(e.url) !== void 0;
|
|
1510
|
+
}
|
|
1511
|
+
function Xt(e) {
|
|
1512
|
+
if (e == null || e < 0) return "";
|
|
1513
|
+
if (e < 1024) return `${e} B`;
|
|
1514
|
+
const t = e / 1024;
|
|
1515
|
+
return t < 1024 ? `${t.toFixed(1)} KB` : `${(t / 1024).toFixed(1)} MB`;
|
|
1516
|
+
}
|
|
1517
|
+
function Tt(e) {
|
|
1518
|
+
return {
|
|
1519
|
+
id: String(e.id ?? ""),
|
|
1520
|
+
name: typeof e.name == "string" && e.name ? e.name : "file",
|
|
1521
|
+
contentType: typeof e.content_type == "string" ? e.content_type : void 0,
|
|
1522
|
+
fileSize: typeof e.file_size == "number" ? e.file_size : void 0,
|
|
1523
|
+
url: typeof e.file_url == "string" ? e.file_url : void 0,
|
|
1524
|
+
isSafeImage: e.is_safe_image === !0
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
function zt(e) {
|
|
1528
|
+
return e.map((t, s) => ({
|
|
1529
|
+
id: `local-${s}-${t.name}`,
|
|
1530
|
+
name: t.name,
|
|
1531
|
+
contentType: t.type || void 0,
|
|
1532
|
+
fileSize: t.size,
|
|
1533
|
+
url: typeof URL < "u" && URL.createObjectURL ? URL.createObjectURL(t) : void 0,
|
|
1534
|
+
isSafeImage: kt.has(t.type)
|
|
1535
|
+
}));
|
|
1536
|
+
}
|
|
1537
|
+
var It = class {
|
|
1538
|
+
constructor() {
|
|
1539
|
+
this.handlers = /* @__PURE__ */ new Map();
|
|
1540
|
+
}
|
|
1541
|
+
on(e, t) {
|
|
1542
|
+
this.handlers.has(e) || this.handlers.set(e, /* @__PURE__ */ new Set()), this.handlers.get(e).add(t);
|
|
1543
|
+
}
|
|
1544
|
+
off(e, t) {
|
|
1545
|
+
const s = this.handlers.get(e);
|
|
1546
|
+
s && s.delete(t);
|
|
1547
|
+
}
|
|
1548
|
+
emit(e, t) {
|
|
1549
|
+
const s = this.handlers.get(e);
|
|
1550
|
+
s && s.forEach((i) => {
|
|
1551
|
+
try {
|
|
1552
|
+
i(t);
|
|
1553
|
+
} catch (r) {
|
|
1554
|
+
console.error(`Error in event handler for ${String(e)}:`, r);
|
|
1555
|
+
}
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
once(e, t) {
|
|
1559
|
+
const s = ((i) => {
|
|
1560
|
+
this.off(e, s), t(i);
|
|
1561
|
+
});
|
|
1562
|
+
this.on(e, s);
|
|
1563
|
+
}
|
|
1564
|
+
waitFor(e, t) {
|
|
1565
|
+
return new Promise((s, i) => {
|
|
1566
|
+
let r;
|
|
1567
|
+
const n = ((a) => {
|
|
1568
|
+
r && clearTimeout(r), s(a);
|
|
1569
|
+
});
|
|
1570
|
+
this.once(e, n), t?.timeout && (r = setTimeout(() => {
|
|
1571
|
+
this.off(e, n), i(/* @__PURE__ */ new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`));
|
|
1572
|
+
}, t.timeout));
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
removeAllListeners(e) {
|
|
1576
|
+
e ? this.handlers.delete(e) : this.handlers.clear();
|
|
1577
|
+
}
|
|
1578
|
+
}, xt = 4e3, Ft = 150, Mt = 600;
|
|
1579
|
+
function Dt() {
|
|
1580
|
+
if (!(typeof document > "u"))
|
|
1581
|
+
return document.modelContext;
|
|
1582
|
+
}
|
|
1583
|
+
function $t(e, t) {
|
|
1584
|
+
return new Promise((s) => {
|
|
1585
|
+
let i, r = !1;
|
|
1586
|
+
const n = () => {
|
|
1587
|
+
if (!r) {
|
|
1588
|
+
r = !0, clearTimeout(i), clearTimeout(c), clearTimeout(o);
|
|
1589
|
+
for (const d of t) d?.removeEventListener("abort", n);
|
|
1590
|
+
u(), s();
|
|
1591
|
+
}
|
|
1592
|
+
}, a = () => {
|
|
1593
|
+
clearTimeout(c), clearTimeout(i), i = setTimeout(n, Ft);
|
|
1594
|
+
}, o = setTimeout(n, xt), c = setTimeout(n, Mt), u = e(a);
|
|
1595
|
+
for (const d of t) {
|
|
1596
|
+
if (d?.aborted) return n();
|
|
1597
|
+
d?.addEventListener("abort", n);
|
|
1598
|
+
}
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
function Pt(e) {
|
|
1602
|
+
const t = Dt();
|
|
1603
|
+
if (!t)
|
|
1604
|
+
return l.log("WebMCP is not available in this browser; bridge not attached"), () => {
|
|
1605
|
+
};
|
|
1606
|
+
const s = t, i = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Set(), n = new AbortController();
|
|
1607
|
+
let a = !1, o = !1;
|
|
1608
|
+
function c(f) {
|
|
1609
|
+
return JSON.stringify([
|
|
1610
|
+
f.description,
|
|
1611
|
+
f.inputSchema,
|
|
1612
|
+
f.annotations
|
|
1613
|
+
]);
|
|
1614
|
+
}
|
|
1615
|
+
function u(f, h) {
|
|
1616
|
+
const p = e.getFunctionRegistrations().find((y) => y.name === f)?.webmcp;
|
|
1617
|
+
return !p || !p.navigates ? !1 : h?.success !== !1;
|
|
1618
|
+
}
|
|
1619
|
+
function d() {
|
|
1620
|
+
const f = /* @__PURE__ */ new Map();
|
|
1621
|
+
for (const h of e.getFunctionRegistrations()) {
|
|
1622
|
+
if (h.webmcp === !1) continue;
|
|
1623
|
+
const p = h.webmcp || void 0, y = h.name, b = {
|
|
1624
|
+
name: y,
|
|
1625
|
+
description: h.schema.description,
|
|
1626
|
+
inputSchema: h.schema.parameters,
|
|
1627
|
+
annotations: p?.annotations,
|
|
1628
|
+
execute: async (w, ve) => {
|
|
1629
|
+
const J = await e.runExternalFunction(y, w ?? {});
|
|
1630
|
+
return !a && u(y, J) && await $t((we) => e.onFunctionsChanged(we), [ve?.signal, n.signal]), J;
|
|
1631
|
+
}
|
|
1632
|
+
};
|
|
1633
|
+
f.set(y, {
|
|
1634
|
+
tool: b,
|
|
1635
|
+
signature: c(b)
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1638
|
+
return f;
|
|
1639
|
+
}
|
|
1640
|
+
function g() {
|
|
1641
|
+
a || o || (o = !0, queueMicrotask(() => {
|
|
1642
|
+
o = !1, m();
|
|
1643
|
+
}));
|
|
1644
|
+
}
|
|
1645
|
+
function m() {
|
|
1646
|
+
if (a) return;
|
|
1647
|
+
const f = d();
|
|
1648
|
+
for (const [h, p] of i)
|
|
1649
|
+
f.get(h)?.signature !== p.signature && (p.controller.abort(), i.delete(h));
|
|
1650
|
+
for (const [h, p] of f) {
|
|
1651
|
+
if (i.has(h)) continue;
|
|
1652
|
+
const y = new AbortController();
|
|
1653
|
+
i.set(h, {
|
|
1654
|
+
signature: p.signature,
|
|
1655
|
+
controller: y
|
|
1656
|
+
}), Promise.resolve(s.registerTool(p.tool, { signal: y.signal })).catch((b) => {
|
|
1657
|
+
if (l.error(`WebMCP rejected the tool "${h}":`, b), i.get(h)?.controller !== y) return;
|
|
1658
|
+
i.delete(h);
|
|
1659
|
+
const w = JSON.stringify([h, p.signature]);
|
|
1660
|
+
r.has(w) || (r.add(w), g());
|
|
1661
|
+
});
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
const v = e.onFunctionsChanged(g);
|
|
1665
|
+
return m(), l.log("WebMCP bridge attached"), () => {
|
|
1666
|
+
if (!a) {
|
|
1667
|
+
a = !0, n.abort(), v();
|
|
1668
|
+
for (const f of i.values()) f.controller.abort();
|
|
1669
|
+
i.clear(), l.log("WebMCP bridge detached");
|
|
1670
|
+
}
|
|
1671
|
+
};
|
|
1672
|
+
}
|
|
1673
|
+
var oe = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the public demo account https://playground.api.useago.com (agent generic-guide). See docs/general/configuration.md#error-codes (config_missing_base_url).', Nt = /^[a-z][a-z0-9+.-]*:\/\//i, ae = !1;
|
|
1674
|
+
function ce(e, t = "AgoClient") {
|
|
1675
|
+
if (typeof e != "object" || e === null) throw new C(`${t}: ${oe}`, "config_missing_base_url");
|
|
1676
|
+
const s = e.baseUrl;
|
|
1677
|
+
if (typeof s != "string" || s.trim() === "") throw new C(`${t}: ${oe}`, "config_missing_base_url");
|
|
1678
|
+
$(e.language), !s.startsWith("/") && !Nt.test(s) && (ae || (ae = !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).`)));
|
|
1679
|
+
}
|
|
1680
|
+
function Ot(e) {
|
|
1681
|
+
return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1682
|
+
}
|
|
1683
|
+
function M(e) {
|
|
1684
|
+
return e.split("/").filter((t) => t.startsWith(":")).map((t) => t.slice(1));
|
|
1685
|
+
}
|
|
1686
|
+
function jt(e, t) {
|
|
1687
|
+
const s = [];
|
|
1688
|
+
return {
|
|
1689
|
+
path: e.split("/").map((i) => {
|
|
1690
|
+
if (!i.startsWith(":")) return i;
|
|
1691
|
+
const r = i.slice(1), n = t[r];
|
|
1692
|
+
return n == null || n === "" ? (s.push(r), i) : encodeURIComponent(String(n));
|
|
1693
|
+
}).join("/"),
|
|
1694
|
+
missing: s
|
|
1695
|
+
};
|
|
1696
|
+
}
|
|
1697
|
+
function Lt(e, t) {
|
|
1698
|
+
const s = t.find((r) => r.path === e);
|
|
1699
|
+
if (s) return s;
|
|
1700
|
+
const i = t.find((r) => {
|
|
1701
|
+
if (!r.path.includes(":")) return !1;
|
|
1702
|
+
const n = "^" + r.path.split("/").map((a) => a.startsWith(":") ? "[^/]+" : Ot(a)).join("/") + "/?$";
|
|
1703
|
+
return new RegExp(n).test(e);
|
|
1704
|
+
});
|
|
1705
|
+
return i || t.filter((r) => r.path !== "/" && e.startsWith(r.path)).sort((r, n) => n.path.length - r.path.length)[0];
|
|
1706
|
+
}
|
|
1707
|
+
var Ut = "activity:recent", Wt = "state:delta", le = "errors:recent";
|
|
1708
|
+
function ue(e) {
|
|
1709
|
+
return e === "setPageState" ? "readPageData" : `read${e.charAt(0).toUpperCase()}${e.slice(1)}Data`;
|
|
1710
|
+
}
|
|
1711
|
+
var Vt = class k {
|
|
1712
|
+
constructor(t) {
|
|
1713
|
+
this.errorWatcher = null, this.lastSentPageState = null, this.warnedEmptyConversations = /* @__PURE__ */ new Set(), this.warnedPageDataPlaceholder = !1, this.pageDataCompanions = /* @__PURE__ */ new Set(), this.pendingResumes = /* @__PURE__ */ new Map(), this.pendingApprovals = /* @__PURE__ */ new Map(), this.resumeGate = null, this.activeTurn = null, this.pausedTurn = null, this.stoppedTurnIds = /* @__PURE__ */ new Set(), this.proactive = null, this.detachWebMCP = null, ce(t, "AgoClient"), this.config = t, this.activityLedger = new be(t.maxActivityEntries), this.httpClient = new _e(t), this.functionRegistry = new Me({ maxResultBytes: t.maxFunctionResultBytes }), this.contextRegistry = new vt(), this.eventEmitter = new It(), this.registerActivityContext(), this.functionRegistry.onChange(() => {
|
|
1714
|
+
this.eventEmitter.emit("functions:changed", this.functionRegistry.getSchemas());
|
|
1715
|
+
}), t.debug && l.enable(), t.errorWatcher && this.enableErrorWatcher(t.errorWatcher === !0 ? void 0 : t.errorWatcher), t.proactive && re(this, t.proactive), this.attachWebMCPBridge(), l.log("AgoClient initialized");
|
|
1716
|
+
}
|
|
1717
|
+
attachWebMCPBridge() {
|
|
1718
|
+
!this.config.webmcp || this.detachWebMCP || (this.detachWebMCP = Pt(this));
|
|
1719
|
+
}
|
|
1720
|
+
async sendMessage(t, s) {
|
|
1721
|
+
const i = this.functionRegistry.getSchemas(), r = this.buildSendContext(), n = this.config.agent || this.config.defaultAgentId, a = this.resolveClientFunctionsMode(s), o = s?.metadata !== void 0 ? s.metadata : this.config.metadata, c = o != null ? JSON.stringify(o) : void 0, u = {
|
|
1722
|
+
content: t,
|
|
1723
|
+
conversation_id: s?.conversationId,
|
|
1724
|
+
agent_id: s?.agentId || n
|
|
1725
|
+
};
|
|
1726
|
+
o != null && (u.metadata = o), i.length > 0 && (u.client_functions = i, a === "pause" && (u.client_functions_mode = a)), r && (u.client_context = r), s?.hidden && (u.hidden = !0);
|
|
1727
|
+
const d = this.beginTurn();
|
|
1728
|
+
let g;
|
|
1729
|
+
if (s?.files && s.files.length > 0) {
|
|
1730
|
+
const m = new FormData();
|
|
1731
|
+
m.append("content", t), c !== void 0 && m.append("metadata", c), s.conversationId && m.append("conversation_id", s.conversationId), (s.agentId || n) && m.append("agent_id", s.agentId || n || ""), i.length > 0 && (m.append("client_functions", JSON.stringify(i)), a === "pause" && m.append("client_functions_mode", a)), r && m.append("client_context", JSON.stringify(r)), s.hidden && m.append("hidden", "true");
|
|
1732
|
+
for (const v of s.files) m.append("files", v);
|
|
1733
|
+
g = await this.sendRequest(d, () => this.httpClient.postFormData("/api/sdk/v1/messages", m, { signal: d.controller.signal }));
|
|
1734
|
+
} else g = await this.sendRequest(d, () => this.httpClient.postStream("/api/sdk/v1/messages", u, { signal: d.controller.signal }));
|
|
1735
|
+
return g ? this.processSSEResponse(g, d) : this.buildStoppedMessage(d);
|
|
1736
|
+
}
|
|
1737
|
+
async sendRequest(t, s) {
|
|
1738
|
+
try {
|
|
1739
|
+
return await s();
|
|
1740
|
+
} catch (i) {
|
|
1741
|
+
if (this.endTurn(t), P(i)) return null;
|
|
1742
|
+
throw i;
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
async processSSEResponse(t, s) {
|
|
1746
|
+
let i = !1;
|
|
1747
|
+
const r = new At({
|
|
1748
|
+
onRawChunk: (n) => {
|
|
1749
|
+
s && (n.message_id && !s.messageId && (s.messageId = n.message_id), n.thread?.id && (s.conversationId = n.thread.id)), this.eventEmitter.emit("stream:message", n);
|
|
1750
|
+
},
|
|
1751
|
+
onStart: (n) => {
|
|
1752
|
+
this.eventEmitter.emit("message:start", n);
|
|
1753
|
+
},
|
|
1754
|
+
onChunk: (n) => {
|
|
1755
|
+
this.eventEmitter.emit("message:chunk", n);
|
|
1756
|
+
},
|
|
1757
|
+
onToolCall: (n) => {
|
|
1758
|
+
this.eventEmitter.emit("toolCall:received", n), n.type === "form" && this.eventEmitter.emit("toolCall:form", n);
|
|
1759
|
+
},
|
|
1760
|
+
onClientFunction: async (n) => {
|
|
1761
|
+
if (i = !0, this.eventEmitter.emit("function:invoke", n), this.recordAgentAction(n), n.invocationId && this.requiresApproval(n)) {
|
|
1762
|
+
this.pendingApprovals.set(n.invocationId, n), this.eventEmitter.emit("function:awaiting-approval", n);
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
await this.handleClientFunctionInvocation(n);
|
|
1766
|
+
},
|
|
1767
|
+
onTitle: (n) => {
|
|
1768
|
+
this.eventEmitter.emit("conversation:title", n);
|
|
1769
|
+
},
|
|
1770
|
+
onAnswerComplete: (n) => {
|
|
1771
|
+
this.eventEmitter.emit("message:answer-complete", n);
|
|
1772
|
+
},
|
|
1773
|
+
onWaitingClient: (n) => {
|
|
1774
|
+
this.pausedTurn = {
|
|
1775
|
+
messageId: n.messageId,
|
|
1776
|
+
conversationId: n.conversationId
|
|
1777
|
+
}, this.eventEmitter.emit("message:waiting-client", n), this.markResumeSignal(n.messageId, n.conversationId, "waitingConfirmed");
|
|
1778
|
+
},
|
|
1779
|
+
onComplete: (n) => {
|
|
1780
|
+
s?.stopRequested && !n.id || this.eventEmitter.emit("message:complete", n);
|
|
1781
|
+
},
|
|
1782
|
+
onError: (n) => {
|
|
1783
|
+
this.eventEmitter.emit("message:error", {
|
|
1784
|
+
error: n.message,
|
|
1785
|
+
code: n instanceof C ? n.code : void 0
|
|
1786
|
+
});
|
|
1787
|
+
}
|
|
1788
|
+
}, { signal: s?.controller.signal });
|
|
1789
|
+
try {
|
|
1790
|
+
const n = await r.processStream(t);
|
|
1791
|
+
return s?.stopRequested && (this.postStopForTurn(s, s.messageId ?? n.id), this.eventEmitter.emit("message:stopped", {
|
|
1792
|
+
conversationId: s.conversationId ?? n.conversationId ?? "",
|
|
1793
|
+
messageId: s.messageId ?? n.id ?? ""
|
|
1794
|
+
})), n.status !== "WAITING_CLIENT" && this.maybeFlagEmptyReply(n, i), n;
|
|
1795
|
+
} finally {
|
|
1796
|
+
s && this.endTurn(s);
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
async stop() {
|
|
1800
|
+
const t = this.activeTurn;
|
|
1801
|
+
if (t) {
|
|
1802
|
+
t.stopRequested = !0;
|
|
1803
|
+
const r = t.messageId;
|
|
1804
|
+
return t.controller.abort(), r ? this.postStopForTurn(t, r) : null;
|
|
1805
|
+
}
|
|
1806
|
+
const s = this.pausedTurn;
|
|
1807
|
+
if (!s) return null;
|
|
1808
|
+
this.pausedTurn = null, this.pendingResumes.delete(s.messageId), this.stoppedTurnIds.add(s.messageId);
|
|
1809
|
+
let i = null;
|
|
1810
|
+
try {
|
|
1811
|
+
i = await this.stopMessage(s.messageId);
|
|
1812
|
+
} catch (r) {
|
|
1813
|
+
l.warn("Failed to stop the paused turn:", r);
|
|
1814
|
+
}
|
|
1815
|
+
return this.eventEmitter.emit("message:stopped", {
|
|
1816
|
+
conversationId: s.conversationId,
|
|
1817
|
+
messageId: s.messageId
|
|
1818
|
+
}), i;
|
|
1819
|
+
}
|
|
1820
|
+
async stopMessage(t) {
|
|
1821
|
+
const s = await this.httpClient.post(`/api/sdk/v1/messages/${t}/stop`);
|
|
1822
|
+
return {
|
|
1823
|
+
status: s.status,
|
|
1824
|
+
messageStatus: s.message_status
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
isGenerating() {
|
|
1828
|
+
return this.activeTurn !== null || this.pausedTurn !== null;
|
|
1829
|
+
}
|
|
1830
|
+
beginTurn() {
|
|
1831
|
+
this.pausedTurn = null;
|
|
1832
|
+
const t = {
|
|
1833
|
+
controller: new AbortController(),
|
|
1834
|
+
messageId: null,
|
|
1835
|
+
conversationId: null,
|
|
1836
|
+
stopRequested: !1,
|
|
1837
|
+
stopPosted: !1
|
|
1838
|
+
};
|
|
1839
|
+
return this.activeTurn = t, t;
|
|
1840
|
+
}
|
|
1841
|
+
endTurn(t) {
|
|
1842
|
+
this.activeTurn === t && (this.activeTurn = null);
|
|
1843
|
+
}
|
|
1844
|
+
async postStopForTurn(t, s) {
|
|
1845
|
+
if (!s || t.stopPosted) return null;
|
|
1846
|
+
t.stopPosted = !0;
|
|
1847
|
+
try {
|
|
1848
|
+
return await this.stopMessage(s);
|
|
1849
|
+
} catch (i) {
|
|
1850
|
+
return l.warn("Failed to stop the turn server-side:", i), null;
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
buildStoppedMessage(t) {
|
|
1854
|
+
const s = {
|
|
1855
|
+
id: t.messageId ?? "",
|
|
1856
|
+
conversationId: t.conversationId ?? "",
|
|
1857
|
+
content: "",
|
|
1858
|
+
role: "assistant",
|
|
1859
|
+
status: "CANCELED",
|
|
1860
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1861
|
+
};
|
|
1862
|
+
return s.id && this.eventEmitter.emit("message:complete", s), this.eventEmitter.emit("message:stopped", {
|
|
1863
|
+
conversationId: s.conversationId,
|
|
1864
|
+
messageId: s.id
|
|
1865
|
+
}), s;
|
|
1866
|
+
}
|
|
1867
|
+
resolveClientFunctionsMode(t) {
|
|
1868
|
+
return t?.clientFunctionsMode ?? this.config.clientFunctionsMode ?? "pause";
|
|
1869
|
+
}
|
|
1870
|
+
registerResumeGate(t) {
|
|
1871
|
+
return this.resumeGate = t, () => {
|
|
1872
|
+
this.resumeGate === t && (this.resumeGate = null);
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
async continueMessage(t) {
|
|
1876
|
+
const s = this.functionRegistry.getSchemas(), i = this.buildSendContext(), r = {};
|
|
1877
|
+
s.length > 0 && (r.client_functions = s), i && (r.client_context = i);
|
|
1878
|
+
const n = this.beginTurn();
|
|
1879
|
+
n.messageId = t;
|
|
1880
|
+
const a = await this.sendRequest(n, () => this.httpClient.postStream(`/api/sdk/v1/messages/${t}/continue`, r, { signal: n.controller.signal }));
|
|
1881
|
+
return a ? this.processSSEResponse(a, n) : this.buildStoppedMessage(n);
|
|
1882
|
+
}
|
|
1883
|
+
markResumeSignal(t, s, i) {
|
|
1884
|
+
if (!t) return;
|
|
1885
|
+
const r = this.pendingResumes.get(t) ?? {
|
|
1886
|
+
conversationId: s,
|
|
1887
|
+
waitingConfirmed: !1,
|
|
1888
|
+
resultsReady: !1,
|
|
1889
|
+
started: !1
|
|
1890
|
+
};
|
|
1891
|
+
r[i] = !0, s && (r.conversationId = s), this.pendingResumes.set(t, r), !(!r.waitingConfirmed || !r.resultsReady || r.started) && (r.started = !0, this.runAutoResume(t, r.conversationId));
|
|
1892
|
+
}
|
|
1893
|
+
async runAutoResume(t, s) {
|
|
1894
|
+
try {
|
|
1895
|
+
this.resumeGate && await this.resumeGate({
|
|
1896
|
+
conversationId: s,
|
|
1897
|
+
messageId: t
|
|
1898
|
+
});
|
|
1899
|
+
} catch (i) {
|
|
1900
|
+
l.warn("Resume gate threw; resuming anyway:", i);
|
|
1901
|
+
}
|
|
1902
|
+
if (this.pendingResumes.delete(t), !this.stoppedTurnIds.delete(t))
|
|
1903
|
+
try {
|
|
1904
|
+
await this.continueMessage(t);
|
|
1905
|
+
} catch (i) {
|
|
1906
|
+
l.warn("Auto-resume of paused turn failed:", i);
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
maybeFlagEmptyReply(t, s) {
|
|
1910
|
+
t.status === "DONE" && (t.content ?? "").trim() === "" && !s && !(t.toolCalls && t.toolCalls.length > 0) && !(t.followUpReplies && t.followUpReplies.length > 0) && setTimeout(() => {
|
|
1911
|
+
if (this.eventEmitter.emit("message:empty", {
|
|
1912
|
+
conversationId: t.conversationId ?? "",
|
|
1913
|
+
messageId: t.id ?? ""
|
|
1914
|
+
}), this.config.warnOnEmptyReply === !1) return;
|
|
1915
|
+
const i = t.conversationId || "(no conversation)";
|
|
1916
|
+
if (this.warnedEmptyConversations.has(i)) return;
|
|
1917
|
+
this.warnedEmptyConversations.add(i);
|
|
1918
|
+
const r = this.config.agent || this.config.defaultAgentId;
|
|
1919
|
+
t.id ? console.warn("[AGO] Reply completed with empty content. Possible causes: " + (r ? `the agent "${r}" 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: " + (r ? `the agent "${r}" 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`.");
|
|
1920
|
+
}, 0);
|
|
1921
|
+
}
|
|
1922
|
+
async handleClientFunctionInvocation(t) {
|
|
1923
|
+
let s, i;
|
|
1924
|
+
try {
|
|
1925
|
+
s = await this.functionRegistry.execute(t.functionName, t.arguments);
|
|
1926
|
+
} catch (r) {
|
|
1927
|
+
i = r instanceof Error ? r.message : "Unknown error", l.error("Client function execution failed:", r);
|
|
1928
|
+
}
|
|
1929
|
+
if (t.invocationId) try {
|
|
1930
|
+
const r = await this.submitToolCallForm(t.invocationId, {
|
|
1931
|
+
result: s,
|
|
1932
|
+
error: i,
|
|
1933
|
+
_type: "client_function_result"
|
|
1934
|
+
});
|
|
1935
|
+
r?.resume?.ready && this.markResumeSignal(r.resume.message_id, t.conversationId, "resultsReady");
|
|
1936
|
+
} catch (r) {
|
|
1937
|
+
l.error("Failed to submit function result:", r);
|
|
1938
|
+
}
|
|
1939
|
+
this.eventEmitter.emit("function:result", {
|
|
1940
|
+
invocationId: t.invocationId,
|
|
1941
|
+
result: s,
|
|
1942
|
+
error: i
|
|
1943
|
+
});
|
|
1944
|
+
}
|
|
1945
|
+
requiresApproval(t) {
|
|
1946
|
+
const s = this.config.approvalPolicy;
|
|
1947
|
+
if (s) try {
|
|
1948
|
+
if (s(t)) return !0;
|
|
1949
|
+
} catch (i) {
|
|
1950
|
+
l.warn("approvalPolicy threw; not gating this call:", i);
|
|
1951
|
+
}
|
|
1952
|
+
return this.functionRegistry.get(t.functionName)?.requiresApproval === !0;
|
|
1953
|
+
}
|
|
1954
|
+
async approveFunction(t) {
|
|
1955
|
+
const s = this.pendingApprovals.get(t);
|
|
1956
|
+
s && (this.pendingApprovals.delete(t), await this.handleClientFunctionInvocation(s));
|
|
1957
|
+
}
|
|
1958
|
+
async rejectFunction(t) {
|
|
1959
|
+
const s = this.pendingApprovals.get(t);
|
|
1960
|
+
if (!s) return;
|
|
1961
|
+
this.pendingApprovals.delete(t);
|
|
1962
|
+
const i = {
|
|
1963
|
+
approved: !1,
|
|
1964
|
+
reason: "user_rejected"
|
|
1965
|
+
};
|
|
1966
|
+
try {
|
|
1967
|
+
const r = await this.submitToolCallForm(t, {
|
|
1968
|
+
result: i,
|
|
1969
|
+
_type: "client_function_result"
|
|
1970
|
+
});
|
|
1971
|
+
r?.resume?.ready && this.markResumeSignal(r.resume.message_id, s.conversationId, "resultsReady");
|
|
1972
|
+
} catch (r) {
|
|
1973
|
+
l.error("Failed to submit function rejection:", r);
|
|
1974
|
+
}
|
|
1975
|
+
this.eventEmitter.emit("function:result", {
|
|
1976
|
+
invocationId: t,
|
|
1977
|
+
result: i
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
async runExternalFunction(t, s) {
|
|
1981
|
+
const i = {
|
|
1982
|
+
invocationId: `webmcp-${W()}`,
|
|
1983
|
+
functionName: t,
|
|
1984
|
+
arguments: s,
|
|
1985
|
+
conversationId: ""
|
|
1986
|
+
}, { invocationId: r } = i;
|
|
1987
|
+
this.eventEmitter.emit("function:invoke", i);
|
|
1988
|
+
try {
|
|
1989
|
+
const n = await this.functionRegistry.execute(t, s);
|
|
1990
|
+
return this.eventEmitter.emit("function:result", {
|
|
1991
|
+
invocationId: r,
|
|
1992
|
+
result: n
|
|
1993
|
+
}), n;
|
|
1994
|
+
} catch (n) {
|
|
1995
|
+
throw this.eventEmitter.emit("function:result", {
|
|
1996
|
+
invocationId: r,
|
|
1997
|
+
result: null,
|
|
1998
|
+
error: n instanceof Error ? n.message : String(n)
|
|
1999
|
+
}), n;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
async getConversations(t) {
|
|
2003
|
+
const s = new URLSearchParams();
|
|
2004
|
+
t?.page !== void 0 && s.set("page", String(t.page)), t?.pageSize !== void 0 && s.set("page_size", String(t.pageSize));
|
|
2005
|
+
const i = s.toString(), r = await this.httpClient.get(`/api/sdk/v1/conversations${i ? `?${i}` : ""}`), n = (Array.isArray(r.data) ? r.data : []).map((a) => ({
|
|
2006
|
+
id: String(a.id),
|
|
2007
|
+
title: a.title ?? "",
|
|
2008
|
+
lastMessageDate: new Date(a.last_message_at ?? a.created_at ?? 0)
|
|
2009
|
+
}));
|
|
2010
|
+
return {
|
|
2011
|
+
data: n,
|
|
2012
|
+
hasMore: r.has_more ?? !1,
|
|
2013
|
+
total: r.total ?? n.length
|
|
2014
|
+
};
|
|
2015
|
+
}
|
|
2016
|
+
async getConversation(t) {
|
|
2017
|
+
const s = await this.httpClient.get(`/api/sdk/v1/conversations/${t}`), i = {
|
|
2018
|
+
id: s.id,
|
|
2019
|
+
title: s.title,
|
|
2020
|
+
lastMessageDate: new Date(s.last_message_at ?? s.created_at ?? 0),
|
|
2021
|
+
messages: s.messages.map((r) => ({
|
|
2022
|
+
id: r.id,
|
|
2023
|
+
conversationId: s.id,
|
|
2024
|
+
content: r.content,
|
|
2025
|
+
role: r.role,
|
|
2026
|
+
status: r.status,
|
|
2027
|
+
createdAt: new Date(r.created_at),
|
|
2028
|
+
hidden: r.hidden,
|
|
2029
|
+
sources: r.sources && r.sources.length > 0 ? r.sources.map(({ id: n, title: a, url: o }) => ({
|
|
2030
|
+
id: n,
|
|
2031
|
+
title: a,
|
|
2032
|
+
url: o ?? void 0
|
|
2033
|
+
})) : void 0,
|
|
2034
|
+
toolCalls: k.mapPersistedToolCalls(r.tool_call_data),
|
|
2035
|
+
attachments: r.attachments && r.attachments.length > 0 ? r.attachments.map(Tt) : void 0,
|
|
2036
|
+
followUpReplies: r.follow_up_replies && r.follow_up_replies.length > 0 ? r.follow_up_replies : void 0
|
|
2037
|
+
}))
|
|
2038
|
+
};
|
|
2039
|
+
return this.eventEmitter.emit("conversation:loaded", i), i;
|
|
2040
|
+
}
|
|
2041
|
+
static mapPersistedToolCalls(t) {
|
|
2042
|
+
if (!(!t || t.length === 0))
|
|
2043
|
+
return t.map((s) => ({
|
|
2044
|
+
id: String(s.id ?? ""),
|
|
2045
|
+
type: s.type ?? "status_message",
|
|
2046
|
+
status: String(s.status ?? "unknown"),
|
|
2047
|
+
toolName: s.tool_name ?? "",
|
|
2048
|
+
toolDisplayName: s.tool_display_name,
|
|
2049
|
+
message: s.message,
|
|
2050
|
+
formSchema: s.form_schema,
|
|
2051
|
+
data: s.data,
|
|
2052
|
+
functionName: s.function_name,
|
|
2053
|
+
arguments: s.arguments,
|
|
2054
|
+
displayMode: s.display_mode,
|
|
2055
|
+
askToTalkToHuman: s.ask_to_talk_to_human,
|
|
2056
|
+
allowedToCreateTicket: s.allowed_to_create_ticket,
|
|
2057
|
+
ticket: s.ticket,
|
|
2058
|
+
mode: s.mode,
|
|
2059
|
+
ticketFormId: s.ticket_form_id,
|
|
2060
|
+
embedHtml: s.embed_html,
|
|
2061
|
+
embedDescription: s.embed_description
|
|
2062
|
+
}));
|
|
2063
|
+
}
|
|
2064
|
+
async transcribeAudio(t, s) {
|
|
2065
|
+
const i = new FormData();
|
|
2066
|
+
return i.append("file", t, t.name), (await this.httpClient.postFormData("/api/sdk/v1/audio/transcriptions", i, s)).json();
|
|
2067
|
+
}
|
|
2068
|
+
async getConfig() {
|
|
2069
|
+
const t = await this.httpClient.get("/api/sdk/v1/config");
|
|
2070
|
+
return {
|
|
2071
|
+
permissions: (t.permissions ?? []).map((s) => ({
|
|
2072
|
+
id: s.id ?? void 0,
|
|
2073
|
+
name: s.name ?? void 0,
|
|
2074
|
+
displayName: s.display_name ?? void 0,
|
|
2075
|
+
agents: (s.agents ?? []).map((i) => ({
|
|
2076
|
+
id: i.id,
|
|
2077
|
+
name: i.name ?? void 0
|
|
2078
|
+
})),
|
|
2079
|
+
ticketForm: s.ticket_form ? k.mapTicketForm(s.ticket_form) : void 0,
|
|
2080
|
+
homePage: s.home_page ? k.mapHomePage(s.home_page) : void 0,
|
|
2081
|
+
fileAttachmentsEnabled: !!s.file_attachments_enabled,
|
|
2082
|
+
voiceEnabled: !!s.voice_enabled,
|
|
2083
|
+
speechToTextEnabled: !!s.speech_to_text_enabled
|
|
2084
|
+
})),
|
|
2085
|
+
proactive: { enabled: !!t.proactive?.enabled }
|
|
2086
|
+
};
|
|
2087
|
+
}
|
|
2088
|
+
static mapHomePage(t) {
|
|
2089
|
+
const s = t.widget_starter;
|
|
2090
|
+
return {
|
|
2091
|
+
title: t.title ?? void 0,
|
|
2092
|
+
subtitle: t.subtitle ?? void 0,
|
|
2093
|
+
starters: (t.home_starters ?? []).flatMap((i) => {
|
|
2094
|
+
const r = i.description || i.title || "", n = i.initial_message || r;
|
|
2095
|
+
return !r || !n ? [] : [{
|
|
2096
|
+
id: i.id,
|
|
2097
|
+
label: r,
|
|
2098
|
+
message: n,
|
|
2099
|
+
agentId: i.agent_id ?? void 0
|
|
2100
|
+
}];
|
|
2101
|
+
}),
|
|
2102
|
+
widgetStarter: s && s.initial_message ? {
|
|
2103
|
+
id: s.id,
|
|
2104
|
+
message: s.initial_message,
|
|
2105
|
+
agentId: s.agent_id ?? void 0
|
|
2106
|
+
} : void 0
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
static mapTicketForm(t) {
|
|
2110
|
+
return {
|
|
2111
|
+
id: t.id,
|
|
2112
|
+
name: t.name ?? void 0,
|
|
2113
|
+
mode: t.mode === "embed" ? "embed" : "form",
|
|
2114
|
+
showSubject: t.show_subject ?? !0,
|
|
2115
|
+
showBody: t.show_body ?? !0,
|
|
2116
|
+
showPriority: t.show_priority ?? !0,
|
|
2117
|
+
showTypology: t.show_typology ?? !0,
|
|
2118
|
+
priorityTypologies: t.priority_typologies ?? void 0,
|
|
2119
|
+
successMessageText: t.success_message_text ?? void 0,
|
|
2120
|
+
successMessageUrlLabel: t.success_message_url_label ?? void 0,
|
|
2121
|
+
fields: (t.fields ?? []).map((s) => ({
|
|
2122
|
+
id: s.id,
|
|
2123
|
+
externalId: s.external_id ?? void 0,
|
|
2124
|
+
title: s.title ?? void 0,
|
|
2125
|
+
type: s.type ?? void 0,
|
|
2126
|
+
required: !!s.required,
|
|
2127
|
+
hidden: !!s.hidden,
|
|
2128
|
+
active: s.active,
|
|
2129
|
+
alwaysVisible: s.always_visible,
|
|
2130
|
+
regexpForValidation: s.regexp_for_validation ?? void 0,
|
|
2131
|
+
position: s.position ?? 0,
|
|
2132
|
+
options: (s.options ?? []).map((i) => ({
|
|
2133
|
+
id: i.id,
|
|
2134
|
+
name: i.name ?? void 0,
|
|
2135
|
+
value: i.value ?? void 0,
|
|
2136
|
+
default: !!i.default,
|
|
2137
|
+
position: i.position ?? void 0,
|
|
2138
|
+
group: i.group ?? void 0,
|
|
2139
|
+
noDisplay: i.no_display,
|
|
2140
|
+
conditionalFieldId: i.conditional_field_id ?? void 0,
|
|
2141
|
+
conditionalFieldValues: i.conditional_field_values ?? void 0,
|
|
2142
|
+
message: i.message ?? void 0,
|
|
2143
|
+
messageType: i.message_type ?? "info"
|
|
2144
|
+
})),
|
|
2145
|
+
conditionalFieldId: s.conditional_field_id ?? void 0,
|
|
2146
|
+
conditionalFieldValue: s.conditional_field_value ?? void 0,
|
|
2147
|
+
conditionalFieldValues: s.conditional_field_values ?? void 0
|
|
2148
|
+
}))
|
|
2149
|
+
};
|
|
2150
|
+
}
|
|
2151
|
+
async createTicket(t) {
|
|
2152
|
+
const s = new FormData();
|
|
2153
|
+
s.append("subject", t.subject), s.append("body", t.body), t.priority && s.append("priority", t.priority), t.typology && s.append("typology", t.typology), t.conversationId && s.append("conversation_id", t.conversationId), t.email && s.append("email", t.email), t.customFields && t.customFields.length > 0 && s.append("custom_fields", JSON.stringify(t.customFields));
|
|
2154
|
+
for (const r of t.files ?? []) s.append("files", r, r.name);
|
|
2155
|
+
t.ticketFormId && s.append("ticket_form_id", t.ticketFormId);
|
|
2156
|
+
const i = await (await this.httpClient.postFormData("/api/sdk/v1/tickets", s)).json();
|
|
2157
|
+
return {
|
|
2158
|
+
id: String(i.id ?? ""),
|
|
2159
|
+
url: typeof i.url == "string" && i.url ? i.url : void 0
|
|
2160
|
+
};
|
|
2161
|
+
}
|
|
2162
|
+
async getMessages(t) {
|
|
2163
|
+
return (await this.getConversation(t)).messages || [];
|
|
2164
|
+
}
|
|
2165
|
+
async resumePendingClientFunctions(t) {
|
|
2166
|
+
const s = [...t.messages ?? []].reverse().find((o) => o.role === "assistant" && o.status === "WAITING_CLIENT");
|
|
2167
|
+
if (!s) return null;
|
|
2168
|
+
const i = (s.toolCalls ?? []).filter((o) => o.type === "client_function" && o.status === "waiting_input" && o.functionName), r = new Set(this.functionRegistry.getSchemas().map((o) => o.name)), n = i.filter((o) => !r.has(o.functionName));
|
|
2169
|
+
if (n.length > 0)
|
|
2170
|
+
return l.warn("Cannot resume paused turn: function(s) not registered on this page:", n.map((o) => o.functionName)), null;
|
|
2171
|
+
let a = i.length === 0;
|
|
2172
|
+
for (const o of i) {
|
|
2173
|
+
const c = {
|
|
2174
|
+
invocationId: o.id,
|
|
2175
|
+
functionName: o.functionName,
|
|
2176
|
+
arguments: o.arguments ?? {},
|
|
2177
|
+
conversationId: t.id
|
|
2178
|
+
};
|
|
2179
|
+
if (this.requiresApproval(c)) {
|
|
2180
|
+
this.pendingApprovals.set(o.id, c), this.markResumeSignal(s.id, t.id, "waitingConfirmed"), this.eventEmitter.emit("function:awaiting-approval", c), a = !1;
|
|
2181
|
+
continue;
|
|
2182
|
+
}
|
|
2183
|
+
this.eventEmitter.emit("function:invoke", c);
|
|
2184
|
+
let u, d;
|
|
2185
|
+
try {
|
|
2186
|
+
u = await this.functionRegistry.execute(o.functionName, o.arguments ?? {});
|
|
2187
|
+
} catch (g) {
|
|
2188
|
+
d = g instanceof Error ? g.message : "Unknown error", l.error("Client function execution failed:", g);
|
|
2189
|
+
}
|
|
2190
|
+
this.eventEmitter.emit("function:result", {
|
|
2191
|
+
invocationId: o.id,
|
|
2192
|
+
result: u,
|
|
2193
|
+
error: d
|
|
2194
|
+
}), a = (await this.submitToolCallForm(o.id, {
|
|
2195
|
+
result: u,
|
|
2196
|
+
error: d,
|
|
2197
|
+
_type: "client_function_result"
|
|
2198
|
+
}))?.resume?.ready ?? a;
|
|
2199
|
+
}
|
|
2200
|
+
return a ? this.continueMessage(s.id) : null;
|
|
2201
|
+
}
|
|
2202
|
+
async submitToolCallForm(t, s) {
|
|
2203
|
+
return this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`, { formData: s });
|
|
2204
|
+
}
|
|
2205
|
+
async confirmToolCall(t) {
|
|
2206
|
+
await this.httpClient.post(`/api/tool-calls/${t}/confirm/`);
|
|
2207
|
+
}
|
|
2208
|
+
async rejectToolCall(t) {
|
|
2209
|
+
await this.httpClient.post(`/api/tool-calls/${t}/reject/`);
|
|
2210
|
+
}
|
|
2211
|
+
async getFormCollector(t) {
|
|
2212
|
+
const s = await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);
|
|
2213
|
+
return {
|
|
2214
|
+
name: s.name,
|
|
2215
|
+
description: s.description,
|
|
2216
|
+
schema: s.schema,
|
|
2217
|
+
submit: s.submit ?? void 0
|
|
2218
|
+
};
|
|
2219
|
+
}
|
|
2220
|
+
async submitFormCollector(t, s) {
|
|
2221
|
+
return this.httpClient.post("/api/sdk/v1/forms/submit", {
|
|
2222
|
+
name: t,
|
|
2223
|
+
values: s
|
|
2224
|
+
});
|
|
2225
|
+
}
|
|
2226
|
+
async submitFeedback(t, s, i) {
|
|
2227
|
+
const r = i?.comment?.trim(), n = i?.reasons?.length ? [...new Set(i.reasons)] : [];
|
|
2228
|
+
await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`, {
|
|
2229
|
+
rating: s,
|
|
2230
|
+
...n.length ? { reasons: n } : {},
|
|
2231
|
+
...r ? { comment: r } : {}
|
|
2232
|
+
});
|
|
2233
|
+
}
|
|
2234
|
+
async submitConversationFeedback(t, s, i) {
|
|
2235
|
+
let r = i?.lastMessageId;
|
|
2236
|
+
if (!r) {
|
|
2237
|
+
const n = [...(await this.getConversation(t)).messages ?? []].reverse().find((a) => a.role === "assistant" && !a.hidden && !!a.content && a.status !== "IN_PROGRESS" && a.status !== "WAITING_CLIENT");
|
|
2238
|
+
if (!n) throw new C(`Conversation ${t} has no finished answer to report feedback on. Wait for the turn to complete, or pass \`lastMessageId\`.`, "feedback_no_message");
|
|
2239
|
+
r = n.id;
|
|
2240
|
+
}
|
|
2241
|
+
return await this.submitFeedback(r, s, i), r;
|
|
2242
|
+
}
|
|
2243
|
+
registerFunction(t, s, i) {
|
|
2244
|
+
typeof t == "object" ? this.functionRegistry.register(t) : this.functionRegistry.register(t, s, i);
|
|
2245
|
+
}
|
|
2246
|
+
register(t) {
|
|
2247
|
+
if (Array.isArray(t)) for (const s of t) this.functionRegistry.register(s);
|
|
2248
|
+
else this.functionRegistry.register(t);
|
|
2249
|
+
}
|
|
2250
|
+
unregisterFunction(t) {
|
|
2251
|
+
return this.functionRegistry.unregister(t);
|
|
2252
|
+
}
|
|
2253
|
+
getRegisteredFunctions() {
|
|
2254
|
+
return this.functionRegistry.getSchemas();
|
|
2255
|
+
}
|
|
2256
|
+
onFunctionsChanged(t) {
|
|
2257
|
+
return this.functionRegistry.onChange(t);
|
|
2258
|
+
}
|
|
2259
|
+
getFunctionRegistrations() {
|
|
2260
|
+
return this.functionRegistry.getAll();
|
|
2261
|
+
}
|
|
2262
|
+
async executeClientFunction(t, s) {
|
|
2263
|
+
return this.functionRegistry.execute(t, s);
|
|
2264
|
+
}
|
|
2265
|
+
registerNavigationFunction(t, s) {
|
|
2266
|
+
const i = s.map((o) => o.name), r = s.map((o) => {
|
|
2267
|
+
const c = M(o.path), u = c.length > 0 ? ` (requires ${c.map((d) => `"${d}"`).join(", ")})` : "";
|
|
2268
|
+
return `- "${o.name}"${u}: ${o.description}`;
|
|
2269
|
+
}).join(`
|
|
2270
|
+
`), n = /* @__PURE__ */ new Map();
|
|
2271
|
+
for (const o of s) for (const c of M(o.path)) n.set(c, [...n.get(c) ?? [], o.name]);
|
|
2272
|
+
const a = { page: {
|
|
2273
|
+
type: "string",
|
|
2274
|
+
description: "The page to navigate to",
|
|
2275
|
+
enum: i
|
|
2276
|
+
} };
|
|
2277
|
+
for (const [o, c] of n) {
|
|
2278
|
+
if (o === "page") {
|
|
2279
|
+
l.error('registerNavigationFunction: a ":page" placeholder collides with the "page" argument and is ignored. Rename the placeholder.');
|
|
2280
|
+
continue;
|
|
2281
|
+
}
|
|
2282
|
+
a[o] = {
|
|
2283
|
+
type: "string",
|
|
2284
|
+
description: `Value for ":${o}" in the page path. Required when page is ${c.map((u) => `"${u}"`).join(" or ")}.`
|
|
2285
|
+
};
|
|
2286
|
+
}
|
|
2287
|
+
this.registerFunction("navigateToPage", async (o) => {
|
|
2288
|
+
const c = o.page, u = s.find((f) => f.name === c);
|
|
2289
|
+
if (!u) return {
|
|
2290
|
+
success: !1,
|
|
2291
|
+
error: `Unknown page: ${c}`
|
|
2292
|
+
};
|
|
2293
|
+
let d = {};
|
|
2294
|
+
if (typeof o.params == "string") try {
|
|
2295
|
+
d = JSON.parse(o.params);
|
|
2296
|
+
} catch {
|
|
2297
|
+
}
|
|
2298
|
+
else o.params && typeof o.params == "object" && (d = o.params);
|
|
2299
|
+
const g = {};
|
|
2300
|
+
for (const f of M(u.path)) g[f] = o[f] ?? d[f];
|
|
2301
|
+
const { path: m, missing: v } = jt(u.path, g);
|
|
2302
|
+
if (v.length > 0) {
|
|
2303
|
+
const f = v.map((h) => `"${h}": "..."`).join(", ");
|
|
2304
|
+
return {
|
|
2305
|
+
success: !1,
|
|
2306
|
+
error: `Page "${c}" needs ${v.map((h) => `"${h}"`).join(", ")}. Retry with { "page": "${c}", ${f} }.`
|
|
2307
|
+
};
|
|
2308
|
+
}
|
|
2309
|
+
return t(m), {
|
|
2310
|
+
success: !0,
|
|
2311
|
+
navigatedTo: m
|
|
2312
|
+
};
|
|
2313
|
+
}, {
|
|
2314
|
+
description: `Navigate the user to a page in the application. Available pages:
|
|
2315
|
+
${r}`,
|
|
2316
|
+
parameters: {
|
|
2317
|
+
type: "object",
|
|
2318
|
+
properties: a,
|
|
2319
|
+
required: ["page"]
|
|
2320
|
+
},
|
|
2321
|
+
webmcp: { navigates: !0 }
|
|
2322
|
+
}), this.addDynamicContext("current-page", () => {
|
|
2323
|
+
if (typeof window > "u" || !window.location) return null;
|
|
2324
|
+
const o = window.location.href, c = typeof document < "u" ? document.title : void 0, u = Lt(window.location.pathname, s), d = { url: o };
|
|
2325
|
+
return u && (d.page = u.name), c && (d.title = c), {
|
|
2326
|
+
name: "Current page",
|
|
2327
|
+
description: "The page the user is currently viewing.",
|
|
2328
|
+
data: d
|
|
2329
|
+
};
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
unregisterNavigationFunction() {
|
|
2333
|
+
this.unregisterFunction("navigateToPage"), this.removeDynamicContext("current-page");
|
|
2334
|
+
}
|
|
2335
|
+
registerPageStateFunction(t, s) {
|
|
2336
|
+
const i = s?.functionName ?? "setPageState", r = s?.data;
|
|
2337
|
+
this.registerFunction(Ke(t, {
|
|
2338
|
+
name: i,
|
|
2339
|
+
requiresApproval: s?.requiresApproval,
|
|
2340
|
+
getResultBudget: () => r ? this.pageDataBudget(r) : this.functionRegistry.getDefaultMaxResultBytes(),
|
|
2341
|
+
data: r ? {
|
|
2342
|
+
description: r.description,
|
|
2343
|
+
maxResultBytes: r.maxResultBytes,
|
|
2344
|
+
read: async (a) => Q(i, await this.readPageData(i, r, s), this.pageDataBudget(r) - this.envelopeBytes(a))
|
|
2345
|
+
} : void 0
|
|
2346
|
+
}));
|
|
2347
|
+
const n = ue(i);
|
|
2348
|
+
r ? (this.warnIfPlaceholderMode(i), this.registerFunction(n, async () => ({ data: Q(i, await this.readPageData(i, r, s), this.pageDataBudget(r) - this.envelopeBytes({})) }), {
|
|
2349
|
+
description: `Read what the current page is displaying, without changing anything: ${r.description}`,
|
|
2350
|
+
parameters: {
|
|
2351
|
+
type: "object",
|
|
2352
|
+
properties: {}
|
|
2353
|
+
},
|
|
2354
|
+
maxResultBytes: r.maxResultBytes
|
|
2355
|
+
}), this.pageDataCompanions.add(n)) : this.pageDataCompanions.delete(n) && this.unregisterFunction(n), this.addDynamicContext(`page-state:${i}`, () => {
|
|
2356
|
+
const a = t.filter((c) => typeof c.get == "function");
|
|
2357
|
+
if (a.length === 0) return null;
|
|
2358
|
+
const o = {};
|
|
2359
|
+
for (const c of a) o[c.name] = c.get();
|
|
2360
|
+
return {
|
|
2361
|
+
name: "Page state",
|
|
2362
|
+
description: "Current, editable state of the page the user is viewing.",
|
|
2363
|
+
data: o
|
|
2364
|
+
};
|
|
2365
|
+
});
|
|
2366
|
+
}
|
|
2367
|
+
unregisterPageStateFunction(t) {
|
|
2368
|
+
const s = t ?? "setPageState";
|
|
2369
|
+
this.unregisterFunction(s);
|
|
2370
|
+
const i = ue(s);
|
|
2371
|
+
this.pageDataCompanions.delete(i) && this.unregisterFunction(i), this.removeDynamicContext(`page-state:${s}`);
|
|
2372
|
+
}
|
|
2373
|
+
pageDataBudget(t) {
|
|
2374
|
+
return t.maxResultBytes ?? this.functionRegistry.getDefaultMaxResultBytes();
|
|
2375
|
+
}
|
|
2376
|
+
envelopeBytes(t) {
|
|
2377
|
+
return E(JSON.stringify({
|
|
2378
|
+
...t,
|
|
2379
|
+
data: null
|
|
2380
|
+
})) - 4;
|
|
2381
|
+
}
|
|
2382
|
+
readPageData(t, s, i) {
|
|
2383
|
+
return je(() => s, i?.settleTimeoutMs ?? 1e4).catch((r) => (l.warn(`Reading page data for "${t}" failed:`, r), {
|
|
2384
|
+
error: "page_data_unavailable",
|
|
2385
|
+
message: r instanceof Error ? r.message : String(r)
|
|
2386
|
+
}));
|
|
2387
|
+
}
|
|
2388
|
+
warnIfPlaceholderMode(t) {
|
|
2389
|
+
this.warnedPageDataPlaceholder || this.config.clientFunctionsMode === "placeholder" && (this.warnedPageDataPlaceholder = !0, l.warn(`"${t}" declares a data source, but clientFunctionsMode is "placeholder": the agent will not see that data during the turn it calls the function. Switch to "pause" (the default) for the data to come back as the result of its own call.`));
|
|
2390
|
+
}
|
|
2391
|
+
setContext(t, s) {
|
|
2392
|
+
this.contextRegistry.set(t, s), this.notifyContextChanged();
|
|
2393
|
+
}
|
|
2394
|
+
removeContext(t) {
|
|
2395
|
+
const s = this.contextRegistry.remove(t);
|
|
2396
|
+
return s && this.notifyContextChanged(), s;
|
|
2397
|
+
}
|
|
2398
|
+
addDynamicContext(t, s) {
|
|
2399
|
+
this.contextRegistry.addDynamicProvider(t, s), this.notifyContextChanged();
|
|
2400
|
+
}
|
|
2401
|
+
removeDynamicContext(t) {
|
|
2402
|
+
const s = this.contextRegistry.removeDynamicProvider(t);
|
|
2403
|
+
return s && this.notifyContextChanged(), s;
|
|
2404
|
+
}
|
|
2405
|
+
notifyContextChanged() {
|
|
2406
|
+
this.eventEmitter.emit("context:changed", this.contextRegistry.getSnapshot());
|
|
2407
|
+
}
|
|
2408
|
+
emitFormEvent(t, s) {
|
|
2409
|
+
this.eventEmitter.emit(t, s);
|
|
2410
|
+
}
|
|
2411
|
+
emitProactiveEvent(t, s) {
|
|
2412
|
+
this.eventEmitter.emit(t, s);
|
|
2413
|
+
}
|
|
2414
|
+
getHttp() {
|
|
2415
|
+
return this.httpClient;
|
|
2416
|
+
}
|
|
2417
|
+
getConfiguredAgent() {
|
|
2418
|
+
return this.config.agent || this.config.defaultAgentId;
|
|
2419
|
+
}
|
|
2420
|
+
getUserIdentity() {
|
|
2421
|
+
return {
|
|
2422
|
+
email: this.config.userEmail || void 0,
|
|
2423
|
+
hasJwt: !!this.config.userJwt
|
|
2424
|
+
};
|
|
2425
|
+
}
|
|
2426
|
+
enableAutoPageContext() {
|
|
2427
|
+
this.addDynamicContext("browser-page", () => {
|
|
2428
|
+
const t = typeof window < "u" ? window.location.href : void 0, s = typeof document < "u" ? document.title : void 0;
|
|
2429
|
+
return !t && !s ? null : {
|
|
2430
|
+
name: "Browser page",
|
|
2431
|
+
description: "Current page the user is viewing",
|
|
2432
|
+
data: {
|
|
2433
|
+
url: t,
|
|
2434
|
+
title: s
|
|
2435
|
+
}
|
|
2436
|
+
};
|
|
2437
|
+
});
|
|
2438
|
+
}
|
|
2439
|
+
getContextSnapshot() {
|
|
2440
|
+
return this.contextRegistry.getSnapshot();
|
|
2441
|
+
}
|
|
2442
|
+
buildSendContext() {
|
|
2443
|
+
const t = this.contextRegistry.getSnapshot(), s = t?.entries ?? {}, { changes: i, baseline: r } = _t(this.lastSentPageState, s);
|
|
2444
|
+
return this.lastSentPageState = r, i.length === 0 ? t : { entries: {
|
|
2445
|
+
...s,
|
|
2446
|
+
[Wt]: {
|
|
2447
|
+
name: "State changes",
|
|
2448
|
+
description: "Fields in the page state that changed since your last message, as field: <old> -> <new>.",
|
|
2449
|
+
data: { changes: i }
|
|
2450
|
+
}
|
|
2451
|
+
} };
|
|
2452
|
+
}
|
|
2453
|
+
recordActivity(t) {
|
|
2454
|
+
this.addActivity(t);
|
|
2455
|
+
}
|
|
2456
|
+
getRecentActivity() {
|
|
2457
|
+
return this.activityLedger.getRecent();
|
|
2458
|
+
}
|
|
2459
|
+
clearActivity() {
|
|
2460
|
+
this.activityLedger.clear();
|
|
2461
|
+
}
|
|
2462
|
+
addActivity(t) {
|
|
2463
|
+
const s = this.activityLedger.add(t);
|
|
2464
|
+
this.eventEmitter.emit("activity:recorded", s);
|
|
2465
|
+
}
|
|
2466
|
+
recordAgentAction(t) {
|
|
2467
|
+
const s = t.functionName, i = t.arguments;
|
|
2468
|
+
let r, n;
|
|
2469
|
+
if (s === "navigateToPage") {
|
|
2470
|
+
const a = i?.page;
|
|
2471
|
+
r = "agent.navigate", n = a ? `Agent navigated to "${String(a)}"` : "Agent navigated";
|
|
2472
|
+
} else s === "setPageState" ? (r = "agent.page_state", n = "Agent changed the page state") : (r = `agent.${s}`, n = `Agent ran "${s}"`);
|
|
2473
|
+
this.addActivity({
|
|
2474
|
+
actor: "agent",
|
|
2475
|
+
name: r,
|
|
2476
|
+
summary: n,
|
|
2477
|
+
...i && Object.keys(i).length > 0 ? { data: { arguments: i } } : {}
|
|
2478
|
+
});
|
|
2479
|
+
}
|
|
2480
|
+
registerActivityContext() {
|
|
2481
|
+
this.contextRegistry.addDynamicProvider(Ut, () => {
|
|
2482
|
+
const t = this.activityLedger.getRecent();
|
|
2483
|
+
return t.length === 0 ? null : {
|
|
2484
|
+
name: "Recent activity",
|
|
2485
|
+
description: "Recent actions by the user and the agent in the app, oldest first. Use this to understand what just happened before this message.",
|
|
2486
|
+
data: { events: t }
|
|
2487
|
+
};
|
|
2488
|
+
});
|
|
2489
|
+
}
|
|
2490
|
+
enableErrorWatcher(t) {
|
|
2491
|
+
this.disableErrorWatcher();
|
|
2492
|
+
const s = new Te(t);
|
|
2493
|
+
this.errorWatcher = s, s.start(), s.subscribe((i) => {
|
|
2494
|
+
this.eventEmitter.emit("error:captured", i), this.notifyContextChanged();
|
|
2495
|
+
}), this.contextRegistry.addDynamicProvider(le, () => {
|
|
2496
|
+
const i = s.getErrors();
|
|
2497
|
+
if (i.length === 0) return null;
|
|
2498
|
+
const r = Date.now();
|
|
2499
|
+
return {
|
|
2500
|
+
name: "Recent JavaScript errors",
|
|
2501
|
+
description: "JavaScript errors captured on the page in the last minutes, oldest first, with how long ago each last fired (ageMs) and how many times (count). Use them to diagnose when the user reports something broken or unresponsive; do not bring them up otherwise.",
|
|
2502
|
+
data: { errors: i.map(({ firstAt: n, lastAt: a, ...o }) => ({
|
|
2503
|
+
...o,
|
|
2504
|
+
ageMs: Math.max(0, r - a),
|
|
2505
|
+
...n !== a ? { firstSeenAgoMs: Math.max(0, r - n) } : {}
|
|
2506
|
+
})) }
|
|
2507
|
+
};
|
|
2508
|
+
});
|
|
2509
|
+
}
|
|
2510
|
+
disableErrorWatcher() {
|
|
2511
|
+
this.errorWatcher && (this.errorWatcher.destroy(), this.errorWatcher = null, this.contextRegistry.removeDynamicProvider(le));
|
|
2512
|
+
}
|
|
2513
|
+
reportError(t, s) {
|
|
2514
|
+
if (!this.errorWatcher) {
|
|
2515
|
+
l.warn("reportError() ignored: enable the error watcher first (errorWatcher: true).");
|
|
2516
|
+
return;
|
|
2517
|
+
}
|
|
2518
|
+
this.errorWatcher.report(t, s);
|
|
2519
|
+
}
|
|
2520
|
+
getRecentErrors() {
|
|
2521
|
+
return this.errorWatcher?.getErrors() ?? [];
|
|
2522
|
+
}
|
|
2523
|
+
clearErrors() {
|
|
2524
|
+
this.errorWatcher?.clear();
|
|
2525
|
+
}
|
|
2526
|
+
on(t, s) {
|
|
2527
|
+
this.eventEmitter.on(t, s);
|
|
2528
|
+
}
|
|
2529
|
+
off(t, s) {
|
|
2530
|
+
this.eventEmitter.off(t, s);
|
|
2531
|
+
}
|
|
2532
|
+
once(t, s) {
|
|
2533
|
+
this.eventEmitter.once(t, s);
|
|
2534
|
+
}
|
|
2535
|
+
waitFor(t, s) {
|
|
2536
|
+
return this.eventEmitter.waitFor(t, s);
|
|
2537
|
+
}
|
|
2538
|
+
updateConfig(t) {
|
|
2539
|
+
const s = {};
|
|
2540
|
+
for (const [r, n] of Object.entries(t)) n !== void 0 && (s[r] = n);
|
|
2541
|
+
const i = {
|
|
2542
|
+
...this.config,
|
|
2543
|
+
...s
|
|
2544
|
+
};
|
|
2545
|
+
ce(i, "AgoClient.updateConfig"), this.config = i, this.httpClient.updateConfig(s), s.debug !== void 0 && (s.debug ? l.enable() : l.disable()), s.maxFunctionResultBytes !== void 0 && this.functionRegistry.setDefaultMaxResultBytes(s.maxFunctionResultBytes), s.errorWatcher !== void 0 && (s.errorWatcher ? this.enableErrorWatcher(s.errorWatcher === !0 ? void 0 : s.errorWatcher) : this.disableErrorWatcher());
|
|
2546
|
+
}
|
|
2547
|
+
destroy() {
|
|
2548
|
+
this.proactive?.destroy(), this.proactive = null, this.errorWatcher?.destroy(), this.errorWatcher = null, this.detachWebMCP?.(), this.detachWebMCP = null, this.activeTurn?.controller.abort(), this.activeTurn = null, this.pausedTurn = null, this.stoppedTurnIds.clear(), this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), this.pendingResumes.clear(), this.pendingApprovals.clear(), this.resumeGate = null, l.log("AgoClient destroyed");
|
|
2549
|
+
}
|
|
2550
|
+
reviveAfterDestroy() {
|
|
2551
|
+
this.registerActivityContext(), this.config.errorWatcher && !this.errorWatcher && this.enableErrorWatcher(this.config.errorWatcher === !0 ? void 0 : this.config.errorWatcher), this.config.proactive && !this.proactive && re(this, this.config.proactive), this.attachWebMCPBridge();
|
|
2552
|
+
}
|
|
2553
|
+
}, Yt = [
|
|
2554
|
+
"inaccurate",
|
|
2555
|
+
"incomplete",
|
|
2556
|
+
"information_not_found",
|
|
2557
|
+
"technical_issue"
|
|
2558
|
+
];
|
|
2559
|
+
export {
|
|
2560
|
+
be as C,
|
|
2561
|
+
l as S,
|
|
2562
|
+
et as _,
|
|
2563
|
+
zt as a,
|
|
2564
|
+
Jt as b,
|
|
2565
|
+
Rt as c,
|
|
2566
|
+
vt as d,
|
|
2567
|
+
re as f,
|
|
2568
|
+
tt as g,
|
|
2569
|
+
ye as h,
|
|
2570
|
+
It as i,
|
|
2571
|
+
At as l,
|
|
2572
|
+
ct as m,
|
|
2573
|
+
Vt as n,
|
|
2574
|
+
Ht as o,
|
|
2575
|
+
at as p,
|
|
2576
|
+
ce as r,
|
|
2577
|
+
Xt as s,
|
|
2578
|
+
Yt as t,
|
|
2579
|
+
Kt as u,
|
|
2580
|
+
Me as v,
|
|
2581
|
+
Gt as w,
|
|
2582
|
+
Te as x,
|
|
2583
|
+
qt as y
|
|
2584
|
+
};
|