/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/@anam-ai/agent-widget@0.6.0/dist/index.umd.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
(function(ue,de){typeof exports=="object"&&typeof module<"u"?de(exports):typeof define=="function"&&define.amd?define(["exports"],de):(ue=typeof globalThis<"u"?globalThis:ue||self,de(ue.AnamAgentWidget={}))})(this,(function(ue){"use strict";var de,N,Ht,zt,Te,qt,Yt,Kt,Jt,ht,ft,pt,Fe={},Xt=[],pn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Xe=Array.isArray;function ae(t,e){for(var i in e)t[i]=e[i];return t}function _t(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ae(t,e,i){var n,a,s,c={};for(s in e)s=="key"?n=e[s]:s=="ref"?a=e[s]:c[s]=e[s];if(arguments.length>2&&(c.children=arguments.length>3?de.call(arguments,2):i),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)c[s]===void 0&&(c[s]=t.defaultProps[s]);return $e(t,c,n,a,null)}function $e(t,e,i,n,a){var s={type:t,props:e,key:i,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:a??++Ht,__i:-1,__u:0};return a==null&&N.vnode!=null&&N.vnode(s),s}function he(t){return t.children}function Oe(t,e){this.props=t,this.context=e}function xe(t,e){if(e==null)return t.__?xe(t.__,t.__i+1):null;for(var i;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null)return i.__e;return typeof t.type=="function"?xe(t):null}function Zt(t){var e,i;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null){t.__e=t.__c.base=i.__e;break}return Zt(t)}}function Qt(t){(!t.__d&&(t.__d=!0)&&Te.push(t)&&!Ze.__r++||qt!=N.debounceRendering)&&((qt=N.debounceRendering)||Yt)(Ze)}function Ze(){for(var t,e,i,n,a,s,c,l=1;Te.length;)Te.length>l&&Te.sort(Kt),t=Te.shift(),l=Te.length,t.__d&&(i=void 0,n=void 0,a=(n=(e=t).__v).__e,s=[],c=[],e.__P&&((i=ae({},n)).__v=n.__v+1,N.vnode&&N.vnode(i),mt(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[a]:null,s,a??xe(n),!!(32&n.__u),c),i.__v=n.__v,i.__.__k[i.__i]=i,ri(s,i,c),n.__e=n.__=null,i.__e!=a&&Zt(i)));Ze.__r=0}function ei(t,e,i,n,a,s,c,l,m,p,f){var u,y,E,S,T,I,w,b=n&&n.__k||Xt,O=e.length;for(m=_n(i,e,b,m,O),u=0;u<O;u++)(E=i.__k[u])!=null&&(y=E.__i==-1?Fe:b[E.__i]||Fe,E.__i=u,I=mt(t,E,y,a,s,c,l,m,p,f),S=E.__e,E.ref&&y.ref!=E.ref&&(y.ref&&Et(y.ref,null,E),f.push(E.ref,E.__c||S,E)),T==null&&S!=null&&(T=S),(w=!!(4&E.__u))||y.__k===E.__k?m=ti(E,m,t,w):typeof E.type=="function"&&I!==void 0?m=I:S&&(m=S.nextSibling),E.__u&=-7);return i.__e=T,m}function _n(t,e,i,n,a){var s,c,l,m,p,f=i.length,u=f,y=0;for(t.__k=new Array(a),s=0;s<a;s++)(c=e[s])!=null&&typeof c!="boolean"&&typeof c!="function"?(typeof c=="string"||typeof c=="number"||typeof c=="bigint"||c.constructor==String?c=t.__k[s]=$e(null,c,null,null,null):Xe(c)?c=t.__k[s]=$e(he,{children:c},null,null,null):c.constructor===void 0&&c.__b>0?c=t.__k[s]=$e(c.type,c.props,c.key,c.ref?c.ref:null,c.__v):t.__k[s]=c,m=s+y,c.__=t,c.__b=t.__b+1,l=null,(p=c.__i=mn(c,i,m,u))!=-1&&(u--,(l=i[p])&&(l.__u|=2)),l==null||l.__v==null?(p==-1&&(a>f?y--:a<f&&y++),typeof c.type!="function"&&(c.__u|=4)):p!=m&&(p==m-1?y--:p==m+1?y++:(p>m?y--:y++,c.__u|=4))):t.__k[s]=null;if(u)for(s=0;s<f;s++)(l=i[s])!=null&&(2&l.__u)==0&&(l.__e==n&&(n=xe(l)),si(l,l));return n}function ti(t,e,i,n){var a,s;if(typeof t.type=="function"){for(a=t.__k,s=0;a&&s<a.length;s++)a[s]&&(a[s].__=t,e=ti(a[s],e,i,n));return e}t.__e!=e&&(n&&(e&&t.type&&!e.parentNode&&(e=xe(t)),i.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function mn(t,e,i,n){var a,s,c,l=t.key,m=t.type,p=e[i],f=p!=null&&(2&p.__u)==0;if(p===null&&l==null||f&&l==p.key&&m==p.type)return i;if(n>(f?1:0)){for(a=i-1,s=i+1;a>=0||s<e.length;)if((p=e[c=a>=0?a--:s++])!=null&&(2&p.__u)==0&&l==p.key&&m==p.type)return c}return-1}function ii(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||pn.test(e)?i:i+"px"}function Qe(t,e,i,n,a){var s,c;e:if(e=="style")if(typeof i=="string")t.style.cssText=i;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)i&&e in i||ii(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||ii(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Jt,"$1")),c=e.toLowerCase(),e=c in t||e=="onFocusOut"||e=="onFocusIn"?c.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=i,i?n?i.u=n.u:(i.u=ht,t.addEventListener(e,s?pt:ft,s)):t.removeEventListener(e,s?pt:ft,s);else{if(a=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=i??"";break e}catch{}typeof i=="function"||(i==null||i===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&i==1?"":i))}}function ni(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=ht++;else if(e.t<i.u)return;return i(N.event?N.event(e):e)}}}function mt(t,e,i,n,a,s,c,l,m,p){var f,u,y,E,S,T,I,w,b,O,L,R,Q,H,oe,te,se,K=e.type;if(e.constructor!==void 0)return null;128&i.__u&&(m=!!(32&i.__u),s=[l=e.__e=i.__e]),(f=N.__b)&&f(e);e:if(typeof K=="function")try{if(w=e.props,b="prototype"in K&&K.prototype.render,O=(f=K.contextType)&&n[f.__c],L=f?O?O.props.value:f.__:n,i.__c?I=(u=e.__c=i.__c).__=u.__E:(b?e.__c=u=new K(w,L):(e.__c=u=new Oe(w,L),u.constructor=K,u.render=En),O&&O.sub(u),u.state||(u.state={}),u.__n=n,y=u.__d=!0,u.__h=[],u._sb=[]),b&&u.__s==null&&(u.__s=u.state),b&&K.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=ae({},u.__s)),ae(u.__s,K.getDerivedStateFromProps(w,u.__s))),E=u.props,S=u.state,u.__v=e,y)b&&K.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),b&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(b&&K.getDerivedStateFromProps==null&&w!==E&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(w,L),e.__v==i.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(w,u.__s,L)===!1){for(e.__v!=i.__v&&(u.props=w,u.state=u.__s,u.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(ee){ee&&(ee.__=e)}),R=0;R<u._sb.length;R++)u.__h.push(u._sb[R]);u._sb=[],u.__h.length&&c.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(w,u.__s,L),b&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,S,T)})}if(u.context=L,u.props=w,u.__P=t,u.__e=!1,Q=N.__r,H=0,b){for(u.state=u.__s,u.__d=!1,Q&&Q(e),f=u.render(u.props,u.state,u.context),oe=0;oe<u._sb.length;oe++)u.__h.push(u._sb[oe]);u._sb=[]}else do u.__d=!1,Q&&Q(e),f=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++H<25);u.state=u.__s,u.getChildContext!=null&&(n=ae(ae({},n),u.getChildContext())),b&&!y&&u.getSnapshotBeforeUpdate!=null&&(T=u.getSnapshotBeforeUpdate(E,S)),te=f,f!=null&&f.type===he&&f.key==null&&(te=oi(f.props.children)),l=ei(t,Xe(te)?te:[te],e,i,n,a,s,c,l,m,p),u.base=e.__e,e.__u&=-161,u.__h.length&&c.push(u),I&&(u.__E=u.__=null)}catch(ee){if(e.__v=null,m||s!=null)if(ee.then){for(e.__u|=m?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s[s.indexOf(l)]=null,e.__e=l}else{for(se=s.length;se--;)_t(s[se]);gt(e)}else e.__e=i.__e,e.__k=i.__k,ee.then||gt(e);N.__e(ee,e,i)}else s==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):l=e.__e=gn(i.__e,e,i,n,a,s,c,m,p);return(f=N.diffed)&&f(e),128&e.__u?void 0:l}function gt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(gt)}function ri(t,e,i){for(var n=0;n<i.length;n++)Et(i[n],i[++n],i[++n]);N.__c&&N.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){N.__e(s,a.__v)}})}function oi(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Xe(t)?t.map(oi):ae({},t)}function gn(t,e,i,n,a,s,c,l,m){var p,f,u,y,E,S,T,I=i.props||Fe,w=e.props,b=e.type;if(b=="svg"?a="http://www.w3.org/2000/svg":b=="math"?a="http://www.w3.org/1998/Math/MathML":a||(a="http://www.w3.org/1999/xhtml"),s!=null){for(p=0;p<s.length;p++)if((E=s[p])&&"setAttribute"in E==!!b&&(b?E.localName==b:E.nodeType==3)){t=E,s[p]=null;break}}if(t==null){if(b==null)return document.createTextNode(w);t=document.createElementNS(a,b,w.is&&w),l&&(N.__m&&N.__m(e,s),l=!1),s=null}if(b==null)I===w||l&&t.data==w||(t.data=w);else{if(s=s&&de.call(t.childNodes),!l&&s!=null)for(I={},p=0;p<t.attributes.length;p++)I[(E=t.attributes[p]).name]=E.value;for(p in I)if(E=I[p],p!="children"){if(p=="dangerouslySetInnerHTML")u=E;else if(!(p in w)){if(p=="value"&&"defaultValue"in w||p=="checked"&&"defaultChecked"in w)continue;Qe(t,p,null,E,a)}}for(p in w)E=w[p],p=="children"?y=E:p=="dangerouslySetInnerHTML"?f=E:p=="value"?S=E:p=="checked"?T=E:l&&typeof E!="function"||I[p]===E||Qe(t,p,E,I[p],a);if(f)l||u&&(f.__html==u.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(u&&(t.innerHTML=""),ei(e.type=="template"?t.content:t,Xe(y)?y:[y],e,i,n,b=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,c,s?s[0]:i.__k&&xe(i,0),l,m),s!=null)for(p=s.length;p--;)_t(s[p]);l||(p="value",b=="progress"&&S==null?t.removeAttribute("value"):S!=null&&(S!==t[p]||b=="progress"&&!S||b=="option"&&S!=I[p])&&Qe(t,p,S,I[p],a),p="checked",T!=null&&T!=t[p]&&Qe(t,p,T,I[p],a))}return t}function Et(t,e,i){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(a){N.__e(a,i)}}function si(t,e,i){var n,a;if(N.unmount&&N.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Et(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(s){N.__e(s,e)}n.base=n.__P=null}if(n=t.__k)for(a=0;a<n.length;a++)n[a]&&si(n[a],e,i||typeof t.type!="function");i||_t(t.__e),t.__c=t.__=t.__e=void 0}function En(t,e,i){return this.constructor(t,i)}function et(t,e,i){var n,a,s,c;e==document&&(e=document.documentElement),N.__&&N.__(t,e),a=(n=typeof i=="function")?null:i&&i.__k||e.__k,s=[],c=[],mt(e,t=(!n&&i||e).__k=Ae(he,null,[t]),a||Fe,Fe,e.namespaceURI,!n&&i?[i]:a?null:e.firstChild?de.call(e.childNodes):null,s,!n&&i?i:a?a.__e:e.firstChild,n,c),ri(s,t,c)}function ai(t,e){et(t,e,ai)}function li(t,e,i){var n,a,s,c,l=ae({},t.props);for(s in t.type&&t.type.defaultProps&&(c=t.type.defaultProps),e)s=="key"?n=e[s]:s=="ref"?a=e[s]:l[s]=e[s]===void 0&&c!=null?c[s]:e[s];return arguments.length>2&&(l.children=arguments.length>3?de.call(arguments,2):i),$e(t.type,l,n||t.key,a||t.ref,null)}de=Xt.slice,N={__e:function(t,e,i,n){for(var a,s,c;e=e.__;)if((a=e.__c)&&!a.__)try{if((s=a.constructor)&&s.getDerivedStateFromError!=null&&(a.setState(s.getDerivedStateFromError(t)),c=a.__d),a.componentDidCatch!=null&&(a.componentDidCatch(t,n||{}),c=a.__d),c)return a.__E=a}catch(l){t=l}throw t}},Ht=0,zt=function(t){return t!=null&&t.constructor===void 0},Oe.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ae({},this.state),typeof t=="function"&&(t=t(ae({},i),this.props)),t&&ae(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Qt(this))},Oe.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Qt(this))},Oe.prototype.render=he,Te=[],Yt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Kt=function(t,e){return t.__v.__b-e.__v.__b},Ze.__r=0,Jt=/(PointerCapture)$|Capture$/i,ht=0,ft=ni(!1),pt=ni(!0);function tt(){return tt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},tt.apply(this,arguments)}function ci(t,e){if(t==null)return{};var i,n,a={},s=Object.keys(t);for(n=0;n<s.length;n++)e.indexOf(i=s[n])>=0||(a[i]=t[i]);return a}var vn=["context","children"],Cn=["useFragment"];function Sn(t,e,i,n){function a(){var s,c=Reflect.construct(HTMLElement,[],a);return c._vdomComponent=t,n&&n.shadow?(c._root=c.attachShadow({mode:n.mode||"open",serializable:(s=n.serializable)!=null&&s}),n.adoptedStyleSheets&&(c._root.adoptedStyleSheets=n.adoptedStyleSheets)):c._root=c,c}return(a.prototype=Object.create(HTMLElement.prototype)).constructor=a,a.prototype.connectedCallback=function(){Tn.call(this,n)},a.prototype.attributeChangedCallback=In,a.prototype.disconnectedCallback=bn,i=i||t.observedAttributes||Object.keys(t.propTypes||{}),a.observedAttributes=i,t.formAssociated&&(a.formAssociated=!0),i.forEach(function(s){Object.defineProperty(a.prototype,s,{get:function(){return this._vdom?this._vdom.props[s]:this._props[s]},set:function(c){this._vdom?this.attributeChangedCallback(s,null,c):(this._props||(this._props={}),this._props[s]=c);var l=typeof c;c!=null&&l!=="string"&&l!=="boolean"&&l!=="number"||this.setAttribute(s,c)}})}),customElements.define(e||t.tagName||t.displayName||t.name,a),a}function yn(t){this.getChildContext=function(){return t.context};var e=t.children,i=ci(t,vn);return li(e,i)}function Tn(t){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=Ae(yn,tt({},this._props,{context:e.detail.context}),hi(this,this._vdomComponent,t)),(this.hasAttribute("hydrate")?ai:et)(this._vdom,this._root)}function di(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function In(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[di(t)]=i,this._vdom=li(this._vdom,n),et(this._vdom,this._root)}}function bn(){et(this._vdom=null,this._root)}function ui(t,e){var i=this,n=t.useFragment,a=ci(t,Cn);return Ae(n?he:"slot",tt({},a,{ref:function(s){s?(i.ref=s,i._listener||(i._listener=function(c){c.stopPropagation(),c.detail.context=e},s.addEventListener("_preact",i._listener))):i.ref.removeEventListener("_preact",i._listener)}}))}function hi(t,e,i){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var n=[],a={},s=0,c=t.attributes,l=t.childNodes;for(s=c.length;s--;)c[s].name!=="slot"&&(a[c[s].name]=c[s].value,a[di(c[s].name)]=c[s].value);for(s=l.length;s--;){var m=hi(l[s],null,i),p=l[s].slot;p?a[p]=Ae(ui,{name:p},m):n[s]=m}var f=!(!i||!i.shadow),u=e?Ae(ui,{useFragment:!f},n):n;return!f&&e&&(t.innerHTML=""),Ae(e||t.nodeName.toLowerCase(),a,u)}var wn=0;function C(t,e,i,n,a,s){e||(e={});var c,l,m=e;if("ref"in m)for(l in m={},e)l=="ref"?c=e[l]:m[l]=e[l];var p={type:t,props:m,key:i,ref:c,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--wn,__i:-1,__u:0,__source:a,__self:s};if(typeof t=="function"&&(c=t.defaultProps))for(l in c)m[l]===void 0&&(m[l]=c[l]);return N.vnode&&N.vnode(p),p}var Ve,F,vt,fi,We=0,pi=[],V=N,_i=V.__b,mi=V.__r,gi=V.diffed,Ei=V.__c,vi=V.unmount,Ci=V.__;function Ct(t,e){V.__h&&V.__h(F,t,We||e),We=0;var i=F.__H||(F.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function St(t){return We=1,Rn(Ti,t)}function Rn(t,e,i){var n=Ct(Ve++,2);if(n.t=t,!n.__c&&(n.__=[Ti(void 0,e),function(l){var m=n.__N?n.__N[0]:n.__[0],p=n.t(m,l);m!==p&&(n.__N=[p,n.__[1]],n.__c.setState({}))}],n.__c=F,!F.__f)){var a=function(l,m,p){if(!n.__c.__H)return!0;var f=n.__c.__H.__.filter(function(y){return!!y.__c});if(f.every(function(y){return!y.__N}))return!s||s.call(this,l,m,p);var u=n.__c.props!==l;return f.forEach(function(y){if(y.__N){var E=y.__[0];y.__=y.__N,y.__N=void 0,E!==y.__[0]&&(u=!0)}}),s&&s.call(this,l,m,p)||u};F.__f=!0;var s=F.shouldComponentUpdate,c=F.componentWillUpdate;F.componentWillUpdate=function(l,m,p){if(this.__e){var f=s;s=void 0,a(l,m,p),s=f}c&&c.call(this,l,m,p)},F.shouldComponentUpdate=a}return n.__N||n.__}function Ie(t,e){var i=Ct(Ve++,3);!V.__s&&yi(i.__H,e)&&(i.__=t,i.u=e,F.__H.__h.push(i))}function je(t){return We=5,Ne(function(){return{current:t}},[])}function Ne(t,e){var i=Ct(Ve++,7);return yi(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function Ge(t,e){return We=8,Ne(function(){return t},e)}function An(){for(var t;t=pi.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(it),t.__H.__h.forEach(yt),t.__H.__h=[]}catch(e){t.__H.__h=[],V.__e(e,t.__v)}}V.__b=function(t){F=null,_i&&_i(t)},V.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Ci&&Ci(t,e)},V.__r=function(t){mi&&mi(t),Ve=0;var e=(F=t.__c).__H;e&&(vt===F?(e.__h=[],F.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(it),e.__h.forEach(yt),e.__h=[],Ve=0)),vt=F},V.diffed=function(t){gi&&gi(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(pi.push(e)!==1&&fi===V.requestAnimationFrame||((fi=V.requestAnimationFrame)||On)(An)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),vt=F=null},V.__c=function(t,e){e.some(function(i){try{i.__h.forEach(it),i.__h=i.__h.filter(function(n){return!n.__||yt(n)})}catch(n){e.some(function(a){a.__h&&(a.__h=[])}),e=[],V.__e(n,i.__v)}}),Ei&&Ei(t,e)},V.unmount=function(t){vi&&vi(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{it(n)}catch(a){e=a}}),i.__H=void 0,e&&V.__e(e,i.__v))};var Si=typeof requestAnimationFrame=="function";function On(t){var e,i=function(){clearTimeout(n),Si&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);Si&&(e=requestAnimationFrame(i))}function it(t){var e=F,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),F=e}function yt(t){var e=F;t.__c=t.__(),F=e}function yi(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function Ti(t,e){return typeof e=="function"?e(t):e}var xn=Symbol.for("preact-signals");function nt(){if(fe>1)fe--;else{for(var t,e=!1;He!==void 0;){var i=He;for(He=void 0,Tt++;i!==void 0;){var n=i.o;if(i.o=void 0,i.f&=-3,!(8&i.f)&&wi(i))try{i.c()}catch(a){e||(t=a,e=!0)}i=n}}if(Tt=0,fe--,e)throw t}}function Nn(t){if(fe>0)return t();fe++;try{return t()}finally{nt()}}var k=void 0;function Ii(t){var e=k;k=void 0;try{return t()}finally{k=e}}var He=void 0,fe=0,Tt=0,rt=0;function bi(t){if(k!==void 0){var e=t.n;if(e===void 0||e.t!==k)return e={i:0,S:t,p:k.s,n:void 0,t:k,e:void 0,x:void 0,r:e},k.s!==void 0&&(k.s.n=e),k.s=e,t.n=e,32&k.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=k.s,e.n=void 0,k.s.n=e,k.s=e),e}}function z(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}z.prototype.brand=xn,z.prototype.h=function(){return!0},z.prototype.S=function(t){var e=this,i=this.t;i!==t&&t.e===void 0&&(t.x=i,this.t=t,i!==void 0?i.e=t:Ii(function(){var n;(n=e.W)==null||n.call(e)}))},z.prototype.U=function(t){var e=this;if(this.t!==void 0){var i=t.e,n=t.x;i!==void 0&&(i.x=n,t.e=void 0),n!==void 0&&(n.e=i,t.x=void 0),t===this.t&&(this.t=n,n===void 0&&Ii(function(){var a;(a=e.Z)==null||a.call(e)}))}},z.prototype.subscribe=function(t){var e=this;return ze(function(){var i=e.value,n=k;k=void 0;try{t(i)}finally{k=n}},{name:"sub"})},z.prototype.valueOf=function(){return this.value},z.prototype.toString=function(){return this.value+""},z.prototype.toJSON=function(){return this.value},z.prototype.peek=function(){var t=k;k=void 0;try{return this.value}finally{k=t}},Object.defineProperty(z.prototype,"value",{get:function(){var t=bi(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Tt>100)throw new Error("Cycle detected");this.v=t,this.i++,rt++,fe++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{nt()}}}});function G(t,e){return new z(t,e)}function wi(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function Ri(t){for(var e=t.s;e!==void 0;e=e.n){var i=e.S.n;if(i!==void 0&&(e.r=i),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function Ai(t){for(var e=t.s,i=void 0;e!==void 0;){var n=e.p;e.i===-1?(e.S.U(e),n!==void 0&&(n.n=e.n),e.n!==void 0&&(e.n.p=n)):i=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=n}t.s=i}function be(t,e){z.call(this,void 0),this.x=t,this.s=void 0,this.g=rt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}be.prototype=new z,be.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===rt))return!0;if(this.g=rt,this.f|=1,this.i>0&&!wi(this))return this.f&=-2,!0;var t=k;try{Ri(this),k=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(i){this.v=i,this.f|=16,this.i++}return k=t,Ai(this),this.f&=-2,!0},be.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}z.prototype.S.call(this,t)},be.prototype.U=function(t){if(this.t!==void 0&&(z.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},be.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(be.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=bi(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function Oi(t,e){return new be(t,e)}function xi(t){var e=t.u;if(t.u=void 0,typeof e=="function"){fe++;var i=k;k=void 0;try{e()}catch(n){throw t.f&=-2,t.f|=8,It(t),n}finally{k=i,nt()}}}function It(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,xi(t)}function kn(t){if(k!==this)throw new Error("Out-of-order effect");Ai(this),k=t,this.f&=-2,8&this.f&&It(this),nt()}function ke(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}ke.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},ke.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,xi(this),Ri(this),fe++;var t=k;return k=this,kn.bind(this,t)},ke.prototype.N=function(){2&this.f||(this.f|=2,this.o=He,He=this)},ke.prototype.d=function(){this.f|=8,1&this.f||It(this)},ke.prototype.dispose=function(){this.d()};function ze(t,e){var i=new ke(t,e);try{i.c()}catch(a){throw i.d(),a}var n=i.d.bind(i);return n[Symbol.dispose]=n,n}var Ni,bt,Ln=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,ki=[];ze(function(){Ni=this.N})();function Le(t,e){N[t]=e.bind(null,N[t]||function(){})}function ot(t){bt&&bt(),bt=t&&t.S()}function Li(t){var e=this,i=t.data,n=Mi(i);n.value=i;var a=Ne(function(){for(var l=e,m=e.__v;m=m.__;)if(m.__c){m.__c.__$f|=4;break}var p=Oi(function(){var E=n.value.value;return E===0?0:E===!0?"":E||""}),f=Oi(function(){return!Array.isArray(p.value)&&!zt(p.value)}),u=ze(function(){if(this.N=Di,f.value){var E=p.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=E)}}),y=e.__$u.d;return e.__$u.d=function(){u(),y.call(this)},[f,p]},[]),s=a[0],c=a[1];return s.value?c.peek():c.value}Li.displayName="ReactiveTextNode",Object.defineProperties(z.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Li},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Le("__b",function(t,e){if(typeof e.type=="string"){var i,n=e.props;for(var a in n)if(a!=="children"){var s=n[a];s instanceof z&&(i||(e.__np=i={}),i[a]=s,n[a]=s.peek())}}t(e)}),Le("__r",function(t,e){if(e.type!==he){ot();var i,n=e.__c;n&&(n.__$f&=-2,(i=n.__$u)===void 0&&(n.__$u=i=(function(a,s){var c;return ze(function(){c=this},{name:s}),c.c=a,c})(function(){var a;Ln&&((a=i.y)==null||a.call(i)),n.__$f|=1,n.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),ot(i)}t(e)}),Le("__e",function(t,e,i,n){ot(),t(e,i,n)}),Le("diffed",function(t,e){ot();var i;if(typeof e.type=="string"&&(i=e.__e)){var n=e.__np,a=e.props;if(n){var s=i.U;if(s)for(var c in s){var l=s[c];l!==void 0&&!(c in n)&&(l.d(),s[c]=void 0)}else s={},i.U=s;for(var m in n){var p=s[m],f=n[m];p===void 0?(p=Mn(i,m,f,a),s[m]=p):p.o(f,a)}}}t(e)});function Mn(t,e,i,n){var a=e in t&&t.ownerSVGElement===void 0,s=G(i);return{o:function(c,l){s.value=c,n=l},d:ze(function(){this.N=Di;var c=s.value.value;n[e]!==c&&(n[e]=c,a?t[e]=c:c!=null&&(c!==!1||e[4]==="-")?t.setAttribute(e,c):t.removeAttribute(e))})}}Le("unmount",function(t,e){if(typeof e.type=="string"){var i=e.__e;if(i){var n=i.U;if(n){i.U=void 0;for(var a in n){var s=n[a];s&&s.d()}}}}else{var c=e.__c;if(c){var l=c.__$u;l&&(c.__$u=void 0,l.d())}}t(e)}),Le("__h",function(t,e,i,n){(n<3||n===9)&&(e.__$f|=2),t(e,i,n)}),Oe.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var i=this.__$u,n=i&&i.s!==void 0;for(var a in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(n||s||4&this.__$f)||1&this.__$f)return!0}else if(!(n||4&this.__$f)||3&this.__$f)return!0;for(var c in t)if(c!=="__source"&&t[c]!==this.props[c])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function Mi(t,e){return St(function(){return G(t,e)})[0]}var Dn=function(t){queueMicrotask(function(){queueMicrotask(t)})};function Un(){Nn(function(){for(var t;t=ki.shift();)Ni.call(t)})}function Di(){ki.push(this)===1&&(N.requestAnimationFrame||Dn)(Un)}const wt={layout:"floating",initialState:"expanded",position:"bottom-right",showCaptions:!1,showTextInput:!0,showMuteButton:!0,showTranscript:!0,removeWatermark:!1,callToAction:"Talk to our assistant"},st={"bottom-right":{bottom:"24px",right:"24px"},"bottom-left":{bottom:"24px",left:"24px"},"top-right":{top:"24px",right:"24px"},"top-left":{top:"24px",left:"24px"}},Pn=new Set(["top","right","bottom","left","margin","margin-top","margin-right","margin-bottom","margin-left"]);function Bn(t){if(st[t])return st[t];const e=t.match(/^\[(.+)\]$/);if(!e)return st["bottom-right"];const i={};for(const n of e[1].split(",")){const a=n.trim(),s=a.lastIndexOf("-");if(s<=0)continue;const c=a.slice(0,s);if(!Pn.has(c))continue;const l=a.slice(s+1);/^[\w.%-]+$/.test(l)&&(i[c]=/^\d+$/.test(l)?`${l}px`:l)}return Object.keys(i).length>0?i:st["bottom-right"]}var Rt={},qe={},Ui;function Fn(){if(Ui)return qe;Ui=1,qe.byteLength=l,qe.toByteArray=p,qe.fromByteArray=y;for(var t=[],e=[],i=typeof Uint8Array<"u"?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,s=n.length;a<s;++a)t[a]=n[a],e[n.charCodeAt(a)]=a;e[45]=62,e[95]=63;function c(E){var S=E.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var T=E.indexOf("=");T===-1&&(T=S);var I=T===S?0:4-T%4;return[T,I]}function l(E){var S=c(E),T=S[0],I=S[1];return(T+I)*3/4-I}function m(E,S,T){return(S+T)*3/4-T}function p(E){var S,T=c(E),I=T[0],w=T[1],b=new i(m(E,I,w)),O=0,L=w>0?I-4:I,R;for(R=0;R<L;R+=4)S=e[E.charCodeAt(R)]<<18|e[E.charCodeAt(R+1)]<<12|e[E.charCodeAt(R+2)]<<6|e[E.charCodeAt(R+3)],b[O++]=S>>16&255,b[O++]=S>>8&255,b[O++]=S&255;return w===2&&(S=e[E.charCodeAt(R)]<<2|e[E.charCodeAt(R+1)]>>4,b[O++]=S&255),w===1&&(S=e[E.charCodeAt(R)]<<10|e[E.charCodeAt(R+1)]<<4|e[E.charCodeAt(R+2)]>>2,b[O++]=S>>8&255,b[O++]=S&255),b}function f(E){return t[E>>18&63]+t[E>>12&63]+t[E>>6&63]+t[E&63]}function u(E,S,T){for(var I,w=[],b=S;b<T;b+=3)I=(E[b]<<16&16711680)+(E[b+1]<<8&65280)+(E[b+2]&255),w.push(f(I));return w.join("")}function y(E){for(var S,T=E.length,I=T%3,w=[],b=16383,O=0,L=T-I;O<L;O+=b)w.push(u(E,O,O+b>L?L:O+b));return I===1?(S=E[T-1],w.push(t[S>>2]+t[S<<4&63]+"==")):I===2&&(S=(E[T-2]<<8)+E[T-1],w.push(t[S>>10]+t[S>>4&63]+t[S<<2&63]+"=")),w.join("")}return qe}var at={};var Pi;function $n(){return Pi||(Pi=1,at.read=function(t,e,i,n,a){var s,c,l=a*8-n-1,m=(1<<l)-1,p=m>>1,f=-7,u=i?a-1:0,y=i?-1:1,E=t[e+u];for(u+=y,s=E&(1<<-f)-1,E>>=-f,f+=l;f>0;s=s*256+t[e+u],u+=y,f-=8);for(c=s&(1<<-f)-1,s>>=-f,f+=n;f>0;c=c*256+t[e+u],u+=y,f-=8);if(s===0)s=1-p;else{if(s===m)return c?NaN:(E?-1:1)*(1/0);c=c+Math.pow(2,n),s=s-p}return(E?-1:1)*c*Math.pow(2,s-n)},at.write=function(t,e,i,n,a,s){var c,l,m,p=s*8-a-1,f=(1<<p)-1,u=f>>1,y=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,E=n?0:s-1,S=n?1:-1,T=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=f):(c=Math.floor(Math.log(e)/Math.LN2),e*(m=Math.pow(2,-c))<1&&(c--,m*=2),c+u>=1?e+=y/m:e+=y*Math.pow(2,1-u),e*m>=2&&(c++,m/=2),c+u>=f?(l=0,c=f):c+u>=1?(l=(e*m-1)*Math.pow(2,a),c=c+u):(l=e*Math.pow(2,u-1)*Math.pow(2,a),c=0));a>=8;t[i+E]=l&255,E+=S,l/=256,a-=8);for(c=c<<a|l,p+=a;p>0;t[i+E]=c&255,E+=S,c/=256,p-=8);t[i+E-S]|=T*128}),at}var Bi;function Vn(){return Bi||(Bi=1,(function(t){const e=Fn(),i=$n(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=b,t.INSPECT_MAX_BYTES=50;const a=2147483647;t.kMaxLength=a,l.TYPED_ARRAY_SUPPORT=s(),!l.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const d=new Uint8Array(1),r={foo:function(){return 42}};return Object.setPrototypeOf(r,Uint8Array.prototype),Object.setPrototypeOf(d,r),d.foo()===42}catch{return!1}}Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}});function c(d){if(d>a)throw new RangeError('The value "'+d+'" is invalid for option "size"');const r=new Uint8Array(d);return Object.setPrototypeOf(r,l.prototype),r}function l(d,r,o){if(typeof d=="number"){if(typeof r=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(d)}return m(d,r,o)}l.poolSize=8192;function m(d,r,o){if(typeof d=="string")return y(d,r);if(ArrayBuffer.isView(d))return S(d);if(d==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof d);if(ce(d,ArrayBuffer)||d&&ce(d.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ce(d,SharedArrayBuffer)||d&&ce(d.buffer,SharedArrayBuffer)))return T(d,r,o);if(typeof d=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const h=d.valueOf&&d.valueOf();if(h!=null&&h!==d)return l.from(h,r,o);const _=I(d);if(_)return _;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof d[Symbol.toPrimitive]=="function")return l.from(d[Symbol.toPrimitive]("string"),r,o);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof d)}l.from=function(d,r,o){return m(d,r,o)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array);function p(d){if(typeof d!="number")throw new TypeError('"size" argument must be of type number');if(d<0)throw new RangeError('The value "'+d+'" is invalid for option "size"')}function f(d,r,o){return p(d),d<=0?c(d):r!==void 0?typeof o=="string"?c(d).fill(r,o):c(d).fill(r):c(d)}l.alloc=function(d,r,o){return f(d,r,o)};function u(d){return p(d),c(d<0?0:w(d)|0)}l.allocUnsafe=function(d){return u(d)},l.allocUnsafeSlow=function(d){return u(d)};function y(d,r){if((typeof r!="string"||r==="")&&(r="utf8"),!l.isEncoding(r))throw new TypeError("Unknown encoding: "+r);const o=O(d,r)|0;let h=c(o);const _=h.write(d,r);return _!==o&&(h=h.slice(0,_)),h}function E(d){const r=d.length<0?0:w(d.length)|0,o=c(r);for(let h=0;h<r;h+=1)o[h]=d[h]&255;return o}function S(d){if(ce(d,Uint8Array)){const r=new Uint8Array(d);return T(r.buffer,r.byteOffset,r.byteLength)}return E(d)}function T(d,r,o){if(r<0||d.byteLength<r)throw new RangeError('"offset" is outside of buffer bounds');if(d.byteLength<r+(o||0))throw new RangeError('"length" is outside of buffer bounds');let h;return r===void 0&&o===void 0?h=new Uint8Array(d):o===void 0?h=new Uint8Array(d,r):h=new Uint8Array(d,r,o),Object.setPrototypeOf(h,l.prototype),h}function I(d){if(l.isBuffer(d)){const r=w(d.length)|0,o=c(r);return o.length===0||d.copy(o,0,0,r),o}if(d.length!==void 0)return typeof d.length!="number"||Gt(d.length)?c(0):E(d);if(d.type==="Buffer"&&Array.isArray(d.data))return E(d.data)}function w(d){if(d>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return d|0}function b(d){return+d!=d&&(d=0),l.alloc(+d)}l.isBuffer=function(r){return r!=null&&r._isBuffer===!0&&r!==l.prototype},l.compare=function(r,o){if(ce(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),ce(o,Uint8Array)&&(o=l.from(o,o.offset,o.byteLength)),!l.isBuffer(r)||!l.isBuffer(o))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(r===o)return 0;let h=r.length,_=o.length;for(let g=0,v=Math.min(h,_);g<v;++g)if(r[g]!==o[g]){h=r[g],_=o[g];break}return h<_?-1:_<h?1:0},l.isEncoding=function(r){switch(String(r).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(r,o){if(!Array.isArray(r))throw new TypeError('"list" argument must be an Array of Buffers');if(r.length===0)return l.alloc(0);let h;if(o===void 0)for(o=0,h=0;h<r.length;++h)o+=r[h].length;const _=l.allocUnsafe(o);let g=0;for(h=0;h<r.length;++h){let v=r[h];if(ce(v,Uint8Array))g+v.length>_.length?(l.isBuffer(v)||(v=l.from(v)),v.copy(_,g)):Uint8Array.prototype.set.call(_,v,g);else if(l.isBuffer(v))v.copy(_,g);else throw new TypeError('"list" argument must be an Array of Buffers');g+=v.length}return _};function O(d,r){if(l.isBuffer(d))return d.length;if(ArrayBuffer.isView(d)||ce(d,ArrayBuffer))return d.byteLength;if(typeof d!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof d);const o=d.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&o===0)return 0;let _=!1;for(;;)switch(r){case"ascii":case"latin1":case"binary":return o;case"utf8":case"utf-8":return jt(d).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return o*2;case"hex":return o>>>1;case"base64":return fn(d).length;default:if(_)return h?-1:jt(d).length;r=(""+r).toLowerCase(),_=!0}}l.byteLength=O;function L(d,r,o){let h=!1;if((r===void 0||r<0)&&(r=0),r>this.length||((o===void 0||o>this.length)&&(o=this.length),o<=0)||(o>>>=0,r>>>=0,o<=r))return"";for(d||(d="utf8");;)switch(d){case"hex":return dt(this,r,o);case"utf8":case"utf-8":return Se(this,r,o);case"ascii":return ne(this,r,o);case"latin1":case"binary":return Vt(this,r,o);case"base64":return Ce(this,r,o);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,r,o);default:if(h)throw new TypeError("Unknown encoding: "+d);d=(d+"").toLowerCase(),h=!0}}l.prototype._isBuffer=!0;function R(d,r,o){const h=d[r];d[r]=d[o],d[o]=h}l.prototype.swap16=function(){const r=this.length;if(r%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let o=0;o<r;o+=2)R(this,o,o+1);return this},l.prototype.swap32=function(){const r=this.length;if(r%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let o=0;o<r;o+=4)R(this,o,o+3),R(this,o+1,o+2);return this},l.prototype.swap64=function(){const r=this.length;if(r%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let o=0;o<r;o+=8)R(this,o,o+7),R(this,o+1,o+6),R(this,o+2,o+5),R(this,o+3,o+4);return this},l.prototype.toString=function(){const r=this.length;return r===0?"":arguments.length===0?Se(this,0,r):L.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(r){if(!l.isBuffer(r))throw new TypeError("Argument must be a Buffer");return this===r?!0:l.compare(this,r)===0},l.prototype.inspect=function(){let r="";const o=t.INSPECT_MAX_BYTES;return r=this.toString("hex",0,o).replace(/(.{2})/g,"$1 ").trim(),this.length>o&&(r+=" ... "),"<Buffer "+r+">"},n&&(l.prototype[n]=l.prototype.inspect),l.prototype.compare=function(r,o,h,_,g){if(ce(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),!l.isBuffer(r))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof r);if(o===void 0&&(o=0),h===void 0&&(h=r?r.length:0),_===void 0&&(_=0),g===void 0&&(g=this.length),o<0||h>r.length||_<0||g>this.length)throw new RangeError("out of range index");if(_>=g&&o>=h)return 0;if(_>=g)return-1;if(o>=h)return 1;if(o>>>=0,h>>>=0,_>>>=0,g>>>=0,this===r)return 0;let v=g-_,x=h-o;const P=Math.min(v,x),D=this.slice(_,g),B=r.slice(o,h);for(let M=0;M<P;++M)if(D[M]!==B[M]){v=D[M],x=B[M];break}return v<x?-1:x<v?1:0};function Q(d,r,o,h,_){if(d.length===0)return-1;if(typeof o=="string"?(h=o,o=0):o>2147483647?o=2147483647:o<-2147483648&&(o=-2147483648),o=+o,Gt(o)&&(o=_?0:d.length-1),o<0&&(o=d.length+o),o>=d.length){if(_)return-1;o=d.length-1}else if(o<0)if(_)o=0;else return-1;if(typeof r=="string"&&(r=l.from(r,h)),l.isBuffer(r))return r.length===0?-1:H(d,r,o,h,_);if(typeof r=="number")return r=r&255,typeof Uint8Array.prototype.indexOf=="function"?_?Uint8Array.prototype.indexOf.call(d,r,o):Uint8Array.prototype.lastIndexOf.call(d,r,o):H(d,[r],o,h,_);throw new TypeError("val must be string, number or Buffer")}function H(d,r,o,h,_){let g=1,v=d.length,x=r.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(d.length<2||r.length<2)return-1;g=2,v/=2,x/=2,o/=2}function P(B,M){return g===1?B[M]:B.readUInt16BE(M*g)}let D;if(_){let B=-1;for(D=o;D<v;D++)if(P(d,D)===P(r,B===-1?0:D-B)){if(B===-1&&(B=D),D-B+1===x)return B*g}else B!==-1&&(D-=D-B),B=-1}else for(o+x>v&&(o=v-x),D=o;D>=0;D--){let B=!0;for(let M=0;M<x;M++)if(P(d,D+M)!==P(r,M)){B=!1;break}if(B)return D}return-1}l.prototype.includes=function(r,o,h){return this.indexOf(r,o,h)!==-1},l.prototype.indexOf=function(r,o,h){return Q(this,r,o,h,!0)},l.prototype.lastIndexOf=function(r,o,h){return Q(this,r,o,h,!1)};function oe(d,r,o,h){o=Number(o)||0;const _=d.length-o;h?(h=Number(h),h>_&&(h=_)):h=_;const g=r.length;h>g/2&&(h=g/2);let v;for(v=0;v<h;++v){const x=parseInt(r.substr(v*2,2),16);if(Gt(x))return v;d[o+v]=x}return v}function te(d,r,o,h){return ut(jt(r,d.length-o),d,o,h)}function se(d,r,o,h){return ut(fo(r),d,o,h)}function K(d,r,o,h){return ut(fn(r),d,o,h)}function ee(d,r,o,h){return ut(po(r,d.length-o),d,o,h)}l.prototype.write=function(r,o,h,_){if(o===void 0)_="utf8",h=this.length,o=0;else if(h===void 0&&typeof o=="string")_=o,h=this.length,o=0;else if(isFinite(o))o=o>>>0,isFinite(h)?(h=h>>>0,_===void 0&&(_="utf8")):(_=h,h=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const g=this.length-o;if((h===void 0||h>g)&&(h=g),r.length>0&&(h<0||o<0)||o>this.length)throw new RangeError("Attempt to write outside buffer bounds");_||(_="utf8");let v=!1;for(;;)switch(_){case"hex":return oe(this,r,o,h);case"utf8":case"utf-8":return te(this,r,o,h);case"ascii":case"latin1":case"binary":return se(this,r,o,h);case"base64":return K(this,r,o,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,r,o,h);default:if(v)throw new TypeError("Unknown encoding: "+_);_=(""+_).toLowerCase(),v=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ce(d,r,o){return r===0&&o===d.length?e.fromByteArray(d):e.fromByteArray(d.slice(r,o))}function Se(d,r,o){o=Math.min(d.length,o);const h=[];let _=r;for(;_<o;){const g=d[_];let v=null,x=g>239?4:g>223?3:g>191?2:1;if(_+x<=o){let P,D,B,M;switch(x){case 1:g<128&&(v=g);break;case 2:P=d[_+1],(P&192)===128&&(M=(g&31)<<6|P&63,M>127&&(v=M));break;case 3:P=d[_+1],D=d[_+2],(P&192)===128&&(D&192)===128&&(M=(g&15)<<12|(P&63)<<6|D&63,M>2047&&(M<55296||M>57343)&&(v=M));break;case 4:P=d[_+1],D=d[_+2],B=d[_+3],(P&192)===128&&(D&192)===128&&(B&192)===128&&(M=(g&15)<<18|(P&63)<<12|(D&63)<<6|B&63,M>65535&&M<1114112&&(v=M))}}v===null?(v=65533,x=1):v>65535&&(v-=65536,h.push(v>>>10&1023|55296),v=56320|v&1023),h.push(v),_+=x}return Re(h)}const we=4096;function Re(d){const r=d.length;if(r<=we)return String.fromCharCode.apply(String,d);let o="",h=0;for(;h<r;)o+=String.fromCharCode.apply(String,d.slice(h,h+=we));return o}function ne(d,r,o){let h="";o=Math.min(d.length,o);for(let _=r;_<o;++_)h+=String.fromCharCode(d[_]&127);return h}function Vt(d,r,o){let h="";o=Math.min(d.length,o);for(let _=r;_<o;++_)h+=String.fromCharCode(d[_]);return h}function dt(d,r,o){const h=d.length;(!r||r<0)&&(r=0),(!o||o<0||o>h)&&(o=h);let _="";for(let g=r;g<o;++g)_+=_o[d[g]];return _}function W(d,r,o){const h=d.slice(r,o);let _="";for(let g=0;g<h.length-1;g+=2)_+=String.fromCharCode(h[g]+h[g+1]*256);return _}l.prototype.slice=function(r,o){const h=this.length;r=~~r,o=o===void 0?h:~~o,r<0?(r+=h,r<0&&(r=0)):r>h&&(r=h),o<0?(o+=h,o<0&&(o=0)):o>h&&(o=h),o<r&&(o=r);const _=this.subarray(r,o);return Object.setPrototypeOf(_,l.prototype),_};function j(d,r,o){if(d%1!==0||d<0)throw new RangeError("offset is not uint");if(d+r>o)throw new RangeError("Trying to access beyond buffer length")}l.prototype.readUintLE=l.prototype.readUIntLE=function(r,o,h){r=r>>>0,o=o>>>0,h||j(r,o,this.length);let _=this[r],g=1,v=0;for(;++v<o&&(g*=256);)_+=this[r+v]*g;return _},l.prototype.readUintBE=l.prototype.readUIntBE=function(r,o,h){r=r>>>0,o=o>>>0,h||j(r,o,this.length);let _=this[r+--o],g=1;for(;o>0&&(g*=256);)_+=this[r+--o]*g;return _},l.prototype.readUint8=l.prototype.readUInt8=function(r,o){return r=r>>>0,o||j(r,1,this.length),this[r]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(r,o){return r=r>>>0,o||j(r,2,this.length),this[r]|this[r+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(r,o){return r=r>>>0,o||j(r,2,this.length),this[r]<<8|this[r+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(r,o){return r=r>>>0,o||j(r,4,this.length),(this[r]|this[r+1]<<8|this[r+2]<<16)+this[r+3]*16777216},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(r,o){return r=r>>>0,o||j(r,4,this.length),this[r]*16777216+(this[r+1]<<16|this[r+2]<<8|this[r+3])},l.prototype.readBigUInt64LE=ye(function(r){r=r>>>0,Be(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Je(r,this.length-8);const _=o+this[++r]*2**8+this[++r]*2**16+this[++r]*2**24,g=this[++r]+this[++r]*2**8+this[++r]*2**16+h*2**24;return BigInt(_)+(BigInt(g)<<BigInt(32))}),l.prototype.readBigUInt64BE=ye(function(r){r=r>>>0,Be(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Je(r,this.length-8);const _=o*2**24+this[++r]*2**16+this[++r]*2**8+this[++r],g=this[++r]*2**24+this[++r]*2**16+this[++r]*2**8+h;return(BigInt(_)<<BigInt(32))+BigInt(g)}),l.prototype.readIntLE=function(r,o,h){r=r>>>0,o=o>>>0,h||j(r,o,this.length);let _=this[r],g=1,v=0;for(;++v<o&&(g*=256);)_+=this[r+v]*g;return g*=128,_>=g&&(_-=Math.pow(2,8*o)),_},l.prototype.readIntBE=function(r,o,h){r=r>>>0,o=o>>>0,h||j(r,o,this.length);let _=o,g=1,v=this[r+--_];for(;_>0&&(g*=256);)v+=this[r+--_]*g;return g*=128,v>=g&&(v-=Math.pow(2,8*o)),v},l.prototype.readInt8=function(r,o){return r=r>>>0,o||j(r,1,this.length),this[r]&128?(255-this[r]+1)*-1:this[r]},l.prototype.readInt16LE=function(r,o){r=r>>>0,o||j(r,2,this.length);const h=this[r]|this[r+1]<<8;return h&32768?h|4294901760:h},l.prototype.readInt16BE=function(r,o){r=r>>>0,o||j(r,2,this.length);const h=this[r+1]|this[r]<<8;return h&32768?h|4294901760:h},l.prototype.readInt32LE=function(r,o){return r=r>>>0,o||j(r,4,this.length),this[r]|this[r+1]<<8|this[r+2]<<16|this[r+3]<<24},l.prototype.readInt32BE=function(r,o){return r=r>>>0,o||j(r,4,this.length),this[r]<<24|this[r+1]<<16|this[r+2]<<8|this[r+3]},l.prototype.readBigInt64LE=ye(function(r){r=r>>>0,Be(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Je(r,this.length-8);const _=this[r+4]+this[r+5]*2**8+this[r+6]*2**16+(h<<24);return(BigInt(_)<<BigInt(32))+BigInt(o+this[++r]*2**8+this[++r]*2**16+this[++r]*2**24)}),l.prototype.readBigInt64BE=ye(function(r){r=r>>>0,Be(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Je(r,this.length-8);const _=(o<<24)+this[++r]*2**16+this[++r]*2**8+this[++r];return(BigInt(_)<<BigInt(32))+BigInt(this[++r]*2**24+this[++r]*2**16+this[++r]*2**8+h)}),l.prototype.readFloatLE=function(r,o){return r=r>>>0,o||j(r,4,this.length),i.read(this,r,!0,23,4)},l.prototype.readFloatBE=function(r,o){return r=r>>>0,o||j(r,4,this.length),i.read(this,r,!1,23,4)},l.prototype.readDoubleLE=function(r,o){return r=r>>>0,o||j(r,8,this.length),i.read(this,r,!0,52,8)},l.prototype.readDoubleBE=function(r,o){return r=r>>>0,o||j(r,8,this.length),i.read(this,r,!1,52,8)};function ie(d,r,o,h,_,g){if(!l.isBuffer(d))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>_||r<g)throw new RangeError('"value" argument is out of bounds');if(o+h>d.length)throw new RangeError("Index out of range")}l.prototype.writeUintLE=l.prototype.writeUIntLE=function(r,o,h,_){if(r=+r,o=o>>>0,h=h>>>0,!_){const x=Math.pow(2,8*h)-1;ie(this,r,o,h,x,0)}let g=1,v=0;for(this[o]=r&255;++v<h&&(g*=256);)this[o+v]=r/g&255;return o+h},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(r,o,h,_){if(r=+r,o=o>>>0,h=h>>>0,!_){const x=Math.pow(2,8*h)-1;ie(this,r,o,h,x,0)}let g=h-1,v=1;for(this[o+g]=r&255;--g>=0&&(v*=256);)this[o+g]=r/v&255;return o+h},l.prototype.writeUint8=l.prototype.writeUInt8=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,1,255,0),this[o]=r&255,o+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,2,65535,0),this[o]=r&255,this[o+1]=r>>>8,o+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,2,65535,0),this[o]=r>>>8,this[o+1]=r&255,o+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,4,4294967295,0),this[o+3]=r>>>24,this[o+2]=r>>>16,this[o+1]=r>>>8,this[o]=r&255,o+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,4,4294967295,0),this[o]=r>>>24,this[o+1]=r>>>16,this[o+2]=r>>>8,this[o+3]=r&255,o+4};function sn(d,r,o,h,_){hn(r,h,_,d,o,7);let g=Number(r&BigInt(4294967295));d[o++]=g,g=g>>8,d[o++]=g,g=g>>8,d[o++]=g,g=g>>8,d[o++]=g;let v=Number(r>>BigInt(32)&BigInt(4294967295));return d[o++]=v,v=v>>8,d[o++]=v,v=v>>8,d[o++]=v,v=v>>8,d[o++]=v,o}function an(d,r,o,h,_){hn(r,h,_,d,o,7);let g=Number(r&BigInt(4294967295));d[o+7]=g,g=g>>8,d[o+6]=g,g=g>>8,d[o+5]=g,g=g>>8,d[o+4]=g;let v=Number(r>>BigInt(32)&BigInt(4294967295));return d[o+3]=v,v=v>>8,d[o+2]=v,v=v>>8,d[o+1]=v,v=v>>8,d[o]=v,o+8}l.prototype.writeBigUInt64LE=ye(function(r,o=0){return sn(this,r,o,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=ye(function(r,o=0){return an(this,r,o,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(r,o,h,_){if(r=+r,o=o>>>0,!_){const P=Math.pow(2,8*h-1);ie(this,r,o,h,P-1,-P)}let g=0,v=1,x=0;for(this[o]=r&255;++g<h&&(v*=256);)r<0&&x===0&&this[o+g-1]!==0&&(x=1),this[o+g]=(r/v>>0)-x&255;return o+h},l.prototype.writeIntBE=function(r,o,h,_){if(r=+r,o=o>>>0,!_){const P=Math.pow(2,8*h-1);ie(this,r,o,h,P-1,-P)}let g=h-1,v=1,x=0;for(this[o+g]=r&255;--g>=0&&(v*=256);)r<0&&x===0&&this[o+g+1]!==0&&(x=1),this[o+g]=(r/v>>0)-x&255;return o+h},l.prototype.writeInt8=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,1,127,-128),r<0&&(r=255+r+1),this[o]=r&255,o+1},l.prototype.writeInt16LE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,2,32767,-32768),this[o]=r&255,this[o+1]=r>>>8,o+2},l.prototype.writeInt16BE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,2,32767,-32768),this[o]=r>>>8,this[o+1]=r&255,o+2},l.prototype.writeInt32LE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,4,2147483647,-2147483648),this[o]=r&255,this[o+1]=r>>>8,this[o+2]=r>>>16,this[o+3]=r>>>24,o+4},l.prototype.writeInt32BE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),this[o]=r>>>24,this[o+1]=r>>>16,this[o+2]=r>>>8,this[o+3]=r&255,o+4},l.prototype.writeBigInt64LE=ye(function(r,o=0){return sn(this,r,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=ye(function(r,o=0){return an(this,r,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ln(d,r,o,h,_,g){if(o+h>d.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("Index out of range")}function cn(d,r,o,h,_){return r=+r,o=o>>>0,_||ln(d,r,o,4),i.write(d,r,o,h,23,4),o+4}l.prototype.writeFloatLE=function(r,o,h){return cn(this,r,o,!0,h)},l.prototype.writeFloatBE=function(r,o,h){return cn(this,r,o,!1,h)};function dn(d,r,o,h,_){return r=+r,o=o>>>0,_||ln(d,r,o,8),i.write(d,r,o,h,52,8),o+8}l.prototype.writeDoubleLE=function(r,o,h){return dn(this,r,o,!0,h)},l.prototype.writeDoubleBE=function(r,o,h){return dn(this,r,o,!1,h)},l.prototype.copy=function(r,o,h,_){if(!l.isBuffer(r))throw new TypeError("argument should be a Buffer");if(h||(h=0),!_&&_!==0&&(_=this.length),o>=r.length&&(o=r.length),o||(o=0),_>0&&_<h&&(_=h),_===h||r.length===0||this.length===0)return 0;if(o<0)throw new RangeError("targetStart out of bounds");if(h<0||h>=this.length)throw new RangeError("Index out of range");if(_<0)throw new RangeError("sourceEnd out of bounds");_>this.length&&(_=this.length),r.length-o<_-h&&(_=r.length-o+h);const g=_-h;return this===r&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(o,h,_):Uint8Array.prototype.set.call(r,this.subarray(h,_),o),g},l.prototype.fill=function(r,o,h,_){if(typeof r=="string"){if(typeof o=="string"?(_=o,o=0,h=this.length):typeof h=="string"&&(_=h,h=this.length),_!==void 0&&typeof _!="string")throw new TypeError("encoding must be a string");if(typeof _=="string"&&!l.isEncoding(_))throw new TypeError("Unknown encoding: "+_);if(r.length===1){const v=r.charCodeAt(0);(_==="utf8"&&v<128||_==="latin1")&&(r=v)}}else typeof r=="number"?r=r&255:typeof r=="boolean"&&(r=Number(r));if(o<0||this.length<o||this.length<h)throw new RangeError("Out of range index");if(h<=o)return this;o=o>>>0,h=h===void 0?this.length:h>>>0,r||(r=0);let g;if(typeof r=="number")for(g=o;g<h;++g)this[g]=r;else{const v=l.isBuffer(r)?r:l.from(r,_),x=v.length;if(x===0)throw new TypeError('The value "'+r+'" is invalid for argument "value"');for(g=0;g<h-o;++g)this[g+o]=v[g%x]}return this};const Pe={};function Wt(d,r,o){Pe[d]=class extends o{constructor(){super(),Object.defineProperty(this,"message",{value:r.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${d}]`,this.stack,delete this.name}get code(){return d}set code(_){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:_,writable:!0})}toString(){return`${this.name} [${d}]: ${this.message}`}}}Wt("ERR_BUFFER_OUT_OF_BOUNDS",function(d){return d?`${d} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Wt("ERR_INVALID_ARG_TYPE",function(d,r){return`The "${d}" argument must be of type number. Received type ${typeof r}`},TypeError),Wt("ERR_OUT_OF_RANGE",function(d,r,o){let h=`The value of "${d}" is out of range.`,_=o;return Number.isInteger(o)&&Math.abs(o)>2**32?_=un(String(o)):typeof o=="bigint"&&(_=String(o),(o>BigInt(2)**BigInt(32)||o<-(BigInt(2)**BigInt(32)))&&(_=un(_)),_+="n"),h+=` It must be ${r}. Received ${_}`,h},RangeError);function un(d){let r="",o=d.length;const h=d[0]==="-"?1:0;for(;o>=h+4;o-=3)r=`_${d.slice(o-3,o)}${r}`;return`${d.slice(0,o)}${r}`}function co(d,r,o){Be(r,"offset"),(d[r]===void 0||d[r+o]===void 0)&&Je(r,d.length-(o+1))}function hn(d,r,o,h,_,g){if(d>o||d<r){const v=typeof r=="bigint"?"n":"";let x;throw r===0||r===BigInt(0)?x=`>= 0${v} and < 2${v} ** ${(g+1)*8}${v}`:x=`>= -(2${v} ** ${(g+1)*8-1}${v}) and < 2 ** ${(g+1)*8-1}${v}`,new Pe.ERR_OUT_OF_RANGE("value",x,d)}co(h,_,g)}function Be(d,r){if(typeof d!="number")throw new Pe.ERR_INVALID_ARG_TYPE(r,"number",d)}function Je(d,r,o){throw Math.floor(d)!==d?(Be(d,o),new Pe.ERR_OUT_OF_RANGE("offset","an integer",d)):r<0?new Pe.ERR_BUFFER_OUT_OF_BOUNDS:new Pe.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${r}`,d)}const uo=/[^+/0-9A-Za-z-_]/g;function ho(d){if(d=d.split("=")[0],d=d.trim().replace(uo,""),d.length<2)return"";for(;d.length%4!==0;)d=d+"=";return d}function jt(d,r){r=r||1/0;let o;const h=d.length;let _=null;const g=[];for(let v=0;v<h;++v){if(o=d.charCodeAt(v),o>55295&&o<57344){if(!_){if(o>56319){(r-=3)>-1&&g.push(239,191,189);continue}else if(v+1===h){(r-=3)>-1&&g.push(239,191,189);continue}_=o;continue}if(o<56320){(r-=3)>-1&&g.push(239,191,189),_=o;continue}o=(_-55296<<10|o-56320)+65536}else _&&(r-=3)>-1&&g.push(239,191,189);if(_=null,o<128){if((r-=1)<0)break;g.push(o)}else if(o<2048){if((r-=2)<0)break;g.push(o>>6|192,o&63|128)}else if(o<65536){if((r-=3)<0)break;g.push(o>>12|224,o>>6&63|128,o&63|128)}else if(o<1114112){if((r-=4)<0)break;g.push(o>>18|240,o>>12&63|128,o>>6&63|128,o&63|128)}else throw new Error("Invalid code point")}return g}function fo(d){const r=[];for(let o=0;o<d.length;++o)r.push(d.charCodeAt(o)&255);return r}function po(d,r){let o,h,_;const g=[];for(let v=0;v<d.length&&!((r-=2)<0);++v)o=d.charCodeAt(v),h=o>>8,_=o%256,g.push(_),g.push(h);return g}function fn(d){return e.toByteArray(ho(d))}function ut(d,r,o,h){let _;for(_=0;_<h&&!(_+o>=r.length||_>=d.length);++_)r[_+o]=d[_];return _}function ce(d,r){return d instanceof r||d!=null&&d.constructor!=null&&d.constructor.name!=null&&d.constructor.name===r.name}function Gt(d){return d!==d}const _o=(function(){const d="0123456789abcdef",r=new Array(256);for(let o=0;o<16;++o){const h=o*16;for(let _=0;_<16;++_)r[h+_]=d[o]+d[_]}return r})();function ye(d){return typeof BigInt>"u"?mo:d}function mo(){throw new Error("BigInt not supported")}})(Rt)),Rt}var Wn=Vn();const jn="https://api.anam.ai",Gn="/v1",Fi={client:"js-sdk",version:"4.20.0"},Hn=3,zn=250,qn=2e3,Yn=1e4;var $i=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(c){c(s)})}return new(i||(i=Promise))(function(s,c){function l(f){try{p(n.next(f))}catch(u){c(u)}}function m(f){try{p(n.throw(f))}catch(u){c(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};const Vi="https://api.anam.ai",At="/v1";var le;(function(t){t.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONE="client_connection_milestone",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONES="client_connection_milestones",t.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",t.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success",t.CLIENT_METRIC_MEASUREMENT_ICE_RESTART="client_ice_restart"})(le||(le={}));const Wi=50;let Ot=Vi,ji=At,pe,Gi=!1;const Kn=(t,e=At)=>{Ot=t,ji=e},Jn=t=>{pe=t},Xn=t=>{Gi=t};let _e={sessionId:null,organizationId:null,attemptCorrelationId:null};const Ye=t=>{_e=Object.assign(Object.assign({},_e),t)},Me=(t,e,i)=>$i(void 0,void 0,void 0,function*(){yield Hi([{name:t,value:e,tags:i}])}),Hi=t=>$i(void 0,void 0,void 0,function*(){if(!(Gi||t.length===0))try{const e=`${ji}/metrics/client`;let i;const n={"Content-Type":"application/json"};pe?.enabled&&pe?.baseUrl?(i=`${pe.baseUrl}${e}`,n["X-Anam-Target-Url"]=`${Ot}${e}`):i=`${Ot}${e}`;const a=t.map(s=>{var c;return Object.assign(Object.assign({},s),{clientTimestamp:(c=s.clientTimestamp)!==null&&c!==void 0?c:new Date().toISOString(),tags:Zn(s.tags)})});for(let s=0;s<a.length;s+=Wi){const c=a.slice(s,s+Wi),l=c.length===1?c[0]:{metrics:c};yield fetch(i,{method:"POST",headers:n,body:JSON.stringify(l)})}}catch(e){console.error("Failed to send client metric:",e)}}),Zn=t=>{const e=Object.assign(Object.assign({},Fi),t);return _e.sessionId&&e.sessionId===void 0&&(e.sessionId=_e.sessionId),_e.organizationId&&e.organizationId===void 0&&(e.organizationId=_e.organizationId),_e.attemptCorrelationId&&e.attemptCorrelationId===void 0&&(e.attemptCorrelationId=_e.attemptCorrelationId),e},Qn=(t,e="console")=>{var i,n,a;const s={};t.forEach(u=>{s[u.type]||(s[u.type]=[]),s[u.type].push(u)});const c={issues:[]},l=((i=s["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="video"))||[];l.length>0&&(c.personaVideoStream=[],l.forEach(u=>{var y,E,S,T,I;const w={framesReceived:(y=u.framesReceived)!==null&&y!==void 0?y:"unknown",framesDropped:(E=u.framesDropped)!==null&&E!==void 0?E:"unknown",framesPerSecond:(S=u.framesPerSecond)!==null&&S!==void 0?S:"unknown",packetsReceived:(T=u.packetsReceived)!==null&&T!==void 0?T:"unknown",packetsLost:(I=u.packetsLost)!==null&&I!==void 0?I:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};c.personaVideoStream.push(w)}));const m=((n=s["inbound-rtp"])===null||n===void 0?void 0:n.filter(u=>u.kind==="audio"))||[];m.length>0&&(c.personaAudioStream=[],m.forEach(u=>{var y,E,S;const T={packetsReceived:(y=u.packetsReceived)!==null&&y!==void 0?y:"unknown",packetsLost:(E=u.packetsLost)!==null&&E!==void 0?E:"unknown",audioLevel:(S=u.audioLevel)!==null&&S!==void 0?S:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};c.personaAudioStream.push(T)}));const p=((a=s["outbound-rtp"])===null||a===void 0?void 0:a.filter(u=>u.kind==="audio"))||[];p.length>0&&(c.userAudioInput=[],p.forEach(u=>{var y,E;const S={packetsSent:(y=u.packetsSent)!==null&&y!==void 0?y:"unknown",retransmittedPackets:(E=u.retransmittedPacketsSent)!==null&&E!==void 0?E:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};c.userAudioInput.push(S)})),s.codec&&(c.codecs=[],s.codec.forEach(u=>{const y={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};c.codecs.push(y)})),s.transport&&(c.transportLayer=[],s.transport.forEach(u=>{const y={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};c.transportLayer.push(y)}));const f=[];if(l.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&f.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&f.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&f.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),m.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&f.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&f.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),c.issues=f,e==="json")return c;console.group("📊 WebRTC Session Statistics Report"),c.personaVideoStream&&c.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),c.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),c.personaAudioStream&&c.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),c.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),c.userAudioInput&&c.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),c.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),c.codecs&&c.codecs.length>0&&(console.group("🔧 Codecs Used"),c.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(`  Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(`  Channels: ${u.channels}`)}),console.groupEnd()),c.transportLayer&&c.transportLayer.length>0&&(console.group("🚚 Transport Layer"),c.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),c.issues.length>0?(console.group("⚠️ Potential Issues Detected"),c.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var q;(function(t){t.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",t.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",t.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",t.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",t.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",t.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",t.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",t.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",t.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",t.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(q||(q={}));class $ extends Error{constructor(e,i,n=500,a){super(e),this.name="ClientError",this.code=i,this.statusCode=n,this.details=a,Object.setPrototypeOf(this,$.prototype),Me(le.CLIENT_METRIC_MEASUREMENT_ERROR,i,{details:a,statusCode:n})}}function er(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}const zi=0,tr=5e3;class ir{constructor(e={}){var i,n,a,s;this.milestones=[],this.context={sessionId:null,organizationId:null,attemptCorrelationId:null},this.published=!1,this.sessionSuccessful=!1,this.now=(i=e.now)!==null&&i!==void 0?i:nr,this.attemptStartedAtMs=this.now(),this.sampleRatio=rr((n=e.connectionMilestoneSampleRatio)!==null&&n!==void 0?n:zi),this.slowConnectionThresholdMs=Math.max(0,qi(e.slowConnectionThresholdMs,tr)),this.sampled=((a=e.random)!==null&&a!==void 0?a:Math.random)()<this.sampleRatio,this.updateContext((s=e.context)!==null&&s!==void 0?s:{}),this.record("client_session_attempt")}updateContext(e){this.context=Object.assign(Object.assign({},this.context),e)}record(e,i){if(this.published)return;const n=Yi(i),a={name:e,elapsedMs:this.elapsedMs(),clientTimestamp:new Date().toISOString()};Object.keys(n).length>0&&(a.tags=n),this.milestones.push(a)}recordSessionSuccess(e){this.sessionSuccessful||(this.sessionSuccessful=!0,this.record("client_session_success",e),this.publishIfNeeded(),this.finalize())}finalize(){this.published=!0,this.milestones.length=0}publishFailure(e){this.sessionSuccessful||this.published||(this.record("connection_attempt_failed",e),this.publish("failed",e))}publishIfNeeded(){if(!this.published){if(this.elapsedMs()>=this.slowConnectionThresholdMs){this.publish("slow");return}this.sampled&&this.publish("sampled")}}publish(e,i){if(this.published||this.milestones.length===0)return;this.published=!0;const n=Ki(Object.assign(Object.assign(Object.assign({},i),this.context),{publishReason:e,attemptDurationMs:this.elapsedMs(),milestoneCount:this.milestones.length,connectionMilestoneSampleRatio:this.sampleRatio,slowConnectionThresholdMs:this.slowConnectionThresholdMs,wasSampled:this.sampled?1:0})),a=[{name:le.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONES,value:"1",tags:n},...this.milestones.map((s,c)=>({name:le.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONE,value:s.elapsedMs,clientTimestamp:s.clientTimestamp,tags:Ki(Object.assign(Object.assign(Object.assign({},this.context),{publishReason:e,milestone:s.name,sequence:c}),s.tags))}))];Hi(a)}elapsedMs(){return Math.max(0,Math.round(this.now()-this.attemptStartedAtMs))}}const nr=()=>typeof performance<"u"?performance.now():Date.now(),rr=t=>{const e=qi(t,zi);return Math.min(1,Math.max(0,e))},qi=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e,Yi=t=>{if(!t)return{};const e={};return Object.entries(t).forEach(([i,n])=>{n!=null&&(typeof n=="number"&&!Number.isFinite(n)||(e[i]=n))}),e},Ki=t=>{const e={};return Object.entries(Yi(t)).forEach(([i,n])=>{e[i]=typeof n=="boolean"?String(n):n}),e};function or(t){if(!(!t||!t.enabled)){if(!t.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(t.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${t.baseUrl}`}if(t.wsPath&&!t.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var J;(function(t){t.OFFER="offer",t.ANSWER="answer",t.ICE_CANDIDATE="icecandidate",t.END_SESSION="endsession",t.HEARTBEAT="heartbeat",t.WARNING="warning",t.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",t.TALK_STREAM_INPUT="talkstream",t.SESSION_READY="sessionready",t.AGENT_AUDIO_INPUT="agentaudioinput",t.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(J||(J={}));var re;(function(t){t.SPEECH_TEXT="speechText",t.CLIENT_TOOL_EVENT="clientToolEvent",t.TOOL_CALL_STARTED_EVENT="toolCallStarted",t.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",t.TOOL_CALL_FAILED_EVENT="toolCallFailed",t.REASONING_TEXT="reasoningText",t.USER_SPEECH_STARTED="userSpeechStarted",t.USER_SPEECH_ENDED="userSpeechEnded",t.DIRECTOR_NOTE_CUE_APPLIED="directorNoteCueApplied"})(re||(re={}));var me;(function(t){t.PENDING="pending",t.GRANTED="granted",t.DENIED="denied",t.NOT_REQUESTED="not_requested"})(me||(me={}));var ge;(function(t){t.USER="user",t.PERSONA="persona"})(ge||(ge={}));var A;(function(t){t.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",t.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",t.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",t.CONNECTION_CLOSED="CONNECTION_CLOSED",t.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",t.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",t.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",t.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",t.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",t.SESSION_READY="SESSION_READY",t.SERVER_WARNING="SERVER_WARNING",t.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",t.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",t.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",t.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",t.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",t.TOOL_CALL_STARTED="TOOL_CALL_STARTED",t.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",t.TOOL_CALL_FAILED="TOOL_CALL_FAILED",t.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",t.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",t.USER_SPEECH_STARTED="USER_SPEECH_STARTED",t.USER_SPEECH_ENDED="USER_SPEECH_ENDED",t.DIRECTOR_NOTE_CUE_APPLIED="DIRECTOR_NOTE_CUE_APPLIED"})(A||(A={}));var U;(function(t){t.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",t.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",t.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",t.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",t.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",t.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",t.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",t.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED",t.TOOL_CALL_RESULT_READY="TOOL_CALL_RESULT_READY"})(U||(U={}));var Ee;(function(t){t.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",t.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",t.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",t.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",t.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(Ee||(Ee={}));class sr{constructor(e,i){this.sequenceNumber=0,this.config=e,this.signallingClient=i}sendAudioChunk(e){const n={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(n)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const i=e instanceof Uint8Array?e:new Uint8Array(e),n=Array.from(i,a=>String.fromCharCode(a)).join("");return btoa(n)}}var De=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(c){c(s)})}return new(i||(i=Promise))(function(s,c){function l(f){try{p(n.next(f))}catch(u){c(u)}}function m(f){try{p(n.throw(f))}catch(u){c(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};const ar=5,lr=5,cr=24;class dr{constructor(e,i,n,a,s,c){var l,m,p,f,u;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.permanentlyClosed=!1,this.iceRestartReconnectInProgress=!1,this.heartBeatIntervalRef=null,this.reconnectTimer=null,this.publicEventEmitter=n,this.internalEventEmitter=a,this.apiGatewayConfig=s,this.connectionMilestones=c,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:y,maxWsReconnectionAttempts:E,url:S}=i;if(this.heartbeatIntervalSeconds=y||ar,this.maxWsReconnectionAttempts=E||lr,!S.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((l=this.apiGatewayConfig)===null||l===void 0)&&l.enabled&&(!((m=this.apiGatewayConfig)===null||m===void 0)&&m.baseUrl)){const T=new URL(this.apiGatewayConfig.baseUrl),I=(p=this.apiGatewayConfig.wsPath)!==null&&p!==void 0?p:"/ws";T.protocol=T.protocol.replace("http","ws"),T.pathname=I,this.url=T;const w=S.protocol||"https",b=w==="http"?"ws":"wss",O=`${w}://${S.baseUrl}`,L=(f=S.signallingPath)!==null&&f!==void 0?f:"/ws",R=new URL(O);R.protocol=b==="ws"?"ws:":"wss:",S.port&&(R.port=S.port),R.pathname=L,R.searchParams.append("session_id",e),this.url.searchParams.append("target_url",R.href)}else{const I=`${S.protocol||"https"}://${S.baseUrl}`;this.url=new URL(I),this.url.protocol=S.protocol==="http"?"ws:":"wss:",S.port&&(this.url.port=S.port),this.url.pathname=(u=S.signallingPath)!==null&&u!==void 0?u:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){var e;this.clearReconnectTimer(),(e=this.connectionMilestones)===null||e===void 0||e.record("websocket_connecting",{attemptNumber:this.wsConnectionAttempts+1});const i=new WebSocket(this.url.href);return this.socket=i,i.onopen=()=>{this.onOpen(i)},i.onclose=n=>{this.onClose(i,n)},i.onerror=n=>{this.onError(i,n)},i}reconnectForIceRestart(){if(!this.isPermanentlyClosed()){if(this.clearReconnectTimer(),this.socket){this.socket.onopen=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null;try{this.socket.close()}catch(e){console.warn("SignallingClient - reconnectForIceRestart: error closing stale socket",e)}this.socket=null}this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.wsConnectionAttempts=0,this.iceRestartReconnectInProgress=!0,this.connect()}}endIceRestartReconnect(){this.iceRestartReconnectInProgress=!1}isConnected(){var e;return((e=this.socket)===null||e===void 0?void 0:e.readyState)===WebSocket.OPEN}isPermanentlyClosed(){return this.permanentlyClosed||this.stopSignal}sendOffer(e){return De(this,void 0,void 0,function*(){const i={connectionDescription:e,userUid:this.sessionId},n={actionType:J.OFFER,sessionId:this.sessionId,payload:i};this.sendSignalMessage(n)})}sendIceCandidate(e){return De(this,void 0,void 0,function*(){const i={actionType:J.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(i)})}sendSignalMessage(e){var i;if(((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(n){console.error("SignallingClient - sendSignalMessage: error sending message",n)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return De(this,void 0,void 0,function*(){const i={actionType:J.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)})}sendAgentAudioInput(e){const i={actionType:J.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)}sendAgentAudioInputEnd(){const e={actionType:J.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.clearReconnectTimer(),this.iceRestartReconnectInProgress=!1,this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(e){return De(this,void 0,void 0,function*(){var i;if(this.socket===e)try{(i=this.connectionMilestones)===null||i===void 0||i.record("websocket_open",{attemptNumber:this.wsConnectionAttempts+1}),this.wsConnectionAttempts=0,this.flushSendingBuffer(),e.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(U.WEB_SOCKET_OPEN)}catch(n){console.error("SignallingClient - onOpen: error in onOpen",n),this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.permanentlyClosed=!0}})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}onClose(e,i){return De(this,void 0,void 0,function*(){var n,a,s;if(this.socket!==e||((n=this.connectionMilestones)===null||n===void 0||n.record("websocket_closed",{attemptNumber:this.wsConnectionAttempts+1,closeCode:i?.code,wasClean:i?.wasClean}),this.wsConnectionAttempts+=1,this.stopSignal))return;const c=this.getMaxReconnectionAttempts();if(this.wsConnectionAttempts<=c){const l=100*this.wsConnectionAttempts;(a=this.connectionMilestones)===null||a===void 0||a.record("websocket_retry_scheduled",{attemptNumber:this.wsConnectionAttempts+1,delayMs:l}),this.socket=null,this.clearReconnectTimer(),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},l)}else this.clearReconnectTimer(),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),(s=this.connectionMilestones)===null||s===void 0||s.publishFailure({failureStage:"websocket",closeCode:i?.code}),this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.iceRestartReconnectInProgress=!1,this.permanentlyClosed=!0})}getMaxReconnectionAttempts(){return this.iceRestartReconnectInProgress?Math.max(this.maxWsReconnectionAttempts,cr):this.maxWsReconnectionAttempts}onError(e,i){var n;this.stopSignal||this.socket!==e||((n=this.connectionMilestones)===null||n===void 0||n.record("websocket_error",{eventType:i.type}),console.error("SignallingClient - onError: ",i))}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(i=>{var n;((n=this.socket)===null||n===void 0?void 0:n.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(i)):e.push(i)}),this.sendingBuffer=e}onMessage(e){return De(this,void 0,void 0,function*(){const i=JSON.parse(e.data);this.internalEventEmitter.emit(U.SIGNAL_MESSAGE_RECEIVED,i)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,i={actionType:J.HEARTBEAT,sessionId:this.sessionId,payload:""},n=JSON.stringify(i);this.heartBeatIntervalRef=setInterval(()=>{var a;this.stopSignal||((a=this.socket)===null||a===void 0?void 0:a.readyState)===WebSocket.OPEN&&this.socket.send(n)},e)}}function ur(t){return"brainType"in t||"llmId"in t}var xt=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(c){c(s)})}return new(i||(i=Promise))(function(s,c){function l(f){try{p(n.next(f))}catch(u){c(u)}}function m(f){try{p(n.throw(f))}catch(u){c(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};class hr{constructor(e,i,n){if(!e&&!i)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=i||null,this.baseUrl=n?.baseUrl||jn,this.apiVersion=n?.apiVersion||Gn,this.apiGatewayConfig=n?.apiGateway||void 0,this.retryOptions=fr(n?.retry),this.requestTimeoutMs=Math.max(0,lt(n?.requestTimeoutMs,Yn))}buildGatewayUrlAndHeaders(e,i){var n,a;if(!((n=this.apiGatewayConfig)===null||n===void 0)&&n.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const s=`${this.apiGatewayConfig.baseUrl}${e}`,c=new URL(`${this.baseUrl}${e}`),l=Object.assign(Object.assign({},i),{"X-Anam-Target-Url":c.href});return{url:s,headers:l}}else return{url:`${this.baseUrl}${e}`,headers:i}}startSession(e,i){return xt(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new $("Persona configuration must be provided when using apiKey",q.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");const{maxAttempts:n}=this.retryOptions;let a;for(let s=1;s<=n;s++)try{return yield this.attemptStartSession(e,i)}catch(c){if(a=c,s>=n||!pr(c))throw c;yield _r(this.computeBackoffDelay(s))}throw a})}attemptStartSession(e,i){return xt(this,void 0,void 0,function*(){const n=this.requestTimeoutMs>0?new AbortController:void 0,a=n!==void 0?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{const s=`${this.apiVersion}/engine/session`,{url:c,headers:l}=this.buildGatewayUrlAndHeaders(s,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),m=yield fetch(c,{method:"POST",headers:l,body:JSON.stringify({personaConfig:e,sessionOptions:i,clientMetadata:Fi}),signal:n?.signal}),p=yield m.json(),f=p.error;switch(m.status){case 200:case 201:return p;case 400:throw new $("Invalid request to start session",q.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:p.message});case 401:throw new $("Authentication failed when starting session",q.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:p.message});case 402:throw new $("Please sign up for a plan to start a session",q.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:p.message});case 403:throw new $("Authentication failed when starting session",q.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:p.message});case 429:throw f==="Concurrent session limit reached"?new $("Concurrency limit reached, please upgrade your plan",q.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:p.message}):f==="Spend cap reached"?new $("Spend cap reached, please upgrade your plan",q.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:p.message}):new $("Usage limit reached, please upgrade your plan",q.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:p.message});case 503:throw new $("There are no available personas, please try again later",q.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:p.message});default:throw new $("Unknown error when starting session",q.CLIENT_ERROR_CODE_SERVER_ERROR,m.status,{cause:p.message})}}catch(s){throw s instanceof $?s:new $("Failed to start session",q.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:s instanceof Error?s.message:String(s)})}finally{a!==void 0&&clearTimeout(a)}})}computeBackoffDelay(e){const{initialBackoffMs:i,maxBackoffMs:n}=this.retryOptions,a=Math.min(n,i*Math.pow(2,e-1));return Math.floor(a/2+Math.random()*(a/2))}unsafe_getSessionToken(e){return xt(this,void 0,void 0,function*(){if(console.warn("Using an insecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let i={clientLabel:"js-sdk-api-key"};ur(e)&&(i=Object.assign(Object.assign({},i),{personaConfig:e}));try{const n=`${this.apiVersion}/auth/session-token`,{url:a,headers:s}=this.buildGatewayUrlAndHeaders(n,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(a,{method:"POST",headers:s,body:JSON.stringify(i)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}function fr(t){const e=Math.max(1,Math.floor(lt(t?.maxAttempts,Hn))),i=Math.max(0,lt(t?.initialBackoffMs,zn)),n=Math.max(i,lt(t?.maxBackoffMs,qn));return{maxAttempts:e,initialBackoffMs:i,maxBackoffMs:n}}function lt(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function pr(t){return t instanceof $?t.statusCode>=500&&t.statusCode<600:!0}function _r(t){return new Promise(e=>setTimeout(e,t))}var mr=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(c){c(s)})}return new(i||(i=Promise))(function(s,c){function l(f){try{p(n.next(f))}catch(u){c(u)}}function m(f){try{p(n.throw(f))}catch(u){c(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};class gr{constructor(e,i,n){this.baseUrl=e,this.sessionId=i,this.apiGatewayConfig=n}sendTalkCommand(e){return mr(this,void 0,void 0,function*(){var i,n;try{let a,s={"Content-Type":"application/json"};const c="/talk",l=`?session_id=${this.sessionId}`;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((n=this.apiGatewayConfig)===null||n===void 0)&&n.baseUrl)){a=`${this.apiGatewayConfig.baseUrl}${c}${l}`;const p=new URL(`${this.baseUrl}${c}${l}`);s["X-Anam-Target-Url"]=p.href}else a=`${this.baseUrl}${c}${l}`;const m=yield fetch(a,{method:"POST",headers:s,body:JSON.stringify({content:e})});if(!m.ok)throw new Error(`Failed to send talk command: ${m.status} ${m.statusText}`)}catch(a){throw console.error(a),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Er{constructor(){this.listeners={}}addListener(e,i){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(i)}removeListener(e,i){this.listeners[e]&&this.listeners[e].delete(i)}emit(e,...i){this.listeners[e]&&this.listeners[e].forEach(n=>{n(...i)})}}class vr{constructor(e,i){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=i,this.internalEventEmitter.addListener(U.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return Object.assign({id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted},e.cue_tag?{cueTag:e.cue_tag}:{})}processUserMessage(e){const i={id:e.id,content:e.content,role:e.role};this.messages.push(i)}processPersonaMessage(e){const i={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},n=this.messages.findIndex(a=>a.id===i.id);if(n!==-1){const a=this.messages[n];this.messages[n]=Object.assign(Object.assign({},a),{content:a.content+i.content,interrupted:a.interrupted||i.interrupted})}else this.messages.push(i)}processWebRtcTextMessageEvent(e){const i=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(A.MESSAGE_STREAM_EVENT_RECEIVED,i),i.role){case ge.USER:this.processUserMessage(i);break;case ge.PERSONA:this.processPersonaMessage(i);break}i.endOfSpeech&&this.publicEventEmitter.emit(A.MESSAGE_HISTORY_UPDATED,this.messages)}}class Cr{constructor(){this.listeners={}}addListener(e,i){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(i)}removeListener(e,i){this.listeners[e]&&this.listeners[e].delete(i)}emit(e,...i){if(e===A.CONNECTION_ESTABLISHED&&Me(le.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===A.CONNECTION_CLOSED){const[n,a]=i;Me(le.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,n,a?{details:a}:void 0)}this.listeners[e]&&this.listeners[e].forEach(n=>{n(...i)})}}var Z;(function(t){t[t.UNSTARTED=0]="UNSTARTED",t[t.STREAMING=1]="STREAMING",t[t.INTERRUPTED=2]="INTERRUPTED",t[t.ENDED=3]="ENDED"})(Z||(Z={}));var Nt=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(c){c(s)})}return new(i||(i=Promise))(function(s,c){function l(f){try{p(n.next(f))}catch(u){c(u)}}function m(f){try{p(n.throw(f))}catch(u){c(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};class Sr{constructor(e,i,n){this.state=Z.UNSTARTED,this.correlationId=e,this.internalEventEmitter=i,this.signallingClient=n,this.internalEventEmitter.addListener(U.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(U.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Nt(this,void 0,void 0,function*(){e.actionType===J.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=Z.INTERRUPTED,this.onDeactivate())})}endMessage(){return Nt(this,void 0,void 0,function*(){if(this.state===Z.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==Z.STREAMING){console.warn("Talk stream is not in an active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=Z.ENDED,this.onDeactivate()})}streamMessageChunk(e,i){return Nt(this,void 0,void 0,function*(){if(this.state!==Z.STREAMING&&this.state!==Z.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const n={content:e,startOfSpeech:this.state===Z.UNSTARTED,endOfSpeech:i,correlationId:this.correlationId};this.state=i?Z.ENDED:Z.STREAMING,this.state===Z.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(n)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===Z.STREAMING||this.state===Z.UNSTARTED}getState(){return this.state}}var kt=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(c){c(s)})}return new(i||(i=Promise))(function(s,c){function l(f){try{p(n.next(f))}catch(u){c(u)}}function m(f){try{p(n.throw(f))}catch(u){c(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};const Ji=(t,e)=>{if(isNaN(t)||isNaN(e))return 0;const i=e-t;return i>0?i:0};class Xi{constructor(e,i){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.failedCalls=Object.create(null),this.activeSessionId=null,this.publicEventEmitter=e,this.internalEventEmitter=i}setActiveSession(e){this.activeSessionId=e,this.clearPendingCalls(),this.clearFailedCalls()}clearSessionState(){this.activeSessionId=null,this.clearPendingCalls(),this.clearFailedCalls()}clearPendingCalls(){this.pendingCalls=Object.create(null)}clearFailedCalls(){this.failedCalls=Object.create(null)}registerHandler(e,i){return this.handlers[e]=i,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return kt(this,void 0,void 0,function*(){if(this.activeSessionId!==e.session_id)return;const{tool_name:i,timestamp:n}=e,a=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),s=new Date(n);if(this.pendingCalls[e.tool_call_id]={payload:a,timestamp:s.getTime()},!(i in this.handlers))return;const c=this.handlers[i];if(c.onStart)try{let l=yield c.onStart(a);if(e.tool_type==="client"){this.sendToolResult({sessionId:e.session_id,toolCallId:e.tool_call_id,userActionCorrelationId:e.user_action_correlation_id,timestampUserAction:e.timestamp_user_action,result:l??void 0,errorMessage:void 0}),yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:l,timestamp:new Date().toISOString()}));return}}catch(l){const m=l instanceof Error?l.message:String(l);e.tool_type==="client"&&this.sendToolResult({sessionId:e.session_id,toolCallId:e.tool_call_id,userActionCorrelationId:e.user_action_correlation_id,timestampUserAction:e.timestamp_user_action,result:void 0,errorMessage:`Error in handler: ${m}`}),yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${m}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return kt(this,void 0,void 0,function*(){const{tool_name:i,tool_call_id:n,timestamp:a}=e;if(this.activeSessionId!==e.session_id)return;if(n in this.failedCalls){delete this.failedCalls[n];return}const s=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(n in this.pendingCalls&&delete this.pendingCalls[n],!(i in this.handlers))return;const c=this.handlers[i];if(c.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(A.TOOL_CALL_COMPLETED,s);try{yield c.onComplete(s)}catch(l){console.error(`Error in onComplete handler for tool ${i}:`,l);return}}})}processToolCallFailedEvent(e){return kt(this,void 0,void 0,function*(){const{tool_name:i,tool_call_id:n,timestamp:a}=e;if(this.activeSessionId!==e.session_id)return;const s=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(this.failedCalls[n]=s,n in this.pendingCalls&&delete this.pendingCalls[n],!(i in this.handlers))return;const c=this.handlers[i];if(c.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(A.TOOL_CALL_FAILED,s);try{yield c.onFail(s)}catch(l){console.error(`Error in onFail handler for tool ${i}:`,l);return}}})}sendToolResult(e){const i={sessionId:e.sessionId,toolCallId:e.toolCallId,result:e.result,errorMessage:e.errorMessage,userActionCorrelationId:e.userActionCorrelationId,timestampUserAction:e.timestampUserAction};this.internalEventEmitter.emit(U.TOOL_CALL_RESULT_READY,i)}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const i=new Date(e.timestamp),n=this.pendingCalls[e.tool_call_id],a=n?Ji(n.timestamp,i.getTime()):0;return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:a>0?a:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const i=new Date(e.timestamp),n=this.pendingCalls[e.tool_call_id],a=n?Ji(n.timestamp,i.getTime()):0;return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:a>0?a:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var X=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(c){c(s)})}return new(i||(i=Promise))(function(s,c){function l(f){try{p(n.next(f))}catch(u){c(u)}}function m(f){try{p(n.throw(f))}catch(u){c(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};const Lt=15e3,yr=5e3,Zi=2,Tr=3,Ir=2e3,Mt=3e3,br=5e3;class wr{constructor(e,i,n,a,s,c){var l,m,p,f;this.peerConnection=null,this.connectionEstablishedEmitted=!1,this.iceRestartInProgress=!1,this.iceRestartAttempts=0,this.iceRestartAwaitedAnswer=!1,this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,this.iceRestartStopped=!1,this.iceDisconnectedGraceTimer=null,this.iceRestartWatchdogTimer=null,this.pendingWsOpenListener=null,this.pendingWsOpenTimeout=null,this.pendingWsOpenReject=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.iceRestartCandidateBuffer=null,this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:me.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.firstLocalIceCandidateSent=!1,this.firstRemoteIceCandidateReceived=!1,this.firstRemoteIceCandidateApplied=!1,this.connectionEstablishedMilestoneRecorded=!1,this.publicEventEmitter=n,this.internalEventEmitter=a,this.toolCallManager=s,this.connectionMilestones=c,this.apiGatewayConfig=i.apiGateway;const{inputAudio:u}=i;this.inputAudioState=u.inputAudioState,i.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=i.inputAudio.userProvidedMediaStream),this.disableInputAudio=i.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(U.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(U.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(U.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(U.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(U.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(U.TOOL_CALL_RESULT_READY,this.onToolCallResultReceived.bind(this)),this.iceServers=i.iceServers,this.iceTransportPolicy=i.iceTransportPolicy,this.rtcConfiguration=i.rtcConfiguration,this.signallingClient=new dr(e,i.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig,this.connectionMilestones),this.engineApiRestClient=new gr(i.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=i.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(m=(l=i.metrics)===null||l===void 0?void 0:l.showPeerConnectionStatsReport)!==null&&m!==void 0?m:!1,this.peerConnectionStatsReportOutputFormat=(f=(p=i.metrics)===null||p===void 0?void 0:p.peerConnectionStatsReportOutputFormat)!==null&&f!==void 0?f:"console"}onInputAudioStateChange(e,i){e.isMuted!==i.isMuted&&(i.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(i=>{i.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(i=>{i.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>X(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),yr))}sendClientSideMetrics(e){e.forEach(i=>{if(i.type==="inbound-rtp"){const n={message_type:"remote_rtp_stats",data:i};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(n))}})}recordSessionSuccess(e){var i,n;this.successMetricFired||(this.successMetricFired=!0,(i=this.connectionMilestones)===null||i===void 0||i.record("first_video_frame",{detectionMethod:e}),(n=this.connectionMilestones)===null||n===void 0||n.recordSessionSuccess({detectionMethod:e}),Me(le.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:e}))}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{var i,n;this.successMetricPoller&&((i=this.connectionMilestones)===null||i===void 0||i.record("first_video_frame_timeout",{timeoutMs:Lt}),(n=this.connectionMilestones)===null||n===void 0||n.publishFailure({failureStage:"first_video_frame",timeoutMs:Lt}),console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Lt);this.successMetricPoller=setInterval(()=>X(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const i=yield this.peerConnection.getStats();let n=!1,a=null;i.forEach(s=>{s.type==="inbound-rtp"&&s.kind==="video"&&(s.framesDecoded!==void 0&&s.framesDecoded>0?(n=!0,a="framesDecoded"):s.framesReceived!==void 0&&s.framesReceived>0?(n=!0,a="framesReceived"):s.bytesReceived>0&&s.packetsReceived>0&&s.bytesReceived>1e5&&(n=!0,a="bytesReceived"))}),n&&!this.successMetricFired&&(this.recordSessionSuccess(a??"unknown"),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,i=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=i,this.onInputAudioStateChange(e,i),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,i=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=i,this.onInputAudioStateChange(e,i),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const i=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(a=>{a.stop()});const n={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:n}),this.audioDeviceId=e,yield this.setupAudioTrack(),i&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(A.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(n){throw console.error("Failed to change audio input device:",n),new Error(`StreamingClient - changeAudioInputDevice: ${n instanceof Error?n.message:String(n)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}onToolCallResultReceived(e){const i={session_id:e.sessionId,message_type:"tool_result",tool_call_id:e.toolCallId,user_action_correlation_id:e.userActionCorrelationId,timestamp_user_action:e.timestampUserAction};e.result!==void 0&&(i.result=e.result),e.errorMessage&&(i.error=e.errorMessage),this.sendDataMessage(JSON.stringify(i))}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const i=document.getElementById(e);if(!i)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=i}}startConnection(){var e;try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.resetAttemptScopedMilestoneState(),(e=this.connectionMilestones)===null||e===void 0||e.record("connection_start_requested"),this.signallingClient.connect()}catch(i){console.error("StreamingClient - startConnection: error",i),this.handleWebrtcFailure(i)}}resetAttemptScopedMilestoneState(){this.firstLocalIceCandidateSent=!1,this.firstRemoteIceCandidateReceived=!1,this.firstRemoteIceCandidateApplied=!1,this.connectionEstablishedMilestoneRecorded=!1}stopConnection(){return X(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Sr(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new sr(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return X(this,void 0,void 0,function*(){var e,i,n,a,s,c,l,m,p,f;(e=this.connectionMilestones)===null||e===void 0||e.record("peer_connection_creating"),this.peerConnection=new RTCPeerConnection(Object.assign(Object.assign({iceCandidatePoolSize:Zi},this.rtcConfiguration),{iceTransportPolicy:(a=(n=(i=this.rtcConfiguration)===null||i===void 0?void 0:i.iceTransportPolicy)!==null&&n!==void 0?n:this.iceTransportPolicy)!==null&&a!==void 0?a:void 0,iceServers:this.iceServers})),(s=this.connectionMilestones)===null||s===void 0||s.record("peer_connection_created",{iceCandidatePoolSize:Zi,iceServerCount:this.iceServers.length,iceTransportPolicy:(m=(l=(c=this.rtcConfiguration)===null||c===void 0?void 0:c.iceTransportPolicy)!==null&&l!==void 0?l:this.iceTransportPolicy)!==null&&m!==void 0?m:"all"}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?((p=this.connectionMilestones)===null||p===void 0||p.record("microphone_permission_skipped",{reason:"input_audio_disabled"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?((f=this.connectionMilestones)===null||f===void 0||f.record("input_audio_stream_provided",{audioTrackCount:this.inputAudioStream.getAudioTracks().length}),yield this.setupAudioTrack()):this.requestMicrophonePermissionAsync().catch(u=>{console.error("Async microphone permission request failed:",u)}))})}onSignalMessage(e){return X(this,void 0,void 0,function*(){var i,n,a,s;if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case J.ANSWER:{(i=this.connectionMilestones)===null||i===void 0||i.record("answer_received");const f=e.payload;if(this.peerConnection.signalingState!=="have-local-offer")break;try{yield this.peerConnection.setRemoteDescription(f)}catch(u){console.error("StreamingClient - setRemoteDescription(answer) failed",u),!this.connectionEstablishedEmitted&&!this.isAwaitingRestartAnswer()&&this.handleWebrtcFailure(u);break}(n=this.connectionMilestones)===null||n===void 0||n.record("remote_description_set"),this.connectionReceivedAnswer=!0,this.onAnswerAccepted(),yield this.flushRemoteIceCandidateBuffer();break}case J.ICE_CANDIDATE:{const f=e.payload,u=new RTCIceCandidate(f);this.firstRemoteIceCandidateReceived||(this.firstRemoteIceCandidateReceived=!0,(a=this.connectionMilestones)===null||a===void 0||a.record("first_remote_ice_candidate_received",Dt(u))),this.connectionReceivedAnswer?yield this.addRemoteIceCandidate(u):this.remoteIceCandidateBuffer.push(u);break}case J.END_SESSION:const c=e.payload;this.sendIceRestartMetric("aborted"),(s=this.connectionMilestones)===null||s===void 0||s.publishFailure({failureStage:"server_closed_connection"}),this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.SERVER_CLOSED_CONNECTION,c),this.shutdown();break;case J.WARNING:const l=e.payload;console.warn("Warning received from server: "+l),this.publicEventEmitter.emit(A.SERVER_WARNING,l);break;case J.TALK_STREAM_INTERRUPTED:const m=e.payload;this.publicEventEmitter.emit(A.TALK_STREAM_INTERRUPTED,m.correlationId);break;case J.SESSION_READY:const p=e.sessionId;this.publicEventEmitter.emit(A.SESSION_READY,p);break;case J.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your @anam-ai/js-sdk version up to date?",e)}})}onSignallingClientConnected(){return X(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){return X(this,void 0,void 0,function*(){const e=[...this.remoteIceCandidateBuffer];this.remoteIceCandidateBuffer=[];for(const i of e)yield this.addRemoteIceCandidate(i)})}addRemoteIceCandidate(e){return X(this,void 0,void 0,function*(){if(this.peerConnection)try{yield this.peerConnection.addIceCandidate(e),this.recordFirstRemoteIceCandidateApplied(e)}catch(i){console.warn("StreamingClient - addRemoteIceCandidate: failed to add remote ICE candidate",i)}})}recordFirstRemoteIceCandidateApplied(e){var i;this.firstRemoteIceCandidateApplied||(this.firstRemoteIceCandidateApplied=!0,(i=this.connectionMilestones)===null||i===void 0||i.record("first_remote_ice_candidate_applied",Dt(e)))}onIceCandidate(e){var i,n;if(e.candidate){if(this.firstLocalIceCandidateSent||(this.firstLocalIceCandidateSent=!0,(i=this.connectionMilestones)===null||i===void 0||i.record("first_local_ice_candidate_sent",Dt(e.candidate))),this.iceRestartCandidateBuffer){this.iceRestartCandidateBuffer.push(e.candidate);return}this.signallingClient.sendIceCandidate(e.candidate)}else(n=this.connectionMilestones)===null||n===void 0||n.record("ice_gathering_complete")}onIceConnectionStateChange(){var e,i,n;const a=(e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState;switch(a&&((i=this.connectionMilestones)===null||i===void 0||i.record("ice_connection_state_changed",{iceConnectionState:a})),a){case"connected":case"completed":this.clearIceDisconnectedGraceTimer(),this.clearIceRestartWatchdog(),this.iceRestartInProgress=!1,this.sendIceRestartMetric("recovered"),this.iceRestartAttempts=0,this.signallingClient.endIceRestartReconnect(),this.connectionEstablishedMilestoneRecorded||(this.connectionEstablishedMilestoneRecorded=!0,(n=this.connectionMilestones)===null||n===void 0||n.record("client_connection_established",{iceConnectionState:a})),this.connectionEstablishedEmitted||(this.connectionEstablishedEmitted=!0,this.publicEventEmitter.emit(A.CONNECTION_ESTABLISHED)),this.startStatsCollection();break;case"disconnected":this.scheduleIceRestartAfterGrace();break;case"failed":this.clearIceDisconnectedGraceTimer(),this.restartIce();break}}clearIceDisconnectedGraceTimer(){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null)}clearIceRestartWatchdog(){this.iceRestartWatchdogTimer&&(clearTimeout(this.iceRestartWatchdogTimer),this.iceRestartWatchdogTimer=null)}sendIceRestartMetric(e){var i;if(this.iceRestartEpisodeStartMs===null)return;const n=Math.round(performance.now()-this.iceRestartEpisodeStartMs),a=(i=this.iceRestartEpisodeTrigger)!==null&&i!==void 0?i:"unknown";this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,Me(le.CLIENT_METRIC_MEASUREMENT_ICE_RESTART,n,{outcome:e,attempts:this.iceRestartAttempts,trigger:a})}isAwaitingRestartAnswer(){return this.iceRestartInProgress||this.iceRestartAwaitedAnswer||this.iceRestartWatchdogTimer!==null}onAnswerAccepted(){var e;const i=this.isAwaitingRestartAnswer();if(this.clearIceRestartWatchdog(),this.iceRestartAwaitedAnswer=!1,!i)return;this.iceRestartInProgress=!1;const n=(e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState;(n==="disconnected"||n==="failed")&&this.scheduleIceRestartAfterGrace()}clearPendingWsOpenWait(){this.pendingWsOpenTimeout&&(clearTimeout(this.pendingWsOpenTimeout),this.pendingWsOpenTimeout=null),this.pendingWsOpenListener&&(this.internalEventEmitter.removeListener(U.WEB_SOCKET_OPEN,this.pendingWsOpenListener),this.pendingWsOpenListener=null),this.pendingWsOpenReject=null}cancelIceRestart(){this.clearIceDisconnectedGraceTimer(),this.clearIceRestartWatchdog();const e=this.pendingWsOpenReject;this.clearPendingWsOpenWait(),e&&e(new Error("ice restart cancelled")),this.iceRestartCandidateBuffer=null,this.iceRestartInProgress=!1,this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,this.signallingClient.endIceRestartReconnect()}flushIceRestartCandidateBuffer(){const e=this.iceRestartCandidateBuffer;if(this.iceRestartCandidateBuffer=null,!!e)for(const i of e)this.signallingClient.sendIceCandidate(i)}scheduleIceRestartAfterGrace(){this.iceRestartStopped||this.iceRestartInProgress||this.iceDisconnectedGraceTimer||(this.iceDisconnectedGraceTimer=setTimeout(()=>{var e;if(this.iceDisconnectedGraceTimer=null,this.iceRestartStopped)return;const i=(e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState;(i==="disconnected"||i==="failed")&&this.restartIce()},Ir))}ensureSignallingConnected(){return this.signallingClient.isConnected()?Promise.resolve():this.signallingClient.isPermanentlyClosed()?Promise.reject(new Error("signalling permanently closed")):new Promise((e,i)=>{this.pendingWsOpenReject=i,this.pendingWsOpenTimeout=setTimeout(()=>{this.clearPendingWsOpenWait(),i(new Error("timed out waiting for signalling WebSocket"))},br);const n=()=>{this.clearPendingWsOpenWait(),e()};this.pendingWsOpenListener=n,this.internalEventEmitter.addListener(U.WEB_SOCKET_OPEN,n)})}restartIce(){return X(this,void 0,void 0,function*(){var e,i;if(!(!this.peerConnection||this.iceRestartInProgress||this.iceRestartStopped)){if(this.signallingClient.isPermanentlyClosed()){this.sendIceRestartMetric("aborted"),this.cancelIceRestart();return}if(this.iceRestartAttempts>=Tr){console.error("StreamingClient - restartIce: exhausted attempts"),(e=this.connectionMilestones)===null||e===void 0||e.publishFailure({failureStage:"ice_connection",iceConnectionState:(i=this.peerConnection)===null||i===void 0?void 0:i.iceConnectionState}),this.sendIceRestartMetric("exhausted"),this.cancelIceRestart(),this.handleWebrtcFailure("The connection to our servers was lost. Please try again.");return}this.iceRestartAttempts===0&&(this.iceRestartEpisodeStartMs=performance.now(),this.iceRestartEpisodeTrigger=this.peerConnection.iceConnectionState),this.iceRestartInProgress=!0,this.iceRestartAttempts+=1;try{if(this.peerConnection.signalingState!=="stable"&&(yield this.peerConnection.setLocalDescription({type:"rollback"})),this.iceRestartAttempts===1&&this.signallingClient.reconnectForIceRestart(),yield this.ensureSignallingConnected(),this.iceRestartStopped)return;const n=this.peerConnection.iceConnectionState;if(n==="connected"||n==="completed"){this.iceRestartInProgress=!1,this.sendIceRestartMetric("recovered"),this.signallingClient.endIceRestartReconnect();return}this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[];const a=yield this.peerConnection.createOffer({iceRestart:!0});if(this.iceRestartCandidateBuffer=[],yield this.peerConnection.setLocalDescription(a),!this.peerConnection.localDescription)throw new Error("null local description after ICE restart offer");yield this.signallingClient.sendOffer(this.peerConnection.localDescription),this.flushIceRestartCandidateBuffer(),this.iceRestartAwaitedAnswer=!1,this.clearIceRestartWatchdog(),this.iceRestartWatchdogTimer=setTimeout(()=>this.onIceRestartWatchdog(),Mt)}catch(n){if(this.iceRestartCandidateBuffer=null,console.error("StreamingClient - restartIce: error",n),this.iceRestartInProgress=!1,this.iceRestartStopped){this.cancelIceRestart();return}if(this.signallingClient.isPermanentlyClosed()){this.sendIceRestartMetric("aborted"),this.cancelIceRestart();return}this.clearIceRestartWatchdog(),this.iceRestartWatchdogTimer=setTimeout(()=>{this.iceRestartWatchdogTimer=null,this.restartIce()},Mt)}}})}onIceRestartWatchdog(){var e;if(this.iceRestartWatchdogTimer=null,this.iceRestartInProgress=!1,this.iceRestartStopped)return;const i=(e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState;if(!(i==="connected"||i==="completed")){if(!this.connectionReceivedAnswer&&!this.iceRestartAwaitedAnswer){this.iceRestartAwaitedAnswer=!0,this.iceRestartInProgress=!0,this.iceRestartWatchdogTimer=setTimeout(()=>this.onIceRestartWatchdog(),Mt);return}this.restartIce()}}onConnectionStateChange(){var e,i,n,a,s;const c=(e=this.peerConnection)===null||e===void 0?void 0:e.connectionState;if(c&&((i=this.connectionMilestones)===null||i===void 0||i.record("webrtc_connection_state_changed",{connectionState:c})),c==="failed"){const l=(n=this.peerConnection)===null||n===void 0?void 0:n.iceConnectionState;!this.iceRestartStopped&&(l==="disconnected"||l==="failed")||(a=this.connectionMilestones)===null||a===void 0||a.publishFailure({failureStage:"webrtc_connection",connectionState:c})}((s=this.peerConnection)===null||s===void 0?void 0:s.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){var i,n;(i=this.connectionMilestones)===null||i===void 0||i.record("webrtc_failure",Ke(e)),(n=this.connectionMilestones)===null||n===void 0||n.publishFailure(Object.assign({failureStage:"webrtc"},Ke(e))),console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.WEBRTC_FAILURE);try{this.stopConnection()}catch(a){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",a)}}onTrackEventHandler(e){var i,n;if(e.track.kind==="video"){if((i=this.connectionMilestones)===null||i===void 0||i.record("video_track_received"),this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(A.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const a=this.videoElement.requestVideoFrameCallback(()=>{var s;(s=this.videoElement)===null||s===void 0||s.cancelVideoFrameCallback(a),this.publicEventEmitter.emit(A.VIDEO_PLAY_STARTED),this.recordSessionSuccess("videoElement")})}}else e.track.kind==="audio"&&((n=this.connectionMilestones)===null||n===void 0||n.record("audio_track_received"),this.audioStream=e.streams[0],this.publicEventEmitter.emit(A.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return X(this,void 0,void 0,function*(){var e;if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const i=this.peerConnection.createDataChannel("session",{ordered:!0});(e=this.connectionMilestones)===null||e===void 0||e.record("data_channel_created"),i.onopen=()=>{var n;this.dataChannel=i??null,(n=this.connectionMilestones)===null||n===void 0||n.record("data_channel_open")},i.onclose=()=>{var n;(n=this.connectionMilestones)===null||n===void 0||n.record("data_channel_closed")},i.onmessage=n=>{var a,s,c,l,m,p;try{const f=JSON.parse(n.data);switch(f.messageType){case re.SPEECH_TEXT:this.internalEventEmitter.emit(U.WEBRTC_CHAT_MESSAGE_RECEIVED,f.data);break;case re.CLIENT_TOOL_EVENT:const u=f.data;this.internalEventEmitter.emit(U.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,u);const y=Xi.WebRTCClientToolEventToClientToolEvent(u);this.publicEventEmitter.emit(A.CLIENT_TOOL_EVENT_RECEIVED,y);break;case re.TOOL_CALL_STARTED_EVENT:const E=f.data;this.publicEventEmitter.emit(A.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(E)),this.internalEventEmitter.emit(U.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,E);break;case re.TOOL_CALL_COMPLETED_EVENT:const S=f.data;this.publicEventEmitter.emit(A.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(S)),this.internalEventEmitter.emit(U.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,S);break;case re.TOOL_CALL_FAILED_EVENT:const T=f.data;this.publicEventEmitter.emit(A.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(T)),this.internalEventEmitter.emit(U.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,T);break;case re.REASONING_TEXT:this.internalEventEmitter.emit(U.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,f.data);break;case re.USER_SPEECH_STARTED:this.publicEventEmitter.emit(A.USER_SPEECH_STARTED,(s=(a=f.data)===null||a===void 0?void 0:a.user_action_correlation_id)!==null&&s!==void 0?s:"unknown");break;case re.USER_SPEECH_ENDED:this.publicEventEmitter.emit(A.USER_SPEECH_ENDED,(l=(c=f.data)===null||c===void 0?void 0:c.user_action_correlation_id)!==null&&l!==void 0?l:"unknown");break;case re.DIRECTOR_NOTE_CUE_APPLIED:const I=f.data;this.publicEventEmitter.emit(A.DIRECTOR_NOTE_CUE_APPLIED,{cueTag:(m=I?.cue_tag)!==null&&m!==void 0?m:"unknown",correlationId:(p=I?.user_action_correlation_id)!==null&&p!==void 0?p:"unknown"});break;default:break}}catch(f){console.error("Failed to parse data channel message:",f)}}})}requestMicrophonePermissionAsync(){return X(this,void 0,void 0,function*(){var e,i,n;if(this.inputAudioState.permissionState!==me.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:me.PENDING}),(e=this.connectionMilestones)===null||e===void 0||e.record("microphone_permission_pending"),this.publicEventEmitter.emit(A.MIC_PERMISSION_PENDING);try{const a={echoCancellation:!0};this.audioDeviceId&&(a.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:a}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:me.GRANTED}),(i=this.connectionMilestones)===null||i===void 0||i.record("microphone_permission_granted"),this.publicEventEmitter.emit(A.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(a){console.error("Failed to get microphone permission:",a),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:me.DENIED}),(n=this.connectionMilestones)===null||n===void 0||n.record("microphone_permission_denied",Object.assign({},Ke(a)));const s=a instanceof Error?a.message:String(a);this.publicEventEmitter.emit(A.MIC_PERMISSION_DENIED,s)}}})}setupAudioTrack(){return X(this,void 0,void 0,function*(){var e;if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const i=this.inputAudioStream.getAudioTracks()[0],a=this.peerConnection.getSenders().find(s=>{var c;return((c=s.track)===null||c===void 0?void 0:c.kind)==="audio"||s.track===null&&s.dtmf!==null});if(a)try{yield a.replaceTrack(i)}catch(s){console.error("Failed to replace audio track:",s),this.peerConnection.addTrack(i,this.inputAudioStream)}else this.peerConnection.addTrack(i,this.inputAudioStream);(e=this.connectionMilestones)===null||e===void 0||e.record("input_audio_stream_started",{audioTrackCount:this.inputAudioStream.getAudioTracks().length}),this.publicEventEmitter.emit(A.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return X(this,void 0,void 0,function*(){var e,i,n,a,s,c;if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{(e=this.connectionMilestones)===null||e===void 0||e.record("offer_creation_started");const l=yield this.peerConnection.createOffer();(i=this.connectionMilestones)===null||i===void 0||i.record("offer_creation_completed"),yield this.peerConnection.setLocalDescription(l),(n=this.connectionMilestones)===null||n===void 0||n.record("local_description_set")}catch(l){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",l),(a=this.connectionMilestones)===null||a===void 0||a.record("offer_creation_failed",Object.assign({},Ke(l))),(s=this.connectionMilestones)===null||s===void 0||s.publishFailure(Object.assign({failureStage:"offer_creation"},Ke(l)))}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription),(c=this.connectionMilestones)===null||c===void 0||c.record("offer_sent")})}shutdown(){return X(this,void 0,void 0,function*(){var e;if(this.iceRestartStopped=!0,this.cancelIceRestart(),this.showPeerConnectionStatsReport){const i=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(i){const n=Qn(i,this.peerConnectionStatsReportOutputFormat);n&&console.log(n,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(i=>{i.stop()}),this.inputAudioStream=null}catch(i){console.error("StreamingClient - shutdown: error stopping input audio stream",i)}try{this.signallingClient.stop()}catch(i){console.error("StreamingClient - shutdown: error stopping signallilng",i)}try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(i){console.error("StreamingClient - shutdown: error closing peer connection",i)}})}}const Dt=t=>{const e=t;return Ut({candidateType:e.type,protocol:e.protocol,relayProtocol:e.relayProtocol,tcpType:e.tcpType,component:e.component})},Ke=t=>{if(t instanceof Error)return Ut({errorName:t.name});if(typeof t=="object"&&t!==null){const e=t;return Ut({errorName:typeof e.name=="string"?e.name:void 0,errorCode:typeof e.code=="string"||typeof e.code=="number"?e.code:void 0})}return{}},Ut=t=>{const e={};return Object.entries(t).forEach(([i,n])=>{n!==void 0&&(e[i]=n)}),e};class Rr{constructor(e,i){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=i,this.internalEventEmitter.addListener(U.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const i=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(A.REASONING_STREAM_EVENT_RECEIVED,i);const n={id:i.id,content:i.content,role:i.role},a=this.reasoning_messages.findIndex(s=>s.id===n.id);if(a!==-1){const s=this.reasoning_messages[a];s.content+=n.content,this.reasoning_messages[a]=s}else this.reasoning_messages.push(n);i.endOfThought&&this.publicEventEmitter.emit(A.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var ve=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(c){c(s)})}return new(i||(i=Promise))(function(s,c){function l(f){try{p(n.next(f))}catch(u){c(u)}}function m(f){try{p(n.throw(f))}catch(u){c(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};class Ar{constructor(e,i,n){var a,s,c,l,m;this.inputAudioState={isMuted:!1,permissionState:me.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const p=this.validateClientConfig(e,i,n);if(p)throw new $(p,q.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=i,this.clientOptions=n,(!((a=n?.api)===null||a===void 0)&&a.baseUrl||!((s=n?.api)===null||s===void 0)&&s.apiVersion)&&Kn(n.api.baseUrl||Vi,n.api.apiVersion||At),!((l=(c=n?.api)===null||c===void 0?void 0:c.apiGateway)===null||l===void 0)&&l.enabled&&Jn(n.api.apiGateway),!((m=n?.metrics)===null||m===void 0)&&m.disableClientMetrics&&Xn(!0),this.publicEventEmitter=new Cr,this.internalEventEmitter=new Er,this.toolCallManager=new Xi(this.publicEventEmitter,this.internalEventEmitter),this.apiClient=new hr(e,n?.apiKey,n?.api),this.messageHistoryClient=new vr(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Rr(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const i=e.split(".")[1],n=Wn.Buffer.from(i,"base64").toString("utf8");return JSON.parse(n)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,i,n){var a,s;if(!e&&!n?.apiKey)return"Either sessionToken or apiKey must be provided";if(n?.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const c=or((a=n?.api)===null||a===void 0?void 0:a.apiGateway);if(c)return c;if(e){const l=this.decodeJwt(e);this.organizationId=l.accountId,Ye({organizationId:this.organizationId});const m=(s=l.type)===null||s===void 0?void 0:s.toLowerCase();if(m==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((m==="ephemeral"||m==="stateful")&&i)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!i)return"Missing persona config. Persona configuration must be provided when using apiKey";if(n?.voiceDetection){if(n.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(n.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof n.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(n.voiceDetection.endOfSpeechSensitivity<0||n.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const i={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(i.voiceDetection=this.clientOptions.voiceDetection),Object.keys(i).length!==0)return i}startConnectionAttempt(){var e,i,n,a;const s=er();Ye({attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId});const c=new ir({context:{attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId},connectionMilestoneSampleRatio:(i=(e=this.clientOptions)===null||e===void 0?void 0:e.metrics)===null||i===void 0?void 0:i.connectionMilestoneSampleRatio,slowConnectionThresholdMs:(a=(n=this.clientOptions)===null||n===void 0?void 0:n.metrics)===null||a===void 0?void 0:a.slowConnectionThresholdMs});return Me(le.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),c}startSession(e,i){return ve(this,void 0,void 0,function*(){var n,a,s,c,l,m,p,f,u,y,E,S,T,I,w,b,O;const L=this.personaConfig,R=this.buildStartSessionOptionsForClient();i?.record("start_session_request_started");let Q;try{Q=yield this.apiClient.startSession(L,R),i?.record("start_session_request_completed")}catch(ne){throw i?.record("start_session_request_failed",Object.assign({},Ue(ne))),i?.publishFailure(Object.assign({failureStage:"start_session_request"},Ue(ne))),ne}const{sessionId:H,clientConfig:oe,engineHost:te,engineProtocol:se,signallingEndpoint:K}=Q,{heartbeatIntervalSeconds:ee,maxWsReconnectionAttempts:Ce,iceServers:Se,iceTransportPolicy:we}=oe;this.sessionId=H,this.toolCallManager.setActiveSession(H),Ye({sessionId:this.sessionId}),i?.updateContext({sessionId:this.sessionId,organizationId:this.organizationId});const Re=(l=(a=(n=this.clientOptions)===null||n===void 0?void 0:n.iceServers)!==null&&a!==void 0?a:(c=(s=this.clientOptions)===null||s===void 0?void 0:s.rtcConfiguration)===null||c===void 0?void 0:c.iceServers)!==null&&l!==void 0?l:Se;try{this.streamingClient=new wr(H,{engine:{baseUrl:`${se}://${te}`},signalling:{heartbeatIntervalSeconds:ee,maxWsReconnectionAttempts:Ce,url:{baseUrl:te,protocol:se,signallingPath:K}},iceServers:Re,iceTransportPolicy:we,rtcConfiguration:(m=this.clientOptions)===null||m===void 0?void 0:m.rtcConfiguration,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((p=this.clientOptions)===null||p===void 0)&&p.disableInputAudio?void 0:e,audioDeviceId:(f=this.clientOptions)===null||f===void 0?void 0:f.audioDeviceId,disableInputAudio:(u=this.clientOptions)===null||u===void 0?void 0:u.disableInputAudio},apiGateway:(E=(y=this.clientOptions)===null||y===void 0?void 0:y.api)===null||E===void 0?void 0:E.apiGateway,metrics:{showPeerConnectionStatsReport:(I=(T=(S=this.clientOptions)===null||S===void 0?void 0:S.metrics)===null||T===void 0?void 0:T.showPeerConnectionStatsReport)!==null&&I!==void 0?I:!1,peerConnectionStatsReportOutputFormat:(O=(b=(w=this.clientOptions)===null||w===void 0?void 0:w.metrics)===null||b===void 0?void 0:b.peerConnectionStatsReportOutputFormat)!==null&&O!==void 0?O:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager,i)}catch(ne){throw i?.publishFailure(Object.assign({failureStage:"streaming_client_initialization"},Ue(ne))),this.toolCallManager.clearSessionState(),Ye({sessionId:null}),new $("Failed to initialize streaming client",q.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:ne instanceof Error?ne.message:String(ne),sessionId:H})}return H})}startSessionIfNeeded(e,i){return ve(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e,i),!this.sessionId||!this.streamingClient))throw i?.publishFailure({failureStage:"start_session_validation"}),new $("Session ID or streaming client is not available after starting session",q.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return ve(this,void 0,void 0,function*(){var i;if(this._isStreaming)throw new Error("Already streaming");const n=this.startConnectionAttempt();!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&e&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(e,n)}catch(a){throw n.publishFailure(Object.assign({failureStage:"start_session"},Ue(a))),a}return this._isStreaming=!0,new Promise(a=>{var s;const c=[];let l=!1,m=!1;this.publicEventEmitter.addListener(A.VIDEO_STREAM_STARTED,p=>{c.push(p),l=!0,m&&a(c)}),this.publicEventEmitter.addListener(A.AUDIO_STREAM_STARTED,p=>{c.push(p),m=!0,l&&a(c)}),(s=this.streamingClient)===null||s===void 0||s.startConnection()})})}streamToVideoAndAudioElements(e,i,n){return ve(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,n)})}streamToVideoElement(e,i){return ve(this,void 0,void 0,function*(){var n;const a=this.startConnectionAttempt();!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio&&i&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(i,a)}catch(s){throw a.publishFailure(Object.assign({failureStage:"start_session"},Ue(s))),s instanceof $?s:new $("Failed to start session",q.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:s instanceof Error?s.message:String(s),sessionId:this.sessionId})}if(this._isStreaming)throw a.publishFailure({failureStage:"already_streaming"}),new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw a.publishFailure({failureStage:"streaming_client_missing"}),new Error("Failed to stream: streaming client is not available");try{this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()}catch(s){throw a.publishFailure(Object.assign({failureStage:"start_connection"},Ue(s))),s}})}talk(e){return ve(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const i=this.getActiveSessionId();if(!i)throw new Error("Failed to send user message: no active session");const n=new Date().toISOString().replace("Z",""),a=JSON.stringify({content:e,timestamp:n,session_id:i,message_type:"speech"});this.sendDataMessage(a)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const i=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(i)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const i=this.getActiveSessionId();if(!i)throw new Error("Failed to add context: no active session");const n=JSON.stringify({message_type:"context",session_id:i,content:e});this.sendDataMessage(n)}stopStreaming(){return ve(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.NORMAL),this.toolCallManager.clearSessionState(),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Ye({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,i;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,i;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return ve(this,void 0,void 0,function*(){var i;if(!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,i){this.publicEventEmitter.addListener(e,i)}removeListener(e,i){this.publicEventEmitter.removeListener(e,i)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,i){return this.toolCallManager.registerHandler(e,i)}}const Ue=t=>t instanceof $?{errorName:t.name,errorCode:t.code,httpStatusCode:t.statusCode}:t instanceof Error?{errorName:t.name}:{},Or=(t,e)=>new Ar(t,void 0,e),Qi=80;function xr(t){if(typeof t.url!="string"||!t.url.trim())return null;let e;try{e=new URL(t.url.trim())}catch{return null}if(e.protocol!=="https:"&&e.protocol!=="mailto:")return null;const i=e.protocol==="mailto:"?e.pathname:e.host;let n=typeof t.label=="string"?t.label.trim():"";return n||(n=i),n.length>Qi&&(n=`${n.slice(0,Qi-1)}…`),{url:e.href,label:n,host:i}}const en={anam_show_link:t=>{const e=xr(t);return e?{kind:"link",data:e}:null}};function tn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Nr(t,e,i){if(!Object.prototype.hasOwnProperty.call(en,t))return null;const n=en[t];let a;if(typeof i=="string"){let s;try{s=JSON.parse(i)}catch{return null}if(!tn(s))return null;a=s}else if(tn(i))a=i;else return null;try{const s=n(a);return s?{id:`tool-${e}`,...s}:null}catch{return null}}const kr=()=>C("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[C("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),C("path",{d:"M15 3h6v6"}),C("path",{d:"M10 14L21 3"})]}),Lr=({data:t})=>C("a",{class:"anam-transcript-block-link",href:t.url,target:"_blank",rel:"noopener noreferrer",children:[C("span",{class:"anam-transcript-block-link-text",children:[C("span",{class:"anam-transcript-block-link-label",children:t.label}),C("span",{class:"anam-transcript-block-link-host",children:t.host})]}),C(kr,{})]}),Mr={link:t=>C(Lr,{data:t})};function Dr(t){return Mr[t.kind](t.data)}const Y={SESSION_STARTED:"anam-agent:session-started",SESSION_ENDED:"anam-agent:session-ended",MESSAGE_RECEIVED:"anam-agent:message-received",MESSAGE_SENT:"anam-agent:message-sent",EXPANDED:"anam-agent:expanded",COLLAPSED:"anam-agent:collapsed",TRANSCRIPT_OPENED:"anam-agent:transcript-opened",TRANSCRIPT_CLOSED:"anam-agent:transcript-closed",ERROR:"anam-agent:error",MIC_MUTED:"anam-agent:mic-muted",MIC_UNMUTED:"anam-agent:mic-unmuted",TOOL_CALL_STARTED:"anam-agent:tool-call-started",TOOL_CALL_COMPLETED:"anam-agent:tool-call-completed",TOOL_CALL_FAILED:"anam-agent:tool-call-failed"},Ur="https://api.anam.ai";function nn(t){return/^[a-zA-Z0-9_-]{1,128}$/.test(t)}function rn(t){try{const e=t.split(".")[1];return JSON.parse(atob(e))}catch{return{}}}function Pr(t,e){return e===401||e===403?"This agent is not authorized. Check your agent ID.":e===404?"Agent not found. Check your agent ID.":e===429?"Too many requests. Please wait a moment.":e&&e>=500?"Server error. Please try again later.":t instanceof TypeError&&t.message==="Failed to fetch"?"Unable to connect. Check your network connection.":t instanceof Error&&t.message.length<80?t.message:"Something went wrong. Please try again."}function Br(){return{client:G(null),connectionStatus:G("idle"),isStreaming:G(!1),isMuted:G(!1),messages:G([]),messageTimes:new Map,pendingSent:[],messageSeq:new Map,seqCounter:0,localIdCounter:0,toolBlocks:G([]),seenToolCallIds:new Set,caption:G(null),captionTimer:null,sentCaption:G(null),sentCaptionTimer:null,error:G(null),sessionId:G(null),avatarThumbnailUrl:G(null),avatarVideoUrl:G(null),personaName:G(null),serverConfig:G(null),isConfigured:G(!1),isReady:G(!1),generation:0,prevMessageCount:0,dispatch:null}}function Fr(t,e){for(const n of e){if(t.messageSeq.has(n.id))continue;const a=n.role===ge.USER?t.pendingSent.findIndex(s=>s.content===n.content):-1;if(a>=0){const s=t.pendingSent[a];t.messageSeq.set(n.id,t.messageSeq.get(s.id));const c=t.messageTimes.get(s.id);c&&t.messageTimes.set(n.id,c),t.pendingSent.splice(a,1)}else t.messageSeq.set(n.id,t.seqCounter++)}const i=[...e,...t.pendingSent];return i.sort((n,a)=>t.messageSeq.get(n.id)-t.messageSeq.get(a.id)),i}function Pt(t){t.messages.value=[],t.messageTimes.clear(),t.pendingSent=[],t.messageSeq.clear(),t.toolBlocks.value=[],t.seenToolCallIds.clear(),t.prevMessageCount=0}async function $r(t,e,i){if(t.isReady.value=!1,!nn(e)){console.error("[AnamWidget] Invalid agent ID format:",e);return}try{const n=await fetch(`${i}/v1/personas/${e}/widget`);if(!n.ok){const s=n.status===404?"Agent not found. Check your agent ID.":n.status===401||n.status===403?"Not authorized. Check your agent ID.":"Server error. Please try again later.";console.error(`[AnamWidget] Failed to load widget config: ${s}`);return}const a=await n.json();t.avatarThumbnailUrl.value=a.persona?.avatarImageUrl||null,t.avatarVideoUrl.value=a.persona?.avatarVideoUrl||null,t.personaName.value=a.persona?.name||null,t.serverConfig.value=a.widgetConfig||null,t.isReady.value=!0}catch(n){console.error("[AnamWidget] Failed to load widget config:",n)}}async function Vr(t,e,i,n,a){if(t.connectionStatus.value==="connecting"||t.connectionStatus.value==="connected")return;const s=++t.generation;Pt(t),t.connectionStatus.value="connecting",t.error.value=null;let c;try{let l;if(a)l=a;else{if(!nn(e))throw new Error("Invalid agent ID format");const f=await fetch(`${i}/v1/auth/widget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:e})});if(s!==t.generation)return;if(c=f.status,!f.ok){const y=await f.json().catch(()=>({}));throw new Error(y.error||`HTTP ${f.status}`)}l=(await f.json()).sessionToken}if(s!==t.generation)return;const m=Or(l,{api:i?{baseUrl:i}:void 0,metrics:{disableClientMetrics:!0}});m.addListener(A.CONNECTION_ESTABLISHED,()=>{s===t.generation&&(t.connectionStatus.value="connected")}),m.addListener(A.VIDEO_STREAM_STARTED,()=>{s===t.generation&&(t.isStreaming.value=!0)}),m.addListener(A.AUDIO_STREAM_STARTED,()=>{}),m.addListener(A.MESSAGE_HISTORY_UPDATED,f=>{if(s!==t.generation)return;for(let E=t.prevMessageCount;E<f.length;E++){const S=f[E];t.dispatch?.(Y.MESSAGE_RECEIVED,{role:S.role==="persona"?"agent":"user",content:S.content})}t.prevMessageCount=f.length;const u=Fr(t,f),y=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});for(const E of u)t.messageTimes.has(E.id)||t.messageTimes.set(E.id,y);t.messages.value=u}),m.addListener(A.MESSAGE_STREAM_EVENT_RECEIVED,f=>{if(s!==t.generation)return;t.captionTimer&&(clearTimeout(t.captionTimer),t.captionTimer=null);const u=t.caption.value,y=f.role===ge.PERSONA&&u?.id===f.id?u.content+f.content:f.content;t.caption.value={id:f.id,role:f.role,content:y,at:Date.now()},f.endOfSpeech&&(t.captionTimer=window.setTimeout(()=>{t.caption.value=null,t.captionTimer=null},4e3))}),m.addListener(A.TOOL_CALL_STARTED,f=>{if(s!==t.generation)return;t.dispatch?.(Y.TOOL_CALL_STARTED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,arguments:f.arguments});const u=Nr(f.toolName,f.toolCallId,f.arguments);u&&!t.seenToolCallIds.has(f.toolCallId)&&(t.seenToolCallIds.add(f.toolCallId),t.messageSeq.set(u.id,t.seqCounter++),t.messageTimes.set(u.id,new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})),t.toolBlocks.value=[...t.toolBlocks.value,u])}),m.addListener(A.TOOL_CALL_COMPLETED,f=>{s===t.generation&&t.dispatch?.(Y.TOOL_CALL_COMPLETED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,result:f.result,executionTime:f.executionTime,documentsAccessed:f.documentsAccessed})}),m.addListener(A.TOOL_CALL_FAILED,f=>{s===t.generation&&t.dispatch?.(Y.TOOL_CALL_FAILED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,errorMessage:f.errorMessage,executionTime:f.executionTime})}),m.addListener(A.CONNECTION_CLOSED,(f,u)=>{if(s!==t.generation)return;const y=t.sessionId.value;t.connectionStatus.value="idle",t.isStreaming.value=!1,t.sessionId.value=null,t.dispatch?.(Y.SESSION_ENDED,{sessionId:y??"",reason:u??f})}),m.addListener(A.SESSION_READY,f=>{s===t.generation&&(t.sessionId.value=f,t.dispatch?.(Y.SESSION_STARTED,{sessionId:f}))});const p=await m.stream();if(s!==t.generation){try{await m.stopStreaming()}catch{}return}if(t.client.value=m,n&&p.length>0){const f=p.find(u=>u.getVideoTracks().length>0);f&&(n.srcObject=f)}}catch(l){if(s!==t.generation)return;console.error("[AnamWidget] Failed to start session:",l);const m=Pr(l,c);t.error.value=m,t.connectionStatus.value="error",t.client.value=null,t.dispatch?.(Y.ERROR,{code:c?`HTTP_${c}`:"SESSION_ERROR",message:m})}}async function Wr(t){const e=t.sessionId.value,i=t.connectionStatus.value!=="idle";if(t.generation++,t.client.value)try{await t.client.value.stopStreaming()}catch(n){console.error("[AnamWidget] Failed to stop session:",n)}t.client.value=null,t.connectionStatus.value="idle",t.isStreaming.value=!1,t.isMuted.value=!1,Pt(t),t.captionTimer&&clearTimeout(t.captionTimer),t.captionTimer=null,t.caption.value=null,t.sentCaptionTimer&&clearTimeout(t.sentCaptionTimer),t.sentCaptionTimer=null,t.sentCaption.value=null,t.sessionId.value=null,i&&t.dispatch?.(Y.SESSION_ENDED,{sessionId:e??"",reason:"USER_ENDED"})}function jr(t,e){if(!t.client.value||t.connectionStatus.value!=="connected")return;t.client.value.sendUserMessage(e);const i={id:`local-${t.localIdCounter++}`,content:e,role:ge.USER};t.messageSeq.set(i.id,t.seqCounter++),t.messageTimes.set(i.id,new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})),t.pendingSent.push(i),t.messages.value=[...t.messages.value,i],t.sentCaptionTimer&&clearTimeout(t.sentCaptionTimer),t.sentCaption.value={id:i.id,role:ge.USER,content:e,at:Date.now()},t.sentCaptionTimer=window.setTimeout(()=>{t.sentCaption.value=null,t.sentCaptionTimer=null},4e3),t.dispatch?.(Y.MESSAGE_SENT,{content:e})}function Gr(t){t.client.value&&(t.isMuted.value?(t.client.value.unmuteInputAudio(),t.isMuted.value=!1,t.dispatch?.(Y.MIC_UNMUTED,{})):(t.client.value.muteInputAudio(),t.isMuted.value=!0,t.dispatch?.(Y.MIC_MUTED,{})))}function Hr(t){t.generation++,t.client.value?.isStreaming()&&t.client.value.stopStreaming(),t.client.value=null,t.connectionStatus.value="idle",t.isStreaming.value=!1,t.isMuted.value=!1,Pt(t),t.captionTimer&&clearTimeout(t.captionTimer),t.captionTimer=null,t.caption.value=null,t.sentCaptionTimer&&clearTimeout(t.sentCaptionTimer),t.sentCaptionTimer=null,t.sentCaption.value=null,t.error.value=null,t.sessionId.value=null,t.avatarThumbnailUrl.value=null,t.avatarVideoUrl.value=null,t.personaName.value=null,t.serverConfig.value=null}function zr(t,e,i,n){const a=je();a.current||(a.current=Br());const s=a.current;s.dispatch=n??null;const c=t||(i?rn(i).personaId:void 0),l=!!c||!!i;s.isConfigured.value!==l&&(s.isConfigured.value=l);const m=e||Ur;return{connectionStatus:s.connectionStatus,isStreaming:s.isStreaming,isMuted:s.isMuted,messages:s.messages,messageTimes:s.messageTimes,messageSeq:s.messageSeq,toolBlocks:s.toolBlocks,caption:s.caption,sentCaption:s.sentCaption,error:s.error,sessionId:s.sessionId,isConfigured:s.isConfigured,isReady:s.isReady,avatarThumbnailUrl:s.avatarThumbnailUrl,avatarVideoUrl:s.avatarVideoUrl,personaName:s.personaName,serverConfig:s.serverConfig,fetchWidgetConfig:()=>{if(c){$r(s,c,m);return}if(i){const f=rn(i).widgetConfig;f&&(typeof f.personaName=="string"&&f.personaName&&(s.personaName.value=f.personaName),typeof f.avatarImageUrl=="string"&&f.avatarImageUrl&&(s.avatarThumbnailUrl.value=f.avatarImageUrl),typeof f.avatarVideoUrl=="string"&&f.avatarVideoUrl&&(s.avatarVideoUrl.value=f.avatarVideoUrl),f.removeWatermark===!0&&(s.serverConfig.value={removeWatermark:!0})),s.isReady.value=!0;return}s.isReady.value=!0},startSession:p=>!c&&!i?(s.error.value="No agent ID or session token configured",Promise.resolve()):Vr(s,c||"",m,p,i),stopSession:()=>Wr(s),sendMessage:p=>jr(s,p),toggleMute:()=>Gr(s),cleanup:()=>Hr(s)}}function qr(t,e,i){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:i}))}const Yr='@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-outline-style:solid}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.visible{visibility:visible}.block{display:block}.flex{display:flex}.inline{display:inline}.flex-shrink{flex-shrink:1}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}}:host{--anam-trigger-size:80px;--anam-sheet-width:400px;--anam-sheet-height:640px;all:initial;color:#18181b;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:DM Sans,system-ui,-apple-system,sans-serif;font-size:15px;line-height:1.5}@media(max-width:640px){:host{--anam-trigger-size:72px;--anam-sheet-width: calc(100vw - 24px) ;--anam-sheet-height: calc(100dvh - 100px) }}.anam-widget{z-index:9999;font-family:inherit}.anam-widget[data-layout=floating]{position:fixed}.anam-widget[data-layout=inline]{position:relative}.anam-trigger{width:var(--anam-trigger-size);height:var(--anam-trigger-size);cursor:pointer;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;padding:0;transition:all .25s cubic-bezier(.4,0,.2,1);display:flex;overflow:hidden;box-shadow:0 2px 8px #00000014,0 8px 24px -4px #0000002e}.anam-trigger:hover{transform:scale(1.06);box-shadow:0 4px 12px #0000001a,0 12px 32px -4px #00000040}.anam-trigger:active{transform:scale(.97)}.anam-trigger img{object-fit:cover;width:100%;height:100%;display:block}.anam-sheet{width:var(--anam-sheet-width);max-height:var(--anam-sheet-height);border-radius:8px;flex-direction:column;animation:.25s cubic-bezier(.16,1,.3,1) sheetIn;display:flex;position:relative;overflow:hidden;box-shadow:0 32px 64px -16px #00000040,0 0 0 1px #00000014}.anam-sheet[data-orientation=portrait]{flex-direction:row;align-items:stretch;width:auto}.anam-widget[data-layout=inline] .anam-sheet{border-radius:8px;width:100%;max-height:none;animation:none}@keyframes sheetIn{0%{opacity:0;transform:translateY(8px)scale(.97)}to{opacity:1;transform:translateY(0)scale(1)}}.anam-video-region{aspect-ratio:3/2;background:#000;flex:none;width:100%;position:relative;overflow:hidden}.anam-sheet[data-orientation=portrait] .anam-video-region{aspect-ratio:2/3;width:auto;height:min(540px,var(--anam-sheet-height))}.anam-sheet[data-orientation=landscape] .anam-video-region{z-index:1;box-shadow:0 4px 10px #00000029}.anam-video{object-fit:cover;background:#000;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-video[data-hidden=true]{visibility:hidden}.anam-overlay-idle{z-index:2;position:absolute;inset:0}.anam-overlay-idle img{object-fit:cover;width:100%;height:100%;display:block}.anam-preview-video{object-fit:cover;z-index:1;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-preview-fallback{z-index:0;position:absolute;inset:0}.anam-overlay-idle .anam-scrim{z-index:1}.anam-cta-pill{z-index:2;box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffeb;letter-spacing:-.01em;cursor:pointer;white-space:nowrap;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;justify-content:center;align-items:center;gap:10px;padding:12px 26px;font-family:inherit;font-size:17px;font-weight:600;transition:all .2s;display:flex;position:absolute;bottom:20px;left:50%;transform:translate(-50%);box-shadow:0 16px 38px #0000002e}.anam-cta-pill:hover{background:#ffffff29;transform:translate(-50%)scale(1.03)}.anam-cta-pill:active{transform:translate(-50%)scale(.98)}.anam-cta-pill svg{flex-shrink:0;transform:translateY(-1px)}.anam-overlay-unconfigured{z-index:2;background:#111;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-unconfigured span{color:#ffffff59;letter-spacing:-.01em;font-size:14px;font-weight:400}.anam-overlay-loading{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:20px;display:flex;position:absolute;inset:0}.anam-overlay-loading span{color:#fffc;letter-spacing:-.01em;font-size:15px;font-weight:400}.anam-overlay-error{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-error-text{color:#fff9;text-align:center;max-width:260px;font-size:14px;line-height:1.5}.anam-overlay-error .anam-retry-btn{box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffeb;cursor:pointer;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;padding:10px 24px;font-family:inherit;font-size:14px;font-weight:500;transition:background .15s;box-shadow:0 16px 38px #0000002e}.anam-overlay-error .anam-retry-btn:hover{background:#ffffff29}.anam-spinner{border:2.5px solid #ffffff1f;border-top-color:#fff;border-radius:50%;width:32px;height:32px;animation:.75s linear infinite spin}@keyframes spin{to{transform:rotate(360deg)}}.anam-close-btn{z-index:10;box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffbd;cursor:pointer;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:background .15s,color .15s;display:flex;position:absolute;top:12px;right:12px;box-shadow:0 16px 38px #0000002e}.anam-close-btn:hover{color:#ffffffeb;background:#ffffff24}.anam-scrim{z-index:8;pointer-events:none;background:linear-gradient(#0000,#00000040 40%,#0000008c);height:42%;position:absolute;bottom:0;left:0;right:0}.anam-captions{z-index:9;pointer-events:none;color:#fffffff2;letter-spacing:-.01em;text-shadow:0 1px 4px #00000073;-webkit-line-clamp:3;-webkit-box-orient:vertical;font-size:15px;line-height:1.4;display:-webkit-box;position:absolute;bottom:72px;left:18px;right:18px;overflow:hidden}.anam-captions-agent{text-align:left}.anam-captions-user{text-align:right}.anam-control-bar{z-index:10;background:0 0;justify-content:center;align-items:center;gap:10px;padding:0;display:flex;position:absolute;bottom:14px;left:14px;right:14px}.anam-ctl-btn{box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffbd;cursor:pointer;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;flex-shrink:0;justify-content:center;align-items:center;width:44px;height:44px;padding:0;transition:background .15s,color .15s;display:flex;box-shadow:0 16px 38px #0000002e}.anam-ctl-btn:hover{color:#ffffffeb;background:#ffffff24}.anam-ctl-btn:disabled{opacity:.38;cursor:not-allowed}.anam-ctl-input-wrap{flex:1;align-items:center;min-width:0;display:flex;position:relative}.anam-ctl-input{box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffeb;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;outline:none;width:100%;height:44px;padding:0 54px 0 18px;font-family:inherit;font-size:15px;transition:background .15s,border-color .15s;box-shadow:0 18px 42px #0000002e}.anam-ctl-input::placeholder{color:#fff6}.anam-ctl-input:focus{background:#ffffff24;border-color:#ffffff47}.anam-ctl-input:disabled{opacity:.38;cursor:not-allowed}.anam-ctl-send{color:#fff6;cursor:pointer;background:0 0;border:none;border-radius:999px;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:color .15s;display:flex;position:absolute;right:8px}.anam-ctl-send:not(:disabled){color:#ffffffbd}.anam-ctl-send:not(:disabled):hover{color:#ffffffeb}.anam-ctl-send:disabled{cursor:not-allowed;opacity:.38}@media(max-width:640px){.anam-control-bar{gap:8px}.anam-ctl-input{padding:0 50px 0 14px;font-size:16px}}.anam-transcript-pane{background:#f7f5f2;flex-direction:column;flex:none;height:0;transition:height .35s cubic-bezier(.32,.72,.33,1);display:flex;overflow:hidden}.anam-sheet[data-transcript=open] .anam-transcript-pane{height:min(320px,45dvh)}.anam-transcript-toggle svg{transition:transform .3s}.anam-sheet[data-transcript=open] .anam-transcript-toggle svg{transform:rotate(180deg)}.anam-transcript-rail{background:#f7f5f2;border-right:1px solid #eae5dd;flex:none;width:0;transition:width .35s cubic-bezier(.32,.72,.33,1);overflow:hidden}.anam-sheet[data-transcript=open] .anam-transcript-rail{width:300px}.anam-transcript-rail-inner{flex-direction:column;width:300px;height:100%;display:flex}.anam-transcript-head{border-bottom:1px solid #eae5dd;flex:none;justify-content:space-between;align-items:center;padding:14px 14px 10px 18px;display:flex}.anam-transcript-title{letter-spacing:.14em;text-transform:uppercase;color:#8a8378;font-size:10px;font-weight:700}.anam-transcript-collapse{color:#9a9285;cursor:pointer;background:0 0;border:none;padding:4px;transition:color .15s;display:flex}.anam-transcript-collapse:hover{color:#4a4239}.anam-transcript-tab{z-index:10;box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffbd;cursor:pointer;background:#ffffff1a;border:1.4px solid #ffffff38;border-left:none;border-radius:0 10px 10px 0;justify-content:center;align-items:center;width:24px;height:84px;padding:0;transition:background .15s;display:flex;position:absolute;top:50%;left:0;transform:translateY(-50%);box-shadow:0 16px 38px #0000002e}.anam-transcript-tab:hover{color:#ffffffeb;background:#ffffff24}.anam-transcript-rows{overscroll-behavior:contain;flex:1;min-height:0;padding:10px 18px 8px 22px;overflow-y:auto}.anam-transcript-empty{color:#b0a89b;padding:14px 0;font-size:12.5px}.anam-transcript-row{border-left:2px solid #e3ded6;padding:10px 0 10px 16px;position:relative}.anam-transcript-row:last-child{border-left-color:#ff6200}.anam-transcript-meta{align-items:baseline;gap:8px;margin-bottom:3px;display:flex}.anam-transcript-role{letter-spacing:.1em;text-transform:uppercase;color:#6b7280;font-size:9.5px;font-weight:700}.anam-transcript-row-agent .anam-transcript-role{color:#ff6200}.anam-transcript-time{color:#b4aca0;font-variant-numeric:tabular-nums;font-size:9.5px}.anam-transcript-text{color:#33383f;overflow-wrap:anywhere;font-size:12.5px;line-height:1.5}.anam-transcript-row-user .anam-transcript-text{color:#5a616b}.anam-transcript-block-link{color:#33383f;background:#fff;border:1px solid #e2dcd2;border-radius:10px;justify-content:space-between;align-items:center;gap:10px;margin-top:2px;padding:8px 12px;text-decoration:none;transition:border-color .15s,background .15s;display:flex}.anam-transcript-block-link:hover{background:#fffaf6;border-color:#ff6200}.anam-transcript-block-link-text{flex-direction:column;gap:1px;min-width:0;display:flex}.anam-transcript-block-link-label{color:#33383f;overflow-wrap:anywhere;font-size:12.5px;font-weight:600;line-height:1.4}.anam-transcript-block-link-host{color:#b4aca0;text-overflow:ellipsis;white-space:nowrap;font-size:9.5px;overflow:hidden}.anam-transcript-block-link svg{color:#b4aca0;flex:none}.anam-transcript-block-link:hover svg{color:#ff6200}.anam-transcript-footer{flex:none;padding:8px 12px 12px;display:flex}.anam-transcript-footer .anam-control-bar{width:100%;position:static}.anam-transcript-footer .anam-ctl-btn{-webkit-backdrop-filter:none;box-shadow:none;color:#6b6257;background:#fff;border:1px solid #e2dcd2}.anam-transcript-footer .anam-ctl-btn:hover{color:#4a4239;background:#faf8f5}.anam-transcript-footer .anam-ctl-input{-webkit-backdrop-filter:none;box-shadow:none;color:#33383f;background:#fff;border:1px solid #e2dcd2}.anam-transcript-footer .anam-ctl-input::placeholder{color:#b0a89b}.anam-transcript-footer .anam-ctl-input:focus{background:#fff;border-color:#d0c8ba}.anam-transcript-footer .anam-ctl-send,.anam-transcript-footer .anam-ctl-send:not(:disabled){color:#b0a89b}.anam-transcript-footer .anam-ctl-send:not(:disabled):hover{color:#4a4239}.anam-watermark{z-index:11;opacity:.5;line-height:0;text-decoration:none;transition:opacity .15s;position:absolute;top:16px;left:16px}.anam-watermark:hover{opacity:.8}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}';class Kr extends Oe{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.error("[AnamWidget] Render error:",e)}render(){return this.state.hasError?C("div",{class:"anam-overlay-error",children:C("div",{class:"anam-overlay-error-text",children:"Widget failed to load"})}):this.props.children}}function Bt(t,e){const i={...t};for(const n of Object.keys(e)){const a=e[n];a!==void 0&&(a!==null&&typeof a=="object"&&!Array.isArray(a)&&typeof i[n]=="object"&&i[n]!==null&&!Array.isArray(i[n])?i[n]=Bt(i[n],a):i[n]=a)}return i}function ct(t){if(t!==void 0)return t==="true"}function Jr(t){const e={};t.layout&&(e.layout=t.layout),t["initial-state"]&&(e.initialState=t["initial-state"]),t.position&&(e.position=t.position);const i=ct(t["ui-mute-button"]);i!==void 0&&(e.showMuteButton=i);const n=ct(t["ui-text-input"]);n!==void 0&&(e.showTextInput=n);const a=ct(t["ui-captions"]);a!==void 0&&(e.showCaptions=a);const s=ct(t["ui-transcript"]);return s!==void 0&&(e.showTranscript=s),t["call-to-action"]&&(e.callToAction=t["call-to-action"]),e}const Xr=()=>C("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"3","stroke-linecap":"round",children:C("path",{d:"M18 6L6 18M6 6l12 12"})}),Zr=()=>C("svg",{width:"24",height:"24",viewBox:"0 0 640 640",fill:"currentColor",children:C("path",{d:"M187.2 100.9C174.8 94.1 159.8 94.4 147.6 101.6C135.4 108.8 128 121.9 128 136L128 504C128 518.1 135.5 531.2 147.6 538.4C159.7 545.6 174.8 545.9 187.2 539.1L523.2 355.1C536 348.1 544 334.6 544 320C544 305.4 536 291.9 523.2 284.9L187.2 100.9z"})}),Qr=()=>C("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),C("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),C("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),eo=()=>C("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),C("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"}),C("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2c0 .87-.16 1.71-.46 2.49"}),C("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),to=()=>C("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),C("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),io=()=>C("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:C("path",{d:"M6 9l6 6 6-6"})}),no=()=>C("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",children:C("path",{d:"M15 18l-6-6 6-6"})}),ro=()=>C("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",children:C("path",{d:"M9 18l6-6-6-6"})}),Ft=()=>C("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",style:{opacity:.3},children:[C("circle",{cx:"24",cy:"18",r:"8",stroke:"white","stroke-width":"2",fill:"none"}),C("path",{d:"M8 42c0-8.837 7.163-16 16-16s16 7.163 16 16",stroke:"white","stroke-width":"2",fill:"none"})]});function on({session:t,agentLabel:e,rowsRef:i}){const n=t.messages.value,a=t.toolBlocks.value,s=[...n.map(c=>({seq:t.messageSeq.get(c.id)??0,type:"message",message:c})),...a.map(c=>({seq:t.messageSeq.get(c.id)??0,type:"block",block:c}))].sort((c,l)=>c.seq-l.seq);return C("div",{class:"anam-transcript-rows",ref:i,children:[s.length===0&&C("div",{class:"anam-transcript-empty",children:"Messages will appear here as you talk."}),s.map(c=>{if(c.type==="block")return C("div",{class:"anam-transcript-row anam-transcript-row-agent",children:[C("div",{class:"anam-transcript-meta",children:[C("span",{class:"anam-transcript-role",children:e}),C("span",{class:"anam-transcript-time",children:t.messageTimes.get(c.block.id)??""})]}),Dr(c.block)]},c.block.id);const l=c.message,m=l.role==="persona";return C("div",{class:`anam-transcript-row ${m?"anam-transcript-row-agent":"anam-transcript-row-user"}`,children:[C("div",{class:"anam-transcript-meta",children:[C("span",{class:"anam-transcript-role",children:m?e:"You"}),C("span",{class:"anam-transcript-time",children:t.messageTimes.get(l.id)??""})]}),C("div",{class:"anam-transcript-text",children:l.content})]},l.id)})]})}function oo({config:t,session:e,videoRef:i,avatarSrc:n,avatarVideoSrc:a,displayCta:s,agentName:c,onCollapse:l,onStop:m,dispatch:p}){const f=je(null),[u,y]=St(""),E=e.connectionStatus.value==="connected",S=e.connectionStatus.value==="connecting",T=e.connectionStatus.value==="error",I=e.isStreaming.value,w=!S&&!E&&!T,b=E||I,O=t.orientation??"landscape",L=t.showTranscript&&b,[R,Q]=St(!1),H=je(null),oe=c||"Agent",te=Ge(()=>{const W=!R;Q(W),p(W?Y.TRANSCRIPT_OPENED:Y.TRANSCRIPT_CLOSED,{})},[R,p]);Ie(()=>{b||Q(!1)},[b]);const se=e.toolBlocks.value.length;Ie(()=>{se>0&&b&&L&&!R&&(Q(!0),p(Y.TRANSCRIPT_OPENED,{}))},[se]),Ie(()=>{R&&H.current&&(H.current.scrollTop=H.current.scrollHeight)},[R]),Ie(()=>{const W=H.current;if(!W||!R)return;W.scrollHeight-W.scrollTop-W.clientHeight<160&&(W.scrollTop=W.scrollHeight)},[e.messages.value,e.toolBlocks.value,R]);const K=L&&R&&O==="landscape",ee=t.showCaptions?e.caption.value:null,Ce=e.sentCaption.value,Se=ee&&Ce?ee.at>=Ce.at?ee:Ce:ee??Ce,we=Ge(async()=>{i.current&&await e.startSession(i.current)},[e.startSession]),Re=Ge(()=>{u.trim()&&(e.sendMessage(u.trim()),y(""),f.current?.focus())},[u]),ne=Ge(W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),Re())},[Re]),Vt=t.showTextInput?C("div",{class:"anam-ctl-input-wrap",children:[C("input",{ref:f,type:"text",class:"anam-ctl-input",placeholder:"Type a message...",value:u,onInput:W=>y(W.target.value),onKeyDown:ne,disabled:!E}),C("button",{class:"anam-ctl-send",onClick:Re,disabled:!E||!u.trim(),"aria-label":"Send message",children:C(to,{})})]}):null,dt=C("div",{class:"anam-control-bar",children:[t.showMuteButton&&C("button",{class:`anam-ctl-btn ${e.isMuted.value?"anam-ctl-btn-muted":""}`,onClick:()=>e.toggleMute(),"aria-label":e.isMuted.value?"Unmute":"Mute",children:e.isMuted.value?C(eo,{}):C(Qr,{})}),Vt,L&&O==="landscape"&&C("button",{class:"anam-ctl-btn anam-transcript-toggle",onClick:te,"aria-expanded":R,"aria-label":R?"Hide transcript":"Show transcript",children:C(io,{})})]});return C("div",{class:"anam-sheet","data-orientation":O,"data-transcript":R?"open":"closed",children:[L&&O==="portrait"&&C("div",{class:"anam-transcript-rail",children:C("div",{class:"anam-transcript-rail-inner",children:[C("div",{class:"anam-transcript-head",children:[C("span",{class:"anam-transcript-title",children:"Transcript"}),C("button",{class:"anam-transcript-collapse",onClick:te,"aria-label":"Hide transcript",children:C(no,{})})]}),C(on,{session:e,agentLabel:oe,rowsRef:H})]})}),C("div",{class:"anam-video-region",children:[C("video",{ref:i,class:"anam-video",autoplay:!0,playsinline:!0,"data-hidden":I?void 0:"true"}),w&&(e.isConfigured.value?C("div",{class:"anam-overlay-idle",children:[a?C("video",{src:a,autoplay:!0,loop:!0,muted:!0,playsinline:!0,class:"anam-preview-video",onError:W=>{W.target.style.display="none"}}):null,n?C("img",{src:n,alt:"Avatar",class:a?"anam-preview-fallback":void 0}):C(Ft,{}),C("div",{class:"anam-scrim"}),C("button",{class:"anam-cta-pill",onClick:we,children:[C(Zr,{}),s]})]}):C("div",{class:"anam-overlay-unconfigured",children:[C(Ft,{}),C("span",{children:"Agent not configured"})]})),S&&C("div",{class:"anam-overlay-loading",children:[C("span",{class:"anam-spinner"}),C("span",{children:"Starting your conversation..."})]}),T&&C("div",{class:"anam-overlay-error",children:[C("div",{class:"anam-overlay-error-text",children:e.error.value||"Something went wrong"}),C("button",{class:"anam-retry-btn",onClick:we,children:"Try Again"})]}),(l||m&&(E||S||I))&&C("button",{class:"anam-close-btn",onClick:l||m,"aria-label":l?"Close":"End call",children:C(Xr,{})}),b&&C(he,{children:[C("div",{class:"anam-scrim"}),Se&&C("div",{class:`anam-captions ${Se.role==="persona"?"anam-captions-agent":"anam-captions-user"}`,children:Se.content}),!K&&dt,L&&O==="portrait"&&!R&&C("button",{class:"anam-transcript-tab",onClick:te,"aria-label":"Show transcript",children:C(ro,{})})]}),!t.removeWatermark&&C("a",{class:"anam-watermark",href:"https://anam.ai",target:"_blank",rel:"noopener noreferrer",children:C("svg",{width:"48",height:"16",viewBox:"0 0 86 29",fill:"white",xmlns:"http://www.w3.org/2000/svg",children:[C("path",{d:"M18.1491 28.1986L16.2127 21.63L6.3408 21.63L4.40439 28.1986H0L9.03659 -1.79687L13.4789 -1.79687L22.5535 28.1986H18.1491ZM7.47986 17.8331L15.0736 17.8331L11.2767 4.96161L7.47986 17.8331Z"}),C("path",{d:"M24.7666 28.1984L24.7666 7.69518L39.5745 7.69518V28.1984L35.3979 28.1984V11.4921L28.9432 11.4921L28.9432 28.1984H24.7666Z"}),C("path",{d:"M61.0239 28.1984V7.69518L85.7037 7.69518V28.1984H81.5271V11.4921L75.4521 11.4921V28.1984L71.2755 28.1984V11.4921L65.2005 11.4921V28.1984H61.0239Z"}),C("path",{d:"M42.8948 7.69518L57.7026 7.69518V28.1984L53.5261 28.1984V27.1353C52.4629 28.0466 51.0201 28.5781 49.3495 28.5781C45.4007 28.5781 42.8948 25.7305 42.8948 21.2501C42.8948 16.8457 45.4007 14.074 49.3495 14.074C51.0201 14.074 52.4629 14.5676 53.5261 15.4788V11.3022L42.8948 11.3022V7.69518ZM50.4885 24.7812C52.6148 24.7812 53.9437 23.4143 53.9057 21.2501C53.8678 19.0859 52.5389 17.681 50.4885 17.681C48.4003 17.681 47.0713 19.0859 47.0713 21.2501C47.0713 23.4143 48.4003 24.7812 50.4885 24.7812Z"})]})})]}),L&&O==="landscape"&&C("div",{class:"anam-transcript-pane",children:[C(on,{session:e,agentLabel:oe,rowsRef:H}),K&&C("div",{class:"anam-transcript-footer",children:dt})]})]})}function so(t){return C(he,{children:[C("style",{children:Yr}),C(Kr,{children:C(ao,{...t})})]})}function ao(t){const e=je(null),i=je(null),n=Ge((O,L)=>{const R=i.current?.getRootNode();R&&R instanceof ShadowRoot&&qr(R.host,O,L)},[]);t["agent-id"]&&t["session-token"]&&console.warn("[AnamWidget] Both agent-id and session-token are set. Use one or the other. Ignoring agent-id.");const a=t["session-token"]?void 0:t["agent-id"],s=zr(a,t["api-base-url"],t["session-token"],n);Ie(()=>()=>{s.cleanup()},[]);const c=Ne(()=>Jr(t),[t.layout,t["initial-state"],t.position,t["ui-mute-button"],t["ui-text-input"],t["ui-captions"],t["ui-transcript"],t["call-to-action"]]),l=Ne(()=>{const O=s.serverConfig.value;return Bt(Bt({...wt},O??{}),c)},[s.serverConfig.value,c]),m=Mi(l.layout==="floating"?l.initialState:"expanded");Ie(()=>{l.layout==="inline"?m.value="expanded":m.value=l.initialState},[l.layout,l.initialState]),Ie(()=>{s.fetchWidgetConfig()},[a,t["api-base-url"],t["session-token"]]);const p=t["avatar-url"]||s.avatarThumbnailUrl.value||null,f=t["avatar-video-url"]||s.avatarVideoUrl.value||null,y=t["agent-name"]||s.personaName.value,E=l.callToAction===wt.callToAction&&y?`Talk to ${y}`:l.callToAction,S=Ne(()=>{if(l.layout==="inline")return"";const O=Bn(l.position);return Object.entries(O).map(([L,R])=>`${L}: ${R}`).join("; ")},[l.layout,l.position]),T=l.layout==="floating",I=()=>{m.value="expanded",n(Y.EXPANDED,{})},w=async()=>{s.connectionStatus.value!=="idle"&&await s.stopSession(),m.value="minimized",n(Y.COLLAPSED,{})},b=T?m.value==="expanded":!0;return s.isReady.value?C("div",{ref:i,class:"anam-widget","data-layout":l.layout,"data-state":m.value,style:S,children:[T&&m.value==="minimized"&&C("button",{class:"anam-trigger",onClick:I,"aria-label":E,children:p?C("img",{src:p,alt:"Avatar"}):C(Ft,{})}),b&&C(oo,{config:l,session:s,videoRef:e,avatarSrc:p,avatarVideoSrc:f,displayCta:E,agentName:y||null,onCollapse:T?w:null,onStop:T?null:()=>s.stopSession(),dispatch:n})]}):null}const lo=["agent-id","api-base-url","session-token","layout","initial-state","position","ui-mute-button","ui-text-input","ui-captions","ui-transcript","call-to-action","avatar-url","avatar-video-url","agent-name"];function $t(t="anam-agent"){Sn(so,t,[...lo],{shadow:!0})}typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>$t()):$t()),ue.DefaultConfig=wt,ue.WidgetEventNames=Y,ue.registerWidget=$t,Object.defineProperty(ue,Symbol.toStringTag,{value:"Module"})}));
