@telnyx/ai-agent-widget 0.32.1-beta.4 → 0.32.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle.min.js +1 -1
- package/package.json +1 -1
package/dist/bundle.min.js
CHANGED
|
@@ -111,4 +111,4 @@ var s0=Object.defineProperty;var r0=(Qe,G,Ft)=>G in Qe?s0(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-${es}`};switch(o){case Ie.Offer:this.setState(q.Requesting),r=new gu(a);break;case Ie.Answer:this._isRecovering||this.setState(q.Answering),r=this.options.attach===!0?new vu(a):new mu(a);break;default:return T.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===Ie.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(l=>{T.error(`${this.id} - Sending ${o} error:`,l),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return T.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-${es}`};switch(i){case Ie.Offer:this.setState(q.Requesting),s=new gu(o);break;case Ie.Answer:this._isRecovering||this.setState(q.Answering),s=this.options.attach===!0?new vu(o):new mu(o);break;default:return T.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===Ie.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(r=>{T.error(`${this.id} - Sending ${i} error:`,r),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;if(this._iceTimeout===null){const i=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),i)}e.candidate?T.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(T.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new $y({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 T.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(()=>{T.debug("Successfully added ICE candidate:",e)}).catch(i=>{T.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Hy({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(T.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Au(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&&ii(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{T.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&T.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{var i;if(T.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Au(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&&ii(i,s)})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error";this._dispatchNotification({type:Je.userMediaError,error:e,call:this,errorName:n,errorMessage:i}),T.error(`Media error (${n}): ${i}`,e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Je.peerConnectionFailureError,error:e}),T.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Je.signalingStateClosed},e)),T.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Je.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(K(V.Notification,e,this.id,!1)||K(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():_n(),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,Lt(V.MediaError,this._onMediaError,this.id),Lt(V.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Lt(V.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),bn(s)&&Lt(V.Notification,s.bind(this),this.id);const r=this.session.options.enableCallReports!==!1,a=this.session.options.callReportInterval||5e3,l=this.session.options.debugLogLevel||"debug",c=this.session.options.debugLogMaxEntries||1e3;r&&(this._callReportCollector=new xt({enabled:!0,interval:a},{enabled:!0,level:l,maxEntries:c}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()}),this._isRecovering?this.setState(q.Recovering):this.setState(q.New),T.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),T.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;si(n),si(i),Pt(V.MediaError,null,this.id),Pt(V.PeerConnectionFailureError,null,this.id),Pt(V.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch(s=>{T.error("Unexpected error in _postCallReport",{error:s})})}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void T.debug("Cannot flush intermediate report: call_report_id not available");const i=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!i)return void T.debug("Cannot flush intermediate report: connection host not available");const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===ut.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:es},o=this._callReportCollector.flush(s);if(!o)return;const r=zt()||void 0;this._callReportCollector.sendPayload(o,n,i,r).catch(a=>{T.error("Failed to post intermediate call report segment",{error:a})})}_postCallReport(){var e;return B(this,void 0,void 0,function*(){if(!this._callReportCollector)return void T.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return T.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===ut.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:es},s=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!s)return void T.error("Cannot post call report: connection host not available");const o=zt()||void 0;this._callReportCollector.postReport(i,n,s,o).catch(r=>{T.error("Failed to post call report",{error:r})}).finally(()=>{var r;(r=this._callReportCollector)===null||r===void 0||r.cleanup()})})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),T.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),T.debug("Stats stopped")}}Lu.setStateTelnyx=t=>{if(t){switch(t._state){case q.Recovering:t.state="recovering";break;case q.Requesting: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 Lu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new Qy(e,n))}hangup(e={},n=!0){this.screenShare instanceof qt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return B(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 B(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&_u(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>B(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
|
-
`)}))}),T.info(i)}),2e3)}}class l_ extends Ky{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 B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return B(this,void 0,void 0,function*(){try{const i=yield Ji({audio:e,video:n});return si(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(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(lu(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 ri().catch(e=>(K(V.MediaError,e,this.uuid),[]))}getVideoDevices(){return ri(ht.Video).catch(e=>(K(V.MediaError,e,this.uuid),[]))}getAudioInDevices(){return ri(ht.AudioIn).catch(e=>(K(V.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return ri(ht.AudioOut).catch(e=>(T.error("getAudioOutDevices",e),K(V.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Zi(e,n,i)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(n=>B(void 0,void 0,void 0,function*(){const i=[],s=yield Ji({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<bu.length;r++){const[a,l]=bu[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 si(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(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=Gi(e,["micId","micLabel"]);return Yy(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield Zi(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?ky:xy}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Ki(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Ki(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 Gy({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 B(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Wy({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=to(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 B(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new zy({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=to(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&&(T.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,T.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 Pu{constructor(e,n){this.code=n,this.message=e}}class c_{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0,this.receivedAuthenticationRequired=0}_ack(e,n){const i=new jy(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*ru(2,6)}handleMessage(e){var n,i,s;const{session:o}=this,{id:r,method:a,params:l={},voice_sdk_id:c}=e,d=l==null?void 0:l.callID,u=l==null?void 0:l.eventChannel,f=l==null?void 0:l.eventType,m=o.calls[d],y=(n=m==null?void 0:m.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(f==="channelPvtData")return this._handlePvtEvent(l.pvtData);const v=(C=!1)=>{var k,E,R,O,S,x;const p={audio:!0,video:o.options.video,remoteSdp:l.sdp,destinationNumber:l.callee_id_number,remoteCallerName:l.caller_id_name,remoteCallerNumber:l.caller_id_number,callerName:l.callee_id_name,callerNumber:l.callee_id_number,attach:a===Q.Attach,mediaSettings:l.mediaSettings,debug:(k=o.options.debug)!==null&&k!==void 0&&k,debugOutput:(E=o.options.debugOutput)!==null&&E!==void 0?E:"socket",trickleIce:a!==Q.Attach&&(R=o.options.trickleIce)!==null&&R!==void 0&&R,prefetchIceCandidates:(O=o.options.prefetchIceCandidates)===null||O===void 0||O,forceRelayCandidate:(S=o.options.forceRelayCandidate)!==null&&S!==void 0&&S,keepConnectionAliveOnSocketClose:(x=o.options.keepConnectionAliveOnSocketClose)!==null&&x!==void 0&&x};d&&(p.id=d),l.telnyx_call_control_id&&(p.telnyxCallControlId=l.telnyx_call_control_id),l.telnyx_session_id&&(p.telnyxSessionId=l.telnyx_session_id),l.telnyx_leg_id&&(p.telnyxLegId=l.telnyx_leg_id),l.client_state&&(p.clientState=l.client_state),l.dialogParams&&l.dialogParams.custom_headers&&l.dialogParams.custom_headers.length&&(p.customHeaders=l.dialogParams.custom_headers);const g=new qt(o,p,C);return g.nodeId=this.nodeId,g},w=new hu(c),_=new fu(c);switch(a){case Q.Answer:case Q.Display:case Q.Candidate:case Q.Ringing:case Q.Bye:case Q.Media:if(!d||!m)return void T.error(`Received ${a} for non existing call:`,l);m.handleMessage(e),this._ack(r,a);break;case Q.Ping:this.session.setPingReceived(),this.session.execute(_).then(()=>{this.receivedAuthenticationRequired=0}).catch(E=>B(this,void 0,void 0,function*(){E.code===this.session.authenticationRequiredErrorCode&&this.receivedAuthenticationRequired>=0&&(this.receivedAuthenticationRequired+=1,this.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(T.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),this.receivedAuthenticationRequired=-1))}));break;case Q.Punt:o.options.keepConnectionAliveOnSocketClose&&y?(T.info(`[${new Date().toISOString()}][${d}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),o.socketDisconnect(),this._ack(r,a)):o.disconnect();break;case Q.Invite:{const E=v();E.direction=ut.Inbound,E.playRingtone(),E.setState(q.Ringing),this._ack(r,a);break}case Q.Attach:{if(!m)return v().answer(),void this._ack(r,a);const E=!!m;T.info(`[${new Date().toISOString()}][${d}] closing existing call on ATTACH.`),m.hangup({isRecovering:E},!1),T.info(`[${new Date().toISOString()}][${d}] Attach: Creating new call for recovery`),v(E).answer(),this._ack(r,a);break}case Q.Event:case"webrtc.event":if(!u)return void T.error("Verto received an unknown event:",l);const C=o.relayProtocol,k=u.split(".")[0];o._existsSubscription(C,u)?K(C,l,u):u===o.sessionid?this._handleSessionEvent(l.eventData):o._existsSubscription(C,k)?K(C,l,k):o.calls.hasOwnProperty(u)?o.calls[u].handleMessage(e):K(V.Notification,l,o.uuid);break;case Q.Info:l.type=Je.generic,K(V.Notification,l,o.uuid);break;case Q.ClientReady:this.session.execute(w);break;default:{const E=Kr(e);if(E){switch(E){case Ne.REGISTER:case Ne.REGED:if(o.connection.previousGatewayState!==Ne.REGED&&o.connection.previousGatewayState!==Ne.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const R=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;R&&(o.callReportId=R,T.debug("Captured call_report_id from REGED:",R)),l.type=Je.vertoClientReady,K(V.Ready,l,o.uuid)}break;case Ne.UNREGED:case Ne.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0,K(V.Error,{error:new Pu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{this.session.execute(w)},this.reconnectDelay());break;case Ne.FAILED:case Ne.FAIL_WAIT:if(o.connection.previousGatewayState!==Ne.FAILED&&o.connection.previousGatewayState!==Ne.FAIL_WAIT){if(!this.session.hasAutoReconnect()){this.retriedConnect=0,K(V.Error,{error:new Pu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:o.sessionid},o.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,K(V.Error,{error:new Error("Connection Retry Failed"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{if(T.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(o.calls).some(R=>{var O;return((O=R.peer)===null||O===void 0?void 0:O.instance)&&!R.signalingStateClosed}))return T.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();T.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:T.warn("GatewayState message unknown method:",e)}break}T.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 B(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 m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},y={nodeId:this.nodeId,channels:[o],handler:({data:w})=>{const _=f||this._retrieveCallId(w,o);if(_&&n.calls.hasOwnProperty(_)){const C=n.calls[_];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(w,e).then(k=>{k==="INVALID_PACKET"&&m()})}}},v=yield n.vertoSubscribe(y).catch(w=>{T.error("liveArray subscription error:",w)});eo(v,o)&&m();break}case"conference-liveArray-part":{let m=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(m=n.calls[v]||null,v!==null){const w={type:Je.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};K(V.Notification,w,v,!1)||K(V.Notification,w,n.uuid),m===null&&Pt(V.Notification,null,v)}}const y=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:y}).then(({unsubscribedChannels:v=[]})=>{m&&(m.channels=m.channels.filter(w=>!v.includes(w)))}).catch(v=>{T.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Iu(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};K(V.Notification,n,this.session.uuid);break}}}}class d_ extends l_{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new c_(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(T.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return Xi(this.options)||ei(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!!ei(this.options)||!!e.destinationNumber}_onSocketOpen(){return B(this,void 0,void 0,function*(){return Xi(this.options)?this.handleLoginOnSocketOpen():ei(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class u_ extends d_{constructor(e){super(e),T.info(`SDK version: ${pu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Zy()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:_e.not_supported},{browserName:"Firefox",supported:_e.not_supported},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",features:["audio"],supported:_e.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",features:["audio"],supported:_e.partial}]}]}}function Mu(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Du={exports:{}},Ou;function h_(){return Ou||(Ou=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 m=new s(d,u||l,f),y=n?n+c:c;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],m]:l._events[y].push(m):(l._events[y]=m,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,m=new Array(f);u<f;u++)m[u]=d[u].fn;return m},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,m){var y=n?n+l:l;if(!this._events[y])return!1;var v=this._events[y],w=arguments.length,_,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),w){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,m),!0}for(C=1,_=new Array(w-1);C<w;C++)_[C-1]=arguments[C];v.fn.apply(v.context,_)}else{var k=v.length,E;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),w){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,d);break;case 4:v[C].fn.call(v[C].context,c,d,u);break;default:if(!_)for(E=1,_=new Array(w-1);E<w;E++)_[E-1]=arguments[E];v[C].fn.apply(v[C].context,_)}}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 m=this._events[f];if(m.fn)m.fn===c&&(!u||m.once)&&(!d||m.context===d)&&r(this,f);else{for(var y=0,v=[],w=m.length;y<w;y++)(m[y].fn!==c||u&&!m[y].once||d&&m[y].context!==d)&&v.push(m[y]);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}(Du)),Du.exports}var f_=h_();const io=Mu(f_),ts=new io;var so={exports:{}},p_=so.exports,Nu;function g_(){return Nu||(Nu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(p_,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,w){var _=v[w];if(typeof _.bind=="function")return _.bind(v);try{return Function.prototype.bind.call(_,v)}catch{return function(){return Function.prototype.apply.apply(_,[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(),w=0;w<s.length;w++){var _=s[w];this[_]=w<v?e:this.methodFactory(_,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,w,_){return c(v)||u.apply(this,arguments)}function m(v,w){var _=this,C,k,E,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!R)){try{window.localStorage[R]=b;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!R)){try{h=window.localStorage[R]}catch{}if(typeof h===n)try{var b=window.document.cookie,A=encodeURIComponent(R),P=b.indexOf(A+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+A.length+1))[1])}catch{}return _.levels[h]===void 0&&(h=void 0),h}}function x(){if(!(typeof window===n||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&_.levels[b.toUpperCase()]!==void 0&&(b=_.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=_.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}_.name=v,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=w||f,_.getLevel=function(){return E??k??C},_.setLevel=function(h,b){return E=p(h),b!==!1&&O(E),d.call(_)},_.setDefaultLevel=function(h){k=p(h),S()||_.setLevel(h,!1)},_.resetLevel=function(){E=null,x(),d.call(_)},_.enableAll=function(h){_.setLevel(_.levels.TRACE,h)},_.disableAll=function(h){_.setLevel(_.levels.SILENT,h)},_.rebuild=function(){if(r!==_&&(C=p(r.getLevel())),d.call(_),r===_)for(var h in o)o[h].rebuild()},C=p(r?r.getLevel():"WARN");var g=S();g!=null&&(E=p(g)),d.call(_)}r=new m,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 w=o[v];return w||(w=o[v]=new m(v,r.methodFactory)),w};var y=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=y),r},r.getLoggers=function(){return o},r.default=r,r})}(so)),so.exports}var m_=g_();const v_=Mu(m_),y_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Re=v_.getLogger("telnyx-ai-agent"),__=Re.methodFactory;Re.methodFactory=(t,e,n)=>{const i=__(t,e,n);return function(...s){i(y_(),"-",...s)}},Re.setLevel("info");function b_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const w_=10,S_=500,C_=100,Fu=20;class x_{constructor(e){Z(this,"remoteIntervalId",null);Z(this,"localIntervalId",null);Z(this,"remoteStream",null);Z(this,"localStream",null);Z(this,"remoteAudioContext",null);Z(this,"remoteSource",null);Z(this,"remoteAnalyser",null);Z(this,"localAudioContext",null);Z(this,"localSource",null);Z(this,"localAnalyser",null);Z(this,"thinkingStartTime",null);Z(this,"lastState",null);Z(this,"userIsSpeaking",!1);Z(this,"lastUserAudioTime",null);Z(this,"userSpeechStartTime",null);Z(this,"userSilenceStartTime",null);Z(this,"isFirstAgentSpeech",!0);Z(this,"monitorStartTime",null);Z(this,"volumeThreshold");Z(this,"silenceDurationMs");Z(this,"minSpeechDurationMs");Z(this,"maxLatencyMs");Z(this,"updateAgentState",b_(e=>{Re.debug("AudioStreamMonitor updateAgentState",e),Re.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,ts.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??w_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??S_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??C_,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){Re.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Re.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Re.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Re.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&&Re.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,Fu)}startLocalMonitor(){if(!this.localStream){Re.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Re.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Re.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&&Re.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,Fu)}destroy(){this.stopAudioStreamMonitor()}}function k_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function T_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function E_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function A_(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 I_(t){return T_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function R_(t){if(!E_(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 L_ extends io{constructor(n){super();Z(this,"telnyxRTC");Z(this,"transcript",[]);Z(this,"onSocketMessage",n=>{if(k_(n))switch(n.params.type){case"response.text.delta":{const i=I_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),ts.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(A_(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=R_(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 P_ extends io{constructor(n){super();Z(this,"telnyxRTC");Z(this,"transcription");Z(this,"agentId");Z(this,"versionId");Z(this,"conversationId");Z(this,"debug");Z(this,"audioStreamMonitor");Z(this,"activeCall");Z(this,"chatMode");Z(this,"onClientReady",()=>{this.emit("agent.connected")});Z(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});Z(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()))});Z(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Z(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Re.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId};n.conversationId&&(i.target_params={conversation_id:n.conversationId}),this.telnyxRTC=new u_({env:n.environment||"production",anonymous_login:i,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 L_(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ts.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new x_(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(),ts.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Re.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){Re.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}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!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 Vu={exports:{}},oi={},Bu;function M_(){if(Bu)return oi;Bu=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 oi.Fragment=e,oi.jsx=n,oi.jsxs=n,oi}var ju;function D_(){return ju||(ju=1,Vu.exports=M_()),Vu.exports}D_(),vt(void 0),vt(null);const O_=(t,e,n,i,s,o,r,a)=>new P_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o,conversationId:r,chatMode:a}),N_=(t,e,n,i,s,o,r,a)=>{const[l,c]=Ce(null),[d,u]=Ce(!1),[f,m]=Ce(null);return xe(()=>{if(!t)return;const y=O_(t,e,n,i,s,o,r,a),v=()=>{u(!0),m(null)},w=()=>{u(!1)},_=C=>{m(C),Te.error("AI Agent error:",C)};return y.on("agent.connected",v),y.on("agent.disconnected",w),y.on("agent.error",_),y.connect(),c(y),()=>{y.off("agent.connected",v),y.off("agent.disconnected",w),y.off("agent.error",_),y.disconnect()}},[t,e,n,i,s,o,r,a]),{client:l,isConnected:d,error:f}},F_="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 Uu(){const t=document.querySelector(F_);return t instanceof HTMLElement?t:null}function Xt(t,e,n){const i=n||Uu();if(!i){Te.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Te.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const V_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=me(null);xe(()=>{r.current=Uu()},[]),xe(()=>{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=C=>{s(C);const k={message:C.message,name:C.name};Xt(Kt.AGENT_ERROR,k,a)},u=C=>{var k;i(C),Xt(Kt.CONVERSATION_UPDATE,{type:C.type,callState:(k=C.call)==null?void 0:k.state},a)},f=C=>{Xt(Kt.TRANSCRIPT_ITEM,C,a)},m=C=>{Xt(Kt.CONVERSATION_AGENT_STATE,C,a)},y=C=>{Xt(Kt.AGENT_AUDIO_MUTE,{muted:C},a)},w=t.telnyxRTC,_=C=>{o(C)};return w&&typeof w=="object"&&w.on(V.SocketMessage,_),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",m),t.on("agent.audio.mute",y),()=>{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",m),t.off("agent.audio.mute",y),w&&typeof w=="object"&&w.off(V.SocketMessage,_)}},[t,n,i,s,o])},B_=2e3;async function j_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function $u(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 U_=(t,e)=>{const[n,i]=Ce([]),[,s]=jr(),o=me(e);xe(()=>{o.current=e},[e]);const r=me(void 0),a=me(void 0);return xe(()=>{if(!t)return;const c=f=>{i(m=>{const y=m[m.length-1];if(f.role==="assistant"&&y&&$u(y.id)===$u(f.id)&&y.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&y.userPerceivedLatencyMs===void 0,w=o.current.showGreetingLatency&&a.current!==void 0&&y.greetingLatencyMs===void 0,_={...y,content:y.content+f.content,timestamp:f.timestamp,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),w&&(a.current=void 0),[...m.slice(0,-1),_]}if(f.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0,w=o.current.showGreetingLatency&&a.current!==void 0;if(v||w){const _={...f,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...m,_]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=m.findIndex(_=>_.id===f.id);if(v!==-1){const _=[...m];return _[v]={...m[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},_}if(y&&y.role==="user"&&f.timestamp.getTime()-y.timestamp.getTime()<B_){const C={...y,id:f.id,content:y.content+" "+f.content,timestamp:f.timestamp,attachments:[...y.attachments||[],...f.attachments||[]]};return[...m.slice(0,-1),C]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...m,f]})},d=({state:f,userPerceivedLatencyMs:m,greetingLatencyMs:y,thinkingStartedAt:v})=>{(m!==void 0||y!==void 0)&&Te.info(`[AgentState] state=${f} userPerceivedLatencyMs=${m} greetingLatencyMs=${y} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),m!==void 0&&(r.current=m),y!==void 0&&(a.current=y)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},u=f=>{var y;const m=(y=f.call)==null?void 0:y.state;(m==="destroy"||m==="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 m=await j_(f);u.push(m)}catch(m){throw Te.error("Failed to convert file to base64:",m),m}t.sendConversationMessage(c,u)}}},$_=({call:t,client:e,latencySettings:n,chatMode:i})=>{const s=Wt(),[o,r]=Ce(i?"expanded":s.default_state),a=()=>r("expanded"),l=()=>r("collapsed"),{transcript:c}=U_(e,n),d=me(!1);switch(xe(()=>{if(i&&t&&!d.current){const u="remoteStream"in t?t.remoteStream:null;u&&(d.current=!0,u.getAudioTracks().forEach(f=>{f.enabled=!1,Te.info(`[ChatMode] Disabled remote audio track: ${f.label}`)}))}},[i,t]),o){case"collapsed":return I(Gd,{onExpand:a,call:t,client:e,chatMode:i});case"expanded":return I(by,{transcript:c,onCollapse:l,call:t,chatMode:i});default:return I(Gd,{onExpand:a,call:t,client:e,chatMode:i})}},ro=()=>I(gn.div,{layoutId:Jn,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:I("div",{className:"rounded-full animate-spin",children:I(Jv,{})})}),H_=({call:t,client:e,latencySettings:n,chatMode:i})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return I(ro,{});case"done":case"purged":case"destroy":return null;case"active":return I($_,{client:e,call:t,latencySettings:n,chatMode:i});default:return I(ro,{})}},G_=({className:t})=>I("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:[I("g",{clipPath:"url(#:R5lfm:)",children:[I("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"}),I("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"}),I("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"}),I("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"}),I("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"})]}),I("defs",{children:I("clipPath",{id:":R5lfm:",children:I("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Hu(){const t=Wt();return t.logo_icon_url?I("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:I("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):I(G_,{className:"w-8 h-8 mr-2"})}const W_=({client:t,callProps:e,chatMode:n})=>{const i=Wt(),s=me(!1),o=yt(()=>{if(!t){Te.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return xe(()=>{n&&t&&!s.current&&(s.current=!0,Te.info("[ChatMode] Auto-starting conversation"),o())},[n,t,o]),n?I(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[I(Hu,{}),"Connecting..."]}):I(gn.button,{layoutId:Jn,onClick:o,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:[I(Hu,{}),i.start_call_text]})},z_='@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}.contents{display:contents}.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)}}',q_=({children:t})=>I("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:I("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),K_={duration:.1,ease:"circOut"},X_=({children:t,position:e="fixed"})=>{const n=Wt(),s=(e??n.position??"fixed")==="fixed"?I(q_,{children:t}):t;return I("div",{className:wt(n.theme==="dark"&&"dark"),children:I($p,{transition:K_,children:[I("style",{children:z_}),s]})})},Y_=t=>I(gn.div,{layoutId:Jn,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:[I(Xv,{className:"w-8 h-8 text-red-400"}),I("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),I("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[I("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),I("li",{children:["Make sure that the"," ",I("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"," ",I(iy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function ai(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,"conversation-id":u,"chat-mode":f,environment:m,position:y="fixed","version-id":v}){const w=ai(e),_=ai(n),C=ai(f),k=ze(()=>{if(l)try{return JSON.parse(l)}catch(ee){Te.error("Invalid JSON for vad attribute:",l,ee);return}},[l]),E=ze(()=>({showUserPerceivedLatency:ai(c),showGreetingLatency:ai(d)}),[c,d]),{client:R}=N_(t,m,v,w,_,k,u,C),[O,S]=Ce(null),[x,p]=Ce(!1),[g,h]=Ce(!1),[b,A]=Ce(!1),[P,L]=Ce(!1),D=Es($d),M=Sv(),N={};if(i&&(N.destinationNumber=i),s&&(N.callerNumber=s),o&&(N.callerName=o),r)try{N.customHeaders=JSON.parse(r)}catch(ee){Te.error("Invalid JSON for call-custom-headers attribute:",r,ee)}if(a)try{N.audio=JSON.parse(a);const ee=N.audio;if(typeof ee=="object"){const $=navigator.mediaDevices.getSupportedConstraints();Object.keys(ee).forEach(Y=>{$[Y]||Te.warn(`Audio constraint not supported by browser: ${Y}`)})}}catch(ee){Te.error("Invalid JSON for call-audio attribute:",a,ee)}const X=yt(()=>{p(!1)},[]),j=yt(ee=>{var $;if((($=ee.call)==null?void 0:$.state)==="destroy")return D(!1),L(!0),S(null);S(ee)},[D]),oe=yt(()=>{p(!1),h(!0)},[]),te=yt(ee=>{if(wv(ee)){const $=ee.params.widget_settings;$&&Object.keys($).length>0&&(M($),A(!0))}},[M]);return V_(R,{onReady:X,onConversationUpdate:j,onError:oe,onConfigMessage:te}),I(X_,{position:y,children:t?g?I(Y_,{agentId:t}):x?I(ro,{}):O!=null&&O.call?I(H_,{call:O.call,client:R,latencySettings:E,chatMode:C}):b?I(W_,{client:R,callProps:N,chatMode:C&&!P}):null:I("div",{children:"Please provide an assistant ID."})})}oh(J_,"telnyx-ai-agent",_v,{shadow:!0})})();
|
|
114
|
+
`)}))}),T.info(i)}),2e3)}}class l_ extends Ky{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 B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return B(this,void 0,void 0,function*(){try{const i=yield Ji({audio:e,video:n});return si(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(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(lu(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 ri().catch(e=>(K(V.MediaError,e,this.uuid),[]))}getVideoDevices(){return ri(ht.Video).catch(e=>(K(V.MediaError,e,this.uuid),[]))}getAudioInDevices(){return ri(ht.AudioIn).catch(e=>(K(V.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return ri(ht.AudioOut).catch(e=>(T.error("getAudioOutDevices",e),K(V.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Zi(e,n,i)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(n=>B(void 0,void 0,void 0,function*(){const i=[],s=yield Ji({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<bu.length;r++){const[a,l]=bu[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 si(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(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=Gi(e,["micId","micLabel"]);return Yy(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield Zi(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?ky:xy}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Ki(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Ki(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 Gy({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 B(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Wy({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=to(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 B(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new zy({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=to(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&&(T.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,T.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 Pu{constructor(e,n){this.code=n,this.message=e}}class c_{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0,this.receivedAuthenticationRequired=0}_ack(e,n){const i=new jy(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*ru(2,6)}handleMessage(e){var n,i,s;const{session:o}=this,{id:r,method:a,params:l={},voice_sdk_id:c}=e,d=l==null?void 0:l.callID,u=l==null?void 0:l.eventChannel,f=l==null?void 0:l.eventType,m=o.calls[d],y=(n=m==null?void 0:m.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(f==="channelPvtData")return this._handlePvtEvent(l.pvtData);const v=(C=!1)=>{var k,E,R,O,S,x;const p={audio:!0,video:o.options.video,remoteSdp:l.sdp,destinationNumber:l.callee_id_number,remoteCallerName:l.caller_id_name,remoteCallerNumber:l.caller_id_number,callerName:l.callee_id_name,callerNumber:l.callee_id_number,attach:a===Q.Attach,mediaSettings:l.mediaSettings,debug:(k=o.options.debug)!==null&&k!==void 0&&k,debugOutput:(E=o.options.debugOutput)!==null&&E!==void 0?E:"socket",trickleIce:a!==Q.Attach&&(R=o.options.trickleIce)!==null&&R!==void 0&&R,prefetchIceCandidates:(O=o.options.prefetchIceCandidates)===null||O===void 0||O,forceRelayCandidate:(S=o.options.forceRelayCandidate)!==null&&S!==void 0&&S,keepConnectionAliveOnSocketClose:(x=o.options.keepConnectionAliveOnSocketClose)!==null&&x!==void 0&&x};d&&(p.id=d),l.telnyx_call_control_id&&(p.telnyxCallControlId=l.telnyx_call_control_id),l.telnyx_session_id&&(p.telnyxSessionId=l.telnyx_session_id),l.telnyx_leg_id&&(p.telnyxLegId=l.telnyx_leg_id),l.client_state&&(p.clientState=l.client_state),l.dialogParams&&l.dialogParams.custom_headers&&l.dialogParams.custom_headers.length&&(p.customHeaders=l.dialogParams.custom_headers);const g=new qt(o,p,C);return g.nodeId=this.nodeId,g},w=new hu(c),_=new fu(c);switch(a){case Q.Answer:case Q.Display:case Q.Candidate:case Q.Ringing:case Q.Bye:case Q.Media:if(!d||!m)return void T.error(`Received ${a} for non existing call:`,l);m.handleMessage(e),this._ack(r,a);break;case Q.Ping:this.session.setPingReceived(),this.session.execute(_).then(()=>{this.receivedAuthenticationRequired=0}).catch(E=>B(this,void 0,void 0,function*(){E.code===this.session.authenticationRequiredErrorCode&&this.receivedAuthenticationRequired>=0&&(this.receivedAuthenticationRequired+=1,this.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(T.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),this.receivedAuthenticationRequired=-1))}));break;case Q.Punt:o.options.keepConnectionAliveOnSocketClose&&y?(T.info(`[${new Date().toISOString()}][${d}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),o.socketDisconnect(),this._ack(r,a)):o.disconnect();break;case Q.Invite:{const E=v();E.direction=ut.Inbound,E.playRingtone(),E.setState(q.Ringing),this._ack(r,a);break}case Q.Attach:{if(!m)return v().answer(),void this._ack(r,a);const E=!!m;T.info(`[${new Date().toISOString()}][${d}] closing existing call on ATTACH.`),m.hangup({isRecovering:E},!1),T.info(`[${new Date().toISOString()}][${d}] Attach: Creating new call for recovery`),v(E).answer(),this._ack(r,a);break}case Q.Event:case"webrtc.event":if(!u)return void T.error("Verto received an unknown event:",l);const C=o.relayProtocol,k=u.split(".")[0];o._existsSubscription(C,u)?K(C,l,u):u===o.sessionid?this._handleSessionEvent(l.eventData):o._existsSubscription(C,k)?K(C,l,k):o.calls.hasOwnProperty(u)?o.calls[u].handleMessage(e):K(V.Notification,l,o.uuid);break;case Q.Info:l.type=Je.generic,K(V.Notification,l,o.uuid);break;case Q.ClientReady:this.session.execute(w);break;default:{const E=Kr(e);if(E){switch(E){case Ne.REGISTER:case Ne.REGED:if(o.connection.previousGatewayState!==Ne.REGED&&o.connection.previousGatewayState!==Ne.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const R=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;R&&(o.callReportId=R,T.debug("Captured call_report_id from REGED:",R)),l.type=Je.vertoClientReady,K(V.Ready,l,o.uuid)}break;case Ne.UNREGED:case Ne.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0,K(V.Error,{error:new Pu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{this.session.execute(w)},this.reconnectDelay());break;case Ne.FAILED:case Ne.FAIL_WAIT:if(o.connection.previousGatewayState!==Ne.FAILED&&o.connection.previousGatewayState!==Ne.FAIL_WAIT){if(!this.session.hasAutoReconnect()){this.retriedConnect=0,K(V.Error,{error:new Pu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:o.sessionid},o.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,K(V.Error,{error:new Error("Connection Retry Failed"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{if(T.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(o.calls).some(R=>{var O;return((O=R.peer)===null||O===void 0?void 0:O.instance)&&!R.signalingStateClosed}))return T.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();T.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:T.warn("GatewayState message unknown method:",e)}break}T.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 B(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 m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},y={nodeId:this.nodeId,channels:[o],handler:({data:w})=>{const _=f||this._retrieveCallId(w,o);if(_&&n.calls.hasOwnProperty(_)){const C=n.calls[_];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(w,e).then(k=>{k==="INVALID_PACKET"&&m()})}}},v=yield n.vertoSubscribe(y).catch(w=>{T.error("liveArray subscription error:",w)});eo(v,o)&&m();break}case"conference-liveArray-part":{let m=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(m=n.calls[v]||null,v!==null){const w={type:Je.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};K(V.Notification,w,v,!1)||K(V.Notification,w,n.uuid),m===null&&Pt(V.Notification,null,v)}}const y=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:y}).then(({unsubscribedChannels:v=[]})=>{m&&(m.channels=m.channels.filter(w=>!v.includes(w)))}).catch(v=>{T.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Iu(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};K(V.Notification,n,this.session.uuid);break}}}}class d_ extends l_{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new c_(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(T.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return Xi(this.options)||ei(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!!ei(this.options)||!!e.destinationNumber}_onSocketOpen(){return B(this,void 0,void 0,function*(){return Xi(this.options)?this.handleLoginOnSocketOpen():ei(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class u_ extends d_{constructor(e){super(e),T.info(`SDK version: ${pu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Zy()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:_e.not_supported},{browserName:"Firefox",supported:_e.not_supported},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",features:["audio"],supported:_e.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",features:["audio"],supported:_e.partial}]}]}}function Mu(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Du={exports:{}},Ou;function h_(){return Ou||(Ou=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 m=new s(d,u||l,f),y=n?n+c:c;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],m]:l._events[y].push(m):(l._events[y]=m,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,m=new Array(f);u<f;u++)m[u]=d[u].fn;return m},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,m){var y=n?n+l:l;if(!this._events[y])return!1;var v=this._events[y],w=arguments.length,_,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),w){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,m),!0}for(C=1,_=new Array(w-1);C<w;C++)_[C-1]=arguments[C];v.fn.apply(v.context,_)}else{var k=v.length,E;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),w){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,d);break;case 4:v[C].fn.call(v[C].context,c,d,u);break;default:if(!_)for(E=1,_=new Array(w-1);E<w;E++)_[E-1]=arguments[E];v[C].fn.apply(v[C].context,_)}}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 m=this._events[f];if(m.fn)m.fn===c&&(!u||m.once)&&(!d||m.context===d)&&r(this,f);else{for(var y=0,v=[],w=m.length;y<w;y++)(m[y].fn!==c||u&&!m[y].once||d&&m[y].context!==d)&&v.push(m[y]);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}(Du)),Du.exports}var f_=h_();const io=Mu(f_),ts=new io;var so={exports:{}},p_=so.exports,Nu;function g_(){return Nu||(Nu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(p_,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,w){var _=v[w];if(typeof _.bind=="function")return _.bind(v);try{return Function.prototype.bind.call(_,v)}catch{return function(){return Function.prototype.apply.apply(_,[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(),w=0;w<s.length;w++){var _=s[w];this[_]=w<v?e:this.methodFactory(_,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,w,_){return c(v)||u.apply(this,arguments)}function m(v,w){var _=this,C,k,E,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!R)){try{window.localStorage[R]=b;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!R)){try{h=window.localStorage[R]}catch{}if(typeof h===n)try{var b=window.document.cookie,A=encodeURIComponent(R),P=b.indexOf(A+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+A.length+1))[1])}catch{}return _.levels[h]===void 0&&(h=void 0),h}}function x(){if(!(typeof window===n||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&_.levels[b.toUpperCase()]!==void 0&&(b=_.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=_.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}_.name=v,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=w||f,_.getLevel=function(){return E??k??C},_.setLevel=function(h,b){return E=p(h),b!==!1&&O(E),d.call(_)},_.setDefaultLevel=function(h){k=p(h),S()||_.setLevel(h,!1)},_.resetLevel=function(){E=null,x(),d.call(_)},_.enableAll=function(h){_.setLevel(_.levels.TRACE,h)},_.disableAll=function(h){_.setLevel(_.levels.SILENT,h)},_.rebuild=function(){if(r!==_&&(C=p(r.getLevel())),d.call(_),r===_)for(var h in o)o[h].rebuild()},C=p(r?r.getLevel():"WARN");var g=S();g!=null&&(E=p(g)),d.call(_)}r=new m,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 w=o[v];return w||(w=o[v]=new m(v,r.methodFactory)),w};var y=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=y),r},r.getLoggers=function(){return o},r.default=r,r})}(so)),so.exports}var m_=g_();const v_=Mu(m_),y_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Re=v_.getLogger("telnyx-ai-agent"),__=Re.methodFactory;Re.methodFactory=(t,e,n)=>{const i=__(t,e,n);return function(...s){i(y_(),"-",...s)}},Re.setLevel("info");function b_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const w_=10,S_=500,C_=100,Fu=20;class x_{constructor(e){Z(this,"remoteIntervalId",null);Z(this,"localIntervalId",null);Z(this,"remoteStream",null);Z(this,"localStream",null);Z(this,"remoteAudioContext",null);Z(this,"remoteSource",null);Z(this,"remoteAnalyser",null);Z(this,"localAudioContext",null);Z(this,"localSource",null);Z(this,"localAnalyser",null);Z(this,"thinkingStartTime",null);Z(this,"lastState",null);Z(this,"userIsSpeaking",!1);Z(this,"lastUserAudioTime",null);Z(this,"userSpeechStartTime",null);Z(this,"userSilenceStartTime",null);Z(this,"isFirstAgentSpeech",!0);Z(this,"monitorStartTime",null);Z(this,"volumeThreshold");Z(this,"silenceDurationMs");Z(this,"minSpeechDurationMs");Z(this,"maxLatencyMs");Z(this,"updateAgentState",b_(e=>{Re.debug("AudioStreamMonitor updateAgentState",e),Re.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,ts.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??w_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??S_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??C_,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){Re.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Re.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Re.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Re.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&&Re.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,Fu)}startLocalMonitor(){if(!this.localStream){Re.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Re.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Re.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&&Re.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,Fu)}destroy(){this.stopAudioStreamMonitor()}}function k_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function T_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function E_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function A_(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 I_(t){return T_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function R_(t){if(!E_(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 L_ extends io{constructor(n){super();Z(this,"telnyxRTC");Z(this,"transcript",[]);Z(this,"onSocketMessage",n=>{if(k_(n))switch(n.params.type){case"response.text.delta":{const i=I_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),ts.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(A_(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=R_(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 P_ extends io{constructor(n){super();Z(this,"telnyxRTC");Z(this,"transcription");Z(this,"agentId");Z(this,"versionId");Z(this,"conversationId");Z(this,"debug");Z(this,"audioStreamMonitor");Z(this,"activeCall");Z(this,"chatMode");Z(this,"onClientReady",()=>{this.emit("agent.connected")});Z(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});Z(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()))});Z(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Z(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Re.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId};n.conversationId&&(i.target_params={conversation_id:n.conversationId}),this.telnyxRTC=new u_({env:n.environment||"production",anonymous_login:i,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 L_(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ts.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new x_(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(),ts.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Re.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){Re.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}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!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 Vu={exports:{}},oi={},Bu;function M_(){if(Bu)return oi;Bu=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 oi.Fragment=e,oi.jsx=n,oi.jsxs=n,oi}var ju;function D_(){return ju||(ju=1,Vu.exports=M_()),Vu.exports}D_(),vt(void 0),vt(null);const O_=(t,e,n,i,s,o,r,a)=>new P_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o,conversationId:r,chatMode:a}),N_=(t,e,n,i,s,o,r,a)=>{const[l,c]=Ce(null),[d,u]=Ce(!1),[f,m]=Ce(null);return xe(()=>{if(!t)return;const y=O_(t,e,n,i,s,o,r,a),v=()=>{u(!0),m(null)},w=()=>{u(!1)},_=C=>{m(C),Te.error("AI Agent error:",C)};return y.on("agent.connected",v),y.on("agent.disconnected",w),y.on("agent.error",_),y.connect(),c(y),()=>{y.off("agent.connected",v),y.off("agent.disconnected",w),y.off("agent.error",_),y.disconnect()}},[t,e,n,i,s,o,r,a]),{client:l,isConnected:d,error:f}},F_="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 Uu(){const t=document.querySelector(F_);return t instanceof HTMLElement?t:null}function Xt(t,e,n){const i=n||Uu();if(!i){Te.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Te.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const V_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=me(null);xe(()=>{r.current=Uu()},[]),xe(()=>{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=C=>{s(C);const k={message:C.message,name:C.name};Xt(Kt.AGENT_ERROR,k,a)},u=C=>{var k;i(C),Xt(Kt.CONVERSATION_UPDATE,{type:C.type,callState:(k=C.call)==null?void 0:k.state},a)},f=C=>{Xt(Kt.TRANSCRIPT_ITEM,C,a)},m=C=>{Xt(Kt.CONVERSATION_AGENT_STATE,C,a)},y=C=>{Xt(Kt.AGENT_AUDIO_MUTE,{muted:C},a)},w=t.telnyxRTC,_=C=>{o(C)};return w&&typeof w=="object"&&w.on(V.SocketMessage,_),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",m),t.on("agent.audio.mute",y),()=>{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",m),t.off("agent.audio.mute",y),w&&typeof w=="object"&&w.off(V.SocketMessage,_)}},[t,n,i,s,o])},B_=2e3;async function j_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function $u(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 U_=(t,e)=>{const[n,i]=Ce([]),[,s]=jr(),o=me(e);xe(()=>{o.current=e},[e]);const r=me(void 0),a=me(void 0);return xe(()=>{if(!t)return;const c=f=>{i(m=>{const y=m[m.length-1];if(f.role==="assistant"&&y&&$u(y.id)===$u(f.id)&&y.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&y.userPerceivedLatencyMs===void 0,w=o.current.showGreetingLatency&&a.current!==void 0&&y.greetingLatencyMs===void 0,_={...y,content:y.content+f.content,timestamp:f.timestamp,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),w&&(a.current=void 0),[...m.slice(0,-1),_]}if(f.role==="assistant"){s(_=>_==="thinking"||_==="processing_image"?"speaking":_);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,w=o.current.showGreetingLatency&&a.current!==void 0;if(v||w){const _={...f,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...m,_]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=m.findIndex(_=>_.id===f.id);if(v!==-1){const _=[...m];return _[v]={...m[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},_}if(y&&y.role==="user"&&f.timestamp.getTime()-y.timestamp.getTime()<B_){const C={...y,id:f.id,content:y.content+" "+f.content,timestamp:f.timestamp,attachments:[...y.attachments||[],...f.attachments||[]]};return[...m.slice(0,-1),C]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...m,f]})},d=({state:f,userPerceivedLatencyMs:m,greetingLatencyMs:y,thinkingStartedAt:v})=>{(m!==void 0||y!==void 0)&&Te.info(`[AgentState] state=${f} userPerceivedLatencyMs=${m} greetingLatencyMs=${y} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),m!==void 0&&(r.current=m),y!==void 0&&(a.current=y)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},u=f=>{var y;const m=(y=f.call)==null?void 0:y.state;(m==="destroy"||m==="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 m=await j_(f);u.push(m)}catch(m){throw Te.error("Failed to convert file to base64:",m),m}t.sendConversationMessage(c,u)}}},$_=({call:t,client:e,latencySettings:n,chatMode:i})=>{const s=Wt(),[o,r]=Ce(i?"expanded":s.default_state),a=()=>r("expanded"),l=()=>r("collapsed"),{transcript:c}=U_(e,n),d=me(!1);switch(xe(()=>{if(i&&t&&!d.current){const u="remoteStream"in t?t.remoteStream:null;u&&(d.current=!0,u.getAudioTracks().forEach(f=>{f.enabled=!1,Te.info(`[ChatMode] Disabled remote audio track: ${f.label}`)}))}},[i,t]),o){case"collapsed":return I(Gd,{onExpand:a,call:t,client:e,chatMode:i});case"expanded":return I(by,{transcript:c,onCollapse:l,call:t,chatMode:i});default:return I(Gd,{onExpand:a,call:t,client:e,chatMode:i})}},ro=()=>I(gn.div,{layoutId:Jn,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:I("div",{className:"rounded-full animate-spin",children:I(Jv,{})})}),H_=({call:t,client:e,latencySettings:n,chatMode:i})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return I(ro,{});case"done":case"purged":case"destroy":return null;case"active":return I($_,{client:e,call:t,latencySettings:n,chatMode:i});default:return I(ro,{})}},G_=({className:t})=>I("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:[I("g",{clipPath:"url(#:R5lfm:)",children:[I("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"}),I("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"}),I("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"}),I("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"}),I("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"})]}),I("defs",{children:I("clipPath",{id:":R5lfm:",children:I("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Hu(){const t=Wt();return t.logo_icon_url?I("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:I("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):I(G_,{className:"w-8 h-8 mr-2"})}const W_=({client:t,callProps:e,chatMode:n})=>{const i=Wt(),s=me(!1),o=yt(()=>{if(!t){Te.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return xe(()=>{n&&t&&!s.current&&(s.current=!0,Te.info("[ChatMode] Auto-starting conversation"),o())},[n,t,o]),n?I(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[I(Hu,{}),"Connecting..."]}):I(gn.button,{layoutId:Jn,onClick:o,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:[I(Hu,{}),i.start_call_text]})},z_='@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}.contents{display:contents}.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)}}',q_=({children:t})=>I("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:I("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),K_={duration:.1,ease:"circOut"},X_=({children:t,position:e="fixed"})=>{const n=Wt(),s=(e??n.position??"fixed")==="fixed"?I(q_,{children:t}):t;return I("div",{className:wt(n.theme==="dark"&&"dark"),children:I($p,{transition:K_,children:[I("style",{children:z_}),s]})})},Y_=t=>I(gn.div,{layoutId:Jn,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:[I(Xv,{className:"w-8 h-8 text-red-400"}),I("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),I("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[I("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),I("li",{children:["Make sure that the"," ",I("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"," ",I(iy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function ai(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,"conversation-id":u,"chat-mode":f,environment:m,position:y="fixed","version-id":v}){const w=ai(e),_=ai(n),C=ai(f),k=ze(()=>{if(l)try{return JSON.parse(l)}catch(ee){Te.error("Invalid JSON for vad attribute:",l,ee);return}},[l]),E=ze(()=>({showUserPerceivedLatency:ai(c),showGreetingLatency:ai(d)}),[c,d]),{client:R}=N_(t,m,v,w,_,k,u,C),[O,S]=Ce(null),[x,p]=Ce(!1),[g,h]=Ce(!1),[b,A]=Ce(!1),[P,L]=Ce(!1),D=Es($d),M=Sv(),N={};if(i&&(N.destinationNumber=i),s&&(N.callerNumber=s),o&&(N.callerName=o),r)try{N.customHeaders=JSON.parse(r)}catch(ee){Te.error("Invalid JSON for call-custom-headers attribute:",r,ee)}if(a)try{N.audio=JSON.parse(a);const ee=N.audio;if(typeof ee=="object"){const $=navigator.mediaDevices.getSupportedConstraints();Object.keys(ee).forEach(Y=>{$[Y]||Te.warn(`Audio constraint not supported by browser: ${Y}`)})}}catch(ee){Te.error("Invalid JSON for call-audio attribute:",a,ee)}const X=yt(()=>{p(!1)},[]),j=yt(ee=>{var $;if((($=ee.call)==null?void 0:$.state)==="destroy")return D(!1),L(!0),S(null);S(ee)},[D]),oe=yt(()=>{p(!1),h(!0)},[]),te=yt(ee=>{if(wv(ee)){const $=ee.params.widget_settings;$&&Object.keys($).length>0&&(M($),A(!0))}},[M]);return V_(R,{onReady:X,onConversationUpdate:j,onError:oe,onConfigMessage:te}),I(X_,{position:y,children:t?g?I(Y_,{agentId:t}):x?I(ro,{}):O!=null&&O.call?I(H_,{call:O.call,client:R,latencySettings:E,chatMode:C}):b?I(W_,{client:R,callProps:N,chatMode:C&&!P}):null:I("div",{children:"Please provide an assistant ID."})})}oh(J_,"telnyx-ai-agent",_v,{shadow:!0})})();
|