@useago/sdk 1.13.3 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/angular.cjs +1 -1
  3. package/dist/angular.d.cts +7 -0
  4. package/dist/angular.d.ts +7 -0
  5. package/dist/angular.js +1 -1
  6. package/dist/{createConversationSession-DrmOaZdO.js → createConversationSession-CybQdMpK.js} +1 -1
  7. package/dist/{createConversationSession-Digvn0GQ.cjs → createConversationSession-jwSXhTLe.cjs} +1 -1
  8. package/dist/{createFormCollector-D_5SDuk9.cjs → createFormCollector-B_hSKcLd.cjs} +1 -1
  9. package/dist/{createFormCollector-D6_N8wYq.js → createFormCollector-DJjms78E.js} +1 -1
  10. package/dist/devtools.d.cts +7 -0
  11. package/dist/devtools.d.ts +7 -0
  12. package/dist/index.cjs +1 -1
  13. package/dist/index.d.cts +7 -0
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.js +6 -6
  16. package/dist/react.cjs +4 -4
  17. package/dist/react.d.cts +8 -1
  18. package/dist/react.d.ts +8 -1
  19. package/dist/react.js +901 -912
  20. package/dist/speechToText-BB25_zVM.cjs +7 -0
  21. package/dist/speechToText-BLvTis4S.js +1496 -0
  22. package/dist/testing.d.cts +7 -0
  23. package/dist/testing.d.ts +7 -0
  24. package/dist/{types-D1ZrqVhr.js → types-C39MJUE3.js} +284 -259
  25. package/dist/{types-DNr6XEwI.cjs → types-PGXnhAmQ.cjs} +7 -7
  26. package/dist/vue.cjs +1 -1
  27. package/dist/vue.d.cts +7 -0
  28. package/dist/vue.d.ts +7 -0
  29. package/dist/vue.js +1 -1
  30. package/dist/widget.cjs +5 -6
  31. package/dist/widget.d.cts +12 -4
  32. package/dist/widget.d.ts +12 -4
  33. package/dist/widget.js +1868 -1841
  34. package/llms-full.txt +23 -3
  35. package/package.json +1 -1
  36. package/dist/speechToText-BV7qxqPF.js +0 -704
  37. package/dist/speechToText-ZciRyyJE.cjs +0 -1
