@useago/sdk 1.12.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 (48) hide show
  1. package/CHANGELOG.md +71 -4
  2. package/README.md +73 -0
  3. package/dist/angular.cjs +1 -1
  4. package/dist/angular.d.cts +97 -28
  5. package/dist/angular.d.ts +97 -28
  6. package/dist/angular.js +4 -1
  7. package/dist/{createConversationSession-B1Qn-y0I.js → createConversationSession-BfJg0WyA.js} +1 -1
  8. package/dist/{createConversationSession-B3v_xOU7.cjs → createConversationSession-CiOXKWl0.cjs} +1 -1
  9. package/dist/{createFormCollector-m79zk_NA.js → createFormCollector-DN1xjAv5.js} +1 -1
  10. package/dist/{createFormCollector-FvwDOqnV.cjs → createFormCollector-DnQl77Ko.cjs} +1 -1
  11. package/dist/createMockClient-BPt1gSve.cjs +1 -0
  12. package/dist/{createMockClient-Beao82tu.js → createMockClient-YoYr3pQr.js} +1 -0
  13. package/dist/devtools.cjs +4 -4
  14. package/dist/devtools.d.cts +95 -28
  15. package/dist/devtools.d.ts +95 -28
  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 +101 -35
  21. package/dist/index.d.ts +101 -35
  22. package/dist/index.js +44 -43
  23. package/dist/react.cjs +4 -4
  24. package/dist/react.d.cts +147 -28
  25. package/dist/react.d.ts +147 -28
  26. package/dist/react.js +814 -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 +95 -28
  31. package/dist/testing.d.ts +95 -28
  32. package/dist/testing.js +1 -1
  33. package/dist/{types-Ct1hlKwg.js → types-Q7t1peH-.js} +595 -419
  34. package/dist/types-a7teDBnC.cjs +10 -0
  35. package/dist/vue.cjs +1 -1
  36. package/dist/vue.d.cts +105 -28
  37. package/dist/vue.d.ts +105 -28
  38. package/dist/vue.js +103 -101
  39. package/dist/widget.cjs +6 -6
  40. package/dist/widget.d.cts +127 -28
  41. package/dist/widget.d.ts +127 -28
  42. package/dist/widget.js +1717 -1772
  43. package/llms-full.txt +129 -1
  44. package/package.json +1 -1
  45. package/dist/createMockClient-BEOXI8yW.cjs +0 -1
  46. package/dist/sheetController-BThJRtOu.cjs +0 -1
  47. package/dist/sheetController-aEKXIvjk.js +0 -343
  48. package/dist/types-mcW8vB1U.cjs +0 -10
