@useago/sdk 1.5.3 → 1.5.4

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