@useago/sdk 1.4.0 → 1.4.1

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 (36) hide show
  1. package/dist/{AgoClient-BrhKkDWt.js → AgoClient-BdtuHX7k.js} +49 -25
  2. package/dist/{AgoClient-B2BU8tfB.cjs → AgoClient-CRAnT4qE.cjs} +4 -4
  3. package/dist/angular.cjs +1 -1
  4. package/dist/angular.d.cts +12 -0
  5. package/dist/angular.d.ts +12 -0
  6. package/dist/angular.js +4 -1
  7. package/dist/{createConversationSession-Cin8dVNq.cjs → createConversationSession-B8zfTL78.cjs} +1 -1
  8. package/dist/{createConversationSession-ByePKfus.js → createConversationSession-CWpf4u6I.js} +1 -1
  9. package/dist/{createFormCollector-BYKe5Uxm.js → createFormCollector-B4n0_diV.js} +1 -1
  10. package/dist/{createFormCollector-CpYX_5PT.cjs → createFormCollector-BB_l0Sia.cjs} +1 -1
  11. package/dist/{createMockClient-DwdxNwEn.js → createMockClient-d-arlmCq.js} +19 -17
  12. package/dist/createMockClient-ucPENDzz.cjs +1 -0
  13. package/dist/devtools.d.cts +10 -0
  14. package/dist/devtools.d.ts +10 -0
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.d.cts +10 -0
  17. package/dist/index.d.ts +10 -0
  18. package/dist/index.js +4 -4
  19. package/dist/react.cjs +2 -2
  20. package/dist/react.d.cts +10 -0
  21. package/dist/react.d.ts +10 -0
  22. package/dist/react.js +22 -22
  23. package/dist/testing.cjs +1 -1
  24. package/dist/testing.d.cts +10 -0
  25. package/dist/testing.d.ts +10 -0
  26. package/dist/testing.js +1 -1
  27. package/dist/vue.cjs +1 -1
  28. package/dist/vue.d.cts +10 -0
  29. package/dist/vue.d.ts +10 -0
  30. package/dist/vue.js +14 -14
  31. package/dist/widget.cjs +1 -1
  32. package/dist/widget.d.cts +10 -0
  33. package/dist/widget.d.ts +10 -0
  34. package/dist/widget.js +3 -3
  35. package/package.json +1 -1
  36. package/dist/createMockClient-zHQ0cjUH.cjs +0 -1
@@ -129,7 +129,7 @@ var k = class {
129
129
  let s = "";
130
130
  throw e.status === 401 || e.status === 403 ? s = " Check `userJwt` (and that it has not expired)." : e.status === 404 && (s = " Check that `baseUrl` points at your AGO API root."), new u(`HTTP ${e.status}: ${e.statusText}.${s}`, "http_error", e.status, "api_error");
131
131
  }
