@useago/sdk 1.9.0 → 1.13.0

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