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