132
- }, A = class {
132
+ }, x = class {
133
133
  constructor() {
134
134
  this.functions = /* @__PURE__ */ new Map();
135
135
  }
@@ -181,7 +181,7 @@ var k = class {
181
181
  get size() {
182
182
  return this.functions.size;
183
183
  }
184
- }, x = class {
184
+ }, A = class {
185
185
  constructor() {
186
186
  this.entries = /* @__PURE__ */ new Map(), this.dynamicProviders = /* @__PURE__ */ new Map();
187
187
  }
@@ -215,8 +215,8 @@ var k = class {
215
215
  this.entries.clear(), this.dynamicProviders.clear(), a.log("ClientContext cleared");
216
216
  }
217
217
  };
218
- function g(e) {
219
- return e === null || typeof e != "object" ? JSON.stringify(e) ?? "null" : Array.isArray(e) ? `[${e.map(g).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${g(e[t])}`).join(",")}}`;
218
+ function f(e) {
219
+ return e === null || typeof e != "object" ? JSON.stringify(e) ?? "null" : Array.isArray(e) ? `[${e.map(f).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${f(e[t])}`).join(",")}}`;
220
220
  }
221
221
  var R = class {
222
222
  constructor(e) {
@@ -281,7 +281,7 @@ var R = class {
281
281
  url: s.use_external_link ? s.external_link_url : s.internal_link_url
282
282
  };
283
283
  })), e.type === "client_function" && e.function_name) {
284
- const t = `${e.function_name}::${g(e.arguments ?? {})}`;
284
+ const t = `${e.function_name}::${f(e.arguments ?? {})}`;
285
285
  this.firedClientFunctions.has(t) || (this.firedClientFunctions.add(t), this.callbacks.onClientFunction?.({
286
286
  invocationId: e.id || "",
287
287
  functionName: e.function_name,
@@ -330,11 +330,11 @@ var R = class {
330
330
  return this.callbacks.onComplete?.(e), e;
331
331
  }
332
332
  };
333
- function N(e) {
333
+ function O(e) {
334
334
  const t = e.message.toLowerCase();
335
335
  return t.includes("load failed") || t.includes("failed to fetch") || t.includes("network") || t.includes("abort");
336
336
  }
337
- var I = /* @__PURE__ */ new Set([
337
+ var F = /* @__PURE__ */ new Set([
338
338
  "image/jpeg",
339
339
  "image/png",
340
340
  "image/gif",
@@ -342,7 +342,7 @@ var I = /* @__PURE__ */ new Set([
342
342
  "image/bmp",
343
343
  "image/tiff"
344
344
  ]);
345
- function F(e) {
345
+ function I(e) {
346
346
  if (!e) return;
347
347
  const t = typeof window < "u" && window.location ? window.location.href : "https://ago.local/";
348
348
  try {
@@ -351,10 +351,10 @@ function F(e) {
351
351
  } catch {
352
352
  }
353
353
  }
354
- function P(e) {
355
- return e.isSafeImage === !0 && typeof e.contentType == "string" && e.contentType.startsWith("image/") && F(e.url) !== void 0;
354
+ function j(e) {
355
+ return e.isSafeImage === !0 && typeof e.contentType == "string" && e.contentType.startsWith("image/") && I(e.url) !== void 0;
356
356
  }
357
- function O(e) {
357
+ function M(e) {
358
358
  if (e == null || e < 0) return "";
359
359
  if (e < 1024) return `${e} B`;
360
360
  const t = e / 1024;
@@ -370,14 +370,14 @@ function U(e) {
370
370
  isSafeImage: e.is_safe_image === !0
371
371
  };
372
372
  }
373
- function j(e) {
373
+ function L(e) {
374
374
  return e.map((t, s) => ({
375
375
  id: `local-${s}-${t.name}`,
376
376
  name: t.name,
377
377
  contentType: t.type || void 0,
378
378
  fileSize: t.size,
379
379
  url: typeof URL < "u" && URL.createObjectURL ? URL.createObjectURL(t) : void 0,
380
- isSafeImage: I.has(t.type)
380
+ isSafeImage: F.has(t.type)
381
381
  }));
382
382
  }
383
383
  var T = class {
@@ -428,9 +428,22 @@ function b(e, t = "AgoClient") {
428
428
  if (typeof s != "string" || s.trim() === "") throw new h(`${t}: ${v}`, "config_missing_base_url");
429
429
  !s.startsWith("/") && !D.test(s) && (C || (C = !0, console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)));
430
430
  }
431
- var M = class _ {
431
+ function N(e) {
432
+ return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
433
+ }
434
+ function P(e, t) {
435
+ const s = t.find((n) => n.path === e);
436
+ if (s) return s;
437
+ const i = t.find((n) => {
438
+ if (!n.path.includes(":")) return !1;
439
+ const r = "^" + n.path.split("/").map((o) => o.startsWith(":") ? "[^/]+" : N(o)).join("/") + "/?$";
440
+ return new RegExp(r).test(e);
441
+ });
442
+ return i || t.filter((n) => n.path !== "/" && e.startsWith(n.path)).sort((n, r) => r.path.length - n.path.length)[0];
443
+ }
444
+ var z = class _ {
432
445
  constructor(t) {
433
- this.warnedEmptyConversations = /* @__PURE__ */ new Set(), b(t, "AgoClient"), this.config = t, this.httpClient = new k(t), this.functionRegistry = new A(), this.contextRegistry = new x(), this.eventEmitter = new T(), t.debug && a.enable(), a.log("AgoClient initialized");
446
+ this.warnedEmptyConversations = /* @__PURE__ */ new Set(), b(t, "AgoClient"), this.config = t, this.httpClient = new k(t), this.functionRegistry = new x(), this.contextRegistry = new A(), this.eventEmitter = new T(), t.debug && a.enable(), a.log("AgoClient initialized");
434
447
  }
435
448
  async sendMessage(t, s) {
436
449
  const i = this.functionRegistry.getSchemas(), n = this.contextRegistry.getSnapshot(), r = this.config.agent || this.config.defaultAgentId, o = {
@@ -624,8 +637,19 @@ ${n}`,
624
637
  } },
625
638
  required: ["page"]
626
639
  }
640
+ }), this.addDynamicContext("current-page", () => {
641
+ if (typeof window > "u" || !window.location) return null;
642
+ const r = window.location.href, o = typeof document < "u" ? document.title : void 0, l = P(window.location.pathname, s), c = { url: r };
643
+ return l && (c.page = l.name), o && (c.title = o), {
644
+ name: "Current page",
645
+ description: "The page the user is currently viewing.",
646
+ data: c
647
+ };
627
648
  });
628
649
  }
650
+ unregisterNavigationFunction() {
651
+ this.unregisterFunction("navigateToPage"), this.removeDynamicContext("current-page");
652
+ }
629
653
  registerPageStateFunction(t, s) {
630
654
  const i = s?.functionName ?? "setPageState", n = new Map(t.map((o) => [o.name, o])), r = t.map((o) => `- "${o.name}": ${o.description}`).join(`
631
655
  `);
@@ -633,8 +657,8 @@ ${n}`,
633
657
  const l = {};
634
658
  for (const [c, d] of Object.entries(o)) {
635
659
  if (d === void 0) continue;
636
- const f = n.get(c);
637
- f && (await f.set(d), l[c] = d);
660
+ const g = n.get(c);
661
+ g && (await g.set(d), l[c] = d);
638
662
  }
639
663
  return {
640
664
  success: !0,
@@ -729,20 +753,20 @@ ${r}`,
729
753
  };
730
754
  export {
731
755
  p as _,
732
- P as a,
756
+ j as a,
733
757
  R as c,
734
- A as d,
758
+ x as d,
735
759
  a as f,
736
760
  m as g,
737
761
  y as h,
738
- j as i,
739
- N as l,
762
+ L as i,
763
+ O as l,
740
764
  h as m,
741
765
  b as n,
742
- O as o,
766
+ M as o,
743
767
  u as p,
744
768
  T as r,
745
- F as s,
746
- M as t,
747
- x as u
769
+ I as s,
770
+ z as t,
771
+ A as u
748
772
  };
@@ -1,8 +1,8 @@
1
- var h=class extends Error{constructor(e,t,n){super(e),this.code=t,this.statusCode=n,this.name="AgoError"}},u=class E extends h{constructor(t,n,r,s,i,o){super(t,n,r),this.type=s,this.param=i,this.docUrl=o,this.name="AgoApiError"}static fromResponse(t,n){const r=t.error;return new E(r.doc_url?`${r.message} See ${r.doc_url}`:r.message,r.code,n,r.type,r.param,r.doc_url)}},m=class extends h{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},f=class extends h{constructor(e,t="stream_error"){super(e,t),this.name="AgoStreamError"}},g=class extends h{constructor(e,t,n){super(e,"function_error"),this.functionName=t,this.originalError=n,this.name="AgoFunctionError"}},R=class{constructor(e=!1){this.enabled=e}enable(){this.enabled=!0}disable(){this.enabled=!1}log(...e){this.enabled&&console.log("[AGO SDK]",...e)}warn(...e){this.enabled&&console.warn("[AGO SDK]",...e)}error(...e){console.error("[AGO SDK]",...e)}debug(...e){this.enabled&&console.debug("[AGO SDK]",...e)}},a=new R,v="ago_widget_id";function x(){if(typeof localStorage<"u"){const t=localStorage.getItem(v);if(t)return t}const e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`;if(typeof localStorage<"u")try{localStorage.setItem(v,e)}catch{}return e}var I=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||x()},e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission&&(this.headers["X-Widget-Permission"]=e.permission)}updateConfig(e){e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-User-Anon-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"])}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async postStream(e,t){const n=`${this.baseUrl}${e}`;a.debug("POST (stream)",n,t);try{const r=await fetch(n,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0});return r.ok||await this.handleErrorResponse(r),r}catch(r){throw r instanceof u?r:new m(`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)}}async postFormData(e,t){const n=`${this.baseUrl}${e}`;a.debug("POST (formData)",n);const r={...this.headers};try{const s=await fetch(n,{method:"POST",headers:r,body:t});return s.ok||await this.handleErrorResponse(s),s}catch(s){throw s instanceof u?s:new m(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async request(e,t,n){const r=`${this.baseUrl}${t}`;a.debug(e,r,n);try{const s=await fetch(r,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0});return s.ok||await this.handleErrorResponse(s),s.status===204?void 0:s.json()}catch(s){throw s instanceof u?s:new m(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw u.fromResponse(t,e.status);let n="";throw e.status===401||e.status===403?n=" Check `userJwt` (and that it has not expired).":e.status===404&&(n=" Check that `baseUrl` points at your AGO API root."),new u(`HTTP ${e.status}: ${e.statusText}.${n}`,"http_error",e.status,"api_error")}},_=class{constructor(){this.functions=new Map}register(e,t,n){if(typeof e=="object"){const{name:s,handler:i,description:o,parameters:l}=e;return this.register(s,i,{description:o,parameters:l})}const r=e;if(!t||!n)throw new h(`registerFunction("${r}"): 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");this.functions.has(r)&&a.warn(`Function "${r}" is being overwritten`),this.functions.set(r,{schema:{...n,name:r},handler:t}),a.log(`Registered function: ${r}`)}unregister(e){const t=this.functions.delete(e);return t&&a.log(`Unregistered function: ${e}`),t}get(e){return this.functions.get(e)}has(e){return this.functions.has(e)}getSchemas(){return Array.from(this.functions.values()).map(e=>e.schema)}async execute(e,t){const n=this.functions.get(e);if(!n)throw new g(`Function "${e}" is not registered`,e);a.log(`Executing function: ${e}`,t);try{const r=await n.handler(t);return a.log(`Function ${e} completed:`,r),r}catch(r){throw a.error(`Function ${e} failed:`,r),new g(`Function "${e}" execution failed: ${r instanceof Error?r.message:"Unknown error"}`,e,r instanceof Error?r:void 0)}}clear(){this.functions.clear(),a.log("Cleared all registered functions")}get size(){return this.functions.size}},S=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),a.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&a.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),a.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&a.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,n]of this.entries)e[t]=n;for(const[t,n]of this.dynamicProviders)try{const r=n();r&&(e[t]=r)}catch(r){a.error(`DynamicContext provider "${t}" threw:`,r)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),a.log("ClientContext cleared")}};function p(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(p).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${p(e[t])}`).join(",")}}`}var k=class{constructor(e){this.callbacks=e,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.firedClientFunctions=new Set}async processStream(e){if(!e.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");const t=e.body.getReader(),n=new TextDecoder;try{for(;;){const{done:r,value:s}=await t.read();if(r)break;const i=n.decode(s,{stream:!0});this.buffer+=i,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(r){const s=r instanceof Error?r:new f("Stream processing failed mid-flight. The connection may have dropped; retry the message.");throw this.callbacks.onError?.(s),s}finally{t.releaseLock()}}processBuffer(){const e=this.buffer.split(`
1
+ var u=class extends Error{constructor(e,t,n){super(e),this.code=t,this.statusCode=n,this.name="AgoError"}},h=class E extends u{constructor(t,n,r,s,i,o){super(t,n,r),this.type=s,this.param=i,this.docUrl=o,this.name="AgoApiError"}static fromResponse(t,n){const r=t.error;return new E(r.doc_url?`${r.message} See ${r.doc_url}`:r.message,r.code,n,r.type,r.param,r.doc_url)}},f=class extends u{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},m=class extends u{constructor(e,t="stream_error"){super(e,t),this.name="AgoStreamError"}},g=class extends u{constructor(e,t,n){super(e,"function_error"),this.functionName=t,this.originalError=n,this.name="AgoFunctionError"}},R=class{constructor(e=!1){this.enabled=e}enable(){this.enabled=!0}disable(){this.enabled=!1}log(...e){this.enabled&&console.log("[AGO SDK]",...e)}warn(...e){this.enabled&&console.warn("[AGO SDK]",...e)}error(...e){console.error("[AGO SDK]",...e)}debug(...e){this.enabled&&console.debug("[AGO SDK]",...e)}},a=new R,v="ago_widget_id";function F(){if(typeof localStorage<"u"){const t=localStorage.getItem(v);if(t)return t}const e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`;if(typeof localStorage<"u")try{localStorage.setItem(v,e)}catch{}return e}var I=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||F()},e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission&&(this.headers["X-Widget-Permission"]=e.permission)}updateConfig(e){e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-User-Anon-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"])}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async postStream(e,t){const n=`${this.baseUrl}${e}`;a.debug("POST (stream)",n,t);try{const r=await fetch(n,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0});return r.ok||await this.handleErrorResponse(r),r}catch(r){throw r instanceof h?r:new f(`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)}}async postFormData(e,t){const n=`${this.baseUrl}${e}`;a.debug("POST (formData)",n);const r={...this.headers};try{const s=await fetch(n,{method:"POST",headers:r,body:t});return s.ok||await this.handleErrorResponse(s),s}catch(s){throw s instanceof h?s:new f(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async request(e,t,n){const r=`${this.baseUrl}${t}`;a.debug(e,r,n);try{const s=await fetch(r,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0});return s.ok||await this.handleErrorResponse(s),s.status===204?void 0:s.json()}catch(s){throw s instanceof h?s:new f(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw h.fromResponse(t,e.status);let n="";throw e.status===401||e.status===403?n=" Check `userJwt` (and that it has not expired).":e.status===404&&(n=" Check that `baseUrl` points at your AGO API root."),new h(`HTTP ${e.status}: ${e.statusText}.${n}`,"http_error",e.status,"api_error")}},_=class{constructor(){this.functions=new Map}register(e,t,n){if(typeof e=="object"){const{name:s,handler:i,description:o,parameters:l}=e;return this.register(s,i,{description:o,parameters:l})}const r=e;if(!t||!n)throw new u(`registerFunction("${r}"): 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");this.functions.has(r)&&a.warn(`Function "${r}" is being overwritten`),this.functions.set(r,{schema:{...n,name:r},handler:t}),a.log(`Registered function: ${r}`)}unregister(e){const t=this.functions.delete(e);return t&&a.log(`Unregistered function: ${e}`),t}get(e){return this.functions.get(e)}has(e){return this.functions.has(e)}getSchemas(){return Array.from(this.functions.values()).map(e=>e.schema)}async execute(e,t){const n=this.functions.get(e);if(!n)throw new g(`Function "${e}" is not registered`,e);a.log(`Executing function: ${e}`,t);try{const r=await n.handler(t);return a.log(`Function ${e} completed:`,r),r}catch(r){throw a.error(`Function ${e} failed:`,r),new g(`Function "${e}" execution failed: ${r instanceof Error?r.message:"Unknown error"}`,e,r instanceof Error?r:void 0)}}clear(){this.functions.clear(),a.log("Cleared all registered functions")}get size(){return this.functions.size}},S=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),a.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&a.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),a.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&a.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,n]of this.entries)e[t]=n;for(const[t,n]of this.dynamicProviders)try{const r=n();r&&(e[t]=r)}catch(r){a.error(`DynamicContext provider "${t}" threw:`,r)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),a.log("ClientContext cleared")}};function p(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(p).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${p(e[t])}`).join(",")}}`}var $=class{constructor(e){this.callbacks=e,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.firedClientFunctions=new Set}async processStream(e){if(!e.body)throw new m("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");const t=e.body.getReader(),n=new TextDecoder;try{for(;;){const{done:r,value:s}=await t.read();if(r)break;const i=n.decode(s,{stream:!0});this.buffer+=i,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(r){const s=r instanceof Error?r:new m("Stream processing failed mid-flight. The connection may have dropped; retry the message.");throw this.callbacks.onError?.(s),s}finally{t.releaseLock()}}processBuffer(){const e=this.buffer.split(`
2
2
 
3
3
  `);this.buffer=e.pop()||"";for(const t of e){if(!t.trim())continue;const n=t.split(`
4
- `);for(const r of n)if(!r.startsWith(": ")&&r.startsWith("data: ")){const s=r.slice(6);try{const i=JSON.parse(s);this.handleChunk(i)}catch(i){a.warn("Failed to parse SSE data:",s,i)}}}}handleChunk(e){if(this.callbacks.onRawChunk?.(e),e.message_id&&!this.message.id&&(this.message.id=e.message_id),e.thread?.id&&(this.message.conversationId=e.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),e.content!==void 0&&(this.message.content=(this.message.content||"")+e.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:e.content,conversationId:this.message.conversationId,messageId:this.message.id})),e.full_content!==void 0&&(this.message.content=e.full_content),e.status&&(this.message.status=e.status),e.agent&&(this.message.agent={id:e.agent.id,name:e.agent.name,displayName:e.agent.display_name}),e.knowledge_sources&&(this.sources=e.knowledge_sources.map(t=>{const n=t.knowledge_document;return{id:n.id,title:n.title,url:n.use_external_link?n.external_link_url:n.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${p(e.arguments??{})}`;this.firedClientFunctions.has(t)||(this.firedClientFunctions.add(t),this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}))}if(e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const n=this.toolCalls.findIndex(r=>r.id===t.id);n>=0?this.toolCalls[n]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies),this.message.status==="DONE"&&!this.answerCompleteEmitted&&this.message.id&&(this.answerCompleteEmitted=!0,this.callbacks.onAnswerComplete?.(this.buildMessage()))}parseToolCall(e){return{id:e.id||"",type:e.type||"status_message",status:e.status||"unknown",toolName:e.tool_name||"",toolDisplayName:e.tool_display_name,message:e.message,formSchema:e.form_schema,data:e.data,functionName:e.function_name,arguments:e.arguments}}buildMessage(){return{id:this.message.id||"",conversationId:this.message.conversationId||"",content:this.message.content||"",role:"assistant",status:this.message.status||"DONE",agent:this.message.agent,sources:this.sources.length>0?this.sources:void 0,toolCalls:this.toolCalls.length>0?this.toolCalls:void 0,followUpReplies:this.followUpReplies.length>0?this.followUpReplies:void 0,createdAt:new Date}}buildFinalMessage(){const e=this.buildMessage();return this.callbacks.onComplete?.(e),e}};function U(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var P=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function A(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const n=new URL(e,t);if(n.protocol==="http:"||n.protocol==="https:"||n.protocol==="blob:")return e}catch{}}function O(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&A(e.url)!==void 0}function j(e){if(e==null||e<0)return"";if(e<1024)return`${e} B`;const t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function N(e){return{id:String(e.id??""),name:typeof e.name=="string"&&e.name?e.name:"file",contentType:typeof e.content_type=="string"?e.content_type:void 0,fileSize:typeof e.file_size=="number"?e.file_size:void 0,url:typeof e.file_url=="string"?e.file_url:void 0,isSafeImage:e.is_safe_image===!0}}function T(e){return e.map((t,n)=>({id:`local-${n}-${t.name}`,name:t.name,contentType:t.type||void 0,fileSize:t.size,url:typeof URL<"u"&&URL.createObjectURL?URL.createObjectURL(t):void 0,isSafeImage:P.has(t.type)}))}var $=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){const n=this.handlers.get(e);n&&n.delete(t)}emit(e,t){const n=this.handlers.get(e);n&&n.forEach(r=>{try{r(t)}catch(s){console.error(`Error in event handler for ${String(e)}:`,s)}})}once(e,t){const n=(r=>{this.off(e,n),t(r)});this.on(e,n)}waitFor(e,t){return new Promise((n,r)=>{let s;const i=(o=>{s&&clearTimeout(s),n(o)});this.once(e,i),t?.timeout&&(s=setTimeout(()=>{this.off(e,i),r(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},b='`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).',D=/^[a-z][a-z0-9+.-]*:\/\//i,C=!1;function y(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new h(`${t}: ${b}`,"config_missing_base_url");const n=e.baseUrl;if(typeof n!="string"||n.trim()==="")throw new h(`${t}: ${b}`,"config_missing_base_url");!n.startsWith("/")&&!D.test(n)&&(C||(C=!0,console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)))}var M=class F{constructor(t){this.warnedEmptyConversations=new Set,y(t,"AgoClient"),this.config=t,this.httpClient=new I(t),this.functionRegistry=new _,this.contextRegistry=new S,this.eventEmitter=new $,t.debug&&a.enable(),a.log("AgoClient initialized")}async sendMessage(t,n){const r=this.functionRegistry.getSchemas(),s=this.contextRegistry.getSnapshot(),i=this.config.agent||this.config.defaultAgentId,o={content:t,conversation_id:n?.conversationId,agent_id:n?.agentId||i};r.length>0&&(o.client_functions=r),s&&(o.client_context=s),n?.hidden&&(o.hidden=!0);let l;if(n?.files&&n.files.length>0){const c=new FormData;c.append("content",t),n.conversationId&&c.append("conversation_id",n.conversationId),(n.agentId||i)&&c.append("agent_id",n.agentId||i||""),r.length>0&&c.append("client_functions",JSON.stringify(r)),s&&c.append("client_context",JSON.stringify(s)),n.hidden&&c.append("hidden","true");for(const d of n.files)c.append("files",d);l=await this.httpClient.postFormData("/api/sdk/v1/messages",c)}else l=await this.httpClient.postStream("/api/sdk/v1/messages",o);return this.processSSEResponse(l)}async processSSEResponse(t){let n=!1;const r=await new k({onRawChunk:s=>{this.eventEmitter.emit("stream:message",s)},onStart:s=>{this.eventEmitter.emit("message:start",s)},onChunk:s=>{this.eventEmitter.emit("message:chunk",s)},onToolCall:s=>{this.eventEmitter.emit("toolCall:received",s),s.type==="form"&&this.eventEmitter.emit("toolCall:form",s)},onClientFunction:async s=>{n=!0,this.eventEmitter.emit("function:invoke",s),await this.handleClientFunctionInvocation(s)},onAnswerComplete:s=>{this.eventEmitter.emit("message:answer-complete",s)},onComplete:s=>{this.eventEmitter.emit("message:complete",s)},onError:s=>{this.eventEmitter.emit("message:error",{error:s.message,code:s instanceof h?s.code:void 0})}}).processStream(t);return this.maybeFlagEmptyReply(r,n),r}maybeFlagEmptyReply(t,n){t.status==="DONE"&&(t.content??"").trim()===""&&!n&&!(t.toolCalls&&t.toolCalls.length>0)&&!(t.followUpReplies&&t.followUpReplies.length>0)&&setTimeout(()=>{if(this.eventEmitter.emit("message:empty",{conversationId:t.conversationId??"",messageId:t.id??""}),this.config.warnOnEmptyReply===!1)return;const r=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(r))return;this.warnedEmptyConversations.add(r);const s=this.config.agent||this.config.defaultAgentId;t.id?console.warn("[AGO] Reply completed with empty content. Possible causes: "+(s?`the agent "${s}" 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: "+(s?`the agent "${s}" 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`.")},0)}async handleClientFunctionInvocation(t){let n,r;try{n=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(s){r=s instanceof Error?s.message:"Unknown error",a.error("Client function execution failed:",s)}if(t.invocationId)try{await this.submitToolCallForm(t.invocationId,{result:n,error:r,_type:"client_function_result"})}catch(s){a.error("Failed to submit function result:",s)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:n,error:r})}async getConversations(){return(await this.httpClient.get("/api/sdk/v1/conversations")).items.map(t=>({id:t.id,title:t.title,lastMessageDate:new Date(t.last_message_date)}))}async getConversation(t){const n=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),r={id:n.id,title:n.title,lastMessageDate:new Date(n.last_message_date),messages:n.messages.map(s=>({id:s.id,conversationId:n.id,content:s.content,role:s.role,status:s.status,createdAt:new Date(s.created_at),hidden:s.hidden,toolCalls:F.mapPersistedToolCalls(s.tool_call_data),attachments:s.attachments&&s.attachments.length>0?s.attachments.map(N):void 0}))};return this.eventEmitter.emit("conversation:loaded",r),r}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(n=>({id:String(n.id??""),type:n.type??"status_message",status:String(n.status??"unknown"),toolName:n.tool_name??"",toolDisplayName:n.tool_display_name,message:n.message,formSchema:n.form_schema,data:n.data,functionName:n.function_name,arguments:n.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async submitToolCallForm(t,n){await this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:n})}async confirmToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/confirm/`)}async rejectToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/reject/`)}async getFormCollector(t){const n=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:n.name,description:n.description,schema:n.schema,submit:n.submit??void 0}}async submitFormCollector(t,n){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:n})}async submitFeedback(t,n){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:n})}registerFunction(t,n,r){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,n,r)}register(t){if(Array.isArray(t))for(const n of t)this.functionRegistry.register(n);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}registerNavigationFunction(t,n){const r=n.map(i=>i.name),s=n.map(i=>`- "${i.name}": ${i.description}`).join(`
4
+ `);for(const r of n)if(!r.startsWith(": ")&&r.startsWith("data: ")){const s=r.slice(6);try{const i=JSON.parse(s);this.handleChunk(i)}catch(i){a.warn("Failed to parse SSE data:",s,i)}}}}handleChunk(e){if(this.callbacks.onRawChunk?.(e),e.message_id&&!this.message.id&&(this.message.id=e.message_id),e.thread?.id&&(this.message.conversationId=e.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),e.content!==void 0&&(this.message.content=(this.message.content||"")+e.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:e.content,conversationId:this.message.conversationId,messageId:this.message.id})),e.full_content!==void 0&&(this.message.content=e.full_content),e.status&&(this.message.status=e.status),e.agent&&(this.message.agent={id:e.agent.id,name:e.agent.name,displayName:e.agent.display_name}),e.knowledge_sources&&(this.sources=e.knowledge_sources.map(t=>{const n=t.knowledge_document;return{id:n.id,title:n.title,url:n.use_external_link?n.external_link_url:n.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${p(e.arguments??{})}`;this.firedClientFunctions.has(t)||(this.firedClientFunctions.add(t),this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}))}if(e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const n=this.toolCalls.findIndex(r=>r.id===t.id);n>=0?this.toolCalls[n]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies),this.message.status==="DONE"&&!this.answerCompleteEmitted&&this.message.id&&(this.answerCompleteEmitted=!0,this.callbacks.onAnswerComplete?.(this.buildMessage()))}parseToolCall(e){return{id:e.id||"",type:e.type||"status_message",status:e.status||"unknown",toolName:e.tool_name||"",toolDisplayName:e.tool_display_name,message:e.message,formSchema:e.form_schema,data:e.data,functionName:e.function_name,arguments:e.arguments}}buildMessage(){return{id:this.message.id||"",conversationId:this.message.conversationId||"",content:this.message.content||"",role:"assistant",status:this.message.status||"DONE",agent:this.message.agent,sources:this.sources.length>0?this.sources:void 0,toolCalls:this.toolCalls.length>0?this.toolCalls:void 0,followUpReplies:this.followUpReplies.length>0?this.followUpReplies:void 0,createdAt:new Date}}buildFinalMessage(){const e=this.buildMessage();return this.callbacks.onComplete?.(e),e}};function U(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var P=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function k(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const n=new URL(e,t);if(n.protocol==="http:"||n.protocol==="https:"||n.protocol==="blob:")return e}catch{}}function O(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&k(e.url)!==void 0}function j(e){if(e==null||e<0)return"";if(e<1024)return`${e} B`;const t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function N(e){return{id:String(e.id??""),name:typeof e.name=="string"&&e.name?e.name:"file",contentType:typeof e.content_type=="string"?e.content_type:void 0,fileSize:typeof e.file_size=="number"?e.file_size:void 0,url:typeof e.file_url=="string"?e.file_url:void 0,isSafeImage:e.is_safe_image===!0}}function T(e){return e.map((t,n)=>({id:`local-${n}-${t.name}`,name:t.name,contentType:t.type||void 0,fileSize:t.size,url:typeof URL<"u"&&URL.createObjectURL?URL.createObjectURL(t):void 0,isSafeImage:P.has(t.type)}))}var A=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){const n=this.handlers.get(e);n&&n.delete(t)}emit(e,t){const n=this.handlers.get(e);n&&n.forEach(r=>{try{r(t)}catch(s){console.error(`Error in event handler for ${String(e)}:`,s)}})}once(e,t){const n=(r=>{this.off(e,n),t(r)});this.on(e,n)}waitFor(e,t){return new Promise((n,r)=>{let s;const i=(o=>{s&&clearTimeout(s),n(o)});this.once(e,i),t?.timeout&&(s=setTimeout(()=>{this.off(e,i),r(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},b='`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).',D=/^[a-z][a-z0-9+.-]*:\/\//i,C=!1;function y(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new u(`${t}: ${b}`,"config_missing_base_url");const n=e.baseUrl;if(typeof n!="string"||n.trim()==="")throw new u(`${t}: ${b}`,"config_missing_base_url");!n.startsWith("/")&&!D.test(n)&&(C||(C=!0,console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)))}function M(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function z(e,t){const n=t.find(s=>s.path===e);if(n)return n;const r=t.find(s=>{if(!s.path.includes(":"))return!1;const i="^"+s.path.split("/").map(o=>o.startsWith(":")?"[^/]+":M(o)).join("/")+"/?$";return new RegExp(i).test(e)});return r||t.filter(s=>s.path!=="/"&&e.startsWith(s.path)).sort((s,i)=>i.path.length-s.path.length)[0]}var L=class x{constructor(t){this.warnedEmptyConversations=new Set,y(t,"AgoClient"),this.config=t,this.httpClient=new I(t),this.functionRegistry=new _,this.contextRegistry=new S,this.eventEmitter=new A,t.debug&&a.enable(),a.log("AgoClient initialized")}async sendMessage(t,n){const r=this.functionRegistry.getSchemas(),s=this.contextRegistry.getSnapshot(),i=this.config.agent||this.config.defaultAgentId,o={content:t,conversation_id:n?.conversationId,agent_id:n?.agentId||i};r.length>0&&(o.client_functions=r),s&&(o.client_context=s),n?.hidden&&(o.hidden=!0);let l;if(n?.files&&n.files.length>0){const c=new FormData;c.append("content",t),n.conversationId&&c.append("conversation_id",n.conversationId),(n.agentId||i)&&c.append("agent_id",n.agentId||i||""),r.length>0&&c.append("client_functions",JSON.stringify(r)),s&&c.append("client_context",JSON.stringify(s)),n.hidden&&c.append("hidden","true");for(const d of n.files)c.append("files",d);l=await this.httpClient.postFormData("/api/sdk/v1/messages",c)}else l=await this.httpClient.postStream("/api/sdk/v1/messages",o);return this.processSSEResponse(l)}async processSSEResponse(t){let n=!1;const r=await new $({onRawChunk:s=>{this.eventEmitter.emit("stream:message",s)},onStart:s=>{this.eventEmitter.emit("message:start",s)},onChunk:s=>{this.eventEmitter.emit("message:chunk",s)},onToolCall:s=>{this.eventEmitter.emit("toolCall:received",s),s.type==="form"&&this.eventEmitter.emit("toolCall:form",s)},onClientFunction:async s=>{n=!0,this.eventEmitter.emit("function:invoke",s),await this.handleClientFunctionInvocation(s)},onAnswerComplete:s=>{this.eventEmitter.emit("message:answer-complete",s)},onComplete:s=>{this.eventEmitter.emit("message:complete",s)},onError:s=>{this.eventEmitter.emit("message:error",{error:s.message,code:s instanceof u?s.code:void 0})}}).processStream(t);return this.maybeFlagEmptyReply(r,n),r}maybeFlagEmptyReply(t,n){t.status==="DONE"&&(t.content??"").trim()===""&&!n&&!(t.toolCalls&&t.toolCalls.length>0)&&!(t.followUpReplies&&t.followUpReplies.length>0)&&setTimeout(()=>{if(this.eventEmitter.emit("message:empty",{conversationId:t.conversationId??"",messageId:t.id??""}),this.config.warnOnEmptyReply===!1)return;const r=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(r))return;this.warnedEmptyConversations.add(r);const s=this.config.agent||this.config.defaultAgentId;t.id?console.warn("[AGO] Reply completed with empty content. Possible causes: "+(s?`the agent "${s}" 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: "+(s?`the agent "${s}" 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`.")},0)}async handleClientFunctionInvocation(t){let n,r;try{n=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(s){r=s instanceof Error?s.message:"Unknown error",a.error("Client function execution failed:",s)}if(t.invocationId)try{await this.submitToolCallForm(t.invocationId,{result:n,error:r,_type:"client_function_result"})}catch(s){a.error("Failed to submit function result:",s)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:n,error:r})}async getConversations(){return(await this.httpClient.get("/api/sdk/v1/conversations")).items.map(t=>({id:t.id,title:t.title,lastMessageDate:new Date(t.last_message_date)}))}async getConversation(t){const n=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),r={id:n.id,title:n.title,lastMessageDate:new Date(n.last_message_date),messages:n.messages.map(s=>({id:s.id,conversationId:n.id,content:s.content,role:s.role,status:s.status,createdAt:new Date(s.created_at),hidden:s.hidden,toolCalls:x.mapPersistedToolCalls(s.tool_call_data),attachments:s.attachments&&s.attachments.length>0?s.attachments.map(N):void 0}))};return this.eventEmitter.emit("conversation:loaded",r),r}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(n=>({id:String(n.id??""),type:n.type??"status_message",status:String(n.status??"unknown"),toolName:n.tool_name??"",toolDisplayName:n.tool_display_name,message:n.message,formSchema:n.form_schema,data:n.data,functionName:n.function_name,arguments:n.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async submitToolCallForm(t,n){await this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:n})}async confirmToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/confirm/`)}async rejectToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/reject/`)}async getFormCollector(t){const n=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:n.name,description:n.description,schema:n.schema,submit:n.submit??void 0}}async submitFormCollector(t,n){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:n})}async submitFeedback(t,n){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:n})}registerFunction(t,n,r){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,n,r)}register(t){if(Array.isArray(t))for(const n of t)this.functionRegistry.register(n);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}registerNavigationFunction(t,n){const r=n.map(i=>i.name),s=n.map(i=>`- "${i.name}": ${i.description}`).join(`
5
5
  `);this.registerFunction("navigateToPage",async i=>{const o=i.page,l=n.find(c=>c.name===o);return l?(t(l.path),{success:!0,navigatedTo:l.path}):{success:!1,error:`Unknown page: ${o}`}},{description:`Navigate the user to a page in the application. Available pages:
6
- ${s}`,parameters:{type:"object",properties:{page:{type:"string",description:"The page to navigate to",enum:r}},required:["page"]}})}registerPageStateFunction(t,n){const r=n?.functionName??"setPageState",s=new Map(t.map(o=>[o.name,o])),i=t.map(o=>`- "${o.name}": ${o.description}`).join(`
6
+ ${s}`,parameters:{type:"object",properties:{page:{type:"string",description:"The page to navigate to",enum:r}},required:["page"]}}),this.addDynamicContext("current-page",()=>{if(typeof window>"u"||!window.location)return null;const i=window.location.href,o=typeof document<"u"?document.title:void 0,l=z(window.location.pathname,n),c={url:i};return l&&(c.page=l.name),o&&(c.title=o),{name:"Current page",description:"The page the user is currently viewing.",data:c}})}unregisterNavigationFunction(){this.unregisterFunction("navigateToPage"),this.removeDynamicContext("current-page")}registerPageStateFunction(t,n){const r=n?.functionName??"setPageState",s=new Map(t.map(o=>[o.name,o])),i=t.map(o=>`- "${o.name}": ${o.description}`).join(`
7
7
  `);this.registerFunction(r,async o=>{const l={};for(const[c,d]of Object.entries(o)){if(d===void 0)continue;const w=s.get(c);w&&(await w.set(d),l[c]=d)}return{success:!0,applied:l}},{description:`Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
8
- ${i}`,parameters:{type:"object",properties:Object.fromEntries(t.map(o=>[o.name,{...o.schema,description:o.description}]))}}),this.addDynamicContext(`page-state:${r}`,()=>{const o=t.filter(c=>typeof c.get=="function");if(o.length===0)return null;const l={};for(const c of o)l[c.name]=c.get();return{name:"Page state",description:"Current, editable state of the page the user is viewing.",data:l}})}unregisterPageStateFunction(t){const n=t??"setPageState";this.unregisterFunction(n),this.removeDynamicContext(`page-state:${n}`)}setContext(t,n){this.contextRegistry.set(t,n),this.notifyContextChanged()}removeContext(t){const n=this.contextRegistry.remove(t);return n&&this.notifyContextChanged(),n}addDynamicContext(t,n){this.contextRegistry.addDynamicProvider(t,n),this.notifyContextChanged()}removeDynamicContext(t){const n=this.contextRegistry.removeDynamicProvider(t);return n&&this.notifyContextChanged(),n}notifyContextChanged(){this.eventEmitter.emit("context:changed",this.contextRegistry.getSnapshot())}emitFormEvent(t,n){this.eventEmitter.emit(t,n)}enableAutoPageContext(){this.addDynamicContext("browser-page",()=>{const t=typeof window<"u"?window.location.href:void 0,n=typeof document<"u"?document.title:void 0;return!t&&!n?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:t,title:n}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}on(t,n){this.eventEmitter.on(t,n)}off(t,n){this.eventEmitter.off(t,n)}once(t,n){this.eventEmitter.once(t,n)}waitFor(t,n){return this.eventEmitter.waitFor(t,n)}updateConfig(t){const n={};for(const[s,i]of Object.entries(t))i!==void 0&&(n[s]=i);const r={...this.config,...n};y(r,"AgoClient.updateConfig"),this.config=r,this.httpClient.updateConfig(n),n.debug!==void 0&&(n.debug?a.enable():a.disable())}destroy(){this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.contextRegistry.clear(),a.log("AgoClient destroyed")}};Object.defineProperty(exports,"AgoApiError",{enumerable:!0,get:function(){return u}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return M}});Object.defineProperty(exports,"AgoError",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"AgoFunctionError",{enumerable:!0,get:function(){return g}});Object.defineProperty(exports,"AgoNetworkError",{enumerable:!0,get:function(){return m}});Object.defineProperty(exports,"AgoStreamError",{enumerable:!0,get:function(){return f}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return S}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return $}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return _}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return k}});Object.defineProperty(exports,"attachmentsFromFiles",{enumerable:!0,get:function(){return T}});Object.defineProperty(exports,"canInlineImage",{enumerable:!0,get:function(){return O}});Object.defineProperty(exports,"formatFileSize",{enumerable:!0,get:function(){return j}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return U}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return a}});Object.defineProperty(exports,"safeAttachmentUrl",{enumerable:!0,get:function(){return A}});Object.defineProperty(exports,"validateConfig",{enumerable:!0,get:function(){return y}});
8
+ ${i}`,parameters:{type:"object",properties:Object.fromEntries(t.map(o=>[o.name,{...o.schema,description:o.description}]))}}),this.addDynamicContext(`page-state:${r}`,()=>{const o=t.filter(c=>typeof c.get=="function");if(o.length===0)return null;const l={};for(const c of o)l[c.name]=c.get();return{name:"Page state",description:"Current, editable state of the page the user is viewing.",data:l}})}unregisterPageStateFunction(t){const n=t??"setPageState";this.unregisterFunction(n),this.removeDynamicContext(`page-state:${n}`)}setContext(t,n){this.contextRegistry.set(t,n),this.notifyContextChanged()}removeContext(t){const n=this.contextRegistry.remove(t);return n&&this.notifyContextChanged(),n}addDynamicContext(t,n){this.contextRegistry.addDynamicProvider(t,n),this.notifyContextChanged()}removeDynamicContext(t){const n=this.contextRegistry.removeDynamicProvider(t);return n&&this.notifyContextChanged(),n}notifyContextChanged(){this.eventEmitter.emit("context:changed",this.contextRegistry.getSnapshot())}emitFormEvent(t,n){this.eventEmitter.emit(t,n)}enableAutoPageContext(){this.addDynamicContext("browser-page",()=>{const t=typeof window<"u"?window.location.href:void 0,n=typeof document<"u"?document.title:void 0;return!t&&!n?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:t,title:n}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}on(t,n){this.eventEmitter.on(t,n)}off(t,n){this.eventEmitter.off(t,n)}once(t,n){this.eventEmitter.once(t,n)}waitFor(t,n){return this.eventEmitter.waitFor(t,n)}updateConfig(t){const n={};for(const[s,i]of Object.entries(t))i!==void 0&&(n[s]=i);const r={...this.config,...n};y(r,"AgoClient.updateConfig"),this.config=r,this.httpClient.updateConfig(n),n.debug!==void 0&&(n.debug?a.enable():a.disable())}destroy(){this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.contextRegistry.clear(),a.log("AgoClient destroyed")}};Object.defineProperty(exports,"AgoApiError",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return L}});Object.defineProperty(exports,"AgoError",{enumerable:!0,get:function(){return u}});Object.defineProperty(exports,"AgoFunctionError",{enumerable:!0,get:function(){return g}});Object.defineProperty(exports,"AgoNetworkError",{enumerable:!0,get:function(){return f}});Object.defineProperty(exports,"AgoStreamError",{enumerable:!0,get:function(){return m}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return S}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return A}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return _}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return $}});Object.defineProperty(exports,"attachmentsFromFiles",{enumerable:!0,get:function(){return T}});Object.defineProperty(exports,"canInlineImage",{enumerable:!0,get:function(){return O}});Object.defineProperty(exports,"formatFileSize",{enumerable:!0,get:function(){return j}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return U}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return a}});Object.defineProperty(exports,"safeAttachmentUrl",{enumerable:!0,get:function(){return k}});Object.defineProperty(exports,"validateConfig",{enumerable:!0,get:function(){return y}});
package/dist/angular.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-B2BU8tfB.cjs");var n=class{constructor(e){this.client=new o.AgoClient(e),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(e){const t=this.client;return{subscribe(i){const s=r=>{i.next?.(r)};return t.on(e,s),{unsubscribe:()=>t.off(e,s)}}}}sendMessage(e,t){return this.client.sendMessage(e,t)}getConversations(){return this.client.getConversations()}getConversation(e){return this.client.getConversation(e)}getMessages(e){return this.client.getMessages(e)}submitToolCallForm(e,t){return this.client.submitToolCallForm(e,t)}confirmToolCall(e){return this.client.confirmToolCall(e)}rejectToolCall(e){return this.client.rejectToolCall(e)}submitFeedback(e,t){return this.client.submitFeedback(e,t)}registerFunction(e,t,i){typeof e=="object"?this.client.registerFunction(e):this.client.registerFunction(e,t,i)}unregisterFunction(e){return this.client.unregisterFunction(e)}registerNavigationFunction(e,t){this.client.registerNavigationFunction(e,t)}registerPageStateFunction(e,t){this.client.registerPageStateFunction(e,t)}unregisterPageStateFunction(e){this.client.unregisterPageStateFunction(e)}on(e,t){this.client.on(e,t)}off(e,t){this.client.off(e,t)}updateConfig(e){this.client.updateConfig(e)}getClient(){return this.client}destroy(){this.client.destroy()}};function c(e){return{provide:n,useValue:new n(e)}}exports.AgoService=n;exports.provideAgo=c;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-CRAnT4qE.cjs");var n=class{constructor(e){this.client=new o.AgoClient(e),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(e){const t=this.client;return{subscribe(i){const s=r=>{i.next?.(r)};return t.on(e,s),{unsubscribe:()=>t.off(e,s)}}}}sendMessage(e,t){return this.client.sendMessage(e,t)}getConversations(){return this.client.getConversations()}getConversation(e){return this.client.getConversation(e)}getMessages(e){return this.client.getMessages(e)}submitToolCallForm(e,t){return this.client.submitToolCallForm(e,t)}confirmToolCall(e){return this.client.confirmToolCall(e)}rejectToolCall(e){return this.client.rejectToolCall(e)}submitFeedback(e,t){return this.client.submitFeedback(e,t)}registerFunction(e,t,i){typeof e=="object"?this.client.registerFunction(e):this.client.registerFunction(e,t,i)}unregisterFunction(e){return this.client.unregisterFunction(e)}registerNavigationFunction(e,t){this.client.registerNavigationFunction(e,t)}unregisterNavigationFunction(){this.client.unregisterNavigationFunction()}registerPageStateFunction(e,t){this.client.registerPageStateFunction(e,t)}unregisterPageStateFunction(e){this.client.unregisterPageStateFunction(e)}on(e,t){this.client.on(e,t)}off(e,t){this.client.off(e,t)}updateConfig(e){this.client.updateConfig(e)}getClient(){return this.client}destroy(){this.client.destroy()}};function c(e){return{provide:n,useValue:new n(e)}}exports.AgoService=n;exports.provideAgo=c;
@@ -146,6 +146,12 @@ declare class AgoClient {
146
146
  getRegisteredFunctions(): ClientFunctionSchema[];
147
147
  /**
148
148
  * Register a navigation function that lets AGO navigate users to different pages.
149
+ *
150
+ * Also registers a dynamic context entry (`current-page`) that reports the page
151
+ * the user is currently on, by route name, on every message. This is what lets
152
+ * the agent know *where* it is after it navigates (e.g. so auto-continuation
153
+ * can apply page state on the destination), not just how to navigate away.
154
+ *
149
155
  * @param navigate - A callback that performs the navigation (e.g. react-router's navigate)
150
156
  * @param routes - Map of route names to paths, with descriptions for the LLM
151
157
  */
@@ -154,6 +160,10 @@ declare class AgoClient {
154
160
  path: string;
155
161
  description: string;
156
162
  }>): void;
163
+ /**
164
+ * Unregister the navigation function and its `current-page` context provider.
165
+ */
166
+ unregisterNavigationFunction(): void;
157
167
  /**
158
168
  * Register a "page state" function that lets AGO change the current page's
159
169
  * state (filters, sort, view mode, selection…) and reads the current state
@@ -511,6 +521,8 @@ export declare class AgoService {
511
521
  path: string;
512
522
  description: string;
513
523
  }>): void;
524
+ /** Unregister navigation (function + current-page context) */
525
+ unregisterNavigationFunction(): void;
514
526
  /** Register editable page-state controls (filters, sort, view mode…) */
515
527
  registerPageStateFunction(controls: AgoStateControl[], opts?: AgoPageStateOptions): void;
516
528
  /** Unregister a page-state function and its dynamic context */
package/dist/angular.d.ts CHANGED
@@ -146,6 +146,12 @@ declare class AgoClient {
146
146
  getRegisteredFunctions(): ClientFunctionSchema[];
147
147
  /**
148
148
  * Register a navigation function that lets AGO navigate users to different pages.
149
+ *
150
+ * Also registers a dynamic context entry (`current-page`) that reports the page
151
+ * the user is currently on, by route name, on every message. This is what lets
152
+ * the agent know *where* it is after it navigates (e.g. so auto-continuation
153
+ * can apply page state on the destination), not just how to navigate away.
154
+ *
149
155
  * @param navigate - A callback that performs the navigation (e.g. react-router's navigate)
150
156
  * @param routes - Map of route names to paths, with descriptions for the LLM
151
157
  */
@@ -154,6 +160,10 @@ declare class AgoClient {
154
160
  path: string;
155
161
  description: string;
156
162
  }>): void;
163
+ /**
164
+ * Unregister the navigation function and its `current-page` context provider.
165
+ */
166
+ unregisterNavigationFunction(): void;
157
167
  /**
158
168
  * Register a "page state" function that lets AGO change the current page's
159
169
  * state (filters, sort, view mode, selection…) and reads the current state
@@ -511,6 +521,8 @@ export declare class AgoService {
511
521
  path: string;
512
522
  description: string;
513
523
  }>): void;
524
+ /** Unregister navigation (function + current-page context) */
525
+ unregisterNavigationFunction(): void;
514
526
  /** Register editable page-state controls (filters, sort, view mode…) */
515
527
  registerPageStateFunction(controls: AgoStateControl[], opts?: AgoPageStateOptions): void;
516
528
  /** Unregister a page-state function and its dynamic context */
package/dist/angular.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as o } from "./AgoClient-BrhKkDWt.js";
1
+ import { t as o } from "./AgoClient-BdtuHX7k.js";
2
2
  var s = class {
3
3
  constructor(t) {
4
4
  this.client = new o(t), this.messages$ = this.fromEvent("message:complete"), this.chunks$ = this.fromEvent("message:chunk"), this.errors$ = this.fromEvent("message:error"), this.messageStart$ = this.fromEvent("message:start");
@@ -45,6 +45,9 @@ var s = class {
45
45
  registerNavigationFunction(t, e) {
46
46
  this.client.registerNavigationFunction(t, e);
47
47
  }
48
+ unregisterNavigationFunction() {
49
+ this.client.unregisterNavigationFunction();
50
+ }
48
51
  registerPageStateFunction(t, e) {
49
52
  this.client.registerPageStateFunction(t, e);
50
53
  }
@@ -1 +1 @@
1
- const d=require("./createFormCollector-CpYX_5PT.cjs");var f="ago_widget_id",g="ago_last_thread",y=7200*1e3;function v(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.floor(Math.random()*16);return(e==="x"?r:r&3|8).toString(16)})}function _(e={}){const r=e.key??f,i=e.threadKey??g,u=e.ttlMs??y,l=e.storage??(typeof localStorage<"u"?localStorage:void 0);let n=e.widgetId??"";if(!n&&l)try{n=l.getItem(r)??""}catch{}if(n||(n=v()),l)try{l.setItem(r,n)}catch{}const o=d.createStore({value:null,lastMessageAt:null},{key:i,storage:l}),c=o.get();c.value!==null&&s(c.lastMessageAt)&&o.set({value:null,lastMessageAt:null});function s(t){return t===null?!0:Number.isFinite(u)?Date.now()-t>u:!1}return{widgetId:n,key:r,getLastActiveThread(){const{value:t,lastMessageAt:a}=o.get();return t===null||s(a)?null:t},setActiveThread(t,a){const x=a==null?null:a instanceof Date?a.getTime():a;o.set({value:t,lastMessageAt:x})},clear(){o.set({value:null,lastMessageAt:null})}}}Object.defineProperty(exports,"createConversationSession",{enumerable:!0,get:function(){return _}});
1
+ const d=require("./createFormCollector-BB_l0Sia.cjs");var f="ago_widget_id",g="ago_last_thread",y=7200*1e3;function v(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.floor(Math.random()*16);return(e==="x"?r:r&3|8).toString(16)})}function _(e={}){const r=e.key??f,i=e.threadKey??g,u=e.ttlMs??y,l=e.storage??(typeof localStorage<"u"?localStorage:void 0);let n=e.widgetId??"";if(!n&&l)try{n=l.getItem(r)??""}catch{}if(n||(n=v()),l)try{l.setItem(r,n)}catch{}const o=d.createStore({value:null,lastMessageAt:null},{key:i,storage:l}),c=o.get();c.value!==null&&s(c.lastMessageAt)&&o.set({value:null,lastMessageAt:null});function s(t){return t===null?!0:Number.isFinite(u)?Date.now()-t>u:!1}return{widgetId:n,key:r,getLastActiveThread(){const{value:t,lastMessageAt:a}=o.get();return t===null||s(a)?null:t},setActiveThread(t,a){const x=a==null?null:a instanceof Date?a.getTime():a;o.set({value:t,lastMessageAt:x})},clear(){o.set({value:null,lastMessageAt:null})}}}Object.defineProperty(exports,"createConversationSession",{enumerable:!0,get:function(){return _}});
@@ -1,4 +1,4 @@
1
- import { i as d } from "./createFormCollector-BYKe5Uxm.js";
1
+ import { i as d } from "./createFormCollector-B4n0_diV.js";
2
2
  var f = "ago_widget_id", g = "ago_last_thread", y = 7200 * 1e3;
