@useago/sdk 1.5.6 → 1.7.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 (42) hide show
  1. package/CHANGELOG.md +223 -0
  2. package/README.md +59 -0
  3. package/dist/AgoClient-BHegN73y.cjs +9 -0
  4. package/dist/{AgoClient-B_R_qi2s.js → AgoClient-PWPaekcg.js} +656 -387
  5. package/dist/angular.cjs +1 -1
  6. package/dist/angular.d.cts +230 -5
  7. package/dist/angular.d.ts +230 -5
  8. package/dist/angular.js +10 -1
  9. package/dist/{createConversationSession-Dqh7NXK4.cjs → createConversationSession-BbUUukV0.cjs} +1 -1
  10. package/dist/{createConversationSession-CdtI4vrf.js → createConversationSession-BkruoOVm.js} +1 -1
  11. package/dist/{createFormCollector-BjO3oB63.cjs → createFormCollector-C1ixsjV0.cjs} +1 -1
  12. package/dist/{createFormCollector-YwaZ78wU.js → createFormCollector-CvVFNkp6.js} +1 -1
  13. package/dist/{createMockClient-DcuNlufr.js → createMockClient-BDLW6tVc.js} +5 -2
  14. package/dist/createMockClient-BSNuN3ys.cjs +1 -0
  15. package/dist/devtools.d.cts +220 -5
  16. package/dist/devtools.d.ts +220 -5
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.d.cts +238 -6
  19. package/dist/index.d.ts +238 -6
  20. package/dist/index.js +111 -109
  21. package/dist/react.cjs +40 -3
  22. package/dist/react.d.cts +419 -7
  23. package/dist/react.d.ts +419 -7
  24. package/dist/react.js +1195 -743
  25. package/dist/sheetController-CBUVOroo.js +205 -0
  26. package/dist/sheetController-DY-sC13T.cjs +1 -0
  27. package/dist/testing.cjs +1 -1
  28. package/dist/testing.d.cts +220 -5
  29. package/dist/testing.d.ts +220 -5
  30. package/dist/testing.js +1 -1
  31. package/dist/vue.cjs +1 -1
  32. package/dist/vue.d.cts +235 -5
  33. package/dist/vue.d.ts +235 -5
  34. package/dist/vue.js +121 -100
  35. package/dist/widget.cjs +4 -4
  36. package/dist/widget.d.cts +328 -5
  37. package/dist/widget.d.ts +328 -5
  38. package/dist/widget.js +721 -629
  39. package/llms-full.txt +202 -14
  40. package/package.json +1 -1
  41. package/dist/AgoClient-DLB9icvv.cjs +0 -8
  42. package/dist/createMockClient-Dw-cyISN.cjs +0 -1
