(function(he,de){typeof exports=="object"&&typeof module<"u"?de(exports):typeof define=="function"&&define.amd?define(["exports"],de):(he=typeof globalThis<"u"?globalThis:he||self,de(he.AnamAgentWidget={}))})(this,(function(he){"use strict";var de,L,Ht,zt,ye,qt,Yt,Kt,Jt,ht,ft,pt,Fe={},Xt=[],_n=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ze=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&&L.vnode!=null&&L.vnode(s),s}function fe(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)&&ye.push(t)&&!Qe.__r++||qt!=L.debounceRendering)&&((qt=L.debounceRendering)||Yt)(Qe)}function Qe(){for(var t,e,i,n,a,s,c,l=1;ye.length;)ye.length>l&&ye.sort(Kt),t=ye.shift(),l=ye.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,L.vnode&&L.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)));Qe.__r=0}function ei(t,e,i,n,a,s,c,l,m,f,p){var u,y,E,T,I,w,A,R=n&&n.__k||Xt,b=e.length;for(m=mn(i,e,R,m,b),u=0;u<b;u++)(E=i.__k[u])!=null&&(y=E.__i==-1?Fe:R[E.__i]||Fe,E.__i=u,w=mt(t,E,y,a,s,c,l,m,f,p),T=E.__e,E.ref&&y.ref!=E.ref&&(y.ref&&Et(y.ref,null,E),p.push(E.ref,E.__c||T,E)),I==null&&T!=null&&(I=T),(A=!!(4&E.__u))||y.__k===E.__k?m=ti(E,m,t,A):typeof E.type=="function"&&w!==void 0?m=w:T&&(m=T.nextSibling),E.__u&=-7);return i.__e=I,m}function mn(t,e,i,n,a){var s,c,l,m,f,p=i.length,u=p,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):Ze(c)?c=t.__k[s]=$e(fe,{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,(f=c.__i=gn(c,i,m,u))!=-1&&(u--,(l=i[f])&&(l.__u|=2)),l==null||l.__v==null?(f==-1&&(a>p?y--:a<p&&y++),typeof c.type!="function"&&(c.__u|=4)):f!=m&&(f==m-1?y--:f==m+1?y++:(f>m?y--:y++,c.__u|=4))):t.__k[s]=null;if(u)for(s=0;s<p;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 gn(t,e,i,n){var a,s,c,l=t.key,m=t.type,f=e[i],p=f!=null&&(2&f.__u)==0;if(f===null&&l==null||p&&l==f.key&&m==f.type)return i;if(n>(p?1:0)){for(a=i-1,s=i+1;a>=0||s<e.length;)if((f=e[c=a>=0?a--:s++])!=null&&(2&f.__u)==0&&l==f.key&&m==f.type)return c}return-1}function ii(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||_n.test(e)?i:i+"px"}function et(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(L.event?L.event(e):e)}}}function mt(t,e,i,n,a,s,c,l,m,f){var p,u,y,E,T,I,w,A,R,b,N,S,k,U,q,X,se,Z=e.type;if(e.constructor!==void 0)return null;128&i.__u&&(m=!!(32&i.__u),s=[l=e.__e=i.__e]),(p=L.__b)&&p(e);e:if(typeof Z=="function")try{if(A=e.props,R="prototype"in Z&&Z.prototype.render,b=(p=Z.contextType)&&n[p.__c],N=p?b?b.props.value:p.__:n,i.__c?w=(u=e.__c=i.__c).__=u.__E:(R?e.__c=u=new Z(A,N):(e.__c=u=new Oe(A,N),u.constructor=Z,u.render=vn),b&&b.sub(u),u.state||(u.state={}),u.__n=n,y=u.__d=!0,u.__h=[],u._sb=[]),R&&u.__s==null&&(u.__s=u.state),R&&Z.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=ae({},u.__s)),ae(u.__s,Z.getDerivedStateFromProps(A,u.__s))),E=u.props,T=u.state,u.__v=e,y)R&&Z.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),R&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(R&&Z.getDerivedStateFromProps==null&&A!==E&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(A,N),e.__v==i.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(A,u.__s,N)===!1){for(e.__v!=i.__v&&(u.props=A,u.state=u.__s,u.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(ie){ie&&(ie.__=e)}),S=0;S<u._sb.length;S++)u.__h.push(u._sb[S]);u._sb=[],u.__h.length&&c.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(A,u.__s,N),R&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,T,I)})}if(u.context=N,u.props=A,u.__P=t,u.__e=!1,k=L.__r,U=0,R){for(u.state=u.__s,u.__d=!1,k&&k(e),p=u.render(u.props,u.state,u.context),q=0;q<u._sb.length;q++)u.__h.push(u._sb[q]);u._sb=[]}else do u.__d=!1,k&&k(e),p=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++U<25);u.state=u.__s,u.getChildContext!=null&&(n=ae(ae({},n),u.getChildContext())),R&&!y&&u.getSnapshotBeforeUpdate!=null&&(I=u.getSnapshotBeforeUpdate(E,T)),X=p,p!=null&&p.type===fe&&p.key==null&&(X=oi(p.props.children)),l=ei(t,Ze(X)?X:[X],e,i,n,a,s,c,l,m,f),u.base=e.__e,e.__u&=-161,u.__h.length&&c.push(u),w&&(u.__E=u.__=null)}catch(ie){if(e.__v=null,m||s!=null)if(ie.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,ie.then||gt(e);L.__e(ie,e,i)}else s==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):l=e.__e=En(i.__e,e,i,n,a,s,c,m,f);return(p=L.diffed)&&p(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]);L.__c&&L.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){L.__e(s,a.__v)}})}function oi(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Ze(t)?t.map(oi):ae({},t)}function En(t,e,i,n,a,s,c,l,m){var f,p,u,y,E,T,I,w=i.props||Fe,A=e.props,R=e.type;if(R=="svg"?a="http://www.w3.org/2000/svg":R=="math"?a="http://www.w3.org/1998/Math/MathML":a||(a="http://www.w3.org/1999/xhtml"),s!=null){for(f=0;f<s.length;f++)if((E=s[f])&&"setAttribute"in E==!!R&&(R?E.localName==R:E.nodeType==3)){t=E,s[f]=null;break}}if(t==null){if(R==null)return document.createTextNode(A);t=document.createElementNS(a,R,A.is&&A),l&&(L.__m&&L.__m(e,s),l=!1),s=null}if(R==null)w===A||l&&t.data==A||(t.data=A);else{if(s=s&&de.call(t.childNodes),!l&&s!=null)for(w={},f=0;f<t.attributes.length;f++)w[(E=t.attributes[f]).name]=E.value;for(f in w)if(E=w[f],f!="children"){if(f=="dangerouslySetInnerHTML")u=E;else if(!(f in A)){if(f=="value"&&"defaultValue"in A||f=="checked"&&"defaultChecked"in A)continue;et(t,f,null,E,a)}}for(f in A)E=A[f],f=="children"?y=E:f=="dangerouslySetInnerHTML"?p=E:f=="value"?T=E:f=="checked"?I=E:l&&typeof E!="function"||w[f]===E||et(t,f,E,w[f],a);if(p)l||u&&(p.__html==u.__html||p.__html==t.innerHTML)||(t.innerHTML=p.__html),e.__k=[];else if(u&&(t.innerHTML=""),ei(e.type=="template"?t.content:t,Ze(y)?y:[y],e,i,n,R=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,c,s?s[0]:i.__k&&xe(i,0),l,m),s!=null)for(f=s.length;f--;)_t(s[f]);l||(f="value",R=="progress"&&T==null?t.removeAttribute("value"):T!=null&&(T!==t[f]||R=="progress"&&!T||R=="option"&&T!=w[f])&&et(t,f,T,w[f],a),f="checked",I!=null&&I!=t[f]&&et(t,f,I,w[f],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){L.__e(a,i)}}function si(t,e,i){var n,a;if(L.unmount&&L.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){L.__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 vn(t,e,i){return this.constructor(t,i)}function tt(t,e,i){var n,a,s,c;e==document&&(e=document.documentElement),L.__&&L.__(t,e),a=(n=typeof i=="function")?null:i&&i.__k||e.__k,s=[],c=[],mt(e,t=(!n&&i||e).__k=Ae(fe,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){tt(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,L={__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=fe,ye=[],Yt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Kt=function(t,e){return t.__v.__b-e.__v.__b},Qe.__r=0,Jt=/(PointerCapture)$|Capture$/i,ht=0,ft=ni(!1),pt=ni(!0);function it(){return it=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},it.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 Cn=["context","children"],Sn=["useFragment"];function Tn(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(){In.call(this,n)},a.prototype.attributeChangedCallback=bn,a.prototype.disconnectedCallback=wn,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,Cn);return li(e,i)}function In(t){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=Ae(yn,it({},this._props,{context:e.detail.context}),hi(this,this._vdomComponent,t)),(this.hasAttribute("hydrate")?ai:tt)(this._vdom,this._root)}function di(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function bn(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[di(t)]=i,this._vdom=li(this._vdom,n),tt(this._vdom,this._root)}}function wn(){tt(this._vdom=null,this._root)}function ui(t,e){var i=this,n=t.useFragment,a=ci(t,Sn);return Ae(n?fe:"slot",it({},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),f=l[s].slot;f?a[f]=Ae(ui,{name:f},m):n[s]=m}var p=!(!i||!i.shadow),u=e?Ae(ui,{useFragment:!p},n):n;return!p&&e&&(t.innerHTML=""),Ae(e||t.nodeName.toLowerCase(),a,u)}var Rn=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 f={type:t,props:m,key:i,ref:c,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Rn,__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 L.vnode&&L.vnode(f),f}var Ve,V,vt,fi,We=0,pi=[],j=L,_i=j.__b,mi=j.__r,gi=j.diffed,Ei=j.__c,vi=j.unmount,Ci=j.__;function Ct(t,e){j.__h&&j.__h(V,t,We||e),We=0;var i=V.__H||(V.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function St(t){return We=1,An(yi,t)}function An(t,e,i){var n=Ct(Ve++,2);if(n.t=t,!n.__c&&(n.__=[yi(void 0,e),function(l){var m=n.__N?n.__N[0]:n.__[0],f=n.t(m,l);m!==f&&(n.__N=[f,n.__[1]],n.__c.setState({}))}],n.__c=V,!V.__f)){var a=function(l,m,f){if(!n.__c.__H)return!0;var p=n.__c.__H.__.filter(function(y){return!!y.__c});if(p.every(function(y){return!y.__N}))return!s||s.call(this,l,m,f);var u=n.__c.props!==l;return p.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,f)||u};V.__f=!0;var s=V.shouldComponentUpdate,c=V.componentWillUpdate;V.componentWillUpdate=function(l,m,f){if(this.__e){var p=s;s=void 0,a(l,m,f),s=p}c&&c.call(this,l,m,f)},V.shouldComponentUpdate=a}return n.__N||n.__}function Ie(t,e){var i=Ct(Ve++,3);!j.__s&&Ti(i.__H,e)&&(i.__=t,i.u=e,V.__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 Ti(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 On(){for(var t;t=pi.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(nt),t.__H.__h.forEach(Tt),t.__H.__h=[]}catch(e){t.__H.__h=[],j.__e(e,t.__v)}}j.__b=function(t){V=null,_i&&_i(t)},j.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Ci&&Ci(t,e)},j.__r=function(t){mi&&mi(t),Ve=0;var e=(V=t.__c).__H;e&&(vt===V?(e.__h=[],V.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(nt),e.__h.forEach(Tt),e.__h=[],Ve=0)),vt=V},j.diffed=function(t){gi&&gi(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(pi.push(e)!==1&&fi===j.requestAnimationFrame||((fi=j.requestAnimationFrame)||xn)(On)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),vt=V=null},j.__c=function(t,e){e.some(function(i){try{i.__h.forEach(nt),i.__h=i.__h.filter(function(n){return!n.__||Tt(n)})}catch(n){e.some(function(a){a.__h&&(a.__h=[])}),e=[],j.__e(n,i.__v)}}),Ei&&Ei(t,e)},j.unmount=function(t){vi&&vi(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{nt(n)}catch(a){e=a}}),i.__H=void 0,e&&j.__e(e,i.__v))};var Si=typeof requestAnimationFrame=="function";function xn(t){var e,i=function(){clearTimeout(n),Si&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);Si&&(e=requestAnimationFrame(i))}function nt(t){var e=V,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),V=e}function Tt(t){var e=V;t.__c=t.__(),V=e}function Ti(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function yi(t,e){return typeof e=="function"?e(t):e}var Nn=Symbol.for("preact-signals");function rt(){if(pe>1)pe--;else{for(var t,e=!1;He!==void 0;){var i=He;for(He=void 0,yt++;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(yt=0,pe--,e)throw t}}function kn(t){if(pe>0)return t();pe++;try{return t()}finally{rt()}}var M=void 0;function Ii(t){var e=M;M=void 0;try{return t()}finally{M=e}}var He=void 0,pe=0,yt=0,ot=0;function bi(t){if(M!==void 0){var e=t.n;if(e===void 0||e.t!==M)return e={i:0,S:t,p:M.s,n:void 0,t:M,e:void 0,x:void 0,r:e},M.s!==void 0&&(M.s.n=e),M.s=e,t.n=e,32&M.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=M.s,e.n=void 0,M.s.n=e,M.s=e),e}}function Y(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}Y.prototype.brand=Nn,Y.prototype.h=function(){return!0},Y.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)}))},Y.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)}))}},Y.prototype.subscribe=function(t){var e=this;return ze(function(){var i=e.value,n=M;M=void 0;try{t(i)}finally{M=n}},{name:"sub"})},Y.prototype.valueOf=function(){return this.value},Y.prototype.toString=function(){return this.value+""},Y.prototype.toJSON=function(){return this.value},Y.prototype.peek=function(){var t=M;M=void 0;try{return this.value}finally{M=t}},Object.defineProperty(Y.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(yt>100)throw new Error("Cycle detected");this.v=t,this.i++,ot++,pe++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{rt()}}}});function G(t,e){return new Y(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){Y.call(this,void 0),this.x=t,this.s=void 0,this.g=ot-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}be.prototype=new Y,be.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===ot))return!0;if(this.g=ot,this.f|=1,this.i>0&&!wi(this))return this.f&=-2,!0;var t=M;try{Ri(this),M=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 M=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)}Y.prototype.S.call(this,t)},be.prototype.U=function(t){if(this.t!==void 0&&(Y.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"){pe++;var i=M;M=void 0;try{e()}catch(n){throw t.f&=-2,t.f|=8,It(t),n}finally{M=i,rt()}}}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 Ln(t){if(M!==this)throw new Error("Out-of-order effect");Ai(this),M=t,this.f&=-2,8&this.f&&It(this),rt()}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),pe++;var t=M;return M=this,Ln.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,Mn=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,ki=[];ze(function(){Ni=this.N})();function Le(t,e){L[t]=e.bind(null,L[t]||function(){})}function st(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 f=Oi(function(){var E=n.value.value;return E===0?0:E===!0?"":E||""}),p=Oi(function(){return!Array.isArray(f.value)&&!zt(f.value)}),u=ze(function(){if(this.N=Di,p.value){var E=f.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)},[p,f]},[]),s=a[0],c=a[1];return s.value?c.peek():c.value}Li.displayName="ReactiveTextNode",Object.defineProperties(Y.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 Y&&(i||(e.__np=i={}),i[a]=s,n[a]=s.peek())}}t(e)}),Le("__r",function(t,e){if(e.type!==fe){st();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;Mn&&((a=i.y)==null||a.call(i)),n.__$f|=1,n.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),st(i)}t(e)}),Le("__e",function(t,e,i,n){st(),t(e,i,n)}),Le("diffed",function(t,e){st();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 f=s[m],p=n[m];f===void 0?(f=Dn(i,m,p,a),s[m]=f):f.o(p,a)}}}t(e)});function Dn(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 Un=function(t){queueMicrotask(function(){queueMicrotask(t)})};function Pn(){kn(function(){for(var t;t=ki.shift();)Ni.call(t)})}function Di(){ki.push(this)===1&&(L.requestAnimationFrame||Un)(Pn)}const wt={layout:"floating",initialState:"expanded",position:"bottom-right",showCaptions:!1,showTextInput:!0,showMuteButton:!0,showTranscript:!0,showPreviewVideo:!0,removeWatermark:!1,callToAction:"Talk to our assistant"},at={"bottom-right":{bottom:"24px",right:"24px"},"bottom-left":{bottom:"24px",left:"24px"},"top-right":{top:"24px",right:"24px"},"top-left":{top:"24px",left:"24px"}},Bn=new Set(["top","right","bottom","left","margin","margin-top","margin-right","margin-bottom","margin-left"]);function Fn(t){if(at[t])return at[t];const e=t.match(/^\[(.+)\]$/);if(!e)return at["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(!Bn.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:at["bottom-right"]}var Rt={},qe={},Ui;function $n(){if(Ui)return qe;Ui=1,qe.byteLength=l,qe.toByteArray=f,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 T=E.length;if(T%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var I=E.indexOf("=");I===-1&&(I=T);var w=I===T?0:4-I%4;return[I,w]}function l(E){var T=c(E),I=T[0],w=T[1];return(I+w)*3/4-w}function m(E,T,I){return(T+I)*3/4-I}function f(E){var T,I=c(E),w=I[0],A=I[1],R=new i(m(E,w,A)),b=0,N=A>0?w-4:w,S;for(S=0;S<N;S+=4)T=e[E.charCodeAt(S)]<<18|e[E.charCodeAt(S+1)]<<12|e[E.charCodeAt(S+2)]<<6|e[E.charCodeAt(S+3)],R[b++]=T>>16&255,R[b++]=T>>8&255,R[b++]=T&255;return A===2&&(T=e[E.charCodeAt(S)]<<2|e[E.charCodeAt(S+1)]>>4,R[b++]=T&255),A===1&&(T=e[E.charCodeAt(S)]<<10|e[E.charCodeAt(S+1)]<<4|e[E.charCodeAt(S+2)]>>2,R[b++]=T>>8&255,R[b++]=T&255),R}function p(E){return t[E>>18&63]+t[E>>12&63]+t[E>>6&63]+t[E&63]}function u(E,T,I){for(var w,A=[],R=T;R<I;R+=3)w=(E[R]<<16&16711680)+(E[R+1]<<8&65280)+(E[R+2]&255),A.push(p(w));return A.join("")}function y(E){for(var T,I=E.length,w=I%3,A=[],R=16383,b=0,N=I-w;b<N;b+=R)A.push(u(E,b,b+R>N?N:b+R));return w===1?(T=E[I-1],A.push(t[T>>2]+t[T<<4&63]+"==")):w===2&&(T=(E[I-2]<<8)+E[I-1],A.push(t[T>>10]+t[T>>4&63]+t[T<<2&63]+"=")),A.join("")}return qe}var lt={};var Pi;function Vn(){return Pi||(Pi=1,lt.read=function(t,e,i,n,a){var s,c,l=a*8-n-1,m=(1<<l)-1,f=m>>1,p=-7,u=i?a-1:0,y=i?-1:1,E=t[e+u];for(u+=y,s=E&(1<<-p)-1,E>>=-p,p+=l;p>0;s=s*256+t[e+u],u+=y,p-=8);for(c=s&(1<<-p)-1,s>>=-p,p+=n;p>0;c=c*256+t[e+u],u+=y,p-=8);if(s===0)s=1-f;else{if(s===m)return c?NaN:(E?-1:1)*(1/0);c=c+Math.pow(2,n),s=s-f}return(E?-1:1)*c*Math.pow(2,s-n)},lt.write=function(t,e,i,n,a,s){var c,l,m,f=s*8-a-1,p=(1<<f)-1,u=p>>1,y=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,E=n?0:s-1,T=n?1:-1,I=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=p):(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>=p?(l=0,c=p):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+=T,l/=256,a-=8);for(c=c<<a|l,f+=a;f>0;t[i+E]=c&255,E+=T,c/=256,f-=8);t[i+E-T]|=I*128}),lt}var Bi;function Wn(){return Bi||(Bi=1,(function(t){const e=$n(),i=Vn(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=R,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 T(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 I(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 _=w(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 f(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 p(d,r,o){return f(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 p(d,r,o)};function u(d){return f(d),c(d<0?0:A(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=b(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:A(d.length)|0,o=c(r);for(let h=0;h<r;h+=1)o[h]=d[h]&255;return o}function T(d){if(ce(d,Uint8Array)){const r=new Uint8Array(d);return I(r.buffer,r.byteOffset,r.byteLength)}return E(d)}function I(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 w(d){if(l.isBuffer(d)){const r=A(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 A(d){if(d>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return d|0}function R(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 b(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 pn(d).length;default:if(_)return h?-1:jt(d).length;r=(""+r).toLowerCase(),_=!0}}l.byteLength=b;function N(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 re(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 H(this,r,o);default:if(h)throw new TypeError("Unknown encoding: "+d);d=(d+"").toLowerCase(),h=!0}}l.prototype._isBuffer=!0;function S(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)S(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)S(this,o,o+3),S(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)S(this,o,o+7),S(this,o+1,o+6),S(this,o+2,o+5),S(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):N.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 F=Math.min(v,x),P=this.slice(_,g),$=r.slice(o,h);for(let D=0;D<F;++D)if(P[D]!==$[D]){v=P[D],x=$[D];break}return v<x?-1:x<v?1:0};function k(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:U(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):U(d,[r],o,h,_);throw new TypeError("val must be string, number or Buffer")}function U(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 F($,D){return g===1?$[D]:$.readUInt16BE(D*g)}let P;if(_){let $=-1;for(P=o;P<v;P++)if(F(d,P)===F(r,$===-1?0:P-$)){if($===-1&&($=P),P-$+1===x)return $*g}else $!==-1&&(P-=P-$),$=-1}else for(o+x>v&&(o=v-x),P=o;P>=0;P--){let $=!0;for(let D=0;D<x;D++)if(F(d,P+D)!==F(r,D)){$=!1;break}if($)return P}return-1}l.prototype.includes=function(r,o,h){return this.indexOf(r,o,h)!==-1},l.prototype.indexOf=function(r,o,h){return k(this,r,o,h,!0)},l.prototype.lastIndexOf=function(r,o,h){return k(this,r,o,h,!1)};function q(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 X(d,r,o,h){return ut(jt(r,d.length-o),d,o,h)}function se(d,r,o,h){return ut(po(r),d,o,h)}function Z(d,r,o,h){return ut(pn(r),d,o,h)}function ie(d,r,o,h){return ut(_o(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 q(this,r,o,h);case"utf8":case"utf-8":return X(this,r,o,h);case"ascii":case"latin1":case"binary":return se(this,r,o,h);case"base64":return Z(this,r,o,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ie(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 F,P,$,D;switch(x){case 1:g<128&&(v=g);break;case 2:F=d[_+1],(F&192)===128&&(D=(g&31)<<6|F&63,D>127&&(v=D));break;case 3:F=d[_+1],P=d[_+2],(F&192)===128&&(P&192)===128&&(D=(g&15)<<12|(F&63)<<6|P&63,D>2047&&(D<55296||D>57343)&&(v=D));break;case 4:F=d[_+1],P=d[_+2],$=d[_+3],(F&192)===128&&(P&192)===128&&($&192)===128&&(D=(g&15)<<18|(F&63)<<12|(P&63)<<6|$&63,D>65535&&D<1114112&&(v=D))}}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 re(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)_+=mo[d[g]];return _}function H(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 z(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||z(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||z(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||z(r,1,this.length),this[r]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(r,o){return r=r>>>0,o||z(r,2,this.length),this[r]|this[r+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(r,o){return r=r>>>0,o||z(r,2,this.length),this[r]<<8|this[r+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(r,o){return r=r>>>0,o||z(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||z(r,4,this.length),this[r]*16777216+(this[r+1]<<16|this[r+2]<<8|this[r+3])},l.prototype.readBigUInt64LE=Te(function(r){r=r>>>0,Be(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Xe(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=Te(function(r){r=r>>>0,Be(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Xe(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||z(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||z(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||z(r,1,this.length),this[r]&128?(255-this[r]+1)*-1:this[r]},l.prototype.readInt16LE=function(r,o){r=r>>>0,o||z(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||z(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||z(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||z(r,4,this.length),this[r]<<24|this[r+1]<<16|this[r+2]<<8|this[r+3]},l.prototype.readBigInt64LE=Te(function(r){r=r>>>0,Be(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Xe(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=Te(function(r){r=r>>>0,Be(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Xe(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||z(r,4,this.length),i.read(this,r,!0,23,4)},l.prototype.readFloatBE=function(r,o){return r=r>>>0,o||z(r,4,this.length),i.read(this,r,!1,23,4)},l.prototype.readDoubleLE=function(r,o){return r=r>>>0,o||z(r,8,this.length),i.read(this,r,!0,52,8)},l.prototype.readDoubleBE=function(r,o){return r=r>>>0,o||z(r,8,this.length),i.read(this,r,!1,52,8)};function ne(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;ne(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;ne(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||ne(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||ne(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||ne(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||ne(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||ne(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 an(d,r,o,h,_){fn(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 ln(d,r,o,h,_){fn(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=Te(function(r,o=0){return an(this,r,o,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Te(function(r,o=0){return ln(this,r,o,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(r,o,h,_){if(r=+r,o=o>>>0,!_){const F=Math.pow(2,8*h-1);ne(this,r,o,h,F-1,-F)}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 F=Math.pow(2,8*h-1);ne(this,r,o,h,F-1,-F)}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||ne(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||ne(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||ne(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||ne(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||ne(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=Te(function(r,o=0){return an(this,r,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Te(function(r,o=0){return ln(this,r,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function cn(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 dn(d,r,o,h,_){return r=+r,o=o>>>0,_||cn(d,r,o,4),i.write(d,r,o,h,23,4),o+4}l.prototype.writeFloatLE=function(r,o,h){return dn(this,r,o,!0,h)},l.prototype.writeFloatBE=function(r,o,h){return dn(this,r,o,!1,h)};function un(d,r,o,h,_){return r=+r,o=o>>>0,_||cn(d,r,o,8),i.write(d,r,o,h,52,8),o+8}l.prototype.writeDoubleLE=function(r,o,h){return un(this,r,o,!0,h)},l.prototype.writeDoubleBE=function(r,o,h){return un(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?_=hn(String(o)):typeof o=="bigint"&&(_=String(o),(o>BigInt(2)**BigInt(32)||o<-(BigInt(2)**BigInt(32)))&&(_=hn(_)),_+="n"),h+=` It must be ${r}. Received ${_}`,h},RangeError);function hn(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 uo(d,r,o){Be(r,"offset"),(d[r]===void 0||d[r+o]===void 0)&&Xe(r,d.length-(o+1))}function fn(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)}uo(h,_,g)}function Be(d,r){if(typeof d!="number")throw new Pe.ERR_INVALID_ARG_TYPE(r,"number",d)}function Xe(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 ho=/[^+/0-9A-Za-z-_]/g;function fo(d){if(d=d.split("=")[0],d=d.trim().replace(ho,""),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 po(d){const r=[];for(let o=0;o<d.length;++o)r.push(d.charCodeAt(o)&255);return r}function _o(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 pn(d){return e.toByteArray(fo(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 mo=(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 Te(d){return typeof BigInt>"u"?go:d}function go(){throw new Error("BigInt not supported")}})(Rt)),Rt}var jn=Wn();const Gn="https://api.anam.ai",Hn="/v1",Fi={client:"js-sdk",version:"4.20.0"},zn=3,qn=250,Yn=2e3,Kn=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(p){try{f(n.next(p))}catch(u){c(u)}}function m(p){try{f(n.throw(p))}catch(u){c(u)}}function f(p){p.done?s(p.value):a(p.value).then(l,m)}f((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,_e,Gi=!1;const Jn=(t,e=At)=>{Ot=t,ji=e},Xn=t=>{_e=t},Zn=t=>{Gi=t};let me={sessionId:null,organizationId:null,attemptCorrelationId:null};const Ye=t=>{me=Object.assign(Object.assign({},me),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"};_e?.enabled&&_e?.baseUrl?(i=`${_e.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:Qn(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)}}),Qn=t=>{const e=Object.assign(Object.assign({},Fi),t);return me.sessionId&&e.sessionId===void 0&&(e.sessionId=me.sessionId),me.organizationId&&e.organizationId===void 0&&(e.organizationId=me.organizationId),me.attemptCorrelationId&&e.attemptCorrelationId===void 0&&(e.attemptCorrelationId=me.attemptCorrelationId),e},er=(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,T,I,w;const A={framesReceived:(y=u.framesReceived)!==null&&y!==void 0?y:"unknown",framesDropped:(E=u.framesDropped)!==null&&E!==void 0?E:"unknown",framesPerSecond:(T=u.framesPerSecond)!==null&&T!==void 0?T:"unknown",packetsReceived:(I=u.packetsReceived)!==null&&I!==void 0?I:"unknown",packetsLost:(w=u.packetsLost)!==null&&w!==void 0?w:"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(A)}));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,T;const I={packetsReceived:(y=u.packetsReceived)!==null&&y!==void 0?y:"unknown",packetsLost:(E=u.packetsLost)!==null&&E!==void 0?E:"unknown",audioLevel:(T=u.audioLevel)!==null&&T!==void 0?T:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};c.personaAudioStream.push(I)}));const f=((a=s["outbound-rtp"])===null||a===void 0?void 0:a.filter(u=>u.kind==="audio"))||[];f.length>0&&(c.userAudioInput=[],f.forEach(u=>{var y,E;const T={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(T)})),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 p=[];if(l.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&p.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&p.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&p.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),m.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&p.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&p.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),c.issues=p,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 K;(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"})(K||(K={}));class W 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,W.prototype),Me(le.CLIENT_METRIC_MEASUREMENT_ERROR,i,{details:a,statusCode:n})}}function tr(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}const zi=0,ir=5e3;class nr{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:rr,this.attemptStartedAtMs=this.now(),this.sampleRatio=or((n=e.connectionMilestoneSampleRatio)!==null&&n!==void 0?n:zi),this.slowConnectionThresholdMs=Math.max(0,qi(e.slowConnectionThresholdMs,ir)),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 rr=()=>typeof performance<"u"?performance.now():Date.now(),or=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 sr(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 Q;(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"})(Q||(Q={}));var oe;(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"})(oe||(oe={}));var ge;(function(t){t.PENDING="pending",t.GRANTED="granted",t.DENIED="denied",t.NOT_REQUESTED="not_requested"})(ge||(ge={}));var Ee;(function(t){t.USER="user",t.PERSONA="persona"})(Ee||(Ee={}));var O;(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"})(O||(O={}));var B;(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"})(B||(B={}));var ue;(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"})(ue||(ue={}));class ar{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(p){try{f(n.next(p))}catch(u){c(u)}}function m(p){try{f(n.throw(p))}catch(u){c(u)}}function f(p){p.done?s(p.value):a(p.value).then(l,m)}f((n=n.apply(t,e||[])).next())})};const lr=5,cr=5,dr=24;class ur{constructor(e,i,n,a,s,c){var l,m,f,p,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:T}=i;if(this.heartbeatIntervalSeconds=y||lr,this.maxWsReconnectionAttempts=E||cr,!T.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 I=new URL(this.apiGatewayConfig.baseUrl),w=(f=this.apiGatewayConfig.wsPath)!==null&&f!==void 0?f:"/ws";I.protocol=I.protocol.replace("http","ws"),I.pathname=w,this.url=I;const A=T.protocol||"https",R=A==="http"?"ws":"wss",b=`${A}://${T.baseUrl}`,N=(p=T.signallingPath)!==null&&p!==void 0?p:"/ws",S=new URL(b);S.protocol=R==="ws"?"ws:":"wss:",T.port&&(S.port=T.port),S.pathname=N,S.searchParams.append("session_id",e),this.url.searchParams.append("target_url",S.href)}else{const w=`${T.protocol||"https"}://${T.baseUrl}`;this.url=new URL(w),this.url.protocol=T.protocol==="http"?"ws:":"wss:",T.port&&(this.url.port=T.port),this.url.pathname=(u=T.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:Q.OFFER,sessionId:this.sessionId,payload:i};this.sendSignalMessage(n)})}sendIceCandidate(e){return De(this,void 0,void 0,function*(){const i={actionType:Q.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:Q.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)})}sendAgentAudioInput(e){const i={actionType:Q.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)}sendAgentAudioInputEnd(){const e={actionType:Q.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(B.WEB_SOCKET_OPEN)}catch(n){console.error("SignallingClient - onOpen: error in onOpen",n),this.publicEventEmitter.emit(O.CONNECTION_CLOSED,ue.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(O.CONNECTION_CLOSED,ue.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.iceRestartReconnectInProgress=!1,this.permanentlyClosed=!0})}getMaxReconnectionAttempts(){return this.iceRestartReconnectInProgress?Math.max(this.maxWsReconnectionAttempts,dr):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(B.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:Q.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 hr(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(p){try{f(n.next(p))}catch(u){c(u)}}function m(p){try{f(n.throw(p))}catch(u){c(u)}}function f(p){p.done?s(p.value):a(p.value).then(l,m)}f((n=n.apply(t,e||[])).next())})};class fr{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||Gn,this.apiVersion=n?.apiVersion||Hn,this.apiGatewayConfig=n?.apiGateway||void 0,this.retryOptions=pr(n?.retry),this.requestTimeoutMs=Math.max(0,ct(n?.requestTimeoutMs,Kn))}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 W("Persona configuration must be provided when using apiKey",K.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||!_r(c))throw c;yield mr(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}),f=yield m.json(),p=f.error;switch(m.status){case 200:case 201:return f;case 400:throw new W("Invalid request to start session",K.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:f.message});case 401:throw new W("Authentication failed when starting session",K.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:f.message});case 402:throw new W("Please sign up for a plan to start a session",K.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:f.message});case 403:throw new W("Authentication failed when starting session",K.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:f.message});case 429:throw p==="Concurrent session limit reached"?new W("Concurrency limit reached, please upgrade your plan",K.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:f.message}):p==="Spend cap reached"?new W("Spend cap reached, please upgrade your plan",K.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:f.message}):new W("Usage limit reached, please upgrade your plan",K.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:f.message});case 503:throw new W("There are no available personas, please try again later",K.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:f.message});default:throw new W("Unknown error when starting session",K.CLIENT_ERROR_CODE_SERVER_ERROR,m.status,{cause:f.message})}}catch(s){throw s instanceof W?s:new W("Failed to start session",K.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"};hr(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 pr(t){const e=Math.max(1,Math.floor(ct(t?.maxAttempts,zn))),i=Math.max(0,ct(t?.initialBackoffMs,qn)),n=Math.max(i,ct(t?.maxBackoffMs,Yn));return{maxAttempts:e,initialBackoffMs:i,maxBackoffMs:n}}function ct(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function _r(t){return t instanceof W?t.statusCode>=500&&t.statusCode<600:!0}function mr(t){return new Promise(e=>setTimeout(e,t))}var gr=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(p){try{f(n.next(p))}catch(u){c(u)}}function m(p){try{f(n.throw(p))}catch(u){c(u)}}function f(p){p.done?s(p.value):a(p.value).then(l,m)}f((n=n.apply(t,e||[])).next())})};class Er{constructor(e,i,n){this.baseUrl=e,this.sessionId=i,this.apiGatewayConfig=n}sendTalkCommand(e){return gr(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 f=new URL(`${this.baseUrl}${c}${l}`);s["X-Anam-Target-Url"]=f.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 vr{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 Cr{constructor(e,i){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=i,this.internalEventEmitter.addListener(B.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(O.MESSAGE_STREAM_EVENT_RECEIVED,i),i.role){case Ee.USER:this.processUserMessage(i);break;case Ee.PERSONA:this.processPersonaMessage(i);break}i.endOfSpeech&&this.publicEventEmitter.emit(O.MESSAGE_HISTORY_UPDATED,this.messages)}}class Sr{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===O.CONNECTION_ESTABLISHED&&Me(le.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===O.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 te;(function(t){t[t.UNSTARTED=0]="UNSTARTED",t[t.STREAMING=1]="STREAMING",t[t.INTERRUPTED=2]="INTERRUPTED",t[t.ENDED=3]="ENDED"})(te||(te={}));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(p){try{f(n.next(p))}catch(u){c(u)}}function m(p){try{f(n.throw(p))}catch(u){c(u)}}function f(p){p.done?s(p.value):a(p.value).then(l,m)}f((n=n.apply(t,e||[])).next())})};class Tr{constructor(e,i,n){this.state=te.UNSTARTED,this.correlationId=e,this.internalEventEmitter=i,this.signallingClient=n,this.internalEventEmitter.addListener(B.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(B.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Nt(this,void 0,void 0,function*(){e.actionType===Q.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=te.INTERRUPTED,this.onDeactivate())})}endMessage(){return Nt(this,void 0,void 0,function*(){if(this.state===te.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==te.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=te.ENDED,this.onDeactivate()})}streamMessageChunk(e,i){return Nt(this,void 0,void 0,function*(){if(this.state!==te.STREAMING&&this.state!==te.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const n={content:e,startOfSpeech:this.state===te.UNSTARTED,endOfSpeech:i,correlationId:this.correlationId};this.state=i?te.ENDED:te.STREAMING,this.state===te.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(n)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===te.STREAMING||this.state===te.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(p){try{f(n.next(p))}catch(u){c(u)}}function m(p){try{f(n.throw(p))}catch(u){c(u)}}function f(p){p.done?s(p.value):a(p.value).then(l,m)}f((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(O.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(O.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(B.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 ee=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(p){try{f(n.next(p))}catch(u){c(u)}}function m(p){try{f(n.throw(p))}catch(u){c(u)}}function f(p){p.done?s(p.value):a(p.value).then(l,m)}f((n=n.apply(t,e||[])).next())})};const Lt=15e3,yr=5e3,Zi=2,Ir=3,br=2e3,Mt=3e3,wr=5e3;class Rr{constructor(e,i,n,a,s,c){var l,m,f,p;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:ge.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(B.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(B.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(B.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(B.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(B.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(B.TOOL_CALL_RESULT_READY,this.onToolCallResultReceived.bind(this)),this.iceServers=i.iceServers,this.iceTransportPolicy=i.iceTransportPolicy,this.rtcConfiguration=i.rtcConfiguration,this.signallingClient=new ur(e,i.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig,this.connectionMilestones),this.engineApiRestClient=new Er(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=(p=(f=i.metrics)===null||f===void 0?void 0:f.peerConnectionStatsReportOutputFormat)!==null&&p!==void 0?p:"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(()=>ee(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(()=>ee(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 ee(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(O.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 ee(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return ee(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 Tr(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new ar(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return ee(this,void 0,void 0,function*(){var e,i,n,a,s,c,l,m,f,p;(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?((f=this.connectionMilestones)===null||f===void 0||f.record("microphone_permission_skipped",{reason:"input_audio_disabled"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?((p=this.connectionMilestones)===null||p===void 0||p.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 ee(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 Q.ANSWER:{(i=this.connectionMilestones)===null||i===void 0||i.record("answer_received");const p=e.payload;if(this.peerConnection.signalingState!=="have-local-offer")break;try{yield this.peerConnection.setRemoteDescription(p)}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 Q.ICE_CANDIDATE:{const p=e.payload,u=new RTCIceCandidate(p);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 Q.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(O.CONNECTION_CLOSED,ue.SERVER_CLOSED_CONNECTION,c),this.shutdown();break;case Q.WARNING:const l=e.payload;console.warn("Warning received from server: "+l),this.publicEventEmitter.emit(O.SERVER_WARNING,l);break;case Q.TALK_STREAM_INTERRUPTED:const m=e.payload;this.publicEventEmitter.emit(O.TALK_STREAM_INTERRUPTED,m.correlationId);break;case Q.SESSION_READY:const f=e.sessionId;this.publicEventEmitter.emit(O.SESSION_READY,f);break;case Q.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 ee(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 ee(this,void 0,void 0,function*(){const e=[...this.remoteIceCandidateBuffer];this.remoteIceCandidateBuffer=[];for(const i of e)yield this.addRemoteIceCandidate(i)})}addRemoteIceCandidate(e){return ee(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(O.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(B.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()},br))}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"))},wr);const n=()=>{this.clearPendingWsOpenWait(),e()};this.pendingWsOpenListener=n,this.internalEventEmitter.addListener(B.WEB_SOCKET_OPEN,n)})}restartIce(){return ee(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>=Ir){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(O.CONNECTION_CLOSED,ue.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(O.CONNECTION_CLOSED,ue.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(O.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(O.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(O.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return ee(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,f;try{const p=JSON.parse(n.data);switch(p.messageType){case oe.SPEECH_TEXT:this.internalEventEmitter.emit(B.WEBRTC_CHAT_MESSAGE_RECEIVED,p.data);break;case oe.CLIENT_TOOL_EVENT:const u=p.data;this.internalEventEmitter.emit(B.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,u);const y=Xi.WebRTCClientToolEventToClientToolEvent(u);this.publicEventEmitter.emit(O.CLIENT_TOOL_EVENT_RECEIVED,y);break;case oe.TOOL_CALL_STARTED_EVENT:const E=p.data;this.publicEventEmitter.emit(O.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(E)),this.internalEventEmitter.emit(B.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,E);break;case oe.TOOL_CALL_COMPLETED_EVENT:const T=p.data;this.publicEventEmitter.emit(O.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(T)),this.internalEventEmitter.emit(B.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,T);break;case oe.TOOL_CALL_FAILED_EVENT:const I=p.data;this.publicEventEmitter.emit(O.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(I)),this.internalEventEmitter.emit(B.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,I);break;case oe.REASONING_TEXT:this.internalEventEmitter.emit(B.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,p.data);break;case oe.USER_SPEECH_STARTED:this.publicEventEmitter.emit(O.USER_SPEECH_STARTED,(s=(a=p.data)===null||a===void 0?void 0:a.user_action_correlation_id)!==null&&s!==void 0?s:"unknown");break;case oe.USER_SPEECH_ENDED:this.publicEventEmitter.emit(O.USER_SPEECH_ENDED,(l=(c=p.data)===null||c===void 0?void 0:c.user_action_correlation_id)!==null&&l!==void 0?l:"unknown");break;case oe.DIRECTOR_NOTE_CUE_APPLIED:const w=p.data;this.publicEventEmitter.emit(O.DIRECTOR_NOTE_CUE_APPLIED,{cueTag:(m=w?.cue_tag)!==null&&m!==void 0?m:"unknown",correlationId:(f=w?.user_action_correlation_id)!==null&&f!==void 0?f:"unknown"});break;default:break}}catch(p){console.error("Failed to parse data channel message:",p)}}})}requestMicrophonePermissionAsync(){return ee(this,void 0,void 0,function*(){var e,i,n;if(this.inputAudioState.permissionState!==ge.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:ge.PENDING}),(e=this.connectionMilestones)===null||e===void 0||e.record("microphone_permission_pending"),this.publicEventEmitter.emit(O.MIC_PERMISSION_PENDING);try{const a={echoCancellation:!0};this.audioDeviceId&&(a.deviceId={exact:this.audioDeviceId});const s=yield navigator.mediaDevices.getUserMedia({audio:a});if(this.iceRestartStopped||!this.peerConnection){s.getTracks().forEach(c=>c.stop());return}this.inputAudioStream=s,this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:ge.GRANTED}),(i=this.connectionMilestones)===null||i===void 0||i.record("microphone_permission_granted"),this.publicEventEmitter.emit(O.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:ge.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(O.MIC_PERMISSION_DENIED,s)}}})}setupAudioTrack(){return ee(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(O.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return ee(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 ee(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=er(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 Ar{constructor(e,i){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=i,this.internalEventEmitter.addListener(B.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(O.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(O.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(p){try{f(n.next(p))}catch(u){c(u)}}function m(p){try{f(n.throw(p))}catch(u){c(u)}}function f(p){p.done?s(p.value):a(p.value).then(l,m)}f((n=n.apply(t,e||[])).next())})};class Or{constructor(e,i,n){var a,s,c,l,m;this.inputAudioState={isMuted:!1,permissionState:ge.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const f=this.validateClientConfig(e,i,n);if(f)throw new W(f,K.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)&&Jn(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&&Xn(n.api.apiGateway),!((m=n?.metrics)===null||m===void 0)&&m.disableClientMetrics&&Zn(!0),this.publicEventEmitter=new Sr,this.internalEventEmitter=new vr,this.toolCallManager=new Xi(this.publicEventEmitter,this.internalEventEmitter),this.apiClient=new fr(e,n?.apiKey,n?.api),this.messageHistoryClient=new Cr(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Ar(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const i=e.split(".")[1],n=jn.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=sr((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=tr();Ye({attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId});const c=new nr({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,f,p,u,y,E,T,I,w,A,R,b;const N=this.personaConfig,S=this.buildStartSessionOptionsForClient();i?.record("start_session_request_started");let k;try{k=yield this.apiClient.startSession(N,S),i?.record("start_session_request_completed")}catch(re){throw i?.record("start_session_request_failed",Object.assign({},Ue(re))),i?.publishFailure(Object.assign({failureStage:"start_session_request"},Ue(re))),re}const{sessionId:U,clientConfig:q,engineHost:X,engineProtocol:se,signallingEndpoint:Z}=k,{heartbeatIntervalSeconds:ie,maxWsReconnectionAttempts:Ce,iceServers:Se,iceTransportPolicy:we}=q;this.sessionId=U,this.toolCallManager.setActiveSession(U),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 Rr(U,{engine:{baseUrl:`${se}://${X}`},signalling:{heartbeatIntervalSeconds:ie,maxWsReconnectionAttempts:Ce,url:{baseUrl:X,protocol:se,signallingPath:Z}},iceServers:Re,iceTransportPolicy:we,rtcConfiguration:(m=this.clientOptions)===null||m===void 0?void 0:m.rtcConfiguration,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((f=this.clientOptions)===null||f===void 0)&&f.disableInputAudio?void 0:e,audioDeviceId:(p=this.clientOptions)===null||p===void 0?void 0:p.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:(w=(I=(T=this.clientOptions)===null||T===void 0?void 0:T.metrics)===null||I===void 0?void 0:I.showPeerConnectionStatsReport)!==null&&w!==void 0?w:!1,peerConnectionStatsReportOutputFormat:(b=(R=(A=this.clientOptions)===null||A===void 0?void 0:A.metrics)===null||R===void 0?void 0:R.peerConnectionStatsReportOutputFormat)!==null&&b!==void 0?b:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager,i)}catch(re){throw i?.publishFailure(Object.assign({failureStage:"streaming_client_initialization"},Ue(re))),this.toolCallManager.clearSessionState(),Ye({sessionId:null}),new W("Failed to initialize streaming client",K.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:re instanceof Error?re.message:String(re),sessionId:U})}return U})}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 W("Session ID or streaming client is not available after starting session",K.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(O.VIDEO_STREAM_STARTED,f=>{c.push(f),l=!0,m&&a(c)}),this.publicEventEmitter.addListener(O.AUDIO_STREAM_STARTED,f=>{c.push(f),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 W?s:new W("Failed to start session",K.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(O.CONNECTION_CLOSED,ue.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 W?{errorName:t.name,errorCode:t.code,httpStatusCode:t.statusCode}:t instanceof Error?{errorName:t.name}:{},xr=(t,e)=>new Or(t,void 0,e),Qi=80;function Nr(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=Nr(t);return e?{kind:"link",data:e}:null}};function tn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function kr(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 Lr=()=>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"})]}),Mr=({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(Lr,{})]}),Dr={link:t=>C(Mr,{data:t})};function Ur(t){return Dr[t.kind](t.data)}const J={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"},Pr="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 Br(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 on(t,e){return t===ue.SERVER_CLOSED_CONNECTION&&e?.startsWith("Session reached max duration of ")===!0}function Fr(){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),timeLimitReached:G(!1),sessionId:G(null),avatarThumbnailUrl:G(null),avatarVideoUrl:G(null),personaName:G(null),serverConfig:G(null),isConfigured:G(!1),isReady:G(!1),generation:0,stopAttempt:null,prevMessageCount:0,dispatch:null}}function $r(t,e){for(const n of e){if(t.messageSeq.has(n.id))continue;const a=n.role===Ee.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 Vr(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 Wr(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,t.timeLimitReached.value=!1;let c,l=null,m="",f=!1,p=null,u,y;const E=new AbortController,T=()=>{clearInterval(u),clearTimeout(y),u=void 0},I=()=>{if(!l)return!1;const b=l.getActiveSessionId();try{l.stopStreaming().catch(()=>{})}catch{}if(b&&!f&&p!==b){p=b;try{fetch(`${i.replace(/\/$/,"")}/api/sessions/${encodeURIComponent(b)}/release`,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{Authorization:`Bearer ${m}`}}).catch(()=>{})}catch{}}return!!b},w=()=>{if(clearTimeout(R),E.abort(),I()){T();return}l&&!u&&!p&&(u=setInterval(()=>{l?.getActiveSessionId()&&I()&&T()},100),y=setTimeout(T,45e3))},A=(b,N="SESSION_ERROR")=>{s===t.generation&&(t.generation++,t.stopAttempt=null,w(),t.client.value=null,t.isStreaming.value=!1,t.sessionId.value=null,t.error.value=b,t.connectionStatus.value="error",t.dispatch?.(J.ERROR,{code:N,message:b}))},R=setTimeout(()=>A("Taking too long to connect. Check your network and try again.","STARTUP_TIMEOUT"),45e3);t.stopAttempt=w;try{if(a)m=a;else{if(!nn(e))throw new Error("Invalid agent ID format");const S=await fetch(`${i}/v1/auth/widget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:e}),signal:E.signal});if(s!==t.generation)return;if(c=S.status,!S.ok){const U=await S.json().catch(()=>({}));throw new Error(U.error||`HTTP ${S.status}`)}m=(await S.json()).sessionToken}if(s!==t.generation)return;const b=xr(m,{api:i?{baseUrl:i}:void 0,metrics:{disableClientMetrics:!0}});l=b,t.client.value=b,b.addListener(O.CONNECTION_ESTABLISHED,()=>{s===t.generation&&(t.connectionStatus.value="connected")}),b.addListener(O.AUDIO_STREAM_STARTED,()=>{}),b.addListener(O.MESSAGE_HISTORY_UPDATED,S=>{if(s!==t.generation)return;for(let q=t.prevMessageCount;q<S.length;q++){const X=S[q];t.dispatch?.(J.MESSAGE_RECEIVED,{role:X.role==="persona"?"agent":"user",content:X.content})}t.prevMessageCount=S.length;const k=$r(t,S),U=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});for(const q of k)t.messageTimes.has(q.id)||t.messageTimes.set(q.id,U);t.messages.value=k}),b.addListener(O.MESSAGE_STREAM_EVENT_RECEIVED,S=>{if(s!==t.generation)return;t.captionTimer&&(clearTimeout(t.captionTimer),t.captionTimer=null);const k=t.caption.value,U=S.role===Ee.PERSONA&&k?.id===S.id?k.content+S.content:S.content;t.caption.value={id:S.id,role:S.role,content:U,at:Date.now()},S.endOfSpeech&&(t.captionTimer=window.setTimeout(()=>{t.caption.value=null,t.captionTimer=null},4e3))}),b.addListener(O.TOOL_CALL_STARTED,S=>{if(s!==t.generation)return;t.dispatch?.(J.TOOL_CALL_STARTED,{toolName:S.toolName,toolCallId:S.toolCallId,toolType:S.toolType,toolSubtype:S.toolSubtype,arguments:S.arguments});const k=kr(S.toolName,S.toolCallId,S.arguments);k&&!t.seenToolCallIds.has(S.toolCallId)&&(t.seenToolCallIds.add(S.toolCallId),t.messageSeq.set(k.id,t.seqCounter++),t.messageTimes.set(k.id,new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})),t.toolBlocks.value=[...t.toolBlocks.value,k])}),b.addListener(O.TOOL_CALL_COMPLETED,S=>{s===t.generation&&t.dispatch?.(J.TOOL_CALL_COMPLETED,{toolName:S.toolName,toolCallId:S.toolCallId,toolType:S.toolType,toolSubtype:S.toolSubtype,result:S.result,executionTime:S.executionTime,documentsAccessed:S.documentsAccessed})}),b.addListener(O.TOOL_CALL_FAILED,S=>{s===t.generation&&t.dispatch?.(J.TOOL_CALL_FAILED,{toolName:S.toolName,toolCallId:S.toolCallId,toolType:S.toolType,toolSubtype:S.toolSubtype,errorMessage:S.errorMessage,executionTime:S.executionTime})}),b.addListener(O.CONNECTION_CLOSED,(S,k)=>{if(s!==t.generation)return;if(!t.isStreaming.value&&!on(S,k)){A("The connection ended before playback. Please try again.");return}const U=t.sessionId.value;t.generation++,t.stopAttempt=null,w(),t.client.value=null,t.connectionStatus.value="idle",t.isStreaming.value=!1,t.sessionId.value=null,t.timeLimitReached.value=on(S,k),t.dispatch?.(J.SESSION_ENDED,{sessionId:U??"",reason:k??S})}),b.addListener(O.SESSION_READY,S=>{s===t.generation&&(f=!0,t.sessionId.value=S,t.dispatch?.(J.SESSION_STARTED,{sessionId:S}))});const N=await b.stream();if(s!==t.generation){w();return}if(n&&N.length>0){const S=N.find(k=>k.getVideoTracks().length>0);if(S){if(n.srcObject=S,await n.play(),s!==t.generation)return;t.isStreaming.value=!0,clearTimeout(R)}}}catch(b){if(s!==t.generation){w();return}A(Br(b,c),c?`HTTP_${c}`:"SESSION_ERROR")}}async function jr(t){const e=t.sessionId.value,i=t.connectionStatus.value!=="idle";t.generation++;const n=t.stopAttempt;t.stopAttempt=null,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,t.timeLimitReached.value=!1,n?.(),i&&t.dispatch?.(J.SESSION_ENDED,{sessionId:e??"",reason:"USER_ENDED"})}function Gr(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:Ee.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:Ee.USER,content:e,at:Date.now()},t.sentCaptionTimer=window.setTimeout(()=>{t.sentCaption.value=null,t.sentCaptionTimer=null},4e3),t.dispatch?.(J.MESSAGE_SENT,{content:e})}function Hr(t){t.client.value&&(t.isMuted.value?(t.client.value.unmuteInputAudio(),t.isMuted.value=!1,t.dispatch?.(J.MIC_UNMUTED,{})):(t.client.value.muteInputAudio(),t.isMuted.value=!0,t.dispatch?.(J.MIC_MUTED,{})))}function zr(t){t.generation++,t.stopAttempt?.(),t.stopAttempt=null,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.timeLimitReached.value=!1,t.sessionId.value=null,t.avatarThumbnailUrl.value=null,t.avatarVideoUrl.value=null,t.personaName.value=null,t.serverConfig.value=null}function qr(t,e,i,n){const a=je();a.current||(a.current=Fr());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||Pr;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,timeLimitReached:s.timeLimitReached,sessionId:s.sessionId,isConfigured:s.isConfigured,isReady:s.isReady,avatarThumbnailUrl:s.avatarThumbnailUrl,avatarVideoUrl:s.avatarVideoUrl,personaName:s.personaName,serverConfig:s.serverConfig,fetchWidgetConfig:()=>{if(c){Vr(s,c,m);return}if(i){const p=rn(i).widgetConfig;p&&(typeof p.personaName=="string"&&p.personaName&&(s.personaName.value=p.personaName),typeof p.avatarImageUrl=="string"&&p.avatarImageUrl&&(s.avatarThumbnailUrl.value=p.avatarImageUrl),typeof p.avatarVideoUrl=="string"&&p.avatarVideoUrl&&(s.avatarVideoUrl.value=p.avatarVideoUrl),p.removeWatermark===!0&&(s.serverConfig.value={removeWatermark:!0})),s.isReady.value=!0;return}s.isReady.value=!0},startSession:f=>!c&&!i?(s.error.value="No agent ID or session token configured",Promise.resolve()):Wr(s,c||"",m,f,i),stopSession:()=>jr(s),sendMessage:f=>Gr(s,f),toggleMute:()=>Hr(s),cleanup:()=>zr(s)}}function Yr(t,e,i){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:i}))}const Kr='@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-ended-notice{z-index:2;box-sizing:border-box;color:#ffffffeb;text-align:center;background:#00000073;border-radius:999px;width:max-content;max-width:calc(100% - 32px);padding:6px 14px;font-size:14px;font-weight:500;position:absolute;bottom:84px;left:50%;transform:translate(-50%)}.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 Jr 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 Je(t){if(t!==void 0)return t==="true"}function Xr(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=Je(t["ui-mute-button"]);i!==void 0&&(e.showMuteButton=i);const n=Je(t["ui-text-input"]);n!==void 0&&(e.showTextInput=n);const a=Je(t["ui-captions"]);a!==void 0&&(e.showCaptions=a);const s=Je(t["ui-transcript"]);s!==void 0&&(e.showTranscript=s);const c=Je(t["ui-preview-video"]);return c!==void 0&&(e.showPreviewVideo=c),t["call-to-action"]&&(e.callToAction=t["call-to-action"]),e}const Zr=()=>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"})}),Qr=()=>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"})}),eo=()=>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"})]}),to=()=>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"})]}),io=()=>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"})]}),no=()=>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"})}),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:"M15 18l-6-6 6-6"})}),oo=()=>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 sn({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)??""})]}),Ur(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 so({config:t,session:e,videoRef:i,avatarSrc:n,avatarVideoSrc:a,displayCta:s,agentName:c,onCollapse:l,onStop:m,dispatch:f}){const p=je(null),[u,y]=St(""),E=e.connectionStatus.value==="connected",T=e.connectionStatus.value==="connecting",I=e.connectionStatus.value==="error",w=e.isStreaming.value,A=!T&&!E&&!I,R=E||w,b=t.orientation??"landscape",N=t.showTranscript&&R,[S,k]=St(!1),U=je(null),q=c||"Agent",X=Ge(()=>{const H=!S;k(H),f(H?J.TRANSCRIPT_OPENED:J.TRANSCRIPT_CLOSED,{})},[S,f]);Ie(()=>{R||k(!1)},[R]);const se=e.toolBlocks.value.length;Ie(()=>{se>0&&R&&N&&!S&&(k(!0),f(J.TRANSCRIPT_OPENED,{}))},[se]),Ie(()=>{S&&U.current&&(U.current.scrollTop=U.current.scrollHeight)},[S]),Ie(()=>{const H=U.current;if(!H||!S)return;H.scrollHeight-H.scrollTop-H.clientHeight<160&&(H.scrollTop=H.scrollHeight)},[e.messages.value,e.toolBlocks.value,S]);const Z=N&&S&&b==="landscape",ie=t.showCaptions?e.caption.value:null,Ce=e.sentCaption.value,Se=ie&&Ce?ie.at>=Ce.at?ie:Ce:ie??Ce,we=Ge(async()=>{i.current&&await e.startSession(i.current)},[e.startSession]),Re=Ge(()=>{u.trim()&&(e.sendMessage(u.trim()),y(""),p.current?.focus())},[u]),re=Ge(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Re())},[Re]),Vt=t.showTextInput?C("div",{class:"anam-ctl-input-wrap",children:[C("input",{ref:p,type:"text",class:"anam-ctl-input",placeholder:"Type a message...",value:u,onInput:H=>y(H.target.value),onKeyDown:re,disabled:!E}),C("button",{class:"anam-ctl-send",onClick:Re,disabled:!E||!u.trim(),"aria-label":"Send message",children:C(io,{})})]}):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(to,{}):C(eo,{})}),Vt,N&&b==="landscape"&&C("button",{class:"anam-ctl-btn anam-transcript-toggle",onClick:X,"aria-expanded":S,"aria-label":S?"Hide transcript":"Show transcript",children:C(no,{})})]});return C("div",{class:"anam-sheet","data-orientation":b,"data-transcript":S?"open":"closed",children:[N&&b==="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:X,"aria-label":"Hide transcript",children:C(ro,{})})]}),C(sn,{session:e,agentLabel:q,rowsRef:U})]})}),C("div",{class:"anam-video-region",children:[C("video",{ref:i,class:"anam-video",autoplay:!0,playsinline:!0,"data-hidden":w?void 0:"true"}),A&&(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:H=>{H.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"}),e.timeLimitReached.value&&C("div",{class:"anam-ended-notice",role:"status",children:"Session time limit reached"}),C("button",{class:"anam-cta-pill",onClick:we,children:[C(Qr,{}),s]})]}):C("div",{class:"anam-overlay-unconfigured",children:[C(Ft,{}),C("span",{children:"Agent not configured"})]})),T&&C("div",{class:"anam-overlay-loading",children:[C("span",{class:"anam-spinner"}),C("span",{children:"Starting your conversation..."})]}),I&&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||T||w))&&C("button",{class:"anam-close-btn",onClick:l||m,"aria-label":l?"Close":"End call",children:C(Zr,{})}),R&&C(fe,{children:[C("div",{class:"anam-scrim"}),Se&&C("div",{class:`anam-captions ${Se.role==="persona"?"anam-captions-agent":"anam-captions-user"}`,children:Se.content}),!Z&&dt,N&&b==="portrait"&&!S&&C("button",{class:"anam-transcript-tab",onClick:X,"aria-label":"Show transcript",children:C(oo,{})})]}),!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"})]})})]}),N&&b==="landscape"&&C("div",{class:"anam-transcript-pane",children:[C(sn,{session:e,agentLabel:q,rowsRef:U}),Z&&C("div",{class:"anam-transcript-footer",children:dt})]})]})}function ao(t){return C(fe,{children:[C("style",{children:Kr}),C(Jr,{children:C(lo,{...t})})]})}function lo(t){const e=je(null),i=je(null),n=Ge((b,N)=>{const S=i.current?.getRootNode();S&&S instanceof ShadowRoot&&Yr(S.host,b,N)},[]);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=qr(a,t["api-base-url"],t["session-token"],n);Ie(()=>()=>{s.cleanup()},[]);const c=Ne(()=>Xr(t),[t.layout,t["initial-state"],t.position,t["ui-mute-button"],t["ui-text-input"],t["ui-captions"],t["ui-transcript"],t["ui-preview-video"],t["call-to-action"]]),l=Ne(()=>{const b=s.serverConfig.value;return Bt(Bt({...wt},b??{}),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 f=t["avatar-url"]||s.avatarThumbnailUrl.value||null,p=l.showPreviewVideo&&(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,T=Ne(()=>{if(l.layout==="inline")return"";const b=Fn(l.position);return Object.entries(b).map(([N,S])=>`${N}: ${S}`).join("; ")},[l.layout,l.position]),I=l.layout==="floating",w=()=>{m.value="expanded",n(J.EXPANDED,{})},A=async()=>{s.connectionStatus.value!=="idle"&&await s.stopSession(),m.value="minimized",n(J.COLLAPSED,{})},R=I?m.value==="expanded":!0;return s.isReady.value?C("div",{ref:i,class:"anam-widget","data-layout":l.layout,"data-state":m.value,style:T,children:[I&&m.value==="minimized"&&C("button",{class:"anam-trigger",onClick:w,"aria-label":E,children:f?C("img",{src:f,alt:"Avatar"}):C(Ft,{})}),R&&C(so,{config:l,session:s,videoRef:e,avatarSrc:f,avatarVideoSrc:p,displayCta:E,agentName:y||null,onCollapse:I?A:null,onStop:I?null:()=>s.stopSession(),dispatch:n})]}):null}const co=["agent-id","api-base-url","session-token","layout","initial-state","position","ui-mute-button","ui-text-input","ui-captions","ui-transcript","ui-preview-video","call-to-action","avatar-url","avatar-video-url","agent-name"];function $t(t="anam-agent"){Tn(ao,t,[...co],{shadow:!0})}typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>$t()):$t()),he.DefaultConfig=wt,he.WidgetEventNames=J,he.registerWidget=$t,Object.defineProperty(he,Symbol.toStringTag,{value:"Module"})}));
