@useago/sdk 1.13.1 → 1.13.2
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.
- package/dist/angular.cjs +1 -1
- package/dist/angular.js +1 -1
- package/dist/{createConversationSession-Ri3EKIJU.cjs → createConversationSession-Digvn0GQ.cjs} +1 -1
- package/dist/{createConversationSession-D0vks-8C.js → createConversationSession-DrmOaZdO.js} +1 -1
- package/dist/{createFormCollector-BNCMIUw2.cjs → createFormCollector-Cq7HWjtU.cjs} +1 -1
- package/dist/{createFormCollector-BMN-blXs.js → createFormCollector-ki_GTlp9.js} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/react.cjs +1 -1
- package/dist/react.js +2 -2
- package/dist/{types-fX-VoHfa.js → types-D1ZrqVhr.js} +139 -138
- package/dist/{types-Ck3iZG0K.cjs → types-DNr6XEwI.cjs} +5 -5
- package/dist/vue.cjs +1 -1
- package/dist/vue.js +1 -1
- package/dist/widget.cjs +1 -1
- package/dist/widget.js +3 -3
- package/llms-full.txt +20 -4
- package/package.json +1 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
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
|
|
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
3
|
${t.map(nt).join(`
|
|
4
|
-
`)}`,
|
|
5
|
-
`);return{name:t.name,handler:async n=>{const o=[],a=[],l={};for(const[h,
|
|
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:
|
|
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 u={};for(const[d,f]of Object.entries(l.entries))d.startsWith("page-state:")&&f.data&&Object.assign(u,f.data);return Object.keys(u).length>0?u:null}});r.start();const i=l=>{r.signalJsError(l.type)};e.on("error:captured",i),e.addDynamicContext(ne,()=>{const{pageState:l,...u}=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:u}});const s=new St({frequencyCap:t.frequencyCap,storage:t.storage,storageKey:t.storageKey}),n=new Pt({post:(l,u,d)=>e.getHttp().post(l,u,d),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 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="",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,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(`
|
|
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}::${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 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 Gt(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 qt(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 d of t)d?.removeEventListener("abort",n);u(),r()}},o=()=>{clearTimeout(l),clearTimeout(i),i=setTimeout(n,Jt)},a=setTimeout(n,Kt),l=setTimeout(n,Ht),u=e(o);for(const d of t){if(d?.aborted)return n();d?.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(p){return JSON.stringify([p.description,p.inputSchema,p.annotations])}function u(p,h){const g=e.getFunctionRegistrations().find(y=>y.name===p)?.webmcp;return!g||!g.navigates?!1:h?.success!==!1}function d(){const p=new Map;for(const h of e.getFunctionRegistrations()){if(h.webmcp===!1)continue;const g=h.webmcp||void 0,y=h.name,S={name:y,description:h.schema.description,inputSchema:h.schema.parameters,annotations:g?.annotations,execute:async(b,xe)=>{const z=await e.runExternalFunction(y,b??{});return!o&&u(y,z)&&await zt(Fe=>e.onFunctionsChanged(Fe),[xe?.signal,n.signal]),z}};p.set(y,{tool:S,signature:l(S)})}return p}function f(){o||a||(a=!0,queueMicrotask(()=>{a=!1,m()}))}function m(){if(o)return;const p=d();for(const[h,g]of i)p.get(h)?.signature!==g.signature&&(g.controller.abort(),i.delete(h));for(const[h,g]of p){if(i.has(h))continue;const y=new AbortController;i.set(h,{signature:g.signature,controller:y}),Promise.resolve(r.registerTool(g.tool,{signal:y.signal})).catch(S=>{if(c.error(`WebMCP rejected the tool "${h}":`,S),i.get(h)?.controller!==y)return;i.delete(h);const b=JSON.stringify([h,g.signature]);s.has(b)||(s.add(b),f())})}}const w=e.onFunctionsChanged(f);return m(),c.log("WebMCP bridge attached"),()=>{if(!o){o=!0,n.abort(),w();for(const p of i.values())p.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 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");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,q(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,u={content:t,conversation_id:r?.conversationId,agent_id:r?.agentId||n};a!=null&&(u.metadata=a),i.length>0&&(u.client_functions=i,o==="pause"&&(u.client_functions_mode=o)),s&&(u.client_context=s),r?.hidden&&(u.hidden=!0);const d=this.beginTurn();let f;if(r?.files&&r.files.length>0){const m=new FormData;m.append("content",t),l!==void 0&&m.append("metadata",l),r.conversationId&&m.append("conversation_id",r.conversationId),(r.agentId||n)&&m.append("agent_id",r.agentId||n||""),i.length>0&&(m.append("client_functions",JSON.stringify(i)),o==="pause"&&m.append("client_functions_mode",o)),s&&m.append("client_context",JSON.stringify(s)),r.hidden&&m.append("hidden","true");for(const w of r.files)m.append("files",w);f=await this.sendRequest(d,()=>this.httpClient.postFormData("/api/sdk/v1/messages",m,{signal:d.controller.signal}))}else f=await this.sendRequest(d,()=>this.httpClient.postStream("/api/sdk/v1/messages",u,{signal:d.controller.signal}));return f?this.processSSEResponse(f,d):this.buildStoppedMessage(d)}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(Gt):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 u,d;try{u=await this.functionRegistry.execute(a.functionName,a.arguments??{})}catch(f){d=f instanceof Error?f.message:"Unknown error",c.error("Client function execution failed:",f)}this.eventEmitter.emit("function:result",{invocationId:a.id,result:u,error:d}),o=(await this.submitToolCallForm(a.id,{result:u,error:d,_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=typeof document<"u"?document.title:void 0,o=st(window.location.pathname,r),a={url:s};return o&&(a.page=o.name),n&&(a.title=n),{name:"Current page",description:"The page the user is currently viewing.",data:a}})}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 E(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.",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};q(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 qt}});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 q}});
|
|
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}});
|
package/dist/vue.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./types-
|
|
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=_;
|
package/dist/vue.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as I, t as x } from "./types-
|
|
1
|
+
import { n as I, t as x } from "./types-D1ZrqVhr.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);
|
package/dist/widget.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=require("./types-Ck3iZG0K.cjs"),si=require("./errors-o1IB5fEu.cjs"),li=require("./createConversationSession-Ri3EKIJU.cjs"),to=require("./createFormCollector-BNCMIUw2.cjs"),n=require("./speechToText-ZciRyyJE.cjs");var di=10*1024*1024;var no=["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/csv","application/json","application/xml","text/xml","text/html","application/epub+zip"];function oo(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function ci(t){const e=t.look==="embed";let i=[];const o=new Map,r=document.createElement("form");r.className=e?"ago-chat-input ago-chat-input--embed":"ago-chat-input",e?n.css(r,{width:"100%",borderRadius:"24px",border:`2px solid ${n.PRIMARY_FOREGROUND}`,backgroundColor:"#fff",boxShadow:n.SHADOW,position:"relative",boxSizing:"border-box",display:"block",fontFamily:n.FONT_VAR}):n.css(r,{display:"flex",flexDirection:"column",gap:"8px",padding:"12px",borderTop:`1px solid ${n.BORDER_COLOR}`,backgroundColor:n.PANEL_BACKGROUND});const s=n.div(e?{display:"none",flexWrap:"wrap",gap:"8px",padding:"0 0 8px"}:{display:"flex",flexWrap:"wrap",gap:"6px"});s.className="ago-chat-input__files";const c=n.div(e?{display:"flex",flexDirection:"row",gap:"8px",padding:"16px"}:{display:"flex",gap:"8px",alignItems:"flex-end"}),d=document.createElement("textarea");d.placeholder=t.placeholder,d.setAttribute("aria-label",t.placeholder),d.rows=1,d.autocapitalize="off",d.setAttribute("autocorrect","off");const h=e?208:110;e?n.css(d,{display:"block",width:"100%",minHeight:"40px",maxHeight:`${h}px`,overflowY:"auto",resize:"none",border:"none",outline:"none",boxShadow:"none",background:"transparent",padding:"8px",boxSizing:"border-box",fontSize:"16px",lineHeight:"24px",fontFamily:"inherit",color:"inherit"}):n.css(d,{flex:"1",resize:"none",boxSizing:"border-box",padding:"10px 12px",border:`1px solid ${n.BORDER_COLOR}`,borderRadius:"12px",fontSize:"16px",fontFamily:n.FONT_VAR,lineHeight:"1.4",maxHeight:`${h}px`,overflowY:"hidden"});const f=()=>{const m=e?0:2;d.style.height="auto";const B=Math.min(d.scrollHeight+m,h);d.style.height=`${B}px`,d.style.overflowY=d.scrollHeight+m>h?"auto":"hidden"};d.addEventListener("input",()=>{f(),E()});const p='<svg width="18" height="18" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-160v-487L216-423l-56-57 320-320 320 320-56 57-224-224v487h-80Z"/></svg>',x='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="animation: ago-spin 0.8s linear infinite"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',I='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="5" y="5" width="14" height="14" rx="2"/></svg>',w=document.createElement("button");w.type="submit",w.className="ago-chat-input__send",w.setAttribute("aria-label","Send"),e?n.css(w,{flexShrink:"0",width:"40px",height:"40px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:n.SEND_BACKGROUND,color:"#fafafa",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"background-color 0.15s, color 0.15s"}):(w.innerHTML=p,n.css(w,{flexShrink:"0",width:"44px",height:"44px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:n.BRAND_COLOR,color:n.BRAND_TEXT_COLOR,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}));let u=!1,v=!1;const A=()=>u&&!!t.onStop,E=()=>{const m=d.value.trim()!=="",B=A(),G=!B&&(u||v||!m);if(w.disabled=G,w.type=B?"button":"submit",w.setAttribute("aria-label",B?"Stop generating":"Send"),e){w.replaceChildren(B?n.stopIcon({size:16}):n.arrowUpwardIcon({size:16}));const P=G&&!u;w.style.backgroundColor=P?"#f1f5f9":n.SEND_BACKGROUND,w.style.color=P?"#cbd5e1":"#fafafa",w.style.pointerEvents=G?"none":"auto",w.style.cursor=G?"default":"pointer",J.style.opacity=u?"0.5":"1";return}w.innerHTML=B?I:u?x:p,w.style.opacity=G&&!u?"0.5":"1",w.style.cursor=G?"default":"pointer"};w.addEventListener("click",()=>{A()&&t.onStop?.()});const O=n.div({display:"none",alignItems:"flex-start",justifyContent:"space-between",gap:"8px",margin:"0 0 12px",padding:"12px 16px",borderRadius:"12px",border:"1px solid rgba(239, 68, 68, 0.5)",color:"#ef4444",backgroundColor:"#fff",fontSize:"14px",lineHeight:"20px"});O.className="ago-chat-input__error",O.setAttribute("role","alert");const W=document.createElement("span"),C=document.createElement("button");C.type="button",C.textContent=t.labels?.dismiss??"Dismiss",n.css(C,{border:"none",background:"transparent",color:"inherit",font:"inherit",fontWeight:"500",cursor:"pointer",padding:"0",minHeight:"20px"}),C.addEventListener("click",()=>{O.style.display="none"}),O.append(W,C);const F=m=>{W.textContent=m,O.style.display="flex"},y=(m,B)=>m.replace(/\{(\w+)\}/g,(G,P)=>B[P]??""),k=m=>{if(!e)return m;const B=t.labels,G=[];for(const P of m){if(i.length+G.length>=5){F(y(B?.tooManyFiles??"Too many files. Maximum allowed: {max}",{max:String(5)}));break}if(P.type&&!no.includes(P.type)){F(y(B?.invalidFileType??"Invalid file type: {name}",{name:P.name}));continue}if(P.size>10485760){F(y(B?.fileTooLarge??"File too large: {name} (maximum {max})",{name:P.name,max:oo(di)}));continue}G.push(P)}return G};let S=null,D=null;t.allowFiles&&(S=document.createElement("input"),S.type="file",S.multiple=!0,e&&(S.accept=no.join(",")),n.css(S,{display:"none"}),D=document.createElement("button"),D.type="button",D.className="ago-chat-input__attach",D.setAttribute("aria-label",t.labels?.attachFiles??"Attach file"),e?(D.appendChild(n.attachFileIcon({size:16})),n.css(D,{height:"40px",padding:"8px",display:"flex",alignItems:"center",gap:"4px",fontSize:"14px",color:n.BRAND_COLOR,background:"none",border:"none",cursor:"pointer",borderRadius:"6px"})):(D.textContent="📎",n.css(D,{flexShrink:"0",minWidth:"44px",minHeight:"44px",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 12px",border:`1px solid ${n.BORDER_COLOR}`,borderRadius:"12px",backgroundColor:n.PANEL_BACKGROUND,cursor:"pointer",fontSize:"14px"})),D.addEventListener("click",()=>S?.click()),S.addEventListener("change",()=>{const m=Array.from(S?.files??[]);i=[...i,...k(m)],S&&(S.value=""),j()}));function V(m){if(!e||!m.type.startsWith("image/")||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;let B=o.get(m);return B||(B=URL.createObjectURL(m),o.set(m,B)),B}function M(m){const B=o.get(m);B&&(URL.revokeObjectURL(B),o.delete(m))}function j(){s.replaceChildren(),e&&(s.style.display=i.length>0?"flex":"none"),i.forEach((m,B)=>{const G=n.div(e?{display:"flex",alignItems:"center",gap:"8px",backgroundColor:"#f3f4f6",borderRadius:"8px",padding:"8px 12px",fontSize:"14px",lineHeight:"20px"}:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#f0f4ff",border:`1px solid ${n.BORDER_COLOR}`,borderRadius:"8px",fontSize:"12px"});if(G.className="ago-chat-input__file",e){const re=V(m);if(re){const be=document.createElement("img");be.src=re,be.alt="",n.css(be,{width:"32px",height:"32px",objectFit:"cover",borderRadius:"4px",flexShrink:"0"}),G.appendChild(be)}else G.appendChild(n.descriptionIcon({size:20}))}const P=document.createElement("span");if(P.textContent=m.name,P.title=m.name,e&&n.css(P,{maxWidth:"150px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),G.appendChild(P),e){const re=document.createElement("span");re.textContent=oo(m.size),n.css(re,{fontSize:"12px",lineHeight:"16px",color:"#6b7280"}),G.appendChild(re)}const ee=document.createElement("button");ee.type="button",ee.setAttribute("aria-label",`Remove ${m.name}`),e?ee.appendChild(n.closeIcon({size:16})):ee.textContent="×",n.css(ee,{flexShrink:"0",width:"44px",height:"44px",margin:e?"-10px -16px -10px -8px":"-14px -12px -14px -4px",display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",cursor:"pointer",fontSize:"14px",lineHeight:"1",color:"inherit"}),ee.addEventListener("click",()=>{M(m),i=i.filter((re,be)=>be!==B),j()}),G.appendChild(ee),s.appendChild(G)}),E()}const b=()=>{z?.cancel();const m=d.value,B=i;d.value="",f(),i=[];for(const G of B)M(G);return j(),{content:m,files:B}},R=()=>{if(u||v||!d.value.trim())return;const{content:m,files:B}=b();t.onSend(m.trim(),B.length>0?B:void 0),e&&typeof window<"u"&&window.innerWidth<(t.blurOnSubmitBelow??600)&&d.blur()};r.addEventListener("submit",m=>{m.preventDefault(),R()}),d.addEventListener("keydown",m=>{if(m.key==="Enter"&&!m.shiftKey){if(m.isComposing||m.keyCode===229)return;m.preventDefault(),R()}});const z=t.transcribeAudio?n.createSpeechToText({transcribe:t.transcribeAudio,labels:t.speechToTextLabels,onBusy:m=>{const B=v&&!m&&!u&&r.contains(document.activeElement);v=m,d.disabled=u||m,e?(J.style.display=m?"none":"",Y.style.display=m?"none":"flex",c.style.padding=m?"8px":"16px",z&&(m?c.append(z.el):Y.prepend(z.el))):(d.style.display=m?"none":"",w.style.display=m?"none":"flex",D&&(D.style.display=m?"none":"flex")),E(),B&&d.focus()},onText:m=>{d.value+=`${d.value&&!/\s$/.test(d.value)?" ":""}${m}`,f(),E(),d.focus()},onError:F}):void 0,J=n.div({flex:"1",minWidth:"0"});J.className="ago-chat-input__editor";const Y=n.div({display:"flex",alignItems:"flex-end",flexShrink:"0",gap:"4px"});if(e){J.append(O,s,d);const m=n.div({display:"flex",alignItems:"center"});m.className="ago-chat-input__toolbar",D&&m.appendChild(D),D&&J.appendChild(m),z&&Y.appendChild(z.el),Y.appendChild(w),c.append(J,Y),S&&r.appendChild(S),r.appendChild(c),r.addEventListener("click",B=>{(B.target instanceof Element?B.target:null)?.closest("button,a,input,textarea")||d.focus()})}else D&&c.appendChild(D),c.append(d),z&&c.appendChild(z.el),c.append(w),S&&r.appendChild(S),r.append(O,s,c);return E(),{inputRow:r,getValueAndClear:b,setDisabled:m=>{u=m,z?.setDisabled(m),d.disabled=m||v,E()},focus:()=>d.focus(),blur:()=>d.blur(),restoreDraft:(m,B)=>{m&&!d.value.trim()&&(d.value=m,f()),B?.length&&(i=[...B,...i],j()),E()},setPlaceholder:m=>{d.placeholder=m,m&&d.setAttribute("aria-label",m)},setSpeechToTextEnabled:m=>z?.setEnabled(m),cancelRecording:()=>z?.cancel(),destroy:()=>{z?.destroy();for(const m of o.keys())M(m)}}}var on="rgba(3, 24, 47, 0.07)";function pi(t){const e=document.createElement("footer");e.className="ago-chat-widget__footer",n.css(e,{padding:"12px",flexShrink:"0",background:"transparent"});const i=document.createElement("nav");n.css(i,{display:"flex",alignItems:"center",gap:"4px",width:"100%"});const o=new Map;let r="home";function s(d,h,f){const p=document.createElement("button");p.type="button",p.className="ago-chat-widget__tab",p.dataset.agoScreen=d,n.css(p,{flex:"1",minWidth:"0",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",padding:"12px 8px",borderRadius:"32px",border:"none",background:"transparent",color:n.BRAND_COLOR,cursor:"pointer",transition:"background-color 0.15s",font:"inherit"});const x=document.createElement("span");return x.textContent=h,n.css(x,{fontSize:"12px",lineHeight:"16px",maxWidth:"100%",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),p.append(f,x),p.addEventListener("mouseenter",()=>{p.style.backgroundColor=on}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor=r===d?on:"transparent"}),p.addEventListener("click",()=>t.onNavigate(d)),o.set(d,p),p}i.append(s("home",t.labels.home,n.houseIcon({size:24})),s("history",t.labels.chats,n.conversationsIcon({size:24}))),e.appendChild(i);const c=d=>{r=d==="history"?"history":"home";for(const[h,f]of o){const p=h===r;f.style.color=p?n.PRIMARY_ACCENT:n.BRAND_COLOR,f.style.backgroundColor=p?on:"transparent",p?f.setAttribute("aria-current","page"):f.removeAttribute("aria-current")}};return c("home"),{el:e,setActive:c,setVisible:d=>{e.style.display=d?"block":"none"}}}function rn(t,e,i,o){const r=document.createElement("button");return r.type="button",r.className=t,r.setAttribute("aria-label",e),r.title=e,n.css(r,{display:"flex",alignItems:"center",justifyContent:"center",width:"44px",height:"44px",margin:"-12px",padding:"0",border:"none",background:"transparent",color:"currentColor",opacity:"0.8",cursor:"pointer",transition:"opacity 0.15s",flexShrink:"0"}),r.addEventListener("mouseenter",()=>{r.style.opacity="1"}),r.addEventListener("mouseleave",()=>{r.style.opacity="0.8"}),r.addEventListener("click",o),r.appendChild(i),r}function ui(t){const e=document.createElement("header");e.className="ago-chat-widget__header",n.css(e,{display:"flex",alignItems:"center",justifyContent:"space-between",height:"56px",padding:"0 16px",boxSizing:"border-box",background:n.HEADER_BACKGROUND,color:n.HEADER_TEXT_COLOR,borderBottom:"1px solid #e5e7eb",boxShadow:n.SHADOW_SM,flexShrink:"0"});const i=n.div({display:"flex",alignItems:"center",gap:"12px",minWidth:"0"}),o=rn("ago-chat-widget__back",t.labels.back,n.chevronLeftIcon({size:20}),t.onBack);o.style.marginRight="-8px";const r=document.createElement("span");r.className="ago-chat-widget__title",n.css(r,{fontSize:"14px",lineHeight:"20px",fontWeight:"500",color:"currentColor",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),i.append(o,r);const s=n.div({display:"flex",alignItems:"center",gap:"8px",flexShrink:"0"}),c=rn("ago-chat-widget__new",t.labels.newChat,n.addCommentIcon({size:20}),t.onNewChat),d=rn("ago-chat-widget__close",t.labels.close,n.closeIcon({size:20}),t.onClose);return s.append(c,d),e.append(i,s),{el:e,update:({screen:h})=>{o.style.display=h==="chat"?"flex":"none",c.style.display=h==="home"?"none":"flex",r.textContent=h==="history"?t.labels.history:t.title}}}var uo={minutes:"{n}min ago",hours:"{n}h ago",days:"{n}d ago",weeks:"{n} weeks ago",months:"{n} months ago"},fi=60*1e3;function mi(t,e=Date.now(),i=uo){const o=t instanceof Date?t.getTime():new Date(t).getTime(),r=(p,x)=>p.replace("{n}",String(x));if(!Number.isFinite(o))return r(i.minutes,0);const s=Math.max(0,Math.floor((e-o)/fi)),c=Math.floor(s/60),d=Math.floor(c/24),h=Math.floor(d/7),f=Math.max(1,Math.floor(d/30));return s<60?r(i.minutes,s):c<24?r(i.hours,c):d<7?r(i.days,d):h<4?r(i.weeks,h):r(i.months,f)}var an={home:"Home",chats:"Chats",history:"History",newConversation:"New conversation",noHistory:"No chat history yet",askQuestion:"Ask a question",back:"Back",close:"Close chat",newChat:"New chat",errorTitle:"Something went wrong",errorDescription:"The answer could not be generated. Please try again.",scrollToBottom:"Scroll to bottom",dismiss:"Dismiss",attachFiles:"Attach files",tooManyFiles:"Too many files. Maximum allowed: {max}",invalidFileType:"Invalid file type: {name}",fileTooLarge:"File too large: {name} (maximum {max})",timeAgo:uo};function gi(t){return{...an,...t,timeAgo:{...an.timeAgo,...t?.timeAgo}}}var hi={"&":"&","<":"<",">":">",'"':""","'":"'"};function Xe(t){return t.replace(/[&<>"']/g,e=>hi[e])}function io(t){const e=t.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(e)||!/^[a-z][a-z0-9+.-]*:/i.test(e)?e:null}var fo='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',At="";function ze(t){const e=[],i=r=>(e.push(r),`${At}${e.length-1}${At}`);let o=t;return o=o.replace(/`([^`]+)`/g,(r,s)=>i(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${fo}">${Xe(s)}</code>`)),o=o.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(r,s,c)=>{const d=io(c);return d?i(`<img alt="${Xe(s)}" src="${Xe(d)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):r}),o=o.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(r,s,c)=>{const d=io(c);return d?i(`<a href="${Xe(d)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${ze(s)}</a>`):r}),o=Xe(o),o=o.replace(/\*\*([^*]+?)\*\*/g,"<strong>$1</strong>").replace(/__([^_]+?)__/g,"<strong>$1</strong>").replace(/~~([^~]+?)~~/g,"<del>$1</del>").replace(/(^|[^*])\*(?!\s)([^*]+?)\*/g,"$1<em>$2</em>").replace(/(^|[^\w_])_(?!\s)([^_]+?)_/g,"$1<em>$2</em>"),o=o.replace(new RegExp(`${At}(\\d+)${At}`,"g"),(r,s)=>e[Number(s)]),o}function de(t,e,i){const o=document.createElement(t);return Object.assign(o.style,e),i!==void 0&&(o.innerHTML=i),o}var mo=/^ {0,3}([-*_])( *\1){2,} *$/,go=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,ho=/^ {0,3}(```+|~~~+)/,Ot=/^ {0,3}>\s?/,Ye=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,bi=["20px","18px","16px","15px","14px","13px"],sn=t=>t.match(/^\s*/)?.[0].length??0;function xi(t){return t.trim()===""||mo.test(t)||go.test(t)||ho.test(t)||Ot.test(t)||Ye.test(t)}function bo(t){const e=t[0].match(Ye),i=e[1].length,o=/\d/.test(e[2]),r=de(o?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:o?"decimal":"disc",listStylePosition:"outside"});let s=0;for(;s<t.length;){const c=t[s].match(Ye),d=[];for(s++;s<t.length&&sn(t[s])>i;)d.push(t[s]),s++;const h=de("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),f=c[3].match(/^\[([ xX])\]\s+(.*)$/);f?(h.style.listStyleType="none",h.style.marginLeft="-20px",h.innerHTML=`<span style="margin-right:6px">${f[1].toLowerCase()==="x"?"☑":"☐"}</span>${ze(f[2])}`):h.innerHTML=ze(c[3]),d.filter(p=>Ye.test(p)).length>0&&h.appendChild(bo(d.filter(p=>p.trim()!==""))),r.appendChild(h)}return r}function yi(t){const e=d=>d.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(h=>h.trim()),i=de("div",{overflowX:"auto",margin:"0 0 8px 0"}),o=de("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),r=document.createElement("thead"),s=document.createElement("tr");for(const d of e(t[0]))s.appendChild(de("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},ze(d)));r.appendChild(s),o.appendChild(r);const c=document.createElement("tbody");for(const d of t.slice(2)){const h=document.createElement("tr");for(const f of e(d))h.appendChild(de("td",{border:"1px solid #dee3e8",padding:"6px 10px"},ze(f)));c.appendChild(h)}return o.appendChild(c),i.appendChild(o),i}var Ci=t=>!!t&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(t);function Me(t){const e=document.createDocumentFragment(),i=t.replace(/\r\n?/g,`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=require("./types-DNr6XEwI.cjs"),si=require("./errors-o1IB5fEu.cjs"),li=require("./createConversationSession-Digvn0GQ.cjs"),to=require("./createFormCollector-Cq7HWjtU.cjs"),n=require("./speechToText-ZciRyyJE.cjs");var di=10*1024*1024;var no=["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/csv","application/json","application/xml","text/xml","text/html","application/epub+zip"];function oo(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function ci(t){const e=t.look==="embed";let i=[];const o=new Map,r=document.createElement("form");r.className=e?"ago-chat-input ago-chat-input--embed":"ago-chat-input",e?n.css(r,{width:"100%",borderRadius:"24px",border:`2px solid ${n.PRIMARY_FOREGROUND}`,backgroundColor:"#fff",boxShadow:n.SHADOW,position:"relative",boxSizing:"border-box",display:"block",fontFamily:n.FONT_VAR}):n.css(r,{display:"flex",flexDirection:"column",gap:"8px",padding:"12px",borderTop:`1px solid ${n.BORDER_COLOR}`,backgroundColor:n.PANEL_BACKGROUND});const s=n.div(e?{display:"none",flexWrap:"wrap",gap:"8px",padding:"0 0 8px"}:{display:"flex",flexWrap:"wrap",gap:"6px"});s.className="ago-chat-input__files";const c=n.div(e?{display:"flex",flexDirection:"row",gap:"8px",padding:"16px"}:{display:"flex",gap:"8px",alignItems:"flex-end"}),d=document.createElement("textarea");d.placeholder=t.placeholder,d.setAttribute("aria-label",t.placeholder),d.rows=1,d.autocapitalize="off",d.setAttribute("autocorrect","off");const h=e?208:110;e?n.css(d,{display:"block",width:"100%",minHeight:"40px",maxHeight:`${h}px`,overflowY:"auto",resize:"none",border:"none",outline:"none",boxShadow:"none",background:"transparent",padding:"8px",boxSizing:"border-box",fontSize:"16px",lineHeight:"24px",fontFamily:"inherit",color:"inherit"}):n.css(d,{flex:"1",resize:"none",boxSizing:"border-box",padding:"10px 12px",border:`1px solid ${n.BORDER_COLOR}`,borderRadius:"12px",fontSize:"16px",fontFamily:n.FONT_VAR,lineHeight:"1.4",maxHeight:`${h}px`,overflowY:"hidden"});const f=()=>{const m=e?0:2;d.style.height="auto";const B=Math.min(d.scrollHeight+m,h);d.style.height=`${B}px`,d.style.overflowY=d.scrollHeight+m>h?"auto":"hidden"};d.addEventListener("input",()=>{f(),E()});const p='<svg width="18" height="18" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-160v-487L216-423l-56-57 320-320 320 320-56 57-224-224v487h-80Z"/></svg>',x='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="animation: ago-spin 0.8s linear infinite"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',I='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="5" y="5" width="14" height="14" rx="2"/></svg>',w=document.createElement("button");w.type="submit",w.className="ago-chat-input__send",w.setAttribute("aria-label","Send"),e?n.css(w,{flexShrink:"0",width:"40px",height:"40px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:n.SEND_BACKGROUND,color:"#fafafa",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"background-color 0.15s, color 0.15s"}):(w.innerHTML=p,n.css(w,{flexShrink:"0",width:"44px",height:"44px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:n.BRAND_COLOR,color:n.BRAND_TEXT_COLOR,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}));let u=!1,v=!1;const A=()=>u&&!!t.onStop,E=()=>{const m=d.value.trim()!=="",B=A(),G=!B&&(u||v||!m);if(w.disabled=G,w.type=B?"button":"submit",w.setAttribute("aria-label",B?"Stop generating":"Send"),e){w.replaceChildren(B?n.stopIcon({size:16}):n.arrowUpwardIcon({size:16}));const P=G&&!u;w.style.backgroundColor=P?"#f1f5f9":n.SEND_BACKGROUND,w.style.color=P?"#cbd5e1":"#fafafa",w.style.pointerEvents=G?"none":"auto",w.style.cursor=G?"default":"pointer",J.style.opacity=u?"0.5":"1";return}w.innerHTML=B?I:u?x:p,w.style.opacity=G&&!u?"0.5":"1",w.style.cursor=G?"default":"pointer"};w.addEventListener("click",()=>{A()&&t.onStop?.()});const O=n.div({display:"none",alignItems:"flex-start",justifyContent:"space-between",gap:"8px",margin:"0 0 12px",padding:"12px 16px",borderRadius:"12px",border:"1px solid rgba(239, 68, 68, 0.5)",color:"#ef4444",backgroundColor:"#fff",fontSize:"14px",lineHeight:"20px"});O.className="ago-chat-input__error",O.setAttribute("role","alert");const W=document.createElement("span"),C=document.createElement("button");C.type="button",C.textContent=t.labels?.dismiss??"Dismiss",n.css(C,{border:"none",background:"transparent",color:"inherit",font:"inherit",fontWeight:"500",cursor:"pointer",padding:"0",minHeight:"20px"}),C.addEventListener("click",()=>{O.style.display="none"}),O.append(W,C);const F=m=>{W.textContent=m,O.style.display="flex"},y=(m,B)=>m.replace(/\{(\w+)\}/g,(G,P)=>B[P]??""),k=m=>{if(!e)return m;const B=t.labels,G=[];for(const P of m){if(i.length+G.length>=5){F(y(B?.tooManyFiles??"Too many files. Maximum allowed: {max}",{max:String(5)}));break}if(P.type&&!no.includes(P.type)){F(y(B?.invalidFileType??"Invalid file type: {name}",{name:P.name}));continue}if(P.size>10485760){F(y(B?.fileTooLarge??"File too large: {name} (maximum {max})",{name:P.name,max:oo(di)}));continue}G.push(P)}return G};let S=null,D=null;t.allowFiles&&(S=document.createElement("input"),S.type="file",S.multiple=!0,e&&(S.accept=no.join(",")),n.css(S,{display:"none"}),D=document.createElement("button"),D.type="button",D.className="ago-chat-input__attach",D.setAttribute("aria-label",t.labels?.attachFiles??"Attach file"),e?(D.appendChild(n.attachFileIcon({size:16})),n.css(D,{height:"40px",padding:"8px",display:"flex",alignItems:"center",gap:"4px",fontSize:"14px",color:n.BRAND_COLOR,background:"none",border:"none",cursor:"pointer",borderRadius:"6px"})):(D.textContent="📎",n.css(D,{flexShrink:"0",minWidth:"44px",minHeight:"44px",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 12px",border:`1px solid ${n.BORDER_COLOR}`,borderRadius:"12px",backgroundColor:n.PANEL_BACKGROUND,cursor:"pointer",fontSize:"14px"})),D.addEventListener("click",()=>S?.click()),S.addEventListener("change",()=>{const m=Array.from(S?.files??[]);i=[...i,...k(m)],S&&(S.value=""),j()}));function V(m){if(!e||!m.type.startsWith("image/")||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;let B=o.get(m);return B||(B=URL.createObjectURL(m),o.set(m,B)),B}function M(m){const B=o.get(m);B&&(URL.revokeObjectURL(B),o.delete(m))}function j(){s.replaceChildren(),e&&(s.style.display=i.length>0?"flex":"none"),i.forEach((m,B)=>{const G=n.div(e?{display:"flex",alignItems:"center",gap:"8px",backgroundColor:"#f3f4f6",borderRadius:"8px",padding:"8px 12px",fontSize:"14px",lineHeight:"20px"}:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#f0f4ff",border:`1px solid ${n.BORDER_COLOR}`,borderRadius:"8px",fontSize:"12px"});if(G.className="ago-chat-input__file",e){const re=V(m);if(re){const be=document.createElement("img");be.src=re,be.alt="",n.css(be,{width:"32px",height:"32px",objectFit:"cover",borderRadius:"4px",flexShrink:"0"}),G.appendChild(be)}else G.appendChild(n.descriptionIcon({size:20}))}const P=document.createElement("span");if(P.textContent=m.name,P.title=m.name,e&&n.css(P,{maxWidth:"150px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),G.appendChild(P),e){const re=document.createElement("span");re.textContent=oo(m.size),n.css(re,{fontSize:"12px",lineHeight:"16px",color:"#6b7280"}),G.appendChild(re)}const ee=document.createElement("button");ee.type="button",ee.setAttribute("aria-label",`Remove ${m.name}`),e?ee.appendChild(n.closeIcon({size:16})):ee.textContent="×",n.css(ee,{flexShrink:"0",width:"44px",height:"44px",margin:e?"-10px -16px -10px -8px":"-14px -12px -14px -4px",display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",cursor:"pointer",fontSize:"14px",lineHeight:"1",color:"inherit"}),ee.addEventListener("click",()=>{M(m),i=i.filter((re,be)=>be!==B),j()}),G.appendChild(ee),s.appendChild(G)}),E()}const b=()=>{z?.cancel();const m=d.value,B=i;d.value="",f(),i=[];for(const G of B)M(G);return j(),{content:m,files:B}},R=()=>{if(u||v||!d.value.trim())return;const{content:m,files:B}=b();t.onSend(m.trim(),B.length>0?B:void 0),e&&typeof window<"u"&&window.innerWidth<(t.blurOnSubmitBelow??600)&&d.blur()};r.addEventListener("submit",m=>{m.preventDefault(),R()}),d.addEventListener("keydown",m=>{if(m.key==="Enter"&&!m.shiftKey){if(m.isComposing||m.keyCode===229)return;m.preventDefault(),R()}});const z=t.transcribeAudio?n.createSpeechToText({transcribe:t.transcribeAudio,labels:t.speechToTextLabels,onBusy:m=>{const B=v&&!m&&!u&&r.contains(document.activeElement);v=m,d.disabled=u||m,e?(J.style.display=m?"none":"",Y.style.display=m?"none":"flex",c.style.padding=m?"8px":"16px",z&&(m?c.append(z.el):Y.prepend(z.el))):(d.style.display=m?"none":"",w.style.display=m?"none":"flex",D&&(D.style.display=m?"none":"flex")),E(),B&&d.focus()},onText:m=>{d.value+=`${d.value&&!/\s$/.test(d.value)?" ":""}${m}`,f(),E(),d.focus()},onError:F}):void 0,J=n.div({flex:"1",minWidth:"0"});J.className="ago-chat-input__editor";const Y=n.div({display:"flex",alignItems:"flex-end",flexShrink:"0",gap:"4px"});if(e){J.append(O,s,d);const m=n.div({display:"flex",alignItems:"center"});m.className="ago-chat-input__toolbar",D&&m.appendChild(D),D&&J.appendChild(m),z&&Y.appendChild(z.el),Y.appendChild(w),c.append(J,Y),S&&r.appendChild(S),r.appendChild(c),r.addEventListener("click",B=>{(B.target instanceof Element?B.target:null)?.closest("button,a,input,textarea")||d.focus()})}else D&&c.appendChild(D),c.append(d),z&&c.appendChild(z.el),c.append(w),S&&r.appendChild(S),r.append(O,s,c);return E(),{inputRow:r,getValueAndClear:b,setDisabled:m=>{u=m,z?.setDisabled(m),d.disabled=m||v,E()},focus:()=>d.focus(),blur:()=>d.blur(),restoreDraft:(m,B)=>{m&&!d.value.trim()&&(d.value=m,f()),B?.length&&(i=[...B,...i],j()),E()},setPlaceholder:m=>{d.placeholder=m,m&&d.setAttribute("aria-label",m)},setSpeechToTextEnabled:m=>z?.setEnabled(m),cancelRecording:()=>z?.cancel(),destroy:()=>{z?.destroy();for(const m of o.keys())M(m)}}}var on="rgba(3, 24, 47, 0.07)";function pi(t){const e=document.createElement("footer");e.className="ago-chat-widget__footer",n.css(e,{padding:"12px",flexShrink:"0",background:"transparent"});const i=document.createElement("nav");n.css(i,{display:"flex",alignItems:"center",gap:"4px",width:"100%"});const o=new Map;let r="home";function s(d,h,f){const p=document.createElement("button");p.type="button",p.className="ago-chat-widget__tab",p.dataset.agoScreen=d,n.css(p,{flex:"1",minWidth:"0",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",padding:"12px 8px",borderRadius:"32px",border:"none",background:"transparent",color:n.BRAND_COLOR,cursor:"pointer",transition:"background-color 0.15s",font:"inherit"});const x=document.createElement("span");return x.textContent=h,n.css(x,{fontSize:"12px",lineHeight:"16px",maxWidth:"100%",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),p.append(f,x),p.addEventListener("mouseenter",()=>{p.style.backgroundColor=on}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor=r===d?on:"transparent"}),p.addEventListener("click",()=>t.onNavigate(d)),o.set(d,p),p}i.append(s("home",t.labels.home,n.houseIcon({size:24})),s("history",t.labels.chats,n.conversationsIcon({size:24}))),e.appendChild(i);const c=d=>{r=d==="history"?"history":"home";for(const[h,f]of o){const p=h===r;f.style.color=p?n.PRIMARY_ACCENT:n.BRAND_COLOR,f.style.backgroundColor=p?on:"transparent",p?f.setAttribute("aria-current","page"):f.removeAttribute("aria-current")}};return c("home"),{el:e,setActive:c,setVisible:d=>{e.style.display=d?"block":"none"}}}function rn(t,e,i,o){const r=document.createElement("button");return r.type="button",r.className=t,r.setAttribute("aria-label",e),r.title=e,n.css(r,{display:"flex",alignItems:"center",justifyContent:"center",width:"44px",height:"44px",margin:"-12px",padding:"0",border:"none",background:"transparent",color:"currentColor",opacity:"0.8",cursor:"pointer",transition:"opacity 0.15s",flexShrink:"0"}),r.addEventListener("mouseenter",()=>{r.style.opacity="1"}),r.addEventListener("mouseleave",()=>{r.style.opacity="0.8"}),r.addEventListener("click",o),r.appendChild(i),r}function ui(t){const e=document.createElement("header");e.className="ago-chat-widget__header",n.css(e,{display:"flex",alignItems:"center",justifyContent:"space-between",height:"56px",padding:"0 16px",boxSizing:"border-box",background:n.HEADER_BACKGROUND,color:n.HEADER_TEXT_COLOR,borderBottom:"1px solid #e5e7eb",boxShadow:n.SHADOW_SM,flexShrink:"0"});const i=n.div({display:"flex",alignItems:"center",gap:"12px",minWidth:"0"}),o=rn("ago-chat-widget__back",t.labels.back,n.chevronLeftIcon({size:20}),t.onBack);o.style.marginRight="-8px";const r=document.createElement("span");r.className="ago-chat-widget__title",n.css(r,{fontSize:"14px",lineHeight:"20px",fontWeight:"500",color:"currentColor",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),i.append(o,r);const s=n.div({display:"flex",alignItems:"center",gap:"8px",flexShrink:"0"}),c=rn("ago-chat-widget__new",t.labels.newChat,n.addCommentIcon({size:20}),t.onNewChat),d=rn("ago-chat-widget__close",t.labels.close,n.closeIcon({size:20}),t.onClose);return s.append(c,d),e.append(i,s),{el:e,update:({screen:h})=>{o.style.display=h==="chat"?"flex":"none",c.style.display=h==="home"?"none":"flex",r.textContent=h==="history"?t.labels.history:t.title}}}var uo={minutes:"{n}min ago",hours:"{n}h ago",days:"{n}d ago",weeks:"{n} weeks ago",months:"{n} months ago"},fi=60*1e3;function mi(t,e=Date.now(),i=uo){const o=t instanceof Date?t.getTime():new Date(t).getTime(),r=(p,x)=>p.replace("{n}",String(x));if(!Number.isFinite(o))return r(i.minutes,0);const s=Math.max(0,Math.floor((e-o)/fi)),c=Math.floor(s/60),d=Math.floor(c/24),h=Math.floor(d/7),f=Math.max(1,Math.floor(d/30));return s<60?r(i.minutes,s):c<24?r(i.hours,c):d<7?r(i.days,d):h<4?r(i.weeks,h):r(i.months,f)}var an={home:"Home",chats:"Chats",history:"History",newConversation:"New conversation",noHistory:"No chat history yet",askQuestion:"Ask a question",back:"Back",close:"Close chat",newChat:"New chat",errorTitle:"Something went wrong",errorDescription:"The answer could not be generated. Please try again.",scrollToBottom:"Scroll to bottom",dismiss:"Dismiss",attachFiles:"Attach files",tooManyFiles:"Too many files. Maximum allowed: {max}",invalidFileType:"Invalid file type: {name}",fileTooLarge:"File too large: {name} (maximum {max})",timeAgo:uo};function gi(t){return{...an,...t,timeAgo:{...an.timeAgo,...t?.timeAgo}}}var hi={"&":"&","<":"<",">":">",'"':""","'":"'"};function Xe(t){return t.replace(/[&<>"']/g,e=>hi[e])}function io(t){const e=t.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(e)||!/^[a-z][a-z0-9+.-]*:/i.test(e)?e:null}var fo='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',At="";function ze(t){const e=[],i=r=>(e.push(r),`${At}${e.length-1}${At}`);let o=t;return o=o.replace(/`([^`]+)`/g,(r,s)=>i(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${fo}">${Xe(s)}</code>`)),o=o.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(r,s,c)=>{const d=io(c);return d?i(`<img alt="${Xe(s)}" src="${Xe(d)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):r}),o=o.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(r,s,c)=>{const d=io(c);return d?i(`<a href="${Xe(d)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${ze(s)}</a>`):r}),o=Xe(o),o=o.replace(/\*\*([^*]+?)\*\*/g,"<strong>$1</strong>").replace(/__([^_]+?)__/g,"<strong>$1</strong>").replace(/~~([^~]+?)~~/g,"<del>$1</del>").replace(/(^|[^*])\*(?!\s)([^*]+?)\*/g,"$1<em>$2</em>").replace(/(^|[^\w_])_(?!\s)([^_]+?)_/g,"$1<em>$2</em>"),o=o.replace(new RegExp(`${At}(\\d+)${At}`,"g"),(r,s)=>e[Number(s)]),o}function de(t,e,i){const o=document.createElement(t);return Object.assign(o.style,e),i!==void 0&&(o.innerHTML=i),o}var mo=/^ {0,3}([-*_])( *\1){2,} *$/,go=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,ho=/^ {0,3}(```+|~~~+)/,Ot=/^ {0,3}>\s?/,Ye=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,bi=["20px","18px","16px","15px","14px","13px"],sn=t=>t.match(/^\s*/)?.[0].length??0;function xi(t){return t.trim()===""||mo.test(t)||go.test(t)||ho.test(t)||Ot.test(t)||Ye.test(t)}function bo(t){const e=t[0].match(Ye),i=e[1].length,o=/\d/.test(e[2]),r=de(o?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:o?"decimal":"disc",listStylePosition:"outside"});let s=0;for(;s<t.length;){const c=t[s].match(Ye),d=[];for(s++;s<t.length&&sn(t[s])>i;)d.push(t[s]),s++;const h=de("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),f=c[3].match(/^\[([ xX])\]\s+(.*)$/);f?(h.style.listStyleType="none",h.style.marginLeft="-20px",h.innerHTML=`<span style="margin-right:6px">${f[1].toLowerCase()==="x"?"☑":"☐"}</span>${ze(f[2])}`):h.innerHTML=ze(c[3]),d.filter(p=>Ye.test(p)).length>0&&h.appendChild(bo(d.filter(p=>p.trim()!==""))),r.appendChild(h)}return r}function yi(t){const e=d=>d.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(h=>h.trim()),i=de("div",{overflowX:"auto",margin:"0 0 8px 0"}),o=de("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),r=document.createElement("thead"),s=document.createElement("tr");for(const d of e(t[0]))s.appendChild(de("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},ze(d)));r.appendChild(s),o.appendChild(r);const c=document.createElement("tbody");for(const d of t.slice(2)){const h=document.createElement("tr");for(const f of e(d))h.appendChild(de("td",{border:"1px solid #dee3e8",padding:"6px 10px"},ze(f)));c.appendChild(h)}return o.appendChild(c),i.appendChild(o),i}var Ci=t=>!!t&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(t);function Me(t){const e=document.createDocumentFragment(),i=t.replace(/\r\n?/g,`
|
|
2
2
|
`).split(`
|
|
3
3
|
`);let o=0;for(;o<i.length;){const s=i[o];if(s.trim()===""){o++;continue}const c=s.match(ho);if(c){const f=c[1][0],p=[];for(o++;o<i.length&&!new RegExp(`^ {0,3}${f==="`"?"`{3,}":"~{3,}"}\\s*$`).test(i[o]);)p.push(i[o]),o++;o++;const x=de("pre",{margin:"0 0 8px 0"});x.appendChild(de("code",{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:fo,whiteSpace:"pre"},Xe(p.join(`
|
|
4
4
|
`)))),e.appendChild(x);continue}if(mo.test(s)){e.appendChild(de("hr",{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"})),o++;continue}const d=s.match(go);if(d){const f=d[1].length;e.appendChild(de(`h${f}`,{margin:"16px 0 8px 0",fontSize:bi[f-1],fontWeight:"600",lineHeight:"1.3"},ze(d[2]))),o++;continue}if(Ot.test(s)){const f=[];for(;o<i.length&&Ot.test(i[o]);)f.push(i[o].replace(Ot,"")),o++;const p=de("blockquote",{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"});p.appendChild(Me(f.join(`
|
package/dist/widget.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as Bi, c as Ro, n as Di, o as zo, s as Ho, t as $i } from "./types-
|
|
1
|
+
import { a as Bi, c as Ro, n as Di, o as zo, s as Ho, t as $i } from "./types-D1ZrqVhr.js";
|
|
2
2
|
import { n as Mi } from "./errors-BLfjXnLB.js";
|
|
3
|
-
import { t as Wi } from "./createConversationSession-
|
|
4
|
-
import { r as ji, t as Pi } from "./createFormCollector-
|
|
3
|
+
import { t as Wi } from "./createConversationSession-DrmOaZdO.js";
|
|
4
|
+
import { r as ji, t as Pi } from "./createFormCollector-ki_GTlp9.js";
|
|
5
5
|
import { $ as ee, A as bn, B as Ui, C as Ka, D as Y, E as Vi, F as xn, G as xo, H as Oo, I as qi, J as Gi, K as yn, L as Ki, M as Cn, N as Le, O as fe, P as Bo, Q as Mt, R as Do, S as Xa, T as wn, U as ye, V as tt, W as vn, X as Xi, Y as yo, Z as $o, _ as Yi, a as Qi, at as c, b as Ji, c as Zi, ct as er, d as Mo, dt as mn, et as tr, f as Wo, g as nr, h as or, i as ir, it as f, j as rr, k as nt, l as ar, lt as sr, m as lr, n as dr, nt as Co, o as cr, ot as pr, p as ur, q as jo, r as Fn, rt as fr, s as mr, st as gr, t as Ya, tt as hr, u as br, ut as wo, v as xr, w as ot, x as yr, y as Cr, z as jt } from "./speechToText-BV7qxqPF.js";
|
|
6
6
|
var wr = 10 * 1024 * 1024;
|
|
7
7
|
var vo = [
|