@@ -1,34 +1,34 @@
1
- var Ut = 10, b = 1e3;
2
- function M(t) {
1
+ var ie = 10, x = 1e3;
2
+ function J(t) {
3
3
  if (typeof t != "object" || t === null) return !1;
4
4
  const e = Object.getPrototypeOf(t);
5
5
  return e === Object.prototype || e === null;
6
6
  }
7
- function A(t, e) {
7
+ function b(t, e) {
8
8
  if (typeof t == "string") {
9
9
  if (t.length <= 1e3) return t;
10
- const s = t.length - b;
11
- return t.slice(0, b) + `…[truncated ${s} chars]`;
10
+ const s = t.length - x;
11
+ return t.slice(0, x) + `…[truncated ${s} chars]`;
12
12
  }
13
13
  if (Array.isArray(t)) {
14
14
  if (e.has(t)) return "…[circular]";
15
15
  e.add(t);
16
- const s = t.slice(0, 50).map((i) => A(i, e));
16
+ const s = t.slice(0, 50).map((i) => b(i, e));
17
17
  return t.length > 50 && s.push(`…[+${t.length - 50} more]`), e.delete(t), s;
18
18
  }
19
- if (M(t)) {
19
+ if (J(t)) {
20
20
  if (e.has(t)) return "…[circular]";
21
21
  e.add(t);
22
22
  const s = {};
23
- for (const [i, n] of Object.entries(t)) s[i] = A(n, e);
23
+ for (const [i, n] of Object.entries(t)) s[i] = b(n, e);
24
24
  return e.delete(t), s;
25
25
  }
26
26
  return t;
27
27
  }
28
- function L(t) {
29
- return A(t, /* @__PURE__ */ new WeakSet());
28
+ function z(t) {
29
+ return b(t, /* @__PURE__ */ new WeakSet());
30
30
  }
31
- var j = class {
31
+ var X = class {
32
32
  constructor(t = 10) {
33
33
  this.entries = [];
34
34
  const e = Math.floor(t);
@@ -40,7 +40,7 @@ var j = class {
40
40
  actor: t.actor ?? "user",
41
41
  name: t.name,
42
42
  summary: t.summary,
43
- ...t.data !== void 0 ? { data: L(t.data) } : {}
43
+ ...t.data !== void 0 ? { data: z(t.data) } : {}
44
44
  };
45
45
  this.entries.push(e);
46
46
  const s = this.entries.length - this.maxEntries;
@@ -59,27 +59,27 @@ var j = class {
59
59
  constructor(t, e, s) {
60
60
  super(t), this.code = e, this.statusCode = s, this.name = "AgoError";
61
61
  }
62
- }, p = class P extends g {
63
- constructor(e, s, i, n, o, a) {
64
- super(e, s, i), this.type = n, this.param = o, this.docUrl = a, this.name = "AgoApiError";
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
65
  }
66
66
  static fromResponse(e, s) {
67
67
  const i = e.error;
68
- return new P(i.doc_url ? `${i.message} See ${i.doc_url}` : i.message, i.code, s, i.type, i.param, i.doc_url);
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
69
  }
70
- }, w = class extends g {
70
+ }, S = class extends g {
71
71
  constructor(t, e) {
72
72
  super(t, "network_error"), this.originalError = e, this.name = "AgoNetworkError";
73
73
  }
74
- }, k = class extends g {
74
+ }, F = class extends g {
75
75
  constructor(t, e = "stream_error") {
76
76
  super(t, e), this.name = "AgoStreamError";
77
77
  }
78
- }, R = class extends g {
78
+ }, D = class extends g {
79
79
  constructor(t, e, s) {
80
80
  super(t, "function_error"), this.functionName = e, this.originalError = s, this.name = "AgoFunctionError";
81
81
  }
82
- }, B = class {
82
+ }, Y = class {
83
83
  constructor(t = !1) {
84
84
  this.enabled = t;
85
85
  }
@@ -101,22 +101,25 @@ var j = class {
101
101
  debug(...t) {
102
102
  this.enabled && console.debug("[AGO SDK]", ...t);
103
103
  }
104
- }, c = new B(), I = "ago_widget_id";
105
- function G() {
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() {
106
109
  if (typeof localStorage < "u") {
107
- const e = localStorage.getItem(I);
110
+ const e = localStorage.getItem($);
108
111
  if (e) return e;
109
112
  }
110
113
  const t = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
111
114
  if (typeof localStorage < "u") try {
112
- localStorage.setItem(I, t);
115
+ localStorage.setItem($, t);
113
116
  } catch {
114
117
  }
115
118
  return t;
116
119
  }
117
- var K = class {
120
+ var Q = class {
118
121
  constructor(t) {
119
- this.baseUrl = t.baseUrl.replace(/\/$/, ""), this.headers = { "X-User-Anon-Id": t.widgetId || G() }, 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);
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);
120
123
  }
121
124
  updateConfig(t) {
122
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"]);
@@ -127,43 +130,45 @@ var K = class {
127
130
  async post(t, e, s) {
128
131
  return this.request("POST", t, e, s);
129
132
  }
130
- async postStream(t, e) {
131
- const s = `${this.baseUrl}${t}`;
132
- c.debug("POST (stream)", s, e);
133
+ async postStream(t, e, s) {
134
+ const i = `${this.baseUrl}${t}`;
135
+ l.debug("POST (stream)", i, e);
133
136
  try {
134
- const i = await fetch(s, {
137
+ const n = await fetch(i, {
135
138
  method: "POST",
136
139
  headers: {
137
140
  ...this.headers,
138
141
  "Content-Type": "application/json"
139
142
  },
140
- body: e ? JSON.stringify(e) : void 0
143
+ body: e ? JSON.stringify(e) : void 0,
144
+ signal: s?.signal
141
145
  });
142
- return i.ok || await this.handleErrorResponse(i), i;
143
- } catch (i) {
144
- throw i instanceof p ? i : new w(`Network error: ${i instanceof Error ? i.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, i instanceof Error ? i : void 0);
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);
145
149
  }
146
150
  }
147
- async postFormData(t, e) {
148
- const s = `${this.baseUrl}${t}`;
149
- c.debug("POST (formData)", s);
150
- const i = { ...this.headers };
151
+ async postFormData(t, e, s) {
152
+ const i = `${this.baseUrl}${t}`;
153
+ l.debug("POST (formData)", i);
154
+ const n = { ...this.headers };
151
155
  try {
152
- const n = await fetch(s, {
156
+ const r = await fetch(i, {
153
157
  method: "POST",
154
- headers: i,
155
- body: e
158
+ headers: n,
159
+ body: e,
160
+ signal: s?.signal
156
161
  });
157
- return n.ok || await this.handleErrorResponse(n), n;
158
- } catch (n) {
159
- throw n instanceof p ? n : new w(`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);
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);
160
165
  }
161
166
  }
162
167
  async request(t, e, s, i) {
163
168
  const n = `${this.baseUrl}${e}`;
164
- c.debug(t, n, s);
169
+ l.debug(t, n, s);
165
170
  try {
166
- const o = await fetch(n, {
171
+ const r = await fetch(n, {
167
172
  method: t,
168
173
  headers: {
169
174
  ...this.headers,
@@ -172,9 +177,9 @@ var K = class {
172
177
  body: s ? JSON.stringify(s) : void 0,
173
178
  ...i?.keepalive ? { keepalive: !0 } : {}
174
179
  });
175
- return o.ok || await this.handleErrorResponse(o), o.status === 204 ? void 0 : o.json();
176
- } catch (o) {
177
- throw o instanceof p ? o : new w(`Network error: ${o instanceof Error ? o.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, o instanceof Error ? o : void 0);
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);
178
183
  }
179
184
  }
180
185
  async handleErrorResponse(t) {
@@ -183,44 +188,47 @@ var K = class {
183
188
  e = await t.json();
184
189
  } catch {
185
190
  }
186
- if (e?.error) throw p.fromResponse(e, t.status);
191
+ if (e?.error) throw y.fromResponse(e, t.status);
187
192
  let s = "";
188
- 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 p(`HTTP ${t.status}: ${t.statusText}.${s}`, "http_error", t.status, "api_error");
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");
189
194
  }
190
- }, W = 5e4, q = 2e4, H = 2e3, z = class {
195
+ }, Z = 5e4, tt = 2e4, et = 2e3, st = class {
191
196
  constructor(t) {
192
- this.functions = /* @__PURE__ */ new Map(), this.defaultMaxResultBytes = t?.maxResultBytes ?? W;
197
+ this.functions = /* @__PURE__ */ new Map(), this.defaultMaxResultBytes = t?.maxResultBytes ?? Z;
193
198
  }
194
199
  setDefaultMaxResultBytes(t) {
195
200
  this.defaultMaxResultBytes = t;
196
201
  }
202
+ getDefaultMaxResultBytes() {
203
+ return this.defaultMaxResultBytes;
204
+ }
197
205
  register(t, e, s) {
198
206
  if (typeof t == "object") {
199
- const { name: r, handler: l, description: h, parameters: u, maxResultBytes: d, requiresApproval: m } = t;
200
- return this.register(r, l, {
207
+ const { name: o, handler: a, description: h, parameters: u, maxResultBytes: d, requiresApproval: f } = t;
208
+ return this.register(o, a, {
201
209
  description: h,
202
210
  parameters: u,
203
211
  maxResultBytes: d,
204
- requiresApproval: m
212
+ requiresApproval: f
205
213
  });
206
214
  }
207
215
  const i = t;
208
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");
209
- this.functions.has(i) && c.warn(`Function "${i}" is being overwritten`);
210
- const { maxResultBytes: n, requiresApproval: o, ...a } = s;
217
+ this.functions.has(i) && l.warn(`Function "${i}" is being overwritten`);
218
+ const { maxResultBytes: n, requiresApproval: r, ...c } = s;
211
219
  this.functions.set(i, {
212
220
  schema: {
213
- ...a,
221
+ ...c,
214
222
  name: i
215
223
  },
216
224
  handler: e,
217
225
  maxResultBytes: n,
218
- requiresApproval: o
219
- }), c.log(`Registered function: ${i}`);
226
+ requiresApproval: r
227
+ }), l.log(`Registered function: ${i}`);
220
228
  }
221
229
  unregister(t) {
222
230
  const e = this.functions.delete(t);
223
- return e && c.log(`Unregistered function: ${t}`), e;
231
+ return e && l.log(`Unregistered function: ${t}`), e;
224
232
  }
225
233
  get(t) {
226
234
  return this.functions.get(t);
@@ -233,13 +241,13 @@ var K = class {
233
241
  }
234
242
  async execute(t, e) {
235
243
  const s = this.functions.get(t);
236
- if (!s) throw new R(`Function "${t}" is not registered`, t);
237
- c.log(`Executing function: ${t}`, e);
244
+ if (!s) throw new D(`Function "${t}" is not registered`, t);
245
+ l.log(`Executing function: ${t}`, e);
238
246
  try {
239
247
  const i = await s.handler(e);
240
- return c.log(`Function ${t} completed:`, i), this.guardResultSize(t, i, s.maxResultBytes);
248
+ return l.log(`Function ${t} completed:`, i), this.guardResultSize(t, i, s.maxResultBytes);
241
249
  } catch (i) {
242
- throw c.error(`Function ${t} failed:`, i), new R(`Function "${t}" execution failed: ${i instanceof Error ? i.message : "Unknown error"}`, t, i instanceof Error ? i : void 0);
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);
243
251
  }
244
252
  }
245
253
  guardResultSize(t, e, s) {
@@ -250,47 +258,168 @@ var K = class {
250
258
  return e;
251
259
  }
252
260
  if (i === void 0) return e;
253
- const n = new TextEncoder().encode(i).length, o = s ?? this.defaultMaxResultBytes;
254
- return n > o ? (c.warn(`Function "${t}" result is ${n} bytes, over the ${o}-byte limit; a truncated preview was sent to the agent instead. Return fewer fields, paginate, or raise maxResultBytes for this function.`), {
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.`), {
255
263
  truncated: !0,
256
264
  originalBytes: n,
257
- maxBytes: o,
258
- preview: i.slice(0, H),
259
- hint: `The result of "${t}" exceeded the ${o}-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.`
260
- }) : (n > q && c.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);
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);
261
269
  }
262
270
  clear() {
263
- this.functions.clear(), c.log("Cleared all registered functions");
271
+ this.functions.clear(), l.log("Cleared all registered functions");
264
272
  }
265
273
  get size() {
266
274
  return this.functions.size;
267
275
  }
268
- }, J = 250, X = 3, Y = 1e3, V = 24, Q = 10, Z = 50, tt = [
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 = [
269
398
  "mousemove",
270
399
  "mousedown",
271
400
  "keydown",
272
401
  "scroll",
273
402
  "touchstart"
274
- ], et = class {
403
+ ], St = class {
275
404
  constructor(t = {}) {
276
- 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 ?? J, this.rageClickCount = t.rageClickCount ?? X, this.rageClickWindowMs = t.rageClickWindowMs ?? Y, this.rageClickRadiusPx = t.rageClickRadiusPx ?? V, this.maxRecentRoutes = t.maxRecentRoutes ?? Q, this.maxSignals = t.maxSignals ?? Z;
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;
277
406
  }
278
407
  start() {
279
408
  if (this.started || typeof window > "u" || typeof document > "u") return;
280
409
  this.started = !0;
281
410
  const t = Date.now();
282
411
  this.route = this.currentPathname(), this.routeEnteredAt = t, this.lastActivityAt = t, this.recentRoutes = [this.route];
283
- const e = (i, n, o) => {
284
- i.addEventListener(n, o, { passive: !0 }), this.teardowns.push(() => i.removeEventListener(n, o));
412
+ const e = (i, n, r) => {
413
+ i.addEventListener(n, r, { passive: !0 }), this.teardowns.push(() => i.removeEventListener(n, r));
285
414
  }, s = () => this.recordActivity();
286
- for (const i of tt) e(window, i, s);
415
+ for (const i of Ct) e(window, i, s);
287
416
  e(document, "visibilitychange", () => {
288
417
  document.visibilityState === "visible" && this.recordActivity();
289
- }), e(window, "popstate", () => this.checkRoute()), e(window, "hashchange", () => this.checkRoute()), e(window, "click", (i) => this.onClick(i)), c.log("SignalCollector started");
418
+ }), e(window, "popstate", () => this.checkRoute()), e(window, "hashchange", () => this.checkRoute()), e(window, "click", (i) => this.onClick(i)), l.log("SignalCollector started");
290
419
  }
291
420
  destroy() {
292
421
  for (const t of this.teardowns) t();
293
- this.teardowns = [], this.listeners.clear(), this.recentClicks = [], this.started = !1, c.log("SignalCollector destroyed");
422
+ this.teardowns = [], this.listeners.clear(), this.recentClicks = [], this.started = !1, l.log("SignalCollector destroyed");
294
423
  }
295
424
  signalFieldError(t) {
296
425
  this.checkRoute();
@@ -333,7 +462,7 @@ var K = class {
333
462
  try {
334
463
  return this.getPageState() ?? null;
335
464
  } catch (t) {
336
- return c.warn("SignalCollector getPageState threw:", t), null;
465
+ return l.warn("SignalCollector getPageState threw:", t), null;
337
466
  }
338
467
  }
339
468
  recordActivity() {
@@ -368,9 +497,9 @@ var K = class {
368
497
  y: t.clientY,
369
498
  stateKey: s
370
499
  };
371
- this.recentClicks = this.recentClicks.filter((r) => e - r.at <= this.rageClickWindowMs);
372
- const n = this.recentClicks[0], o = !n || Math.abs(i.x - n.x) <= this.rageClickRadiusPx && Math.abs(i.y - n.y) <= this.rageClickRadiusPx, a = !n || n.stateKey === s;
373
- if (!o || !a) {
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) {
374
503
  this.recentClicks = [i];
375
504
  return;
376
505
  }
@@ -395,20 +524,20 @@ var K = class {
395
524
  for (const e of this.listeners) try {
396
525
  e(t);
397
526
  } catch (s) {
398
- c.error("Signal listener threw:", s);
527
+ l.error("Signal listener threw:", s);
399
528
  }
400
529
  }
401
530
  };
402
- function st(t, e) {
531
+ function At(t, e) {
403
532
  const s = e ? e.storage ?? (typeof localStorage < "u" ? localStorage : void 0) : void 0;
404
533
  let i = t;
405
534
  if (e && s) try {
406
- const r = s.getItem(e.key);
407
- r != null && (i = JSON.parse(r));
535
+ const o = s.getItem(e.key);
536
+ o != null && (i = JSON.parse(o));
408
537
  } catch {
409
538
  }
410
- const n = /* @__PURE__ */ new Set(), o = () => n.forEach((r) => r(i));
411
- function a() {
539
+ const n = /* @__PURE__ */ new Set(), r = () => n.forEach((o) => o(i));
540
+ function c() {
412
541
  if (e && s) try {
413
542
  s.setItem(e.key, JSON.stringify(i));
414
543
  } catch {
@@ -416,31 +545,31 @@ function st(t, e) {
416
545
  }
417
546
  return {
418
547
  get: () => i,
419
- set: (r) => {
420
- i = r, a(), o();
548
+ set: (o) => {
549
+ i = o, c(), r();
421
550
  },
422
- subscribe: (r) => (n.add(r), () => {
423
- n.delete(r);
551
+ subscribe: (o) => (n.add(o), () => {
552
+ n.delete(o);
424
553
  })
425
554
  };
426
555
  }
427
- var it = 6e4, nt = 1440 * 60 * 1e3, rt = "ago_proactive";
428
- function C(t) {
556
+ var Et = 6e4, bt = 1440 * 60 * 1e3, _t = "ago_proactive";
557
+ function A(t) {
429
558
  const e = new Date(t), s = String(e.getMonth() + 1).padStart(2, "0"), i = String(e.getDate()).padStart(2, "0");
430
559
  return `${e.getFullYear()}-${s}-${i}`;
431
560
  }
432
- var ot = class {
561
+ var It = class {
433
562
  constructor(t = {}) {
434
- 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 = st({
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({
435
564
  optOut: !1,
436
565
  lastFiredAt: {},
437
566
  dismissedAt: {},
438
567
  day: {
439
- date: C(Date.now()),
568
+ date: A(Date.now()),
440
569
  count: 0
441
570
  }
442
571
  }, {
443
- key: t.storageKey ?? rt,
572
+ key: t.storageKey ?? _t,
444
573
  storage: t.storage
445
574
  });
446
575
  }
@@ -484,10 +613,10 @@ var ot = class {
484
613
  if (this.engaged) return this.deny(t, "user engaged (widget open)");
485
614
  if (this.turnInFlight) return this.deny(t, "message turn in flight");
486
615
  if (this.slotOccupied) return this.deny(t, "nudge slot occupied");
487
- const i = s.lastFiredAt[t.id], n = t.cooldownMs ?? it;
616
+ const i = s.lastFiredAt[t.id], n = t.cooldownMs ?? Et;
488
617
  if (i !== void 0 && e - i < n) return this.deny(t, "cooldown");
489
- const o = s.dismissedAt[t.id], a = t.resurfaceAfterMs ?? nt;
490
- return o !== void 0 && e - o < a ? 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;
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;
491
620
  }
492
621
  recordFired(t, e = Date.now()) {
493
622
  const s = this.store.get();
@@ -501,7 +630,7 @@ var ot = class {
501
630
  }
502
631
  recordNudgeShown(t = Date.now()) {
503
632
  this.sessionCount += 1;
504
- const e = this.store.get(), s = C(t), i = e.day.date === s ? {
633
+ const e = this.store.get(), s = A(t), i = e.day.date === s ? {
505
634
  date: s,
506
635
  count: e.day.count + 1
507
636
  } : {
@@ -525,53 +654,53 @@ var ot = class {
525
654
  }
526
655
  dayCount(t) {
527
656
  const e = this.store.get();
528
- return e.day.date === C(t) ? e.day.count : 0;
657
+ return e.day.date === A(t) ? e.day.count : 0;
529
658
  }
530
659
  deny(t, e) {
531
- return c.debug(`NudgeGovernor: trigger "${t.id}" blocked — ${e}`), !1;
660
+ return l.debug(`NudgeGovernor: trigger "${t.id}" blocked — ${e}`), !1;
532
661
  }
533
662
  };
534
- function x() {
663
+ function M() {
535
664
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (t) => {
536
665
  const e = Math.floor(Math.random() * 16);
537
666
  return (t === "x" ? e : e & 3 | 8).toString(16);
538
667
  });
539
668
  }
540
- function at(t) {
669
+ function Rt(t) {
541
670
  return t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
542
671
  }
543
- function ct(t, e) {
672
+ function kt(t, e) {
544
673
  if (t === "*" || t === e) return !0;
545
- const s = t.split("/"), i = s.map((n, o) => {
546
- const a = o === s.length - 1;
547
- return n === "*" ? a ? "[^/]+(?:/[^/]+)*" : "[^/]+" : n.startsWith(":") ? "[^/]+" : at(n);
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);
548
677
  });
549
678
  return new RegExp("^" + i.join("/") + "/?$").test(e);
550
679
  }
551
- function O(t, e) {
552
- return t === e ? !0 : t === null || e === null ? !1 : Array.isArray(t) ? !Array.isArray(e) || e.length !== t.length ? !1 : t.every((s, i) => E(s, e[i])) : typeof t == "object" ? typeof e != "object" || Array.isArray(e) ? !1 : Object.entries(t).every(([s, i]) => O(i, e[s])) : !1;
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;
553
682
  }
554
- function E(t, e) {
683
+ function k(t, e) {
555
684
  if (t === e) return !0;
556
685
  if (t === null || e === null || typeof t != typeof e) return !1;
557
686
  if (Array.isArray(t))
558
- return !Array.isArray(e) || t.length !== e.length ? !1 : t.every((s, i) => E(s, e[i]));
687
+ return !Array.isArray(e) || t.length !== e.length ? !1 : t.every((s, i) => k(s, e[i]));
559
688
  if (typeof t == "object") {
560
689
  const s = Object.keys(t), i = Object.keys(e);
561
- return s.length !== i.length ? !1 : s.every((n) => E(t[n], e[n]));
690
+ return s.length !== i.length ? !1 : s.every((n) => k(t[n], e[n]));
562
691
  }
563
692
  return !1;
564
693
  }
565
- function lt(t, e) {
566
- if (t.route !== void 0 && !ct(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;
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;
567
696
  if (t.fieldErrors !== void 0) {
568
697
  for (const [s, i] of Object.entries(t.fieldErrors)) if ((e.fieldErrors[s] ?? 0) < i) return !1;
569
698
  }
570
- return !(t.pageState !== void 0 && !O(t.pageState, e.pageState ?? {}));
699
+ return !(t.pageState !== void 0 && !W(t.pageState, e.pageState ?? {}));
571
700
  }
572
- var ht = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate", gt = class {
701
+ var xt = 1e3, Ft = "/api/sdk/v1/config", Dt = "/api/sdk/v1/proactive/evaluate", $t = class {
573
702
  constructor(t) {
574
- 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 ?? ht;
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;
575
704
  }
576
705
  start() {
577
706
  if (this.started) return;
@@ -597,17 +726,17 @@ var ht = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate",
597
726
  }
598
727
  async loadKillSwitch() {
599
728
  try {
600
- const t = await this.client.getHttp().get(ut);
729
+ const t = await this.client.getHttp().get(Ft);
601
730
  this.governor.setKillSwitch(t?.proactive?.enabled === !0);
602
731
  } catch (t) {
603
- c.debug("Proactive config fetch failed; staying disabled:", t), this.governor.setKillSwitch(!1);
732
+ l.debug("Proactive config fetch failed; staying disabled:", t), this.governor.setKillSwitch(!1);
604
733
  }
605
734
  }
606
735
  evaluate() {
607
736
  if (this.lastEvaluationAt = Date.now(), typeof document < "u" && document.visibilityState === "hidden" || this.governor.isSlotOccupied()) return;
608
737
  const t = this.collector.getSnapshot();
609
738
  for (const e of this.options.triggers)
610
- if (lt(e.when, t) && this.governor.canFire(e)) {
739
+ if (Tt(e.when, t) && this.governor.canFire(e)) {
611
740
  this.fire(e);
612
741
  return;
613
742
  }
@@ -618,7 +747,7 @@ var ht = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate",
618
747
  return;
619
748
  }
620
749
  this.setReady({
621
- id: x(),
750
+ id: M(),
622
751
  triggerId: t.id,
623
752
  source: "static",
624
753
  message: t.intervene.message,
@@ -629,7 +758,7 @@ var ht = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate",
629
758
  });
630
759
  }
631
760
  async evaluateWithAgent(t) {
632
- const e = x(), s = {
761
+ const e = M(), s = {
633
762
  client_nudge_id: e,
634
763
  trigger_id: t.id,
635
764
  goal: t.goal ?? "",
@@ -640,9 +769,9 @@ var ht = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate",
640
769
  };
641
770
  let i;
642
771
  try {
643
- i = await this.client.getHttp().post(dt, s);
772
+ i = await this.client.getHttp().post(Dt, s);
644
773
  } catch (n) {
645
- c.debug("Proactive evaluate failed (treated as no-intervene):", n), this.governor.releaseSlot();
774
+ l.debug("Proactive evaluate failed (treated as no-intervene):", n), this.governor.releaseSlot();
646
775
  return;
647
776
  }
648
777
  if (!i?.intervene || !i.message) {
@@ -654,7 +783,7 @@ var ht = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate",
654
783
  triggerId: t.id,
655
784
  source: "agent",
656
785
  message: i.message,
657
- action: ft(i.action),
786
+ action: Pt(i.action),
658
787
  goal: t.goal,
659
788
  kickoff: t.kickoff,
660
789
  createdAt: /* @__PURE__ */ new Date(),
@@ -690,10 +819,10 @@ var ht = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate",
690
819
  source: t.source,
691
820
  type: "accepted",
692
821
  occurredAt: Date.now()
693
- }), this.clearActive(t), this.client.emitProactiveEvent("nudge:accepted", { nudge: t }), (t.source === "agent" || t.goal) && (this.lastConversationId ? this.client.sendMessage(pt(t), {
822
+ }), this.clearActive(t), this.client.emitProactiveEvent("nudge:accepted", { nudge: t }), (t.source === "agent" || t.goal) && (this.lastConversationId ? this.client.sendMessage(Nt(t), {
694
823
  hidden: !0,
695
824
  conversationId: this.lastConversationId
696
- }).catch((e) => c.debug("Nudge kickoff message failed:", e)) : t.kickoff ? this.client.sendMessage(t.kickoff).catch((e) => c.debug("Nudge kickoff message failed:", e)) : c.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));
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));
697
826
  }
698
827
  markConverted(t) {
699
828
  this.tracker.track({
@@ -711,11 +840,11 @@ var ht = 1e3, ut = "/api/sdk/v1/config", dt = "/api/sdk/v1/proactive/evaluate",
711
840
  try {
712
841
  "functionName" in t ? await this.client.executeClientFunction(t.functionName, t.arguments ?? {}) : await this.client.executeClientFunction("setPageState", t.setPageState);
713
842
  } catch (e) {
714
- c.warn("Nudge action failed:", e);
843
+ l.warn("Nudge action failed:", e);
715
844
  }
716
845
  }
717
846
  };
718
- function ft(t) {
847
+ function Pt(t) {
719
848
  if (t)
720
849
  return {
721
850
  label: t.label,
@@ -723,13 +852,13 @@ function ft(t) {
723
852
  arguments: t.arguments
724
853
  };
725
854
  }
726
- function pt(t) {
855
+ function Nt(t) {
727
856
  const e = t.goal ? ` Goal: ${t.goal}.` : "";
728
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.`;
729
858
  }
730
- var mt = 5e3, yt = "/api/sdk/v1/proactive/events", vt = class {
859
+ var Mt = 5e3, Ot = "/api/sdk/v1/proactive/events", Ut = class {
731
860
  constructor(t) {
732
- 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") {
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") {
733
862
  const e = () => {
734
863
  document.visibilityState === "hidden" && this.flush({ keepalive: !0 });
735
864
  };
@@ -756,8 +885,8 @@ var mt = 5e3, yt = "/api/sdk/v1/proactive/events", vt = class {
756
885
  ...this.agent ? { agent: this.agent } : {},
757
886
  occurred_at: new Date(i.occurredAt).toISOString()
758
887
  })) };
759
- this.post(yt, s, t).catch((i) => {
760
- c.debug("Proactive event batch failed:", i);
888
+ this.post(Ot, s, t).catch((i) => {
889
+ l.debug("Proactive event batch failed:", i);
761
890
  });
762
891
  }
763
892
  destroy() {
@@ -767,77 +896,77 @@ var mt = 5e3, yt = "/api/sdk/v1/proactive/events", vt = class {
767
896
  this.teardowns = [];
768
897
  }
769
898
  }
770
- }, T = "friction_signals";
771
- function F(t, e) {
772
- t.proactive && (c.warn("createAgoProactive: a proactive controller is already attached; replacing it."), t.proactive.destroy());
773
- const s = new et({
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({
774
903
  ...e.signals,
775
904
  getPageState: () => {
776
- const r = t.getContextSnapshot();
777
- if (!r) return null;
778
- const l = {};
779
- for (const [h, u] of Object.entries(r.entries)) h.startsWith("page-state:") && u.data && Object.assign(l, u.data);
780
- return Object.keys(l).length > 0 ? l : null;
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;
781
910
  }
782
911
  });
783
- s.start(), t.addDynamicContext(T, () => {
784
- const { pageState: r, ...l } = s.getSnapshot({ pageState: !1 });
912
+ s.start(), t.addDynamicContext(O, () => {
913
+ const { pageState: o, ...a } = s.getSnapshot({ pageState: !1 });
785
914
  return {
786
915
  name: "Friction signals",
787
916
  description: "Behavioral friction observed on the current page: dwell/idle times, rage clicks, route bounces, repeated field errors (names and counters only).",
788
- data: l
917
+ data: a
789
918
  };
790
919
  });
791
- const i = new ot({
920
+ const i = new It({
792
921
  frequencyCap: e.frequencyCap,
793
922
  storage: e.storage,
794
923
  storageKey: e.storageKey
795
- }), n = new vt({
796
- post: (r, l, h) => t.getHttp().post(r, l, h),
924
+ }), n = new Ut({
925
+ post: (o, a, h) => t.getHttp().post(o, a, h),
797
926
  agent: t.getConfiguredAgent()
798
- }), o = new gt({
927
+ }), r = new $t({
799
928
  client: t,
800
929
  collector: s,
801
930
  governor: i,
802
931
  tracker: n,
803
932
  options: e
804
933
  });
805
- o.start();
806
- const a = {
934
+ r.start();
935
+ const c = {
807
936
  optOut: () => i.optOut(),
808
937
  optIn: () => i.optIn(),
809
938
  isOptedOut: () => i.isOptedOut(),
810
- setEngaged: (r) => i.setEngaged(r),
811
- signalFieldError: (r) => s.signalFieldError(r),
939
+ setEngaged: (o) => i.setEngaged(o),
940
+ signalFieldError: (o) => s.signalFieldError(o),
812
941
  getSignalsSnapshot: () => s.getSnapshot(),
813
- getActiveNudge: () => o.getActiveNudge(),
814
- shown: (r) => o.shown(r),
815
- accept: (r) => o.accept(r),
816
- dismiss: (r) => o.dismiss(r),
817
- markConverted: (r) => o.markConverted(r),
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),
818
947
  destroy: () => {
819
- o.stop(), n.destroy(), s.destroy(), t.removeDynamicContext(T), t.proactive === a && (t.proactive = null);
948
+ r.stop(), n.destroy(), s.destroy(), t.removeDynamicContext(O), t.proactive === c && (t.proactive = null);
820
949
  }
821
950
  };
822
- return t.proactive = a, a;
951
+ return t.proactive = c, c;
823
952
  }
824
- var wt = class {
953
+ var Lt = class {
825
954
  constructor() {
826
955
  this.entries = /* @__PURE__ */ new Map(), this.dynamicProviders = /* @__PURE__ */ new Map();
827
956
  }
828
957
  set(t, e) {
829
- this.entries.set(t, e), c.log(`ClientContext set: ${t}`);
958
+ this.entries.set(t, e), l.log(`ClientContext set: ${t}`);
830
959
  }
831
960
  remove(t) {
832
961
  const e = this.entries.delete(t);
833
- return e && c.log(`ClientContext removed: ${t}`), e;
962
+ return e && l.log(`ClientContext removed: ${t}`), e;
834
963
  }
835
964
  addDynamicProvider(t, e) {
836
- this.dynamicProviders.set(t, e), c.log(`DynamicContext provider added: ${t}`);
965
+ this.dynamicProviders.set(t, e), l.log(`DynamicContext provider added: ${t}`);
837
966
  }
838
967
  removeDynamicProvider(t) {
839
968
  const e = this.dynamicProviders.delete(t);
840
- return e && c.log(`DynamicContext provider removed: ${t}`), e;
969
+ return e && l.log(`DynamicContext provider removed: ${t}`), e;
841
970
  }
842
971
  getSnapshot() {
843
972
  if (this.entries.size === 0 && this.dynamicProviders.size === 0) return null;
@@ -847,66 +976,68 @@ var wt = class {
847
976
  const i = s();
848
977
  i && (t[e] = i);
849
978
  } catch (i) {
850
- c.error(`DynamicContext provider "${e}" threw:`, i);
979
+ l.error(`DynamicContext provider "${e}" threw:`, i);
851
980
  }
852
981
  return Object.keys(t).length === 0 ? null : { entries: t };
853
982
  }
854
983
  clear() {
855
- this.entries.clear(), this.dynamicProviders.clear(), c.log("ClientContext cleared");
984
+ this.entries.clear(), this.dynamicProviders.clear(), l.log("ClientContext cleared");
856
985
  }
857
- }, Ct = "page-state:";
858
- function St(t) {
986
+ }, jt = "page-state:";
987
+ function Bt(t) {
859
988
  const e = {};
860
- for (const [s, i] of Object.entries(t)) s.startsWith(Ct) && i.data && Object.assign(e, i.data);
989
+ for (const [s, i] of Object.entries(t)) s.startsWith(jt) && i.data && Object.assign(e, i.data);
861
990
  return e;
862
991
  }
863
- function At(t) {
992
+ function qt(t) {
864
993
  const e = t["current-page"]?.data;
865
994
  return e?.page ? e.page : e?.url ? e.url : t["browser-page"]?.data?.url;
866
995
  }
867
- function Et(t, e) {
996
+ function Gt(t, e) {
868
997
  return t === e ? !0 : JSON.stringify(t) === JSON.stringify(e);
869
998
  }
870
- function _t(t, e) {
999
+ function Kt(t, e) {
871
1000
  const s = [];
872
1001
  for (const i of Object.keys(e))
873
- i in t && (Et(t[i], e[i]) || s.push({
1002
+ i in t && (Gt(t[i], e[i]) || s.push({
874
1003
  field: i,
875
1004
  from: t[i],
876
1005
  to: e[i]
877
1006
  }));
878
1007
  return s;
879
1008
  }
880
- function bt(t, e) {
881
- const s = St(e), i = At(e);
1009
+ function Wt(t, e) {
1010
+ const s = Bt(e), i = qt(e);
882
1011
  return {
883
- changes: t && t.page === i ? _t(t.state, s) : [],
1012
+ changes: t && t.page === i ? Kt(t.state, s) : [],
884
1013
  baseline: {
885
1014
  page: i,
886
1015
  state: s
887
1016
  }
888
1017
  };
889
1018
  }
890
- function _(t) {
891
- return t === null || typeof t != "object" ? JSON.stringify(t) ?? "null" : Array.isArray(t) ? `[${t.map(_).join(",")}]` : `{${Object.keys(t).sort().map((e) => `${JSON.stringify(e)}:${_(t[e])}`).join(",")}}`;
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(",")}}`;
892
1021
  }
893
- var kt = class {
894
- constructor(t) {
895
- this.callbacks = t, this.buffer = "", this.message = {}, this.toolCalls = [], this.sources = [], this.followUpReplies = [], this.isFirstChunk = !0, this.answerCompleteEmitted = !1, this.waitingClientEmitted = !1, this.firedClientFunctions = /* @__PURE__ */ new Set();
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();
896
1025
  }
897
1026
  async processStream(t) {
898
- if (!t.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");
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");
899
1028
  const e = t.body.getReader(), s = new TextDecoder();
900
1029
  try {
901
1030
  for (; ; ) {
902
1031
  const { done: i, value: n } = await e.read();
903
1032
  if (i) break;
904
- const o = s.decode(n, { stream: !0 });
905
- this.buffer += o, this.processBuffer();
1033
+ const r = s.decode(n, { stream: !0 });
1034
+ this.buffer += r, this.processBuffer();
906
1035
  }
907
1036
  return this.buffer.trim() && this.processBuffer(), this.buildFinalMessage();
908
1037
  } catch (i) {
909
- const n = i instanceof Error ? i : new k("Stream processing failed mid-flight. The connection may have dropped; retry the message.");
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.");
910
1041
  throw this.callbacks.onError?.(n), n;
911
1042
  } finally {
912
1043
  e.releaseLock();
@@ -925,10 +1056,10 @@ var kt = class {
925
1056
  if (!i.startsWith(": ") && i.startsWith("data: ")) {
926
1057
  const n = i.slice(6);
927
1058
  try {
928
- const o = JSON.parse(n);
929
- this.handleChunk(o);
930
- } catch (o) {
931
- c.warn("Failed to parse SSE data:", n, o);
1059
+ const r = JSON.parse(n);
1060
+ this.handleChunk(r);
1061
+ } catch (r) {
1062
+ l.warn("Failed to parse SSE data:", n, r);
932
1063
  }
933
1064
  }
934
1065
  }
@@ -956,13 +1087,14 @@ var kt = class {
956
1087
  url: s.use_external_link ? s.external_link_url : s.internal_link_url
957
1088
  };
958
1089
  })), t.type === "client_function" && t.function_name) {
959
- const e = `${t.function_name}::${_(t.arguments ?? {})}`;
960
- this.firedClientFunctions.has(e) || (this.firedClientFunctions.add(e), this.callbacks.onClientFunction?.({
961
- invocationId: t.id || "",
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,
962
1094
  functionName: t.function_name,
963
1095
  arguments: t.arguments || {},
964
1096
  conversationId: this.message.conversationId || ""
965
- }));
1097
+ });
966
1098
  }
967
1099
  if (t.tool_call_data && t.type && t.type !== "client_function") {
968
1100
  const e = this.parseToolCall(t);
@@ -1009,11 +1141,11 @@ var kt = class {
1009
1141
  return t.status !== "WAITING_CLIENT" && this.callbacks.onComplete?.(t), t;
1010
1142
  }
1011
1143
  };
1012
- function Mt(t) {
1144
+ function ne(t) {
1013
1145
  const e = t.message.toLowerCase();
1014
1146
  return e.includes("load failed") || e.includes("failed to fetch") || e.includes("network") || e.includes("abort");
1015
1147
  }
1016
- var Rt = /* @__PURE__ */ new Set([
1148
+ var Jt = /* @__PURE__ */ new Set([
1017
1149
  "image/jpeg",
1018
1150
  "image/png",
1019
1151
  "image/gif",
@@ -1021,7 +1153,7 @@ var Rt = /* @__PURE__ */ new Set([
1021
1153
  "image/bmp",
1022
1154
  "image/tiff"
1023
1155
  ]);
1024
- function It(t) {
1156
+ function zt(t) {
1025
1157
  if (!t) return;
1026
1158
  const e = typeof window < "u" && window.location ? window.location.href : "https://ago.local/";
1027
1159
  try {
@@ -1030,16 +1162,16 @@ function It(t) {
1030
1162
  } catch {
1031
1163
  }
1032
1164
  }
1033
- function Lt(t) {
1034
- return t.isSafeImage === !0 && typeof t.contentType == "string" && t.contentType.startsWith("image/") && It(t.url) !== void 0;
1165
+ function re(t) {
1166
+ return t.isSafeImage === !0 && typeof t.contentType == "string" && t.contentType.startsWith("image/") && zt(t.url) !== void 0;
1035
1167
  }
1036
- function jt(t) {
1168
+ function oe(t) {
1037
1169
  if (t == null || t < 0) return "";
1038
1170
  if (t < 1024) return `${t} B`;
1039
1171
  const e = t / 1024;
1040
1172
  return e < 1024 ? `${e.toFixed(1)} KB` : `${(e / 1024).toFixed(1)} MB`;
1041
1173
  }
1042
- function xt(t) {
1174
+ function Xt(t) {
1043
1175
  return {
1044
1176
  id: String(t.id ?? ""),
1045
1177
  name: typeof t.name == "string" && t.name ? t.name : "file",
@@ -1049,17 +1181,17 @@ function xt(t) {
1049
1181
  isSafeImage: t.is_safe_image === !0
1050
1182
  };
1051
1183
  }
1052
- function Bt(t) {
1184
+ function ae(t) {
1053
1185
  return t.map((e, s) => ({
1054
1186
  id: `local-${s}-${e.name}`,
1055
1187
  name: e.name,
1056
1188
  contentType: e.type || void 0,
1057
1189
  fileSize: e.size,
1058
1190
  url: typeof URL < "u" && URL.createObjectURL ? URL.createObjectURL(e) : void 0,
1059
- isSafeImage: Rt.has(e.type)
1191
+ isSafeImage: Jt.has(e.type)
1060
1192
  }));
1061
1193
  }
1062
- var Tt = class {
1194
+ var Yt = class {
1063
1195
  constructor() {
1064
1196
  this.handlers = /* @__PURE__ */ new Map();
1065
1197
  }
@@ -1089,113 +1221,205 @@ var Tt = class {
1089
1221
  waitFor(t, e) {
1090
1222
  return new Promise((s, i) => {
1091
1223
  let n;
1092
- const o = ((a) => {
1093
- n && clearTimeout(n), s(a);
1224
+ const r = ((c) => {
1225
+ n && clearTimeout(n), s(c);
1094
1226
  });
1095
- this.once(t, o), e?.timeout && (n = setTimeout(() => {
1096
- this.off(t, o), i(/* @__PURE__ */ new Error(`waitFor("${String(t)}") timed out after ${e.timeout}ms`));
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`));
1097
1229
  }, e.timeout));
1098
1230
  });
1099
1231
  }
1100
1232
  removeAllListeners(t) {
1101
1233
  t ? this.handlers.delete(t) : this.handlers.clear();
1102
1234
  }
1103
- }, $ = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).', Ft = /^[a-z][a-z0-9+.-]*:\/\//i, N = !1;
1104
- function D(t, e = "AgoClient") {
1105
- if (typeof t != "object" || t === null) throw new g(`${e}: ${$}`, "config_missing_base_url");
1235
+ }, j = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. 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");
1106
1238
  const s = t.baseUrl;
1107
- if (typeof s != "string" || s.trim() === "") throw new g(`${e}: ${$}`, "config_missing_base_url");
1108
- !s.startsWith("/") && !Ft.test(s) && (N || (N = !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).`)));
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).`)));
1109
1241
  }
1110
- function $t(t) {
1242
+ function Qt(t) {
1111
1243
  return t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1112
1244
  }
1113
- function S(t) {
1245
+ function E(t) {
1114
1246
  return t.split("/").filter((e) => e.startsWith(":")).map((e) => e.slice(1));
1115
1247
  }
1116
- function Nt(t, e) {
1248
+ function Zt(t, e) {
1117
1249
  const s = [];
1118
1250
  return {
1119
1251
  path: t.split("/").map((i) => {
1120
1252
  if (!i.startsWith(":")) return i;
1121
- const n = i.slice(1), o = e[n];
1122
- return o == null || o === "" ? (s.push(n), i) : encodeURIComponent(String(o));
1253
+ const n = i.slice(1), r = e[n];
1254
+ return r == null || r === "" ? (s.push(n), i) : encodeURIComponent(String(r));
1123
1255
  }).join("/"),
1124
1256
  missing: s
1125
1257
  };
1126
1258
  }
1127
- function Dt(t, e) {
1259
+ function te(t, e) {
1128
1260
  const s = e.find((n) => n.path === t);
1129
1261
  if (s) return s;
1130
1262
  const i = e.find((n) => {
1131
1263
  if (!n.path.includes(":")) return !1;
1132
- const o = "^" + n.path.split("/").map((a) => a.startsWith(":") ? "[^/]+" : $t(a)).join("/") + "/?$";
1133
- return new RegExp(o).test(t);
1264
+ const r = "^" + n.path.split("/").map((c) => c.startsWith(":") ? "[^/]+" : Qt(c)).join("/") + "/?$";
1265
+ return new RegExp(r).test(t);
1134
1266
  });
1135
- return i || e.filter((n) => n.path !== "/" && t.startsWith(n.path)).sort((n, o) => o.path.length - n.path.length)[0];
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`;
1136
1272
  }
1137
- var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1273
+ var ce = class H {
1138
1274
  constructor(e) {
1139
- this.lastSentPageState = null, this.warnedEmptyConversations = /* @__PURE__ */ new Set(), this.pendingResumes = /* @__PURE__ */ new Map(), this.pendingApprovals = /* @__PURE__ */ new Map(), this.resumeGate = null, this.proactive = null, D(e, "AgoClient"), this.config = e, this.activityLedger = new j(e.maxActivityEntries), this.httpClient = new K(e), this.functionRegistry = new z({ maxResultBytes: e.maxFunctionResultBytes }), this.contextRegistry = new wt(), this.eventEmitter = new Tt(), this.registerActivityContext(), e.debug && c.enable(), e.proactive && F(this, e.proactive), c.log("AgoClient initialized");
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");
1140
1276
  }
1141
1277
  async sendMessage(e, s) {
1142
- const i = this.functionRegistry.getSchemas(), n = this.buildSendContext(), o = this.config.agent || this.config.defaultAgentId, a = this.resolveClientFunctionsMode(s), r = {
1278
+ const i = this.functionRegistry.getSchemas(), n = this.buildSendContext(), r = this.config.agent || this.config.defaultAgentId, c = this.resolveClientFunctionsMode(s), o = {
1143
1279
  content: e,
1144
1280
  conversation_id: s?.conversationId,
1145
- agent_id: s?.agentId || o
1281
+ agent_id: s?.agentId || r
1146
1282
  };
1147
- i.length > 0 && (r.client_functions = i, a === "pause" && (r.client_functions_mode = a)), n && (r.client_context = n), s?.hidden && (r.hidden = !0);
1148
- let l;
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;
1149
1286
  if (s?.files && s.files.length > 0) {
1150
- const h = new FormData();
1151
- h.append("content", e), s.conversationId && h.append("conversation_id", s.conversationId), (s.agentId || o) && h.append("agent_id", s.agentId || o || ""), i.length > 0 && (h.append("client_functions", JSON.stringify(i)), a === "pause" && h.append("client_functions_mode", a)), n && h.append("client_context", JSON.stringify(n)), s.hidden && h.append("hidden", "true");
1152
- for (const u of s.files) h.append("files", u);
1153
- l = await this.httpClient.postFormData("/api/sdk/v1/messages", h);
1154
- } else l = await this.httpClient.postStream("/api/sdk/v1/messages", r);
1155
- return this.processSSEResponse(l);
1156
- }
1157
- async processSSEResponse(e) {
1158
- let s = !1;
1159
- const i = await new kt({
1160
- onRawChunk: (n) => {
1161
- this.eventEmitter.emit("stream:message", n);
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);
1162
1307
  },
1163
- onStart: (n) => {
1164
- this.eventEmitter.emit("message:start", n);
1308
+ onStart: (r) => {
1309
+ this.eventEmitter.emit("message:start", r);
1165
1310
  },
1166
- onChunk: (n) => {
1167
- this.eventEmitter.emit("message:chunk", n);
1311
+ onChunk: (r) => {
1312
+ this.eventEmitter.emit("message:chunk", r);
1168
1313
  },
1169
- onToolCall: (n) => {
1170
- this.eventEmitter.emit("toolCall:received", n), n.type === "form" && this.eventEmitter.emit("toolCall:form", n);
1314
+ onToolCall: (r) => {
1315
+ this.eventEmitter.emit("toolCall:received", r), r.type === "form" && this.eventEmitter.emit("toolCall:form", r);
1171
1316
  },
1172
- onClientFunction: async (n) => {
1173
- if (s = !0, this.eventEmitter.emit("function:invoke", n), this.recordAgentAction(n), n.invocationId && this.requiresApproval(n)) {
1174
- this.pendingApprovals.set(n.invocationId, n), this.eventEmitter.emit("function:awaiting-approval", n);
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);
1175
1320
  return;
1176
1321
  }
1177
- await this.handleClientFunctionInvocation(n);
1322
+ await this.handleClientFunctionInvocation(r);
1178
1323
  },
1179
- onTitle: (n) => {
1180
- this.eventEmitter.emit("conversation:title", n);
1324
+ onTitle: (r) => {
1325
+ this.eventEmitter.emit("conversation:title", r);
1181
1326
  },
1182
- onAnswerComplete: (n) => {
1183
- this.eventEmitter.emit("message:answer-complete", n);
1327
+ onAnswerComplete: (r) => {
1328
+ this.eventEmitter.emit("message:answer-complete", r);
1184
1329
  },
1185
- onWaitingClient: (n) => {
1186
- this.eventEmitter.emit("message:waiting-client", n), this.markResumeSignal(n.messageId, n.conversationId, "waitingConfirmed");
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");
1187
1335
  },
1188
- onComplete: (n) => {
1189
- this.eventEmitter.emit("message:complete", n);
1336
+ onComplete: (r) => {
1337
+ s?.stopRequested && !r.id || this.eventEmitter.emit("message:complete", r);
1190
1338
  },
1191
- onError: (n) => {
1339
+ onError: (r) => {
1192
1340
  this.eventEmitter.emit("message:error", {
1193
- error: n.message,
1194
- code: n instanceof g ? n.code : void 0
1341
+ error: r.message,
1342
+ code: r instanceof g ? r.code : void 0
1195
1343
  });
1196
1344
  }
1197
- }).processStream(e);
1198
- return i.status !== "WAITING_CLIENT" && this.maybeFlagEmptyReply(i, s), i;
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;
1199
1423
  }
1200
1424
  resolveClientFunctionsMode(e) {
1201
1425
  return e?.clientFunctionsMode ?? this.config.clientFunctionsMode ?? "pause";
@@ -1208,8 +1432,10 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1208
1432
  async continueMessage(e) {
1209
1433
  const s = this.functionRegistry.getSchemas(), i = this.buildSendContext(), n = {};
1210
1434
  s.length > 0 && (n.client_functions = s), i && (n.client_context = i);
1211
- const o = await this.httpClient.postStream(`/api/sdk/v1/messages/${e}/continue`, n);
1212
- return this.processSSEResponse(o);
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);
1213
1439
  }
1214
1440
  markResumeSignal(e, s, i) {
1215
1441
  if (!e) return;
@@ -1228,14 +1454,14 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1228
1454
  messageId: e
1229
1455
  });
1230
1456
  } catch (i) {
1231
- c.warn("Resume gate threw; resuming anyway:", i);
1232
- }
1233
- this.pendingResumes.delete(e);
1234
- try {
1235
- await this.continueMessage(e);
1236
- } catch (i) {
1237
- c.warn("Auto-resume of paused turn failed:", i);
1457
+ l.warn("Resume gate threw; resuming anyway:", i);
1238
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
+ }
1239
1465
  }
1240
1466
  maybeFlagEmptyReply(e, s) {
1241
1467
  e.status === "DONE" && (e.content ?? "").trim() === "" && !s && !(e.toolCalls && e.toolCalls.length > 0) && !(e.followUpReplies && e.followUpReplies.length > 0) && setTimeout(() => {
@@ -1255,7 +1481,7 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1255
1481
  try {
1256
1482
  s = await this.functionRegistry.execute(e.functionName, e.arguments);
1257
1483
  } catch (n) {
1258
- i = n instanceof Error ? n.message : "Unknown error", c.error("Client function execution failed:", n);
1484
+ i = n instanceof Error ? n.message : "Unknown error", l.error("Client function execution failed:", n);
1259
1485
  }
1260
1486
  if (e.invocationId) try {
1261
1487
  const n = await this.submitToolCallForm(e.invocationId, {
@@ -1265,7 +1491,7 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1265
1491
  });
1266
1492
  n?.resume?.ready && this.markResumeSignal(n.resume.message_id, e.conversationId, "resultsReady");
1267
1493
  } catch (n) {
1268
- c.error("Failed to submit function result:", n);
1494
+ l.error("Failed to submit function result:", n);
1269
1495
  }
1270
1496
  this.eventEmitter.emit("function:result", {
1271
1497
  invocationId: e.invocationId,
@@ -1278,7 +1504,7 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1278
1504
  if (s) try {
1279
1505
  if (s(e)) return !0;
1280
1506
  } catch (i) {
1281
- c.warn("approvalPolicy threw; not gating this call:", i);
1507
+ l.warn("approvalPolicy threw; not gating this call:", i);
1282
1508
  }
1283
1509
  return this.functionRegistry.get(e.functionName)?.requiresApproval === !0;
1284
1510
  }
@@ -1301,7 +1527,7 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1301
1527
  });
1302
1528
  n?.resume?.ready && this.markResumeSignal(n.resume.message_id, s.conversationId, "resultsReady");
1303
1529
  } catch (n) {
1304
- c.error("Failed to submit function rejection:", n);
1530
+ l.error("Failed to submit function rejection:", n);
1305
1531
  }
1306
1532
  this.eventEmitter.emit("function:result", {
1307
1533
  invocationId: e,
@@ -1311,15 +1537,15 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1311
1537
  async getConversations(e) {
1312
1538
  const s = new URLSearchParams();
1313
1539
  e?.page !== void 0 && s.set("page", String(e.page)), e?.pageSize !== void 0 && s.set("page_size", String(e.pageSize));
1314
- const i = s.toString(), n = await this.httpClient.get(`/api/sdk/v1/conversations${i ? `?${i}` : ""}`), o = (Array.isArray(n.data) ? n.data : []).map((a) => ({
1315
- id: String(a.id),
1316
- title: a.title ?? "",
1317
- lastMessageDate: new Date(a.last_message_at ?? a.created_at ?? 0)
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)
1318
1544
  }));
1319
1545
  return {
1320
- data: o,
1546
+ data: r,
1321
1547
  hasMore: n.has_more ?? !1,
1322
- total: n.total ?? o.length
1548
+ total: n.total ?? r.length
1323
1549
  };
1324
1550
  }
1325
1551
  async getConversation(e) {
@@ -1335,8 +1561,8 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1335
1561
  status: n.status,
1336
1562
  createdAt: new Date(n.created_at),
1337
1563
  hidden: n.hidden,
1338
- toolCalls: U.mapPersistedToolCalls(n.tool_call_data),
1339
- attachments: n.attachments && n.attachments.length > 0 ? n.attachments.map(xt) : void 0,
1564
+ toolCalls: H.mapPersistedToolCalls(n.tool_call_data),
1565
+ attachments: n.attachments && n.attachments.length > 0 ? n.attachments.map(Xt) : void 0,
1340
1566
  followUpReplies: n.follow_up_replies && n.follow_up_replies.length > 0 ? n.follow_up_replies : void 0
1341
1567
  }))
1342
1568
  };
@@ -1361,36 +1587,41 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1361
1587
  return (await this.getConversation(e)).messages || [];
1362
1588
  }
1363
1589
  async resumePendingClientFunctions(e) {
1364
- const s = [...e.messages ?? []].reverse().find((r) => r.role === "assistant" && r.status === "WAITING_CLIENT");
1590
+ const s = [...e.messages ?? []].reverse().find((o) => o.role === "assistant" && o.status === "WAITING_CLIENT");
1365
1591
  if (!s) return null;
1366
- const i = (s.toolCalls ?? []).filter((r) => r.type === "client_function" && r.status === "waiting_input" && r.functionName), n = new Set(this.functionRegistry.getSchemas().map((r) => r.name)), o = i.filter((r) => !n.has(r.functionName));
1367
- if (o.length > 0)
1368
- return c.warn("Cannot resume paused turn: function(s) not registered on this page:", o.map((r) => r.functionName)), null;
1369
- let a = i.length === 0;
1370
- for (const r of i) {
1371
- const l = {
1372
- invocationId: r.id,
1373
- functionName: r.functionName,
1374
- arguments: r.arguments ?? {},
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 ?? {},
1375
1601
  conversationId: e.id
1376
1602
  };
1377
- if (this.requiresApproval(l)) {
1378
- this.pendingApprovals.set(r.id, l), this.markResumeSignal(s.id, e.id, "waitingConfirmed"), this.eventEmitter.emit("function:awaiting-approval", l), a = !1;
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;
1379
1605
  continue;
1380
1606
  }
1607
+ this.eventEmitter.emit("function:invoke", a);
1381
1608
  let h, u;
1382
1609
  try {
1383
- h = await this.functionRegistry.execute(r.functionName, r.arguments ?? {});
1610
+ h = await this.functionRegistry.execute(o.functionName, o.arguments ?? {});
1384
1611
  } catch (d) {
1385
- u = d instanceof Error ? d.message : "Unknown error", c.error("Client function execution failed:", d);
1612
+ u = d instanceof Error ? d.message : "Unknown error", l.error("Client function execution failed:", d);
1386
1613
  }
1387
- a = (await this.submitToolCallForm(r.id, {
1614
+ this.eventEmitter.emit("function:result", {
1615
+ invocationId: o.id,
1616
+ result: h,
1617
+ error: u
1618
+ }), c = (await this.submitToolCallForm(o.id, {
1388
1619
  result: h,
1389
1620
  error: u,
1390
1621
  _type: "client_function_result"
1391
- }))?.resume?.ready ?? a;
1622
+ }))?.resume?.ready ?? c;
1392
1623
  }
1393
- return a ? this.continueMessage(s.id) : null;
1624
+ return c ? this.continueMessage(s.id) : null;
1394
1625
  }
1395
1626
  async submitToolCallForm(e, s) {
1396
1627
  return this.httpClient.post(`/api/sdk/v1/tool-calls/${e}/submit`, { formData: s });
@@ -1436,65 +1667,65 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1436
1667
  return this.functionRegistry.execute(e, s);
1437
1668
  }
1438
1669
  registerNavigationFunction(e, s) {
1439
- const i = s.map((r) => r.name), n = s.map((r) => {
1440
- const l = S(r.path), h = l.length > 0 ? ` (requires ${l.map((u) => `"${u}"`).join(", ")})` : "";
1441
- return `- "${r.name}"${h}: ${r.description}`;
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}`;
1442
1673
  }).join(`
1443
- `), o = /* @__PURE__ */ new Map();
1444
- for (const r of s) for (const l of S(r.path)) o.set(l, [...o.get(l) ?? [], r.name]);
1445
- const a = { page: {
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: {
1446
1677
  type: "string",
1447
1678
  description: "The page to navigate to",
1448
1679
  enum: i
1449
1680
  } };
1450
- for (const [r, l] of o) {
1451
- if (r === "page") {
1452
- c.error('registerNavigationFunction: a ":page" placeholder collides with the "page" argument and is ignored. Rename the placeholder.');
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.');
1453
1684
  continue;
1454
1685
  }
1455
- a[r] = {
1686
+ c[o] = {
1456
1687
  type: "string",
1457
- description: `Value for ":${r}" in the page path. Required when page is ${l.map((h) => `"${h}"`).join(" or ")}.`
1688
+ description: `Value for ":${o}" in the page path. Required when page is ${a.map((h) => `"${h}"`).join(" or ")}.`
1458
1689
  };
1459
1690
  }
1460
- this.registerFunction("navigateToPage", async (r) => {
1461
- const l = r.page, h = s.find((f) => f.name === l);
1691
+ this.registerFunction("navigateToPage", async (o) => {
1692
+ const a = o.page, h = s.find((p) => p.name === a);
1462
1693
  if (!h) return {
1463
1694
  success: !1,
1464
- error: `Unknown page: ${l}`
1695
+ error: `Unknown page: ${a}`
1465
1696
  };
1466
1697
  let u = {};
1467
- if (typeof r.params == "string") try {
1468
- u = JSON.parse(r.params);
1698
+ if (typeof o.params == "string") try {
1699
+ u = JSON.parse(o.params);
1469
1700
  } catch {
1470
1701
  }
1471
- else r.params && typeof r.params == "object" && (u = r.params);
1702
+ else o.params && typeof o.params == "object" && (u = o.params);
1472
1703
  const d = {};
1473
- for (const f of S(h.path)) d[f] = r[f] ?? u[f];
1474
- const { path: m, missing: y } = Nt(h.path, d);
1475
- if (y.length > 0) {
1476
- const f = y.map((v) => `"${v}": "..."`).join(", ");
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(", ");
1477
1708
  return {
1478
1709
  success: !1,
1479
- error: `Page "${l}" needs ${y.map((v) => `"${v}"`).join(", ")}. Retry with { "page": "${l}", ${f} }.`
1710
+ error: `Page "${a}" needs ${w.map((C) => `"${C}"`).join(", ")}. Retry with { "page": "${a}", ${p} }.`
1480
1711
  };
1481
1712
  }
1482
- return e(m), {
1713
+ return e(f), {
1483
1714
  success: !0,
1484
- navigatedTo: m
1715
+ navigatedTo: f
1485
1716
  };
1486
1717
  }, {
1487
1718
  description: `Navigate the user to a page in the application. Available pages:
1488
1719
  ${n}`,
1489
1720
  parameters: {
1490
1721
  type: "object",
1491
- properties: a,
1722
+ properties: c,
1492
1723
  required: ["page"]
1493
1724
  }
1494
1725
  }), this.addDynamicContext("current-page", () => {
1495
1726
  if (typeof window > "u" || !window.location) return null;
1496
- const r = window.location.href, l = typeof document < "u" ? document.title : void 0, h = Dt(window.location.pathname, s), u = { url: r };
1497
- return h && (u.page = h.name), l && (u.title = l), {
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), {
1498
1729
  name: "Current page",
1499
1730
  description: "The page the user is currently viewing.",
1500
1731
  data: u
@@ -1505,22 +1736,30 @@ ${n}`,
1505
1736
  this.unregisterFunction("navigateToPage"), this.removeDynamicContext("current-page");
1506
1737
  }
1507
1738
  registerPageStateFunction(e, s) {
1508
- const i = s?.functionName ?? "setPageState", n = new Map(e.map((a) => [a.name, a])), o = e.map((a) => `- "${a.name}": ${a.description}`).join(`
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(`
1509
1740
  `);
1510
1741
  this.registerFunction(i, async (a) => {
1511
- const r = {};
1512
- for (const [l, h] of Object.entries(a)) {
1513
- if (h === void 0) continue;
1514
- const u = n.get(l);
1515
- u && (await u.set(h), r[l] = h);
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);
1516
1747
  }
1517
- return {
1748
+ return r ? {
1518
1749
  success: !0,
1519
- applied: r
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
1520
1758
  };
1521
1759
  }, {
1522
1760
  description: `Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
1523
- ${o}`,
1761
+ ${c}` + (r ? `
1762
+ Returns the resulting page data once it has loaded: ${r.description}` : ""),
1524
1763
  parameters: {
1525
1764
  type: "object",
1526
1765
  properties: Object.fromEntries(e.map((a) => [a.name, {
@@ -1528,22 +1767,52 @@ ${o}`,
1528
1767
  description: a.description
1529
1768
  }]))
1530
1769
  },
1531
- requiresApproval: s?.requiresApproval
1532
- }), this.addDynamicContext(`page-state:${i}`, () => {
1533
- const a = e.filter((l) => typeof l.get == "function");
1770
+ requiresApproval: s?.requiresApproval,
1771
+ maxResultBytes: r?.maxResultBytes
1772
+ });
1773
+ const o = G(i);
1774
+ r ? (this.warnIfPlaceholderMode(i), this.registerFunction(o, async () => ({ data: N(i, await this.readPageData(i, r, s), this.pageDataBudget(r) - this.envelopeBytes({})) }), {
1775
+ description: `Read what the current page is displaying, without changing anything: ${r.description}`,
1776
+ parameters: {
1777
+ type: "object",
1778
+ properties: {}
1779
+ },
1780
+ maxResultBytes: r.maxResultBytes
1781
+ }), this.pageDataCompanions.add(o)) : this.pageDataCompanions.delete(o) && this.unregisterFunction(o), this.addDynamicContext(`page-state:${i}`, () => {
1782
+ const a = e.filter((u) => typeof u.get == "function");
1534
1783
  if (a.length === 0) return null;
1535
- const r = {};
1536
- for (const l of a) r[l.name] = l.get();
1784
+ const h = {};
1785
+ for (const u of a) h[u.name] = u.get();
1537
1786
  return {
1538
1787
  name: "Page state",
1539
1788
  description: "Current, editable state of the page the user is viewing.",
1540
- data: r
1789
+ data: h
1541
1790
  };
1542
1791
  });
1543
1792
  }
1544
1793
  unregisterPageStateFunction(e) {
1545
1794
  const s = e ?? "setPageState";
1546
- this.unregisterFunction(s), this.removeDynamicContext(`page-state:${s}`);
1795
+ this.unregisterFunction(s);
1796
+ const i = G(s);
1797
+ this.pageDataCompanions.delete(i) && this.unregisterFunction(i), this.removeDynamicContext(`page-state:${s}`);
1798
+ }
1799
+ pageDataBudget(e) {
1800
+ return e.maxResultBytes ?? this.functionRegistry.getDefaultMaxResultBytes();
1801
+ }
1802
+ envelopeBytes(e) {
1803
+ return m(JSON.stringify({
1804
+ ...e,
1805
+ data: null
1806
+ })) - 4;
1807
+ }
1808
+ readPageData(e, s, i) {
1809
+ return ct(() => s, i?.settleTimeoutMs ?? 1e4).catch((n) => (l.warn(`Reading page data for "${e}" failed:`, n), {
1810
+ error: "page_data_unavailable",
1811
+ message: n instanceof Error ? n.message : String(n)
1812
+ }));
1813
+ }
1814
+ warnIfPlaceholderMode(e) {
1815
+ 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.`));
1547
1816
  }
1548
1817
  setContext(e, s) {
1549
1818
  this.contextRegistry.set(e, s), this.notifyContextChanged();
@@ -1591,10 +1860,10 @@ ${o}`,
1591
1860
  return this.contextRegistry.getSnapshot();
1592
1861
  }
1593
1862
  buildSendContext() {
1594
- const e = this.contextRegistry.getSnapshot(), s = e?.entries ?? {}, { changes: i, baseline: n } = bt(this.lastSentPageState, s);
1863
+ const e = this.contextRegistry.getSnapshot(), s = e?.entries ?? {}, { changes: i, baseline: n } = Wt(this.lastSentPageState, s);
1595
1864
  return this.lastSentPageState = n, i.length === 0 ? e : { entries: {
1596
1865
  ...s,
1597
- [Ot]: {
1866
+ [se]: {
1598
1867
  name: "State changes",
1599
1868
  description: "Fields in the page state that changed since your last message, as field: <old> -> <new>.",
1600
1869
  data: { changes: i }
@@ -1616,20 +1885,20 @@ ${o}`,
1616
1885
  }
1617
1886
  recordAgentAction(e) {
1618
1887
  const s = e.functionName, i = e.arguments;
1619
- let n, o;
1888
+ let n, r;
1620
1889
  if (s === "navigateToPage") {
1621
- const a = i?.page;
1622
- n = "agent.navigate", o = a ? `Agent navigated to "${String(a)}"` : "Agent navigated";
1623
- } else s === "setPageState" ? (n = "agent.page_state", o = "Agent changed the page state") : (n = `agent.${s}`, o = `Agent ran "${s}"`);
1890
+ const c = i?.page;
1891
+ n = "agent.navigate", r = c ? `Agent navigated to "${String(c)}"` : "Agent navigated";
1892
+ } else s === "setPageState" ? (n = "agent.page_state", r = "Agent changed the page state") : (n = `agent.${s}`, r = `Agent ran "${s}"`);
1624
1893
  this.addActivity({
1625
1894
  actor: "agent",
1626
1895
  name: n,
1627
- summary: o,
1896
+ summary: r,
1628
1897
  ...i && Object.keys(i).length > 0 ? { data: { arguments: i } } : {}
1629
1898
  });
1630
1899
  }
1631
1900
  registerActivityContext() {
1632
- this.contextRegistry.addDynamicProvider(Pt, () => {
1901
+ this.contextRegistry.addDynamicProvider(ee, () => {
1633
1902
  const e = this.activityLedger.getRecent();
1634
1903
  return e.length === 0 ? null : {
1635
1904
  name: "Recent activity",
@@ -1652,44 +1921,44 @@ ${o}`,
1652
1921
  }
1653
1922
  updateConfig(e) {
1654
1923
  const s = {};
1655
- for (const [n, o] of Object.entries(e)) o !== void 0 && (s[n] = o);
1924
+ for (const [n, r] of Object.entries(e)) r !== void 0 && (s[n] = r);
1656
1925
  const i = {
1657
1926
  ...this.config,
1658
1927
  ...s
1659
1928
  };
1660
- D(i, "AgoClient.updateConfig"), this.config = i, this.httpClient.updateConfig(s), s.debug !== void 0 && (s.debug ? c.enable() : c.disable()), s.maxFunctionResultBytes !== void 0 && this.functionRegistry.setDefaultMaxResultBytes(s.maxFunctionResultBytes);
1929
+ 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);
1661
1930
  }
1662
1931
  destroy() {
1663
- this.proactive?.destroy(), this.proactive = null, this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), this.pendingResumes.clear(), this.pendingApprovals.clear(), this.resumeGate = null, c.log("AgoClient destroyed");
1932
+ 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");
1664
1933
  }
1665
1934
  reviveAfterDestroy() {
1666
- this.registerActivityContext(), this.config.proactive && !this.proactive && F(this, this.config.proactive);
1935
+ this.registerActivityContext(), this.config.proactive && !this.proactive && U(this, this.config.proactive);
1667
1936
  }
1668
1937
  };
1669
1938
  export {
1670
- k as C,
1671
- w as S,
1672
- Ut as T,
1673
- z as _,
1674
- Lt as a,
1939
+ F as C,
1940
+ S,
1941
+ ie as T,
1942
+ st as _,
1943
+ re as a,
1675
1944
  g as b,
1676
- kt as c,
1677
- F as d,
1678
- ct as f,
1679
- et as g,
1680
- st as h,
1681
- Bt as i,
1682
- Mt as l,
1683
- O as m,
1684
- D as n,
1685
- jt as o,
1686
- lt as p,
1687
- Tt as r,
1688
- It as s,
1689
- Gt as t,
1690
- wt as u,
1691
- c as v,
1692
- j as w,
1693
- R as x,
1694
- p as y
1945
+ Ht as c,
1946
+ U as d,
1947
+ kt as f,
1948
+ St as g,
1949
+ At as h,
1950
+ ae as i,
1951
+ ne as l,
1952
+ W as m,
1953
+ q as n,
1954
+ oe as o,
1955
+ Tt as p,
1956
+ Yt as r,
1957
+ zt as s,
1958
+ ce as t,
1959
+ Lt as u,
1960
+ l as v,
1961
+ X as w,
1962
+ D as x,
1963
+ y
1695
1964
  };