3
3
  function v() {
4
4
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
@@ -1,4 +1,4 @@
1
- import { f as $ } from "./AgoClient-BrhKkDWt.js";
1
+ import { f as $ } from "./AgoClient-BdtuHX7k.js";
2
2
  function A(s, e) {
3
3
  const a = e ? e.storage ?? (typeof localStorage < "u" ? localStorage : void 0) : void 0;
4
4
  let n = s;
@@ -1 +1 @@
1
- const C=require("./AgoClient-B2BU8tfB.cjs");function W(n,e){const a=e?e.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let s=n;if(e&&a)try{const m=a.getItem(e.key);m!=null&&(s=JSON.parse(m))}catch{}const i=new Set,c=()=>i.forEach(m=>m(s));function b(){if(e&&a)try{a.setItem(e.key,JSON.stringify(s))}catch{}}return{get:()=>s,set:m=>{s=m,b(),c()},subscribe:m=>(i.add(m),()=>{i.delete(m)})}}var T=/^[a-zA-Z0-9_-]{1,40}$/,x=n=>n==null||n==="";function v(n,e){if("anyOf"in n)return n.anyOf.some(c=>v(c,e));if("allOf"in n)return n.allOf.every(c=>v(c,e));const a=e[n.property];if(x(a))return!1;if(Array.isArray(n.value))return n.value.some(c=>String(a)===String(c));if(!n.op)return String(a)===String(n.value);const s=Number(a),i=Number(n.value);if(Number.isNaN(s)||Number.isNaN(i))return!1;switch(n.op){case">=":return s>=i;case"<=":return s<=i;case">":return s>i;case"<":return s<i;default:return C.logger.warn(`Unknown requiredWhen op "${n.op}"; treating as not required.`),!1}}function h(n,e){const a=n.properties??{},s=new Set;for(const c of n.required??[]){const b=a[c]?.requiredWhen;(!b||v(b,e))&&s.add(c)}for(const[c,b]of Object.entries(a))b.requiredWhen&&v(b.requiredWhen,e)&&s.add(c);const i=[...s].filter(c=>x(e[c]));return{missing:i,complete:i.length===0}}function R(n){const e={};for(const[a,s]of Object.entries(n.properties??{}))e[a]={type:s.type,...s.description!=null&&{description:s.description},...s.enum&&{enum:s.enum},...s.default!==void 0&&{default:s.default}};return{type:"object",properties:e,required:[]}}function A(n){const{name:e,description:a,schema:s}=n;if(!T.test(e))throw new Error(`Invalid form collector name "${e}": must match ${T} (it becomes the update_/submit_ function names).`);const i=typeof n.submit=="string"?n.submit?{via:"client",url:n.submit}:!1:n.submit??!1;n.autoSubmit===!0&&!i&&C.logger.warn(`FormCollector "${e}": autoSubmit is ignored because no submit target is configured.`);const c=(n.autoSubmit??!0)&&!!i,b=s.properties??{},m=t=>{const r={};for(const[u,o]of Object.entries(t)){const l=b[u];if(l)if(o==null)r[u]=o;else if(l.type==="number"||l.type==="integer"){const d=typeof o=="number"?o:Number(o);r[u]=Number.isNaN(d)?o:d}else l.type==="boolean"?r[u]=typeof o=="boolean"?o:o==="true"?!0:o==="false"?!1:!!o:r[u]=o}return r},S=n.initialValues??{},f=W({values:S,submitted:!1}),$=t=>{const r=f.get(),u={...r,values:{...r.values,...t}};return f.set(u),u};let g=null;const F=(t,r)=>{g?.emitFormEvent("form:error",{name:e,values:t,error:r})};let y=null;const I=async()=>{const{values:t}=f.get(),{complete:r,missing:u}=h(s,t);if(!r)return{ok:!1,missing:u};if(!i)return{ok:!1,error:"No submit target configured for this form collector."};const o=t;try{let l;if(i.via==="client")if("handler"in i)l=await i.handler(o);else{const d=await fetch(i.url,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(o)});if(!d.ok){const j=`Submit failed: HTTP ${d.status}`;return F(o,j),{ok:!1,error:j}}l=await d.json().catch(()=>{})}else{if(!g)return{ok:!1,error:"Backend submit requires install(client) (or useFormCollector) first."};l=await g.submitFormCollector(e,o)}return f.set({...f.get(),submitted:!0,submitResult:l}),g?.emitFormEvent("form:submitted",{name:e,values:o,result:l}),{ok:!0,result:l}}catch(l){const d=l instanceof Error?l.message:"Submit failed";return C.logger.error(`FormCollector "${e}" submit failed:`,l),F(o,d),{ok:!1,error:d}}},N=()=>y||(y=(async()=>{try{return await I()}finally{y=null}})(),y),k=async()=>{if(!c||!i)return null;const{values:t,submitted:r}=f.get();return r||!h(s,t).complete?null:N()},O={name:`update_${e}`,description:`Fill or update fields of the "${e}" form. ${a} Pass any subset of fields; call it repeatedly to fill the form as the user provides information. Returns the current values and which required fields are still missing.`,parameters:R(s),handler:async t=>{const r=$(m(t)),{missing:u}=h(s,r.values),o=await k();return o?o.ok?{ok:!0,values:r.values,missing:u,submitted:!0}:{ok:!0,values:r.values,missing:u,submitted:!1,submitError:o.error}:{ok:!0,values:r.values,missing:u}}},p=[O];i&&!c&&p.push({name:`submit_${e}`,description:`Submit the completed "${e}" form. Only call this once every required field is collected and the user has confirmed. If fields are missing it returns them instead of submitting.`,parameters:{type:"object",properties:{}},handler:()=>N()});const V="client__",q=i?`submit_${e}`:null,J=t=>{const r=t.functionName??t.toolName;if(r)return r.startsWith(V)?r.slice(8):r},_=t=>{let r={...S},u=!1;for(const o of t){const l=J(o);l===O.name?o.arguments&&(r={...r,...m(o.arguments)}):q&&l===q&&o.status?.toLowerCase()==="done"&&(u=!0)}f.set({values:r,submitted:u})},w=`form:${e}`,E=()=>{const{values:t,submitted:r}=f.get(),{missing:u,complete:o}=h(s,t),l=i?c?" The form is submitted automatically as soon as every required field is filled, so there is no submit function to call.":` When nothing is missing and the user confirms, call submit_${e}.`:"",d=r?`The "${e}" form has been submitted.`:`You are currently collecting information from the user to fill the "${e}" form.`;return{name:`Form: ${e}`,description:`${d} ${a} Some fields are conditionally required; the requiredWhen field in the schema tells you when each becomes required. The form schema is the following: ${JSON.stringify(s)}. Data collected so far: ${JSON.stringify(t)}. Call update_${e} with any fields the user provides; ask only for what is still missing.${l}`,data:{values:t,missing:u,complete:o,submitted:r}}},P=t=>{_((t.messages??[]).flatMap(r=>r.toolCalls??[]))};return{name:e,store:f,functions:p,contextKey:w,contextProvider:E,install:t=>{g=t;for(const u of p)t.register(u);t.addDynamicContext(w,E);const r=f.subscribe(()=>t.notifyContextChanged());return t.on("conversation:loaded",P),()=>{r();for(const u of p)t.unregisterFunction(u.name);t.removeDynamicContext(w),t.off("conversation:loaded",P),g===t&&(g=null)}},hydrate:_,submit:N,getValues:()=>f.get().values,setValues:t=>{$(m(t)),k()},reset:()=>{f.set({values:S,submitted:!1})},getStatus:()=>h(s,f.get().values)}}async function B(n,e){const a=await n.getFormCollector(e.name);return A({name:a.name,description:e.description??a.description,schema:e.schema??a.schema,submit:e.submit??a.submit,initialValues:e.initialValues,autoSubmit:e.autoSubmit??a.autoSubmit})}Object.defineProperty(exports,"createFormCollector",{enumerable:!0,get:function(){return A}});Object.defineProperty(exports,"createStore",{enumerable:!0,get:function(){return W}});Object.defineProperty(exports,"deriveFormStatus",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"loadFormCollector",{enumerable:!0,get:function(){return B}});
1
+ const C=require("./AgoClient-CRAnT4qE.cjs");function W(n,e){const a=e?e.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let s=n;if(e&&a)try{const m=a.getItem(e.key);m!=null&&(s=JSON.parse(m))}catch{}const i=new Set,c=()=>i.forEach(m=>m(s));function b(){if(e&&a)try{a.setItem(e.key,JSON.stringify(s))}catch{}}return{get:()=>s,set:m=>{s=m,b(),c()},subscribe:m=>(i.add(m),()=>{i.delete(m)})}}var T=/^[a-zA-Z0-9_-]{1,40}$/,x=n=>n==null||n==="";function v(n,e){if("anyOf"in n)return n.anyOf.some(c=>v(c,e));if("allOf"in n)return n.allOf.every(c=>v(c,e));const a=e[n.property];if(x(a))return!1;if(Array.isArray(n.value))return n.value.some(c=>String(a)===String(c));if(!n.op)return String(a)===String(n.value);const s=Number(a),i=Number(n.value);if(Number.isNaN(s)||Number.isNaN(i))return!1;switch(n.op){case">=":return s>=i;case"<=":return s<=i;case">":return s>i;case"<":return s<i;default:return C.logger.warn(`Unknown requiredWhen op "${n.op}"; treating as not required.`),!1}}function h(n,e){const a=n.properties??{},s=new Set;for(const c of n.required??[]){const b=a[c]?.requiredWhen;(!b||v(b,e))&&s.add(c)}for(const[c,b]of Object.entries(a))b.requiredWhen&&v(b.requiredWhen,e)&&s.add(c);const i=[...s].filter(c=>x(e[c]));return{missing:i,complete:i.length===0}}function R(n){const e={};for(const[a,s]of Object.entries(n.properties??{}))e[a]={type:s.type,...s.description!=null&&{description:s.description},...s.enum&&{enum:s.enum},...s.default!==void 0&&{default:s.default}};return{type:"object",properties:e,required:[]}}function A(n){const{name:e,description:a,schema:s}=n;if(!T.test(e))throw new Error(`Invalid form collector name "${e}": must match ${T} (it becomes the update_/submit_ function names).`);const i=typeof n.submit=="string"?n.submit?{via:"client",url:n.submit}:!1:n.submit??!1;n.autoSubmit===!0&&!i&&C.logger.warn(`FormCollector "${e}": autoSubmit is ignored because no submit target is configured.`);const c=(n.autoSubmit??!0)&&!!i,b=s.properties??{},m=t=>{const r={};for(const[u,o]of Object.entries(t)){const l=b[u];if(l)if(o==null)r[u]=o;else if(l.type==="number"||l.type==="integer"){const d=typeof o=="number"?o:Number(o);r[u]=Number.isNaN(d)?o:d}else l.type==="boolean"?r[u]=typeof o=="boolean"?o:o==="true"?!0:o==="false"?!1:!!o:r[u]=o}return r},S=n.initialValues??{},f=W({values:S,submitted:!1}),$=t=>{const r=f.get(),u={...r,values:{...r.values,...t}};return f.set(u),u};let g=null;const F=(t,r)=>{g?.emitFormEvent("form:error",{name:e,values:t,error:r})};let y=null;const I=async()=>{const{values:t}=f.get(),{complete:r,missing:u}=h(s,t);if(!r)return{ok:!1,missing:u};if(!i)return{ok:!1,error:"No submit target configured for this form collector."};const o=t;try{let l;if(i.via==="client")if("handler"in i)l=await i.handler(o);else{const d=await fetch(i.url,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(o)});if(!d.ok){const j=`Submit failed: HTTP ${d.status}`;return F(o,j),{ok:!1,error:j}}l=await d.json().catch(()=>{})}else{if(!g)return{ok:!1,error:"Backend submit requires install(client) (or useFormCollector) first."};l=await g.submitFormCollector(e,o)}return f.set({...f.get(),submitted:!0,submitResult:l}),g?.emitFormEvent("form:submitted",{name:e,values:o,result:l}),{ok:!0,result:l}}catch(l){const d=l instanceof Error?l.message:"Submit failed";return C.logger.error(`FormCollector "${e}" submit failed:`,l),F(o,d),{ok:!1,error:d}}},N=()=>y||(y=(async()=>{try{return await I()}finally{y=null}})(),y),k=async()=>{if(!c||!i)return null;const{values:t,submitted:r}=f.get();return r||!h(s,t).complete?null:N()},O={name:`update_${e}`,description:`Fill or update fields of the "${e}" form. ${a} Pass any subset of fields; call it repeatedly to fill the form as the user provides information. Returns the current values and which required fields are still missing.`,parameters:R(s),handler:async t=>{const r=$(m(t)),{missing:u}=h(s,r.values),o=await k();return o?o.ok?{ok:!0,values:r.values,missing:u,submitted:!0}:{ok:!0,values:r.values,missing:u,submitted:!1,submitError:o.error}:{ok:!0,values:r.values,missing:u}}},p=[O];i&&!c&&p.push({name:`submit_${e}`,description:`Submit the completed "${e}" form. Only call this once every required field is collected and the user has confirmed. If fields are missing it returns them instead of submitting.`,parameters:{type:"object",properties:{}},handler:()=>N()});const V="client__",q=i?`submit_${e}`:null,J=t=>{const r=t.functionName??t.toolName;if(r)return r.startsWith(V)?r.slice(8):r},_=t=>{let r={...S},u=!1;for(const o of t){const l=J(o);l===O.name?o.arguments&&(r={...r,...m(o.arguments)}):q&&l===q&&o.status?.toLowerCase()==="done"&&(u=!0)}f.set({values:r,submitted:u})},w=`form:${e}`,E=()=>{const{values:t,submitted:r}=f.get(),{missing:u,complete:o}=h(s,t),l=i?c?" The form is submitted automatically as soon as every required field is filled, so there is no submit function to call.":` When nothing is missing and the user confirms, call submit_${e}.`:"",d=r?`The "${e}" form has been submitted.`:`You are currently collecting information from the user to fill the "${e}" form.`;return{name:`Form: ${e}`,description:`${d} ${a} Some fields are conditionally required; the requiredWhen field in the schema tells you when each becomes required. The form schema is the following: ${JSON.stringify(s)}. Data collected so far: ${JSON.stringify(t)}. Call update_${e} with any fields the user provides; ask only for what is still missing.${l}`,data:{values:t,missing:u,complete:o,submitted:r}}},P=t=>{_((t.messages??[]).flatMap(r=>r.toolCalls??[]))};return{name:e,store:f,functions:p,contextKey:w,contextProvider:E,install:t=>{g=t;for(const u of p)t.register(u);t.addDynamicContext(w,E);const r=f.subscribe(()=>t.notifyContextChanged());return t.on("conversation:loaded",P),()=>{r();for(const u of p)t.unregisterFunction(u.name);t.removeDynamicContext(w),t.off("conversation:loaded",P),g===t&&(g=null)}},hydrate:_,submit:N,getValues:()=>f.get().values,setValues:t=>{$(m(t)),k()},reset:()=>{f.set({values:S,submitted:!1})},getStatus:()=>h(s,f.get().values)}}async function B(n,e){const a=await n.getFormCollector(e.name);return A({name:a.name,description:e.description??a.description,schema:e.schema??a.schema,submit:e.submit??a.submit,initialValues:e.initialValues,autoSubmit:e.autoSubmit??a.autoSubmit})}Object.defineProperty(exports,"createFormCollector",{enumerable:!0,get:function(){return A}});Object.defineProperty(exports,"createStore",{enumerable:!0,get:function(){return W}});Object.defineProperty(exports,"deriveFormStatus",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"loadFormCollector",{enumerable:!0,get:function(){return B}});
@@ -1,5 +1,5 @@
1
1
  function C(g = {}) {
2
- const { overrides: m = {} } = g, d = {
2
+ const { overrides: u = {} } = g, d = {
3
3
  id: "mock-msg-1",
4
4
  conversationId: "mock-conv-1",
5
5
  content: "Mock response",
@@ -10,7 +10,7 @@ function C(g = {}) {
10
10
  id: "mock-conv-1",
11
11
  title: "Mock Conversation",
12
12
  lastMessageDate: /* @__PURE__ */ new Date()
13
- }, t = /* @__PURE__ */ new Map(), i = [], u = {
13
+ }, t = /* @__PURE__ */ new Map(), a = [], m = {
14
14
  sendMessage: async () => d,
15
15
  getConversations: async () => [l],
16
16
  getConversation: async () => l,
@@ -32,6 +32,8 @@ function C(g = {}) {
32
32
  },
33
33
  registerNavigationFunction: () => {
34
34
  },
35
+ unregisterNavigationFunction: () => {
36
+ },
35
37
  on: (e, o) => {
36
38
  t.has(e) || t.set(e, /* @__PURE__ */ new Set()), t.get(e).add(o);
37
39
  },
@@ -39,18 +41,18 @@ function C(g = {}) {
39
41
  t.get(e)?.delete(o);
40
42
  },
41
43
  once: (e, o) => {
42
- const s = (...a) => {
43
- t.get(e)?.delete(s), o(...a);
44
+ const n = (...i) => {
45
+ t.get(e)?.delete(n), o(...i);
44
46
  };
45
- t.has(e) || t.set(e, /* @__PURE__ */ new Set()), t.get(e).add(s);
47
+ t.has(e) || t.set(e, /* @__PURE__ */ new Set()), t.get(e).add(n);
46
48
  },
47
- waitFor: (e, o) => new Promise((s, a) => {
49
+ waitFor: (e, o) => new Promise((n, i) => {
48
50
  let r;
49
51
  const c = (f) => {
50
- r && clearTimeout(r), t.get(e)?.delete(c), s(f);
52
+ r && clearTimeout(r), t.get(e)?.delete(c), n(f);
51
53
  };
52
54
  t.has(e) || t.set(e, /* @__PURE__ */ new Set()), t.get(e).add(c), o?.timeout && (r = setTimeout(() => {
53
- t.get(e)?.delete(c), a(/* @__PURE__ */ new Error(`waitFor("${e}") timed out after ${o.timeout}ms`));
55
+ t.get(e)?.delete(c), i(/* @__PURE__ */ new Error(`waitFor("${e}") timed out after ${o.timeout}ms`));
54
56
  }, o.timeout));
55
57
  }),
56
58
  updateConfig: () => {
@@ -58,16 +60,16 @@ function C(g = {}) {
58
60
  destroy: () => {
59
61
  t.clear();
60
62
  },
61
- ...m
62
- }, n = {};
63
- for (const [e, o] of Object.entries(u)) n[e] = (...s) => (i.push({
63
+ ...u
64
+ }, s = {};
65
+ for (const [e, o] of Object.entries(m)) s[e] = (...n) => (a.push({
64
66
  method: e,
65
- args: s
66
- }), o(...s));
67
- return n.__calls = i, n.__callsFor = (e) => i.filter((o) => o.method === e), n.__emitEvent = (e, o) => {
68
- const s = t.get(e);
69
- s && [...s].forEach((a) => a(o));
70
- }, n;
67
+ args: n
68
+ }), o(...n));
69
+ return s.__calls = a, s.__callsFor = (e) => a.filter((o) => o.method === e), s.__emitEvent = (e, o) => {
70
+ const n = t.get(e);
71
+ n && [...n].forEach((i) => i(o));
72
+ }, s;
71
73
  }
72
74
  export {
73
75
  C as t
@@ -0,0 +1 @@
1
+ function C(g={}){const{overrides:u={}}=g,d={id:"mock-msg-1",conversationId:"mock-conv-1",content:"Mock response",role:"assistant",status:"DONE",createdAt:new Date},l={id:"mock-conv-1",title:"Mock Conversation",lastMessageDate:new Date},t=new Map,r=[],m={sendMessage:async()=>d,getConversations:async()=>[l],getConversation:async()=>l,getMessages:async()=>[d],submitToolCallForm:async()=>{},confirmToolCall:async()=>{},rejectToolCall:async()=>{},submitFeedback:async()=>{},registerFunction:()=>{},unregisterFunction:()=>!0,getRegisteredFunctions:()=>[],getContextSnapshot:()=>null,notifyContextChanged:()=>{},registerNavigationFunction:()=>{},unregisterNavigationFunction:()=>{},on:(e,o)=>{t.has(e)||t.set(e,new Set),t.get(e).add(o)},off:(e,o)=>{t.get(e)?.delete(o)},once:(e,o)=>{const n=(...i)=>{t.get(e)?.delete(n),o(...i)};t.has(e)||t.set(e,new Set),t.get(e).add(n)},waitFor:(e,o)=>new Promise((n,i)=>{let a;const c=f=>{a&&clearTimeout(a),t.get(e)?.delete(c),n(f)};t.has(e)||t.set(e,new Set),t.get(e).add(c),o?.timeout&&(a=setTimeout(()=>{t.get(e)?.delete(c),i(new Error(`waitFor("${e}") timed out after ${o.timeout}ms`))},o.timeout))}),updateConfig:()=>{},destroy:()=>{t.clear()},...u},s={};for(const[e,o]of Object.entries(m))s[e]=(...n)=>(r.push({method:e,args:n}),o(...n));return s.__calls=r,s.__callsFor=e=>r.filter(o=>o.method===e),s.__emitEvent=(e,o)=>{const n=t.get(e);n&&[...n].forEach(i=>i(o))},s}Object.defineProperty(exports,"createMockClient",{enumerable:!0,get:function(){return C}});
@@ -146,6 +146,12 @@ declare class AgoClient {
146
146
  getRegisteredFunctions(): ClientFunctionSchema[];
147
147
  /**
148
148
  * Register a navigation function that lets AGO navigate users to different pages.
149
+ *
150
+ * Also registers a dynamic context entry (`current-page`) that reports the page
151
+ * the user is currently on, by route name, on every message. This is what lets
152
+ * the agent know *where* it is after it navigates (e.g. so auto-continuation
153
+ * can apply page state on the destination), not just how to navigate away.
154
+ *
149
155
  * @param navigate - A callback that performs the navigation (e.g. react-router's navigate)
150
156
  * @param routes - Map of route names to paths, with descriptions for the LLM
151
157
  */
@@ -154,6 +160,10 @@ declare class AgoClient {
154
160
  path: string;
155
161
  description: string;
156
162
  }>): void;
163
+ /**
164
+ * Unregister the navigation function and its `current-page` context provider.
165
+ */
166
+ unregisterNavigationFunction(): void;
157
167
  /**
158
168
  * Register a "page state" function that lets AGO change the current page's
159
169
  * state (filters, sort, view mode, selection…) and reads the current state
@@ -146,6 +146,12 @@ declare class AgoClient {
146
146
  getRegisteredFunctions(): ClientFunctionSchema[];
147
147
  /**
148
148
  * Register a navigation function that lets AGO navigate users to different pages.
149
+ *
150
+ * Also registers a dynamic context entry (`current-page`) that reports the page
151
+ * the user is currently on, by route name, on every message. This is what lets
152
+ * the agent know *where* it is after it navigates (e.g. so auto-continuation
153
+ * can apply page state on the destination), not just how to navigate away.
154
+ *
149
155
  * @param navigate - A callback that performs the navigation (e.g. react-router's navigate)
150
156
  * @param routes - Map of route names to paths, with descriptions for the LLM
151
157
  */
@@ -154,6 +160,10 @@ declare class AgoClient {
154
160
  path: string;
155
161
  description: string;
156
162
  }>): void;
163
+ /**
164
+ * Unregister the navigation function and its `current-page` context provider.
165
+ */
166
+ unregisterNavigationFunction(): void;
157
167
  /**
158
168
  * Register a "page state" function that lets AGO change the current page's
159
169
  * state (filters, sort, view mode, selection…) and reads the current state
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./AgoClient-B2BU8tfB.cjs"),f=require("./createFormCollector-CpYX_5PT.cjs"),h=require("./createConversationSession-Cin8dVNq.cjs"),p=require("./createMockClient-zHQ0cjUH.cjs");require("./testing.cjs");const g=require("./functions-Djnq-JAo.cjs");function w(e){return e}function S(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function E(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function y(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function F(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function b(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function v(e,o){return e.on("form:submitted",o),()=>e.off("form:submitted",o)}function M(e,o){return e.on("form:error",o),()=>e.off("form:error",o)}function q(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*k(e,o,l){const a=[];let n=null,i=!1;const m=s=>{a.push(s),n?.()},c=s=>m({type:"start",data:s}),t=s=>m({type:"chunk",data:s}),u=s=>{m({type:"complete",data:s}),i=!0,n?.()},d=s=>{m({type:"error",data:s}),i=!0,n?.()},C=s=>m({type:"toolCall",data:s});e.on("message:start",c),e.on("message:chunk",t),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",C),e.sendMessage(o,l).catch(()=>{i=!0,n?.()});try{for(;!i||a.length>0;)a.length>0?yield a.shift():(await new Promise(s=>{n=s}),n=null)}finally{e.off("message:start",c),e.off("message:chunk",t),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",C)}}function A(e){let o,l,a,n,i,m;if(typeof window<"u"&&window.AGO){const t=window.AGO;o=t.basepath,l=t.widgetId,a=t.agent||t.defaultAgent,n=t.permission,i=t.email,m=t.jwt}if(typeof document<"u"){const t=u=>document.querySelector(`meta[name="${u}"]`)?.getAttribute("content")||void 0;o=o||t("ago-base-url"),l=l||t("ago-widget-id"),a=a||t("ago-agent")||t("ago-agent-id"),n=n||t("ago-permission"),i=i||t("ago-user-email")}if(typeof document<"u"){const t=[document.body,...Array.from(document.querySelectorAll("script[data-ago-base-url]"))].filter(Boolean);for(const u of t)u&&(o=o||u.getAttribute("data-ago-base-url")||void 0,l=l||u.getAttribute("data-ago-widget-id")||void 0,a=a||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,n=n||u.getAttribute("data-ago-permission")||void 0,i=i||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,a=e?.agent||e?.defaultAgentId||a,n=e?.permission||n,i=e?.userEmail||i,m=e?.userJwt||m;const c=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:n,userEmail:i,userJwt:m,debug:c}:null}function T(e){const o=A(e);if(!o)throw new r.AgoError('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.',"config_missing_base_url");return new r.AgoClient(o)}function I(e,o){return{...e,handler:o}}exports.AgoApiError=r.AgoApiError;exports.AgoClient=r.AgoClient;exports.AgoError=r.AgoError;exports.AgoFunctionError=r.AgoFunctionError;exports.AgoNetworkError=r.AgoNetworkError;exports.AgoStreamError=r.AgoStreamError;exports.ClientContextRegistry=r.ClientContextRegistry;exports.EventEmitter=r.EventEmitter;exports.FunctionRegistry=r.FunctionRegistry;exports.SSEHandler=r.SSEHandler;exports.autoDetectConfig=A;exports.canInlineImage=r.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=T;exports.createConversationSession=h.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=k;exports.createMockClient=p.createMockClient;exports.createStore=f.createStore;exports.defineFunction=w;exports.deriveFormStatus=f.deriveFormStatus;exports.formatFileSize=r.formatFileSize;exports.getLocalStorage=g.getLocalStorage;exports.getUserLocation=g.getUserLocation;exports.highlightElement=g.highlightElement;exports.isStreamNetworkError=r.isStreamNetworkError;exports.loadFormCollector=f.loadFormCollector;exports.logger=r.logger;exports.onFormError=M;exports.onFormSubmitted=v;exports.onFunctionInvoke=q;exports.onMessage=S;exports.onMessageChunk=E;exports.onMessageError=F;exports.onMessageStart=y;exports.onToolCall=b;exports.openUrl=g.openUrl;exports.safeAttachmentUrl=r.safeAttachmentUrl;exports.scrollToElement=g.scrollToElement;exports.setLocalStorage=g.setLocalStorage;exports.setTheme=g.setTheme;exports.showConfirmDialog=g.showConfirmDialog;exports.showNotification=g.showNotification;exports.showToast=g.showToast;exports.submitForm=g.submitForm;exports.trackEvent=g.trackEvent;exports.validateConfig=r.validateConfig;exports.withHandler=I;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./AgoClient-CRAnT4qE.cjs"),f=require("./createFormCollector-BB_l0Sia.cjs"),h=require("./createConversationSession-B8zfTL78.cjs"),p=require("./createMockClient-ucPENDzz.cjs");require("./testing.cjs");const g=require("./functions-Djnq-JAo.cjs");function w(e){return e}function S(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function E(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function y(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function F(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function b(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function v(e,o){return e.on("form:submitted",o),()=>e.off("form:submitted",o)}function M(e,o){return e.on("form:error",o),()=>e.off("form:error",o)}function q(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*k(e,o,l){const a=[];let n=null,i=!1;const m=s=>{a.push(s),n?.()},c=s=>m({type:"start",data:s}),t=s=>m({type:"chunk",data:s}),u=s=>{m({type:"complete",data:s}),i=!0,n?.()},d=s=>{m({type:"error",data:s}),i=!0,n?.()},C=s=>m({type:"toolCall",data:s});e.on("message:start",c),e.on("message:chunk",t),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",C),e.sendMessage(o,l).catch(()=>{i=!0,n?.()});try{for(;!i||a.length>0;)a.length>0?yield a.shift():(await new Promise(s=>{n=s}),n=null)}finally{e.off("message:start",c),e.off("message:chunk",t),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",C)}}function A(e){let o,l,a,n,i,m;if(typeof window<"u"&&window.AGO){const t=window.AGO;o=t.basepath,l=t.widgetId,a=t.agent||t.defaultAgent,n=t.permission,i=t.email,m=t.jwt}if(typeof document<"u"){const t=u=>document.querySelector(`meta[name="${u}"]`)?.getAttribute("content")||void 0;o=o||t("ago-base-url"),l=l||t("ago-widget-id"),a=a||t("ago-agent")||t("ago-agent-id"),n=n||t("ago-permission"),i=i||t("ago-user-email")}if(typeof document<"u"){const t=[document.body,...Array.from(document.querySelectorAll("script[data-ago-base-url]"))].filter(Boolean);for(const u of t)u&&(o=o||u.getAttribute("data-ago-base-url")||void 0,l=l||u.getAttribute("data-ago-widget-id")||void 0,a=a||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,n=n||u.getAttribute("data-ago-permission")||void 0,i=i||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,a=e?.agent||e?.defaultAgentId||a,n=e?.permission||n,i=e?.userEmail||i,m=e?.userJwt||m;const c=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:n,userEmail:i,userJwt:m,debug:c}:null}function T(e){const o=A(e);if(!o)throw new r.AgoError('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.',"config_missing_base_url");return new r.AgoClient(o)}function I(e,o){return{...e,handler:o}}exports.AgoApiError=r.AgoApiError;exports.AgoClient=r.AgoClient;exports.AgoError=r.AgoError;exports.AgoFunctionError=r.AgoFunctionError;exports.AgoNetworkError=r.AgoNetworkError;exports.AgoStreamError=r.AgoStreamError;exports.ClientContextRegistry=r.ClientContextRegistry;exports.EventEmitter=r.EventEmitter;exports.FunctionRegistry=r.FunctionRegistry;exports.SSEHandler=r.SSEHandler;exports.autoDetectConfig=A;exports.canInlineImage=r.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=T;exports.createConversationSession=h.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=k;exports.createMockClient=p.createMockClient;exports.createStore=f.createStore;exports.defineFunction=w;exports.deriveFormStatus=f.deriveFormStatus;exports.formatFileSize=r.formatFileSize;exports.getLocalStorage=g.getLocalStorage;exports.getUserLocation=g.getUserLocation;exports.highlightElement=g.highlightElement;exports.isStreamNetworkError=r.isStreamNetworkError;exports.loadFormCollector=f.loadFormCollector;exports.logger=r.logger;exports.onFormError=M;exports.onFormSubmitted=v;exports.onFunctionInvoke=q;exports.onMessage=S;exports.onMessageChunk=E;exports.onMessageError=F;exports.onMessageStart=y;exports.onToolCall=b;exports.openUrl=g.openUrl;exports.safeAttachmentUrl=r.safeAttachmentUrl;exports.scrollToElement=g.scrollToElement;exports.setLocalStorage=g.setLocalStorage;exports.setTheme=g.setTheme;exports.showConfirmDialog=g.showConfirmDialog;exports.showNotification=g.showNotification;exports.showToast=g.showToast;exports.submitForm=g.submitForm;exports.trackEvent=g.trackEvent;exports.validateConfig=r.validateConfig;exports.withHandler=I;