@@ -1,6 +1,6 @@
1
- import { a as q, i as R, n as S, r as G, t as _ } from "./errors-BLfjXnLB.js";
2
- var $t = 10, K = 1e3;
3
- function pe(e) {
1
+ import { a as K, i as T, n as C, r as H, t as _ } from "./errors-BLfjXnLB.js";
2
+ var Gt = 10, X = 1e3;
3
+ function Ee(e) {
4
4
  if (typeof e != "object" || e === null) return !1;
5
5
  const t = Object.getPrototypeOf(e);
6
6
  return t === Object.prototype || t === null;
@@ -8,8 +8,8 @@ function pe(e) {
8
8
  function D(e, t) {
9
9
  if (typeof e == "string") {
10
10
  if (e.length <= 1e3) return e;
11
- const s = e.length - K;
12
- return e.slice(0, K) + `…[truncated ${s} chars]`;
11
+ const s = e.length - X;
12
+ return e.slice(0, X) + `…[truncated ${s} chars]`;
13
13
  }
14
14
  if (Array.isArray(e)) {
15
15
  if (t.has(e)) return "…[circular]";
@@ -17,7 +17,7 @@ function D(e, t) {
17
17
  const s = e.slice(0, 50).map((i) => D(i, t));
18
18
  return e.length > 50 && s.push(`…[+${e.length - 50} more]`), t.delete(e), s;
19
19
  }
20
- if (pe(e)) {
20
+ if (Ee(e)) {
21
21
  if (t.has(e)) return "…[circular]";
22
22
  t.add(e);
23
23
  const s = {};
@@ -26,10 +26,10 @@ function D(e, t) {
26
26
  }
27
27
  return e;
28
28
  }
29
- function le(e) {
29
+ function de(e) {
30
30
  return D(e, /* @__PURE__ */ new WeakSet());
31
31
  }
32
- var ye = class {
32
+ var be = class {
33
33
  constructor(e = 10) {
34
34
  this.entries = [];
35
35
  const t = Math.floor(e);
@@ -41,7 +41,7 @@ var ye = class {
41
41
  actor: e.actor ?? "user",
42
42
  name: e.name,
43
43
  summary: e.summary,
44
- ...e.data !== void 0 ? { data: le(e.data) } : {}
44
+ ...e.data !== void 0 ? { data: de(e.data) } : {}
45
45
  };
46
46
  this.entries.push(t);
47
47
  const s = this.entries.length - this.maxEntries;
@@ -56,7 +56,20 @@ var ye = class {
56
56
  clear() {
57
57
  this.entries = [];
58
58
  }
59
- }, ve = class {
59
+ };
60
+ function $(e) {
61
+ if (e == null) return null;
62
+ if (typeof e == "string") {
63
+ const t = e.trim().replace(/_/g, "-");
64
+ try {
65
+ const [s] = /^[a-z]{2,3}(?:-[a-z0-9]{1,8})*$/i.test(t) ? Intl.getCanonicalLocales(t) : [];
66
+ if (s) return s;
67
+ } catch {
68
+ }
69
+ }
70
+ throw new C('Use a language tag such as "fr", "de-DE", or "pt-BR", or null to clear it. See docs/general/configuration.md#language (config_invalid_language).', "config_invalid_language");
71
+ }
72
+ var Se = class {
60
73
  constructor(e = !1) {
61
74
  this.enabled = e;
62
75
  }
@@ -78,35 +91,129 @@ var ye = class {
78
91
  debug(...e) {
79
92
  this.enabled && console.debug("[AGO SDK]", ...e);
80
93
  }
81
- }, l = new ve(), Mt = 10, Nt = 6e5;
82
- var we = "[AGO SDK]", Ee = 300;
83
- function $(e, t) {
94
+ }, l = new Se(), z = "ago_widget_id";
95
+ function P(e) {
96
+ return typeof DOMException < "u" && e instanceof DOMException && e.name === "AbortError" || e instanceof Error && e.name === "AbortError";
97
+ }
98
+ function Ce() {
99
+ if (typeof localStorage < "u") {
100
+ const t = localStorage.getItem(z);
101
+ if (t) return t;
102
+ }
103
+ const e = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
104
+ if (typeof localStorage < "u") try {
105
+ localStorage.setItem(z, e);
106
+ } catch {
107
+ }
108
+ return e;
109
+ }
110
+ var _e = class {
111
+ constructor(e) {
112
+ this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.headers = { "X-User-Anon-Id": e.widgetId || Ce() }, e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission && (this.headers["X-Widget-Permission"] = e.permission);
113
+ const t = $(e.language);
114
+ t && (this.headers["Accept-Language"] = t);
115
+ }
116
+ updateConfig(e) {
117
+ const t = $(e.language);
118
+ e.baseUrl && (this.baseUrl = e.baseUrl.replace(/\/$/, "")), e.widgetId && (this.headers["X-User-Anon-Id"] = e.widgetId), e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission !== void 0 && (e.permission ? this.headers["X-Widget-Permission"] = e.permission : delete this.headers["X-Widget-Permission"]), e.language !== void 0 && (t ? this.headers["Accept-Language"] = t : delete this.headers["Accept-Language"]);
119
+ }
120
+ async get(e) {
121
+ return this.request("GET", e);
122
+ }
123
+ async post(e, t, s) {
124
+ return this.request("POST", e, t, s);
125
+ }
126
+ async postStream(e, t, s) {
127
+ const i = `${this.baseUrl}${e}`;
128
+ l.debug("POST (stream)", i, t);
129
+ try {
130
+ const r = await fetch(i, {
131
+ method: "POST",
132
+ headers: {
133
+ ...this.headers,
134
+ "Content-Type": "application/json"
135
+ },
136
+ body: t ? JSON.stringify(t) : void 0,
137
+ signal: s?.signal
138
+ });
139
+ return r.ok || await this.handleErrorResponse(r), r;
140
+ } catch (r) {
141
+ throw r instanceof _ || P(r) ? r : new T(`Network error: ${r instanceof Error ? r.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, r instanceof Error ? r : void 0);
142
+ }
143
+ }
144
+ async postFormData(e, t, s) {
145
+ const i = `${this.baseUrl}${e}`;
146
+ l.debug("POST (formData)", i);
147
+ const r = { ...this.headers };
148
+ try {
149
+ const n = await fetch(i, {
150
+ method: "POST",
151
+ headers: r,
152
+ body: t,
153
+ signal: s?.signal
154
+ });
155
+ return n.ok || await this.handleErrorResponse(n), n;
156
+ } catch (n) {
157
+ throw n instanceof _ || P(n) ? n : new T(`Network error: ${n instanceof Error ? n.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, n instanceof Error ? n : void 0);
158
+ }
159
+ }
160
+ async request(e, t, s, i) {
161
+ const r = `${this.baseUrl}${t}`;
162
+ l.debug(e, r, s);
163
+ try {
164
+ const n = await fetch(r, {
165
+ method: e,
166
+ headers: {
167
+ ...this.headers,
168
+ "Content-Type": "application/json"
169
+ },
170
+ body: s ? JSON.stringify(s) : void 0,
171
+ ...i?.keepalive ? { keepalive: !0 } : {}
172
+ });
173
+ return n.ok || await this.handleErrorResponse(n), n.status === 204 ? void 0 : n.json();
174
+ } catch (n) {
175
+ throw n instanceof _ ? n : new T(`Network error: ${n instanceof Error ? n.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, n instanceof Error ? n : void 0);
176
+ }
177
+ }
178
+ async handleErrorResponse(e) {
179
+ let t;
180
+ try {
181
+ t = await e.json();
182
+ } catch {
183
+ }
184
+ if (t?.error) throw _.fromResponse(t, e.status);
185
+ let s = "";
186
+ throw e.status === 401 || e.status === 403 ? s = " Check `userJwt` (and that it has not expired)." : e.status === 404 && (s = " Check that `baseUrl` points at your AGO API root."), new _(`HTTP ${e.status}: ${e.statusText}.${s}`, "http_error", e.status, "api_error");
187
+ }
188
+ }, qt = 10, Jt = 6e5;
189
+ var Ae = "[AGO SDK]", ke = 300;
190
+ function N(e, t) {
84
191
  return e.length <= t ? e : e.slice(0, t) + `…[truncated ${e.length - t} chars]`;
85
192
  }
86
- function _e(e) {
193
+ function Re(e) {
87
194
  const t = e.search(/[?#]/);
88
195
  return t === -1 ? e : e.slice(0, t);
89
196
  }
90
- function L(e) {
197
+ function G(e) {
91
198
  return typeof e == "object" && e !== null && typeof e.message == "string";
92
199
  }
93
- function de(e) {
200
+ function he(e) {
94
201
  if (typeof e == "string") return e;
95
- if (L(e)) return (typeof e.name == "string" && e.name ? `${e.name}: ` : "") + e.message;
202
+ if (G(e)) return (typeof e.name == "string" && e.name ? `${e.name}: ` : "") + e.message;
96
203
  if (typeof e == "object" && e !== null) try {
97
- return $(JSON.stringify(e), Ee);
204
+ return N(JSON.stringify(e), ke);
98
205
  } catch {
99
206
  return String(e);
100
207
  }
101
208
  return String(e);
102
209
  }
103
210
  function I(e) {
104
- return L(e) ? {
211
+ return G(e) ? {
105
212
  message: (typeof e.name == "string" && e.name && e.name !== "Error" ? `${e.name}: ` : "") + e.message,
106
213
  stack: typeof e.stack == "string" ? e.stack : void 0
107
- } : { message: de(e) };
214
+ } : { message: he(e) };
108
215
  }
109
- var Se = class {
216
+ var Te = class {
110
217
  constructor(e = {}) {
111
218
  this.started = !1, this.teardowns = [], this.errors = [], this.listeners = /* @__PURE__ */ new Set(), this.capturing = !1;
112
219
  const t = Math.floor(e.maxErrors ?? 10);
@@ -130,7 +237,7 @@ var Se = class {
130
237
  type: "manual",
131
238
  message: s.message,
132
239
  stack: s.stack,
133
- ...t ? { context: le(t) } : {}
240
+ ...t ? { context: de(t) } : {}
134
241
  });
135
242
  }
136
243
  subscribe(e) {
@@ -151,7 +258,7 @@ var Se = class {
151
258
  type: "error",
152
259
  message: t.message || e.message || "Unknown error",
153
260
  stack: t.stack,
154
- source: e.filename ? _e(e.filename) : void 0,
261
+ source: e.filename ? Re(e.filename) : void 0,
155
262
  line: e.lineno || void 0,
156
263
  col: e.colno || void 0
157
264
  });
@@ -180,8 +287,8 @@ var Se = class {
180
287
  onConsoleError(e) {
181
288
  if (e.length === 0) return;
182
289
  const t = e[0];
183
- if (typeof t == "string" && t.startsWith(we)) return;
184
- const s = e.find(L), i = e.map(de).join(" ");
290
+ if (typeof t == "string" && t.startsWith(Ae)) return;
291
+ const s = e.find(G), i = e.map(he).join(" ");
185
292
  this.capture({
186
293
  type: "console",
187
294
  message: i,
@@ -195,7 +302,7 @@ var Se = class {
195
302
  const t = Date.now(), s = e.stack !== void 0 ? this.trimStack(e.stack, e.message) : void 0;
196
303
  let i = {
197
304
  type: e.type,
198
- message: $(e.message, 500),
305
+ message: N(e.message, 500),
199
306
  ...e.source !== void 0 ? { source: e.source } : {},
200
307
  ...e.line !== void 0 ? { line: e.line } : {},
201
308
  ...e.col !== void 0 ? { col: e.col } : {},
@@ -212,7 +319,7 @@ var Se = class {
212
319
  i = o;
213
320
  }
214
321
  this.prune(t);
215
- const r = J(i), n = this.errors.find((o) => J(o) === r);
322
+ const r = V(i), n = this.errors.find((o) => V(o) === r);
216
323
  if (n) {
217
324
  n.count += 1, n.lastAt = t, i.context !== void 0 && (n.context = i.context), this.notify(n);
218
325
  return;
@@ -241,110 +348,31 @@ var Se = class {
241
348
  const i = s.indexOf(`
242
349
  `);
243
350
  if (i !== -1 && s.slice(0, i).includes(t.slice(0, 80)) && (s = s.slice(i + 1)), s = s.trim(), !!s)
244
- return $(s, this.maxStackChars);
351
+ return N(s, this.maxStackChars);
245
352
  }
246
353
  currentPathname() {
247
354
  return typeof window < "u" && window.location ? window.location.pathname : "";
248
355
  }
249
356
  };
250
- function J(e) {
357
+ function V(e) {
251
358
  return `${e.type}|${e.message}|${e.source ?? ""}|${e.line ?? ""}`;
252
359
  }
253
- var H = "ago_widget_id";
254
- function M(e) {
255
- return typeof DOMException < "u" && e instanceof DOMException && e.name === "AbortError" || e instanceof Error && e.name === "AbortError";
256
- }
257
- function Ce() {
258
- if (typeof localStorage < "u") {
259
- const t = localStorage.getItem(H);
260
- if (t) return t;
261
- }
262
- const e = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
263
- if (typeof localStorage < "u") try {
264
- localStorage.setItem(H, e);
265
- } catch {
266
- }
267
- return e;
268
- }
269
- var be = class {
360
+ var Ie = 5e4, xe = 2e4, Fe = 2e3, Me = class {
270
361
  constructor(e) {
271
- this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.headers = { "X-User-Anon-Id": e.widgetId || Ce() }, e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission && (this.headers["X-Widget-Permission"] = e.permission);
272
- }
273
- updateConfig(e) {
274
- e.baseUrl && (this.baseUrl = e.baseUrl.replace(/\/$/, "")), e.widgetId && (this.headers["X-User-Anon-Id"] = e.widgetId), e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission !== void 0 && (e.permission ? this.headers["X-Widget-Permission"] = e.permission : delete this.headers["X-Widget-Permission"]);
275
- }
276
- async get(e) {
277
- return this.request("GET", e);
278
- }
279
- async post(e, t, s) {
280
- return this.request("POST", e, t, s);
281
- }
282
- async postStream(e, t, s) {
283
- const i = `${this.baseUrl}${e}`;
284
- l.debug("POST (stream)", i, t);
285
- try {
286
- const r = await fetch(i, {
287
- method: "POST",
288
- headers: {
289
- ...this.headers,
290
- "Content-Type": "application/json"
291
- },
292
- body: t ? JSON.stringify(t) : void 0,
293
- signal: s?.signal
294
- });
295
- return r.ok || await this.handleErrorResponse(r), r;
296
- } catch (r) {
297
- throw r instanceof _ || M(r) ? r : new R(`Network error: ${r instanceof Error ? r.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, r instanceof Error ? r : void 0);
298
- }
362
+ this.functions = /* @__PURE__ */ new Map(), this.changeListeners = /* @__PURE__ */ new Set(), this.defaultMaxResultBytes = e?.maxResultBytes ?? Ie;
299
363
  }
300
- async postFormData(e, t, s) {
301
- const i = `${this.baseUrl}${e}`;
302
- l.debug("POST (formData)", i);
303
- const r = { ...this.headers };
304
- try {
305
- const n = await fetch(i, {
306
- method: "POST",
307
- headers: r,
308
- body: t,
309
- signal: s?.signal
310
- });
311
- return n.ok || await this.handleErrorResponse(n), n;
312
- } catch (n) {
313
- throw n instanceof _ || M(n) ? n : new R(`Network error: ${n instanceof Error ? n.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, n instanceof Error ? n : void 0);
314
- }
364
+ onChange(e) {
365
+ return this.changeListeners.add(e), () => {
366
+ this.changeListeners.delete(e);
367
+ };
315
368
  }
316
- async request(e, t, s, i) {
317
- const r = `${this.baseUrl}${t}`;
318
- l.debug(e, r, s);
319
- try {
320
- const n = await fetch(r, {
321
- method: e,
322
- headers: {
323
- ...this.headers,
324
- "Content-Type": "application/json"
325
- },
326
- body: s ? JSON.stringify(s) : void 0,
327
- ...i?.keepalive ? { keepalive: !0 } : {}
328
- });
329
- return n.ok || await this.handleErrorResponse(n), n.status === 204 ? void 0 : n.json();
330
- } catch (n) {
331
- throw n instanceof _ ? n : new R(`Network error: ${n instanceof Error ? n.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, n instanceof Error ? n : void 0);
369
+ emitChange() {
370
+ for (const e of this.changeListeners) try {
371
+ e();
372
+ } catch (t) {
373
+ l.error("Function registry change listener failed:", t);
332
374
  }
333
375
  }
334
- async handleErrorResponse(e) {
335
- let t;
336
- try {
337
- t = await e.json();
338
- } catch {
339
- }
340
- if (t?.error) throw _.fromResponse(t, e.status);
341
- let s = "";
342
- throw e.status === 401 || e.status === 403 ? s = " Check `userJwt` (and that it has not expired)." : e.status === 404 && (s = " Check that `baseUrl` points at your AGO API root."), new _(`HTTP ${e.status}: ${e.statusText}.${s}`, "http_error", e.status, "api_error");
343
- }
344
- }, Ae = 5e4, ke = 2e4, Re = 2e3, Ie = class {
345
- constructor(e) {
346
- this.functions = /* @__PURE__ */ new Map(), this.defaultMaxResultBytes = e?.maxResultBytes ?? Ae;
347
- }
348
376
  setDefaultMaxResultBytes(e) {
349
377
  this.defaultMaxResultBytes = e;
350
378
  }
@@ -353,31 +381,33 @@ var be = class {
353
381
  }
354
382
  register(e, t, s) {
355
383
  if (typeof e == "object") {
356
- const { name: o, handler: c, description: d, parameters: u, maxResultBytes: h, requiresApproval: f } = e;
357
- return this.register(o, c, {
384
+ const { name: c, handler: u, description: d, parameters: g, maxResultBytes: m, requiresApproval: v, webmcp: f } = e;
385
+ return this.register(c, u, {
358
386
  description: d,
359
- parameters: u,
360
- maxResultBytes: h,
361
- requiresApproval: f
387
+ parameters: g,
388
+ maxResultBytes: m,
389
+ requiresApproval: v,
390
+ webmcp: f
362
391
  });
363
392
  }
364
393
  const i = e;
365
- if (!t || !s) throw new S(`registerFunction("${i}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`, "function_invalid_registration");
394
+ if (!t || !s) throw new C(`registerFunction("${i}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`, "function_invalid_registration");
366
395
  this.functions.has(i) && l.warn(`Function "${i}" is being overwritten`);
367
- const { maxResultBytes: r, requiresApproval: n, ...a } = s;
396
+ const { maxResultBytes: r, requiresApproval: n, webmcp: a, ...o } = s;
368
397
  this.functions.set(i, {
369
398
  schema: {
370
- ...a,
399
+ ...o,
371
400
  name: i
372
401
  },
373
402
  handler: t,
374
403
  maxResultBytes: r,
375
- requiresApproval: n
376
- }), l.log(`Registered function: ${i}`);
404
+ requiresApproval: n,
405
+ webmcp: a
406
+ }), l.log(`Registered function: ${i}`), this.emitChange();
377
407
  }
378
408
  unregister(e) {
379
409
  const t = this.functions.delete(e);
380
- return t && l.log(`Unregistered function: ${e}`), t;
410
+ return t && (l.log(`Unregistered function: ${e}`), this.emitChange()), t;
381
411
  }
382
412
  get(e) {
383
413
  return this.functions.get(e);
@@ -388,15 +418,21 @@ var be = class {
388
418
  getSchemas() {
389
419
  return Array.from(this.functions.values()).map((e) => e.schema);
390
420
  }
421
+ getAll() {
422
+ return Array.from(this.functions.entries()).map(([e, t]) => ({
423
+ ...t,
424
+ name: e
425
+ }));
426
+ }
391
427
  async execute(e, t) {
392
428
  const s = this.functions.get(e);
393
- if (!s) throw new G(`Function "${e}" is not registered`, e);
429
+ if (!s) throw new H(`Function "${e}" is not registered`, e);
394
430
  l.log(`Executing function: ${e}`, t);
395
431
  try {
396
432
  const i = await s.handler(t);
397
433
  return l.log(`Function ${e} completed:`, i), this.guardResultSize(e, i, s.maxResultBytes);
398
434
  } catch (i) {
399
- throw l.error(`Function ${e} failed:`, i), new G(`Function "${e}" execution failed: ${i instanceof Error ? i.message : "Unknown error"}`, e, i instanceof Error ? i : void 0);
435
+ throw l.error(`Function ${e} failed:`, i), new H(`Function "${e}" execution failed: ${i instanceof Error ? i.message : "Unknown error"}`, e, i instanceof Error ? i : void 0);
400
436
  }
401
437
  }
402
438
  guardResultSize(e, t, s) {
@@ -412,46 +448,47 @@ var be = class {
412
448
  truncated: !0,
413
449
  originalBytes: r,
414
450
  maxBytes: n,
415
- preview: i.slice(0, Re),
451
+ preview: i.slice(0, Fe),
416
452
  hint: `The result of "${e}" exceeded the ${n}-byte limit and was truncated. Request less data (use limit or filter parameters if available), or tell the user the result is too large to process.`
417
- }) : (r > ke && l.warn(`Function "${e}" returned a large result (${Math.round(r / 1024)} KB). Large results consume LLM context: return fewer fields, paginate, or push the data to the UI and return a summary.`), t);
453
+ }) : (r > xe && l.warn(`Function "${e}" returned a large result (${Math.round(r / 1024)} KB). Large results consume LLM context: return fewer fields, paginate, or push the data to the UI and return a summary.`), t);
418
454
  }
419
455
  clear() {
420
- this.functions.clear(), l.log("Cleared all registered functions");
456
+ const e = this.functions.size > 0;
457
+ this.functions.clear(), l.log("Cleared all registered functions"), e && this.emitChange();
421
458
  }
422
459
  get size() {
423
460
  return this.functions.size;
424
461
  }
425
- }, Te = new TextEncoder();
426
- function p(e) {
427
- return Te.encode(e).length;
462
+ }, De = new TextEncoder();
463
+ function E(e) {
464
+ return De.encode(e).length;
428
465
  }
429
- function N(e) {
430
- return p(JSON.stringify(e)) - 2;
466
+ function O(e) {
467
+ return E(JSON.stringify(e)) - 2;
431
468
  }
432
- function ue(e, t) {
469
+ function fe(e, t) {
433
470
  if (t <= 0) return "";
434
471
  let s = "", i = 0;
435
472
  for (const r of e) {
436
- const n = N(r);
473
+ const n = O(r);
437
474
  if (i + n > t) break;
438
475
  s += r, i += n;
439
476
  }
440
477
  return s;
441
478
  }
442
- var xe = 50, Fe = 2;
443
- var De = 2e3;
444
- function C(e) {
479
+ var $e = 50, Pe = 2;
480
+ var Ne = 2e3;
481
+ function A(e) {
445
482
  try {
446
483
  return JSON.stringify(e);
447
484
  } catch {
448
485
  return;
449
486
  }
450
487
  }
451
- var P = /* @__PURE__ */ Symbol("ago.pageData.timeout");
452
- function $e(e, t) {
453
- return t <= 0 ? Promise.resolve(P) : new Promise((s, i) => {
454
- const r = setTimeout(() => s(P), t);
488
+ var j = /* @__PURE__ */ Symbol("ago.pageData.timeout");
489
+ function Oe(e, t) {
490
+ return t <= 0 ? Promise.resolve(j) : new Promise((s, i) => {
491
+ const r = setTimeout(() => s(j), t);
455
492
  e.then((n) => {
456
493
  clearTimeout(r), s(n);
457
494
  }, (n) => {
@@ -459,25 +496,25 @@ function $e(e, t) {
459
496
  });
460
497
  });
461
498
  }
462
- async function Me(e, t) {
499
+ async function je(e, t) {
463
500
  const s = Date.now() + t;
464
501
  let i = 0;
465
- for (; Date.now() < s && i < Fe; )
466
- i = e().isLoading?.() ? 0 : i + 1, await new Promise((o) => setTimeout(o, xe));
502
+ for (; Date.now() < s && i < Pe; )
503
+ i = e().isLoading?.() ? 0 : i + 1, await new Promise((o) => setTimeout(o, $e));
467
504
  const r = e().get();
468
- if (!X(r)) return r;
469
- const n = await $e(Promise.resolve(r), s - Date.now());
470
- if (n !== P) return n;
505
+ if (!Y(r)) return r;
506
+ const n = await Oe(Promise.resolve(r), s - Date.now());
507
+ if (n !== j) return n;
471
508
  l.warn("Page data did not resolve within the settle timeout; returning what the page has now. Raise settleTimeoutMs if the work legitimately takes longer.");
472
509
  const a = e().get();
473
- if (!X(a)) return a;
510
+ if (!Y(a)) return a;
474
511
  Promise.resolve(a).catch(() => {
475
512
  });
476
513
  }
477
- function X(e) {
514
+ function Y(e) {
478
515
  return typeof e == "object" && e !== null && typeof e.then == "function";
479
516
  }
480
- function Ne(e) {
517
+ function Le(e) {
481
518
  if (typeof e != "object" || e === null || Array.isArray(e)) return;
482
519
  const t = e;
483
520
  let s;
@@ -487,44 +524,44 @@ function Ne(e) {
487
524
  }
488
525
  return s;
489
526
  }
490
- function Pe(e, t) {
527
+ function Ue(e, t) {
491
528
  let s = 2, i = 0;
492
529
  for (const r of e) {
493
- const n = p(C(r) ?? "null") + (i > 0 ? 1 : 0);
530
+ const n = E(A(r) ?? "null") + (i > 0 ? 1 : 0);
494
531
  if (s + n > t) break;
495
532
  s += n, i++;
496
533
  }
497
534
  return i;
498
535
  }
499
- function O(e) {
536
+ function L(e) {
500
537
  return `The page data returned by "${e}" was too large to send in full. Only the first items are included: ask for fewer rows or narrow the filters to see the rest.`;
501
538
  }
502
- function Oe(e, t, s, i) {
539
+ function We(e, t, s, i) {
503
540
  const r = {
504
541
  truncated: !0,
505
542
  originalBytes: s,
506
543
  maxBytes: i,
507
544
  preview: "",
508
- hint: O(e)
509
- }, n = p(C(r) ?? "{}");
545
+ hint: L(e)
546
+ }, n = E(A(r) ?? "{}");
510
547
  return {
511
548
  ...r,
512
- preview: ue(t, Math.min(De, i - n))
549
+ preview: fe(t, Math.min(Ne, i - n))
513
550
  };
514
551
  }
515
- function je(e, t, s, i, r) {
516
- const n = s === void 0 ? {} : { ...t }, a = s ?? "items", o = p(C({
552
+ function Be(e, t, s, i, r) {
553
+ const n = s === void 0 ? {} : { ...t }, a = s ?? "items", o = E(A({
517
554
  ...n,
518
555
  [a]: [],
519
556
  truncation: {
520
557
  truncated: !0,
521
558
  returnedItems: i.length,
522
559
  totalItems: i.length,
523
- hint: O(e)
560
+ hint: L(e)
524
561
  }
525
562
  }) ?? "{}") - 2;
526
563
  if (o >= r) return;
527
- const c = i.slice(0, Pe(i, r - o));
564
+ const c = i.slice(0, Ue(i, r - o));
528
565
  return {
529
566
  ...n,
530
567
  [a]: c,
@@ -532,149 +569,149 @@ function je(e, t, s, i, r) {
532
569
  truncated: !0,
533
570
  returnedItems: c.length,
534
571
  totalItems: i.length,
535
- hint: O(e)
572
+ hint: L(e)
536
573
  }
537
574
  };
538
575
  }
539
- function V(e, t, s) {
540
- const i = C(t);
576
+ function Q(e, t, s) {
577
+ const i = A(t);
541
578
  if (i === void 0) return t;
542
- const r = p(i);
579
+ const r = E(i);
543
580
  if (r <= s) return t;
544
581
  l.warn(`Page data for "${e}" is ${r} bytes, over the ${s}-byte limit; it was truncated to the first items that fit. Return fewer fields per item, paginate, or raise maxResultBytes on the data source.`);
545
- const n = Ne(t), a = Array.isArray(t) ? t : n !== void 0 ? t[n] : void 0;
582
+ const n = Le(t), a = Array.isArray(t) ? t : n !== void 0 ? t[n] : void 0;
546
583
  if (a) {
547
- const o = je(e, t, n, a, s), c = p(C(o) ?? "");
584
+ const o = Be(e, t, n, a, s), c = E(A(o) ?? "");
548
585
  if (o !== void 0 && c <= s) return o;
549
586
  }
550
- return Oe(e, i, r, s);
587
+ return We(e, i, r, s);
551
588
  }
552
- function k(e, t) {
589
+ function R(e, t) {
553
590
  if (e === t) return !0;
554
591
  if (e === null || t === null || typeof e != "object" || typeof t != "object" || Array.isArray(e) !== Array.isArray(t)) return !1;
555
592
  if (Array.isArray(e))
556
- return e.length !== t.length ? !1 : e.every((r, n) => k(r, t[n]));
593
+ return e.length !== t.length ? !1 : e.every((r, n) => R(r, t[n]));
557
594
  const s = Object.keys(e), i = Object.keys(t);
558
- return s.length !== i.length ? !1 : s.every((r) => r in t && k(e[r], t[r]));
595
+ return s.length !== i.length ? !1 : s.every((r) => r in t && R(e[r], t[r]));
559
596
  }
560
- var z = 100, T = " … [truncated]", he = { truncated: !0 }, Ue = p(',"data":' + JSON.stringify(he));
561
- function j(e) {
562
- return p(JSON.stringify(e));
597
+ var Z = 100, x = " … [truncated]", ge = { truncated: !0 }, Ge = E(',"data":' + JSON.stringify(ge));
598
+ function U(e) {
599
+ return E(JSON.stringify(e));
563
600
  }
564
- function Y(e, t) {
565
- if (j(e) <= t || !e.rejected) return e;
566
- const s = Object.entries(e.rejected), i = Object.fromEntries(s.map(([o]) => [o, T])), r = {
601
+ function ee(e, t) {
602
+ if (U(e) <= t || !e.rejected) return e;
603
+ const s = Object.entries(e.rejected), i = Object.fromEntries(s.map(([o]) => [o, x])), r = {
567
604
  ...e,
568
605
  rejected: i
569
606
  };
570
- let n = j(r);
607
+ let n = U(r);
571
608
  if (n > t) return r;
572
- const a = N(T);
609
+ const a = O(x);
573
610
  for (const [o, c] of s) {
574
- const d = N(c), u = t - n + a;
575
- if (d <= u) {
576
- i[o] = c, n += d - a;
611
+ const u = O(c), d = t - n + a;
612
+ if (u <= d) {
613
+ i[o] = c, n += u - a;
577
614
  continue;
578
615
  }
579
- i[o] = ue(c, u - a) + T;
616
+ i[o] = fe(c, d - a) + x;
580
617
  break;
581
618
  }
582
619
  return r;
583
620
  }
584
- function E(e) {
621
+ function S(e) {
585
622
  return Array.isArray(e) ? "array" : typeof e;
586
623
  }
587
- function Q(e) {
588
- return typeof e != "number" ? `Expected type "number", got "${E(e)}".` : Number.isFinite(e) ? null : "Expected a finite number.";
624
+ function te(e) {
625
+ return typeof e != "number" ? `Expected type "number", got "${S(e)}".` : Number.isFinite(e) ? null : "Expected a finite number.";
589
626
  }
590
- function fe(e) {
591
- const t = e.slice(0, z).map((i) => JSON.stringify(i)), s = e.length - z;
627
+ function me(e) {
628
+ const t = e.slice(0, Z).map((i) => JSON.stringify(i)), s = e.length - Z;
592
629
  return s > 0 ? `${t.join(", ")} (${s} more not shown)` : t.join(", ");
593
630
  }
594
- function Z(e, t) {
595
- return t.includes(e) ? null : `${JSON.stringify(e)} is not an allowed value. Allowed values: ${fe(t)}.`;
631
+ function se(e, t) {
632
+ return t.includes(e) ? null : `${JSON.stringify(e)} is not an allowed value. Allowed values: ${me(t)}.`;
596
633
  }
597
- function Le(e, t) {
634
+ function qe(e, t) {
598
635
  const { schema: s } = t;
599
636
  if (s.type === "array") {
600
- if (!Array.isArray(e)) return `Expected type "array", got "${E(e)}".`;
637
+ if (!Array.isArray(e)) return `Expected type "array", got "${S(e)}".`;
601
638
  for (let r = 0; r < e.length; r++) {
602
639
  const n = e[r];
603
640
  if (s.items?.type) {
604
- const a = s.items.type === "number" ? Q(n) : E(n) !== s.items.type ? `Expected type "${s.items.type}", got "${E(n)}".` : null;
641
+ const a = s.items.type === "number" ? te(n) : S(n) !== s.items.type ? `Expected type "${s.items.type}", got "${S(n)}".` : null;
605
642
  if (a) return `Array item at index ${r}: ${a[0].toLowerCase()}${a.slice(1)}`;
606
643
  }
607
644
  if (s.items?.enum) {
608
- const a = Z(n, s.items.enum);
645
+ const a = se(n, s.items.enum);
609
646
  if (a) return `Array item ${a}`;
610
647
  }
611
648
  }
612
649
  return null;
613
650
  }
614
651
  if (s.type === "number") {
615
- const r = Q(e);
652
+ const r = te(e);
616
653
  if (r) return r;
617
- } else if (E(e) !== s.type) return `Expected type "${s.type}", got "${E(e)}".`;
618
- const i = ge(t);
619
- return i ? Z(e, i) : null;
654
+ } else if (S(e) !== s.type) return `Expected type "${s.type}", got "${S(e)}".`;
655
+ const i = pe(t);
656
+ return i ? se(e, i) : null;
620
657
  }
621
- function B(e) {
658
+ function q(e) {
622
659
  return e.clearable === !0 && e.schema.type === "string";
623
660
  }
624
- function ge(e) {
661
+ function pe(e) {
625
662
  const t = e.schema.enum;
626
663
  if (t)
627
- return B(e) && !t.includes("") ? [...t, ""] : t;
664
+ return q(e) && !t.includes("") ? [...t, ""] : t;
628
665
  }
629
- function Be(e) {
666
+ function Je(e) {
630
667
  const t = {
631
668
  ...e.schema,
632
669
  description: e.description
633
670
  };
634
- B(e) && (t.description = `${e.description} Pass "" to clear it.`);
635
- const s = ge(e);
671
+ q(e) && (t.description = `${e.description} Pass "" to clear it.`);
672
+ const s = pe(e);
636
673
  return s && (t.enum = s), t;
637
674
  }
638
- function We(e, t) {
675
+ function Ke(e, t) {
639
676
  const s = new Map(e.map((n) => [n.name, n])), i = e.map((n) => n.name), r = e.map((n) => `- "${n.name}": ${n.description}`).join(`
640
677
  `);
641
678
  return {
642
679
  name: t.name,
643
680
  handler: async (n) => {
644
681
  const a = [], o = [], c = {};
645
- for (const [g, v] of Object.entries(n)) {
646
- const w = s.get(g);
647
- if (!w) {
648
- c[g] = `"${g}" is not a registered control. Available controls: ${fe(i)}.`;
682
+ for (const [h, p] of Object.entries(n)) {
683
+ const y = s.get(h);
684
+ if (!y) {
685
+ c[h] = `"${h}" is not a registered control. Available controls: ${me(i)}.`;
649
686
  continue;
650
687
  }
651
- if (v == null || v === "" && !B(w)) continue;
652
- const W = Le(v, w);
653
- if (W) {
654
- c[g] = W;
688
+ if (p == null || p === "" && !q(y)) continue;
689
+ const b = qe(p, y);
690
+ if (b) {
691
+ c[h] = b;
655
692
  continue;
656
693
  }
657
- if (w.get && k(v, w.get())) {
658
- o.push(g);
694
+ if (y.get && R(p, y.get())) {
695
+ o.push(h);
659
696
  continue;
660
697
  }
661
- const b = await w.set(v);
662
- b ? b.result === "rejected" ? c[g] = b.reason || "The page rejected this field's update." : b.result === "unchanged" ? o.push(g) : a.push(g) : a.push(g);
698
+ const w = await y.set(p);
699
+ w ? w.result === "rejected" ? c[h] = w.reason || "The page rejected this field's update." : w.result === "unchanged" ? o.push(h) : a.push(h) : a.push(h);
663
700
  }
664
- const d = Object.keys(c).length > 0, u = {
665
- success: !d,
701
+ const u = Object.keys(c).length > 0, d = {
702
+ success: !u,
666
703
  applied: a,
667
704
  unchanged: o,
668
- ...d ? { rejected: c } : {}
669
- }, h = t.getResultBudget();
670
- if (!t.data) return Y(u, h);
671
- const f = Y(u, h - Ue), y = await t.data.read(f), m = {
672
- ...f,
673
- data: y
705
+ ...u ? { rejected: c } : {}
706
+ }, g = t.getResultBudget();
707
+ if (!t.data) return ee(d, g);
708
+ const m = ee(d, g - Ge), v = await t.data.read(m), f = {
709
+ ...m,
710
+ data: v
674
711
  };
675
- return j(m) <= h ? m : {
676
- ...f,
677
- data: he
712
+ return U(f) <= g ? f : {
713
+ ...m,
714
+ data: ge
678
715
  };
679
716
  },
680
717
  description: (e.length > 0 ? `Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
@@ -682,22 +719,22 @@ ${r}` : "The current page has no editable state — nothing to change here.") +
682
719
  Returns the resulting page data once it has loaded: ${t.data.description}` : ""),
683
720
  parameters: {
684
721
  type: "object",
685
- properties: Object.fromEntries(e.map((n) => [n.name, Be(n)])),
722
+ properties: Object.fromEntries(e.map((n) => [n.name, Je(n)])),
686
723
  required: []
687
724
  },
688
725
  requiresApproval: t.requiresApproval,
689
726
  maxResultBytes: t.data?.maxResultBytes
690
727
  };
691
728
  }
692
- var qe = 250, Ge = 3, Ke = 1e3, Je = 24, He = 10, Xe = 50, Ve = [
729
+ var He = 250, Xe = 3, ze = 1e3, Ve = 24, Ye = 10, Qe = 50, Ze = [
693
730
  "mousemove",
694
731
  "mousedown",
695
732
  "keydown",
696
733
  "scroll",
697
734
  "touchstart"
698
- ], ze = class {
735
+ ], et = class {
699
736
  constructor(e = {}) {
700
- this.started = !1, this.teardowns = [], this.route = "", this.routeEnteredAt = 0, this.lastActivityAt = 0, this.lastHeavyActivityAt = 0, this.recentRoutes = [], this.routeBounces = 0, this.rageClicks = 0, this.jsErrors = 0, this.fieldErrors = {}, this.recentClicks = [], this.signals = [], this.listeners = /* @__PURE__ */ new Set(), this.getPageState = e.getPageState, this.activityThrottleMs = e.activityThrottleMs ?? qe, this.rageClickCount = e.rageClickCount ?? Ge, this.rageClickWindowMs = e.rageClickWindowMs ?? Ke, this.rageClickRadiusPx = e.rageClickRadiusPx ?? Je, this.maxRecentRoutes = e.maxRecentRoutes ?? He, this.maxSignals = e.maxSignals ?? Xe;
737
+ this.started = !1, this.teardowns = [], this.route = "", this.routeEnteredAt = 0, this.lastActivityAt = 0, this.lastHeavyActivityAt = 0, this.recentRoutes = [], this.routeBounces = 0, this.rageClicks = 0, this.jsErrors = 0, this.fieldErrors = {}, this.recentClicks = [], this.signals = [], this.listeners = /* @__PURE__ */ new Set(), this.getPageState = e.getPageState, this.activityThrottleMs = e.activityThrottleMs ?? He, this.rageClickCount = e.rageClickCount ?? Xe, this.rageClickWindowMs = e.rageClickWindowMs ?? ze, this.rageClickRadiusPx = e.rageClickRadiusPx ?? Ve, this.maxRecentRoutes = e.maxRecentRoutes ?? Ye, this.maxSignals = e.maxSignals ?? Qe;
701
738
  }
702
739
  start() {
703
740
  if (this.started || typeof window > "u" || typeof document > "u") return;
@@ -707,7 +744,7 @@ var qe = 250, Ge = 3, Ke = 1e3, Je = 24, He = 10, Xe = 50, Ve = [
707
744
  const t = (i, r, n) => {
708
745
  i.addEventListener(r, n, { passive: !0 }), this.teardowns.push(() => i.removeEventListener(r, n));
709
746
  }, s = () => this.recordActivity();
710
- for (const i of Ve) t(window, i, s);
747
+ for (const i of Ze) t(window, i, s);
711
748
  t(document, "visibilitychange", () => {
712
749
  document.visibilityState === "visible" && this.recordActivity();
713
750
  }), t(window, "popstate", () => this.checkRoute()), t(window, "hashchange", () => this.checkRoute()), t(window, "click", (i) => this.onClick(i)), l.log("SignalCollector started");
@@ -833,7 +870,7 @@ var qe = 250, Ge = 3, Ke = 1e3, Je = 24, He = 10, Xe = 50, Ve = [
833
870
  }
834
871
  }
835
872
  };
836
- function Ye(e, t) {
873
+ function tt(e, t) {
837
874
  const s = t ? t.storage ?? (typeof localStorage < "u" ? localStorage : void 0) : void 0;
838
875
  let i = e;
839
876
  if (t && s) try {
@@ -858,23 +895,23 @@ function Ye(e, t) {
858
895
  })
859
896
  };
860
897
  }
861
- var Qe = 6e4, Ze = 1440 * 60 * 1e3, et = "ago_proactive";
862
- function x(e) {
898
+ var st = 6e4, it = 1440 * 60 * 1e3, rt = "ago_proactive";
899
+ function F(e) {
863
900
  const t = new Date(e), s = String(t.getMonth() + 1).padStart(2, "0"), i = String(t.getDate()).padStart(2, "0");
864
901
  return `${t.getFullYear()}-${s}-${i}`;
865
902
  }
866
- var tt = class {
903
+ var nt = class {
867
904
  constructor(e = {}) {
868
- this.killSwitchEnabled = !1, this.engaged = !1, this.turnInFlight = !1, this.slotOccupied = !1, this.sessionCount = 0, this.perSessionCap = e.frequencyCap?.perSession, this.perDayCap = e.frequencyCap?.perDay, this.store = Ye({
905
+ this.killSwitchEnabled = !1, this.engaged = !1, this.turnInFlight = !1, this.slotOccupied = !1, this.sessionCount = 0, this.perSessionCap = e.frequencyCap?.perSession, this.perDayCap = e.frequencyCap?.perDay, this.store = tt({
869
906
  optOut: !1,
870
907
  lastFiredAt: {},
871
908
  dismissedAt: {},
872
909
  day: {
873
- date: x(Date.now()),
910
+ date: F(Date.now()),
874
911
  count: 0
875
912
  }
876
913
  }, {
877
- key: e.storageKey ?? et,
914
+ key: e.storageKey ?? rt,
878
915
  storage: e.storage
879
916
  });
880
917
  }
@@ -918,9 +955,9 @@ var tt = class {
918
955
  if (this.engaged) return this.deny(e, "user engaged (widget open)");
919
956
  if (this.turnInFlight) return this.deny(e, "message turn in flight");
920
957
  if (this.slotOccupied) return this.deny(e, "nudge slot occupied");
921
- const i = s.lastFiredAt[e.id], r = e.cooldownMs ?? Qe;
958
+ const i = s.lastFiredAt[e.id], r = e.cooldownMs ?? st;
922
959
  if (i !== void 0 && t - i < r) return this.deny(e, "cooldown");
923
- const n = s.dismissedAt[e.id], a = e.resurfaceAfterMs ?? Ze;
960
+ const n = s.dismissedAt[e.id], a = e.resurfaceAfterMs ?? it;
924
961
  return n !== void 0 && t - n < a ? this.deny(e, "dismissed recently") : this.perSessionCap !== void 0 && this.sessionCount >= this.perSessionCap ? this.deny(e, "perSession cap") : this.perDayCap !== void 0 && this.dayCount(t) >= this.perDayCap ? this.deny(e, "perDay cap") : !0;
925
962
  }
926
963
  recordFired(e, t = Date.now()) {
@@ -935,7 +972,7 @@ var tt = class {
935
972
  }
936
973
  recordNudgeShown(e = Date.now()) {
937
974
  this.sessionCount += 1;
938
- const t = this.store.get(), s = x(e), i = t.day.date === s ? {
975
+ const t = this.store.get(), s = F(e), i = t.day.date === s ? {
939
976
  date: s,
940
977
  count: t.day.count + 1
941
978
  } : {
@@ -959,42 +996,42 @@ var tt = class {
959
996
  }
960
997
  dayCount(e) {
961
998
  const t = this.store.get();
962
- return t.day.date === x(e) ? t.day.count : 0;
999
+ return t.day.date === F(e) ? t.day.count : 0;
963
1000
  }
964
1001
  deny(e, t) {
965
1002
  return l.debug(`NudgeGovernor: trigger "${e.id}" blocked — ${t}`), !1;
966
1003
  }
967
1004
  };
968
- function ee() {
1005
+ function W() {
969
1006
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
970
1007
  const t = Math.floor(Math.random() * 16);
971
1008
  return (e === "x" ? t : t & 3 | 8).toString(16);
972
1009
  });
973
1010
  }
974
- function st(e) {
1011
+ function ot(e) {
975
1012
  return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
976
1013
  }
977
- function it(e, t) {
1014
+ function at(e, t) {
978
1015
  if (e === "*" || e === t) return !0;
979
1016
  const s = e.split("/"), i = s.map((r, n) => {
980
1017
  const a = n === s.length - 1;
981
- return r === "*" ? a ? "[^/]+(?:/[^/]+)*" : "[^/]+" : r.startsWith(":") ? "[^/]+" : st(r);
1018
+ return r === "*" ? a ? "[^/]+(?:/[^/]+)*" : "[^/]+" : r.startsWith(":") ? "[^/]+" : ot(r);
982
1019
  });
983
1020
  return new RegExp("^" + i.join("/") + "/?$").test(t);
984
1021
  }
985
- function me(e, t) {
986
- return e === t ? !0 : e === null || t === null ? !1 : Array.isArray(e) ? !Array.isArray(t) || t.length !== e.length ? !1 : e.every((s, i) => k(s, t[i])) : typeof e == "object" ? typeof t != "object" || Array.isArray(t) ? !1 : Object.entries(e).every(([s, i]) => me(i, t[s])) : !1;
1022
+ function ye(e, t) {
1023
+ return e === t ? !0 : e === null || t === null ? !1 : Array.isArray(e) ? !Array.isArray(t) || t.length !== e.length ? !1 : e.every((s, i) => R(s, t[i])) : typeof e == "object" ? typeof t != "object" || Array.isArray(t) ? !1 : Object.entries(e).every(([s, i]) => ye(i, t[s])) : !1;
987
1024
  }
988
- function rt(e, t) {
989
- if (e.route !== void 0 && !it(e.route, t.route) || e.idleMs !== void 0 && t.idleMs < e.idleMs || e.dwellMs !== void 0 && t.dwellMs < e.dwellMs || e.rageClicks !== void 0 && t.rageClicks < e.rageClicks || e.jsErrors !== void 0 && (t.jsErrors ?? 0) < e.jsErrors || e.routeBounces !== void 0 && t.routeBounces < e.routeBounces) return !1;
1025
+ function ct(e, t) {
1026
+ if (e.route !== void 0 && !at(e.route, t.route) || e.idleMs !== void 0 && t.idleMs < e.idleMs || e.dwellMs !== void 0 && t.dwellMs < e.dwellMs || e.rageClicks !== void 0 && t.rageClicks < e.rageClicks || e.jsErrors !== void 0 && (t.jsErrors ?? 0) < e.jsErrors || e.routeBounces !== void 0 && t.routeBounces < e.routeBounces) return !1;
990
1027
  if (e.fieldErrors !== void 0) {
991
1028
  for (const [s, i] of Object.entries(e.fieldErrors)) if ((t.fieldErrors[s] ?? 0) < i) return !1;
992
1029
  }
993
- return !(e.pageState !== void 0 && !me(e.pageState, t.pageState ?? {}));
1030
+ return !(e.pageState !== void 0 && !ye(e.pageState, t.pageState ?? {}));
994
1031
  }
995
- var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate", ct = class {
1032
+ var lt = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate", ht = class {
996
1033
  constructor(e) {
997
- this.tickTimer = null, this.teardowns = [], this.started = !1, this.activeNudge = null, this.lastConversationId = null, this.shownIds = /* @__PURE__ */ new Set(), this.resolvedIds = /* @__PURE__ */ new Set(), this.lastEvaluationAt = 0, this.client = e.client, this.collector = e.collector, this.governor = e.governor, this.tracker = e.tracker, this.options = e.options, this.tickMs = e.options.tickMs ?? nt;
1034
+ this.tickTimer = null, this.teardowns = [], this.started = !1, this.activeNudge = null, this.lastConversationId = null, this.shownIds = /* @__PURE__ */ new Set(), this.resolvedIds = /* @__PURE__ */ new Set(), this.lastEvaluationAt = 0, this.client = e.client, this.collector = e.collector, this.governor = e.governor, this.tracker = e.tracker, this.options = e.options, this.tickMs = e.options.tickMs ?? lt;
998
1035
  }
999
1036
  start() {
1000
1037
  if (this.started) return;
@@ -1020,7 +1057,7 @@ var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate",
1020
1057
  }
1021
1058
  async loadKillSwitch() {
1022
1059
  try {
1023
- const e = await this.client.getHttp().get(ot);
1060
+ const e = await this.client.getHttp().get(ut);
1024
1061
  this.governor.setKillSwitch(e?.proactive?.enabled === !0);
1025
1062
  } catch (e) {
1026
1063
  l.debug("Proactive config fetch failed; staying disabled:", e), this.governor.setKillSwitch(!1);
@@ -1030,7 +1067,7 @@ var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate",
1030
1067
  if (this.lastEvaluationAt = Date.now(), typeof document < "u" && document.visibilityState === "hidden" || this.governor.isSlotOccupied()) return;
1031
1068
  const e = this.collector.getSnapshot();
1032
1069
  for (const t of this.options.triggers)
1033
- if (rt(t.when, e) && this.governor.canFire(t)) {
1070
+ if (ct(t.when, e) && this.governor.canFire(t)) {
1034
1071
  this.fire(t);
1035
1072
  return;
1036
1073
  }
@@ -1041,7 +1078,7 @@ var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate",
1041
1078
  return;
1042
1079
  }
1043
1080
  this.setReady({
1044
- id: ee(),
1081
+ id: W(),
1045
1082
  triggerId: e.id,
1046
1083
  source: "static",
1047
1084
  message: e.intervene.message,
@@ -1052,7 +1089,7 @@ var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate",
1052
1089
  });
1053
1090
  }
1054
1091
  async evaluateWithAgent(e) {
1055
- const t = ee(), s = {
1092
+ const t = W(), s = {
1056
1093
  client_nudge_id: t,
1057
1094
  trigger_id: e.id,
1058
1095
  goal: e.goal ?? "",
@@ -1063,7 +1100,7 @@ var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate",
1063
1100
  };
1064
1101
  let i;
1065
1102
  try {
1066
- i = await this.client.getHttp().post(at, s);
1103
+ i = await this.client.getHttp().post(dt, s);
1067
1104
  } catch (r) {
1068
1105
  l.debug("Proactive evaluate failed (treated as no-intervene):", r), this.governor.releaseSlot();
1069
1106
  return;
@@ -1077,7 +1114,7 @@ var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate",
1077
1114
  triggerId: e.id,
1078
1115
  source: "agent",
1079
1116
  message: i.message,
1080
- action: lt(i.action),
1117
+ action: ft(i.action),
1081
1118
  goal: e.goal,
1082
1119
  kickoff: e.kickoff,
1083
1120
  createdAt: /* @__PURE__ */ new Date(),
@@ -1113,7 +1150,7 @@ var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate",
1113
1150
  source: e.source,
1114
1151
  type: "accepted",
1115
1152
  occurredAt: Date.now()
1116
- }), this.clearActive(e), this.client.emitProactiveEvent("nudge:accepted", { nudge: e }), (e.source === "agent" || e.goal) && (this.lastConversationId ? this.client.sendMessage(dt(e), {
1153
+ }), this.clearActive(e), this.client.emitProactiveEvent("nudge:accepted", { nudge: e }), (e.source === "agent" || e.goal) && (this.lastConversationId ? this.client.sendMessage(gt(e), {
1117
1154
  hidden: !0,
1118
1155
  conversationId: this.lastConversationId
1119
1156
  }).catch((t) => l.debug("Nudge kickoff message failed:", t)) : e.kickoff ? this.client.sendMessage(e.kickoff).catch((t) => l.debug("Nudge kickoff message failed:", t)) : l.debug("Nudge accepted with no open conversation and no trigger.kickoff; skipping the chat pre-seed (a hidden message cannot open a conversation).")), e.action && await this.runAction(e.action));
@@ -1138,7 +1175,7 @@ var nt = 1e3, ot = "/api/sdk/v1/config", at = "/api/sdk/v1/proactive/evaluate",
1138
1175
  }
1139
1176
  }
1140
1177
  };
1141
- function lt(e) {
1178
+ function ft(e) {
1142
1179
  if (e)
1143
1180
  return {
1144
1181
  label: e.label,
@@ -1146,13 +1183,13 @@ function lt(e) {
1146
1183
  arguments: e.arguments
1147
1184
  };
1148
1185
  }
1149
- function dt(e) {
1186
+ function gt(e) {
1150
1187
  const t = e.goal ? ` Goal: ${e.goal}.` : "";
1151
1188
  return `The user accepted a proactive nudge that said: "${e.message}".${t} Recent friction signals are in the client context (friction_signals). Start helping with this now: briefly explain what you can do and take the first concrete step.`;
1152
1189
  }
1153
- var ut = 5e3, ht = "/api/sdk/v1/proactive/events", ft = class {
1190
+ var mt = 5e3, pt = "/api/sdk/v1/proactive/events", yt = class {
1154
1191
  constructor(e) {
1155
- if (this.queue = [], this.flushTimer = null, this.teardowns = [], this.destroyed = !1, this.post = e.post, this.agent = e.agent, this.flushIntervalMs = e.flushIntervalMs ?? ut, typeof document < "u") {
1192
+ if (this.queue = [], this.flushTimer = null, this.teardowns = [], this.destroyed = !1, this.post = e.post, this.agent = e.agent, this.flushIntervalMs = e.flushIntervalMs ?? mt, typeof document < "u") {
1156
1193
  const t = () => {
1157
1194
  document.visibilityState === "hidden" && this.flush({ keepalive: !0 });
1158
1195
  };
@@ -1179,7 +1216,7 @@ var ut = 5e3, ht = "/api/sdk/v1/proactive/events", ft = class {
1179
1216
  ...this.agent ? { agent: this.agent } : {},
1180
1217
  occurred_at: new Date(i.occurredAt).toISOString()
1181
1218
  })) };
1182
- this.post(ht, s, e).catch((i) => {
1219
+ this.post(pt, s, e).catch((i) => {
1183
1220
  l.debug("Proactive event batch failed:", i);
1184
1221
  });
1185
1222
  }
@@ -1190,39 +1227,39 @@ var ut = 5e3, ht = "/api/sdk/v1/proactive/events", ft = class {
1190
1227
  this.teardowns = [];
1191
1228
  }
1192
1229
  }
1193
- }, te = "friction_signals";
1194
- function se(e, t) {
1230
+ }, ie = "friction_signals";
1231
+ function re(e, t) {
1195
1232
  e.proactive && (l.warn("createAgoProactive: a proactive controller is already attached; replacing it."), e.proactive.destroy());
1196
- const s = new ze({
1233
+ const s = new et({
1197
1234
  ...t.signals,
1198
1235
  getPageState: () => {
1199
1236
  const c = e.getContextSnapshot();
1200
1237
  if (!c) return null;
1201
- const d = {};
1202
- for (const [u, h] of Object.entries(c.entries)) u.startsWith("page-state:") && h.data && Object.assign(d, h.data);
1203
- return Object.keys(d).length > 0 ? d : null;
1238
+ const u = {};
1239
+ for (const [d, g] of Object.entries(c.entries)) d.startsWith("page-state:") && g.data && Object.assign(u, g.data);
1240
+ return Object.keys(u).length > 0 ? u : null;
1204
1241
  }
1205
1242
  });
1206
1243
  s.start();
1207
1244
  const i = (c) => {
1208
1245
  s.signalJsError(c.type);
1209
1246
  };
1210
- e.on("error:captured", i), e.addDynamicContext(te, () => {
1211
- const { pageState: c, ...d } = s.getSnapshot({ pageState: !1 });
1247
+ e.on("error:captured", i), e.addDynamicContext(ie, () => {
1248
+ const { pageState: c, ...u } = s.getSnapshot({ pageState: !1 });
1212
1249
  return {
1213
1250
  name: "Friction signals",
1214
1251
  description: "Behavioral friction observed on the current page: dwell/idle times, rage clicks, route bounces, repeated field errors, JavaScript error count (names and counters only).",
1215
- data: d
1252
+ data: u
1216
1253
  };
1217
1254
  });
1218
- const r = new tt({
1255
+ const r = new nt({
1219
1256
  frequencyCap: t.frequencyCap,
1220
1257
  storage: t.storage,
1221
1258
  storageKey: t.storageKey
1222
- }), n = new ft({
1223
- post: (c, d, u) => e.getHttp().post(c, d, u),
1259
+ }), n = new yt({
1260
+ post: (c, u, d) => e.getHttp().post(c, u, d),
1224
1261
  agent: e.getConfiguredAgent()
1225
- }), a = new ct({
1262
+ }), a = new ht({
1226
1263
  client: e,
1227
1264
  collector: s,
1228
1265
  governor: r,
@@ -1243,12 +1280,12 @@ function se(e, t) {
1243
1280
  dismiss: (c) => a.dismiss(c),
1244
1281
  markConverted: (c) => a.markConverted(c),
1245
1282
  destroy: () => {
1246
- a.stop(), n.destroy(), e.off("error:captured", i), s.destroy(), e.removeDynamicContext(te), e.proactive === o && (e.proactive = null);
1283
+ a.stop(), n.destroy(), e.off("error:captured", i), s.destroy(), e.removeDynamicContext(ie), e.proactive === o && (e.proactive = null);
1247
1284
  }
1248
1285
  };
1249
1286
  return e.proactive = o, o;
1250
1287
  }
1251
- var gt = class {
1288
+ var vt = class {
1252
1289
  constructor() {
1253
1290
  this.entries = /* @__PURE__ */ new Map(), this.dynamicProviders = /* @__PURE__ */ new Map();
1254
1291
  }
@@ -1281,48 +1318,48 @@ var gt = class {
1281
1318
  clear() {
1282
1319
  this.entries.clear(), this.dynamicProviders.clear(), l.log("ClientContext cleared");
1283
1320
  }
1284
- }, mt = "page-state:";
1285
- function pt(e) {
1321
+ }, wt = "page-state:";
1322
+ function Et(e) {
1286
1323
  const t = {};
1287
- for (const [s, i] of Object.entries(e)) s.startsWith(mt) && i.data && Object.assign(t, i.data);
1324
+ for (const [s, i] of Object.entries(e)) s.startsWith(wt) && i.data && Object.assign(t, i.data);
1288
1325
  return t;
1289
1326
  }
1290
- function yt(e) {
1327
+ function bt(e) {
1291
1328
  const t = e["current-page"]?.data;
1292
1329
  return t?.page ? t.page : t?.url ? t.url : e["browser-page"]?.data?.url;
1293
1330
  }
1294
- function vt(e, t) {
1331
+ function St(e, t) {
1295
1332
  return e === t ? !0 : JSON.stringify(e) === JSON.stringify(t);
1296
1333
  }
1297
- function wt(e, t) {
1334
+ function Ct(e, t) {
1298
1335
  const s = [];
1299
1336
  for (const i of Object.keys(t))
1300
- i in e && (vt(e[i], t[i]) || s.push({
1337
+ i in e && (St(e[i], t[i]) || s.push({
1301
1338
  field: i,
1302
1339
  from: e[i],
1303
1340
  to: t[i]
1304
1341
  }));
1305
1342
  return s;
1306
1343
  }
1307
- function Et(e, t) {
1308
- const s = pt(t), i = yt(t);
1344
+ function _t(e, t) {
1345
+ const s = Et(t), i = bt(t);
1309
1346
  return {
1310
- changes: e && e.page === i ? wt(e.state, s) : [],
1347
+ changes: e && e.page === i ? Ct(e.state, s) : [],
1311
1348
  baseline: {
1312
1349
  page: i,
1313
1350
  state: s
1314
1351
  }
1315
1352
  };
1316
1353
  }
1317
- function U(e) {
1318
- return e === null || typeof e != "object" ? JSON.stringify(e) ?? "null" : Array.isArray(e) ? `[${e.map(U).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${U(e[t])}`).join(",")}}`;
1354
+ function B(e) {
1355
+ return e === null || typeof e != "object" ? JSON.stringify(e) ?? "null" : Array.isArray(e) ? `[${e.map(B).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${B(e[t])}`).join(",")}}`;
1319
1356
  }
1320
- var ie = "", _t = class {
1357
+ var ne = "", At = class {
1321
1358
  constructor(e, t = {}) {
1322
1359
  this.callbacks = e, this.options = t, this.buffer = "", this.message = {}, this.toolCalls = [], this.sources = [], this.followUpReplies = [], this.isFirstChunk = !0, this.answerCompleteEmitted = !1, this.waitingClientEmitted = !1, this.firedClientFunctions = /* @__PURE__ */ new Map();
1323
1360
  }
1324
1361
  async processStream(e) {
1325
- if (!e.body) throw new q("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.", "stream_no_body");
1362
+ if (!e.body) throw new K("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.", "stream_no_body");
1326
1363
  const t = e.body.getReader(), s = new TextDecoder();
1327
1364
  try {
1328
1365
  for (; ; ) {
@@ -1335,7 +1372,7 @@ var ie = "", _t = class {
1335
1372
  } catch (i) {
1336
1373
  if (this.options.signal?.aborted)
1337
1374
  return this.message.status = "CANCELED", this.buildFinalMessage();
1338
- const r = i instanceof Error ? i : new q("Stream processing failed mid-flight. The connection may have dropped; retry the message.");
1375
+ const r = i instanceof Error ? i : new K("Stream processing failed mid-flight. The connection may have dropped; retry the message.");
1339
1376
  throw this.callbacks.onError?.(r), r;
1340
1377
  } finally {
1341
1378
  t.releaseLock();
@@ -1385,9 +1422,9 @@ var ie = "", _t = class {
1385
1422
  url: s.use_external_link ? s.external_link_url : s.internal_link_url
1386
1423
  };
1387
1424
  })), e.type === "client_function" && e.function_name) {
1388
- const t = `${e.function_name}::${U(e.arguments ?? {})}`, s = e.id || "", i = this.firedClientFunctions.get(t);
1425
+ const t = `${e.function_name}::${B(e.arguments ?? {})}`, s = e.id || "", i = this.firedClientFunctions.get(t);
1389
1426
  let r = !1;
1390
- i ? s && !i.has(s) && (i.has(ie) ? (i.delete(ie), i.add(s)) : (i.add(s), r = !0)) : (this.firedClientFunctions.set(t, /* @__PURE__ */ new Set([s])), r = !0), r && this.callbacks.onClientFunction?.({
1427
+ i ? s && !i.has(s) && (i.has(ne) ? (i.delete(ne), i.add(s)) : (i.add(s), r = !0)) : (this.firedClientFunctions.set(t, /* @__PURE__ */ new Set([s])), r = !0), r && this.callbacks.onClientFunction?.({
1391
1428
  invocationId: s,
1392
1429
  functionName: e.function_name,
1393
1430
  arguments: e.arguments || {},
@@ -1447,11 +1484,11 @@ var ie = "", _t = class {
1447
1484
  return e.status !== "WAITING_CLIENT" && this.callbacks.onComplete?.(e), e;
1448
1485
  }
1449
1486
  };
1450
- function Pt(e) {
1487
+ function Kt(e) {
1451
1488
  const t = e.message.toLowerCase();
1452
1489
  return t.includes("load failed") || t.includes("failed to fetch") || t.includes("network") || t.includes("abort");
1453
1490
  }
1454
- var St = /* @__PURE__ */ new Set([
1491
+ var kt = /* @__PURE__ */ new Set([
1455
1492
  "image/jpeg",
1456
1493
  "image/png",
1457
1494
  "image/gif",
@@ -1459,7 +1496,7 @@ var St = /* @__PURE__ */ new Set([
1459
1496
  "image/bmp",
1460
1497
  "image/tiff"
1461
1498
  ]);
1462
- function Ct(e) {
1499
+ function Rt(e) {
1463
1500
  if (!e) return;
1464
1501
  const t = typeof window < "u" && window.location ? window.location.href : "https://ago.local/";
1465
1502
  try {
@@ -1468,16 +1505,16 @@ function Ct(e) {
1468
1505
  } catch {
1469
1506
  }
1470
1507
  }
1471
- function Ot(e) {
1472
- return e.isSafeImage === !0 && typeof e.contentType == "string" && e.contentType.startsWith("image/") && Ct(e.url) !== void 0;
1508
+ function Ht(e) {
1509
+ return e.isSafeImage === !0 && typeof e.contentType == "string" && e.contentType.startsWith("image/") && Rt(e.url) !== void 0;
1473
1510
  }
1474
- function jt(e) {
1511
+ function Xt(e) {
1475
1512
  if (e == null || e < 0) return "";
1476
1513
  if (e < 1024) return `${e} B`;
1477
1514
  const t = e / 1024;
1478
1515
  return t < 1024 ? `${t.toFixed(1)} KB` : `${(t / 1024).toFixed(1)} MB`;
1479
1516
  }
1480
- function bt(e) {
1517
+ function Tt(e) {
1481
1518
  return {
1482
1519
  id: String(e.id ?? ""),
1483
1520
  name: typeof e.name == "string" && e.name ? e.name : "file",
@@ -1487,17 +1524,17 @@ function bt(e) {
1487
1524
  isSafeImage: e.is_safe_image === !0
1488
1525
  };
1489
1526
  }
1490
- function Ut(e) {
1527
+ function zt(e) {
1491
1528
  return e.map((t, s) => ({
1492
1529
  id: `local-${s}-${t.name}`,
1493
1530
  name: t.name,
1494
1531
  contentType: t.type || void 0,
1495
1532
  fileSize: t.size,
1496
1533
  url: typeof URL < "u" && URL.createObjectURL ? URL.createObjectURL(t) : void 0,
1497
- isSafeImage: St.has(t.type)
1534
+ isSafeImage: kt.has(t.type)
1498
1535
  }));
1499
1536
  }
1500
- var At = class {
1537
+ var It = class {
1501
1538
  constructor() {
1502
1539
  this.handlers = /* @__PURE__ */ new Map();
1503
1540
  }
@@ -1538,20 +1575,115 @@ var At = class {
1538
1575
  removeAllListeners(e) {
1539
1576
  e ? this.handlers.delete(e) : this.handlers.clear();
1540
1577
  }
1541
- }, re = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the public demo account https://playground.api.useago.com (agent generic-guide). See docs/general/configuration.md#error-codes (config_missing_base_url).', kt = /^[a-z][a-z0-9+.-]*:\/\//i, ne = !1;
1542
- function oe(e, t = "AgoClient") {
1543
- if (typeof e != "object" || e === null) throw new S(`${t}: ${re}`, "config_missing_base_url");
1578
+ }, xt = 4e3, Ft = 150, Mt = 600;
1579
+ function Dt() {
1580
+ if (!(typeof document > "u"))
1581
+ return document.modelContext;
1582
+ }
1583
+ function $t(e, t) {
1584
+ return new Promise((s) => {
1585
+ let i, r = !1;
1586
+ const n = () => {
1587
+ if (!r) {
1588
+ r = !0, clearTimeout(i), clearTimeout(c), clearTimeout(o);
1589
+ for (const d of t) d?.removeEventListener("abort", n);
1590
+ u(), s();
1591
+ }
1592
+ }, a = () => {
1593
+ clearTimeout(c), clearTimeout(i), i = setTimeout(n, Ft);
1594
+ }, o = setTimeout(n, xt), c = setTimeout(n, Mt), u = e(a);
1595
+ for (const d of t) {
1596
+ if (d?.aborted) return n();
1597
+ d?.addEventListener("abort", n);
1598
+ }
1599
+ });
1600
+ }
1601
+ function Pt(e) {
1602
+ const t = Dt();
1603
+ if (!t)
1604
+ return l.log("WebMCP is not available in this browser; bridge not attached"), () => {
1605
+ };
1606
+ const s = t, i = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Set(), n = new AbortController();
1607
+ let a = !1, o = !1;
1608
+ function c(f) {
1609
+ return JSON.stringify([
1610
+ f.description,
1611
+ f.inputSchema,
1612
+ f.annotations
1613
+ ]);
1614
+ }
1615
+ function u(f, h) {
1616
+ const p = e.getFunctionRegistrations().find((y) => y.name === f)?.webmcp;
1617
+ return !p || !p.navigates ? !1 : h?.success !== !1;
1618
+ }
1619
+ function d() {
1620
+ const f = /* @__PURE__ */ new Map();
1621
+ for (const h of e.getFunctionRegistrations()) {
1622
+ if (h.webmcp === !1) continue;
1623
+ const p = h.webmcp || void 0, y = h.name, b = {
1624
+ name: y,
1625
+ description: h.schema.description,
1626
+ inputSchema: h.schema.parameters,
1627
+ annotations: p?.annotations,
1628
+ execute: async (w, ve) => {
1629
+ const J = await e.runExternalFunction(y, w ?? {});
1630
+ return !a && u(y, J) && await $t((we) => e.onFunctionsChanged(we), [ve?.signal, n.signal]), J;
1631
+ }
1632
+ };
1633
+ f.set(y, {
1634
+ tool: b,
1635
+ signature: c(b)
1636
+ });
1637
+ }
1638
+ return f;
1639
+ }
1640
+ function g() {
1641
+ a || o || (o = !0, queueMicrotask(() => {
1642
+ o = !1, m();
1643
+ }));
1644
+ }
1645
+ function m() {
1646
+ if (a) return;
1647
+ const f = d();
1648
+ for (const [h, p] of i)
1649
+ f.get(h)?.signature !== p.signature && (p.controller.abort(), i.delete(h));
1650
+ for (const [h, p] of f) {
1651
+ if (i.has(h)) continue;
1652
+ const y = new AbortController();
1653
+ i.set(h, {
1654
+ signature: p.signature,
1655
+ controller: y
1656
+ }), Promise.resolve(s.registerTool(p.tool, { signal: y.signal })).catch((b) => {
1657
+ if (l.error(`WebMCP rejected the tool "${h}":`, b), i.get(h)?.controller !== y) return;
1658
+ i.delete(h);
1659
+ const w = JSON.stringify([h, p.signature]);
1660
+ r.has(w) || (r.add(w), g());
1661
+ });
1662
+ }
1663
+ }
1664
+ const v = e.onFunctionsChanged(g);
1665
+ return m(), l.log("WebMCP bridge attached"), () => {
1666
+ if (!a) {
1667
+ a = !0, n.abort(), v();
1668
+ for (const f of i.values()) f.controller.abort();
1669
+ i.clear(), l.log("WebMCP bridge detached");
1670
+ }
1671
+ };
1672
+ }
1673
+ var oe = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the public demo account https://playground.api.useago.com (agent generic-guide). See docs/general/configuration.md#error-codes (config_missing_base_url).', Nt = /^[a-z][a-z0-9+.-]*:\/\//i, ae = !1;
1674
+ function ce(e, t = "AgoClient") {
1675
+ if (typeof e != "object" || e === null) throw new C(`${t}: ${oe}`, "config_missing_base_url");
1544
1676
  const s = e.baseUrl;
1545
- if (typeof s != "string" || s.trim() === "") throw new S(`${t}: ${re}`, "config_missing_base_url");
1546
- !s.startsWith("/") && !kt.test(s) && (ne || (ne = !0, console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)));
1677
+ if (typeof s != "string" || s.trim() === "") throw new C(`${t}: ${oe}`, "config_missing_base_url");
1678
+ $(e.language), !s.startsWith("/") && !Nt.test(s) && (ae || (ae = !0, console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)));
1547
1679
  }
1548
- function Rt(e) {
1680
+ function Ot(e) {
1549
1681
  return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1550
1682
  }
1551
- function F(e) {
1683
+ function M(e) {
1552
1684
  return e.split("/").filter((t) => t.startsWith(":")).map((t) => t.slice(1));
1553
1685
  }
1554
- function It(e, t) {
1686
+ function jt(e, t) {
1555
1687
  const s = [];
1556
1688
  return {
1557
1689
  path: e.split("/").map((i) => {
@@ -1562,52 +1694,57 @@ function It(e, t) {
1562
1694
  missing: s
1563
1695
  };
1564
1696
  }
1565
- function Tt(e, t) {
1697
+ function Lt(e, t) {
1566
1698
  const s = t.find((r) => r.path === e);
1567
1699
  if (s) return s;
1568
1700
  const i = t.find((r) => {
1569
1701
  if (!r.path.includes(":")) return !1;
1570
- const n = "^" + r.path.split("/").map((a) => a.startsWith(":") ? "[^/]+" : Rt(a)).join("/") + "/?$";
1702
+ const n = "^" + r.path.split("/").map((a) => a.startsWith(":") ? "[^/]+" : Ot(a)).join("/") + "/?$";
1571
1703
  return new RegExp(n).test(e);
1572
1704
  });
1573
1705
  return i || t.filter((r) => r.path !== "/" && e.startsWith(r.path)).sort((r, n) => n.path.length - r.path.length)[0];
1574
1706
  }
1575
- var xt = "activity:recent", Ft = "state:delta", ae = "errors:recent";
1576
- function ce(e) {
1707
+ var Ut = "activity:recent", Wt = "state:delta", le = "errors:recent";
1708
+ function ue(e) {
1577
1709
  return e === "setPageState" ? "readPageData" : `read${e.charAt(0).toUpperCase()}${e.slice(1)}Data`;
1578
1710
  }
1579
- var Lt = class A {
1711
+ var Vt = class k {
1580
1712
  constructor(t) {
1581
- this.errorWatcher = null, this.lastSentPageState = null, this.warnedEmptyConversations = /* @__PURE__ */ new Set(), this.warnedPageDataPlaceholder = !1, this.pageDataCompanions = /* @__PURE__ */ new Set(), this.pendingResumes = /* @__PURE__ */ new Map(), this.pendingApprovals = /* @__PURE__ */ new Map(), this.resumeGate = null, this.activeTurn = null, this.pausedTurn = null, this.stoppedTurnIds = /* @__PURE__ */ new Set(), this.proactive = null, oe(t, "AgoClient"), this.config = t, this.activityLedger = new ye(t.maxActivityEntries), this.httpClient = new be(t), this.functionRegistry = new Ie({ maxResultBytes: t.maxFunctionResultBytes }), this.contextRegistry = new gt(), this.eventEmitter = new At(), this.registerActivityContext(), t.debug && l.enable(), t.errorWatcher && this.enableErrorWatcher(t.errorWatcher === !0 ? void 0 : t.errorWatcher), t.proactive && se(this, t.proactive), l.log("AgoClient initialized");
1713
+ this.errorWatcher = null, this.lastSentPageState = null, this.warnedEmptyConversations = /* @__PURE__ */ new Set(), this.warnedPageDataPlaceholder = !1, this.pageDataCompanions = /* @__PURE__ */ new Set(), this.pendingResumes = /* @__PURE__ */ new Map(), this.pendingApprovals = /* @__PURE__ */ new Map(), this.resumeGate = null, this.activeTurn = null, this.pausedTurn = null, this.stoppedTurnIds = /* @__PURE__ */ new Set(), this.proactive = null, this.detachWebMCP = null, ce(t, "AgoClient"), this.config = t, this.activityLedger = new be(t.maxActivityEntries), this.httpClient = new _e(t), this.functionRegistry = new Me({ maxResultBytes: t.maxFunctionResultBytes }), this.contextRegistry = new vt(), this.eventEmitter = new It(), this.registerActivityContext(), this.functionRegistry.onChange(() => {
1714
+ this.eventEmitter.emit("functions:changed", this.functionRegistry.getSchemas());
1715
+ }), t.debug && l.enable(), t.errorWatcher && this.enableErrorWatcher(t.errorWatcher === !0 ? void 0 : t.errorWatcher), t.proactive && re(this, t.proactive), this.attachWebMCPBridge(), l.log("AgoClient initialized");
1716
+ }
1717
+ attachWebMCPBridge() {
1718
+ !this.config.webmcp || this.detachWebMCP || (this.detachWebMCP = Pt(this));
1582
1719
  }
1583
1720
  async sendMessage(t, s) {
1584
- const i = this.functionRegistry.getSchemas(), r = this.buildSendContext(), n = this.config.agent || this.config.defaultAgentId, a = this.resolveClientFunctionsMode(s), o = s?.metadata !== void 0 ? s.metadata : this.config.metadata, c = o != null ? JSON.stringify(o) : void 0, d = {
1721
+ const i = this.functionRegistry.getSchemas(), r = this.buildSendContext(), n = this.config.agent || this.config.defaultAgentId, a = this.resolveClientFunctionsMode(s), o = s?.metadata !== void 0 ? s.metadata : this.config.metadata, c = o != null ? JSON.stringify(o) : void 0, u = {
1585
1722
  content: t,
1586
1723
  conversation_id: s?.conversationId,
1587
1724
  agent_id: s?.agentId || n
1588
1725
  };
1589
- o != null && (d.metadata = o), i.length > 0 && (d.client_functions = i, a === "pause" && (d.client_functions_mode = a)), r && (d.client_context = r), s?.hidden && (d.hidden = !0);
1590
- const u = this.beginTurn();
1591
- let h;
1726
+ o != null && (u.metadata = o), i.length > 0 && (u.client_functions = i, a === "pause" && (u.client_functions_mode = a)), r && (u.client_context = r), s?.hidden && (u.hidden = !0);
1727
+ const d = this.beginTurn();
1728
+ let g;
1592
1729
  if (s?.files && s.files.length > 0) {
1593
- const f = new FormData();
1594
- f.append("content", t), c !== void 0 && f.append("metadata", c), s.conversationId && f.append("conversation_id", s.conversationId), (s.agentId || n) && f.append("agent_id", s.agentId || n || ""), i.length > 0 && (f.append("client_functions", JSON.stringify(i)), a === "pause" && f.append("client_functions_mode", a)), r && f.append("client_context", JSON.stringify(r)), s.hidden && f.append("hidden", "true");
1595
- for (const y of s.files) f.append("files", y);
1596
- h = await this.sendRequest(u, () => this.httpClient.postFormData("/api/sdk/v1/messages", f, { signal: u.controller.signal }));
1597
- } else h = await this.sendRequest(u, () => this.httpClient.postStream("/api/sdk/v1/messages", d, { signal: u.controller.signal }));
1598
- return h ? this.processSSEResponse(h, u) : this.buildStoppedMessage(u);
1730
+ const m = new FormData();
1731
+ m.append("content", t), c !== void 0 && m.append("metadata", c), s.conversationId && m.append("conversation_id", s.conversationId), (s.agentId || n) && m.append("agent_id", s.agentId || n || ""), i.length > 0 && (m.append("client_functions", JSON.stringify(i)), a === "pause" && m.append("client_functions_mode", a)), r && m.append("client_context", JSON.stringify(r)), s.hidden && m.append("hidden", "true");
1732
+ for (const v of s.files) m.append("files", v);
1733
+ g = await this.sendRequest(d, () => this.httpClient.postFormData("/api/sdk/v1/messages", m, { signal: d.controller.signal }));
1734
+ } else g = await this.sendRequest(d, () => this.httpClient.postStream("/api/sdk/v1/messages", u, { signal: d.controller.signal }));
1735
+ return g ? this.processSSEResponse(g, d) : this.buildStoppedMessage(d);
1599
1736
  }
1600
1737
  async sendRequest(t, s) {
1601
1738
  try {
1602
1739
  return await s();
1603
1740
  } catch (i) {
1604
- if (this.endTurn(t), M(i)) return null;
1741
+ if (this.endTurn(t), P(i)) return null;
1605
1742
  throw i;
1606
1743
  }
1607
1744
  }
1608
1745
  async processSSEResponse(t, s) {
1609
1746
  let i = !1;
1610
- const r = new _t({
1747
+ const r = new At({
1611
1748
  onRawChunk: (n) => {
1612
1749
  s && (n.message_id && !s.messageId && (s.messageId = n.message_id), n.thread?.id && (s.conversationId = n.thread.id)), this.eventEmitter.emit("stream:message", n);
1613
1750
  },
@@ -1645,7 +1782,7 @@ var Lt = class A {
1645
1782
  onError: (n) => {
1646
1783
  this.eventEmitter.emit("message:error", {
1647
1784
  error: n.message,
1648
- code: n instanceof S ? n.code : void 0
1785
+ code: n instanceof C ? n.code : void 0
1649
1786
  });
1650
1787
  }
1651
1788
  }, { signal: s?.controller.signal });
@@ -1840,6 +1977,28 @@ var Lt = class A {
1840
1977
  result: i
1841
1978
  });
1842
1979
  }
1980
+ async runExternalFunction(t, s) {
1981
+ const i = {
1982
+ invocationId: `webmcp-${W()}`,
1983
+ functionName: t,
1984
+ arguments: s,
1985
+ conversationId: ""
1986
+ }, { invocationId: r } = i;
1987
+ this.eventEmitter.emit("function:invoke", i);
1988
+ try {
1989
+ const n = await this.functionRegistry.execute(t, s);
1990
+ return this.eventEmitter.emit("function:result", {
1991
+ invocationId: r,
1992
+ result: n
1993
+ }), n;
1994
+ } catch (n) {
1995
+ throw this.eventEmitter.emit("function:result", {
1996
+ invocationId: r,
1997
+ result: null,
1998
+ error: n instanceof Error ? n.message : String(n)
1999
+ }), n;
2000
+ }
2001
+ }
1843
2002
  async getConversations(t) {
1844
2003
  const s = new URLSearchParams();
1845
2004
  t?.page !== void 0 && s.set("page", String(t.page)), t?.pageSize !== void 0 && s.set("page_size", String(t.pageSize));
@@ -1867,8 +2026,13 @@ var Lt = class A {
1867
2026
  status: r.status,
1868
2027
  createdAt: new Date(r.created_at),
1869
2028
  hidden: r.hidden,
1870
- toolCalls: A.mapPersistedToolCalls(r.tool_call_data),
1871
- attachments: r.attachments && r.attachments.length > 0 ? r.attachments.map(bt) : void 0,
2029
+ sources: r.sources && r.sources.length > 0 ? r.sources.map(({ id: n, title: a, url: o }) => ({
2030
+ id: n,
2031
+ title: a,
2032
+ url: o ?? void 0
2033
+ })) : void 0,
2034
+ toolCalls: k.mapPersistedToolCalls(r.tool_call_data),
2035
+ attachments: r.attachments && r.attachments.length > 0 ? r.attachments.map(Tt) : void 0,
1872
2036
  followUpReplies: r.follow_up_replies && r.follow_up_replies.length > 0 ? r.follow_up_replies : void 0
1873
2037
  }))
1874
2038
  };
@@ -1897,6 +2061,10 @@ var Lt = class A {
1897
2061
  embedDescription: s.embed_description
1898
2062
  }));
1899
2063
  }
2064
+ async transcribeAudio(t, s) {
2065
+ const i = new FormData();
2066
+ return i.append("file", t, t.name), (await this.httpClient.postFormData("/api/sdk/v1/audio/transcriptions", i, s)).json();
2067
+ }
1900
2068
  async getConfig() {
1901
2069
  const t = await this.httpClient.get("/api/sdk/v1/config");
1902
2070
  return {
@@ -1908,10 +2076,11 @@ var Lt = class A {
1908
2076
  id: i.id,
1909
2077
  name: i.name ?? void 0
1910
2078
  })),
1911
- ticketForm: s.ticket_form ? A.mapTicketForm(s.ticket_form) : void 0,
1912
- homePage: s.home_page ? A.mapHomePage(s.home_page) : void 0,
2079
+ ticketForm: s.ticket_form ? k.mapTicketForm(s.ticket_form) : void 0,
2080
+ homePage: s.home_page ? k.mapHomePage(s.home_page) : void 0,
1913
2081
  fileAttachmentsEnabled: !!s.file_attachments_enabled,
1914
- voiceEnabled: !!s.voice_enabled
2082
+ voiceEnabled: !!s.voice_enabled,
2083
+ speechToTextEnabled: !!s.speech_to_text_enabled
1915
2084
  })),
1916
2085
  proactive: { enabled: !!t.proactive?.enabled }
1917
2086
  };
@@ -2012,19 +2181,19 @@ var Lt = class A {
2012
2181
  continue;
2013
2182
  }
2014
2183
  this.eventEmitter.emit("function:invoke", c);
2015
- let d, u;
2184
+ let u, d;
2016
2185
  try {
2017
- d = await this.functionRegistry.execute(o.functionName, o.arguments ?? {});
2018
- } catch (h) {
2019
- u = h instanceof Error ? h.message : "Unknown error", l.error("Client function execution failed:", h);
2186
+ u = await this.functionRegistry.execute(o.functionName, o.arguments ?? {});
2187
+ } catch (g) {
2188
+ d = g instanceof Error ? g.message : "Unknown error", l.error("Client function execution failed:", g);
2020
2189
  }
2021
2190
  this.eventEmitter.emit("function:result", {
2022
2191
  invocationId: o.id,
2023
- result: d,
2024
- error: u
2192
+ result: u,
2193
+ error: d
2025
2194
  }), a = (await this.submitToolCallForm(o.id, {
2026
- result: d,
2027
- error: u,
2195
+ result: u,
2196
+ error: d,
2028
2197
  _type: "client_function_result"
2029
2198
  }))?.resume?.ready ?? a;
2030
2199
  }
@@ -2066,7 +2235,7 @@ var Lt = class A {
2066
2235
  let r = i?.lastMessageId;
2067
2236
  if (!r) {
2068
2237
  const n = [...(await this.getConversation(t)).messages ?? []].reverse().find((a) => a.role === "assistant" && !a.hidden && !!a.content && a.status !== "IN_PROGRESS" && a.status !== "WAITING_CLIENT");
2069
- if (!n) throw new S(`Conversation ${t} has no finished answer to report feedback on. Wait for the turn to complete, or pass \`lastMessageId\`.`, "feedback_no_message");
2238
+ if (!n) throw new C(`Conversation ${t} has no finished answer to report feedback on. Wait for the turn to complete, or pass \`lastMessageId\`.`, "feedback_no_message");
2070
2239
  r = n.id;
2071
2240
  }
2072
2241
  return await this.submitFeedback(r, s, i), r;
@@ -2084,16 +2253,22 @@ var Lt = class A {
2084
2253
  getRegisteredFunctions() {
2085
2254
  return this.functionRegistry.getSchemas();
2086
2255
  }
2256
+ onFunctionsChanged(t) {
2257
+ return this.functionRegistry.onChange(t);
2258
+ }
2259
+ getFunctionRegistrations() {
2260
+ return this.functionRegistry.getAll();
2261
+ }
2087
2262
  async executeClientFunction(t, s) {
2088
2263
  return this.functionRegistry.execute(t, s);
2089
2264
  }
2090
2265
  registerNavigationFunction(t, s) {
2091
2266
  const i = s.map((o) => o.name), r = s.map((o) => {
2092
- const c = F(o.path), d = c.length > 0 ? ` (requires ${c.map((u) => `"${u}"`).join(", ")})` : "";
2093
- return `- "${o.name}"${d}: ${o.description}`;
2267
+ const c = M(o.path), u = c.length > 0 ? ` (requires ${c.map((d) => `"${d}"`).join(", ")})` : "";
2268
+ return `- "${o.name}"${u}: ${o.description}`;
2094
2269
  }).join(`
2095
2270
  `), n = /* @__PURE__ */ new Map();
2096
- for (const o of s) for (const c of F(o.path)) n.set(c, [...n.get(c) ?? [], o.name]);
2271
+ for (const o of s) for (const c of M(o.path)) n.set(c, [...n.get(c) ?? [], o.name]);
2097
2272
  const a = { page: {
2098
2273
  type: "string",
2099
2274
  description: "The page to navigate to",
@@ -2106,34 +2281,34 @@ var Lt = class A {
2106
2281
  }
2107
2282
  a[o] = {
2108
2283
  type: "string",
2109
- description: `Value for ":${o}" in the page path. Required when page is ${c.map((d) => `"${d}"`).join(" or ")}.`
2284
+ description: `Value for ":${o}" in the page path. Required when page is ${c.map((u) => `"${u}"`).join(" or ")}.`
2110
2285
  };
2111
2286
  }
2112
2287
  this.registerFunction("navigateToPage", async (o) => {
2113
- const c = o.page, d = s.find((m) => m.name === c);
2114
- if (!d) return {
2288
+ const c = o.page, u = s.find((f) => f.name === c);
2289
+ if (!u) return {
2115
2290
  success: !1,
2116
2291
  error: `Unknown page: ${c}`
2117
2292
  };
2118
- let u = {};
2293
+ let d = {};
2119
2294
  if (typeof o.params == "string") try {
2120
- u = JSON.parse(o.params);
2295
+ d = JSON.parse(o.params);
2121
2296
  } catch {
2122
2297
  }
2123
- else o.params && typeof o.params == "object" && (u = o.params);
2124
- const h = {};
2125
- for (const m of F(d.path)) h[m] = o[m] ?? u[m];
2126
- const { path: f, missing: y } = It(d.path, h);
2127
- if (y.length > 0) {
2128
- const m = y.map((g) => `"${g}": "..."`).join(", ");
2298
+ else o.params && typeof o.params == "object" && (d = o.params);
2299
+ const g = {};
2300
+ for (const f of M(u.path)) g[f] = o[f] ?? d[f];
2301
+ const { path: m, missing: v } = jt(u.path, g);
2302
+ if (v.length > 0) {
2303
+ const f = v.map((h) => `"${h}": "..."`).join(", ");
2129
2304
  return {
2130
2305
  success: !1,
2131
- error: `Page "${c}" needs ${y.map((g) => `"${g}"`).join(", ")}. Retry with { "page": "${c}", ${m} }.`
2306
+ error: `Page "${c}" needs ${v.map((h) => `"${h}"`).join(", ")}. Retry with { "page": "${c}", ${f} }.`
2132
2307
  };
2133
2308
  }
2134
- return t(f), {
2309
+ return t(m), {
2135
2310
  success: !0,
2136
- navigatedTo: f
2311
+ navigatedTo: m
2137
2312
  };
2138
2313
  }, {
2139
2314
  description: `Navigate the user to a page in the application. Available pages:
@@ -2142,14 +2317,15 @@ ${r}`,
2142
2317
  type: "object",
2143
2318
  properties: a,
2144
2319
  required: ["page"]
2145
- }
2320
+ },
2321
+ webmcp: { navigates: !0 }
2146
2322
  }), this.addDynamicContext("current-page", () => {
2147
2323
  if (typeof window > "u" || !window.location) return null;
2148
- const o = window.location.href, c = typeof document < "u" ? document.title : void 0, d = Tt(window.location.pathname, s), u = { url: o };
2149
- return d && (u.page = d.name), c && (u.title = c), {
2324
+ const o = window.location.href, c = typeof document < "u" ? document.title : void 0, u = Lt(window.location.pathname, s), d = { url: o };
2325
+ return u && (d.page = u.name), c && (d.title = c), {
2150
2326
  name: "Current page",
2151
2327
  description: "The page the user is currently viewing.",
2152
- data: u
2328
+ data: d
2153
2329
  };
2154
2330
  });
2155
2331
  }
@@ -2158,18 +2334,18 @@ ${r}`,
2158
2334
  }
2159
2335
  registerPageStateFunction(t, s) {
2160
2336
  const i = s?.functionName ?? "setPageState", r = s?.data;
2161
- this.registerFunction(We(t, {
2337
+ this.registerFunction(Ke(t, {
2162
2338
  name: i,
2163
2339
  requiresApproval: s?.requiresApproval,
2164
2340
  getResultBudget: () => r ? this.pageDataBudget(r) : this.functionRegistry.getDefaultMaxResultBytes(),
2165
2341
  data: r ? {
2166
2342
  description: r.description,
2167
2343
  maxResultBytes: r.maxResultBytes,
2168
- read: async (a) => V(i, await this.readPageData(i, r, s), this.pageDataBudget(r) - this.envelopeBytes(a))
2344
+ read: async (a) => Q(i, await this.readPageData(i, r, s), this.pageDataBudget(r) - this.envelopeBytes(a))
2169
2345
  } : void 0
2170
2346
  }));
2171
- const n = ce(i);
2172
- r ? (this.warnIfPlaceholderMode(i), this.registerFunction(n, async () => ({ data: V(i, await this.readPageData(i, r, s), this.pageDataBudget(r) - this.envelopeBytes({})) }), {
2347
+ const n = ue(i);
2348
+ r ? (this.warnIfPlaceholderMode(i), this.registerFunction(n, async () => ({ data: Q(i, await this.readPageData(i, r, s), this.pageDataBudget(r) - this.envelopeBytes({})) }), {
2173
2349
  description: `Read what the current page is displaying, without changing anything: ${r.description}`,
2174
2350
  parameters: {
2175
2351
  type: "object",
@@ -2191,20 +2367,20 @@ ${r}`,
2191
2367
  unregisterPageStateFunction(t) {
2192
2368
  const s = t ?? "setPageState";
2193
2369
  this.unregisterFunction(s);
2194
- const i = ce(s);
2370
+ const i = ue(s);
2195
2371
  this.pageDataCompanions.delete(i) && this.unregisterFunction(i), this.removeDynamicContext(`page-state:${s}`);
2196
2372
  }
2197
2373
  pageDataBudget(t) {
2198
2374
  return t.maxResultBytes ?? this.functionRegistry.getDefaultMaxResultBytes();
2199
2375
  }
2200
2376
  envelopeBytes(t) {
2201
- return p(JSON.stringify({
2377
+ return E(JSON.stringify({
2202
2378
  ...t,
2203
2379
  data: null
2204
2380
  })) - 4;
2205
2381
  }
2206
2382
  readPageData(t, s, i) {
2207
- return Me(() => s, i?.settleTimeoutMs ?? 1e4).catch((r) => (l.warn(`Reading page data for "${t}" failed:`, r), {
2383
+ return je(() => s, i?.settleTimeoutMs ?? 1e4).catch((r) => (l.warn(`Reading page data for "${t}" failed:`, r), {
2208
2384
  error: "page_data_unavailable",
2209
2385
  message: r instanceof Error ? r.message : String(r)
2210
2386
  }));
@@ -2264,10 +2440,10 @@ ${r}`,
2264
2440
  return this.contextRegistry.getSnapshot();
2265
2441
  }
2266
2442
  buildSendContext() {
2267
- const t = this.contextRegistry.getSnapshot(), s = t?.entries ?? {}, { changes: i, baseline: r } = Et(this.lastSentPageState, s);
2443
+ const t = this.contextRegistry.getSnapshot(), s = t?.entries ?? {}, { changes: i, baseline: r } = _t(this.lastSentPageState, s);
2268
2444
  return this.lastSentPageState = r, i.length === 0 ? t : { entries: {
2269
2445
  ...s,
2270
- [Ft]: {
2446
+ [Wt]: {
2271
2447
  name: "State changes",
2272
2448
  description: "Fields in the page state that changed since your last message, as field: <old> -> <new>.",
2273
2449
  data: { changes: i }
@@ -2302,7 +2478,7 @@ ${r}`,
2302
2478
  });
2303
2479
  }
2304
2480
  registerActivityContext() {
2305
- this.contextRegistry.addDynamicProvider(xt, () => {
2481
+ this.contextRegistry.addDynamicProvider(Ut, () => {
2306
2482
  const t = this.activityLedger.getRecent();
2307
2483
  return t.length === 0 ? null : {
2308
2484
  name: "Recent activity",
@@ -2313,10 +2489,10 @@ ${r}`,
2313
2489
  }
2314
2490
  enableErrorWatcher(t) {
2315
2491
  this.disableErrorWatcher();
2316
- const s = new Se(t);
2492
+ const s = new Te(t);
2317
2493
  this.errorWatcher = s, s.start(), s.subscribe((i) => {
2318
2494
  this.eventEmitter.emit("error:captured", i), this.notifyContextChanged();
2319
- }), this.contextRegistry.addDynamicProvider(ae, () => {
2495
+ }), this.contextRegistry.addDynamicProvider(le, () => {
2320
2496
  const i = s.getErrors();
2321
2497
  if (i.length === 0) return null;
2322
2498
  const r = Date.now();
@@ -2332,7 +2508,7 @@ ${r}`,
2332
2508
  });
2333
2509
  }
2334
2510
  disableErrorWatcher() {
2335
- this.errorWatcher && (this.errorWatcher.destroy(), this.errorWatcher = null, this.contextRegistry.removeDynamicProvider(ae));
2511
+ this.errorWatcher && (this.errorWatcher.destroy(), this.errorWatcher = null, this.contextRegistry.removeDynamicProvider(le));
2336
2512
  }
2337
2513
  reportError(t, s) {
2338
2514
  if (!this.errorWatcher) {
@@ -2366,43 +2542,43 @@ ${r}`,
2366
2542
  ...this.config,
2367
2543
  ...s
2368
2544
  };
2369
- oe(i, "AgoClient.updateConfig"), this.config = i, this.httpClient.updateConfig(s), s.debug !== void 0 && (s.debug ? l.enable() : l.disable()), s.maxFunctionResultBytes !== void 0 && this.functionRegistry.setDefaultMaxResultBytes(s.maxFunctionResultBytes), s.errorWatcher !== void 0 && (s.errorWatcher ? this.enableErrorWatcher(s.errorWatcher === !0 ? void 0 : s.errorWatcher) : this.disableErrorWatcher());
2545
+ ce(i, "AgoClient.updateConfig"), this.config = i, this.httpClient.updateConfig(s), s.debug !== void 0 && (s.debug ? l.enable() : l.disable()), s.maxFunctionResultBytes !== void 0 && this.functionRegistry.setDefaultMaxResultBytes(s.maxFunctionResultBytes), s.errorWatcher !== void 0 && (s.errorWatcher ? this.enableErrorWatcher(s.errorWatcher === !0 ? void 0 : s.errorWatcher) : this.disableErrorWatcher());
2370
2546
  }
2371
2547
  destroy() {
2372
- this.proactive?.destroy(), this.proactive = null, this.errorWatcher?.destroy(), this.errorWatcher = null, this.activeTurn?.controller.abort(), this.activeTurn = null, this.pausedTurn = null, this.stoppedTurnIds.clear(), this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), this.pendingResumes.clear(), this.pendingApprovals.clear(), this.resumeGate = null, l.log("AgoClient destroyed");
2548
+ this.proactive?.destroy(), this.proactive = null, this.errorWatcher?.destroy(), this.errorWatcher = null, this.detachWebMCP?.(), this.detachWebMCP = null, this.activeTurn?.controller.abort(), this.activeTurn = null, this.pausedTurn = null, this.stoppedTurnIds.clear(), this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), this.pendingResumes.clear(), this.pendingApprovals.clear(), this.resumeGate = null, l.log("AgoClient destroyed");
2373
2549
  }
2374
2550
  reviveAfterDestroy() {
2375
- this.registerActivityContext(), this.config.errorWatcher && !this.errorWatcher && this.enableErrorWatcher(this.config.errorWatcher === !0 ? void 0 : this.config.errorWatcher), this.config.proactive && !this.proactive && se(this, this.config.proactive);
2551
+ this.registerActivityContext(), this.config.errorWatcher && !this.errorWatcher && this.enableErrorWatcher(this.config.errorWatcher === !0 ? void 0 : this.config.errorWatcher), this.config.proactive && !this.proactive && re(this, this.config.proactive), this.attachWebMCPBridge();
2376
2552
  }
2377
- }, Bt = [
2553
+ }, Yt = [
2378
2554
  "inaccurate",
2379
2555
  "incomplete",
2380
2556
  "information_not_found",
2381
2557
  "technical_issue"
2382
2558
  ];
2383
2559
  export {
2384
- ye as C,
2560
+ be as C,
2385
2561
  l as S,
2386
- ze as _,
2387
- Ut as a,
2388
- Nt as b,
2389
- Ct as c,
2390
- gt as d,
2391
- se as f,
2392
- Ye as g,
2393
- me as h,
2394
- At as i,
2395
- _t as l,
2396
- rt as m,
2397
- Lt as n,
2398
- Ot as o,
2399
- it as p,
2400
- oe as r,
2401
- jt as s,
2402
- Bt as t,
2403
- Pt as u,
2404
- Ie as v,
2405
- $t as w,
2406
- Se as x,
2407
- Mt as y
2562
+ et as _,
2563
+ zt as a,
2564
+ Jt as b,
2565
+ Rt as c,
2566
+ vt as d,
2567
+ re as f,
2568
+ tt as g,
2569
+ ye as h,
2570
+ It as i,
2571
+ At as l,
2572
+ ct as m,
2573
+ Vt as n,
2574
+ Ht as o,
2575
+ at as p,
2576
+ ce as r,
2577
+ Xt as s,
2578
+ Yt as t,
2579
+ Kt as u,
2580
+ Me as v,
2581
+ Gt as w,
2582
+ Te as x,
2583
+ qt as y
2408
2584
  };