@telnyx/ai-agent-widget 0.31.1 → 0.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -111,4 +111,4 @@ var q_=Object.defineProperty;var K_=(Qe,G,Ot)=>G in Qe?q_(Qe,G,{enumerable:!0,co
111
111
  `),void this._requestAnotherLocalDescription();(i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),performance.mark("ice-gathering-end");let r=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${Su}`};switch(o){case Ee.Offer:this.setState(q.Requesting),r=new pu(a);break;case Ee.Answer:this.setState(q.Answering),r=this.options.attach===!0?new Jr(a):new mu(a);break;default:return M.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(r).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,o===Ee.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(l=>{M.error(`${this.id} - Sending ${o} error:`,l),this.hangup()}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return M.error("No SDP data provided"),this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const o={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${Su}`};switch(i){case Ee.Offer:this.setState(q.Requesting),s=new pu(o);break;case Ee.Answer:this.setState(q.Answering),s=this.options.attach===!0?new Jr(o):new mu(o);break;default:return M.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(s).then(r=>{const{node_id:a=null}=r;this._targetNodeId=a,i===Ee.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(r=>{M.error(`${this.id} - Sending ${i} error:`,r),this.hangup()}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),e.candidate?M.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(M.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new gu({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(n)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return M.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const n=this.peer.instance.addIceCandidate(e);Promise.resolve(n).then(()=>{M.debug("Successfully added ICE candidate:",e)}).catch(i=>{M.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Fy({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(n=>{this._addIceCandidateToPeer(n)})}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=n=>{this._iceDone||this._onIce(n)},e.onicecandidateerror=n=>{var i;if(M.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=_u(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&ni(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{M.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&M.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{var i;if(M.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=_u(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&ni(i,s)})}_onMediaError(e){this._dispatchNotification({type:nt.userMediaError,error:e}),M.error("Media error, hanging up call",e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:nt.peerConnectionFailureError,error:e}),M.error("Peer connection failure error, hanging up call",e),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:nt.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(Y(V.Notification,e,this.id,!1)||Y(V.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:n,remoteCallerNumber:i,onNotification:s}=this.options;var o;this.options.id=e?e.toString():yn(),this.id=this.options.id,n&&(o=n,Object.keys(o).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Wt(V.MediaError,this._onMediaError,this.id),Wt(V.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),_n(s)&&Wt(V.Notification,s.bind(this),this.id),this.setState(q.New),M.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;ii(n),ii(i),zt(V.MediaError,null,this.id),zt(V.PeerConnectionFailureError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),M.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),M.debug("Stats stopped")}}xu.setStateTelnyx=t=>{if(t){switch(t._state){case q.Requesting:case q.Recovering:case q.Trying:case q.Early:t.state="connecting";break;case q.Active:t.state="active";break;case q.Held:t.state="held";break;case q.Hangup:case q.Destroy:t.state="done";break;case q.Answering:t.state="ringing";break;case q.New:t.state="new"}return t}};class qt extends xu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new Uy(e,n))}hangup(e={},n=!0){this.screenShare instanceof qt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return j(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new qt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof qt&&this.screenShare.hangup()}setAudioOutDevice(e){return j(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&ru(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);M.setLevel(2),this._statsInterval=window.setInterval(()=>j(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];n.forEach(r=>{s.includes(r.type)||(i+=`
112
112
  ${r.type}
113
113
  `,Object.keys(r).forEach(a=>{o.includes(a)||(i+=` ${a}: ${r[a]}
114
- `)}))}),M.info(i)}),2e3)}}class Yy extends Ry{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return j(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return j(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return j(this,void 0,void 0,function*(){try{const i=yield qi({audio:e,video:n});return ii(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return j(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(q.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(eu(V.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return si().catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getVideoDevices(){return si(ht.Video).catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getAudioInDevices(){return si(ht.AudioIn).catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return si(ht.AudioOut).catch(e=>(M.error("getAudioOutDevices",e),Y(V.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Ki(e,n,i)}getDeviceResolutions(e){return j(this,void 0,void 0,function*(){try{return yield(n=>j(void 0,void 0,void 0,function*(){const i=[],s=yield qi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<ou.length;r++){const[a,l]=ou[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return ii(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return j(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=Gd(e,["micId","micLabel"]);return Ly(s),this._audioConstraints=yield((o,r,a,l)=>j(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield Ki(o,r,a).catch(u=>null);d&&(l.deviceId={exact:d})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?vy:gy}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Wi(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Wi(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new Vy({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new By({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Yr(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new jy({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Yr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(M.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this.socketDisconnect(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0,M.debug(`Network connectivity lost for session ${this.sessionid}`)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return qt.setStateTelnyx(e)}}class Cu{constructor(e,n){this.code=n,this.message=e}}class ku extends De{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=e,l={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Xi,data:navigator.userAgent}};r&&(l.sessid=r),s&&(l.target_version_id=s),this.buildRequest({method:this.method,params:l})}}const Zy=Xi;class xe{constructor(e){this.session=e,this.handleLogin=()=>j(this,void 0,void 0,function*(){const{login:n,password:i,passwd:s,login_token:o,userVariables:r}=this.session.options,a=new fu(n,i||s,o,this.session.sessionid,r,!!Ht()),l=yield this.session.execute(a).catch(this.session.handleLoginError);l&&(this.session.sessionid=l.sessid)}),this.handleAnonymousLogin=()=>j(this,void 0,void 0,function*(){const{anonymous_login:n}=this.session.options,i=new ku({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.session.sessionid,userVariables:this.session.options.userVariables,reconnection:!!Ht()}),s=yield this.session.execute(i).catch(this.session.handleLoginError);s&&(this.session.sessionid=s.sessid)})}_ack(e,n){const i=new Oy(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Zd(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,l=r==null?void 0:r.callID,c=r==null?void 0:r.eventChannel,d=r==null?void 0:r.eventType,u=o===ne.Attach,f=o===ne.Punt;let g=!1;if(d==="channelPvtData")return this._handlePvtEvent(r.pvtData);if(l&&i.calls.hasOwnProperty(l)){if(!u)return i.calls[l].handleMessage(e),void this._ack(s,o);g=(i.options.keepConnectionAliveOnSocketClose||i.calls[l].options.keepConnectionAliveOnSocketClose)&&!!(!((n=this.session.calls[l].peer)===null||n===void 0)&&n.instance),g?M.info(`[${new Date().toISOString()}][${l}] re-attaching call due to ATTACH and keepConnectionAliveOnSocketClose`):(M.info(`[${new Date().toISOString()}][${l}] Hanging up the call due to ATTACH`),i.calls[l].hangup({},!1))}if(f&&i.options.keepConnectionAliveOnSocketClose)return M.info(`[${new Date().toISOString()}][${l}] keeping call alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),this.session.socketDisconnect(),void this._ack(s,o);const _=()=>{var y,x,C,E,P,O;const S={id:l,audio:!0,video:i.options.video,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:u,mediaSettings:r.mediaSettings,debug:(y=i.options.debug)!==null&&y!==void 0&&y,debugOutput:(x=i.options.debugOutput)!==null&&x!==void 0?x:"socket",trickleIce:(C=i.options.trickleIce)!==null&&C!==void 0&&C,prefetchIceCandidates:(E=i.options.prefetchIceCandidates)!==null&&E!==void 0&&E,forceRelayCandidate:(P=i.options.forceRelayCandidate)!==null&&P!==void 0&&P,keepConnectionAliveOnSocketClose:(O=i.options.keepConnectionAliveOnSocketClose)!==null&&O!==void 0&&O};r.telnyx_call_control_id&&(S.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(S.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(S.telnyxLegId=r.telnyx_leg_id),r.client_state&&(S.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(S.customHeaders=r.dialogParams.custom_headers);const k=new qt(i,S);return k.nodeId=this.nodeId,k},v=new iu(a),b=new su(a);switch(o){case ne.Ping:this.session.setPingReceived(),this.session.execute(b).then(()=>{xe.receivedAuthenticationRequired=0}).catch(C=>j(this,void 0,void 0,function*(){C.code===this.session.authenticationRequiredErrorCode&&xe.receivedAuthenticationRequired>=0&&(xe.receivedAuthenticationRequired+=1,xe.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(M.warn("Ping failed twice with Authentication Required. Re-logging in..."),zi(this.session.options)?this.handleLogin():Qn(this.session.options)&&this.handleAnonymousLogin(),xe.receivedAuthenticationRequired=-1))}));break;case ne.Punt:i.disconnect();break;case ne.Invite:{const C=_();C.playRingtone(),C.setState(q.Ringing),C.direction=Rt.Inbound,this._ack(s,o);break}case ne.Attach:{if(g)return void this.session.execute(new Jr({sessid:this.session.sessionid,sdp:this.session.calls[l].peer.instance.localDescription.sdp,dialogParams:this.session.calls[l].options,"User-Agent":`Web-${Zy}`}));M.info(`[${new Date().toISOString()}][${l}] Re-creating call instance.`);const C=_();this.session.autoRecoverCalls?C.answer():C.setState(q.Recovering),C.handleMessage(e);break}case ne.Event:case"webrtc.event":if(!c)return void M.error("Verto received an unknown event:",r);const y=i.relayProtocol,x=c.split(".")[0];i._existsSubscription(y,c)?Y(y,r,c):c===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(y,x)?Y(y,r,x):i.calls.hasOwnProperty(c)?i.calls[c].handleMessage(e):Y(V.Notification,r,i.uuid);break;case ne.Info:r.type=nt.generic,Y(V.Notification,r,i.uuid);break;case ne.ClientReady:this.session.execute(v);break;default:{const C=Hr(e);if(C){switch(C){case Fe.REGISTER:case Fe.REGED:i.connection.previousGatewayState!==Fe.REGED&&i.connection.previousGatewayState!==Fe.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),xe.retriedRegister=0,r.type=nt.vertoClientReady,Y(V.Ready,r,i.uuid),i.options.trickleIce&&(M.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new gu({candidate:""})).catch(E=>{E.code===this.session.invalidMethodErrorCode?(M.warn("Trickle ICE is not supported by the server, disabling it."),M.debug("Trickle ICE check error:",JSON.stringify(E,null,2)),i.options.trickleIce=!1):M.debug("Trickle ICE check:",JSON.stringify(E,null,2))})));break;case Fe.UNREGED:case Fe.NOREG:if(xe.retriedRegister+=1,xe.retriedRegister===5){xe.retriedRegister=0,Y(V.Error,{error:new Cu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.execute(v)},this.reconnectDelay());break;case Fe.FAILED:case Fe.FAIL_WAIT:if(i.connection.previousGatewayState!==Fe.FAILED&&i.connection.previousGatewayState!==Fe.FAIL_WAIT){if(!this.session.hasAutoReconnect()){xe.retriedConnect=0,Y(V.Error,{error:new Cu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(xe.retriedConnect+=1,xe.retriedConnect===5){xe.retriedConnect=0,Y(V.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{if(M.debug(`Reconnecting... Retry ${xe.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose)return M.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),this.session.socketDisconnect(),void this.session.connect();this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:M.warn("GatewayState message unknown method:",e)}break}M.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return j(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:f}=e;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const y=f||this._retrieveCallId(b,o);if(y&&n.calls.hasOwnProperty(y)){const x=n.calls[y];x._addChannel(o),x.extension=r,x.handleConferenceUpdate(b,e).then(C=>{C==="INVALID_PACKET"&&g()})}}},v=yield n.vertoSubscribe(_).catch(b=>{M.error("liveArray subscription error:",b)});Xr(v,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(g=n.calls[v]||null,v!==null){const b={type:nt.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};Y(V.Notification,b,v,!1)||Y(V.Notification,b,n.uuid),g===null&&zt(V.Notification,null,v)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{g&&(g.channels=g.channels.filter(b=>!v.includes(b)))}).catch(v=>{M.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":bu(this.session,e);break;case"logo-info":{const n={type:nt.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};Y(V.Notification,n,this.session.uuid);break}}}}xe.retriedConnect=0,xe.retriedRegister=0,xe.receivedAuthenticationRequired=0;class Jy extends Yy{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:s,login_token:o,userVariables:r,autoReconnect:a=!0}=this.options,l=new fu(n,i||s,o,this.sessionid,r,!!Ht()),c=yield this.execute(l).catch(this._handleLoginError);c&&(this._autoReconnect=a,this.sessionid=c.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,i=new ku({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Ht()}),s=yield this.execute(i).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(M.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return zi(this.options)||Qn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const n=new qt(this,e);return n.invite(),performance.mark("new-call-end"),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Qn(this.options)||!!e.destinationNumber}_onSocketOpen(){return j(this,void 0,void 0,function*(){return zi(this.options)?this.handleLoginOnSocketOpen():Qn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new xe(this).handleMessage(e)}}class Qy extends Jy{constructor(e){super(e),M.info(`SDK version: ${hu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Dy()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ye.not_supported},{browserName:"Firefox",supported:ye.not_supported},{browserName:"Safari",features:["video","audio"],supported:ye.full},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",features:["video","audio"],supported:ye.full},{browserName:"Edge",features:["audio"],supported:ye.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",features:["audio"],supported:ye.partial}]}]}}function Tu(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Au={exports:{}},Eu;function e_(){return Eu||(Eu=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function o(l,c,d,u,f){if(typeof d!="function")throw new TypeError("The listener must be a function");var g=new s(d,u||l,f),_=n?n+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],g]:l._events[_].push(g):(l._events[_]=g,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)e.call(c,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,f=d.length,g=new Array(f);u<f;u++)g[u]=d[u].fn;return g},a.prototype.listenerCount=function(l){var c=n?n+l:l,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(l,c,d,u,f,g){var _=n?n+l:l;if(!this._events[_])return!1;var v=this._events[_],b=arguments.length,y,x;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,d),!0;case 4:return v.fn.call(v.context,c,d,u),!0;case 5:return v.fn.call(v.context,c,d,u,f),!0;case 6:return v.fn.call(v.context,c,d,u,f,g),!0}for(x=1,y=new Array(b-1);x<b;x++)y[x-1]=arguments[x];v.fn.apply(v.context,y)}else{var C=v.length,E;for(x=0;x<C;x++)switch(v[x].once&&this.removeListener(l,v[x].fn,void 0,!0),b){case 1:v[x].fn.call(v[x].context);break;case 2:v[x].fn.call(v[x].context,c);break;case 3:v[x].fn.call(v[x].context,c,d);break;case 4:v[x].fn.call(v[x].context,c,d,u);break;default:if(!y)for(E=1,y=new Array(b-1);E<b;E++)y[E-1]=arguments[E];v[x].fn.apply(v[x].context,y)}}return!0},a.prototype.on=function(l,c,d){return o(this,l,c,d,!1)},a.prototype.once=function(l,c,d){return o(this,l,c,d,!0)},a.prototype.removeListener=function(l,c,d,u){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return r(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!u||g.once)&&(!d||g.context===d)&&r(this,f);else{for(var _=0,v=[],b=g.length;_<b;_++)(g[_].fn!==c||u&&!g[_].once||d&&g[_].context!==d)&&v.push(g[_]);v.length?this._events[f]=v.length===1?v[0]:v:r(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&r(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(Au)),Au.exports}var t_=e_();const eo=Tu(t_),Zi=new eo;var to={exports:{}},n_=to.exports,Iu;function i_(){return Iu||(Iu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(n_,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function f(v,b,y){return c(v)||u.apply(this,arguments)}function g(v,b){var y=this,x,C,E,P="loglevel";typeof v=="string"?P+=":"+v:typeof v=="symbol"&&(P=void 0);function O(h){var w=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!P)){try{window.localStorage[P]=w;return}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+w+";"}catch{}}}function S(){var h;if(!(typeof window===n||!P)){try{h=window.localStorage[P]}catch{}if(typeof h===n)try{var w=window.document.cookie,T=encodeURIComponent(P),L=w.indexOf(T+"=");L!==-1&&(h=/^([^;]+)/.exec(w.slice(L+T.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function k(){if(!(typeof window===n||!P)){try{window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var w=h;if(typeof w=="string"&&y.levels[w.toUpperCase()]!==void 0&&(w=y.levels[w.toUpperCase()]),typeof w=="number"&&w>=0&&w<=y.levels.SILENT)return w;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||f,y.getLevel=function(){return E??C??x},y.setLevel=function(h,w){return E=p(h),w!==!1&&O(E),d.call(y)},y.setDefaultLevel=function(h){C=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){E=null,k(),d.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(r!==y&&(x=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},x=p(r?r.getLevel():"WARN");var m=S();m!=null&&(E=p(m)),d.call(y)}r=new g,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[v];return b||(b=o[v]=new g(v,r.methodFactory)),b};var _=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(to)),to.exports}var s_=i_();const r_=Tu(s_),o_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Ie=r_.getLogger("telnyx-ai-agent"),a_=Ie.methodFactory;Ie.methodFactory=(t,e,n)=>{const i=a_(t,e,n);return function(...s){i(o_(),"-",...s)}},Ie.setLevel("info");function l_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const c_=10,d_=500,u_=100,Ru=20;class h_{constructor(e){Q(this,"remoteIntervalId",null);Q(this,"localIntervalId",null);Q(this,"remoteStream",null);Q(this,"localStream",null);Q(this,"remoteAudioContext",null);Q(this,"remoteSource",null);Q(this,"remoteAnalyser",null);Q(this,"localAudioContext",null);Q(this,"localSource",null);Q(this,"localAnalyser",null);Q(this,"thinkingStartTime",null);Q(this,"lastState",null);Q(this,"userIsSpeaking",!1);Q(this,"lastUserAudioTime",null);Q(this,"userSpeechStartTime",null);Q(this,"userSilenceStartTime",null);Q(this,"isFirstAgentSpeech",!0);Q(this,"monitorStartTime",null);Q(this,"volumeThreshold");Q(this,"silenceDurationMs");Q(this,"minSpeechDurationMs");Q(this,"maxLatencyMs");Q(this,"updateAgentState",l_(e=>{Ie.debug("AudioStreamMonitor updateAgentState",e),Ie.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Zi.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??c_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??d_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??u_,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){Ie.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Ie.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Ie.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Ie.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const o=n.reduce((l,c)=>l+c,0)/n.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&Ie.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});i=r};this.remoteIntervalId=window.setInterval(s,Ru)}startLocalMonitor(){if(!this.localStream){Ie.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Ie.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Ie.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&Ie.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(n,Ru)}destroy(){this.stopAudioStreamMonitor()}}function f_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function p_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function m_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function g_(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}function v_(t){return p_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function y_(t){if(!m_(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class __ extends eo{constructor(n){super();Q(this,"telnyxRTC");Q(this,"transcript",[]);Q(this,"onSocketMessage",n=>{if(f_(n))switch(n.params.type){case"response.text.delta":{const i=v_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),Zi.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(g_(n)){const i=n.params.item_id,s=this.transcript.findIndex(o=>o.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=y_(n);if(i){const s=this.transcript.findIndex(o=>o.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(V.SocketMessage,this.onSocketMessage)}}class b_ extends eo{constructor(n){super();Q(this,"telnyxRTC");Q(this,"transcription");Q(this,"agentId");Q(this,"versionId");Q(this,"debug");Q(this,"audioStreamMonitor");Q(this,"activeCall");Q(this,"onClientReady",()=>{this.emit("agent.connected")});Q(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});Q(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});Q(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Q(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.debug=n.debug||!1,this.activeCall=null,Ie.setLevel(this.debug?"debug":"info"),this.telnyxRTC=new Qy({environment:n.environment||"production",anonymous_login:{target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId},debug:n.debug||!1,trickleIce:n.trickleIce}),this.telnyxRTC.on(V.Ready,this.onClientReady),this.telnyxRTC.on(V.Error,this.onClientOrSocketError),this.telnyxRTC.on(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(V.Notification,this.onNotification),this.transcription=new __(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Zi.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new h_(n.vad)}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(V.Ready,this.onClientReady),this.telnyxRTC.off(V.Error,this.onClientOrSocketError),this.telnyxRTC.off(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(V.Notification,this.onNotification),this.emit("agent.disconnected"),this.transcription.removeAllListeners(),Zi.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Ie.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,d;if(!this.telnyxRTC){Ie.error("Client is not initialized.");return}const i=(d=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:d.find(u=>u.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:o??!0,preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}}var Pu={exports:{}},ri={},Lu;function w_(){if(Lu)return ri;Lu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:i,key:r,ref:s!==void 0?s:null,props:o}}return ri.Fragment=e,ri.jsx=n,ri.jsxs=n,ri}var Mu;function S_(){return Mu||(Mu=1,Pu.exports=w_()),Pu.exports}S_(),vt(void 0),vt(null);const x_=(t,e,n,i,s,o)=>new b_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o}),C_=(t,e,n,i,s,o)=>{const[r,a]=Te(null),[l,c]=Te(!1),[d,u]=Te(null);return Pe(()=>{if(!t)return;const f=x_(t,e,n,i,s,o),g=()=>{c(!0),u(null)},_=()=>{c(!1)},v=b=>{u(b),Me.error("AI Agent error:",b)};return f.on("agent.connected",g),f.on("agent.disconnected",_),f.on("agent.error",v),f.connect(),a(f),()=>{f.off("agent.connected",g),f.off("agent.disconnected",_),f.off("agent.error",v),f.disconnect()}},[t,e,n,i,s,o]),{client:r,isConnected:l,error:d}},k_="telnyx-ai-agent",Kt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function Du(){const t=document.querySelector(k_);return t instanceof HTMLElement?t:null}function Xt(t,e,n){const i=n||Du();if(!i){Me.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Me.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const T_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=_e(null);Pe(()=>{r.current=Du()},[]),Pe(()=>{if(!t)return;const a=r.current,l=()=>{n(),Xt(Kt.AGENT_CONNECTED,void 0,a)},c=()=>{Xt(Kt.AGENT_DISCONNECTED,void 0,a)},d=x=>{s(x);const C={message:x.message,name:x.name};Xt(Kt.AGENT_ERROR,C,a)},u=x=>{var C;i(x),Xt(Kt.CONVERSATION_UPDATE,{type:x.type,callState:(C=x.call)==null?void 0:C.state},a)},f=x=>{Xt(Kt.TRANSCRIPT_ITEM,x,a)},g=x=>{Xt(Kt.CONVERSATION_AGENT_STATE,x,a)},_=x=>{Xt(Kt.AGENT_AUDIO_MUTE,{muted:x},a)},b=t.telnyxRTC,y=x=>{o(x)};return b&&typeof b=="object"&&b.on(V.SocketMessage,y),t.on("agent.connected",l),t.on("agent.disconnected",c),t.on("agent.error",d),t.on("conversation.update",u),t.on("transcript.item",f),t.on("conversation.agent.state",g),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",l),t.off("agent.disconnected",c),t.off("agent.error",d),t.off("conversation.update",u),t.off("transcript.item",f),t.off("conversation.agent.state",g),t.off("agent.audio.mute",_),b&&typeof b=="object"&&b.off(V.SocketMessage,y)}},[t,n,i,s,o])},A_=2e3;async function E_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Ou(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const I_=(t,e)=>{const[n,i]=Te([]),[,s]=Nr(),o=_e(e);Pe(()=>{o.current=e},[e]);const r=_e(void 0),a=_e(void 0);return Pe(()=>{if(!t)return;const c=f=>{i(g=>{const _=g[g.length-1];if(f.role==="assistant"&&_&&Ou(_.id)===Ou(f.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,y={..._,content:_.content+f.content,timestamp:f.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...g.slice(0,-1),y]}if(f.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const y={...f,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...g,y]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=g.findIndex(y=>y.id===f.id);if(v!==-1){const y=[...g];return y[v]={...g[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(_&&_.role==="user"&&f.timestamp.getTime()-_.timestamp.getTime()<A_){const x={..._,id:f.id,content:_.content+" "+f.content,timestamp:f.timestamp,attachments:[..._.attachments||[],...f.attachments||[]]};return[...g.slice(0,-1),x]}const b=f.attachments&&f.attachments.length>0;s(b?"processing_image":"thinking")}return[...g,f]})},d=({state:f,userPerceivedLatencyMs:g,greetingLatencyMs:_,thinkingStartedAt:v})=>{(g!==void 0||_!==void 0)&&Me.info(`[AgentState] state=${f} userPerceivedLatencyMs=${g} greetingLatencyMs=${_} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),_!==void 0&&(a.current=_)):f==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},u=f=>{var _;const g=(_=f.call)==null?void 0:_.state;(g==="destroy"||g==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",d),t.on("conversation.update",u),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",d),t.off("conversation.update",u)}},[t,s]),{transcript:n,sendMessage:async(c,d)=>{if(!t)return;const u=[];if(d&&d.length>0)for(const f of d)try{const g=await E_(f);u.push(g)}catch(g){throw Me.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,u)}}},R_=({call:t,client:e,latencySettings:n})=>{const i=Gt(),[s,o]=Te(i.default_state),r=()=>o("expanded"),a=()=>o("collapsed"),{transcript:l}=I_(e,n);switch(s){case"collapsed":return A(Ud,{onExpand:r,call:t,client:e});case"expanded":return A(fy,{transcript:l,onCollapse:a,call:t});default:return A(Ud,{onExpand:r,call:t,client:e})}},no=()=>A(Yn.div,{layoutId:Ni,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:A("div",{className:"rounded-full animate-spin",children:A(Hv,{})})}),P_=({call:t,client:e,latencySettings:n})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return A(no,{});case"done":case"purged":case"destroy":return null;case"active":return A(R_,{client:e,call:t,latencySettings:n});default:return A(no,{})}},L_=({className:t})=>A("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[A("g",{clipPath:"url(#:R5lfm:)",children:[A("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),A("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),A("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),A("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),A("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),A("defs",{children:A("clipPath",{id:":R5lfm:",children:A("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function M_(){const t=Gt();return t.logo_icon_url?A("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:A("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):A(L_,{className:"w-8 h-8 mr-2"})}const D_=({client:t,callProps:e})=>{const n=Gt(),i=()=>{if(!t){Me.error("Client is not initialized.");return}t.startConversation({...e})};return A(Yn.button,{layoutId:Ni,onClick:i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[A(M_,{}),n.start_call_text]})},O_='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@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-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@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;--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--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%;-moz-tab-size:4;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}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance: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 utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.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,visibility,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))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',N_=({children:t})=>A("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:A("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),F_={duration:.1,ease:"circOut"},V_=({children:t,position:e="fixed"})=>{const n=Gt(),s=(e??n.position??"fixed")==="fixed"?A(N_,{children:t}):t;return A("div",{className:bt(n.theme==="dark"&&"dark"),children:A(Op,{transition:F_,children:[A("style",{children:O_}),s]})})},B_=t=>A(Yn.div,{layoutId:Ni,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[A($v,{className:"w-8 h-8 text-red-400"}),A("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),A("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[A("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),A("li",{children:["Make sure that the"," ",A("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.agentId}?tab=telephony`,className:"inline-flex items-center gap-1 font-medium text-green-400 underline",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",A(Yv,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function Nu(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function j_({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":d,environment:u,position:f="fixed","version-id":g}){const _=qe(()=>{if(l)try{return JSON.parse(l)}catch(R){Me.error("Invalid JSON for vad attribute:",l,R);return}},[l]),v=qe(()=>({showUserPerceivedLatency:Nu(c),showGreetingLatency:Nu(d)}),[c,d]),{client:b}=C_(t,u,g,e,n,_),[y,x]=Te(null),[C,E]=Te(!1),[P,O]=Te(!1),[S,k]=Te(!1),p=xs(Bd),m=mv(),h={};if(i&&(h.destinationNumber=i),s&&(h.callerNumber=s),o&&(h.callerName=o),r)try{h.customHeaders=JSON.parse(r)}catch(R){Me.error("Invalid JSON for call-custom-headers attribute:",r,R)}if(a)try{h.audio=JSON.parse(a);const R=h.audio;if(typeof R=="object"){const N=navigator.mediaDevices.getSupportedConstraints();Object.keys(R).forEach(z=>{N[z]||Me.warn(`Audio constraint not supported by browser: ${z}`)})}}catch(R){Me.error("Invalid JSON for call-audio attribute:",a,R)}const w=kt(()=>{E(!1)},[]),T=kt(R=>{var N;if(((N=R.call)==null?void 0:N.state)==="destroy")return p(!1),x(null);x(R)},[p]),L=kt(()=>{E(!1),O(!0)},[]),I=kt(R=>{if(pv(R)){const N=R.params.widget_settings;N&&Object.keys(N).length>0&&(m(N),k(!0))}},[m]);return T_(b,{onReady:w,onConversationUpdate:T,onError:L,onConfigMessage:I}),A(V_,{position:f,children:t?P?A(B_,{agentId:t}):C?A(no,{}):y!=null&&y.call?A(P_,{call:y.call,client:b,latencySettings:v}):S?A(D_,{client:b,callProps:h}):null:A("div",{children:"Please provide an assistant ID."})})}Qu(j_,"telnyx-ai-agent",hv,{shadow:!0})})();
114
+ `)}))}),M.info(i)}),2e3)}}class Yy extends Ry{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return j(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return j(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return j(this,void 0,void 0,function*(){try{const i=yield qi({audio:e,video:n});return ii(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return j(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(q.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(eu(V.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return si().catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getVideoDevices(){return si(ht.Video).catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getAudioInDevices(){return si(ht.AudioIn).catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return si(ht.AudioOut).catch(e=>(M.error("getAudioOutDevices",e),Y(V.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Ki(e,n,i)}getDeviceResolutions(e){return j(this,void 0,void 0,function*(){try{return yield(n=>j(void 0,void 0,void 0,function*(){const i=[],s=yield qi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<ou.length;r++){const[a,l]=ou[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return ii(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return j(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=Gd(e,["micId","micLabel"]);return Ly(s),this._audioConstraints=yield((o,r,a,l)=>j(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield Ki(o,r,a).catch(u=>null);d&&(l.deviceId={exact:d})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?vy:gy}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Wi(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Wi(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new Vy({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new By({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Yr(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new jy({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Yr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(M.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this.socketDisconnect(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0,M.debug(`Network connectivity lost for session ${this.sessionid}`)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return qt.setStateTelnyx(e)}}class Cu{constructor(e,n){this.code=n,this.message=e}}class ku extends De{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=e,l={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Xi,data:navigator.userAgent}};r&&(l.sessid=r),s&&(l.target_version_id=s),this.buildRequest({method:this.method,params:l})}}const Zy=Xi;class xe{constructor(e){this.session=e,this.handleLogin=()=>j(this,void 0,void 0,function*(){const{login:n,password:i,passwd:s,login_token:o,userVariables:r}=this.session.options,a=new fu(n,i||s,o,this.session.sessionid,r,!!Ht()),l=yield this.session.execute(a).catch(this.session.handleLoginError);l&&(this.session.sessionid=l.sessid)}),this.handleAnonymousLogin=()=>j(this,void 0,void 0,function*(){const{anonymous_login:n}=this.session.options,i=new ku({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.session.sessionid,userVariables:this.session.options.userVariables,reconnection:!!Ht()}),s=yield this.session.execute(i).catch(this.session.handleLoginError);s&&(this.session.sessionid=s.sessid)})}_ack(e,n){const i=new Oy(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Zd(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,l=r==null?void 0:r.callID,c=r==null?void 0:r.eventChannel,d=r==null?void 0:r.eventType,u=o===ne.Attach,f=o===ne.Punt;let g=!1;if(d==="channelPvtData")return this._handlePvtEvent(r.pvtData);if(l&&i.calls.hasOwnProperty(l)){if(!u)return i.calls[l].handleMessage(e),void this._ack(s,o);g=(i.options.keepConnectionAliveOnSocketClose||i.calls[l].options.keepConnectionAliveOnSocketClose)&&!!(!((n=this.session.calls[l].peer)===null||n===void 0)&&n.instance),g?M.info(`[${new Date().toISOString()}][${l}] re-attaching call due to ATTACH and keepConnectionAliveOnSocketClose`):(M.info(`[${new Date().toISOString()}][${l}] Hanging up the call due to ATTACH`),i.calls[l].hangup({},!1))}if(f&&i.options.keepConnectionAliveOnSocketClose)return M.info(`[${new Date().toISOString()}][${l}] keeping call alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),this.session.socketDisconnect(),void this._ack(s,o);const _=()=>{var y,x,C,E,P,O;const S={id:l,audio:!0,video:i.options.video,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:u,mediaSettings:r.mediaSettings,debug:(y=i.options.debug)!==null&&y!==void 0&&y,debugOutput:(x=i.options.debugOutput)!==null&&x!==void 0?x:"socket",trickleIce:(C=i.options.trickleIce)!==null&&C!==void 0&&C,prefetchIceCandidates:(E=i.options.prefetchIceCandidates)!==null&&E!==void 0&&E,forceRelayCandidate:(P=i.options.forceRelayCandidate)!==null&&P!==void 0&&P,keepConnectionAliveOnSocketClose:(O=i.options.keepConnectionAliveOnSocketClose)!==null&&O!==void 0&&O};r.telnyx_call_control_id&&(S.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(S.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(S.telnyxLegId=r.telnyx_leg_id),r.client_state&&(S.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(S.customHeaders=r.dialogParams.custom_headers);const k=new qt(i,S);return k.nodeId=this.nodeId,k},v=new iu(a),b=new su(a);switch(o){case ne.Ping:this.session.setPingReceived(),this.session.execute(b).then(()=>{xe.receivedAuthenticationRequired=0}).catch(C=>j(this,void 0,void 0,function*(){C.code===this.session.authenticationRequiredErrorCode&&xe.receivedAuthenticationRequired>=0&&(xe.receivedAuthenticationRequired+=1,xe.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(M.warn("Ping failed twice with Authentication Required. Re-logging in..."),zi(this.session.options)?this.handleLogin():Qn(this.session.options)&&this.handleAnonymousLogin(),xe.receivedAuthenticationRequired=-1))}));break;case ne.Punt:i.disconnect();break;case ne.Invite:{const C=_();C.playRingtone(),C.setState(q.Ringing),C.direction=Rt.Inbound,this._ack(s,o);break}case ne.Attach:{if(g)return void this.session.execute(new Jr({sessid:this.session.sessionid,sdp:this.session.calls[l].peer.instance.localDescription.sdp,dialogParams:this.session.calls[l].options,"User-Agent":`Web-${Zy}`}));M.info(`[${new Date().toISOString()}][${l}] Re-creating call instance.`);const C=_();this.session.autoRecoverCalls?C.answer():C.setState(q.Recovering),C.handleMessage(e);break}case ne.Event:case"webrtc.event":if(!c)return void M.error("Verto received an unknown event:",r);const y=i.relayProtocol,x=c.split(".")[0];i._existsSubscription(y,c)?Y(y,r,c):c===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(y,x)?Y(y,r,x):i.calls.hasOwnProperty(c)?i.calls[c].handleMessage(e):Y(V.Notification,r,i.uuid);break;case ne.Info:r.type=nt.generic,Y(V.Notification,r,i.uuid);break;case ne.ClientReady:this.session.execute(v);break;default:{const C=Hr(e);if(C){switch(C){case Fe.REGISTER:case Fe.REGED:i.connection.previousGatewayState!==Fe.REGED&&i.connection.previousGatewayState!==Fe.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),xe.retriedRegister=0,r.type=nt.vertoClientReady,Y(V.Ready,r,i.uuid),i.options.trickleIce&&(M.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new gu({candidate:""})).catch(E=>{E.code===this.session.invalidMethodErrorCode?(M.warn("Trickle ICE is not supported by the server, disabling it."),M.debug("Trickle ICE check error:",JSON.stringify(E,null,2)),i.options.trickleIce=!1):M.debug("Trickle ICE check:",JSON.stringify(E,null,2))})));break;case Fe.UNREGED:case Fe.NOREG:if(xe.retriedRegister+=1,xe.retriedRegister===5){xe.retriedRegister=0,Y(V.Error,{error:new Cu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.execute(v)},this.reconnectDelay());break;case Fe.FAILED:case Fe.FAIL_WAIT:if(i.connection.previousGatewayState!==Fe.FAILED&&i.connection.previousGatewayState!==Fe.FAIL_WAIT){if(!this.session.hasAutoReconnect()){xe.retriedConnect=0,Y(V.Error,{error:new Cu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(xe.retriedConnect+=1,xe.retriedConnect===5){xe.retriedConnect=0,Y(V.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{if(M.debug(`Reconnecting... Retry ${xe.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose)return M.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),this.session.socketDisconnect(),void this.session.connect();this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:M.warn("GatewayState message unknown method:",e)}break}M.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return j(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:f}=e;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const y=f||this._retrieveCallId(b,o);if(y&&n.calls.hasOwnProperty(y)){const x=n.calls[y];x._addChannel(o),x.extension=r,x.handleConferenceUpdate(b,e).then(C=>{C==="INVALID_PACKET"&&g()})}}},v=yield n.vertoSubscribe(_).catch(b=>{M.error("liveArray subscription error:",b)});Xr(v,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(g=n.calls[v]||null,v!==null){const b={type:nt.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};Y(V.Notification,b,v,!1)||Y(V.Notification,b,n.uuid),g===null&&zt(V.Notification,null,v)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{g&&(g.channels=g.channels.filter(b=>!v.includes(b)))}).catch(v=>{M.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":bu(this.session,e);break;case"logo-info":{const n={type:nt.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};Y(V.Notification,n,this.session.uuid);break}}}}xe.retriedConnect=0,xe.retriedRegister=0,xe.receivedAuthenticationRequired=0;class Jy extends Yy{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:s,login_token:o,userVariables:r,autoReconnect:a=!0}=this.options,l=new fu(n,i||s,o,this.sessionid,r,!!Ht()),c=yield this.execute(l).catch(this._handleLoginError);c&&(this._autoReconnect=a,this.sessionid=c.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,i=new ku({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Ht()}),s=yield this.execute(i).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(M.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return zi(this.options)||Qn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const n=new qt(this,e);return n.invite(),performance.mark("new-call-end"),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Qn(this.options)||!!e.destinationNumber}_onSocketOpen(){return j(this,void 0,void 0,function*(){return zi(this.options)?this.handleLoginOnSocketOpen():Qn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new xe(this).handleMessage(e)}}class Qy extends Jy{constructor(e){super(e),M.info(`SDK version: ${hu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Dy()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ye.not_supported},{browserName:"Firefox",supported:ye.not_supported},{browserName:"Safari",features:["video","audio"],supported:ye.full},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",features:["video","audio"],supported:ye.full},{browserName:"Edge",features:["audio"],supported:ye.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",features:["audio"],supported:ye.partial}]}]}}function Tu(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Au={exports:{}},Eu;function e_(){return Eu||(Eu=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function o(l,c,d,u,f){if(typeof d!="function")throw new TypeError("The listener must be a function");var g=new s(d,u||l,f),_=n?n+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],g]:l._events[_].push(g):(l._events[_]=g,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)e.call(c,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,f=d.length,g=new Array(f);u<f;u++)g[u]=d[u].fn;return g},a.prototype.listenerCount=function(l){var c=n?n+l:l,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(l,c,d,u,f,g){var _=n?n+l:l;if(!this._events[_])return!1;var v=this._events[_],b=arguments.length,y,x;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,d),!0;case 4:return v.fn.call(v.context,c,d,u),!0;case 5:return v.fn.call(v.context,c,d,u,f),!0;case 6:return v.fn.call(v.context,c,d,u,f,g),!0}for(x=1,y=new Array(b-1);x<b;x++)y[x-1]=arguments[x];v.fn.apply(v.context,y)}else{var C=v.length,E;for(x=0;x<C;x++)switch(v[x].once&&this.removeListener(l,v[x].fn,void 0,!0),b){case 1:v[x].fn.call(v[x].context);break;case 2:v[x].fn.call(v[x].context,c);break;case 3:v[x].fn.call(v[x].context,c,d);break;case 4:v[x].fn.call(v[x].context,c,d,u);break;default:if(!y)for(E=1,y=new Array(b-1);E<b;E++)y[E-1]=arguments[E];v[x].fn.apply(v[x].context,y)}}return!0},a.prototype.on=function(l,c,d){return o(this,l,c,d,!1)},a.prototype.once=function(l,c,d){return o(this,l,c,d,!0)},a.prototype.removeListener=function(l,c,d,u){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return r(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!u||g.once)&&(!d||g.context===d)&&r(this,f);else{for(var _=0,v=[],b=g.length;_<b;_++)(g[_].fn!==c||u&&!g[_].once||d&&g[_].context!==d)&&v.push(g[_]);v.length?this._events[f]=v.length===1?v[0]:v:r(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&r(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(Au)),Au.exports}var t_=e_();const eo=Tu(t_),Zi=new eo;var to={exports:{}},n_=to.exports,Iu;function i_(){return Iu||(Iu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(n_,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function f(v,b,y){return c(v)||u.apply(this,arguments)}function g(v,b){var y=this,x,C,E,P="loglevel";typeof v=="string"?P+=":"+v:typeof v=="symbol"&&(P=void 0);function O(h){var w=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!P)){try{window.localStorage[P]=w;return}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+w+";"}catch{}}}function S(){var h;if(!(typeof window===n||!P)){try{h=window.localStorage[P]}catch{}if(typeof h===n)try{var w=window.document.cookie,T=encodeURIComponent(P),L=w.indexOf(T+"=");L!==-1&&(h=/^([^;]+)/.exec(w.slice(L+T.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function k(){if(!(typeof window===n||!P)){try{window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var w=h;if(typeof w=="string"&&y.levels[w.toUpperCase()]!==void 0&&(w=y.levels[w.toUpperCase()]),typeof w=="number"&&w>=0&&w<=y.levels.SILENT)return w;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||f,y.getLevel=function(){return E??C??x},y.setLevel=function(h,w){return E=p(h),w!==!1&&O(E),d.call(y)},y.setDefaultLevel=function(h){C=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){E=null,k(),d.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(r!==y&&(x=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},x=p(r?r.getLevel():"WARN");var m=S();m!=null&&(E=p(m)),d.call(y)}r=new g,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[v];return b||(b=o[v]=new g(v,r.methodFactory)),b};var _=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(to)),to.exports}var s_=i_();const r_=Tu(s_),o_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Ie=r_.getLogger("telnyx-ai-agent"),a_=Ie.methodFactory;Ie.methodFactory=(t,e,n)=>{const i=a_(t,e,n);return function(...s){i(o_(),"-",...s)}},Ie.setLevel("info");function l_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const c_=10,d_=500,u_=100,Ru=20;class h_{constructor(e){Q(this,"remoteIntervalId",null);Q(this,"localIntervalId",null);Q(this,"remoteStream",null);Q(this,"localStream",null);Q(this,"remoteAudioContext",null);Q(this,"remoteSource",null);Q(this,"remoteAnalyser",null);Q(this,"localAudioContext",null);Q(this,"localSource",null);Q(this,"localAnalyser",null);Q(this,"thinkingStartTime",null);Q(this,"lastState",null);Q(this,"userIsSpeaking",!1);Q(this,"lastUserAudioTime",null);Q(this,"userSpeechStartTime",null);Q(this,"userSilenceStartTime",null);Q(this,"isFirstAgentSpeech",!0);Q(this,"monitorStartTime",null);Q(this,"volumeThreshold");Q(this,"silenceDurationMs");Q(this,"minSpeechDurationMs");Q(this,"maxLatencyMs");Q(this,"updateAgentState",l_(e=>{Ie.debug("AudioStreamMonitor updateAgentState",e),Ie.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Zi.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??c_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??d_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??u_,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){Ie.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Ie.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Ie.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Ie.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const o=n.reduce((l,c)=>l+c,0)/n.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&Ie.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});i=r};this.remoteIntervalId=window.setInterval(s,Ru)}startLocalMonitor(){if(!this.localStream){Ie.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Ie.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Ie.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&Ie.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(n,Ru)}destroy(){this.stopAudioStreamMonitor()}}function f_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function p_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function m_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function g_(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}function v_(t){return p_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function y_(t){if(!m_(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class __ extends eo{constructor(n){super();Q(this,"telnyxRTC");Q(this,"transcript",[]);Q(this,"onSocketMessage",n=>{if(f_(n))switch(n.params.type){case"response.text.delta":{const i=v_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),Zi.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(g_(n)){const i=n.params.item_id,s=this.transcript.findIndex(o=>o.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=y_(n);if(i){const s=this.transcript.findIndex(o=>o.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(V.SocketMessage,this.onSocketMessage)}}class b_ extends eo{constructor(n){super();Q(this,"telnyxRTC");Q(this,"transcription");Q(this,"agentId");Q(this,"versionId");Q(this,"debug");Q(this,"audioStreamMonitor");Q(this,"activeCall");Q(this,"onClientReady",()=>{this.emit("agent.connected")});Q(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});Q(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});Q(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Q(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.debug=n.debug||!1,this.activeCall=null,Ie.setLevel(this.debug?"debug":"info"),this.telnyxRTC=new Qy({env:n.environment||"production",anonymous_login:{target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId},debug:n.debug||!1,trickleIce:n.trickleIce}),this.telnyxRTC.on(V.Ready,this.onClientReady),this.telnyxRTC.on(V.Error,this.onClientOrSocketError),this.telnyxRTC.on(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(V.Notification,this.onNotification),this.transcription=new __(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Zi.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new h_(n.vad)}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(V.Ready,this.onClientReady),this.telnyxRTC.off(V.Error,this.onClientOrSocketError),this.telnyxRTC.off(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(V.Notification,this.onNotification),this.emit("agent.disconnected"),this.transcription.removeAllListeners(),Zi.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Ie.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,d;if(!this.telnyxRTC){Ie.error("Client is not initialized.");return}const i=(d=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:d.find(u=>u.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:o??!0,preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}}var Pu={exports:{}},ri={},Lu;function w_(){if(Lu)return ri;Lu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:i,key:r,ref:s!==void 0?s:null,props:o}}return ri.Fragment=e,ri.jsx=n,ri.jsxs=n,ri}var Mu;function S_(){return Mu||(Mu=1,Pu.exports=w_()),Pu.exports}S_(),vt(void 0),vt(null);const x_=(t,e,n,i,s,o)=>new b_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o}),C_=(t,e,n,i,s,o)=>{const[r,a]=Te(null),[l,c]=Te(!1),[d,u]=Te(null);return Pe(()=>{if(!t)return;const f=x_(t,e,n,i,s,o),g=()=>{c(!0),u(null)},_=()=>{c(!1)},v=b=>{u(b),Me.error("AI Agent error:",b)};return f.on("agent.connected",g),f.on("agent.disconnected",_),f.on("agent.error",v),f.connect(),a(f),()=>{f.off("agent.connected",g),f.off("agent.disconnected",_),f.off("agent.error",v),f.disconnect()}},[t,e,n,i,s,o]),{client:r,isConnected:l,error:d}},k_="telnyx-ai-agent",Kt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function Du(){const t=document.querySelector(k_);return t instanceof HTMLElement?t:null}function Xt(t,e,n){const i=n||Du();if(!i){Me.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Me.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const T_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=_e(null);Pe(()=>{r.current=Du()},[]),Pe(()=>{if(!t)return;const a=r.current,l=()=>{n(),Xt(Kt.AGENT_CONNECTED,void 0,a)},c=()=>{Xt(Kt.AGENT_DISCONNECTED,void 0,a)},d=x=>{s(x);const C={message:x.message,name:x.name};Xt(Kt.AGENT_ERROR,C,a)},u=x=>{var C;i(x),Xt(Kt.CONVERSATION_UPDATE,{type:x.type,callState:(C=x.call)==null?void 0:C.state},a)},f=x=>{Xt(Kt.TRANSCRIPT_ITEM,x,a)},g=x=>{Xt(Kt.CONVERSATION_AGENT_STATE,x,a)},_=x=>{Xt(Kt.AGENT_AUDIO_MUTE,{muted:x},a)},b=t.telnyxRTC,y=x=>{o(x)};return b&&typeof b=="object"&&b.on(V.SocketMessage,y),t.on("agent.connected",l),t.on("agent.disconnected",c),t.on("agent.error",d),t.on("conversation.update",u),t.on("transcript.item",f),t.on("conversation.agent.state",g),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",l),t.off("agent.disconnected",c),t.off("agent.error",d),t.off("conversation.update",u),t.off("transcript.item",f),t.off("conversation.agent.state",g),t.off("agent.audio.mute",_),b&&typeof b=="object"&&b.off(V.SocketMessage,y)}},[t,n,i,s,o])},A_=2e3;async function E_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Ou(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const I_=(t,e)=>{const[n,i]=Te([]),[,s]=Nr(),o=_e(e);Pe(()=>{o.current=e},[e]);const r=_e(void 0),a=_e(void 0);return Pe(()=>{if(!t)return;const c=f=>{i(g=>{const _=g[g.length-1];if(f.role==="assistant"&&_&&Ou(_.id)===Ou(f.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,y={..._,content:_.content+f.content,timestamp:f.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...g.slice(0,-1),y]}if(f.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const y={...f,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...g,y]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=g.findIndex(y=>y.id===f.id);if(v!==-1){const y=[...g];return y[v]={...g[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(_&&_.role==="user"&&f.timestamp.getTime()-_.timestamp.getTime()<A_){const x={..._,id:f.id,content:_.content+" "+f.content,timestamp:f.timestamp,attachments:[..._.attachments||[],...f.attachments||[]]};return[...g.slice(0,-1),x]}const b=f.attachments&&f.attachments.length>0;s(b?"processing_image":"thinking")}return[...g,f]})},d=({state:f,userPerceivedLatencyMs:g,greetingLatencyMs:_,thinkingStartedAt:v})=>{(g!==void 0||_!==void 0)&&Me.info(`[AgentState] state=${f} userPerceivedLatencyMs=${g} greetingLatencyMs=${_} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),_!==void 0&&(a.current=_)):f==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},u=f=>{var _;const g=(_=f.call)==null?void 0:_.state;(g==="destroy"||g==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",d),t.on("conversation.update",u),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",d),t.off("conversation.update",u)}},[t,s]),{transcript:n,sendMessage:async(c,d)=>{if(!t)return;const u=[];if(d&&d.length>0)for(const f of d)try{const g=await E_(f);u.push(g)}catch(g){throw Me.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,u)}}},R_=({call:t,client:e,latencySettings:n})=>{const i=Gt(),[s,o]=Te(i.default_state),r=()=>o("expanded"),a=()=>o("collapsed"),{transcript:l}=I_(e,n);switch(s){case"collapsed":return A(Ud,{onExpand:r,call:t,client:e});case"expanded":return A(fy,{transcript:l,onCollapse:a,call:t});default:return A(Ud,{onExpand:r,call:t,client:e})}},no=()=>A(Yn.div,{layoutId:Ni,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:A("div",{className:"rounded-full animate-spin",children:A(Hv,{})})}),P_=({call:t,client:e,latencySettings:n})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return A(no,{});case"done":case"purged":case"destroy":return null;case"active":return A(R_,{client:e,call:t,latencySettings:n});default:return A(no,{})}},L_=({className:t})=>A("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[A("g",{clipPath:"url(#:R5lfm:)",children:[A("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),A("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),A("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),A("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),A("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),A("defs",{children:A("clipPath",{id:":R5lfm:",children:A("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function M_(){const t=Gt();return t.logo_icon_url?A("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:A("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):A(L_,{className:"w-8 h-8 mr-2"})}const D_=({client:t,callProps:e})=>{const n=Gt(),i=()=>{if(!t){Me.error("Client is not initialized.");return}t.startConversation({...e})};return A(Yn.button,{layoutId:Ni,onClick:i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[A(M_,{}),n.start_call_text]})},O_='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@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-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@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;--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--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%;-moz-tab-size:4;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}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance: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 utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.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,visibility,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))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',N_=({children:t})=>A("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:A("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),F_={duration:.1,ease:"circOut"},V_=({children:t,position:e="fixed"})=>{const n=Gt(),s=(e??n.position??"fixed")==="fixed"?A(N_,{children:t}):t;return A("div",{className:bt(n.theme==="dark"&&"dark"),children:A(Op,{transition:F_,children:[A("style",{children:O_}),s]})})},B_=t=>A(Yn.div,{layoutId:Ni,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[A($v,{className:"w-8 h-8 text-red-400"}),A("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),A("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[A("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),A("li",{children:["Make sure that the"," ",A("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.agentId}?tab=telephony`,className:"inline-flex items-center gap-1 font-medium text-green-400 underline",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",A(Yv,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function Nu(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function j_({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":d,environment:u,position:f="fixed","version-id":g}){const _=qe(()=>{if(l)try{return JSON.parse(l)}catch(R){Me.error("Invalid JSON for vad attribute:",l,R);return}},[l]),v=qe(()=>({showUserPerceivedLatency:Nu(c),showGreetingLatency:Nu(d)}),[c,d]),{client:b}=C_(t,u,g,e,n,_),[y,x]=Te(null),[C,E]=Te(!1),[P,O]=Te(!1),[S,k]=Te(!1),p=xs(Bd),m=mv(),h={};if(i&&(h.destinationNumber=i),s&&(h.callerNumber=s),o&&(h.callerName=o),r)try{h.customHeaders=JSON.parse(r)}catch(R){Me.error("Invalid JSON for call-custom-headers attribute:",r,R)}if(a)try{h.audio=JSON.parse(a);const R=h.audio;if(typeof R=="object"){const N=navigator.mediaDevices.getSupportedConstraints();Object.keys(R).forEach(z=>{N[z]||Me.warn(`Audio constraint not supported by browser: ${z}`)})}}catch(R){Me.error("Invalid JSON for call-audio attribute:",a,R)}const w=kt(()=>{E(!1)},[]),T=kt(R=>{var N;if(((N=R.call)==null?void 0:N.state)==="destroy")return p(!1),x(null);x(R)},[p]),L=kt(()=>{E(!1),O(!0)},[]),I=kt(R=>{if(pv(R)){const N=R.params.widget_settings;N&&Object.keys(N).length>0&&(m(N),k(!0))}},[m]);return T_(b,{onReady:w,onConversationUpdate:T,onError:L,onConfigMessage:I}),A(V_,{position:f,children:t?P?A(B_,{agentId:t}):C?A(no,{}):y!=null&&y.call?A(P_,{call:y.call,client:b,latencySettings:v}):S?A(D_,{client:b,callProps:h}):null:A("div",{children:"Please provide an assistant ID."})})}Qu(j_,"telnyx-ai-agent",hv,{shadow:!0})})();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@telnyx/ai-agent-widget",
3
3
  "private": false,
4
- "version": "0.31.1",
4
+ "version": "0.31.2",
5
5
  "description": "A widget for Telnyx AI Agent",
6
6
  "type": "module",
7
7
  "author": "Telnyx",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@fontsource/inter": "^5.2.6",
24
- "@telnyx/ai-agent-lib": "^0.2.11",
24
+ "@telnyx/ai-agent-lib": "^0.2.12",
25
25
  "audiomotion-analyzer": "^4.5.1",
26
26
  "clsx": "^2.1.1",
27
27
  "jotai": "^2.12.5",