@@ -1,10 +1,10 @@
1
- const v=require("./errors-o1IB5fEu.cjs");var Pe=10,V=1e3;function De(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function D(e,t){if(typeof e=="string"){if(e.length<=1e3)return e;const r=e.length-V;return e.slice(0,V)+`…[truncated ${r} chars]`}if(Array.isArray(e)){if(t.has(e))return"…[circular]";t.add(e);const r=e.slice(0,50).map(i=>D(i,t));return e.length>50&&r.push(`…[+${e.length-50} more]`),t.delete(e),r}if(De(e)){if(t.has(e))return"…[circular]";t.add(e);const r={};for(const[i,s]of Object.entries(e))r[i]=D(s,t);return t.delete(e),r}return e}function he(e){return D(e,new WeakSet)}var ge=class{constructor(e=10){this.entries=[];const t=Math.floor(e);this.maxEntries=Number.isFinite(t)?Math.max(1,t):10}add(e){const t={ts:e.ts??Date.now(),actor:e.actor??"user",name:e.name,summary:e.summary,...e.data!==void 0?{data:he(e.data)}:{}};this.entries.push(t);const r=this.entries.length-this.maxEntries;return r>0&&this.entries.splice(0,r),t}getRecent(){return[...this.entries]}get size(){return this.entries.length}clear(){this.entries=[]}};function O(e){if(e==null)return null;if(typeof e=="string"){const t=e.trim().replace(/_/g,"-");try{const[r]=/^[a-z]{2,3}(?:-[a-z0-9]{1,8})*$/i.test(t)?Intl.getCanonicalLocales(t):[];if(r)return r}catch{}}throw new v.AgoError('Use a language tag such as "fr", "de-DE", or "pt-BR", or null to clear it. See docs/general/configuration.md#language (config_invalid_language).',"config_invalid_language")}var Oe=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)}},c=new Oe,Y="ago_widget_id";function M(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"}function Me(){if(typeof localStorage<"u"){const t=localStorage.getItem(Y);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(Y,e)}catch{}return e}var $e=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||Me()},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);const t=O(e.language);t&&(this.headers["Accept-Language"]=t)}updateConfig(e){const t=O(e.language);e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-User-Anon-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"]),e.language!==void 0&&(t?this.headers["Accept-Language"]=t:delete this.headers["Accept-Language"])}async get(e){return this.request("GET",e)}async post(e,t,r){return this.request("POST",e,t,r)}async postStream(e,t,r){const i=`${this.baseUrl}${e}`;c.debug("POST (stream)",i,t);try{const s=await fetch(i,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0,signal:r?.signal});return s.ok||await this.handleErrorResponse(s),s}catch(s){throw s instanceof v.AgoApiError||M(s)?s:new v.AgoNetworkError(`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 postFormData(e,t,r){const i=`${this.baseUrl}${e}`;c.debug("POST (formData)",i);const s={...this.headers};try{const n=await fetch(i,{method:"POST",headers:s,body:t,signal:r?.signal});return n.ok||await this.handleErrorResponse(n),n}catch(n){throw n instanceof v.AgoApiError||M(n)?n:new v.AgoNetworkError(`Network error: ${n instanceof Error?n.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,n instanceof Error?n:void 0)}}async request(e,t,r,i){const s=`${this.baseUrl}${t}`;c.debug(e,s,r);try{const n=await fetch(s,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0,...i?.keepalive?{keepalive:!0}:{}});return n.ok||await this.handleErrorResponse(n),n.status===204?void 0:n.json()}catch(n){throw n instanceof v.AgoApiError?n:new v.AgoNetworkError(`Network error: ${n instanceof Error?n.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,n instanceof Error?n:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw v.AgoApiError.fromResponse(t,e.status);let r="";throw e.status===401||e.status===403?r=" Check `userJwt` (and that it has not expired).":e.status===404&&(r=" Check that `baseUrl` points at your AGO API root."),new v.AgoApiError(`HTTP ${e.status}: ${e.statusText}.${r}`,"http_error",e.status,"api_error")}},Ne=10,je=6e5;var Le="[AGO SDK]",Ue=300;function $(e,t){return e.length<=t?e:e.slice(0,t)+`…[truncated ${e.length-t} chars]`}function We(e){const t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}function K(e){return typeof e=="object"&&e!==null&&typeof e.message=="string"}function fe(e){if(typeof e=="string")return e;if(K(e))return(typeof e.name=="string"&&e.name?`${e.name}: `:"")+e.message;if(typeof e=="object"&&e!==null)try{return $(JSON.stringify(e),Ue)}catch{return String(e)}return String(e)}function x(e){return K(e)?{message:(typeof e.name=="string"&&e.name&&e.name!=="Error"?`${e.name}: `:"")+e.message,stack:typeof e.stack=="string"?e.stack:void 0}:{message:fe(e)}}var me=class{constructor(e={}){this.started=!1,this.teardowns=[],this.errors=[],this.listeners=new Set,this.capturing=!1;const t=Math.floor(e.maxErrors??10);this.maxErrors=Number.isFinite(t)?Math.max(1,t):10,this.maxAgeMs=e.maxAgeMs??6e5,this.maxStackChars=e.maxStackChars??2e3,this.filter=e.filter}start(){if(this.started||typeof window>"u")return;this.started=!0;const e=r=>this.onErrorEvent(r);window.addEventListener("error",e),this.teardowns.push(()=>window.removeEventListener("error",e));const t=r=>this.onRejectionEvent(r);window.addEventListener("unhandledrejection",t),this.teardowns.push(()=>window.removeEventListener("unhandledrejection",t)),this.wrapConsoleError(),c.log("ErrorWatcher started")}destroy(){for(const e of this.teardowns)e();this.teardowns=[],this.listeners.clear(),this.started=!1,c.log("ErrorWatcher destroyed")}report(e,t){const r=x(e);this.capture({type:"manual",message:r.message,stack:r.stack,...t?{context:he(t)}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getErrors(){return this.prune(),this.errors.map(e=>({...e}))}clear(){this.errors=[]}onErrorEvent(e){if(typeof e.message!="string"&&!e.error)return;const t=e.error!==void 0&&e.error!==null?x(e.error):{message:e.message??""};this.capture({type:"error",message:t.message||e.message||"Unknown error",stack:t.stack,source:e.filename?We(e.filename):void 0,line:e.lineno||void 0,col:e.colno||void 0})}onRejectionEvent(e){const t=e.reason,r=x(t);this.capture({type:"unhandledrejection",message:r.message||"Unhandled promise rejection",stack:r.stack})}wrapConsoleError(){if(typeof console>"u"||typeof console.error!="function")return;const e=console.error,t=(...r)=>{try{this.onConsoleError(r)}catch{}return e.apply(console,r)};console.error=t,this.teardowns.push(()=>{console.error===t&&(console.error=e)})}onConsoleError(e){if(e.length===0)return;const t=e[0];if(typeof t=="string"&&t.startsWith(Le))return;const r=e.find(K),i=e.map(fe).join(" ");this.capture({type:"console",message:i,stack:r&&typeof r.stack=="string"?r.stack:void 0})}capture(e){if(!this.capturing){this.capturing=!0;try{const t=Date.now(),r=e.stack!==void 0?this.trimStack(e.stack,e.message):void 0;let i={type:e.type,message:$(e.message,500),...e.source!==void 0?{source:e.source}:{},...e.line!==void 0?{line:e.line}:{},...e.col!==void 0?{col:e.col}:{},...r?{stack:r}:{},route:this.currentPathname(),firstAt:t,lastAt:t,count:1,...e.context!==void 0?{context:e.context}:{}};if(this.filter){const a=this.filter(i);if(!a)return;i=a}this.prune(t);const s=Q(i),n=this.errors.find(a=>Q(a)===s);if(n){n.count+=1,n.lastAt=t,i.context!==void 0&&(n.context=i.context),this.notify(n);return}this.errors.push(i);const o=this.errors.length-this.maxErrors;o>0&&this.errors.splice(0,o),this.notify(i)}finally{this.capturing=!1}}}notify(e){const t={...e};for(const r of this.listeners)try{r(t)}catch(i){c.error("ErrorWatcher listener threw:",i)}}prune(e=Date.now()){Number.isFinite(this.maxAgeMs)&&(this.errors=this.errors.filter(t=>e-t.lastAt<=this.maxAgeMs))}trimStack(e,t){let r=e;const i=r.indexOf(`
2
- `);if(i!==-1&&r.slice(0,i).includes(t.slice(0,80))&&(r=r.slice(i+1)),r=r.trim(),!!r)return $(r,this.maxStackChars)}currentPathname(){return typeof window<"u"&&window.location?window.location.pathname:""}};function Q(e){return`${e.type}|${e.message}|${e.source??""}|${e.line??""}`}var A={name:30,description:500,parameterName:30,parameterDescription:150,resultBytes:1500};function Be(e){const t=[],r=(i,s,n)=>{const o=s?.length??0;o>n&&t.push(`${i} (${o}/${n})`)};r("name",e.name,A.name),r("description",e.description,A.description);for(const[i,s]of Object.entries(e.parameters?.properties??{}))r(`"${i}" name`,i,A.parameterName),r(`"${i}" description`,s.description??"",A.parameterDescription);return t}var qe=5e4,Ge=2e4,Ke=2e3,pe=class{constructor(e){this.functions=new Map,this.changeListeners=new Set,this.defaultMaxResultBytes=e?.maxResultBytes??qe}onChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}emitChange(){for(const e of this.changeListeners)try{e()}catch(t){c.error("Function registry change listener failed:",t)}}setDefaultMaxResultBytes(e){this.defaultMaxResultBytes=e}getDefaultMaxResultBytes(){return this.defaultMaxResultBytes}register(e,t,r){if(typeof e=="object"){const{name:u,handler:g,description:f,parameters:w,maxResultBytes:y,requiresApproval:h,webmcp:p}=e;return this.register(u,g,{description:f,parameters:w,maxResultBytes:y,requiresApproval:h,webmcp:p})}const i=e;if(!t||!r)throw new v.AgoError(`registerFunction("${i}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`,"function_invalid_registration");this.functions.has(i)&&c.warn(`Function "${i}" is being overwritten`);const{maxResultBytes:s,requiresApproval:n,webmcp:o,...a}=r,l={...a,name:i};this.functions.set(i,{schema:l,handler:t,maxResultBytes:s,requiresApproval:n,webmcp:o});const d=Be(l);d.length>0&&c.warn(`Function "${i}" is over the per-tool budget on ${d.join(", ")}.`),c.log(`Registered function: ${i}`),this.emitChange()}unregister(e){const t=this.functions.delete(e);return t&&(c.log(`Unregistered function: ${e}`),this.emitChange()),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)}getAll(){return Array.from(this.functions.entries()).map(([e,t])=>({...t,name:e}))}async execute(e,t){const r=this.functions.get(e);if(!r)throw new v.AgoFunctionError(`Function "${e}" is not registered`,e);c.log(`Executing function: ${e}`,t);try{const i=await r.handler(t);return c.log(`Function ${e} completed:`,i),this.guardResultSize(e,i,r.maxResultBytes)}catch(i){throw c.error(`Function ${e} failed:`,i),new v.AgoFunctionError(`Function "${e}" execution failed: ${i instanceof Error?i.message:"Unknown error"}`,e,i instanceof Error?i:void 0)}}guardResultSize(e,t,r){let i;try{i=JSON.stringify(t)}catch{return t}if(i===void 0)return t;const s=new TextEncoder().encode(i).length,n=r??this.defaultMaxResultBytes;return s>n?(c.warn(`Function "${e}" result is ${s} bytes, over the ${n}-byte limit; a truncated preview was sent to the agent instead. Return fewer fields, paginate, or raise maxResultBytes for this function.`),{truncated:!0,originalBytes:s,maxBytes:n,preview:i.slice(0,Ke),hint:`The result of "${e}" exceeded the ${n}-byte limit and was truncated. Request less data (use limit or filter parameters if available), or tell the user the result is too large to process.`}):(s>Ge&&c.warn(`Function "${e}" returned a large result (${Math.round(s/1024)} KB). Large results consume LLM context: return fewer fields, paginate, or push the data to the UI and return a summary.`),t)}clear(){const e=this.functions.size>0;this.functions.clear(),c.log("Cleared all registered functions"),e&&this.emitChange()}get size(){return this.functions.size}},Je=new TextEncoder;function S(e){return Je.encode(e).length}function N(e){return S(JSON.stringify(e))-2}function ye(e,t){if(t<=0)return"";let r="",i=0;for(const s of e){const n=N(s);if(i+n>t)break;r+=s,i+=n}return r}var He=50,Xe=2;var ze=2e3;function C(e){try{return JSON.stringify(e)}catch{return}}var j=Symbol("ago.pageData.timeout");function Ve(e,t){return t<=0?Promise.resolve(j):new Promise((r,i)=>{const s=setTimeout(()=>r(j),t);e.then(n=>{clearTimeout(s),r(n)},n=>{clearTimeout(s),i(n)})})}async function Ye(e,t){const r=Date.now()+t;let i=0;for(;Date.now()<r&&i<Xe;)i=e().isLoading?.()?0:i+1,await new Promise(a=>setTimeout(a,He));const s=e().get();if(!Z(s))return s;const n=await Ve(Promise.resolve(s),r-Date.now());if(n!==j)return n;c.warn("Page data did not resolve within the settle timeout; returning what the page has now. Raise settleTimeoutMs if the work legitimately takes longer.");const o=e().get();if(!Z(o))return o;Promise.resolve(o).catch(()=>{})}function Z(e){return typeof e=="object"&&e!==null&&typeof e.then=="function"}function Qe(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;let r;for(const i of Object.keys(t)){const s=t[i];Array.isArray(s)&&(r===void 0||s.length>t[r].length)&&(r=i)}return r}function Ze(e,t){let r=2,i=0;for(const s of e){const n=S(C(s)??"null")+(i>0?1:0);if(r+n>t)break;r+=n,i++}return i}function L(e){return`The page data returned by "${e}" was too large to send in full. Only the first items are included: ask for fewer rows or narrow the filters to see the rest.`}function et(e,t,r,i){const s={truncated:!0,originalBytes:r,maxBytes:i,preview:"",hint:L(e)},n=S(C(s)??"{}");return{...s,preview:ye(t,Math.min(ze,i-n))}}function tt(e,t,r,i,s){const n=r===void 0?{}:{...t},o=r??"items",a=S(C({...n,[o]:[],truncation:{truncated:!0,returnedItems:i.length,totalItems:i.length,hint:L(e)}})??"{}")-2;if(a>=s)return;const l=i.slice(0,Ze(i,s-a));return{...n,[o]:l,truncation:{truncated:!0,returnedItems:l.length,totalItems:i.length,hint:L(e)}}}function ee(e,t,r){const i=C(t);if(i===void 0)return t;const s=S(i);if(s<=r)return t;c.warn(`Page data for "${e}" is ${s} bytes, over the ${r}-byte limit; it was truncated to the first items that fit. Return fewer fields per item, paginate, or raise maxResultBytes on the data source.`);const n=Qe(t),o=Array.isArray(t)?t:n!==void 0?t[n]:void 0;if(o){const a=tt(e,t,n,o,r),l=S(C(a)??"");if(a!==void 0&&l<=r)return a}return et(e,i,s,r)}var J="navigateToPage",R="listPages";function rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(e){return e.split("/").filter(t=>t.startsWith(":")).map(t=>t.slice(1))}function it(e,t){const r=[];return{path:e.split("/").map(i=>{if(!i.startsWith(":"))return i;const s=i.slice(1),n=t[s];return n==null||n===""?(r.push(s),i):encodeURIComponent(String(n))}).join("/"),missing:r}}function st(e,t){const r=t.find(s=>s.path===e);if(r)return r;const i=t.find(s=>{if(!s.path.includes(":"))return!1;const n="^"+s.path.split("/").map(o=>o.startsWith(":")?"[^/]+":rt(o)).join("/")+"/?$";return new RegExp(n).test(e)});return i||t.filter(s=>s.path!=="/"&&e.startsWith(s.path)).sort((s,n)=>n.path.length-s.path.length)[0]}function ve(e){return[...new Set(e.map(t=>t.section).filter(t=>!!t))]}function nt(e){const t=U(e.path),r=t.length>0?` (requires ${t.map(i=>`"${i}"`).join(", ")})`:"";return`- "${e.name}"${r}: ${e.description}`}function ot(e,t,r){const i=r?.catalogue==="onDemand",s=ve(t);!i&&s.length>0&&c.log('registerNavigationFunction: routes declare "section" but catalogue is "inline", so it is unused. Set catalogue: "onDemand" to use it.');const n="Available functions depend on the current page. After navigation, you will receive the destination page’s available functions and current state. Use them to complete any remaining actions in the user’s request.",o=i?`Navigate the user to a page. Call ${R} for what a page name means. ${n}`:`Navigate the user to a page in the application. ${n} Available pages:
3
- ${t.map(nt).join(`
4
- `)}`,a=new Map;for(const u of t)for(const g of U(u.path))a.set(g,[...a.get(g)??[],u.name]);const l=t.map(u=>u.name),d={page:{type:"string",description:"The page to navigate to",enum:l}};for(const[u,g]of a){if(u==="page"){c.error('registerNavigationFunction: a ":page" placeholder collides with the "page" argument and is ignored. Rename the placeholder.');continue}d[u]={type:"string",description:`Value for ":${u}" in the page path. Required when page is ${g.map(f=>`"${f}"`).join(" or ")}.`}}return{name:J,description:o,parameters:{type:"object",properties:d,required:["page"]},webmcp:{navigates:!0},handler:async u=>{const g=u.page,f=t.find(m=>m.name===g);if(!f)return i?{success:!1,error:`Unknown page: ${g}`,pages:l}:{success:!1,error:`Unknown page: ${g}`};let w={};if(typeof u.params=="string")try{w=JSON.parse(u.params)}catch{}else u.params&&typeof u.params=="object"&&(w=u.params);const y={};for(const m of U(f.path))y[m]=u[m]??w[m];const{path:h,missing:p}=it(f.path,y);if(p.length>0){const m=p.map(b=>`"${b}": "..."`).join(", ");return{success:!1,error:`Page "${g}" needs ${p.map(b=>`"${b}"`).join(", ")}. Retry with { "page": "${g}", ${m} }.`}}return e(h),{success:!0,navigatedTo:h}}}}function at(e){const t=ve(e),r=i=>({name:i.name,description:i.description});return{name:R,description:`List what each page name of ${J} means.`,parameters:{type:"object",properties:t.length>0?{section:{type:"string",description:"Which group of pages to list.",enum:t}}:{},required:t.length>0?["section"]:[]},webmcp:{annotations:{readOnlyHint:!0}},handler:i=>{if(t.length===0)return{pages:e.map(r)};const s=typeof i.section=="string"?i.section:void 0,n=t.find(o=>o.toLowerCase()===s?.toLowerCase());return n?{pages:e.filter(o=>o.section===n).map(r)}:{pages:[],sections:t,error:s?`Unknown section: ${s}`:'"section" is required. Pick one and call again.'}}}}function T(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e))return e.length!==t.length?!1:e.every((s,n)=>T(s,t[n]));const r=Object.keys(e),i=Object.keys(t);return r.length!==i.length?!1:r.every(s=>s in t&&T(e[s],t[s]))}var te=100,F=" … [truncated]",we={truncated:!0},ct=S(',"data":'+JSON.stringify(we));function W(e){return S(JSON.stringify(e))}function re(e,t){if(W(e)<=t||!e.rejected)return e;const r=Object.entries(e.rejected),i=Object.fromEntries(r.map(([a])=>[a,F])),s={...e,rejected:i};let n=W(s);if(n>t)return s;const o=N(F);for(const[a,l]of r){const d=N(l),u=t-n+o;if(d<=u){i[a]=l,n+=d-o;continue}i[a]=ye(l,u-o)+F;break}return s}function _(e){return Array.isArray(e)?"array":typeof e}function ie(e){return typeof e!="number"?`Expected type "number", got "${_(e)}".`:Number.isFinite(e)?null:"Expected a finite number."}function be(e){const t=e.slice(0,te).map(i=>JSON.stringify(i)),r=e.length-te;return r>0?`${t.join(", ")} (${r} more not shown)`:t.join(", ")}function se(e,t){return t.includes(e)?null:t.length===0?"No values are currently allowed.":`${JSON.stringify(e)} is not an allowed value. Allowed values: ${be(t)}.`}function lt(e,t){const{schema:r}=t;if(r.type==="array"){if(!Array.isArray(e))return`Expected type "array", got "${_(e)}".`;for(let s=0;s<e.length;s++){const n=e[s];if(r.items?.type){const o=r.items.type==="number"?ie(n):_(n)!==r.items.type?`Expected type "${r.items.type}", got "${_(n)}".`:null;if(o)return`Array item at index ${s}: ${o[0].toLowerCase()}${o.slice(1)}`}if(r.items?.enum){const o=se(n,r.items.enum);if(o)return`Array item ${o}`}}return null}if(r.type==="number"){const s=ie(e);if(s)return s}else if(_(e)!==r.type)return`Expected type "${r.type}", got "${_(e)}".`;const i=Ee(t);return i?se(e,i):null}function H(e){return e.clearable===!0&&e.schema.type==="string"}function Ee(e){const t=e.schema.enum;if(t)return H(e)&&!t.includes("")?[...t,""]:t}function ut(e){const t={...e.schema,...e.schema.items?{items:{...e.schema.items}}:{},description:e.description};t.enum?.length===0&&delete t.enum,t.items?.enum?.length===0&&delete t.items.enum,H(e)&&(t.description=`${e.description} Pass "" to clear it.`);const r=Ee(e);return r?.length&&(t.enum=r),t}function dt(e,t){const r=new Map(e.map(n=>[n.name,n])),i=e.map(n=>n.name),s=e.map(n=>`- "${n.name}": ${n.description}`).join(`
5
- `);return{name:t.name,handler:async n=>{const o=[],a=[],l={};for(const[h,p]of Object.entries(n)){const m=r.get(h);if(!m){l[h]=`"${h}" is not a registered control. Available controls: ${be(i)}.`;continue}if(p==null||p===""&&!H(m))continue;const b=lt(p,m);if(b){l[h]=b;continue}if(m.get&&T(p,m.get())){a.push(h);continue}const E=await m.set(p);E?E.result==="rejected"?l[h]=E.reason||"The page rejected this field's update.":E.result==="unchanged"?a.push(h):o.push(h):o.push(h)}const d=Object.keys(l).length>0,u={success:!d,applied:o,unchanged:a,...d?{rejected:l}:{}},g=t.getResultBudget();if(!t.data)return re(u,g);const f=re(u,g-ct),w=await t.data.read(f),y={...f,data:w};return W(y)<=g?y:{...f,data:we}},description:(e.length>0?`Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
1
+ const v=require("./errors-o1IB5fEu.cjs");var De=10,V=1e3;function Oe(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function O(e,t){if(typeof e=="string"){if(e.length<=1e3)return e;const r=e.length-V;return e.slice(0,V)+`…[truncated ${r} chars]`}if(Array.isArray(e)){if(t.has(e))return"…[circular]";t.add(e);const r=e.slice(0,50).map(i=>O(i,t));return e.length>50&&r.push(`…[+${e.length-50} more]`),t.delete(e),r}if(Oe(e)){if(t.has(e))return"…[circular]";t.add(e);const r={};for(const[i,s]of Object.entries(e))r[i]=O(s,t);return t.delete(e),r}return e}function he(e){return O(e,new WeakSet)}var ge=class{constructor(e=10){this.entries=[];const t=Math.floor(e);this.maxEntries=Number.isFinite(t)?Math.max(1,t):10}add(e){const t={ts:e.ts??Date.now(),actor:e.actor??"user",name:e.name,summary:e.summary,...e.data!==void 0?{data:he(e.data)}:{}};this.entries.push(t);const r=this.entries.length-this.maxEntries;return r>0&&this.entries.splice(0,r),t}getRecent(){return[...this.entries]}get size(){return this.entries.length}clear(){this.entries=[]}},fe=["en","fr","de","es","it","pt"];function Me(e){const t=e?.toLowerCase().split(/[-_]/)[0];return fe.find(r=>r===t)??"en"}function $e(e){const t=S(e);return t&&fe.some(r=>t.split("-")[0]===r)?t:"en"}function S(e){if(e==null)return null;if(typeof e=="string"){const t=e.trim().replace(/_/g,"-");try{const[r]=/^[a-z]{2,3}(?:-[a-z0-9]{1,8})*$/i.test(t)?Intl.getCanonicalLocales(t):[];if(r)return r}catch{}}throw new v.AgoError('Use a language tag such as "fr", "de-DE", or "pt-BR", or null to clear it. See docs/general/configuration.md#language (config_invalid_language).',"config_invalid_language")}var Ne=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)}},c=new Ne,Y="ago_widget_id";function M(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"}function je(){if(typeof localStorage<"u"){const t=localStorage.getItem(Y);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(Y,e)}catch{}return e}var Le=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||je()},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);const t=S(e.language);t&&(this.headers["Accept-Language"]=t)}updateConfig(e){const t=S(e.language);e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-User-Anon-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"]),e.language!==void 0&&(t?this.headers["Accept-Language"]=t:delete this.headers["Accept-Language"])}async get(e){return this.request("GET",e)}async post(e,t,r){return this.request("POST",e,t,r)}async postStream(e,t,r){const i=`${this.baseUrl}${e}`;c.debug("POST (stream)",i,t);try{const s=await fetch(i,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0,signal:r?.signal});return s.ok||await this.handleErrorResponse(s),s}catch(s){throw s instanceof v.AgoApiError||M(s)?s:new v.AgoNetworkError(`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 postFormData(e,t,r){const i=`${this.baseUrl}${e}`;c.debug("POST (formData)",i);const s={...this.headers};try{const n=await fetch(i,{method:"POST",headers:s,body:t,signal:r?.signal});return n.ok||await this.handleErrorResponse(n),n}catch(n){throw n instanceof v.AgoApiError||M(n)?n:new v.AgoNetworkError(`Network error: ${n instanceof Error?n.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,n instanceof Error?n:void 0)}}async request(e,t,r,i){const s=`${this.baseUrl}${t}`;c.debug(e,s,r);try{const n=await fetch(s,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0,...i?.keepalive?{keepalive:!0}:{}});return n.ok||await this.handleErrorResponse(n),n.status===204?void 0:n.json()}catch(n){throw n instanceof v.AgoApiError?n:new v.AgoNetworkError(`Network error: ${n instanceof Error?n.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,n instanceof Error?n:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw v.AgoApiError.fromResponse(t,e.status);let r="";throw e.status===401||e.status===403?r=" Check `userJwt` (and that it has not expired).":e.status===404&&(r=" Check that `baseUrl` points at your AGO API root."),new v.AgoApiError(`HTTP ${e.status}: ${e.statusText}.${r}`,"http_error",e.status,"api_error")}},Ue=10,We=6e5;var Be="[AGO SDK]",Ge=300;function $(e,t){return e.length<=t?e:e.slice(0,t)+`…[truncated ${e.length-t} chars]`}function qe(e){const t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}function K(e){return typeof e=="object"&&e!==null&&typeof e.message=="string"}function me(e){if(typeof e=="string")return e;if(K(e))return(typeof e.name=="string"&&e.name?`${e.name}: `:"")+e.message;if(typeof e=="object"&&e!==null)try{return $(JSON.stringify(e),Ge)}catch{return String(e)}return String(e)}function F(e){return K(e)?{message:(typeof e.name=="string"&&e.name&&e.name!=="Error"?`${e.name}: `:"")+e.message,stack:typeof e.stack=="string"?e.stack:void 0}:{message:me(e)}}var pe=class{constructor(e={}){this.started=!1,this.teardowns=[],this.errors=[],this.listeners=new Set,this.capturing=!1;const t=Math.floor(e.maxErrors??10);this.maxErrors=Number.isFinite(t)?Math.max(1,t):10,this.maxAgeMs=e.maxAgeMs??6e5,this.maxStackChars=e.maxStackChars??2e3,this.filter=e.filter}start(){if(this.started||typeof window>"u")return;this.started=!0;const e=r=>this.onErrorEvent(r);window.addEventListener("error",e),this.teardowns.push(()=>window.removeEventListener("error",e));const t=r=>this.onRejectionEvent(r);window.addEventListener("unhandledrejection",t),this.teardowns.push(()=>window.removeEventListener("unhandledrejection",t)),this.wrapConsoleError(),c.log("ErrorWatcher started")}destroy(){for(const e of this.teardowns)e();this.teardowns=[],this.listeners.clear(),this.started=!1,c.log("ErrorWatcher destroyed")}report(e,t){const r=F(e);this.capture({type:"manual",message:r.message,stack:r.stack,...t?{context:he(t)}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getErrors(){return this.prune(),this.errors.map(e=>({...e}))}clear(){this.errors=[]}onErrorEvent(e){if(typeof e.message!="string"&&!e.error)return;const t=e.error!==void 0&&e.error!==null?F(e.error):{message:e.message??""};this.capture({type:"error",message:t.message||e.message||"Unknown error",stack:t.stack,source:e.filename?qe(e.filename):void 0,line:e.lineno||void 0,col:e.colno||void 0})}onRejectionEvent(e){const t=e.reason,r=F(t);this.capture({type:"unhandledrejection",message:r.message||"Unhandled promise rejection",stack:r.stack})}wrapConsoleError(){if(typeof console>"u"||typeof console.error!="function")return;const e=console.error,t=(...r)=>{try{this.onConsoleError(r)}catch{}return e.apply(console,r)};console.error=t,this.teardowns.push(()=>{console.error===t&&(console.error=e)})}onConsoleError(e){if(e.length===0)return;const t=e[0];if(typeof t=="string"&&t.startsWith(Be))return;const r=e.find(K),i=e.map(me).join(" ");this.capture({type:"console",message:i,stack:r&&typeof r.stack=="string"?r.stack:void 0})}capture(e){if(!this.capturing){this.capturing=!0;try{const t=Date.now(),r=e.stack!==void 0?this.trimStack(e.stack,e.message):void 0;let i={type:e.type,message:$(e.message,500),...e.source!==void 0?{source:e.source}:{},...e.line!==void 0?{line:e.line}:{},...e.col!==void 0?{col:e.col}:{},...r?{stack:r}:{},route:this.currentPathname(),firstAt:t,lastAt:t,count:1,...e.context!==void 0?{context:e.context}:{}};if(this.filter){const a=this.filter(i);if(!a)return;i=a}this.prune(t);const s=Q(i),n=this.errors.find(a=>Q(a)===s);if(n){n.count+=1,n.lastAt=t,i.context!==void 0&&(n.context=i.context),this.notify(n);return}this.errors.push(i);const o=this.errors.length-this.maxErrors;o>0&&this.errors.splice(0,o),this.notify(i)}finally{this.capturing=!1}}}notify(e){const t={...e};for(const r of this.listeners)try{r(t)}catch(i){c.error("ErrorWatcher listener threw:",i)}}prune(e=Date.now()){Number.isFinite(this.maxAgeMs)&&(this.errors=this.errors.filter(t=>e-t.lastAt<=this.maxAgeMs))}trimStack(e,t){let r=e;const i=r.indexOf(`
2
+ `);if(i!==-1&&r.slice(0,i).includes(t.slice(0,80))&&(r=r.slice(i+1)),r=r.trim(),!!r)return $(r,this.maxStackChars)}currentPathname(){return typeof window<"u"&&window.location?window.location.pathname:""}};function Q(e){return`${e.type}|${e.message}|${e.source??""}|${e.line??""}`}var k={name:30,description:500,parameterName:30,parameterDescription:150,resultBytes:1500};function Ke(e){const t=[],r=(i,s,n)=>{const o=s?.length??0;o>n&&t.push(`${i} (${o}/${n})`)};r("name",e.name,k.name),r("description",e.description,k.description);for(const[i,s]of Object.entries(e.parameters?.properties??{}))r(`"${i}" name`,i,k.parameterName),r(`"${i}" description`,s.description??"",k.parameterDescription);return t}var Je=5e4,He=2e4,Xe=2e3,ye=class{constructor(e){this.functions=new Map,this.changeListeners=new Set,this.defaultMaxResultBytes=e?.maxResultBytes??Je}onChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}emitChange(){for(const e of this.changeListeners)try{e()}catch(t){c.error("Function registry change listener failed:",t)}}setDefaultMaxResultBytes(e){this.defaultMaxResultBytes=e}getDefaultMaxResultBytes(){return this.defaultMaxResultBytes}register(e,t,r){if(typeof e=="object"){const{name:u,handler:g,description:f,parameters:w,maxResultBytes:y,requiresApproval:h,webmcp:p}=e;return this.register(u,g,{description:f,parameters:w,maxResultBytes:y,requiresApproval:h,webmcp:p})}const i=e;if(!t||!r)throw new v.AgoError(`registerFunction("${i}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`,"function_invalid_registration");this.functions.has(i)&&c.warn(`Function "${i}" is being overwritten`);const{maxResultBytes:s,requiresApproval:n,webmcp:o,...a}=r,l={...a,name:i};this.functions.set(i,{schema:l,handler:t,maxResultBytes:s,requiresApproval:n,webmcp:o});const d=Ke(l);d.length>0&&c.warn(`Function "${i}" is over the per-tool budget on ${d.join(", ")}.`),c.log(`Registered function: ${i}`),this.emitChange()}unregister(e){const t=this.functions.delete(e);return t&&(c.log(`Unregistered function: ${e}`),this.emitChange()),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)}getAll(){return Array.from(this.functions.entries()).map(([e,t])=>({...t,name:e}))}async execute(e,t){const r=this.functions.get(e);if(!r)throw new v.AgoFunctionError(`Function "${e}" is not registered`,e);c.log(`Executing function: ${e}`,t);try{const i=await r.handler(t);return c.log(`Function ${e} completed:`,i),this.guardResultSize(e,i,r.maxResultBytes)}catch(i){throw c.error(`Function ${e} failed:`,i),new v.AgoFunctionError(`Function "${e}" execution failed: ${i instanceof Error?i.message:"Unknown error"}`,e,i instanceof Error?i:void 0)}}guardResultSize(e,t,r){let i;try{i=JSON.stringify(t)}catch{return t}if(i===void 0)return t;const s=new TextEncoder().encode(i).length,n=r??this.defaultMaxResultBytes;return s>n?(c.warn(`Function "${e}" result is ${s} bytes, over the ${n}-byte limit; a truncated preview was sent to the agent instead. Return fewer fields, paginate, or raise maxResultBytes for this function.`),{truncated:!0,originalBytes:s,maxBytes:n,preview:i.slice(0,Xe),hint:`The result of "${e}" exceeded the ${n}-byte limit and was truncated. Request less data (use limit or filter parameters if available), or tell the user the result is too large to process.`}):(s>He&&c.warn(`Function "${e}" returned a large result (${Math.round(s/1024)} KB). Large results consume LLM context: return fewer fields, paginate, or push the data to the UI and return a summary.`),t)}clear(){const e=this.functions.size>0;this.functions.clear(),c.log("Cleared all registered functions"),e&&this.emitChange()}get size(){return this.functions.size}},ze=new TextEncoder;function _(e){return ze.encode(e).length}function N(e){return _(JSON.stringify(e))-2}function ve(e,t){if(t<=0)return"";let r="",i=0;for(const s of e){const n=N(s);if(i+n>t)break;r+=s,i+=n}return r}var Ve=50,Ye=2;var Qe=2e3;function A(e){try{return JSON.stringify(e)}catch{return}}var j=Symbol("ago.pageData.timeout");function Ze(e,t){return t<=0?Promise.resolve(j):new Promise((r,i)=>{const s=setTimeout(()=>r(j),t);e.then(n=>{clearTimeout(s),r(n)},n=>{clearTimeout(s),i(n)})})}async function et(e,t){const r=Date.now()+t;let i=0;for(;Date.now()<r&&i<Ye;)i=e().isLoading?.()?0:i+1,await new Promise(a=>setTimeout(a,Ve));const s=e().get();if(!Z(s))return s;const n=await Ze(Promise.resolve(s),r-Date.now());if(n!==j)return n;c.warn("Page data did not resolve within the settle timeout; returning what the page has now. Raise settleTimeoutMs if the work legitimately takes longer.");const o=e().get();if(!Z(o))return o;Promise.resolve(o).catch(()=>{})}function Z(e){return typeof e=="object"&&e!==null&&typeof e.then=="function"}function tt(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;let r;for(const i of Object.keys(t)){const s=t[i];Array.isArray(s)&&(r===void 0||s.length>t[r].length)&&(r=i)}return r}function rt(e,t){let r=2,i=0;for(const s of e){const n=_(A(s)??"null")+(i>0?1:0);if(r+n>t)break;r+=n,i++}return i}function L(e){return`The page data returned by "${e}" was too large to send in full. Only the first items are included: ask for fewer rows or narrow the filters to see the rest.`}function it(e,t,r,i){const s={truncated:!0,originalBytes:r,maxBytes:i,preview:"",hint:L(e)},n=_(A(s)??"{}");return{...s,preview:ve(t,Math.min(Qe,i-n))}}function st(e,t,r,i,s){const n=r===void 0?{}:{...t},o=r??"items",a=_(A({...n,[o]:[],truncation:{truncated:!0,returnedItems:i.length,totalItems:i.length,hint:L(e)}})??"{}")-2;if(a>=s)return;const l=i.slice(0,rt(i,s-a));return{...n,[o]:l,truncation:{truncated:!0,returnedItems:l.length,totalItems:i.length,hint:L(e)}}}function ee(e,t,r){const i=A(t);if(i===void 0)return t;const s=_(i);if(s<=r)return t;c.warn(`Page data for "${e}" is ${s} bytes, over the ${r}-byte limit; it was truncated to the first items that fit. Return fewer fields per item, paginate, or raise maxResultBytes on the data source.`);const n=tt(t),o=Array.isArray(t)?t:n!==void 0?t[n]:void 0;if(o){const a=st(e,t,n,o,r),l=_(A(a)??"");if(a!==void 0&&l<=r)return a}return it(e,i,s,r)}var J="navigateToPage",T="listPages";function nt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(e){return e.split("/").filter(t=>t.startsWith(":")).map(t=>t.slice(1))}function ot(e,t){const r=[];return{path:e.split("/").map(i=>{if(!i.startsWith(":"))return i;const s=i.slice(1),n=t[s];return n==null||n===""?(r.push(s),i):encodeURIComponent(String(n))}).join("/"),missing:r}}function at(e,t){const r=t.find(s=>s.path===e);if(r)return r;const i=t.find(s=>{if(!s.path.includes(":"))return!1;const n="^"+s.path.split("/").map(o=>o.startsWith(":")?"[^/]+":nt(o)).join("/")+"/?$";return new RegExp(n).test(e)});return i||t.filter(s=>s.path!=="/"&&e.startsWith(s.path)).sort((s,n)=>n.path.length-s.path.length)[0]}function we(e){return[...new Set(e.map(t=>t.section).filter(t=>!!t))]}function ct(e){const t=U(e.path),r=t.length>0?` (requires ${t.map(i=>`"${i}"`).join(", ")})`:"";return`- "${e.name}"${r}: ${e.description}`}function lt(e,t,r){const i=r?.catalogue==="onDemand",s=we(t);!i&&s.length>0&&c.log('registerNavigationFunction: routes declare "section" but catalogue is "inline", so it is unused. Set catalogue: "onDemand" to use it.');const n="Available functions depend on the current page. After navigation, you will receive the destination page’s available functions and current state. Use them to complete any remaining actions in the user’s request.",o=i?`Navigate the user to a page. Call ${T} for what a page name means. ${n}`:`Navigate the user to a page in the application. ${n} Available pages:
3
+ ${t.map(ct).join(`
4
+ `)}`,a=new Map;for(const u of t)for(const g of U(u.path))a.set(g,[...a.get(g)??[],u.name]);const l=t.map(u=>u.name),d={page:{type:"string",description:"The page to navigate to",enum:l}};for(const[u,g]of a){if(u==="page"){c.error('registerNavigationFunction: a ":page" placeholder collides with the "page" argument and is ignored. Rename the placeholder.');continue}d[u]={type:"string",description:`Value for ":${u}" in the page path. Required when page is ${g.map(f=>`"${f}"`).join(" or ")}.`}}return{name:J,description:o,parameters:{type:"object",properties:d,required:["page"]},webmcp:{navigates:!0},handler:async u=>{const g=u.page,f=t.find(m=>m.name===g);if(!f)return i?{success:!1,error:`Unknown page: ${g}`,pages:l}:{success:!1,error:`Unknown page: ${g}`};let w={};if(typeof u.params=="string")try{w=JSON.parse(u.params)}catch{}else u.params&&typeof u.params=="object"&&(w=u.params);const y={};for(const m of U(f.path))y[m]=u[m]??w[m];const{path:h,missing:p}=ot(f.path,y);if(p.length>0){const m=p.map(b=>`"${b}": "..."`).join(", ");return{success:!1,error:`Page "${g}" needs ${p.map(b=>`"${b}"`).join(", ")}. Retry with { "page": "${g}", ${m} }.`}}return e(h),{success:!0,navigatedTo:h}}}}function ut(e){const t=we(e),r=i=>({name:i.name,description:i.description});return{name:T,description:`List what each page name of ${J} means.`,parameters:{type:"object",properties:t.length>0?{section:{type:"string",description:"Which group of pages to list.",enum:t}}:{},required:t.length>0?["section"]:[]},webmcp:{annotations:{readOnlyHint:!0}},handler:i=>{if(t.length===0)return{pages:e.map(r)};const s=typeof i.section=="string"?i.section:void 0,n=t.find(o=>o.toLowerCase()===s?.toLowerCase());return n?{pages:e.filter(o=>o.section===n).map(r)}:{pages:[],sections:t,error:s?`Unknown section: ${s}`:'"section" is required. Pick one and call again.'}}}}function I(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e))return e.length!==t.length?!1:e.every((s,n)=>I(s,t[n]));const r=Object.keys(e),i=Object.keys(t);return r.length!==i.length?!1:r.every(s=>s in t&&I(e[s],t[s]))}var te=100,P=" … [truncated]",be={truncated:!0},dt=_(',"data":'+JSON.stringify(be));function W(e){return _(JSON.stringify(e))}function re(e,t){if(W(e)<=t||!e.rejected)return e;const r=Object.entries(e.rejected),i=Object.fromEntries(r.map(([a])=>[a,P])),s={...e,rejected:i};let n=W(s);if(n>t)return s;const o=N(P);for(const[a,l]of r){const d=N(l),u=t-n+o;if(d<=u){i[a]=l,n+=d-o;continue}i[a]=ve(l,u-o)+P;break}return s}function C(e){return Array.isArray(e)?"array":typeof e}function ie(e){return typeof e!="number"?`Expected type "number", got "${C(e)}".`:Number.isFinite(e)?null:"Expected a finite number."}function Ee(e){const t=e.slice(0,te).map(i=>JSON.stringify(i)),r=e.length-te;return r>0?`${t.join(", ")} (${r} more not shown)`:t.join(", ")}function se(e,t){return t.includes(e)?null:t.length===0?"No values are currently allowed.":`${JSON.stringify(e)} is not an allowed value. Allowed values: ${Ee(t)}.`}function ht(e,t){const{schema:r}=t;if(r.type==="array"){if(!Array.isArray(e))return`Expected type "array", got "${C(e)}".`;for(let s=0;s<e.length;s++){const n=e[s];if(r.items?.type){const o=r.items.type==="number"?ie(n):C(n)!==r.items.type?`Expected type "${r.items.type}", got "${C(n)}".`:null;if(o)return`Array item at index ${s}: ${o[0].toLowerCase()}${o.slice(1)}`}if(r.items?.enum){const o=se(n,r.items.enum);if(o)return`Array item ${o}`}}return null}if(r.type==="number"){const s=ie(e);if(s)return s}else if(C(e)!==r.type)return`Expected type "${r.type}", got "${C(e)}".`;const i=_e(t);return i?se(e,i):null}function H(e){return e.clearable===!0&&e.schema.type==="string"}function _e(e){const t=e.schema.enum;if(t)return H(e)&&!t.includes("")?[...t,""]:t}function gt(e){const t={...e.schema,...e.schema.items?{items:{...e.schema.items}}:{},description:e.description};t.enum?.length===0&&delete t.enum,t.items?.enum?.length===0&&delete t.items.enum,H(e)&&(t.description=`${e.description} Pass "" to clear it.`);const r=_e(e);return r?.length&&(t.enum=r),t}function ft(e,t){const r=new Map(e.map(n=>[n.name,n])),i=e.map(n=>n.name),s=e.map(n=>`- "${n.name}": ${n.description}`).join(`
5
+ `);return{name:t.name,handler:async n=>{const o=[],a=[],l={};for(const[h,p]of Object.entries(n)){const m=r.get(h);if(!m){l[h]=`"${h}" is not a registered control. Available controls: ${Ee(i)}.`;continue}if(p==null||p===""&&!H(m))continue;const b=ht(p,m);if(b){l[h]=b;continue}if(m.get&&I(p,m.get())){a.push(h);continue}const E=await m.set(p);E?E.result==="rejected"?l[h]=E.reason||"The page rejected this field's update.":E.result==="unchanged"?a.push(h):o.push(h):o.push(h)}const d=Object.keys(l).length>0,u={success:!d,applied:o,unchanged:a,...d?{rejected:l}:{}},g=t.getResultBudget();if(!t.data)return re(u,g);const f=re(u,g-dt),w=await t.data.read(f),y={...f,data:w};return W(y)<=g?y:{...f,data:be}},description:(e.length>0?`Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
6
6
  ${s}`:"The current page has no editable state — nothing to change here.")+(t.data?`
7
- Returns the resulting page data once it has loaded: ${t.data.description}`:""),parameters:{type:"object",properties:Object.fromEntries(e.map(n=>[n.name,ut(n)])),required:[]},requiresApproval:t.requiresApproval,maxResultBytes:t.data?.maxResultBytes}}var ht=250,gt=3,ft=1e3,mt=24,pt=10,yt=50,vt=["mousemove","mousedown","keydown","scroll","touchstart"],Se=class{constructor(e={}){this.started=!1,this.teardowns=[],this.route="",this.routeEnteredAt=0,this.lastActivityAt=0,this.lastHeavyActivityAt=0,this.recentRoutes=[],this.routeBounces=0,this.rageClicks=0,this.jsErrors=0,this.fieldErrors={},this.recentClicks=[],this.signals=[],this.listeners=new Set,this.getPageState=e.getPageState,this.activityThrottleMs=e.activityThrottleMs??ht,this.rageClickCount=e.rageClickCount??gt,this.rageClickWindowMs=e.rageClickWindowMs??ft,this.rageClickRadiusPx=e.rageClickRadiusPx??mt,this.maxRecentRoutes=e.maxRecentRoutes??pt,this.maxSignals=e.maxSignals??yt}start(){if(this.started||typeof window>"u"||typeof document>"u")return;this.started=!0;const e=Date.now();this.route=this.currentPathname(),this.routeEnteredAt=e,this.lastActivityAt=e,this.recentRoutes=[this.route];const t=(i,s,n)=>{i.addEventListener(s,n,{passive:!0}),this.teardowns.push(()=>i.removeEventListener(s,n))},r=()=>this.recordActivity();for(const i of vt)t(window,i,r);t(document,"visibilitychange",()=>{document.visibilityState==="visible"&&this.recordActivity()}),t(window,"popstate",()=>this.checkRoute()),t(window,"hashchange",()=>this.checkRoute()),t(window,"click",i=>this.onClick(i)),c.log("SignalCollector started")}destroy(){for(const e of this.teardowns)e();this.teardowns=[],this.listeners.clear(),this.recentClicks=[],this.started=!1,c.log("SignalCollector destroyed")}signalFieldError(e){this.checkRoute();const t=(this.fieldErrors[e]??0)+1;this.fieldErrors[e]=t,this.pushSignal({type:"field_error",route:this.route,at:Date.now(),count:t,meta:{field:e}})}signalJsError(e){this.checkRoute(),this.jsErrors+=1,this.pushSignal({type:"js_error",route:this.route,at:Date.now(),count:this.jsErrors,meta:{kind:e}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSignals(){return[...this.signals]}getSnapshot(e){this.checkRoute();const t=Date.now();return{route:this.route,dwellMs:this.started?t-this.routeEnteredAt:0,idleMs:this.started?t-this.lastActivityAt:0,rageClicks:this.rageClicks,jsErrors:this.jsErrors,routeBounces:this.routeBounces,fieldErrors:{...this.fieldErrors},recentRoutes:[...this.recentRoutes],pageState:e?.pageState===!1?null:this.readPageState()}}currentPathname(){return typeof window<"u"&&window.location?window.location.pathname:""}readPageState(){if(!this.getPageState)return null;try{return this.getPageState()??null}catch(e){return c.warn("SignalCollector getPageState threw:",e),null}}recordActivity(){const e=Date.now();this.lastActivityAt=e,e-this.lastHeavyActivityAt>=this.activityThrottleMs&&(this.lastHeavyActivityAt=e,this.checkRoute())}checkRoute(){if(!this.started)return;const e=this.currentPathname();if(e===this.route)return;const t=Date.now(),r=this.route;this.route=e,this.routeEnteredAt=t,this.rageClicks=0,this.jsErrors=0,this.fieldErrors={},this.recentClicks=[],this.recentRoutes.push(e),this.recentRoutes.length>this.maxRecentRoutes&&this.recentRoutes.splice(0,this.recentRoutes.length-this.maxRecentRoutes),this.pushSignal({type:"route_change",route:e,at:t,meta:{from:r}});const i=this.recentRoutes,s=i.length;s>=4&&i[s-1]===i[s-3]&&i[s-2]===i[s-4]&&i[s-1]!==i[s-2]&&(this.routeBounces+=1,this.pushSignal({type:"route_bounce",route:e,at:t,count:this.routeBounces,meta:{between:`${i[s-2]}↔${i[s-1]}`}}))}onClick(e){this.recordActivity();const t=Date.now(),r=this.pageStateKey(),i={at:t,x:e.clientX,y:e.clientY,stateKey:r};this.recentClicks=this.recentClicks.filter(a=>t-a.at<=this.rageClickWindowMs);const s=this.recentClicks[0],n=!s||Math.abs(i.x-s.x)<=this.rageClickRadiusPx&&Math.abs(i.y-s.y)<=this.rageClickRadiusPx,o=!s||s.stateKey===r;if(!n||!o){this.recentClicks=[i];return}this.recentClicks.push(i),this.recentClicks.length>=this.rageClickCount&&(this.rageClicks+=1,this.recentClicks=[],this.pushSignal({type:"rage_click",route:this.route,at:t,count:this.rageClicks}))}pageStateKey(){const e=this.readPageState();if(!e)return"";try{return JSON.stringify(e)}catch{return""}}pushSignal(e){this.signals.push(e),this.signals.length>this.maxSignals&&this.signals.splice(0,this.signals.length-this.maxSignals);for(const t of this.listeners)try{t(e)}catch(r){c.error("Signal listener threw:",r)}}};function _e(e,t){const r=t?t.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let i=e;if(t&&r)try{const a=r.getItem(t.key);a!=null&&(i=JSON.parse(a))}catch{}const s=new Set,n=()=>s.forEach(a=>a(i));function o(){if(t&&r)try{r.setItem(t.key,JSON.stringify(i))}catch{}}return{get:()=>i,set:a=>{i=a,o(),n()},subscribe:a=>(s.add(a),()=>{s.delete(a)})}}var wt=6e4,bt=1440*60*1e3,Et="ago_proactive";function P(e){const t=new Date(e),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${r}-${i}`}var St=class{constructor(e={}){this.killSwitchEnabled=!1,this.engaged=!1,this.turnInFlight=!1,this.slotOccupied=!1,this.sessionCount=0,this.perSessionCap=e.frequencyCap?.perSession,this.perDayCap=e.frequencyCap?.perDay,this.store=_e({optOut:!1,lastFiredAt:{},dismissedAt:{},day:{date:P(Date.now()),count:0}},{key:e.storageKey??Et,storage:e.storage})}setKillSwitch(e){this.killSwitchEnabled=e}optOut(){this.store.set({...this.store.get(),optOut:!0})}optIn(){this.store.set({...this.store.get(),optOut:!1})}isOptedOut(){return this.store.get().optOut}setEngaged(e){this.engaged=e}setTurnInFlight(e){this.turnInFlight=e}isSlotOccupied(){return this.slotOccupied}occupySlot(){this.slotOccupied=!0}releaseSlot(){this.slotOccupied=!1}canFire(e,t=Date.now()){if(!this.killSwitchEnabled)return this.deny(e,"kill-switch (proactive disabled server-side)");const r=this.store.get();if(r.optOut)return this.deny(e,"user opted out");if(this.engaged)return this.deny(e,"user engaged (widget open)");if(this.turnInFlight)return this.deny(e,"message turn in flight");if(this.slotOccupied)return this.deny(e,"nudge slot occupied");const i=r.lastFiredAt[e.id],s=e.cooldownMs??wt;if(i!==void 0&&t-i<s)return this.deny(e,"cooldown");const n=r.dismissedAt[e.id],o=e.resurfaceAfterMs??bt;return n!==void 0&&t-n<o?this.deny(e,"dismissed recently"):this.perSessionCap!==void 0&&this.sessionCount>=this.perSessionCap?this.deny(e,"perSession cap"):this.perDayCap!==void 0&&this.dayCount(t)>=this.perDayCap?this.deny(e,"perDay cap"):!0}recordFired(e,t=Date.now()){const r=this.store.get();this.store.set({...r,lastFiredAt:{...r.lastFiredAt,[e]:t}})}recordNudgeShown(e=Date.now()){this.sessionCount+=1;const t=this.store.get(),r=P(e),i=t.day.date===r?{date:r,count:t.day.count+1}:{date:r,count:1};this.store.set({...t,day:i})}recordDismissed(e,t=Date.now()){const r=this.store.get();this.store.set({...r,dismissedAt:{...r.dismissedAt,[e]:t}})}dayCount(e){const t=this.store.get();return t.day.date===P(e)?t.day.count:0}deny(e,t){return c.debug(`NudgeGovernor: trigger "${e.id}" blocked — ${t}`),!1}};function I(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(Math.random()*16);return(e==="x"?t:t&3|8).toString(16)})}function _t(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ce(e,t){if(e==="*"||e===t)return!0;const r=e.split("/"),i=r.map((s,n)=>{const o=n===r.length-1;return s==="*"?o?"[^/]+(?:/[^/]+)*":"[^/]+":s.startsWith(":")?"[^/]+":_t(s)});return new RegExp("^"+i.join("/")+"/?$").test(t)}function X(e,t){return e===t?!0:e===null||t===null?!1:Array.isArray(e)?!Array.isArray(t)||t.length!==e.length?!1:e.every((r,i)=>T(r,t[i])):typeof e=="object"?typeof t!="object"||Array.isArray(t)?!1:Object.entries(e).every(([r,i])=>X(i,t[r])):!1}function Ae(e,t){if(e.route!==void 0&&!Ce(e.route,t.route)||e.idleMs!==void 0&&t.idleMs<e.idleMs||e.dwellMs!==void 0&&t.dwellMs<e.dwellMs||e.rageClicks!==void 0&&t.rageClicks<e.rageClicks||e.jsErrors!==void 0&&(t.jsErrors??0)<e.jsErrors||e.routeBounces!==void 0&&t.routeBounces<e.routeBounces)return!1;if(e.fieldErrors!==void 0){for(const[r,i]of Object.entries(e.fieldErrors))if((t.fieldErrors[r]??0)<i)return!1}return!(e.pageState!==void 0&&!X(e.pageState,t.pageState??{}))}var Ct=1e3,At="/api/sdk/v1/config",kt="/api/sdk/v1/proactive/evaluate",Rt=class{constructor(e){this.tickTimer=null,this.teardowns=[],this.started=!1,this.activeNudge=null,this.lastConversationId=null,this.shownIds=new Set,this.resolvedIds=new Set,this.lastEvaluationAt=0,this.client=e.client,this.collector=e.collector,this.governor=e.governor,this.tracker=e.tracker,this.options=e.options,this.tickMs=e.options.tickMs??Ct}start(){if(this.started)return;this.started=!0,this.options.enabledOverride!==void 0?this.governor.setKillSwitch(this.options.enabledOverride):this.loadKillSwitch();const e=s=>{s.conversationId&&(this.lastConversationId=s.conversationId),this.governor.setTurnInFlight(!0)},t=()=>this.governor.setTurnInFlight(!1),r=()=>this.governor.setTurnInFlight(!1),i=s=>{s?.id&&(this.lastConversationId=s.id)};this.client.on("message:start",e),this.client.on("message:complete",t),this.client.on("message:error",r),this.client.on("conversation:loaded",i),this.teardowns.push(()=>{this.client.off("message:start",e),this.client.off("message:complete",t),this.client.off("message:error",r),this.client.off("conversation:loaded",i)}),this.tickTimer=setInterval(()=>this.evaluate(),this.tickMs),this.teardowns.push(this.collector.subscribe(()=>{Date.now()-this.lastEvaluationAt>=this.tickMs&&this.evaluate()}))}stop(){this.tickTimer!==null&&(clearInterval(this.tickTimer),this.tickTimer=null);for(const e of this.teardowns)e();this.teardowns=[],this.started=!1}getActiveNudge(){return this.activeNudge}async loadKillSwitch(){try{const e=await this.client.getHttp().get(At);this.governor.setKillSwitch(e?.proactive?.enabled===!0)}catch(e){c.debug("Proactive config fetch failed; staying disabled:",e),this.governor.setKillSwitch(!1)}}evaluate(){if(this.lastEvaluationAt=Date.now(),typeof document<"u"&&document.visibilityState==="hidden"||this.governor.isSlotOccupied())return;const e=this.collector.getSnapshot();for(const t of this.options.triggers)if(Ae(t.when,e)&&this.governor.canFire(t)){this.fire(t);return}}fire(e){if(this.governor.recordFired(e.id),this.governor.occupySlot(),e.intervene==="agent"){this.evaluateWithAgent(e);return}this.setReady({id:I(),triggerId:e.id,source:"static",message:e.intervene.message,action:e.intervene.action,goal:e.goal,kickoff:e.kickoff,createdAt:new Date})}async evaluateWithAgent(e){const t=I(),r={client_nudge_id:t,trigger_id:e.id,goal:e.goal??"",agent:this.client.getConfiguredAgent(),signals:this.collector.getSnapshot(),client_context:this.client.getContextSnapshot()??{entries:{}},client_functions:this.client.getRegisteredFunctions()};let i;try{i=await this.client.getHttp().post(kt,r)}catch(s){c.debug("Proactive evaluate failed (treated as no-intervene):",s),this.governor.releaseSlot();return}if(!i?.intervene||!i.message){this.governor.releaseSlot();return}this.setReady({id:t,triggerId:e.id,source:"agent",message:i.message,action:Tt(i.action),goal:e.goal,kickoff:e.kickoff,createdAt:new Date,serverNudgeId:i.nudge_id})}setReady(e){this.activeNudge=e,this.client.emitProactiveEvent("nudge:ready",e)}shown(e){this.shownIds.has(e.id)||(this.shownIds.add(e.id),this.governor.recordNudgeShown(),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"shown",message:e.message,occurredAt:Date.now()}),this.client.emitProactiveEvent("nudge:shown",{nudge:e}))}dismiss(e){this.resolvedIds.has(e.id)||(this.resolvedIds.add(e.id),this.governor.recordDismissed(e.triggerId),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"dismissed",occurredAt:Date.now()}),this.clearActive(e),this.client.emitProactiveEvent("nudge:dismissed",{nudge:e}))}async accept(e){this.resolvedIds.has(e.id)||(this.resolvedIds.add(e.id),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"accepted",occurredAt:Date.now()}),this.clearActive(e),this.client.emitProactiveEvent("nudge:accepted",{nudge:e}),(e.source==="agent"||e.goal)&&(this.lastConversationId?this.client.sendMessage(It(e),{hidden:!0,conversationId:this.lastConversationId}).catch(t=>c.debug("Nudge kickoff message failed:",t)):e.kickoff?this.client.sendMessage(e.kickoff).catch(t=>c.debug("Nudge kickoff message failed:",t)):c.debug("Nudge accepted with no open conversation and no trigger.kickoff; skipping the chat pre-seed (a hidden message cannot open a conversation).")),e.action&&await this.runAction(e.action))}markConverted(e){this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"converted",occurredAt:Date.now()})}clearActive(e){this.activeNudge?.id===e.id&&(this.activeNudge=null),this.governor.releaseSlot()}async runAction(e){try{"functionName"in e?await this.client.executeClientFunction(e.functionName,e.arguments??{}):await this.client.executeClientFunction("setPageState",e.setPageState)}catch(t){c.warn("Nudge action failed:",t)}}};function Tt(e){if(e)return{label:e.label,functionName:e.function_name,arguments:e.arguments}}function It(e){const t=e.goal?` Goal: ${e.goal}.`:"";return`The user accepted a proactive nudge that said: "${e.message}".${t} Recent friction signals are in the client context (friction_signals). Start helping with this now: briefly explain what you can do and take the first concrete step.`}var xt=5e3,Ft="/api/sdk/v1/proactive/events",Pt=class{constructor(e){if(this.queue=[],this.flushTimer=null,this.teardowns=[],this.destroyed=!1,this.post=e.post,this.agent=e.agent,this.flushIntervalMs=e.flushIntervalMs??xt,typeof document<"u"){const t=()=>{document.visibilityState==="hidden"&&this.flush({keepalive:!0})};document.addEventListener("visibilitychange",t),this.teardowns.push(()=>document.removeEventListener("visibilitychange",t))}if(typeof window<"u"){const t=()=>this.flush({keepalive:!0});window.addEventListener("pagehide",t),this.teardowns.push(()=>window.removeEventListener("pagehide",t))}}track(e){this.destroyed||(this.queue.push(e),this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),this.flushIntervalMs)))}flush(e){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0)return;const t=this.queue;this.queue=[];const r={events:t.map(i=>({client_nudge_id:i.clientNudgeId,trigger_id:i.triggerId,source:i.source,type:i.type,...i.message!==void 0?{message:i.message}:{},...this.agent?{agent:this.agent}:{},occurred_at:new Date(i.occurredAt).toISOString()}))};this.post(Ft,r,e).catch(i=>{c.debug("Proactive event batch failed:",i)})}destroy(){if(!this.destroyed){this.flush({keepalive:!0}),this.destroyed=!0;for(const e of this.teardowns)e();this.teardowns=[]}}},ne="friction_signals";function B(e,t){e.proactive&&(c.warn("createAgoProactive: a proactive controller is already attached; replacing it."),e.proactive.destroy());const r=new Se({...t.signals,getPageState:()=>{const l=e.getContextSnapshot();if(!l)return null;const d={};for(const[u,g]of Object.entries(l.entries))u.startsWith("page-state:")&&g.data&&Object.assign(d,g.data);return Object.keys(d).length>0?d:null}});r.start();const i=l=>{r.signalJsError(l.type)};e.on("error:captured",i),e.addDynamicContext(ne,()=>{const{pageState:l,...d}=r.getSnapshot({pageState:!1});return{name:"Friction signals",description:"Behavioral friction observed on the current page: dwell/idle times, rage clicks, route bounces, repeated field errors, JavaScript error count (names and counters only).",data:d}});const s=new St({frequencyCap:t.frequencyCap,storage:t.storage,storageKey:t.storageKey}),n=new Pt({post:(l,d,u)=>e.getHttp().post(l,d,u),agent:e.getConfiguredAgent()}),o=new Rt({client:e,collector:r,governor:s,tracker:n,options:t});o.start();const a={optOut:()=>s.optOut(),optIn:()=>s.optIn(),isOptedOut:()=>s.isOptedOut(),setEngaged:l=>s.setEngaged(l),signalFieldError:l=>r.signalFieldError(l),getSignalsSnapshot:()=>r.getSnapshot(),getActiveNudge:()=>o.getActiveNudge(),shown:l=>o.shown(l),accept:l=>o.accept(l),dismiss:l=>o.dismiss(l),markConverted:l=>o.markConverted(l),destroy:()=>{o.stop(),n.destroy(),e.off("error:captured",i),r.destroy(),e.removeDynamicContext(ne),e.proactive===a&&(e.proactive=null)}};return e.proactive=a,a}var ke=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),c.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&c.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),c.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&c.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,r]of this.entries)e[t]=r;for(const[t,r]of this.dynamicProviders)try{const i=r();i&&(e[t]=i)}catch(i){c.error(`DynamicContext provider "${t}" threw:`,i)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),c.log("ClientContext cleared")}},Dt="page-state:";function Ot(e){const t={};for(const[r,i]of Object.entries(e))r.startsWith(Dt)&&i.data&&Object.assign(t,i.data);return t}function Mt(e){const t=e["current-page"]?.data;return t?.page?t.page:t?.url?t.url:e["browser-page"]?.data?.url}function $t(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Nt(e,t){const r=[];for(const i of Object.keys(t))i in e&&($t(e[i],t[i])||r.push({field:i,from:e[i],to:t[i]}));return r}function jt(e,t){const r=Ot(t),i=Mt(t);return{changes:e&&e.page===i?Nt(e.state,r):[],baseline:{page:i,state:r}}}function q(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(q).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${q(e[t])}`).join(",")}}`}var oe="",Re=class{constructor(e,t={}){this.callbacks=e,this.options=t,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.waitingClientEmitted=!1,this.firedClientFunctions=new Map}async processStream(e){if(!e.body)throw new v.AgoStreamError("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(),r=new TextDecoder;try{for(;;){const{done:i,value:s}=await t.read();if(i)break;const n=r.decode(s,{stream:!0});this.buffer+=n,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(i){if(this.options.signal?.aborted)return this.message.status="CANCELED",this.buildFinalMessage();const s=i instanceof Error?i:new v.AgoStreamError("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(`
7
+ Returns the resulting page data once it has loaded: ${t.data.description}`:""),parameters:{type:"object",properties:Object.fromEntries(e.map(n=>[n.name,gt(n)])),required:[]},requiresApproval:t.requiresApproval,maxResultBytes:t.data?.maxResultBytes}}var mt=250,pt=3,yt=1e3,vt=24,wt=10,bt=50,Et=["mousemove","mousedown","keydown","scroll","touchstart"],Se=class{constructor(e={}){this.started=!1,this.teardowns=[],this.route="",this.routeEnteredAt=0,this.lastActivityAt=0,this.lastHeavyActivityAt=0,this.recentRoutes=[],this.routeBounces=0,this.rageClicks=0,this.jsErrors=0,this.fieldErrors={},this.recentClicks=[],this.signals=[],this.listeners=new Set,this.getPageState=e.getPageState,this.activityThrottleMs=e.activityThrottleMs??mt,this.rageClickCount=e.rageClickCount??pt,this.rageClickWindowMs=e.rageClickWindowMs??yt,this.rageClickRadiusPx=e.rageClickRadiusPx??vt,this.maxRecentRoutes=e.maxRecentRoutes??wt,this.maxSignals=e.maxSignals??bt}start(){if(this.started||typeof window>"u"||typeof document>"u")return;this.started=!0;const e=Date.now();this.route=this.currentPathname(),this.routeEnteredAt=e,this.lastActivityAt=e,this.recentRoutes=[this.route];const t=(i,s,n)=>{i.addEventListener(s,n,{passive:!0}),this.teardowns.push(()=>i.removeEventListener(s,n))},r=()=>this.recordActivity();for(const i of Et)t(window,i,r);t(document,"visibilitychange",()=>{document.visibilityState==="visible"&&this.recordActivity()}),t(window,"popstate",()=>this.checkRoute()),t(window,"hashchange",()=>this.checkRoute()),t(window,"click",i=>this.onClick(i)),c.log("SignalCollector started")}destroy(){for(const e of this.teardowns)e();this.teardowns=[],this.listeners.clear(),this.recentClicks=[],this.started=!1,c.log("SignalCollector destroyed")}signalFieldError(e){this.checkRoute();const t=(this.fieldErrors[e]??0)+1;this.fieldErrors[e]=t,this.pushSignal({type:"field_error",route:this.route,at:Date.now(),count:t,meta:{field:e}})}signalJsError(e){this.checkRoute(),this.jsErrors+=1,this.pushSignal({type:"js_error",route:this.route,at:Date.now(),count:this.jsErrors,meta:{kind:e}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSignals(){return[...this.signals]}getSnapshot(e){this.checkRoute();const t=Date.now();return{route:this.route,dwellMs:this.started?t-this.routeEnteredAt:0,idleMs:this.started?t-this.lastActivityAt:0,rageClicks:this.rageClicks,jsErrors:this.jsErrors,routeBounces:this.routeBounces,fieldErrors:{...this.fieldErrors},recentRoutes:[...this.recentRoutes],pageState:e?.pageState===!1?null:this.readPageState()}}currentPathname(){return typeof window<"u"&&window.location?window.location.pathname:""}readPageState(){if(!this.getPageState)return null;try{return this.getPageState()??null}catch(e){return c.warn("SignalCollector getPageState threw:",e),null}}recordActivity(){const e=Date.now();this.lastActivityAt=e,e-this.lastHeavyActivityAt>=this.activityThrottleMs&&(this.lastHeavyActivityAt=e,this.checkRoute())}checkRoute(){if(!this.started)return;const e=this.currentPathname();if(e===this.route)return;const t=Date.now(),r=this.route;this.route=e,this.routeEnteredAt=t,this.rageClicks=0,this.jsErrors=0,this.fieldErrors={},this.recentClicks=[],this.recentRoutes.push(e),this.recentRoutes.length>this.maxRecentRoutes&&this.recentRoutes.splice(0,this.recentRoutes.length-this.maxRecentRoutes),this.pushSignal({type:"route_change",route:e,at:t,meta:{from:r}});const i=this.recentRoutes,s=i.length;s>=4&&i[s-1]===i[s-3]&&i[s-2]===i[s-4]&&i[s-1]!==i[s-2]&&(this.routeBounces+=1,this.pushSignal({type:"route_bounce",route:e,at:t,count:this.routeBounces,meta:{between:`${i[s-2]}↔${i[s-1]}`}}))}onClick(e){this.recordActivity();const t=Date.now(),r=this.pageStateKey(),i={at:t,x:e.clientX,y:e.clientY,stateKey:r};this.recentClicks=this.recentClicks.filter(a=>t-a.at<=this.rageClickWindowMs);const s=this.recentClicks[0],n=!s||Math.abs(i.x-s.x)<=this.rageClickRadiusPx&&Math.abs(i.y-s.y)<=this.rageClickRadiusPx,o=!s||s.stateKey===r;if(!n||!o){this.recentClicks=[i];return}this.recentClicks.push(i),this.recentClicks.length>=this.rageClickCount&&(this.rageClicks+=1,this.recentClicks=[],this.pushSignal({type:"rage_click",route:this.route,at:t,count:this.rageClicks}))}pageStateKey(){const e=this.readPageState();if(!e)return"";try{return JSON.stringify(e)}catch{return""}}pushSignal(e){this.signals.push(e),this.signals.length>this.maxSignals&&this.signals.splice(0,this.signals.length-this.maxSignals);for(const t of this.listeners)try{t(e)}catch(r){c.error("Signal listener threw:",r)}}};function Ce(e,t){const r=t?t.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let i=e;if(t&&r)try{const a=r.getItem(t.key);a!=null&&(i=JSON.parse(a))}catch{}const s=new Set,n=()=>s.forEach(a=>a(i));function o(){if(t&&r)try{r.setItem(t.key,JSON.stringify(i))}catch{}}return{get:()=>i,set:a=>{i=a,o(),n()},subscribe:a=>(s.add(a),()=>{s.delete(a)})}}var _t=6e4,St=1440*60*1e3,Ct="ago_proactive";function D(e){const t=new Date(e),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${r}-${i}`}var At=class{constructor(e={}){this.killSwitchEnabled=!1,this.engaged=!1,this.turnInFlight=!1,this.slotOccupied=!1,this.sessionCount=0,this.perSessionCap=e.frequencyCap?.perSession,this.perDayCap=e.frequencyCap?.perDay,this.store=Ce({optOut:!1,lastFiredAt:{},dismissedAt:{},day:{date:D(Date.now()),count:0}},{key:e.storageKey??Ct,storage:e.storage})}setKillSwitch(e){this.killSwitchEnabled=e}optOut(){this.store.set({...this.store.get(),optOut:!0})}optIn(){this.store.set({...this.store.get(),optOut:!1})}isOptedOut(){return this.store.get().optOut}setEngaged(e){this.engaged=e}setTurnInFlight(e){this.turnInFlight=e}isSlotOccupied(){return this.slotOccupied}occupySlot(){this.slotOccupied=!0}releaseSlot(){this.slotOccupied=!1}canFire(e,t=Date.now()){if(!this.killSwitchEnabled)return this.deny(e,"kill-switch (proactive disabled server-side)");const r=this.store.get();if(r.optOut)return this.deny(e,"user opted out");if(this.engaged)return this.deny(e,"user engaged (widget open)");if(this.turnInFlight)return this.deny(e,"message turn in flight");if(this.slotOccupied)return this.deny(e,"nudge slot occupied");const i=r.lastFiredAt[e.id],s=e.cooldownMs??_t;if(i!==void 0&&t-i<s)return this.deny(e,"cooldown");const n=r.dismissedAt[e.id],o=e.resurfaceAfterMs??St;return n!==void 0&&t-n<o?this.deny(e,"dismissed recently"):this.perSessionCap!==void 0&&this.sessionCount>=this.perSessionCap?this.deny(e,"perSession cap"):this.perDayCap!==void 0&&this.dayCount(t)>=this.perDayCap?this.deny(e,"perDay cap"):!0}recordFired(e,t=Date.now()){const r=this.store.get();this.store.set({...r,lastFiredAt:{...r.lastFiredAt,[e]:t}})}recordNudgeShown(e=Date.now()){this.sessionCount+=1;const t=this.store.get(),r=D(e),i=t.day.date===r?{date:r,count:t.day.count+1}:{date:r,count:1};this.store.set({...t,day:i})}recordDismissed(e,t=Date.now()){const r=this.store.get();this.store.set({...r,dismissedAt:{...r.dismissedAt,[e]:t}})}dayCount(e){const t=this.store.get();return t.day.date===D(e)?t.day.count:0}deny(e,t){return c.debug(`NudgeGovernor: trigger "${e.id}" blocked — ${t}`),!1}};function x(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(Math.random()*16);return(e==="x"?t:t&3|8).toString(16)})}function kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ae(e,t){if(e==="*"||e===t)return!0;const r=e.split("/"),i=r.map((s,n)=>{const o=n===r.length-1;return s==="*"?o?"[^/]+(?:/[^/]+)*":"[^/]+":s.startsWith(":")?"[^/]+":kt(s)});return new RegExp("^"+i.join("/")+"/?$").test(t)}function X(e,t){return e===t?!0:e===null||t===null?!1:Array.isArray(e)?!Array.isArray(t)||t.length!==e.length?!1:e.every((r,i)=>I(r,t[i])):typeof e=="object"?typeof t!="object"||Array.isArray(t)?!1:Object.entries(e).every(([r,i])=>X(i,t[r])):!1}function ke(e,t){if(e.route!==void 0&&!Ae(e.route,t.route)||e.idleMs!==void 0&&t.idleMs<e.idleMs||e.dwellMs!==void 0&&t.dwellMs<e.dwellMs||e.rageClicks!==void 0&&t.rageClicks<e.rageClicks||e.jsErrors!==void 0&&(t.jsErrors??0)<e.jsErrors||e.routeBounces!==void 0&&t.routeBounces<e.routeBounces)return!1;if(e.fieldErrors!==void 0){for(const[r,i]of Object.entries(e.fieldErrors))if((t.fieldErrors[r]??0)<i)return!1}return!(e.pageState!==void 0&&!X(e.pageState,t.pageState??{}))}var Rt=1e3,Tt="/api/sdk/v1/config",It="/api/sdk/v1/proactive/evaluate",xt=class{constructor(e){this.tickTimer=null,this.teardowns=[],this.started=!1,this.activeNudge=null,this.lastConversationId=null,this.shownIds=new Set,this.resolvedIds=new Set,this.lastEvaluationAt=0,this.client=e.client,this.collector=e.collector,this.governor=e.governor,this.tracker=e.tracker,this.options=e.options,this.tickMs=e.options.tickMs??Rt}start(){if(this.started)return;this.started=!0,this.options.enabledOverride!==void 0?this.governor.setKillSwitch(this.options.enabledOverride):this.loadKillSwitch();const e=s=>{s.conversationId&&(this.lastConversationId=s.conversationId),this.governor.setTurnInFlight(!0)},t=()=>this.governor.setTurnInFlight(!1),r=()=>this.governor.setTurnInFlight(!1),i=s=>{s?.id&&(this.lastConversationId=s.id)};this.client.on("message:start",e),this.client.on("message:complete",t),this.client.on("message:error",r),this.client.on("conversation:loaded",i),this.teardowns.push(()=>{this.client.off("message:start",e),this.client.off("message:complete",t),this.client.off("message:error",r),this.client.off("conversation:loaded",i)}),this.tickTimer=setInterval(()=>this.evaluate(),this.tickMs),this.teardowns.push(this.collector.subscribe(()=>{Date.now()-this.lastEvaluationAt>=this.tickMs&&this.evaluate()}))}stop(){this.tickTimer!==null&&(clearInterval(this.tickTimer),this.tickTimer=null);for(const e of this.teardowns)e();this.teardowns=[],this.started=!1}getActiveNudge(){return this.activeNudge}async loadKillSwitch(){try{const e=await this.client.getHttp().get(Tt);this.governor.setKillSwitch(e?.proactive?.enabled===!0)}catch(e){c.debug("Proactive config fetch failed; staying disabled:",e),this.governor.setKillSwitch(!1)}}evaluate(){if(this.lastEvaluationAt=Date.now(),typeof document<"u"&&document.visibilityState==="hidden"||this.governor.isSlotOccupied())return;const e=this.collector.getSnapshot();for(const t of this.options.triggers)if(ke(t.when,e)&&this.governor.canFire(t)){this.fire(t);return}}fire(e){if(this.governor.recordFired(e.id),this.governor.occupySlot(),e.intervene==="agent"){this.evaluateWithAgent(e);return}this.setReady({id:x(),triggerId:e.id,source:"static",message:e.intervene.message,action:e.intervene.action,goal:e.goal,kickoff:e.kickoff,createdAt:new Date})}async evaluateWithAgent(e){const t=x(),r={client_nudge_id:t,trigger_id:e.id,goal:e.goal??"",agent:this.client.getConfiguredAgent(),signals:this.collector.getSnapshot(),client_context:this.client.getContextSnapshot()??{entries:{}},client_functions:this.client.getRegisteredFunctions()};let i;try{i=await this.client.getHttp().post(It,r)}catch(s){c.debug("Proactive evaluate failed (treated as no-intervene):",s),this.governor.releaseSlot();return}if(!i?.intervene||!i.message){this.governor.releaseSlot();return}this.setReady({id:t,triggerId:e.id,source:"agent",message:i.message,action:Ft(i.action),goal:e.goal,kickoff:e.kickoff,createdAt:new Date,serverNudgeId:i.nudge_id})}setReady(e){this.activeNudge=e,this.client.emitProactiveEvent("nudge:ready",e)}shown(e){this.shownIds.has(e.id)||(this.shownIds.add(e.id),this.governor.recordNudgeShown(),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"shown",message:e.message,occurredAt:Date.now()}),this.client.emitProactiveEvent("nudge:shown",{nudge:e}))}dismiss(e){this.resolvedIds.has(e.id)||(this.resolvedIds.add(e.id),this.governor.recordDismissed(e.triggerId),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"dismissed",occurredAt:Date.now()}),this.clearActive(e),this.client.emitProactiveEvent("nudge:dismissed",{nudge:e}))}async accept(e){this.resolvedIds.has(e.id)||(this.resolvedIds.add(e.id),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"accepted",occurredAt:Date.now()}),this.clearActive(e),this.client.emitProactiveEvent("nudge:accepted",{nudge:e}),(e.source==="agent"||e.goal)&&(this.lastConversationId?this.client.sendMessage(Pt(e),{hidden:!0,conversationId:this.lastConversationId}).catch(t=>c.debug("Nudge kickoff message failed:",t)):e.kickoff?this.client.sendMessage(e.kickoff).catch(t=>c.debug("Nudge kickoff message failed:",t)):c.debug("Nudge accepted with no open conversation and no trigger.kickoff; skipping the chat pre-seed (a hidden message cannot open a conversation).")),e.action&&await this.runAction(e.action))}markConverted(e){this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"converted",occurredAt:Date.now()})}clearActive(e){this.activeNudge?.id===e.id&&(this.activeNudge=null),this.governor.releaseSlot()}async runAction(e){try{"functionName"in e?await this.client.executeClientFunction(e.functionName,e.arguments??{}):await this.client.executeClientFunction("setPageState",e.setPageState)}catch(t){c.warn("Nudge action failed:",t)}}};function Ft(e){if(e)return{label:e.label,functionName:e.function_name,arguments:e.arguments}}function Pt(e){const t=e.goal?` Goal: ${e.goal}.`:"";return`The user accepted a proactive nudge that said: "${e.message}".${t} Recent friction signals are in the client context (friction_signals). Start helping with this now: briefly explain what you can do and take the first concrete step.`}var Dt=5e3,Ot="/api/sdk/v1/proactive/events",Mt=class{constructor(e){if(this.queue=[],this.flushTimer=null,this.teardowns=[],this.destroyed=!1,this.post=e.post,this.agent=e.agent,this.flushIntervalMs=e.flushIntervalMs??Dt,typeof document<"u"){const t=()=>{document.visibilityState==="hidden"&&this.flush({keepalive:!0})};document.addEventListener("visibilitychange",t),this.teardowns.push(()=>document.removeEventListener("visibilitychange",t))}if(typeof window<"u"){const t=()=>this.flush({keepalive:!0});window.addEventListener("pagehide",t),this.teardowns.push(()=>window.removeEventListener("pagehide",t))}}track(e){this.destroyed||(this.queue.push(e),this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),this.flushIntervalMs)))}flush(e){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0)return;const t=this.queue;this.queue=[];const r={events:t.map(i=>({client_nudge_id:i.clientNudgeId,trigger_id:i.triggerId,source:i.source,type:i.type,...i.message!==void 0?{message:i.message}:{},...this.agent?{agent:this.agent}:{},occurred_at:new Date(i.occurredAt).toISOString()}))};this.post(Ot,r,e).catch(i=>{c.debug("Proactive event batch failed:",i)})}destroy(){if(!this.destroyed){this.flush({keepalive:!0}),this.destroyed=!0;for(const e of this.teardowns)e();this.teardowns=[]}}},ne="friction_signals";function B(e,t){e.proactive&&(c.warn("createAgoProactive: a proactive controller is already attached; replacing it."),e.proactive.destroy());const r=new Se({...t.signals,getPageState:()=>{const l=e.getContextSnapshot();if(!l)return null;const d={};for(const[u,g]of Object.entries(l.entries))u.startsWith("page-state:")&&g.data&&Object.assign(d,g.data);return Object.keys(d).length>0?d:null}});r.start();const i=l=>{r.signalJsError(l.type)};e.on("error:captured",i),e.addDynamicContext(ne,()=>{const{pageState:l,...d}=r.getSnapshot({pageState:!1});return{name:"Friction signals",description:"Behavioral friction observed on the current page: dwell/idle times, rage clicks, route bounces, repeated field errors, JavaScript error count (names and counters only).",data:d}});const s=new At({frequencyCap:t.frequencyCap,storage:t.storage,storageKey:t.storageKey}),n=new Mt({post:(l,d,u)=>e.getHttp().post(l,d,u),agent:e.getConfiguredAgent()}),o=new xt({client:e,collector:r,governor:s,tracker:n,options:t});o.start();const a={optOut:()=>s.optOut(),optIn:()=>s.optIn(),isOptedOut:()=>s.isOptedOut(),setEngaged:l=>s.setEngaged(l),signalFieldError:l=>r.signalFieldError(l),getSignalsSnapshot:()=>r.getSnapshot(),getActiveNudge:()=>o.getActiveNudge(),shown:l=>o.shown(l),accept:l=>o.accept(l),dismiss:l=>o.dismiss(l),markConverted:l=>o.markConverted(l),destroy:()=>{o.stop(),n.destroy(),e.off("error:captured",i),r.destroy(),e.removeDynamicContext(ne),e.proactive===a&&(e.proactive=null)}};return e.proactive=a,a}var Re=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),c.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&c.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),c.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&c.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,r]of this.entries)e[t]=r;for(const[t,r]of this.dynamicProviders)try{const i=r();i&&(e[t]=i)}catch(i){c.error(`DynamicContext provider "${t}" threw:`,i)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),c.log("ClientContext cleared")}},$t="page-state:";function Nt(e){const t={};for(const[r,i]of Object.entries(e))r.startsWith($t)&&i.data&&Object.assign(t,i.data);return t}function jt(e){const t=e["current-page"]?.data;return t?.page?t.page:t?.url?t.url:e["browser-page"]?.data?.url}function Lt(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Ut(e,t){const r=[];for(const i of Object.keys(t))i in e&&(Lt(e[i],t[i])||r.push({field:i,from:e[i],to:t[i]}));return r}function Wt(e,t){const r=Nt(t),i=jt(t);return{changes:e&&e.page===i?Ut(e.state,r):[],baseline:{page:i,state:r}}}function G(e){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(",")}}`}var oe="",Te=class{constructor(e,t={}){this.callbacks=e,this.options=t,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.waitingClientEmitted=!1,this.firedClientFunctions=new Map}async processStream(e){if(!e.body)throw new v.AgoStreamError("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(),r=new TextDecoder;try{for(;;){const{done:i,value:s}=await t.read();if(i)break;const n=r.decode(s,{stream:!0});this.buffer+=n,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(i){if(this.options.signal?.aborted)return this.message.status="CANCELED",this.buildFinalMessage();const s=i instanceof Error?i:new v.AgoStreamError("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(`
8
8
 
9
9
  `);this.buffer=e.pop()||"";for(const t of e){if(!t.trim())continue;const r=t.split(`
10
- `);for(const i of r)if(!i.startsWith(": ")&&i.startsWith("data: ")){const s=i.slice(6);try{const n=JSON.parse(s);this.handleChunk(n)}catch(n){c.warn("Failed to parse SSE data:",s,n)}}}}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.title&&this.message.conversationId&&this.callbacks.onTitle?.({conversationId:this.message.conversationId,title:e.title}),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 r=t.knowledge_document;return{id:r.id,title:r.title,url:r.use_external_link?r.external_link_url:r.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${q(e.arguments??{})}`,r=e.id||"",i=this.firedClientFunctions.get(t);let s=!1;i?r&&!i.has(r)&&(i.has(oe)?(i.delete(oe),i.add(r)):(i.add(r),s=!0)):(this.firedClientFunctions.set(t,new Set([r])),s=!0),s&&this.callbacks.onClientFunction?.({invocationId:r,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 r=this.toolCalls.findIndex(i=>i.id===t.id);r>=0?this.toolCalls[r]=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())),this.message.status==="WAITING_CLIENT"&&!this.waitingClientEmitted&&this.message.id&&(this.waitingClientEmitted=!0,this.callbacks.onWaitingClient?.({conversationId:this.message.conversationId||"",messageId:this.message.id,waitingToolCallIds:e.waiting_tool_call_ids??[]}))}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,displayMode:e.display_mode,askToTalkToHuman:e.ask_to_talk_to_human,allowedToCreateTicket:e.allowed_to_create_ticket,ticket:e.ticket,mode:e.mode,ticketFormId:e.ticket_form_id,embedHtml:e.embed_html,embedDescription:e.embed_description}}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 e.status!=="WAITING_CLIENT"&&this.callbacks.onComplete?.(e),e}};function Lt(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var Ut=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function Te(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const r=new URL(e,t);if(r.protocol==="http:"||r.protocol==="https:"||r.protocol==="blob:")return e}catch{}}function Wt(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&Te(e.url)!==void 0}function Bt(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 qt(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 Gt(e){return e.map((t,r)=>({id:`local-${r}-${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:Ut.has(t.type)}))}var Ie=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 r=this.handlers.get(e);r&&r.delete(t)}emit(e,t){const r=this.handlers.get(e);r&&r.forEach(i=>{try{i(t)}catch(s){console.error(`Error in event handler for ${String(e)}:`,s)}})}once(e,t){const r=(i=>{this.off(e,r),t(i)});this.on(e,r)}waitFor(e,t){return new Promise((r,i)=>{let s;const n=(o=>{s&&clearTimeout(s),r(o)});this.once(e,n),t?.timeout&&(s=setTimeout(()=>{this.off(e,n),i(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},Kt=4e3,Jt=150,Ht=600;function Xt(){if(!(typeof document>"u"))return document.modelContext}function zt(e,t){return new Promise(r=>{let i,s=!1;const n=()=>{if(!s){s=!0,clearTimeout(i),clearTimeout(l),clearTimeout(a);for(const u of t)u?.removeEventListener("abort",n);d(),r()}},o=()=>{clearTimeout(l),clearTimeout(i),i=setTimeout(n,Jt)},a=setTimeout(n,Kt),l=setTimeout(n,Ht),d=e(o);for(const u of t){if(u?.aborted)return n();u?.addEventListener("abort",n)}})}function Vt(e){const t=Xt();if(!t)return c.log("WebMCP is not available in this browser; bridge not attached"),()=>{};const r=t,i=new Map,s=new Set,n=new AbortController;let o=!1,a=!1;function l(y){return JSON.stringify([y.description,y.inputSchema,y.annotations])}function d(y,h){const p=e.getFunctionRegistrations().find(m=>m.name===y)?.webmcp;return!p||!p.navigates?!1:h?.success!==!1}function u(){const y=new Map;for(const h of e.getFunctionRegistrations()){if(h.webmcp===!1)continue;const p=h.webmcp||void 0,m=h.name,b={name:m,description:h.schema.description,inputSchema:h.schema.parameters,annotations:p?.annotations,execute:async(E,xe)=>{const z=await e.runExternalFunction(m,E??{});return!o&&d(m,z)&&await zt(Fe=>e.onFunctionsChanged(Fe),[xe?.signal,n.signal]),z}};y.set(m,{tool:b,signature:l(b)})}return y}function g(){o||a||(a=!0,queueMicrotask(()=>{a=!1,f()}))}function f(){if(o)return;const y=u();for(const[h,p]of i)y.get(h)?.signature!==p.signature&&(p.controller.abort(),i.delete(h));for(const[h,p]of y){if(i.has(h))continue;const m=new AbortController;i.set(h,{signature:p.signature,controller:m}),Promise.resolve(r.registerTool(p.tool,{signal:m.signal})).catch(b=>{if(c.error(`WebMCP rejected the tool "${h}":`,b),i.get(h)?.controller!==m)return;i.delete(h);const E=JSON.stringify([h,p.signature]);s.has(E)||(s.add(E),g())})}}const w=e.onFunctionsChanged(g);return f(),c.log("WebMCP bridge attached"),()=>{if(!o){o=!0,n.abort(),w();for(const y of i.values())y.controller.abort();i.clear(),c.log("WebMCP bridge detached")}}}var Yt="/api/sdk/v1/client-function-calls",ae="ago_webmcp_tab";function Qt(){try{const e=sessionStorage.getItem(ae);if(e)return e;const t=I();return sessionStorage.setItem(ae,t),t}catch{return}}function Zt(e,t){const{name:r}=t.schema,i=Qt(),s={function_name:r,arguments:t.args,result:t.error===void 0?t.result??null:null,error:t.error??null,duration_ms:t.durationMs,...i?{tab_id:i}:{},...e.declared.has(r)?{}:{client_functions:[t.schema]}};e.post(Yt,s,t.navigates?{keepalive:!0}:void 0).then(()=>{e.declared.add(r)}).catch(n=>{c.debug("External call report failed:",n)})}var ce='`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the public demo account https://playground.api.useago.com (agent generic-guide). See docs/general/configuration.md#error-codes (config_missing_base_url).',er=/^[a-z][a-z0-9+.-]*:\/\//i,le=!1;function G(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new v.AgoError(`${t}: ${ce}`,"config_missing_base_url");const r=e.baseUrl;if(typeof r!="string"||r.trim()==="")throw new v.AgoError(`${t}: ${ce}`,"config_missing_base_url");O(e.language),!r.startsWith("/")&&!er.test(r)&&(le||(le=!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 tr="activity:recent",rr="state:delta",ue="errors:recent";function de(e){return e==="setPageState"?"readPageData":`read${e.charAt(0).toUpperCase()}${e.slice(1)}Data`}var ir=class k{constructor(t){this.errorWatcher=null,this.lastSentPageState=null,this.warnedEmptyConversations=new Set,this.declaredExternally=new Set,this.warnedPageDataPlaceholder=!1,this.pageDataCompanions=new Set,this.pendingResumes=new Map,this.pendingApprovals=new Map,this.resumeGate=null,this.activeTurn=null,this.pausedTurn=null,this.stoppedTurnIds=new Set,this.proactive=null,this.detachWebMCP=null,this.listPagesRegistered=!1,G(t,"AgoClient"),this.config=t,this.activityLedger=new ge(t.maxActivityEntries),this.httpClient=new $e(t),this.functionRegistry=new pe({maxResultBytes:t.maxFunctionResultBytes}),this.contextRegistry=new ke,this.eventEmitter=new Ie,this.registerActivityContext(),this.functionRegistry.onChange(()=>{this.eventEmitter.emit("functions:changed",this.functionRegistry.getSchemas())}),t.debug&&c.enable(),t.errorWatcher&&this.enableErrorWatcher(t.errorWatcher===!0?void 0:t.errorWatcher),t.proactive&&B(this,t.proactive),this.attachWebMCPBridge(),c.log("AgoClient initialized")}attachWebMCPBridge(){!this.config.webmcp||this.detachWebMCP||(this.detachWebMCP=Vt(this))}async sendMessage(t,r){if(typeof t!="string"||!t.trim())throw new v.AgoError("Add message text before sending, including when attaching files. See docs/general/core.md#file-attachments.","message_empty_content");const i=this.functionRegistry.getSchemas(),s=this.buildSendContext(),n=this.config.agent||this.config.defaultAgentId,o=this.resolveClientFunctionsMode(r),a=r?.metadata!==void 0?r.metadata:this.config.metadata,l=a!=null?JSON.stringify(a):void 0,d={content:t,conversation_id:r?.conversationId,agent_id:r?.agentId||n};a!=null&&(d.metadata=a),i.length>0&&(d.client_functions=i,o==="pause"&&(d.client_functions_mode=o)),s&&(d.client_context=s),r?.hidden&&(d.hidden=!0);const u=this.beginTurn();let g;if(r?.files&&r.files.length>0){const f=new FormData;f.append("content",t),l!==void 0&&f.append("metadata",l),r.conversationId&&f.append("conversation_id",r.conversationId),(r.agentId||n)&&f.append("agent_id",r.agentId||n||""),i.length>0&&(f.append("client_functions",JSON.stringify(i)),o==="pause"&&f.append("client_functions_mode",o)),s&&f.append("client_context",JSON.stringify(s)),r.hidden&&f.append("hidden","true");for(const w of r.files)f.append("files",w);g=await this.sendRequest(u,()=>this.httpClient.postFormData("/api/sdk/v1/messages",f,{signal:u.controller.signal}))}else g=await this.sendRequest(u,()=>this.httpClient.postStream("/api/sdk/v1/messages",d,{signal:u.controller.signal}));return g?this.processSSEResponse(g,u):this.buildStoppedMessage(u)}async sendRequest(t,r){try{return await r()}catch(i){if(this.endTurn(t),M(i))return null;throw i}}async processSSEResponse(t,r){let i=!1;const s=new Re({onRawChunk:n=>{r&&(n.message_id&&!r.messageId&&(r.messageId=n.message_id),n.thread?.id&&(r.conversationId=n.thread.id)),this.eventEmitter.emit("stream:message",n)},onStart:n=>{this.eventEmitter.emit("message:start",n)},onChunk:n=>{this.eventEmitter.emit("message:chunk",n)},onToolCall:n=>{this.eventEmitter.emit("toolCall:received",n),n.type==="form"&&this.eventEmitter.emit("toolCall:form",n)},onClientFunction:async n=>{if(i=!0,this.eventEmitter.emit("function:invoke",n),this.recordAgentAction(n),n.invocationId&&this.requiresApproval(n)){this.pendingApprovals.set(n.invocationId,n),this.eventEmitter.emit("function:awaiting-approval",n);return}await this.handleClientFunctionInvocation(n)},onTitle:n=>{this.eventEmitter.emit("conversation:title",n)},onAnswerComplete:n=>{this.eventEmitter.emit("message:answer-complete",n)},onWaitingClient:n=>{this.pausedTurn={messageId:n.messageId,conversationId:n.conversationId},this.eventEmitter.emit("message:waiting-client",n),this.markResumeSignal(n.messageId,n.conversationId,"waitingConfirmed")},onComplete:n=>{r?.stopRequested&&!n.id||this.eventEmitter.emit("message:complete",n)},onError:n=>{this.eventEmitter.emit("message:error",{error:n.message,code:n instanceof v.AgoError?n.code:void 0})}},{signal:r?.controller.signal});try{const n=await s.processStream(t);return r?.stopRequested&&(this.postStopForTurn(r,r.messageId??n.id),this.eventEmitter.emit("message:stopped",{conversationId:r.conversationId??n.conversationId??"",messageId:r.messageId??n.id??""})),n.status!=="WAITING_CLIENT"&&this.maybeFlagEmptyReply(n,i),n}finally{r&&this.endTurn(r)}}async stop(){const t=this.activeTurn;if(t){t.stopRequested=!0;const s=t.messageId;return t.controller.abort(),s?this.postStopForTurn(t,s):null}const r=this.pausedTurn;if(!r)return null;this.pausedTurn=null,this.pendingResumes.delete(r.messageId),this.stoppedTurnIds.add(r.messageId);let i=null;try{i=await this.stopMessage(r.messageId)}catch(s){c.warn("Failed to stop the paused turn:",s)}return this.eventEmitter.emit("message:stopped",{conversationId:r.conversationId,messageId:r.messageId}),i}async stopMessage(t){const r=await this.httpClient.post(`/api/sdk/v1/messages/${t}/stop`);return{status:r.status,messageStatus:r.message_status}}isGenerating(){return this.activeTurn!==null||this.pausedTurn!==null}beginTurn(){this.pausedTurn=null;const t={controller:new AbortController,messageId:null,conversationId:null,stopRequested:!1,stopPosted:!1};return this.activeTurn=t,t}endTurn(t){this.activeTurn===t&&(this.activeTurn=null)}async postStopForTurn(t,r){if(!r||t.stopPosted)return null;t.stopPosted=!0;try{return await this.stopMessage(r)}catch(i){return c.warn("Failed to stop the turn server-side:",i),null}}buildStoppedMessage(t){const r={id:t.messageId??"",conversationId:t.conversationId??"",content:"",role:"assistant",status:"CANCELED",createdAt:new Date};return r.id&&this.eventEmitter.emit("message:complete",r),this.eventEmitter.emit("message:stopped",{conversationId:r.conversationId,messageId:r.id}),r}resolveClientFunctionsMode(t){return t?.clientFunctionsMode??this.config.clientFunctionsMode??"pause"}registerResumeGate(t){return this.resumeGate=t,()=>{this.resumeGate===t&&(this.resumeGate=null)}}async continueMessage(t){const r=this.functionRegistry.getSchemas(),i=this.buildSendContext(),s={};r.length>0&&(s.client_functions=r),i&&(s.client_context=i);const n=this.beginTurn();n.messageId=t;const o=await this.sendRequest(n,()=>this.httpClient.postStream(`/api/sdk/v1/messages/${t}/continue`,s,{signal:n.controller.signal}));return o?this.processSSEResponse(o,n):this.buildStoppedMessage(n)}markResumeSignal(t,r,i){if(!t)return;const s=this.pendingResumes.get(t)??{conversationId:r,waitingConfirmed:!1,resultsReady:!1,started:!1};s[i]=!0,r&&(s.conversationId=r),this.pendingResumes.set(t,s),!(!s.waitingConfirmed||!s.resultsReady||s.started)&&(s.started=!0,this.runAutoResume(t,s.conversationId))}async runAutoResume(t,r){try{this.resumeGate&&await this.resumeGate({conversationId:r,messageId:t})}catch(i){c.warn("Resume gate threw; resuming anyway:",i)}if(this.pendingResumes.delete(t),!this.stoppedTurnIds.delete(t))try{await this.continueMessage(t)}catch(i){c.warn("Auto-resume of paused turn failed:",i)}}maybeFlagEmptyReply(t,r){t.status==="DONE"&&(t.content??"").trim()===""&&!r&&!(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 i=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(i))return;this.warnedEmptyConversations.add(i);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 r,i;try{r=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(s){i=s instanceof Error?s.message:"Unknown error",c.error("Client function execution failed:",s)}if(t.invocationId)try{const s=await this.submitToolCallForm(t.invocationId,{result:r,error:i,_type:"client_function_result"});s?.resume?.ready&&this.markResumeSignal(s.resume.message_id,t.conversationId,"resultsReady")}catch(s){c.error("Failed to submit function result:",s)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:r,error:i})}requiresApproval(t){const r=this.config.approvalPolicy;if(r)try{if(r(t))return!0}catch(i){c.warn("approvalPolicy threw; not gating this call:",i)}return this.functionRegistry.get(t.functionName)?.requiresApproval===!0}async approveFunction(t){const r=this.pendingApprovals.get(t);r&&(this.pendingApprovals.delete(t),await this.handleClientFunctionInvocation(r))}async rejectFunction(t){const r=this.pendingApprovals.get(t);if(!r)return;this.pendingApprovals.delete(t);const i={approved:!1,reason:"user_rejected"};try{const s=await this.submitToolCallForm(t,{result:i,_type:"client_function_result"});s?.resume?.ready&&this.markResumeSignal(s.resume.message_id,r.conversationId,"resultsReady")}catch(s){c.error("Failed to submit function rejection:",s)}this.eventEmitter.emit("function:result",{invocationId:t,result:i})}async runExternalFunction(t,r){const i={invocationId:`webmcp-${I()}`,functionName:t,arguments:r,conversationId:""},{invocationId:s}=i;this.eventEmitter.emit("function:invoke",i);const n=Date.now();try{const o=await this.functionRegistry.execute(t,r);return this.eventEmitter.emit("function:result",{invocationId:s,result:o}),this.reportExternalCall(t,r,n,{result:o}),o}catch(o){const a=o instanceof Error?o.message:String(o);throw this.eventEmitter.emit("function:result",{invocationId:s,result:null,error:a}),this.reportExternalCall(t,r,n,{error:a}),o}}reportExternalCall(t,r,i,s){const n=this.functionRegistry.get(t);n&&Zt({post:(o,a,l)=>this.httpClient.post(o,a,l),declared:this.declaredExternally},{schema:n.schema,args:r,durationMs:Date.now()-i,navigates:n.webmcp?n.webmcp.navigates:void 0,...s})}async getConversations(t){const r=new URLSearchParams;t?.page!==void 0&&r.set("page",String(t.page)),t?.pageSize!==void 0&&r.set("page_size",String(t.pageSize));const i=r.toString(),s=await this.httpClient.get(`/api/sdk/v1/conversations${i?`?${i}`:""}`),n=(Array.isArray(s.data)?s.data:[]).map(o=>({id:String(o.id),title:o.title??"",lastMessageDate:new Date(o.last_message_at??o.created_at??0)}));return{data:n,hasMore:s.has_more??!1,total:s.total??n.length}}async getConversation(t){const r=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),i={id:r.id,title:r.title,lastMessageDate:new Date(r.last_message_at??r.created_at??0),messages:r.messages.map(s=>({id:s.id,conversationId:r.id,content:s.content,role:s.role,status:s.status,createdAt:new Date(s.created_at),hidden:s.hidden,sources:s.sources&&s.sources.length>0?s.sources.map(({id:n,title:o,url:a})=>({id:n,title:o,url:a??void 0})):void 0,toolCalls:k.mapPersistedToolCalls(s.tool_call_data),attachments:s.attachments&&s.attachments.length>0?s.attachments.map(qt):void 0,followUpReplies:s.follow_up_replies&&s.follow_up_replies.length>0?s.follow_up_replies:void 0}))};return this.eventEmitter.emit("conversation:loaded",i),i}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(r=>({id:String(r.id??""),type:r.type??"status_message",status:String(r.status??"unknown"),toolName:r.tool_name??"",toolDisplayName:r.tool_display_name,message:r.message,formSchema:r.form_schema,data:r.data,functionName:r.function_name,arguments:r.arguments,displayMode:r.display_mode,askToTalkToHuman:r.ask_to_talk_to_human,allowedToCreateTicket:r.allowed_to_create_ticket,ticket:r.ticket,mode:r.mode,ticketFormId:r.ticket_form_id,embedHtml:r.embed_html,embedDescription:r.embed_description}))}async transcribeAudio(t,r){const i=new FormData;return i.append("file",t,t.name),(await this.httpClient.postFormData("/api/sdk/v1/audio/transcriptions",i,r)).json()}async getConfig(){const t=await this.httpClient.get("/api/sdk/v1/config");return{permissions:(t.permissions??[]).map(r=>({id:r.id??void 0,name:r.name??void 0,displayName:r.display_name??void 0,agents:(r.agents??[]).map(i=>({id:i.id,name:i.name??void 0})),ticketForm:r.ticket_form?k.mapTicketForm(r.ticket_form):void 0,homePage:r.home_page?k.mapHomePage(r.home_page):void 0,fileAttachmentsEnabled:!!r.file_attachments_enabled,voiceEnabled:!!r.voice_enabled,speechToTextEnabled:!!r.speech_to_text_enabled})),proactive:{enabled:!!t.proactive?.enabled}}}static mapHomePage(t){const r=t.widget_starter;return{title:t.title??void 0,subtitle:t.subtitle??void 0,starters:(t.home_starters??[]).flatMap(i=>{const s=i.description||i.title||"",n=i.initial_message||s;return!s||!n?[]:[{id:i.id,label:s,message:n,agentId:i.agent_id??void 0}]}),widgetStarter:r&&r.initial_message?{id:r.id,message:r.initial_message,agentId:r.agent_id??void 0}:void 0}}static mapTicketForm(t){return{id:t.id,name:t.name??void 0,mode:t.mode==="embed"?"embed":"form",showSubject:t.show_subject??!0,showBody:t.show_body??!0,showPriority:t.show_priority??!0,showTypology:t.show_typology??!0,priorityTypologies:t.priority_typologies??void 0,successMessageText:t.success_message_text??void 0,successMessageUrlLabel:t.success_message_url_label??void 0,fields:(t.fields??[]).map(r=>({id:r.id,externalId:r.external_id??void 0,title:r.title??void 0,type:r.type??void 0,required:!!r.required,hidden:!!r.hidden,active:r.active,alwaysVisible:r.always_visible,regexpForValidation:r.regexp_for_validation??void 0,position:r.position??0,options:(r.options??[]).map(i=>({id:i.id,name:i.name??void 0,value:i.value??void 0,default:!!i.default,position:i.position??void 0,group:i.group??void 0,noDisplay:i.no_display,conditionalFieldId:i.conditional_field_id??void 0,conditionalFieldValues:i.conditional_field_values??void 0,message:i.message??void 0,messageType:i.message_type??"info"})),conditionalFieldId:r.conditional_field_id??void 0,conditionalFieldValue:r.conditional_field_value??void 0,conditionalFieldValues:r.conditional_field_values??void 0}))}}async createTicket(t){const r=new FormData;r.append("subject",t.subject),r.append("body",t.body),t.priority&&r.append("priority",t.priority),t.typology&&r.append("typology",t.typology),t.conversationId&&r.append("conversation_id",t.conversationId),t.email&&r.append("email",t.email),t.customFields&&t.customFields.length>0&&r.append("custom_fields",JSON.stringify(t.customFields));for(const s of t.files??[])r.append("files",s,s.name);t.ticketFormId&&r.append("ticket_form_id",t.ticketFormId);const i=await(await this.httpClient.postFormData("/api/sdk/v1/tickets",r)).json();return{id:String(i.id??""),url:typeof i.url=="string"&&i.url?i.url:void 0}}async getMessages(t){return(await this.getConversation(t)).messages||[]}async resumePendingClientFunctions(t){const r=[...t.messages??[]].reverse().find(a=>a.role==="assistant"&&a.status==="WAITING_CLIENT");if(!r)return null;const i=(r.toolCalls??[]).filter(a=>a.type==="client_function"&&a.status==="waiting_input"&&a.functionName),s=new Set(this.functionRegistry.getSchemas().map(a=>a.name)),n=i.filter(a=>!s.has(a.functionName));if(n.length>0)return c.warn("Cannot resume paused turn: function(s) not registered on this page:",n.map(a=>a.functionName)),null;let o=i.length===0;for(const a of i){const l={invocationId:a.id,functionName:a.functionName,arguments:a.arguments??{},conversationId:t.id};if(this.requiresApproval(l)){this.pendingApprovals.set(a.id,l),this.markResumeSignal(r.id,t.id,"waitingConfirmed"),this.eventEmitter.emit("function:awaiting-approval",l),o=!1;continue}this.eventEmitter.emit("function:invoke",l);let d,u;try{d=await this.functionRegistry.execute(a.functionName,a.arguments??{})}catch(g){u=g instanceof Error?g.message:"Unknown error",c.error("Client function execution failed:",g)}this.eventEmitter.emit("function:result",{invocationId:a.id,result:d,error:u}),o=(await this.submitToolCallForm(a.id,{result:d,error:u,_type:"client_function_result"}))?.resume?.ready??o}return o?this.continueMessage(r.id):null}async submitToolCallForm(t,r){return this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:r})}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 r=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:r.name,description:r.description,schema:r.schema,submit:r.submit??void 0}}async submitFormCollector(t,r){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:r})}async submitFeedback(t,r,i){const s=i?.comment?.trim(),n=i?.reasons?.length?[...new Set(i.reasons)]:[];await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:r,...n.length?{reasons:n}:{},...s?{comment:s}:{}})}async submitConversationFeedback(t,r,i){let s=i?.lastMessageId;if(!s){const n=[...(await this.getConversation(t)).messages??[]].reverse().find(o=>o.role==="assistant"&&!o.hidden&&!!o.content&&o.status!=="IN_PROGRESS"&&o.status!=="WAITING_CLIENT");if(!n)throw new v.AgoError(`Conversation ${t} has no finished answer to report feedback on. Wait for the turn to complete, or pass \`lastMessageId\`.`,"feedback_no_message");s=n.id}return await this.submitFeedback(s,r,i),s}registerFunction(t,r,i){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,r,i)}register(t){if(Array.isArray(t))for(const r of t)this.functionRegistry.register(r);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}onFunctionsChanged(t){return this.functionRegistry.onChange(t)}getFunctionRegistrations(){return this.functionRegistry.getAll()}async executeClientFunction(t,r){return this.functionRegistry.execute(t,r)}registerNavigationFunction(t,r,i){this.registerFunction(ot(t,r,i)),i?.catalogue==="onDemand"?(this.registerFunction(at(r)),this.listPagesRegistered=!0):this.listPagesRegistered&&(this.unregisterFunction(R),this.listPagesRegistered=!1),this.addDynamicContext("current-page",()=>{if(typeof window>"u"||!window.location)return null;const s=window.location.href,n=st(window.location.pathname,r),o={url:s};return n&&(o.page=n.name),{name:"Current page",description:"The page the user is currently viewing.",data:o}})}unregisterNavigationFunction(){this.unregisterFunction(J),this.listPagesRegistered&&(this.unregisterFunction(R),this.listPagesRegistered=!1),this.removeDynamicContext("current-page")}registerPageStateFunction(t,r){const i=r?.functionName??"setPageState",s=r?.data;this.registerFunction(dt(t,{name:i,requiresApproval:r?.requiresApproval,getResultBudget:()=>s?this.pageDataBudget(s):this.functionRegistry.getDefaultMaxResultBytes(),data:s?{description:s.description,maxResultBytes:s.maxResultBytes,read:async o=>ee(i,await this.readPageData(i,s,r),this.pageDataBudget(s)-this.envelopeBytes(o))}:void 0}));const n=de(i);s?(this.warnIfPlaceholderMode(i),this.registerFunction(n,async()=>({data:ee(i,await this.readPageData(i,s,r),this.pageDataBudget(s)-this.envelopeBytes({}))}),{description:`Read what the current page is displaying, without changing anything: ${s.description}`,parameters:{type:"object",properties:{}},maxResultBytes:s.maxResultBytes}),this.pageDataCompanions.add(n)):this.pageDataCompanions.delete(n)&&this.unregisterFunction(n),this.addDynamicContext(`page-state:${i}`,()=>{const o=t.filter(l=>typeof l.get=="function");if(o.length===0)return null;const a={};for(const l of o)a[l.name]=l.get();return{name:"Page state",description:"Current, editable state of the page the user is viewing.",data:a}})}unregisterPageStateFunction(t){const r=t??"setPageState";this.unregisterFunction(r);const i=de(r);this.pageDataCompanions.delete(i)&&this.unregisterFunction(i),this.removeDynamicContext(`page-state:${r}`)}pageDataBudget(t){return t.maxResultBytes??this.functionRegistry.getDefaultMaxResultBytes()}envelopeBytes(t){return S(JSON.stringify({...t,data:null}))-4}readPageData(t,r,i){return Ye(()=>r,i?.settleTimeoutMs??1e4).catch(s=>(c.warn(`Reading page data for "${t}" failed:`,s),{error:"page_data_unavailable",message:s instanceof Error?s.message:String(s)}))}warnIfPlaceholderMode(t){this.warnedPageDataPlaceholder||this.config.clientFunctionsMode==="placeholder"&&(this.warnedPageDataPlaceholder=!0,c.warn(`"${t}" declares a data source, but clientFunctionsMode is "placeholder": the agent will not see that data during the turn it calls the function. Switch to "pause" (the default) for the data to come back as the result of its own call.`))}setContext(t,r){this.contextRegistry.set(t,r),this.notifyContextChanged()}removeContext(t){const r=this.contextRegistry.remove(t);return r&&this.notifyContextChanged(),r}addDynamicContext(t,r){this.contextRegistry.addDynamicProvider(t,r),this.notifyContextChanged()}removeDynamicContext(t){const r=this.contextRegistry.removeDynamicProvider(t);return r&&this.notifyContextChanged(),r}notifyContextChanged(){this.eventEmitter.emit("context:changed",this.contextRegistry.getSnapshot())}emitFormEvent(t,r){this.eventEmitter.emit(t,r)}emitProactiveEvent(t,r){this.eventEmitter.emit(t,r)}getHttp(){return this.httpClient}getConfiguredAgent(){return this.config.agent||this.config.defaultAgentId}getUserIdentity(){return{email:this.config.userEmail||void 0,hasJwt:!!this.config.userJwt}}enableAutoPageContext(){this.addDynamicContext("browser-page",()=>{const t=typeof window<"u"?window.location.href:void 0,r=typeof document<"u"?document.title:void 0;return!t&&!r?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:t,title:r}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}buildSendContext(){const t=this.contextRegistry.getSnapshot(),r=t?.entries??{},{changes:i,baseline:s}=jt(this.lastSentPageState,r);return this.lastSentPageState=s,i.length===0?t:{entries:{...r,[rr]:{name:"State changes",description:"Fields in the page state that changed since your last message, as field: <old> -> <new>.",data:{changes:i}}}}}recordActivity(t){this.addActivity(t)}getRecentActivity(){return this.activityLedger.getRecent()}clearActivity(){this.activityLedger.clear()}addActivity(t){const r=this.activityLedger.add(t);this.eventEmitter.emit("activity:recorded",r)}recordAgentAction(t){const r=t.functionName,i=t.arguments;let s,n;if(r==="navigateToPage"){const o=i?.page;s="agent.navigate",n=o?`Agent navigated to "${String(o)}"`:"Agent navigated"}else r==="setPageState"?(s="agent.page_state",n="Agent changed the page state"):(s=`agent.${r}`,n=`Agent ran "${r}"`);this.addActivity({actor:"agent",name:s,summary:n,...i&&Object.keys(i).length>0?{data:{arguments:i}}:{}})}registerActivityContext(){this.contextRegistry.addDynamicProvider(tr,()=>{const t=this.activityLedger.getRecent();return t.length===0?null:{name:"Recent activity",description:"Recent actions by the user and the agent in the app, oldest first. Use this to understand what just happened before this message. Use current-page for the user’s current location.",data:{events:t}}})}enableErrorWatcher(t){this.disableErrorWatcher();const r=new me(t);this.errorWatcher=r,r.start(),r.subscribe(i=>{this.eventEmitter.emit("error:captured",i),this.notifyContextChanged()}),this.contextRegistry.addDynamicProvider(ue,()=>{const i=r.getErrors();if(i.length===0)return null;const s=Date.now();return{name:"Recent JavaScript errors",description:"JavaScript errors captured on the page in the last minutes, oldest first, with how long ago each last fired (ageMs) and how many times (count). Use them to diagnose when the user reports something broken or unresponsive; do not bring them up otherwise.",data:{errors:i.map(({firstAt:n,lastAt:o,...a})=>({...a,ageMs:Math.max(0,s-o),...n!==o?{firstSeenAgoMs:Math.max(0,s-n)}:{}}))}}})}disableErrorWatcher(){this.errorWatcher&&(this.errorWatcher.destroy(),this.errorWatcher=null,this.contextRegistry.removeDynamicProvider(ue))}reportError(t,r){if(!this.errorWatcher){c.warn("reportError() ignored: enable the error watcher first (errorWatcher: true).");return}this.errorWatcher.report(t,r)}getRecentErrors(){return this.errorWatcher?.getErrors()??[]}clearErrors(){this.errorWatcher?.clear()}on(t,r){this.eventEmitter.on(t,r)}off(t,r){this.eventEmitter.off(t,r)}once(t,r){this.eventEmitter.once(t,r)}waitFor(t,r){return this.eventEmitter.waitFor(t,r)}updateConfig(t){const r={};for(const[s,n]of Object.entries(t))n!==void 0&&(r[s]=n);const i={...this.config,...r};G(i,"AgoClient.updateConfig"),this.config=i,this.httpClient.updateConfig(r),r.debug!==void 0&&(r.debug?c.enable():c.disable()),r.maxFunctionResultBytes!==void 0&&this.functionRegistry.setDefaultMaxResultBytes(r.maxFunctionResultBytes),r.errorWatcher!==void 0&&(r.errorWatcher?this.enableErrorWatcher(r.errorWatcher===!0?void 0:r.errorWatcher):this.disableErrorWatcher())}destroy(){this.proactive?.destroy(),this.proactive=null,this.errorWatcher?.destroy(),this.errorWatcher=null,this.detachWebMCP?.(),this.detachWebMCP=null,this.activeTurn?.controller.abort(),this.activeTurn=null,this.pausedTurn=null,this.stoppedTurnIds.clear(),this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.listPagesRegistered=!1,this.contextRegistry.clear(),this.pendingResumes.clear(),this.pendingApprovals.clear(),this.resumeGate=null,c.log("AgoClient destroyed")}reviveAfterDestroy(){this.registerActivityContext(),this.config.errorWatcher&&!this.errorWatcher&&this.enableErrorWatcher(this.config.errorWatcher===!0?void 0:this.config.errorWatcher),this.config.proactive&&!this.proactive&&B(this,this.config.proactive),this.attachWebMCPBridge()}},sr=["inaccurate","incomplete","information_not_found","technical_issue"];Object.defineProperty(exports,"ActivityLedger",{enumerable:!0,get:function(){return ge}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return ir}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return ke}});Object.defineProperty(exports,"DEFAULT_MAX_ACTIVITY_ENTRIES",{enumerable:!0,get:function(){return Pe}});Object.defineProperty(exports,"DEFAULT_MAX_ERRORS",{enumerable:!0,get:function(){return Ne}});Object.defineProperty(exports,"DEFAULT_MAX_ERROR_AGE_MS",{enumerable:!0,get:function(){return je}});Object.defineProperty(exports,"ErrorWatcher",{enumerable:!0,get:function(){return me}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return Ie}});Object.defineProperty(exports,"FEEDBACK_REASONS",{enumerable:!0,get:function(){return sr}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return pe}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return Re}});Object.defineProperty(exports,"SignalCollector",{enumerable:!0,get:function(){return Se}});Object.defineProperty(exports,"attachmentsFromFiles",{enumerable:!0,get:function(){return Gt}});Object.defineProperty(exports,"canInlineImage",{enumerable:!0,get:function(){return Wt}});Object.defineProperty(exports,"createAgoProactive",{enumerable:!0,get:function(){return B}});Object.defineProperty(exports,"createStore",{enumerable:!0,get:function(){return _e}});Object.defineProperty(exports,"formatFileSize",{enumerable:!0,get:function(){return Bt}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return Lt}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return c}});Object.defineProperty(exports,"matchesRoutePattern",{enumerable:!0,get:function(){return Ce}});Object.defineProperty(exports,"matchesWhen",{enumerable:!0,get:function(){return Ae}});Object.defineProperty(exports,"partialDeepMatch",{enumerable:!0,get:function(){return X}});Object.defineProperty(exports,"safeAttachmentUrl",{enumerable:!0,get:function(){return Te}});Object.defineProperty(exports,"validateConfig",{enumerable:!0,get:function(){return G}});
10
+ `);for(const i of r)if(!i.startsWith(": ")&&i.startsWith("data: ")){const s=i.slice(6);try{const n=JSON.parse(s);this.handleChunk(n)}catch(n){c.warn("Failed to parse SSE data:",s,n)}}}}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.title&&this.message.conversationId&&this.callbacks.onTitle?.({conversationId:this.message.conversationId,title:e.title}),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 r=t.knowledge_document;return{id:r.id,title:r.title,url:r.use_external_link?r.external_link_url:r.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${G(e.arguments??{})}`,r=e.id||"",i=this.firedClientFunctions.get(t);let s=!1;i?r&&!i.has(r)&&(i.has(oe)?(i.delete(oe),i.add(r)):(i.add(r),s=!0)):(this.firedClientFunctions.set(t,new Set([r])),s=!0),s&&this.callbacks.onClientFunction?.({invocationId:r,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 r=this.toolCalls.findIndex(i=>i.id===t.id);r>=0?this.toolCalls[r]=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())),this.message.status==="WAITING_CLIENT"&&!this.waitingClientEmitted&&this.message.id&&(this.waitingClientEmitted=!0,this.callbacks.onWaitingClient?.({conversationId:this.message.conversationId||"",messageId:this.message.id,waitingToolCallIds:e.waiting_tool_call_ids??[]}))}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,displayMode:e.display_mode,askToTalkToHuman:e.ask_to_talk_to_human,allowedToCreateTicket:e.allowed_to_create_ticket,ticket:e.ticket,mode:e.mode,ticketFormId:e.ticket_form_id,embedHtml:e.embed_html,embedDescription:e.embed_description}}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 e.status!=="WAITING_CLIENT"&&this.callbacks.onComplete?.(e),e}};function Bt(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var Gt=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function Ie(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const r=new URL(e,t);if(r.protocol==="http:"||r.protocol==="https:"||r.protocol==="blob:")return e}catch{}}function qt(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&Ie(e.url)!==void 0}function Kt(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 Jt(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 Ht(e){return e.map((t,r)=>({id:`local-${r}-${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:Gt.has(t.type)}))}var xe=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 r=this.handlers.get(e);r&&r.delete(t)}emit(e,t){const r=this.handlers.get(e);r&&r.forEach(i=>{try{i(t)}catch(s){console.error(`Error in event handler for ${String(e)}:`,s)}})}once(e,t){const r=(i=>{this.off(e,r),t(i)});this.on(e,r)}waitFor(e,t){return new Promise((r,i)=>{let s;const n=(o=>{s&&clearTimeout(s),r(o)});this.once(e,n),t?.timeout&&(s=setTimeout(()=>{this.off(e,n),i(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},Xt=4e3,zt=150,Vt=600;function Yt(){if(!(typeof document>"u"))return document.modelContext}function Qt(e,t){return new Promise(r=>{let i,s=!1;const n=()=>{if(!s){s=!0,clearTimeout(i),clearTimeout(l),clearTimeout(a);for(const u of t)u?.removeEventListener("abort",n);d(),r()}},o=()=>{clearTimeout(l),clearTimeout(i),i=setTimeout(n,zt)},a=setTimeout(n,Xt),l=setTimeout(n,Vt),d=e(o);for(const u of t){if(u?.aborted)return n();u?.addEventListener("abort",n)}})}function Zt(e){const t=Yt();if(!t)return c.log("WebMCP is not available in this browser; bridge not attached"),()=>{};const r=t,i=new Map,s=new Set,n=new AbortController;let o=!1,a=!1;function l(y){return JSON.stringify([y.description,y.inputSchema,y.annotations])}function d(y,h){const p=e.getFunctionRegistrations().find(m=>m.name===y)?.webmcp;return!p||!p.navigates?!1:h?.success!==!1}function u(){const y=new Map;for(const h of e.getFunctionRegistrations()){if(h.webmcp===!1)continue;const p=h.webmcp||void 0,m=h.name,b={name:m,description:h.schema.description,inputSchema:h.schema.parameters,annotations:p?.annotations,execute:async(E,Fe)=>{const z=await e.runExternalFunction(m,E??{});return!o&&d(m,z)&&await Qt(Pe=>e.onFunctionsChanged(Pe),[Fe?.signal,n.signal]),z}};y.set(m,{tool:b,signature:l(b)})}return y}function g(){o||a||(a=!0,queueMicrotask(()=>{a=!1,f()}))}function f(){if(o)return;const y=u();for(const[h,p]of i)y.get(h)?.signature!==p.signature&&(p.controller.abort(),i.delete(h));for(const[h,p]of y){if(i.has(h))continue;const m=new AbortController;i.set(h,{signature:p.signature,controller:m}),Promise.resolve(r.registerTool(p.tool,{signal:m.signal})).catch(b=>{if(c.error(`WebMCP rejected the tool "${h}":`,b),i.get(h)?.controller!==m)return;i.delete(h);const E=JSON.stringify([h,p.signature]);s.has(E)||(s.add(E),g())})}}const w=e.onFunctionsChanged(g);return f(),c.log("WebMCP bridge attached"),()=>{if(!o){o=!0,n.abort(),w();for(const y of i.values())y.controller.abort();i.clear(),c.log("WebMCP bridge detached")}}}var er="/api/sdk/v1/client-function-calls",ae="ago_webmcp_tab";function tr(){try{const e=sessionStorage.getItem(ae);if(e)return e;const t=x();return sessionStorage.setItem(ae,t),t}catch{return}}function rr(e,t){const{name:r}=t.schema,i=tr(),s={function_name:r,arguments:t.args,result:t.error===void 0?t.result??null:null,error:t.error??null,duration_ms:t.durationMs,...i?{tab_id:i}:{},...e.declared.has(r)?{}:{client_functions:[t.schema]}};e.post(er,s,t.navigates?{keepalive:!0}:void 0).then(()=>{e.declared.add(r)}).catch(n=>{c.debug("External call report failed:",n)})}var ce='`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the public demo account https://playground.api.useago.com (agent generic-guide). See docs/general/configuration.md#error-codes (config_missing_base_url).',ir=/^[a-z][a-z0-9+.-]*:\/\//i,le=!1;function q(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new v.AgoError(`${t}: ${ce}`,"config_missing_base_url");const r=e.baseUrl;if(typeof r!="string"||r.trim()==="")throw new v.AgoError(`${t}: ${ce}`,"config_missing_base_url");S(e.language),!r.startsWith("/")&&!ir.test(r)&&(le||(le=!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 sr="activity:recent",nr="state:delta",ue="errors:recent";function de(e){return e==="setPageState"?"readPageData":`read${e.charAt(0).toUpperCase()}${e.slice(1)}Data`}var or=class R{constructor(t){this.errorWatcher=null,this.lastSentPageState=null,this.warnedEmptyConversations=new Set,this.declaredExternally=new Set,this.warnedPageDataPlaceholder=!1,this.pageDataCompanions=new Set,this.pendingResumes=new Map,this.pendingApprovals=new Map,this.resumeGate=null,this.activeTurn=null,this.pausedTurn=null,this.stoppedTurnIds=new Set,this.proactive=null,this.detachWebMCP=null,this.listPagesRegistered=!1,q(t,"AgoClient"),this.config=t,this.activityLedger=new ge(t.maxActivityEntries),this.httpClient=new Le(t),this.functionRegistry=new ye({maxResultBytes:t.maxFunctionResultBytes}),this.contextRegistry=new Re,this.eventEmitter=new xe,this.registerActivityContext(),this.functionRegistry.onChange(()=>{this.eventEmitter.emit("functions:changed",this.functionRegistry.getSchemas())}),t.debug&&c.enable(),t.errorWatcher&&this.enableErrorWatcher(t.errorWatcher===!0?void 0:t.errorWatcher),t.proactive&&B(this,t.proactive),this.attachWebMCPBridge(),c.log("AgoClient initialized")}attachWebMCPBridge(){!this.config.webmcp||this.detachWebMCP||(this.detachWebMCP=Zt(this))}async sendMessage(t,r){if(typeof t!="string"||!t.trim())throw new v.AgoError("Add message text before sending, including when attaching files. See docs/general/core.md#file-attachments.","message_empty_content");const i=this.functionRegistry.getSchemas(),s=this.buildSendContext(),n=this.config.agent||this.config.defaultAgentId,o=this.resolveClientFunctionsMode(r),a=r?.metadata!==void 0?r.metadata:this.config.metadata,l=a!=null?JSON.stringify(a):void 0,d={content:t,conversation_id:r?.conversationId,agent_id:r?.agentId||n};a!=null&&(d.metadata=a),i.length>0&&(d.client_functions=i,o==="pause"&&(d.client_functions_mode=o)),s&&(d.client_context=s),r?.hidden&&(d.hidden=!0);const u=this.beginTurn();let g;if(r?.files&&r.files.length>0){const f=new FormData;f.append("content",t),l!==void 0&&f.append("metadata",l),r.conversationId&&f.append("conversation_id",r.conversationId),(r.agentId||n)&&f.append("agent_id",r.agentId||n||""),i.length>0&&(f.append("client_functions",JSON.stringify(i)),o==="pause"&&f.append("client_functions_mode",o)),s&&f.append("client_context",JSON.stringify(s)),r.hidden&&f.append("hidden","true");for(const w of r.files)f.append("files",w);g=await this.sendRequest(u,()=>this.httpClient.postFormData("/api/sdk/v1/messages",f,{signal:u.controller.signal}))}else g=await this.sendRequest(u,()=>this.httpClient.postStream("/api/sdk/v1/messages",d,{signal:u.controller.signal}));return g?this.processSSEResponse(g,u):this.buildStoppedMessage(u)}async sendRequest(t,r){try{return await r()}catch(i){if(this.endTurn(t),M(i))return null;throw i}}async processSSEResponse(t,r){let i=!1;const s=new Te({onRawChunk:n=>{r&&(n.message_id&&!r.messageId&&(r.messageId=n.message_id),n.thread?.id&&(r.conversationId=n.thread.id)),this.eventEmitter.emit("stream:message",n)},onStart:n=>{this.eventEmitter.emit("message:start",n)},onChunk:n=>{this.eventEmitter.emit("message:chunk",n)},onToolCall:n=>{this.eventEmitter.emit("toolCall:received",n),n.type==="form"&&this.eventEmitter.emit("toolCall:form",n)},onClientFunction:async n=>{if(i=!0,this.eventEmitter.emit("function:invoke",n),this.recordAgentAction(n),n.invocationId&&this.requiresApproval(n)){this.pendingApprovals.set(n.invocationId,n),this.eventEmitter.emit("function:awaiting-approval",n);return}await this.handleClientFunctionInvocation(n)},onTitle:n=>{this.eventEmitter.emit("conversation:title",n)},onAnswerComplete:n=>{this.eventEmitter.emit("message:answer-complete",n)},onWaitingClient:n=>{this.pausedTurn={messageId:n.messageId,conversationId:n.conversationId},this.eventEmitter.emit("message:waiting-client",n),this.markResumeSignal(n.messageId,n.conversationId,"waitingConfirmed")},onComplete:n=>{r?.stopRequested&&!n.id||this.eventEmitter.emit("message:complete",n)},onError:n=>{this.eventEmitter.emit("message:error",{error:n.message,code:n instanceof v.AgoError?n.code:void 0})}},{signal:r?.controller.signal});try{const n=await s.processStream(t);return r?.stopRequested&&(this.postStopForTurn(r,r.messageId??n.id),this.eventEmitter.emit("message:stopped",{conversationId:r.conversationId??n.conversationId??"",messageId:r.messageId??n.id??""})),n.status!=="WAITING_CLIENT"&&this.maybeFlagEmptyReply(n,i),n}finally{r&&this.endTurn(r)}}async stop(){const t=this.activeTurn;if(t){t.stopRequested=!0;const s=t.messageId;return t.controller.abort(),s?this.postStopForTurn(t,s):null}const r=this.pausedTurn;if(!r)return null;this.pausedTurn=null,this.pendingResumes.delete(r.messageId),this.stoppedTurnIds.add(r.messageId);let i=null;try{i=await this.stopMessage(r.messageId)}catch(s){c.warn("Failed to stop the paused turn:",s)}return this.eventEmitter.emit("message:stopped",{conversationId:r.conversationId,messageId:r.messageId}),i}async stopMessage(t){const r=await this.httpClient.post(`/api/sdk/v1/messages/${t}/stop`);return{status:r.status,messageStatus:r.message_status}}isGenerating(){return this.activeTurn!==null||this.pausedTurn!==null}beginTurn(){this.pausedTurn=null;const t={controller:new AbortController,messageId:null,conversationId:null,stopRequested:!1,stopPosted:!1};return this.activeTurn=t,t}endTurn(t){this.activeTurn===t&&(this.activeTurn=null)}async postStopForTurn(t,r){if(!r||t.stopPosted)return null;t.stopPosted=!0;try{return await this.stopMessage(r)}catch(i){return c.warn("Failed to stop the turn server-side:",i),null}}buildStoppedMessage(t){const r={id:t.messageId??"",conversationId:t.conversationId??"",content:"",role:"assistant",status:"CANCELED",createdAt:new Date};return r.id&&this.eventEmitter.emit("message:complete",r),this.eventEmitter.emit("message:stopped",{conversationId:r.conversationId,messageId:r.id}),r}resolveClientFunctionsMode(t){return t?.clientFunctionsMode??this.config.clientFunctionsMode??"pause"}registerResumeGate(t){return this.resumeGate=t,()=>{this.resumeGate===t&&(this.resumeGate=null)}}async continueMessage(t){const r=this.functionRegistry.getSchemas(),i=this.buildSendContext(),s={};r.length>0&&(s.client_functions=r),i&&(s.client_context=i);const n=this.beginTurn();n.messageId=t;const o=await this.sendRequest(n,()=>this.httpClient.postStream(`/api/sdk/v1/messages/${t}/continue`,s,{signal:n.controller.signal}));return o?this.processSSEResponse(o,n):this.buildStoppedMessage(n)}markResumeSignal(t,r,i){if(!t)return;const s=this.pendingResumes.get(t)??{conversationId:r,waitingConfirmed:!1,resultsReady:!1,started:!1};s[i]=!0,r&&(s.conversationId=r),this.pendingResumes.set(t,s),!(!s.waitingConfirmed||!s.resultsReady||s.started)&&(s.started=!0,this.runAutoResume(t,s.conversationId))}async runAutoResume(t,r){try{this.resumeGate&&await this.resumeGate({conversationId:r,messageId:t})}catch(i){c.warn("Resume gate threw; resuming anyway:",i)}if(this.pendingResumes.delete(t),!this.stoppedTurnIds.delete(t))try{await this.continueMessage(t)}catch(i){c.warn("Auto-resume of paused turn failed:",i)}}maybeFlagEmptyReply(t,r){t.status==="DONE"&&(t.content??"").trim()===""&&!r&&!(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 i=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(i))return;this.warnedEmptyConversations.add(i);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 r,i;try{r=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(s){i=s instanceof Error?s.message:"Unknown error",c.error("Client function execution failed:",s)}if(t.invocationId)try{const s=await this.submitToolCallForm(t.invocationId,{result:r,error:i,_type:"client_function_result"});s?.resume?.ready&&this.markResumeSignal(s.resume.message_id,t.conversationId,"resultsReady")}catch(s){c.error("Failed to submit function result:",s)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:r,error:i})}requiresApproval(t){const r=this.config.approvalPolicy;if(r)try{if(r(t))return!0}catch(i){c.warn("approvalPolicy threw; not gating this call:",i)}return this.functionRegistry.get(t.functionName)?.requiresApproval===!0}async approveFunction(t){const r=this.pendingApprovals.get(t);r&&(this.pendingApprovals.delete(t),await this.handleClientFunctionInvocation(r))}async rejectFunction(t){const r=this.pendingApprovals.get(t);if(!r)return;this.pendingApprovals.delete(t);const i={approved:!1,reason:"user_rejected"};try{const s=await this.submitToolCallForm(t,{result:i,_type:"client_function_result"});s?.resume?.ready&&this.markResumeSignal(s.resume.message_id,r.conversationId,"resultsReady")}catch(s){c.error("Failed to submit function rejection:",s)}this.eventEmitter.emit("function:result",{invocationId:t,result:i})}async runExternalFunction(t,r){const i={invocationId:`webmcp-${x()}`,functionName:t,arguments:r,conversationId:""},{invocationId:s}=i;this.eventEmitter.emit("function:invoke",i);const n=Date.now();try{const o=await this.functionRegistry.execute(t,r);return this.eventEmitter.emit("function:result",{invocationId:s,result:o}),this.reportExternalCall(t,r,n,{result:o}),o}catch(o){const a=o instanceof Error?o.message:String(o);throw this.eventEmitter.emit("function:result",{invocationId:s,result:null,error:a}),this.reportExternalCall(t,r,n,{error:a}),o}}reportExternalCall(t,r,i,s){const n=this.functionRegistry.get(t);n&&rr({post:(o,a,l)=>this.httpClient.post(o,a,l),declared:this.declaredExternally},{schema:n.schema,args:r,durationMs:Date.now()-i,navigates:n.webmcp?n.webmcp.navigates:void 0,...s})}async getConversations(t){const r=new URLSearchParams;t?.page!==void 0&&r.set("page",String(t.page)),t?.pageSize!==void 0&&r.set("page_size",String(t.pageSize));const i=r.toString(),s=await this.httpClient.get(`/api/sdk/v1/conversations${i?`?${i}`:""}`),n=(Array.isArray(s.data)?s.data:[]).map(o=>({id:String(o.id),title:o.title??"",lastMessageDate:new Date(o.last_message_at??o.created_at??0)}));return{data:n,hasMore:s.has_more??!1,total:s.total??n.length}}async getConversation(t){const r=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),i={id:r.id,title:r.title,lastMessageDate:new Date(r.last_message_at??r.created_at??0),messages:r.messages.map(s=>({id:s.id,conversationId:r.id,content:s.content,role:s.role,status:s.status,createdAt:new Date(s.created_at),hidden:s.hidden,sources:s.sources&&s.sources.length>0?s.sources.map(({id:n,title:o,url:a})=>({id:n,title:o,url:a??void 0})):void 0,toolCalls:R.mapPersistedToolCalls(s.tool_call_data),attachments:s.attachments&&s.attachments.length>0?s.attachments.map(Jt):void 0,followUpReplies:s.follow_up_replies&&s.follow_up_replies.length>0?s.follow_up_replies:void 0}))};return this.eventEmitter.emit("conversation:loaded",i),i}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(r=>({id:String(r.id??""),type:r.type??"status_message",status:String(r.status??"unknown"),toolName:r.tool_name??"",toolDisplayName:r.tool_display_name,message:r.message,formSchema:r.form_schema,data:r.data,functionName:r.function_name,arguments:r.arguments,displayMode:r.display_mode,askToTalkToHuman:r.ask_to_talk_to_human,allowedToCreateTicket:r.allowed_to_create_ticket,ticket:r.ticket,mode:r.mode,ticketFormId:r.ticket_form_id,embedHtml:r.embed_html,embedDescription:r.embed_description}))}async transcribeAudio(t,r){const i=new FormData;return i.append("file",t,t.name),(await this.httpClient.postFormData("/api/sdk/v1/audio/transcriptions",i,r)).json()}getLanguage(){return S(this.config.language)}async getConfig(){const t=new URLSearchParams({ticket_form_i18n:"1"});t.set("language",$e(this.config.language));const r=await this.httpClient.get(`/api/sdk/v1/config?${t}`);return{permissions:(r.permissions??[]).map(i=>({id:i.id??void 0,name:i.name??void 0,displayName:i.display_name??void 0,agents:(i.agents??[]).map(s=>({id:s.id,name:s.name??void 0})),ticketForm:i.ticket_form?R.mapTicketForm(i.ticket_form):void 0,homePage:i.home_page?R.mapHomePage(i.home_page):void 0,fileAttachmentsEnabled:!!i.file_attachments_enabled,voiceEnabled:!!i.voice_enabled,speechToTextEnabled:!!i.speech_to_text_enabled})),proactive:{enabled:!!r.proactive?.enabled}}}static mapHomePage(t){const r=t.widget_starter;return{title:t.title??void 0,subtitle:t.subtitle??void 0,starters:(t.home_starters??[]).flatMap(i=>{const s=i.description||i.title||"",n=i.initial_message||s;return!s||!n?[]:[{id:i.id,label:s,message:n,agentId:i.agent_id??void 0}]}),widgetStarter:r&&r.initial_message?{id:r.id,message:r.initial_message,agentId:r.agent_id??void 0}:void 0}}static mapTicketForm(t){return{id:t.id,name:t.name??void 0,embedDescription:t.embed_description??void 0,mode:t.mode==="embed"?"embed":"form",showSubject:t.show_subject??!0,showBody:t.show_body??!0,showPriority:t.show_priority??!0,showTypology:t.show_typology??!0,priorityTypologies:t.priority_typologies??void 0,successMessageText:t.success_message_text??void 0,successMessageUrlLabel:t.success_message_url_label??void 0,fields:(t.fields??[]).map(r=>({id:r.id,externalId:r.external_id??void 0,title:r.title??void 0,prefillAliases:r.prefill_aliases,type:r.type??void 0,required:!!r.required,hidden:!!r.hidden,active:r.active,alwaysVisible:r.always_visible,regexpForValidation:r.regexp_for_validation??void 0,position:r.position??0,options:(r.options??[]).map(i=>({id:i.id,name:i.name??void 0,value:i.value??void 0,default:!!i.default,position:i.position??void 0,group:i.group??void 0,noDisplay:i.no_display,conditionalFieldId:i.conditional_field_id??void 0,conditionalFieldValues:i.conditional_field_values??void 0,message:i.message??void 0,messageType:i.message_type??"info"})),conditionalFieldId:r.conditional_field_id??void 0,conditionalFieldValue:r.conditional_field_value??void 0,conditionalFieldValues:r.conditional_field_values??void 0}))}}async createTicket(t){const r=new FormData;r.append("subject",t.subject),r.append("body",t.body),t.priority&&r.append("priority",t.priority),t.typology&&r.append("typology",t.typology),t.conversationId&&r.append("conversation_id",t.conversationId),t.email&&r.append("email",t.email),t.customFields&&t.customFields.length>0&&r.append("custom_fields",JSON.stringify(t.customFields));for(const s of t.files??[])r.append("files",s,s.name);t.ticketFormId&&r.append("ticket_form_id",t.ticketFormId);const i=await(await this.httpClient.postFormData("/api/sdk/v1/tickets",r)).json();return{id:String(i.id??""),url:typeof i.url=="string"&&i.url?i.url:void 0}}async getMessages(t){return(await this.getConversation(t)).messages||[]}async resumePendingClientFunctions(t){const r=[...t.messages??[]].reverse().find(a=>a.role==="assistant"&&a.status==="WAITING_CLIENT");if(!r)return null;const i=(r.toolCalls??[]).filter(a=>a.type==="client_function"&&a.status==="waiting_input"&&a.functionName),s=new Set(this.functionRegistry.getSchemas().map(a=>a.name)),n=i.filter(a=>!s.has(a.functionName));if(n.length>0)return c.warn("Cannot resume paused turn: function(s) not registered on this page:",n.map(a=>a.functionName)),null;let o=i.length===0;for(const a of i){const l={invocationId:a.id,functionName:a.functionName,arguments:a.arguments??{},conversationId:t.id};if(this.requiresApproval(l)){this.pendingApprovals.set(a.id,l),this.markResumeSignal(r.id,t.id,"waitingConfirmed"),this.eventEmitter.emit("function:awaiting-approval",l),o=!1;continue}this.eventEmitter.emit("function:invoke",l);let d,u;try{d=await this.functionRegistry.execute(a.functionName,a.arguments??{})}catch(g){u=g instanceof Error?g.message:"Unknown error",c.error("Client function execution failed:",g)}this.eventEmitter.emit("function:result",{invocationId:a.id,result:d,error:u}),o=(await this.submitToolCallForm(a.id,{result:d,error:u,_type:"client_function_result"}))?.resume?.ready??o}return o?this.continueMessage(r.id):null}async submitToolCallForm(t,r){return this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:r})}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 r=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:r.name,description:r.description,schema:r.schema,submit:r.submit??void 0}}async submitFormCollector(t,r){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:r})}async submitFeedback(t,r,i){const s=i?.comment?.trim(),n=i?.reasons?.length?[...new Set(i.reasons)]:[];await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:r,...n.length?{reasons:n}:{},...s?{comment:s}:{}})}async submitConversationFeedback(t,r,i){let s=i?.lastMessageId;if(!s){const n=[...(await this.getConversation(t)).messages??[]].reverse().find(o=>o.role==="assistant"&&!o.hidden&&!!o.content&&o.status!=="IN_PROGRESS"&&o.status!=="WAITING_CLIENT");if(!n)throw new v.AgoError(`Conversation ${t} has no finished answer to report feedback on. Wait for the turn to complete, or pass \`lastMessageId\`.`,"feedback_no_message");s=n.id}return await this.submitFeedback(s,r,i),s}registerFunction(t,r,i){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,r,i)}register(t){if(Array.isArray(t))for(const r of t)this.functionRegistry.register(r);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}onFunctionsChanged(t){return this.functionRegistry.onChange(t)}getFunctionRegistrations(){return this.functionRegistry.getAll()}async executeClientFunction(t,r){return this.functionRegistry.execute(t,r)}registerNavigationFunction(t,r,i){this.registerFunction(lt(t,r,i)),i?.catalogue==="onDemand"?(this.registerFunction(ut(r)),this.listPagesRegistered=!0):this.listPagesRegistered&&(this.unregisterFunction(T),this.listPagesRegistered=!1),this.addDynamicContext("current-page",()=>{if(typeof window>"u"||!window.location)return null;const s=window.location.href,n=at(window.location.pathname,r),o={url:s};return n&&(o.page=n.name),{name:"Current page",description:"The page the user is currently viewing.",data:o}})}unregisterNavigationFunction(){this.unregisterFunction(J),this.listPagesRegistered&&(this.unregisterFunction(T),this.listPagesRegistered=!1),this.removeDynamicContext("current-page")}registerPageStateFunction(t,r){const i=r?.functionName??"setPageState",s=r?.data;this.registerFunction(ft(t,{name:i,requiresApproval:r?.requiresApproval,getResultBudget:()=>s?this.pageDataBudget(s):this.functionRegistry.getDefaultMaxResultBytes(),data:s?{description:s.description,maxResultBytes:s.maxResultBytes,read:async o=>ee(i,await this.readPageData(i,s,r),this.pageDataBudget(s)-this.envelopeBytes(o))}:void 0}));const n=de(i);s?(this.warnIfPlaceholderMode(i),this.registerFunction(n,async()=>({data:ee(i,await this.readPageData(i,s,r),this.pageDataBudget(s)-this.envelopeBytes({}))}),{description:`Read what the current page is displaying, without changing anything: ${s.description}`,parameters:{type:"object",properties:{}},maxResultBytes:s.maxResultBytes}),this.pageDataCompanions.add(n)):this.pageDataCompanions.delete(n)&&this.unregisterFunction(n),this.addDynamicContext(`page-state:${i}`,()=>{const o=t.filter(l=>typeof l.get=="function");if(o.length===0)return null;const a={};for(const l of o)a[l.name]=l.get();return{name:"Page state",description:"Current, editable state of the page the user is viewing.",data:a}})}unregisterPageStateFunction(t){const r=t??"setPageState";this.unregisterFunction(r);const i=de(r);this.pageDataCompanions.delete(i)&&this.unregisterFunction(i),this.removeDynamicContext(`page-state:${r}`)}pageDataBudget(t){return t.maxResultBytes??this.functionRegistry.getDefaultMaxResultBytes()}envelopeBytes(t){return _(JSON.stringify({...t,data:null}))-4}readPageData(t,r,i){return et(()=>r,i?.settleTimeoutMs??1e4).catch(s=>(c.warn(`Reading page data for "${t}" failed:`,s),{error:"page_data_unavailable",message:s instanceof Error?s.message:String(s)}))}warnIfPlaceholderMode(t){this.warnedPageDataPlaceholder||this.config.clientFunctionsMode==="placeholder"&&(this.warnedPageDataPlaceholder=!0,c.warn(`"${t}" declares a data source, but clientFunctionsMode is "placeholder": the agent will not see that data during the turn it calls the function. Switch to "pause" (the default) for the data to come back as the result of its own call.`))}setContext(t,r){this.contextRegistry.set(t,r),this.notifyContextChanged()}removeContext(t){const r=this.contextRegistry.remove(t);return r&&this.notifyContextChanged(),r}addDynamicContext(t,r){this.contextRegistry.addDynamicProvider(t,r),this.notifyContextChanged()}removeDynamicContext(t){const r=this.contextRegistry.removeDynamicProvider(t);return r&&this.notifyContextChanged(),r}notifyContextChanged(){this.eventEmitter.emit("context:changed",this.contextRegistry.getSnapshot())}emitFormEvent(t,r){this.eventEmitter.emit(t,r)}emitProactiveEvent(t,r){this.eventEmitter.emit(t,r)}getHttp(){return this.httpClient}getConfiguredAgent(){return this.config.agent||this.config.defaultAgentId}getUserIdentity(){return{email:this.config.userEmail||void 0,hasJwt:!!this.config.userJwt}}enableAutoPageContext(){this.addDynamicContext("browser-page",()=>{const t=typeof window<"u"?window.location.href:void 0,r=typeof document<"u"?document.title:void 0;return!t&&!r?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:t,title:r}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}buildSendContext(){const t=this.contextRegistry.getSnapshot(),r=t?.entries??{},{changes:i,baseline:s}=Wt(this.lastSentPageState,r);return this.lastSentPageState=s,i.length===0?t:{entries:{...r,[nr]:{name:"State changes",description:"Fields in the page state that changed since your last message, as field: <old> -> <new>.",data:{changes:i}}}}}recordActivity(t){this.addActivity(t)}getRecentActivity(){return this.activityLedger.getRecent()}clearActivity(){this.activityLedger.clear()}addActivity(t){const r=this.activityLedger.add(t);this.eventEmitter.emit("activity:recorded",r)}recordAgentAction(t){const r=t.functionName,i=t.arguments;let s,n;if(r==="navigateToPage"){const o=i?.page;s="agent.navigate",n=o?`Agent navigated to "${String(o)}"`:"Agent navigated"}else r==="setPageState"?(s="agent.page_state",n="Agent changed the page state"):(s=`agent.${r}`,n=`Agent ran "${r}"`);this.addActivity({actor:"agent",name:s,summary:n,...i&&Object.keys(i).length>0?{data:{arguments:i}}:{}})}registerActivityContext(){this.contextRegistry.addDynamicProvider(sr,()=>{const t=this.activityLedger.getRecent();return t.length===0?null:{name:"Recent activity",description:"Recent actions by the user and the agent in the app, oldest first. Use this to understand what just happened before this message. Use current-page for the user’s current location.",data:{events:t}}})}enableErrorWatcher(t){this.disableErrorWatcher();const r=new pe(t);this.errorWatcher=r,r.start(),r.subscribe(i=>{this.eventEmitter.emit("error:captured",i),this.notifyContextChanged()}),this.contextRegistry.addDynamicProvider(ue,()=>{const i=r.getErrors();if(i.length===0)return null;const s=Date.now();return{name:"Recent JavaScript errors",description:"JavaScript errors captured on the page in the last minutes, oldest first, with how long ago each last fired (ageMs) and how many times (count). Use them to diagnose when the user reports something broken or unresponsive; do not bring them up otherwise.",data:{errors:i.map(({firstAt:n,lastAt:o,...a})=>({...a,ageMs:Math.max(0,s-o),...n!==o?{firstSeenAgoMs:Math.max(0,s-n)}:{}}))}}})}disableErrorWatcher(){this.errorWatcher&&(this.errorWatcher.destroy(),this.errorWatcher=null,this.contextRegistry.removeDynamicProvider(ue))}reportError(t,r){if(!this.errorWatcher){c.warn("reportError() ignored: enable the error watcher first (errorWatcher: true).");return}this.errorWatcher.report(t,r)}getRecentErrors(){return this.errorWatcher?.getErrors()??[]}clearErrors(){this.errorWatcher?.clear()}on(t,r){this.eventEmitter.on(t,r)}off(t,r){this.eventEmitter.off(t,r)}once(t,r){this.eventEmitter.once(t,r)}waitFor(t,r){return this.eventEmitter.waitFor(t,r)}updateConfig(t){const r={};for(const[o,a]of Object.entries(t))a!==void 0&&(r[o]=a);const i={...this.config,...r};q(i,"AgoClient.updateConfig");const s=S(i.language),n=s!==S(this.config.language);this.config=i,this.httpClient.updateConfig(r),n&&this.eventEmitter.emit("config:changed",{language:s}),r.debug!==void 0&&(r.debug?c.enable():c.disable()),r.maxFunctionResultBytes!==void 0&&this.functionRegistry.setDefaultMaxResultBytes(r.maxFunctionResultBytes),r.errorWatcher!==void 0&&(r.errorWatcher?this.enableErrorWatcher(r.errorWatcher===!0?void 0:r.errorWatcher):this.disableErrorWatcher())}destroy(){this.proactive?.destroy(),this.proactive=null,this.errorWatcher?.destroy(),this.errorWatcher=null,this.detachWebMCP?.(),this.detachWebMCP=null,this.activeTurn?.controller.abort(),this.activeTurn=null,this.pausedTurn=null,this.stoppedTurnIds.clear(),this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.listPagesRegistered=!1,this.contextRegistry.clear(),this.pendingResumes.clear(),this.pendingApprovals.clear(),this.resumeGate=null,c.log("AgoClient destroyed")}reviveAfterDestroy(){this.registerActivityContext(),this.config.errorWatcher&&!this.errorWatcher&&this.enableErrorWatcher(this.config.errorWatcher===!0?void 0:this.config.errorWatcher),this.config.proactive&&!this.proactive&&B(this,this.config.proactive),this.attachWebMCPBridge()}},ar=["inaccurate","incomplete","information_not_found","technical_issue"];Object.defineProperty(exports,"ActivityLedger",{enumerable:!0,get:function(){return ge}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return or}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return Re}});Object.defineProperty(exports,"DEFAULT_MAX_ACTIVITY_ENTRIES",{enumerable:!0,get:function(){return De}});Object.defineProperty(exports,"DEFAULT_MAX_ERRORS",{enumerable:!0,get:function(){return Ue}});Object.defineProperty(exports,"DEFAULT_MAX_ERROR_AGE_MS",{enumerable:!0,get:function(){return We}});Object.defineProperty(exports,"ErrorWatcher",{enumerable:!0,get:function(){return pe}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return xe}});Object.defineProperty(exports,"FEEDBACK_REASONS",{enumerable:!0,get:function(){return ar}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return ye}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return Te}});Object.defineProperty(exports,"SignalCollector",{enumerable:!0,get:function(){return Se}});Object.defineProperty(exports,"attachmentsFromFiles",{enumerable:!0,get:function(){return Ht}});Object.defineProperty(exports,"canInlineImage",{enumerable:!0,get:function(){return qt}});Object.defineProperty(exports,"createAgoProactive",{enumerable:!0,get:function(){return B}});Object.defineProperty(exports,"createStore",{enumerable:!0,get:function(){return Ce}});Object.defineProperty(exports,"formatFileSize",{enumerable:!0,get:function(){return Kt}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return Bt}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return c}});Object.defineProperty(exports,"matchesRoutePattern",{enumerable:!0,get:function(){return Ae}});Object.defineProperty(exports,"matchesWhen",{enumerable:!0,get:function(){return ke}});Object.defineProperty(exports,"partialDeepMatch",{enumerable:!0,get:function(){return X}});Object.defineProperty(exports,"safeAttachmentUrl",{enumerable:!0,get:function(){return Ie}});Object.defineProperty(exports,"uiLanguage",{enumerable:!0,get:function(){return Me}});Object.defineProperty(exports,"validateConfig",{enumerable:!0,get:function(){return q}});
package/dist/vue.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./types-DNr6XEwI.cjs");let a=require("vue");var S=Symbol("ago-client"),I={install(t,e){const n=new y.AgoClient(e);t.provide(S,n)}};function g(t){if(t)return new y.AgoClient(t);const e=(0,a.inject)(S);if(!e)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return e}function b(t={}){const e=t.client??g(),n=(0,a.ref)([]),s=(0,a.ref)(t.conversationId),r=(0,a.ref)(!1),l=(0,a.ref)(null),v=o=>{s.value||(s.value=o.conversationId)},m=o=>{const i=n.value.findIndex(d=>d.id===o.messageId);i>=0&&(n.value[i]={...n.value[i],content:n.value[i].content+o.content})},p=o=>{const i=n.value.findIndex(d=>d.id===o.id);i>=0?n.value[i]=o:n.value.push(o),r.value=!1},C=o=>{l.value=new Error(o.error),r.value=!1},u=()=>{let o=-1;for(let i=n.value.length-1;i>=0;i--){const d=n.value[i];if(d.role==="assistant"&&(d.status==="IN_PROGRESS"||d.status==="WAITING_CLIENT")){o=i;break}}o>=0&&(n.value[o].content?n.value[o]={...n.value[o],status:"CANCELED"}:n.value.splice(o,1)),r.value=!1};(0,a.onMounted)(()=>{e.on("message:start",v),e.on("message:chunk",m),e.on("message:complete",p),e.on("message:error",C),e.on("message:stopped",u)}),(0,a.onUnmounted)(()=>{e.off("message:start",v),e.off("message:chunk",m),e.off("message:complete",p),e.off("message:error",C),e.off("message:stopped",u)});async function c(o,i){r.value=!0,l.value=null;const d={id:`temp-${Date.now()}`,conversationId:s.value||"",content:o,role:"user",status:"DONE",createdAt:new Date},F={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};n.value.push(d,F);try{const f=await e.sendMessage(o,{conversationId:s.value,files:i});f.conversationId&&!s.value&&(s.value=f.conversationId),n.value=n.value.filter(A=>!A.id.startsWith("temp-"));const E={...d,id:d.id.replace("temp-","user-"),conversationId:f.conversationId};return n.value.some(A=>A.id===f.id)?n.value.push(E):n.value.push(E,f),f}catch(f){return l.value=f instanceof Error?f:new Error("Failed to send"),r.value=!1,n.value=n.value.filter(E=>!E.id.startsWith("temp-")),null}}async function h(){await e.stop()}function w(){n.value=[],s.value=void 0,l.value=null}return{messages:n,isLoading:r,error:l,conversationId:s,sendMessage:c,stop:h,clearMessages:w}}function N(t={}){const e=t.client??g(),n=t.autoLoad??!0,s=(0,a.ref)([]),r=(0,a.ref)(null),l=(0,a.ref)(!1),v=(0,a.ref)(null);async function m(){l.value=!0,v.value=null;try{s.value=(await e.getConversations()).data}catch(u){v.value=u instanceof Error?u:new Error("Failed to load conversations")}finally{l.value=!1}}async function p(u){l.value=!0,v.value=null;try{r.value=await e.getConversation(u)}catch(c){v.value=c instanceof Error?c:new Error("Failed to load conversation")}finally{l.value=!1}}function C(){r.value=null}return(0,a.onMounted)(()=>{n&&m()}),{conversations:s,currentConversation:r,isLoading:l,error:v,selectConversation:p,startNewConversation:C,refreshConversations:m}}function M(t={}){const e=b({client:t.client,conversationId:t.conversationId}),n=N({client:t.client,autoLoad:t.autoLoad}),s=(0,a.computed)(()=>e.error.value||n.error.value);return{messages:e.messages,isLoading:e.isLoading,error:s,sendMessage:e.sendMessage,stop:e.stop,clearMessages:e.clearMessages,conversationId:e.conversationId,conversations:n.conversations,currentConversation:n.currentConversation,isConversationsLoading:n.isLoading,selectConversation:n.selectConversation,startNewConversation:n.startNewConversation,refreshConversations:n.refreshConversations}}function L(t={}){const e=t.client??g(),n=(0,a.ref)({}),s=(0,a.ref)(!1),r=(0,a.ref)(null),l=new Map;function v(u){const c=(l.get(u)??0)+1;return l.set(u,c),c}const m=(u,c)=>l.get(u)===c;async function p(u,c,h){const w=v(u);s.value=!0,r.value=null;try{await e.submitFeedback(u,c,h),m(u,w)&&(n.value={...n.value,[u]:c})}catch(o){const i=o instanceof Error?o:new Error("Failed to submit feedback");throw r.value=i,i}finally{s.value=!1}}async function C(u,c,h){const w=v(u);s.value=!0,r.value=null;try{const o=await e.submitConversationFeedback(u,c,h);return m(u,w)&&(n.value={...n.value,[o]:c}),o}catch(o){const i=o instanceof Error?o:new Error("Failed to submit feedback");throw r.value=i,i}finally{s.value=!1}}return{ratings:n,isSubmitting:s,error:r,submitFeedback:p,submitConversationFeedback:C}}function R(t,e){const n=g();(0,a.onMounted)(()=>{n.registerFunction(t,e.handler,{description:e.description,parameters:e.parameters,maxResultBytes:e.maxResultBytes,requiresApproval:e.requiresApproval,webmcp:e.webmcp})}),(0,a.onUnmounted)(()=>{n.unregisterFunction(t)})}function P(t,e,n){const s=g();(0,a.onMounted)(()=>{s.registerNavigationFunction(t,e,{catalogue:n?.catalogue==="onDemand"?"onDemand":"inline"})}),(0,a.onUnmounted)(()=>{s.unregisterNavigationFunction()})}function k(t,e){const n=g(),s=e?.functionName??"setPageState";(0,a.onMounted)(()=>{n.registerPageStateFunction(t,{...e,functionName:s})}),(0,a.onUnmounted)(()=>{n.unregisterPageStateFunction(s)})}function D(t,e){const n=g();(0,a.onMounted)(()=>{n.on(t,e)}),(0,a.onUnmounted)(()=>{n.off(t,e)})}function q(t){const e=(0,a.shallowRef)(t.get());return(0,a.onScopeDispose)(t.subscribe(n=>{e.value=n})),e}function _(){const t=g(),e=(0,a.shallowRef)(null),n=r=>{e.value=r,t.proactive?.shown(r)},s=({nudge:r})=>{e.value?.id===r.id&&(e.value=null)};return(0,a.onMounted)(()=>{t.on("nudge:ready",n),t.on("nudge:accepted",s),t.on("nudge:dismissed",s)}),(0,a.onUnmounted)(()=>{t.off("nudge:ready",n),t.off("nudge:accepted",s),t.off("nudge:dismissed",s)}),{nudge:e,accept:async()=>{const r=e.value;r&&(e.value=null,await t.proactive?.accept(r))},dismiss:()=>{const r=e.value;r&&(e.value=null,t.proactive?.dismiss(r))}}}exports.AGO_CLIENT_KEY=S;exports.AgoPlugin=I;exports.FEEDBACK_REASONS=y.FEEDBACK_REASONS;exports.useAgo=g;exports.useAgoEvents=D;exports.useAgoFunction=R;exports.useAgoNavigation=P;exports.useAgoPageState=k;exports.useAgoStore=q;exports.useChat=M;exports.useConversation=N;exports.useFeedback=L;exports.useMessages=b;exports.useProactiveNudge=_;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./types-PGXnhAmQ.cjs");let a=require("vue");var S=Symbol("ago-client"),I={install(t,e){const n=new y.AgoClient(e);t.provide(S,n)}};function g(t){if(t)return new y.AgoClient(t);const e=(0,a.inject)(S);if(!e)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return e}function b(t={}){const e=t.client??g(),n=(0,a.ref)([]),s=(0,a.ref)(t.conversationId),r=(0,a.ref)(!1),l=(0,a.ref)(null),v=o=>{s.value||(s.value=o.conversationId)},m=o=>{const i=n.value.findIndex(d=>d.id===o.messageId);i>=0&&(n.value[i]={...n.value[i],content:n.value[i].content+o.content})},p=o=>{const i=n.value.findIndex(d=>d.id===o.id);i>=0?n.value[i]=o:n.value.push(o),r.value=!1},C=o=>{l.value=new Error(o.error),r.value=!1},u=()=>{let o=-1;for(let i=n.value.length-1;i>=0;i--){const d=n.value[i];if(d.role==="assistant"&&(d.status==="IN_PROGRESS"||d.status==="WAITING_CLIENT")){o=i;break}}o>=0&&(n.value[o].content?n.value[o]={...n.value[o],status:"CANCELED"}:n.value.splice(o,1)),r.value=!1};(0,a.onMounted)(()=>{e.on("message:start",v),e.on("message:chunk",m),e.on("message:complete",p),e.on("message:error",C),e.on("message:stopped",u)}),(0,a.onUnmounted)(()=>{e.off("message:start",v),e.off("message:chunk",m),e.off("message:complete",p),e.off("message:error",C),e.off("message:stopped",u)});async function c(o,i){r.value=!0,l.value=null;const d={id:`temp-${Date.now()}`,conversationId:s.value||"",content:o,role:"user",status:"DONE",createdAt:new Date},F={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};n.value.push(d,F);try{const f=await e.sendMessage(o,{conversationId:s.value,files:i});f.conversationId&&!s.value&&(s.value=f.conversationId),n.value=n.value.filter(A=>!A.id.startsWith("temp-"));const E={...d,id:d.id.replace("temp-","user-"),conversationId:f.conversationId};return n.value.some(A=>A.id===f.id)?n.value.push(E):n.value.push(E,f),f}catch(f){return l.value=f instanceof Error?f:new Error("Failed to send"),r.value=!1,n.value=n.value.filter(E=>!E.id.startsWith("temp-")),null}}async function h(){await e.stop()}function w(){n.value=[],s.value=void 0,l.value=null}return{messages:n,isLoading:r,error:l,conversationId:s,sendMessage:c,stop:h,clearMessages:w}}function N(t={}){const e=t.client??g(),n=t.autoLoad??!0,s=(0,a.ref)([]),r=(0,a.ref)(null),l=(0,a.ref)(!1),v=(0,a.ref)(null);async function m(){l.value=!0,v.value=null;try{s.value=(await e.getConversations()).data}catch(u){v.value=u instanceof Error?u:new Error("Failed to load conversations")}finally{l.value=!1}}async function p(u){l.value=!0,v.value=null;try{r.value=await e.getConversation(u)}catch(c){v.value=c instanceof Error?c:new Error("Failed to load conversation")}finally{l.value=!1}}function C(){r.value=null}return(0,a.onMounted)(()=>{n&&m()}),{conversations:s,currentConversation:r,isLoading:l,error:v,selectConversation:p,startNewConversation:C,refreshConversations:m}}function M(t={}){const e=b({client:t.client,conversationId:t.conversationId}),n=N({client:t.client,autoLoad:t.autoLoad}),s=(0,a.computed)(()=>e.error.value||n.error.value);return{messages:e.messages,isLoading:e.isLoading,error:s,sendMessage:e.sendMessage,stop:e.stop,clearMessages:e.clearMessages,conversationId:e.conversationId,conversations:n.conversations,currentConversation:n.currentConversation,isConversationsLoading:n.isLoading,selectConversation:n.selectConversation,startNewConversation:n.startNewConversation,refreshConversations:n.refreshConversations}}function L(t={}){const e=t.client??g(),n=(0,a.ref)({}),s=(0,a.ref)(!1),r=(0,a.ref)(null),l=new Map;function v(u){const c=(l.get(u)??0)+1;return l.set(u,c),c}const m=(u,c)=>l.get(u)===c;async function p(u,c,h){const w=v(u);s.value=!0,r.value=null;try{await e.submitFeedback(u,c,h),m(u,w)&&(n.value={...n.value,[u]:c})}catch(o){const i=o instanceof Error?o:new Error("Failed to submit feedback");throw r.value=i,i}finally{s.value=!1}}async function C(u,c,h){const w=v(u);s.value=!0,r.value=null;try{const o=await e.submitConversationFeedback(u,c,h);return m(u,w)&&(n.value={...n.value,[o]:c}),o}catch(o){const i=o instanceof Error?o:new Error("Failed to submit feedback");throw r.value=i,i}finally{s.value=!1}}return{ratings:n,isSubmitting:s,error:r,submitFeedback:p,submitConversationFeedback:C}}function R(t,e){const n=g();(0,a.onMounted)(()=>{n.registerFunction(t,e.handler,{description:e.description,parameters:e.parameters,maxResultBytes:e.maxResultBytes,requiresApproval:e.requiresApproval,webmcp:e.webmcp})}),(0,a.onUnmounted)(()=>{n.unregisterFunction(t)})}function P(t,e,n){const s=g();(0,a.onMounted)(()=>{s.registerNavigationFunction(t,e,{catalogue:n?.catalogue==="onDemand"?"onDemand":"inline"})}),(0,a.onUnmounted)(()=>{s.unregisterNavigationFunction()})}function k(t,e){const n=g(),s=e?.functionName??"setPageState";(0,a.onMounted)(()=>{n.registerPageStateFunction(t,{...e,functionName:s})}),(0,a.onUnmounted)(()=>{n.unregisterPageStateFunction(s)})}function D(t,e){const n=g();(0,a.onMounted)(()=>{n.on(t,e)}),(0,a.onUnmounted)(()=>{n.off(t,e)})}function q(t){const e=(0,a.shallowRef)(t.get());return(0,a.onScopeDispose)(t.subscribe(n=>{e.value=n})),e}function _(){const t=g(),e=(0,a.shallowRef)(null),n=r=>{e.value=r,t.proactive?.shown(r)},s=({nudge:r})=>{e.value?.id===r.id&&(e.value=null)};return(0,a.onMounted)(()=>{t.on("nudge:ready",n),t.on("nudge:accepted",s),t.on("nudge:dismissed",s)}),(0,a.onUnmounted)(()=>{t.off("nudge:ready",n),t.off("nudge:accepted",s),t.off("nudge:dismissed",s)}),{nudge:e,accept:async()=>{const r=e.value;r&&(e.value=null,await t.proactive?.accept(r))},dismiss:()=>{const r=e.value;r&&(e.value=null,t.proactive?.dismiss(r))}}}exports.AGO_CLIENT_KEY=S;exports.AgoPlugin=I;exports.FEEDBACK_REASONS=y.FEEDBACK_REASONS;exports.useAgo=g;exports.useAgoEvents=D;exports.useAgoFunction=R;exports.useAgoNavigation=P;exports.useAgoPageState=k;exports.useAgoStore=q;exports.useChat=M;exports.useConversation=N;exports.useFeedback=L;exports.useMessages=b;exports.useProactiveNudge=_;
package/dist/vue.d.cts CHANGED
@@ -253,6 +253,8 @@ declare class AgoClient {
253
253
  * Show the returned text as a draft; call `sendMessage` when the user sends it.
254
254
  */
255
255
  transcribeAudio(file: File, options?: TranscribeAudioOptions): Promise<AudioTranscription>;
256
+ /** The requested language, before UI fallback. */
257
+ getLanguage(): string | null;
256
258
  /**
257
259
  * The tenant's SDK configuration (`GET /api/sdk/v1/config`): per-permission
258
260
  * agents, the ticket form the agent's `ago_ticketing` tool opens, and the
@@ -628,6 +630,9 @@ declare class AgoClient {
628
630
  * SDK Events
629
631
  */
630
632
  declare interface AgoClientEvents {
633
+ "config:changed": {
634
+ language: string | null;
635
+ };
631
636
  /**
632
637
  * The client-side context changed: a context entry or dynamic provider was
633
638
  * added/removed, or a stateful helper (e.g. `createFormCollector`) updated its
@@ -2017,6 +2022,7 @@ declare interface SubmitToolCallResult {
2017
2022
 
2018
2023
  /** A custom field of a ticket form. */
2019
2024
  declare interface TicketField {
2025
+ prefillAliases?: string[];
2020
2026
  id: string;
2021
2027
  /** The key the ticketing backend expects; used as the submit key when set. */
2022
2028
  externalId?: string;
@@ -2063,6 +2069,7 @@ declare interface TicketFieldOption {
2063
2069
 
2064
2070
  /** The ticket form an agent's `ago_ticketing` tool opens in the conversation. */
2065
2071
  declare interface TicketForm {
2072
+ embedDescription?: string;
2066
2073
  id: string;
2067
2074
  name?: string;
2068
2075
  /** `"form"` renders the SDK's own fields; `"embed"` hosts third-party HTML. */
package/dist/vue.d.ts CHANGED
@@ -253,6 +253,8 @@ declare class AgoClient {
253
253
  * Show the returned text as a draft; call `sendMessage` when the user sends it.
254
254
  */
255
255
  transcribeAudio(file: File, options?: TranscribeAudioOptions): Promise<AudioTranscription>;
256
+ /** The requested language, before UI fallback. */
257
+ getLanguage(): string | null;
256
258
  /**
257
259
  * The tenant's SDK configuration (`GET /api/sdk/v1/config`): per-permission
258
260
  * agents, the ticket form the agent's `ago_ticketing` tool opens, and the
@@ -628,6 +630,9 @@ declare class AgoClient {
628
630
  * SDK Events
629
631
  */
630
632
  declare interface AgoClientEvents {
633
+ "config:changed": {
634
+ language: string | null;
635
+ };
631
636
  /**
632
637
  * The client-side context changed: a context entry or dynamic provider was
633
638
  * added/removed, or a stateful helper (e.g. `createFormCollector`) updated its
@@ -2017,6 +2022,7 @@ declare interface SubmitToolCallResult {
2017
2022
 
2018
2023
  /** A custom field of a ticket form. */
2019
2024
  declare interface TicketField {
2025
+ prefillAliases?: string[];
2020
2026
  id: string;
2021
2027
  /** The key the ticketing backend expects; used as the submit key when set. */
2022
2028
  externalId?: string;
@@ -2063,6 +2069,7 @@ declare interface TicketFieldOption {
2063
2069
 
2064
2070
  /** The ticket form an agent's `ago_ticketing` tool opens in the conversation. */
2065
2071
  declare interface TicketForm {
2072
+ embedDescription?: string;
2066
2073
  id: string;
2067
2074
  name?: string;
2068
2075
  /** `"form"` renders the SDK's own fields; `"embed"` hosts third-party HTML. */
package/dist/vue.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as I, t as x } from "./types-D1ZrqVhr.js";
1
+ import { n as I, t as x } from "./types-C39MJUE3.js";
2
2
  import { computed as L, inject as M, onMounted as p, onScopeDispose as R, onUnmounted as C, ref as d, shallowRef as F } from "vue";
3
3
  var N = /* @__PURE__ */ Symbol("ago-client"), _ = { install(t, e) {
4
4
  const n = new I(e);