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