@telnyx/ai-agent-widget 0.33.0-beta.2 → 0.33.0-beta.3

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.
@@ -116,4 +116,4 @@ var nb=Object.defineProperty;var ib=(nt,G,jt)=>G in nt?nb(nt,G,{enumerable:!0,co
116
116
  `),void this._requestAnotherLocalDescription();if((i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),!m_.test(s)){const l=Dt(h_);k.warn(`[${this.id}] Warning ${l.code}: ${l.message}`),U(O.Warning,{warning:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark("ice-gathering-end");let o=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${ls}`};switch(r){case De.Offer:this.setState(q.Requesting),o=new Iu(a);break;case De.Answer:this._isRecovering||this.setState(q.Answering),o=this.options.attach===!0?new Ru(a):new Au(a);break;default:return k.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(o).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,r===De.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(l=>F(this,void 0,void 0,function*(){k.error(`${this.id} - Sending ${r} error:`,l);const c=ae(su,l);U(O.Error,{error:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(u){k.error("Error during hangup after SDP send failure:",u)}}))}_onTrickleIceSdp(e){if(!e)return k.error("No SDP data provided"),void this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${ls}`};switch(i){case De.Offer:this.setState(q.Requesting),s=new Iu(r);break;case De.Answer:this._isRecovering||this.setState(q.Answering),s=this.options.attach===!0?new Ru(r):new Au(r);break;default:return k.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(s).then(o=>{const{node_id:a=null}=o;this._targetNodeId=a,i===De.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(o=>F(this,void 0,void 0,function*(){k.error(`${this.id} - Sending ${i} error:`,o);const a=ae(su,o);U(O.Error,{error:a,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(l){k.error("Error during hangup after SDP send failure:",l)}}))}_onIce(e){var n;const{instance:i}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(i.localDescription),s)}e.candidate?(k.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(i.localDescription)}_onTrickleIce(e){var n;e.candidate&&e.candidate.candidate?(k.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new F_({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 k.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(()=>{k.debug("Successfully added ICE candidate:",e)}).catch(i=>{k.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new V_({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var n;if(this._firstCandidateSent||(performance.mark("first-candidate"),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=(n=e.candidate.match(/typ (\w+)/))===null||n===void 0?void 0:n[1];i&&i!=="host"&&(performance.mark("first-non-host-candidate"),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!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.onicegatheringstatechange=()=>{e.iceGatheringState==="complete"&&performance.mark("ice-gathering-completed")},e.onicecandidateerror=n=>{var i;if(k.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=ju(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:r}=this.options;r===!1&&li(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{k.debug("ICE gathering state changed:",e.iceGatheringState,n),e.iceGatheringState==="complete"&&(k.debug("Finished gathering candidates"),performance.mark("ice-gathering-completed"))},e.onicecandidateerror=n=>{var i;if(k.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=ju(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:r}=this.options;r===!1&&li(i,s)})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:et.userMediaError,error:s,call:this,errorName:n,errorMessage:i}),k.error(`Media error (${n}): ${i}`,e),U(O.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:et.peerConnectionFailureError,error:e.error}),k.error("Peer connection failure error"),e.warning&&U(O.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:et.signalingStateClosed},e)),k.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:et.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(U(O.Notification,e,this.id,!1)||U(O.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){var e,n;const{id:i,userVariables:s,remoteCallerNumber:r,onNotification:o,recoveredCallId:a}=this.options;var l;this.options.id=i?i.toString():wn(),this.id=this.options.id,a&&(this.recoveredCallId=a,this._isRecovering=!0),s&&(l=s,Object.keys(l).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),r||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Pt(O.MediaError,this._onMediaError,this.id),Pt(O.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Pt(O.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Sn(o)&&Pt(O.Notification,o.bind(this),this.id);const c=this.session.options.enableCallReports!==!1,u=this.session.options.callReportInterval||5e3,d=this.session.options.debugLogLevel||"debug",f=this.session.options.debugLogMaxEntries||1e3;c&&(this._callReportCollector=new Ce({enabled:!0,interval:u},{enabled:!0,level:d,maxEntries:f}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=g=>{U(O.Warning,{warning:g,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}),this._isRecovering?this.setState(q.Recovering):this.setState(q.New),k.info(`New Call — region: ${(e=this.session.region)!==null&&e!==void 0?e:"unknown"}, dc: ${(n=this.session.dc)!==null&&n!==void 0?n:"unknown"}`,this.options)}_finalize(){var e;this._stopStats(),k.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;ci(n),ci(i),Mt(O.MediaError,null,this.id),Mt(O.PeerConnectionFailureError,null,this.id),Mt(O.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch(s=>{k.error("Unexpected error in _postCallReport",{error:s})})}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void k.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 k.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===pt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ls},r=this._callReportCollector.flush(s);if(!r)return;const o=Yt()||void 0;this._callReportCollector.sendPayload(r,n,i,o).catch(a=>{k.error("Failed to post intermediate call report segment",{error:a})})}_postCallReport(){var e;return F(this,void 0,void 0,function*(){if(!this._callReportCollector)return void k.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return k.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===pt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ls},s=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!s)return void k.error("Cannot post call report: connection host not available");const r=Yt()||void 0;this._callReportCollector.postReport(i,n,s,r).catch(o=>{k.error("Failed to post call report",{error:o})}).finally(()=>{var o;(o=this._callReportCollector)===null||o===void 0||o.cleanup()})})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),k.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),k.debug("Stats stopped")}}Gu.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 Jt extends Gu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new q_(e,n))}hangup(e={},n=!0){const i=Object.create(null,{hangup:{get:()=>super.hangup}});return F(this,void 0,void 0,function*(){this.screenShare instanceof Jt&&(yield this.screenShare.hangup(e,n)),yield i.hangup.call(this,e,n)})}startScreenShare(e){return F(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",()=>F(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup())}))});const{remoteCallerName:s,remoteCallerNumber:r,callerName:o,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${r}-screen`,callerName:`${o} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new Jt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return F(this,void 0,void 0,function*(){this.screenShare instanceof Jt&&(yield this.screenShare.hangup())})}setAudioOutDevice(e){return F(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&Du(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>F(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"],r=["id","type","timestamp"];n.forEach(o=>{s.includes(o.type)||(i+=`
117
117
  ${o.type}
118
118
  `,Object.keys(o).forEach(a=>{r.includes(a)||(i+=` ${a}: ${o[a]}
119
- `)}))}),k.info(i)}),2e3)}}class i0 extends ai{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 F(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return F(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return F(this,void 0,void 0,function*(){try{const i=yield os({audio:e,video:n});return ci(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return F(this,void 0,void 0,function*(){k.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(q.Purge),k.info("Start hangup for ",i),yield i.hangup({},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return F(this,void 0,void 0,function*(){k.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(q.Purge),i.hangup({},!1)}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(wu(O.SpeedTest,o=>{const{upDur:a,downDur:l}=o,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 r=".".repeat(1024);for(let o=0;o<s;o++)this.executeRaw(`#SPB ${r}`);this.executeRaw("#SPE")})}getDevices(){return di().catch(e=>{const n=ae(ii(e),e);return U(O.MediaError,n,this.uuid),[]})}getVideoDevices(){return di(mt.Video).catch(e=>(U(O.MediaError,e,this.uuid),[]))}getAudioInDevices(){return di(mt.AudioIn).catch(e=>{const n=ae(ii(e),e);return U(O.MediaError,n,this.uuid),[]})}getAudioOutDevices(){return di(mt.AudioOut).catch(e=>(k.error("getAudioOutDevices",e),U(O.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return rs(e,n,i)}getDeviceResolutions(e){return F(this,void 0,void 0,function*(){try{return yield(n=>F(void 0,void 0,void 0,function*(){const i=[],s=yield os({video:{deviceId:{exact:n}}}),r=s.getVideoTracks()[0];for(let o=0;o<Pu.length;o++){const[a,l]=Pu[o];(yield r.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return ci(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return F(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=Zi(e,["micId","micLabel"]);return W_(s),this._audioConstraints=yield((r,o,a,l)=>F(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(r||o)){const u=yield rs(r,o,a).catch(d=>null);u&&(l.deviceId={exact:u})}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?y_:v_}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=ns(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=ns(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 B_({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(r=>r)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return F(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new U_({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const r=yield this.execute(s),{unauthorized:o=[],subscribed:a=[]}=dr(r);return o.length&&o.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),r})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return F(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new j_({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:r=[],notSubscribed:o=[]}=dr(s);return r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(k.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,k.debug(`Network connectivity lost for session ${this.sessionid}`);const e=ae(n_);U(O.Error,{error:e,sessionId:this.sessionid},this.uuid)},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 Jt.setStateTelnyx(e)}}class zu{constructor(e,n){this.code=n,this.message=e}}class s0{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,n){const i=new N_(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*yu(2,6)}handleMessage(e){var n,i,s,r,o,a,l,c,u;const{session:d}=this;d.setPingReceived();const{id:f,method:g,params:v={},voice_sdk_id:_}=e,w=v==null?void 0:v.callID,y=v==null?void 0:v.eventChannel,T=v==null?void 0:v.eventType,x=d.calls[w],I=(n=x==null?void 0:x.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(Array.isArray(v==null?void 0:v.reattached_sessions)&&v.reattached_sessions.length===0&&Object.keys(d.calls).length>0){const C=Dt(p_);U(O.Warning,{warning:C,sessionId:d.sessionid},d.uuid)}if(T==="channelPvtData")return this._handlePvtEvent(v.pvtData);const A=C=>{var p,m,h,b,E,D;const L={audio:!0,video:d.options.video,remoteSdp:v.sdp,destinationNumber:v.callee_id_number,remoteCallerName:v.caller_id_name,remoteCallerNumber:v.caller_id_number,callerName:v.callee_id_name,callerNumber:v.callee_id_number,attach:g===te.Attach,mediaSettings:v.mediaSettings,debug:(p=d.options.debug)!==null&&p!==void 0&&p,debugOutput:(m=d.options.debugOutput)!==null&&m!==void 0?m:"socket",trickleIce:(h=d.options.trickleIce)!==null&&h!==void 0&&h,prefetchIceCandidates:(b=d.options.prefetchIceCandidates)===null||b===void 0||b,forceRelayCandidate:(E=d.options.forceRelayCandidate)!==null&&E!==void 0&&E,keepConnectionAliveOnSocketClose:(D=d.options.keepConnectionAliveOnSocketClose)!==null&&D!==void 0&&D};w&&(L.id=w),v.telnyx_call_control_id&&(L.telnyxCallControlId=v.telnyx_call_control_id),v.telnyx_session_id&&(L.telnyxSessionId=v.telnyx_session_id),v.telnyx_leg_id&&(L.telnyxLegId=v.telnyx_leg_id),v.client_state&&(L.clientState=v.client_state),v.dialogParams&&v.dialogParams.custom_headers&&v.dialogParams.custom_headers.length&&(L.customHeaders=v.dialogParams.custom_headers),C&&(L.recoveredCallId=C),performance.mark("new-call-start");const N=new Jt(d,L);return N.nodeId=this.nodeId,N},M=new ku(_),S=new xu(_);switch(g){case te.Answer:case te.Display:case te.Candidate:case te.Ringing:case te.Bye:case te.Media:if(!w||!x)return void k.error(`Received ${g} for non existing call:`,v);x.handleMessage(e),this._ack(f,g);break;case te.Ping:this.session.setPingReceived(),this.session.execute(S);break;case te.Punt:d.options.keepConnectionAliveOnSocketClose&&I?(k.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(f,g)):(k.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case te.Invite:{const m=A();m.direction=pt.Inbound,m.playRingtone(),m.setState(q.Ringing),this._ack(f,g);break}case te.Attach:{if(!x)return A().answer(),void this._ack(f,g);const m=x.id;k.info(`[${new Date().toISOString()}][${w}] closing existing call on ATTACH.`),x.hangup({isRecovering:!0},!1),k.info(`[${new Date().toISOString()}][${w}] Attach: Creating new call for recovery (recoveredCallId: ${m})`),A(m).answer(),this._ack(f,g);break}case te.Event:case"webrtc.event":if(!y)return void k.error("Verto received an unknown event:",v);const C=d.relayProtocol,p=y.split(".")[0];d._existsSubscription(C,y)?U(C,v,y):y===d.sessionid?this._handleSessionEvent(v.eventData):d._existsSubscription(C,p)?U(C,v,p):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):U(O.Notification,v,d.uuid);break;case te.Info:v.type=et.generic,U(O.Notification,v,d.uuid);break;case te.ClientReady:this.session.execute(M);break;default:{const m=ir(e);if(m){switch(m){case Ue.REGISTER:case Ue.REGED:if(d.connection.previousGatewayState!==Ue.REGED&&d.connection.previousGatewayState!==Ue.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const h=(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;h&&(d.callReportId=h,k.debug("Captured call_report_id from REGED:",h));const b=(o=(r=e==null?void 0:e.result)===null||r===void 0?void 0:r.params)===null||o===void 0?void 0:o.dc;b&&(d.dc=b);const E=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;E&&(d.region=E),k.info(`Connected to Telnyx — region: ${(c=d.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=d.dc)!==null&&u!==void 0?u:"unknown"}`),v.type=et.vertoClientReady,U(O.Ready,v,d.uuid)}break;case Ue.UNREGED:case Ue.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const h=new zu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),b=ae(ru,h);U(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(M)},this.reconnectDelay());break;case Ue.FAILED:case Ue.FAIL_WAIT:if(d.connection.previousGatewayState!==Ue.FAILED&&d.connection.previousGatewayState!==Ue.FAIL_WAIT){const h=ae(Qy,new Error(`Gateway state: ${m}`));if(U(O.Error,{error:h,sessionId:d.sessionid},d.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const b=new zu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),E=ae(Zy,b);U(O.Error,{error:E,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0;const b=ae(45003,new Error("Connection Retry Failed"));U(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(k.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(b=>{var E;return((E=b.peer)===null||E===void 0?void 0:E.instance)&&!b.signalingStateClosed}))return k.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();k.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:k.warn("GatewayState message unknown method:",e)}break}k.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(r=>i.includes(r[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return F(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:r,laName:o,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:f}=e;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:r,data:{liveArray:{command:"bootstrap",context:r,name:o}}})},v={nodeId:this.nodeId,channels:[r],handler:({data:w})=>{const y=f||this._retrieveCallId(w,r);if(y&&n.calls.hasOwnProperty(y)){const T=n.calls[y];T._addChannel(r),T.extension=o,T.handleConferenceUpdate(w,e).then(x=>{x==="INVALID_PACKET"&&g()})}}},_=yield n.vertoSubscribe(v).catch(w=>{k.error("liveArray subscription error:",w);const y=ae(Xy,w);U(O.Error,{error:y,sessionId:n.sessionid},n.uuid)});cr(_,r)&&g();break}case"conference-liveArray-part":{let g=null;if(r&&n._existsSubscription(i,r)){const{callId:_=null}=n.subscriptions[i][r];if(g=n.calls[_]||null,_!==null){const w={type:et.conferenceUpdate,action:ze.Leave,conferenceName:o,participantId:Number(u),role:d};U(O.Notification,w,_,!1)||U(O.Notification,w,n.uuid),g===null&&Mt(O.Notification,null,_)}}const v=[r,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:v}).then(({unsubscribedChannels:_=[]})=>{g&&(g.channels=g.channels.filter(w=>!_.includes(w)))}).catch(_=>{k.error("liveArray unsubscribe error:",_)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":$u(this.session,e);break;case"logo-info":{const n={type:et.conferenceUpdate,action:ze.LogoInfo,logo:e.logoURL};U(O.Notification,n,this.session.uuid);break}}}}class o0 extends i0{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>F(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>F(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new s0(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(k.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return is(this.options)||si(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ae(qy,void 0,"Error: destinationNumber is required");const n=new Jt(this,e);return performance.mark("new-call-start"),n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!si(this.options)||!!e.destinationNumber}_onSocketOpen(){return F(this,void 0,void 0,function*(){return is(this.options)?this.handleLoginOnSocketOpen():si(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class r0 extends o0{constructor(e){super(e),k.info(`SDK version: ${Eu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return z_()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:we.not_supported},{browserName:"Firefox",supported:we.not_supported},{browserName:"Safari",features:["video","audio"],supported:we.full},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",features:["video","audio"],supported:we.full},{browserName:"Edge",features:["audio"],supported:we.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",features:["audio"],supported:we.partial}]}]}}function qu(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ku={exports:{}},Xu;function a0(){return Xu||(Xu=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,u){this.fn=l,this.context=c,this.once=u||!1}function r(l,c,u,d,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||l,f),v=n?n+c:c;return l._events[v]?l._events[v].fn?l._events[v]=[l._events[v],g]:l._events[v].push(g):(l._events[v]=g,l._eventsCount++),l}function o(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,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},a.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,f,g){var v=n?n+l:l;if(!this._events[v])return!1;var _=this._events[v],w=arguments.length,y,T;if(_.fn){switch(_.once&&this.removeListener(l,_.fn,void 0,!0),w){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,u),!0;case 4:return _.fn.call(_.context,c,u,d),!0;case 5:return _.fn.call(_.context,c,u,d,f),!0;case 6:return _.fn.call(_.context,c,u,d,f,g),!0}for(T=1,y=new Array(w-1);T<w;T++)y[T-1]=arguments[T];_.fn.apply(_.context,y)}else{var x=_.length,I;for(T=0;T<x;T++)switch(_[T].once&&this.removeListener(l,_[T].fn,void 0,!0),w){case 1:_[T].fn.call(_[T].context);break;case 2:_[T].fn.call(_[T].context,c);break;case 3:_[T].fn.call(_[T].context,c,u);break;case 4:_[T].fn.call(_[T].context,c,u,d);break;default:if(!y)for(I=1,y=new Array(w-1);I<w;I++)y[I-1]=arguments[I];_[T].fn.apply(_[T].context,y)}}return!0},a.prototype.on=function(l,c,u){return r(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return r(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!d||g.once)&&(!u||g.context===u)&&o(this,f);else{for(var v=0,_=[],w=g.length;v<w;v++)(g[v].fn!==c||d&&!g[v].once||u&&g[v].context!==u)&&_.push(g[v]);_.length?this._events[f]=_.length===1?_[0]:_:o(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&o(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}(Ku)),Ku.exports}var l0=a0();const hr=qu(l0),cs=new hr;var fr={exports:{}},c0=fr.exports,Yu;function d0(){return Yu||(Yu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(c0,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"],r={},o=null;function a(_,w){var y=_[w];if(typeof y.bind=="function")return y.bind(_);try{return Function.prototype.bind.call(y,_)}catch{return function(){return Function.prototype.apply.apply(y,[_,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(_){return _==="debug"&&(_="log"),typeof console===n?!1:_==="trace"&&i?l:console[_]!==void 0?a(console,_):console.log!==void 0?a(console,"log"):e}function u(){for(var _=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<_?e:this.methodFactory(y,_,this.name)}if(this.log=this.debug,typeof console===n&&_<this.levels.SILENT)return"No console available for logging"}function d(_){return function(){typeof console!==n&&(u.call(this),this[_].apply(this,arguments))}}function f(_,w,y){return c(_)||d.apply(this,arguments)}function g(_,w){var y=this,T,x,I,A="loglevel";typeof _=="string"?A+=":"+_:typeof _=="symbol"&&(A=void 0);function M(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!A)){try{window.localStorage[A]=b;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!A)){try{h=window.localStorage[A]}catch{}if(typeof h===n)try{var b=window.document.cookie,E=encodeURIComponent(A),D=b.indexOf(E+"=");D!==-1&&(h=/^([^;]+)/.exec(b.slice(D+E.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=_,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return I??x??T},y.setLevel=function(h,b){return I=p(h),b!==!1&&M(I),u.call(y)},y.setDefaultLevel=function(h){x=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){I=null,C(),u.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(o!==y&&(T=p(o.getLevel())),u.call(y),o===y)for(var h in r)r[h].rebuild()},T=p(o?o.getLevel():"WARN");var m=S();m!=null&&(I=p(m)),u.call(y)}o=new g,o.getLogger=function(_){if(typeof _!="symbol"&&typeof _!="string"||_==="")throw new TypeError("You must supply a name when creating a logger.");var w=r[_];return w||(w=r[_]=new g(_,o.methodFactory)),w};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return r},o.default=o,o})}(fr)),fr.exports}var u0=d0();const h0=qu(u0),f0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Pe=h0.getLogger("telnyx-ai-agent"),p0=Pe.methodFactory;Pe.methodFactory=(t,e,n)=>{const i=p0(t,e,n);return function(...s){i(f0(),"-",...s)}},Pe.setLevel("info");function m0(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const g0=10,v0=500,y0=100,Ju=20;class _0{constructor(e){J(this,"remoteIntervalId",null);J(this,"localIntervalId",null);J(this,"remoteStream",null);J(this,"localStream",null);J(this,"remoteAudioContext",null);J(this,"remoteSource",null);J(this,"remoteAnalyser",null);J(this,"localAudioContext",null);J(this,"localSource",null);J(this,"localAnalyser",null);J(this,"thinkingStartTime",null);J(this,"lastState",null);J(this,"userIsSpeaking",!1);J(this,"lastUserAudioTime",null);J(this,"userSpeechStartTime",null);J(this,"userSilenceStartTime",null);J(this,"isFirstAgentSpeech",!0);J(this,"monitorStartTime",null);J(this,"volumeThreshold");J(this,"silenceDurationMs");J(this,"minSpeechDurationMs");J(this,"maxLatencyMs");J(this,"updateAgentState",m0(e=>{Pe.debug("AudioStreamMonitor updateAgentState",e),Pe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,cs.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??g0,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??v0,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??y0,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){Pe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Pe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Pe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var r;Pe.debug("AudioContext resumed, state:",(r=this.remoteAudioContext)==null?void 0:r.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 r=n.reduce((l,c)=>l+c,0)/n.length,o=r>=this.volumeThreshold;if(Math.random()<.01&&Pe.debug("Remote audio volume:",r,"threshold:",this.volumeThreshold,"above:",o),o)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=o};this.remoteIntervalId=window.setInterval(s,Ju)}startLocalMonitor(){if(!this.localStream){Pe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Pe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Pe.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((r,o)=>r+o,0)/e.length;if(Math.random()<.02&&Pe.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 r=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:r})}};this.localIntervalId=window.setInterval(n,Ju)}destroy(){this.stopAudioStreamMonitor()}}function b0(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function w0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function S0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function C0(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 T0(t){return w0(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function k0(t){if(!S0(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 x0 extends hr{constructor(n){super();J(this,"telnyxRTC");J(this,"transcript",[]);J(this,"onSocketMessage",n=>{if(b0(n))switch(n.params.type){case"response.text.delta":{const i=T0(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),cs.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(C0(n)){const i=n.params.item_id,s=this.transcript.findIndex(r=>r.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=k0(n);if(i){const s=this.transcript.findIndex(r=>r.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(O.SocketMessage,this.onSocketMessage)}}class E0 extends hr{constructor(n){super();J(this,"telnyxRTC");J(this,"transcription");J(this,"agentId");J(this,"versionId");J(this,"conversationId");J(this,"debug");J(this,"audioStreamMonitor");J(this,"activeCall");J(this,"chatMode");J(this,"dc",null);J(this,"region",null);J(this,"callReportId",null);J(this,"onClientReady",()=>{const n=this.telnyxRTC;this.dc=n.dc??null,this.region=n.region??null,this.callReportId=n.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});J(this,"onClientOrSocketError",n=>{this.emit("agent.error",n.error)});J(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()))});J(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});J(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,Pe.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 r0({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region}),this.telnyxRTC.on(O.Ready,this.onClientReady),this.telnyxRTC.on(O.Error,this.onClientOrSocketError),this.telnyxRTC.on(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(O.Notification,this.onNotification),this.transcription=new x0(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),cs.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new _0(n.vad)}async connect(){return this.telnyxRTC.connect()}clearReconnectToken(){var n,i;(i=(n=this.telnyxRTC).clearReconnectToken)==null||i.call(n)}async retryLogin(){var n,i;return(i=(n=this.telnyxRTC).relogin)==null?void 0:i.call(n)}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(O.Ready,this.onClientReady),this.telnyxRTC.off(O.Error,this.onClientOrSocketError),this.telnyxRTC.off(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(O.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),cs.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Pe.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,u;if(!this.telnyxRTC){Pe.error("Client is not initialized.");return}const i=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:r,...o}=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",...o,audio:this.chatMode?!1:r??!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 Zu={exports:{}},hi={},Qu;function I0(){if(Qu)return hi;Qu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,r){var o=null;if(r!==void 0&&(o=""+r),s.key!==void 0&&(o=""+s.key),"key"in s){r={};for(var a in s)a!=="key"&&(r[a]=s[a])}else r=s;return s=r.ref,{$$typeof:t,type:i,key:o,ref:s!==void 0?s:null,props:r}}return hi.Fragment=e,hi.jsx=n,hi.jsxs=n,hi}var eh;function A0(){return eh||(eh=1,Zu.exports=I0()),Zu.exports}A0(),bt(void 0),bt(null);const R0=(t,e,n,i,s,r,o,a,l)=>new E0({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:r,conversationId:o,chatMode:a,region:l}),ds=10,th=5e3,L0=[46001,46003],D0=["login incorrect","authentication required","authentication failed"];function P0(t){var i;const e=t.code;if(e&&L0.includes(e))return!0;const n=((i=t.message)==null?void 0:i.toLowerCase())||"";return D0.some(s=>n.includes(s))}const M0=(t,e,n,i,s,r,o,a,l)=>{const[c,u]=xe(null),[d,f]=xe(!1),[g,v]=xe(null),[_,w]=xe(!1),y=ce(0),T=ce(null),x=ce(null),I=ce(!1),A=Ge(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),M=Ge(C=>{if(A(),y.current>=ds){ue.error(`Max login retry attempts (${ds}) exceeded`),w(!1);return}y.current+=1,ue.info(`Scheduling login retry attempt ${y.current}/${ds} in ${th}ms due to: ${C}`),w(!0),T.current=window.setTimeout(()=>{var p,m;T.current=null,x.current&&(ue.info(`Executing reconnect attempt ${y.current} (disconnect + clear token + connect)`),x.current.disconnect(),(m=(p=x.current).clearReconnectToken)==null||m.call(p),x.current.connect())},th)},[A]),S=Ge(()=>{A(),y.current=0,w(!1),v(null)},[A]);return Ee(()=>{if(!t)return;const C=R0(t,e,n,i,s,r,o,a,l);x.current=C;const p=()=>{ue.info("Agent connected successfully"),I.current=!0,f(!0),S()},m=()=>{ue.info("Agent disconnected"),I.current=!1,f(!1)},h=b=>{if(ue.error("AI Agent error:",b),P0(b)){if(I.current){ue.debug("Ignoring retryable error — already connected");return}y.current<ds?(v(null),M(b.message)):(v(b),w(!1))}else v(b),w(!1)};return C.on("agent.connected",p),C.on("agent.disconnected",m),C.on("agent.error",h),C.connect(),u(C),()=>{A(),C.off("agent.connected",p),C.off("agent.disconnected",m),C.off("agent.error",h),C.disconnect(),x.current=null}},[t,e,n,i,s,r,o,a,l,A,S,M]),{client:c,isConnected:d,error:g,isReconnecting:_}},N0="telnyx-ai-agent",Nt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function nh(){const t=document.querySelector(N0);return t instanceof HTMLElement?t:null}function Ot(t,e,n){const i=n||nh();if(!i){ue.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),ue.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const O0=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:r}=e,o=ce(null),a=Ei(Gd);Ee(()=>{o.current=nh()},[]),Ee(()=>{if(!t)return;const l=o.current,c=()=>{n();const A=t.telnyxRTC,M={dc:(A==null?void 0:A.dc)??null,region:(A==null?void 0:A.region)??null,callReportId:(A==null?void 0:A.callReportId)??null};a(M),Ot(Nt.AGENT_CONNECTED,M,l)},u=()=>{a(null),Ot(Nt.AGENT_DISCONNECTED,void 0,l)},d=I=>{s(I);const A={message:I.message,name:I.name};Ot(Nt.AGENT_ERROR,A,l)},f=I=>{var A;i(I),Ot(Nt.CONVERSATION_UPDATE,{type:I.type,callState:(A=I.call)==null?void 0:A.state},l)},g=I=>{Ot(Nt.TRANSCRIPT_ITEM,I,l)},v=I=>{Ot(Nt.CONVERSATION_AGENT_STATE,I,l)},_=I=>{Ot(Nt.AGENT_AUDIO_MUTE,{muted:I},l)},y=t.telnyxRTC,T=I=>{r(I)},x=I=>{const A=I,M={code:A==null?void 0:A.code,reason:A==null?void 0:A.reason,wasClean:A==null?void 0:A.wasClean,timestamp:new Date().toISOString()};ue.info("[socket.close]",M),Ot(Nt.SOCKET_CLOSE,M,l)};return y&&typeof y=="object"&&(y.on(O.SocketMessage,T),y.on(O.SocketClose,x)),t.on("agent.connected",c),t.on("agent.disconnected",u),t.on("agent.error",d),t.on("conversation.update",f),t.on("transcript.item",g),t.on("conversation.agent.state",v),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",c),t.off("agent.disconnected",u),t.off("agent.error",d),t.off("conversation.update",f),t.off("transcript.item",g),t.off("conversation.agent.state",v),t.off("agent.audio.mute",_),y&&typeof y=="object"&&(y.off(O.SocketMessage,T),y.off(O.SocketClose,x))}},[t,n,i,s,r,a])},F0=2e3;async function V0(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function ih(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 B0=(t,e)=>{const[n,i]=xe([]),[,s]=Xo(),r=ce(e);Ee(()=>{r.current=e},[e]);const o=ce(void 0),a=ce(void 0);return Ee(()=>{if(!t)return;const c=f=>{i(g=>{const v=g[g.length-1];if(f.role==="assistant"&&v&&ih(v.id)===ih(f.id)&&v.role==="assistant"){const _=r.current.showUserPerceivedLatency&&o.current!==void 0&&v.userPerceivedLatencyMs===void 0,w=r.current.showGreetingLatency&&a.current!==void 0&&v.greetingLatencyMs===void 0,y={...v,content:v.content+f.content,timestamp:f.timestamp,..._&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return _&&(o.current=void 0),w&&(a.current=void 0),[...g.slice(0,-1),y]}if(f.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const _=r.current.showUserPerceivedLatency&&o.current!==void 0,w=r.current.showGreetingLatency&&a.current!==void 0;if(_||w){const y={...f,..._&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return o.current=void 0,a.current=void 0,[...g,y]}o.current=void 0,a.current=void 0}if(f.role==="user"){const _=g.findIndex(y=>y.id===f.id);if(_!==-1){const y=[...g];return y[_]={...g[_],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(v&&v.role==="user"&&f.timestamp.getTime()-v.timestamp.getTime()<F0){const T={...v,id:f.id,content:v.content+" "+f.content,timestamp:f.timestamp,attachments:[...v.attachments||[],...f.attachments||[]]};return[...g.slice(0,-1),T]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...g,f]})},u=({state:f,userPerceivedLatencyMs:g,greetingLatencyMs:v,thinkingStartedAt:_})=>{(g!==void 0||v!==void 0)&&ue.info(`[AgentState] state=${f} userPerceivedLatencyMs=${g} greetingLatencyMs=${v} thinkingStartedAt=${_}`),f==="speaking"?(s("speaking"),g!==void 0&&(o.current=g),v!==void 0&&(a.current=v)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},d=f=>{var v;const g=(v=f.call)==null?void 0:v.state;(g==="destroy"||g==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:n,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const f of u)try{const g=await V0(f);d.push(g)}catch(g){throw ue.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,d)}}},U0=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{const r=Xt(),[o,a]=xe(i?"expanded":r.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=B0(e,n),d=ce(!1);switch(Ee(()=>{if(i&&t&&!d.current){const f="remoteStream"in t?t.remoteStream:null;f&&(d.current=!0,f.getAudioTracks().forEach(g=>{g.enabled=!1,ue.info(`[ChatMode] Disabled remote audio track: ${g.label}`)}))}},[i,t]),o){case"collapsed":return R(Qd,{onExpand:l,call:t,client:e,chatMode:i,debug:s});case"expanded":return R(Oy,{transcript:u,onCollapse:c,call:t,chatMode:i,debug:s});default:return R(Qd,{onExpand:l,call:t,client:e,chatMode:i,debug:s})}},pr=()=>R(vn.div,{layoutId:Qn,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:R("div",{className:"rounded-full animate-spin",children:R(hy,{})})}),j0=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return R(pr,{});case"done":case"purged":case"destroy":return null;case"active":return R(U0,{client:e,call:t,latencySettings:n,chatMode:i,debug:s});default:return R(pr,{})}},$0=({className:t})=>R("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:[R("g",{clipPath:"url(#:R5lfm:)",children:[R("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"}),R("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"}),R("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"}),R("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"}),R("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"})]}),R("defs",{children:R("clipPath",{id:":R5lfm:",children:R("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function sh(){const t=Xt();return t.logo_icon_url?R("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:R("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):R($0,{className:"w-8 h-8 mr-2"})}const H0=({client:t,callProps:e,chatMode:n})=>{const i=Xt(),s=ce(!1),r=Ge(()=>{if(!t){ue.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return Ee(()=>{n&&t&&!s.current&&(s.current=!0,ue.info("[ChatMode] Auto-starting conversation"),r())},[n,t,r]),n?R(vn.div,{layoutId:Qn,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:[R(sh,{}),"Connecting..."]}):R(vn.button,{layoutId:Qn,onClick:r,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:[R(sh,{}),i.start_call_text]})},W0='@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-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--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-green-500{background-color:var(--color-green-500)}.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}.opacity-60{opacity:.6}.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-green-600:hover{background-color:var(--color-green-600)}.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)}}',G0=({children:t})=>R("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:R("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),z0={duration:.1,ease:"circOut"},q0=({children:t,position:e="fixed"})=>{const n=Xt(),s=(e??n.position??"fixed")==="fixed"?R(G0,{children:t}):t;return R("div",{className:Ct(n.theme==="dark"&&"dark"),children:R(im,{transition:z0,children:[R("style",{children:W0}),s]})})},K0=t=>R(vn.div,{layoutId:Qn,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:[R(dy,{className:"w-8 h-8 text-red-400"}),R("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),R("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[R("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),R("li",{children:["Make sure that the"," ",R("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"," ",R(_y,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&R("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[R(vy,{className:"w-4 h-4"}),"Retry"]})]});function fi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function X0({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":r,"call-custom-headers":o,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":f,region:g,environment:v,position:_="fixed","version-id":w}){const y=fi(e),T=fi(n),x=fi(f),I=Xe(()=>{if(l)try{return JSON.parse(l)}catch(H){ue.error("Invalid JSON for vad attribute:",l,H);return}},[l]),A=Xe(()=>({showUserPerceivedLatency:fi(c),showGreetingLatency:fi(u)}),[c,u]),{client:M,error:S,isReconnecting:C}=M0(t,v,w,y,T,I,d,x,g),[p,m]=xe(null),[h,b]=xe(!1),[E,D]=xe(!1),[L,N]=xe(!1),[P,B]=xe(!1),X=Ei(Jd),j=Fv(),ie={};if(i&&(ie.destinationNumber=i),s&&(ie.callerNumber=s),r&&(ie.callerName=r),o)try{ie.customHeaders=JSON.parse(o)}catch(H){ue.error("Invalid JSON for call-custom-headers attribute:",o,H)}if(a)try{ie.audio=JSON.parse(a);const H=ie.audio;if(typeof H=="object"){const se=navigator.mediaDevices.getSupportedConstraints();Object.keys(H).forEach(Ae=>{se[Ae]||ue.warn(`Audio constraint not supported by browser: ${Ae}`)})}}catch(H){ue.error("Invalid JSON for call-audio attribute:",a,H)}const ne=Ge(()=>{b(!1)},[]),$=Ge(H=>{var se;if(((se=H.call)==null?void 0:se.state)==="destroy")return X(!1),B(!0),m(null);m(H)},[X]),de=Ge(()=>{b(!1),C||D(!0)},[C]),Y=Ge(()=>{ue.info("User triggered retry"),D(!1),b(!0),M&&M.connect()},[M]),Q=Ge(H=>{if(Ov(H)){const se=H.params.widget_settings;se&&Object.keys(se).length>0&&(j(se),N(!0))}},[j]);return O0(M,{onReady:ne,onConversationUpdate:$,onError:de,onConfigMessage:Q}),R(q0,{position:_,children:t?E||S?R(K0,{agentId:t,onRetry:Y}):h||C?R(pr,{message:C?"Retrying...":void 0}):p!=null&&p.call?R(j0,{call:p.call,client:M,latencySettings:A,chatMode:x,debug:y}):L?R(H0,{client:M,callProps:ie,chatMode:x&&!P}):null:R("div",{children:"Please provide an assistant ID."})})}wh(X0,"telnyx-ai-agent",Mv,{shadow:!0})})();
119
+ `)}))}),k.info(i)}),2e3)}}class i0 extends ai{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 F(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return F(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return F(this,void 0,void 0,function*(){try{const i=yield os({audio:e,video:n});return ci(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return F(this,void 0,void 0,function*(){k.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(q.Purge),k.info("Start hangup for ",i),yield i.hangup({},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return F(this,void 0,void 0,function*(){k.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(q.Purge),i.hangup({},!1)}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(wu(O.SpeedTest,o=>{const{upDur:a,downDur:l}=o,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 r=".".repeat(1024);for(let o=0;o<s;o++)this.executeRaw(`#SPB ${r}`);this.executeRaw("#SPE")})}getDevices(){return di().catch(e=>{const n=ae(ii(e),e);return U(O.MediaError,n,this.uuid),[]})}getVideoDevices(){return di(mt.Video).catch(e=>(U(O.MediaError,e,this.uuid),[]))}getAudioInDevices(){return di(mt.AudioIn).catch(e=>{const n=ae(ii(e),e);return U(O.MediaError,n,this.uuid),[]})}getAudioOutDevices(){return di(mt.AudioOut).catch(e=>(k.error("getAudioOutDevices",e),U(O.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return rs(e,n,i)}getDeviceResolutions(e){return F(this,void 0,void 0,function*(){try{return yield(n=>F(void 0,void 0,void 0,function*(){const i=[],s=yield os({video:{deviceId:{exact:n}}}),r=s.getVideoTracks()[0];for(let o=0;o<Pu.length;o++){const[a,l]=Pu[o];(yield r.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return ci(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return F(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=Zi(e,["micId","micLabel"]);return W_(s),this._audioConstraints=yield((r,o,a,l)=>F(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(r||o)){const u=yield rs(r,o,a).catch(d=>null);u&&(l.deviceId={exact:u})}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?y_:v_}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=ns(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=ns(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 B_({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(r=>r)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return F(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new U_({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const r=yield this.execute(s),{unauthorized:o=[],subscribed:a=[]}=dr(r);return o.length&&o.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),r})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return F(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new j_({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:r=[],notSubscribed:o=[]}=dr(s);return r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(k.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,k.debug(`Network connectivity lost for session ${this.sessionid}`);const e=ae(n_);U(O.Error,{error:e,sessionId:this.sessionid},this.uuid)},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 Jt.setStateTelnyx(e)}}class zu{constructor(e,n){this.code=n,this.message=e}}class s0{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,n){const i=new N_(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*yu(2,6)}handleMessage(e){var n,i,s,r,o,a,l,c,u;const{session:d}=this;d.setPingReceived();const{id:f,method:g,params:v={},voice_sdk_id:_}=e,w=v==null?void 0:v.callID,y=v==null?void 0:v.eventChannel,T=v==null?void 0:v.eventType,x=d.calls[w],I=(n=x==null?void 0:x.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(Array.isArray(v==null?void 0:v.reattached_sessions)&&v.reattached_sessions.length===0&&Object.keys(d.calls).length>0){const C=Dt(p_);U(O.Warning,{warning:C,sessionId:d.sessionid},d.uuid)}if(T==="channelPvtData")return this._handlePvtEvent(v.pvtData);const A=C=>{var p,m,h,b,E,D;const L={audio:!0,video:d.options.video,remoteSdp:v.sdp,destinationNumber:v.callee_id_number,remoteCallerName:v.caller_id_name,remoteCallerNumber:v.caller_id_number,callerName:v.callee_id_name,callerNumber:v.callee_id_number,attach:g===te.Attach,mediaSettings:v.mediaSettings,debug:(p=d.options.debug)!==null&&p!==void 0&&p,debugOutput:(m=d.options.debugOutput)!==null&&m!==void 0?m:"socket",trickleIce:(h=d.options.trickleIce)!==null&&h!==void 0&&h,prefetchIceCandidates:(b=d.options.prefetchIceCandidates)===null||b===void 0||b,forceRelayCandidate:(E=d.options.forceRelayCandidate)!==null&&E!==void 0&&E,keepConnectionAliveOnSocketClose:(D=d.options.keepConnectionAliveOnSocketClose)!==null&&D!==void 0&&D};w&&(L.id=w),v.telnyx_call_control_id&&(L.telnyxCallControlId=v.telnyx_call_control_id),v.telnyx_session_id&&(L.telnyxSessionId=v.telnyx_session_id),v.telnyx_leg_id&&(L.telnyxLegId=v.telnyx_leg_id),v.client_state&&(L.clientState=v.client_state),v.dialogParams&&v.dialogParams.custom_headers&&v.dialogParams.custom_headers.length&&(L.customHeaders=v.dialogParams.custom_headers),C&&(L.recoveredCallId=C),performance.mark("new-call-start");const N=new Jt(d,L);return N.nodeId=this.nodeId,N},M=new ku(_),S=new xu(_);switch(g){case te.Answer:case te.Display:case te.Candidate:case te.Ringing:case te.Bye:case te.Media:if(!w||!x)return void k.error(`Received ${g} for non existing call:`,v);x.handleMessage(e),this._ack(f,g);break;case te.Ping:this.session.setPingReceived(),this.session.execute(S);break;case te.Punt:d.options.keepConnectionAliveOnSocketClose&&I?(k.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(f,g)):(k.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case te.Invite:{const m=A();m.direction=pt.Inbound,m.playRingtone(),m.setState(q.Ringing),this._ack(f,g);break}case te.Attach:{if(!x)return A().answer(),void this._ack(f,g);const m=x.id;k.info(`[${new Date().toISOString()}][${w}] closing existing call on ATTACH.`),x.hangup({isRecovering:!0},!1),k.info(`[${new Date().toISOString()}][${w}] Attach: Creating new call for recovery (recoveredCallId: ${m})`),A(m).answer(),this._ack(f,g);break}case te.Event:case"webrtc.event":if(!y)return void k.error("Verto received an unknown event:",v);const C=d.relayProtocol,p=y.split(".")[0];d._existsSubscription(C,y)?U(C,v,y):y===d.sessionid?this._handleSessionEvent(v.eventData):d._existsSubscription(C,p)?U(C,v,p):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):U(O.Notification,v,d.uuid);break;case te.Info:v.type=et.generic,U(O.Notification,v,d.uuid);break;case te.ClientReady:this.session.execute(M);break;default:{const m=ir(e);if(m){switch(m){case Ue.REGISTER:case Ue.REGED:if(d.connection.previousGatewayState!==Ue.REGED&&d.connection.previousGatewayState!==Ue.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const h=(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;h&&(d.callReportId=h,k.debug("Captured call_report_id from REGED:",h));const b=(o=(r=e==null?void 0:e.result)===null||r===void 0?void 0:r.params)===null||o===void 0?void 0:o.dc;b&&(d.dc=b);const E=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;E&&(d.region=E),k.info(`Connected to Telnyx — region: ${(c=d.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=d.dc)!==null&&u!==void 0?u:"unknown"}`),v.type=et.vertoClientReady,U(O.Ready,v,d.uuid)}break;case Ue.UNREGED:case Ue.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const h=new zu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),b=ae(ru,h);U(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(M)},this.reconnectDelay());break;case Ue.FAILED:case Ue.FAIL_WAIT:if(d.connection.previousGatewayState!==Ue.FAILED&&d.connection.previousGatewayState!==Ue.FAIL_WAIT){const h=ae(Qy,new Error(`Gateway state: ${m}`));if(U(O.Error,{error:h,sessionId:d.sessionid},d.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const b=new zu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),E=ae(Zy,b);U(O.Error,{error:E,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0;const b=ae(45003,new Error("Connection Retry Failed"));U(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(k.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(b=>{var E;return((E=b.peer)===null||E===void 0?void 0:E.instance)&&!b.signalingStateClosed}))return k.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();k.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:k.warn("GatewayState message unknown method:",e)}break}k.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(r=>i.includes(r[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return F(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:r,laName:o,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:f}=e;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:r,data:{liveArray:{command:"bootstrap",context:r,name:o}}})},v={nodeId:this.nodeId,channels:[r],handler:({data:w})=>{const y=f||this._retrieveCallId(w,r);if(y&&n.calls.hasOwnProperty(y)){const T=n.calls[y];T._addChannel(r),T.extension=o,T.handleConferenceUpdate(w,e).then(x=>{x==="INVALID_PACKET"&&g()})}}},_=yield n.vertoSubscribe(v).catch(w=>{k.error("liveArray subscription error:",w);const y=ae(Xy,w);U(O.Error,{error:y,sessionId:n.sessionid},n.uuid)});cr(_,r)&&g();break}case"conference-liveArray-part":{let g=null;if(r&&n._existsSubscription(i,r)){const{callId:_=null}=n.subscriptions[i][r];if(g=n.calls[_]||null,_!==null){const w={type:et.conferenceUpdate,action:ze.Leave,conferenceName:o,participantId:Number(u),role:d};U(O.Notification,w,_,!1)||U(O.Notification,w,n.uuid),g===null&&Mt(O.Notification,null,_)}}const v=[r,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:v}).then(({unsubscribedChannels:_=[]})=>{g&&(g.channels=g.channels.filter(w=>!_.includes(w)))}).catch(_=>{k.error("liveArray unsubscribe error:",_)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":$u(this.session,e);break;case"logo-info":{const n={type:et.conferenceUpdate,action:ze.LogoInfo,logo:e.logoURL};U(O.Notification,n,this.session.uuid);break}}}}class o0 extends i0{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>F(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>F(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new s0(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(k.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return is(this.options)||si(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ae(qy,void 0,"Error: destinationNumber is required");const n=new Jt(this,e);return performance.mark("new-call-start"),n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!si(this.options)||!!e.destinationNumber}_onSocketOpen(){return F(this,void 0,void 0,function*(){return is(this.options)?this.handleLoginOnSocketOpen():si(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class r0 extends o0{constructor(e){super(e),k.info(`SDK version: ${Eu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return z_()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:we.not_supported},{browserName:"Firefox",supported:we.not_supported},{browserName:"Safari",features:["video","audio"],supported:we.full},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",features:["video","audio"],supported:we.full},{browserName:"Edge",features:["audio"],supported:we.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",features:["audio"],supported:we.partial}]}]}}function qu(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ku={exports:{}},Xu;function a0(){return Xu||(Xu=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,u){this.fn=l,this.context=c,this.once=u||!1}function r(l,c,u,d,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||l,f),v=n?n+c:c;return l._events[v]?l._events[v].fn?l._events[v]=[l._events[v],g]:l._events[v].push(g):(l._events[v]=g,l._eventsCount++),l}function o(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,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},a.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,f,g){var v=n?n+l:l;if(!this._events[v])return!1;var _=this._events[v],w=arguments.length,y,T;if(_.fn){switch(_.once&&this.removeListener(l,_.fn,void 0,!0),w){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,u),!0;case 4:return _.fn.call(_.context,c,u,d),!0;case 5:return _.fn.call(_.context,c,u,d,f),!0;case 6:return _.fn.call(_.context,c,u,d,f,g),!0}for(T=1,y=new Array(w-1);T<w;T++)y[T-1]=arguments[T];_.fn.apply(_.context,y)}else{var x=_.length,I;for(T=0;T<x;T++)switch(_[T].once&&this.removeListener(l,_[T].fn,void 0,!0),w){case 1:_[T].fn.call(_[T].context);break;case 2:_[T].fn.call(_[T].context,c);break;case 3:_[T].fn.call(_[T].context,c,u);break;case 4:_[T].fn.call(_[T].context,c,u,d);break;default:if(!y)for(I=1,y=new Array(w-1);I<w;I++)y[I-1]=arguments[I];_[T].fn.apply(_[T].context,y)}}return!0},a.prototype.on=function(l,c,u){return r(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return r(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!d||g.once)&&(!u||g.context===u)&&o(this,f);else{for(var v=0,_=[],w=g.length;v<w;v++)(g[v].fn!==c||d&&!g[v].once||u&&g[v].context!==u)&&_.push(g[v]);_.length?this._events[f]=_.length===1?_[0]:_:o(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&o(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}(Ku)),Ku.exports}var l0=a0();const hr=qu(l0),cs=new hr;var fr={exports:{}},c0=fr.exports,Yu;function d0(){return Yu||(Yu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(c0,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"],r={},o=null;function a(_,w){var y=_[w];if(typeof y.bind=="function")return y.bind(_);try{return Function.prototype.bind.call(y,_)}catch{return function(){return Function.prototype.apply.apply(y,[_,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(_){return _==="debug"&&(_="log"),typeof console===n?!1:_==="trace"&&i?l:console[_]!==void 0?a(console,_):console.log!==void 0?a(console,"log"):e}function u(){for(var _=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<_?e:this.methodFactory(y,_,this.name)}if(this.log=this.debug,typeof console===n&&_<this.levels.SILENT)return"No console available for logging"}function d(_){return function(){typeof console!==n&&(u.call(this),this[_].apply(this,arguments))}}function f(_,w,y){return c(_)||d.apply(this,arguments)}function g(_,w){var y=this,T,x,I,A="loglevel";typeof _=="string"?A+=":"+_:typeof _=="symbol"&&(A=void 0);function M(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!A)){try{window.localStorage[A]=b;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!A)){try{h=window.localStorage[A]}catch{}if(typeof h===n)try{var b=window.document.cookie,E=encodeURIComponent(A),D=b.indexOf(E+"=");D!==-1&&(h=/^([^;]+)/.exec(b.slice(D+E.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=_,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return I??x??T},y.setLevel=function(h,b){return I=p(h),b!==!1&&M(I),u.call(y)},y.setDefaultLevel=function(h){x=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){I=null,C(),u.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(o!==y&&(T=p(o.getLevel())),u.call(y),o===y)for(var h in r)r[h].rebuild()},T=p(o?o.getLevel():"WARN");var m=S();m!=null&&(I=p(m)),u.call(y)}o=new g,o.getLogger=function(_){if(typeof _!="symbol"&&typeof _!="string"||_==="")throw new TypeError("You must supply a name when creating a logger.");var w=r[_];return w||(w=r[_]=new g(_,o.methodFactory)),w};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return r},o.default=o,o})}(fr)),fr.exports}var u0=d0();const h0=qu(u0),f0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Pe=h0.getLogger("telnyx-ai-agent"),p0=Pe.methodFactory;Pe.methodFactory=(t,e,n)=>{const i=p0(t,e,n);return function(...s){i(f0(),"-",...s)}},Pe.setLevel("info");function m0(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const g0=10,v0=500,y0=100,Ju=20;class _0{constructor(e){J(this,"remoteIntervalId",null);J(this,"localIntervalId",null);J(this,"remoteStream",null);J(this,"localStream",null);J(this,"remoteAudioContext",null);J(this,"remoteSource",null);J(this,"remoteAnalyser",null);J(this,"localAudioContext",null);J(this,"localSource",null);J(this,"localAnalyser",null);J(this,"thinkingStartTime",null);J(this,"lastState",null);J(this,"userIsSpeaking",!1);J(this,"lastUserAudioTime",null);J(this,"userSpeechStartTime",null);J(this,"userSilenceStartTime",null);J(this,"isFirstAgentSpeech",!0);J(this,"monitorStartTime",null);J(this,"volumeThreshold");J(this,"silenceDurationMs");J(this,"minSpeechDurationMs");J(this,"maxLatencyMs");J(this,"updateAgentState",m0(e=>{Pe.debug("AudioStreamMonitor updateAgentState",e),Pe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,cs.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??g0,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??v0,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??y0,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){Pe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Pe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Pe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var r;Pe.debug("AudioContext resumed, state:",(r=this.remoteAudioContext)==null?void 0:r.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 r=n.reduce((l,c)=>l+c,0)/n.length,o=r>=this.volumeThreshold;if(Math.random()<.01&&Pe.debug("Remote audio volume:",r,"threshold:",this.volumeThreshold,"above:",o),o)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=o};this.remoteIntervalId=window.setInterval(s,Ju)}startLocalMonitor(){if(!this.localStream){Pe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Pe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Pe.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((r,o)=>r+o,0)/e.length;if(Math.random()<.02&&Pe.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 r=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:r})}};this.localIntervalId=window.setInterval(n,Ju)}destroy(){this.stopAudioStreamMonitor()}}function b0(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function w0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function S0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function C0(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 T0(t){return w0(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function k0(t){if(!S0(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 x0 extends hr{constructor(n){super();J(this,"telnyxRTC");J(this,"transcript",[]);J(this,"onSocketMessage",n=>{if(b0(n))switch(n.params.type){case"response.text.delta":{const i=T0(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),cs.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(C0(n)){const i=n.params.item_id,s=this.transcript.findIndex(r=>r.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=k0(n);if(i){const s=this.transcript.findIndex(r=>r.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(O.SocketMessage,this.onSocketMessage)}}class E0 extends hr{constructor(n){super();J(this,"telnyxRTC");J(this,"transcription");J(this,"agentId");J(this,"versionId");J(this,"conversationId");J(this,"debug");J(this,"audioStreamMonitor");J(this,"activeCall");J(this,"chatMode");J(this,"dc",null);J(this,"region",null);J(this,"callReportId",null);J(this,"onClientReady",()=>{const n=this.telnyxRTC;this.dc=n.dc??null,this.region=n.region??null,this.callReportId=n.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});J(this,"onClientOrSocketError",n=>{this.emit("agent.error",n.error)});J(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()))});J(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});J(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,Pe.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 r0({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region}),this.telnyxRTC.on(O.Ready,this.onClientReady),this.telnyxRTC.on(O.Error,this.onClientOrSocketError),this.telnyxRTC.on(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(O.Notification,this.onNotification),this.transcription=new x0(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),cs.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new _0(n.vad)}async connect(){return this.telnyxRTC.connect()}clearReconnectToken(){var n,i;(i=(n=this.telnyxRTC).clearReconnectToken)==null||i.call(n)}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(O.Ready,this.onClientReady),this.telnyxRTC.off(O.Error,this.onClientOrSocketError),this.telnyxRTC.off(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(O.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),cs.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Pe.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,u;if(!this.telnyxRTC){Pe.error("Client is not initialized.");return}const i=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:r,...o}=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",...o,audio:this.chatMode?!1:r??!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 Zu={exports:{}},hi={},Qu;function I0(){if(Qu)return hi;Qu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,r){var o=null;if(r!==void 0&&(o=""+r),s.key!==void 0&&(o=""+s.key),"key"in s){r={};for(var a in s)a!=="key"&&(r[a]=s[a])}else r=s;return s=r.ref,{$$typeof:t,type:i,key:o,ref:s!==void 0?s:null,props:r}}return hi.Fragment=e,hi.jsx=n,hi.jsxs=n,hi}var eh;function A0(){return eh||(eh=1,Zu.exports=I0()),Zu.exports}A0(),bt(void 0),bt(null);const R0=(t,e,n,i,s,r,o,a,l)=>new E0({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:r,conversationId:o,chatMode:a,region:l}),ds=10,th=5e3,L0=[46001,46003],D0=["login incorrect","authentication required","authentication failed"];function P0(t){var i;const e=t.code;if(e&&L0.includes(e))return!0;const n=((i=t.message)==null?void 0:i.toLowerCase())||"";return D0.some(s=>n.includes(s))}const M0=(t,e,n,i,s,r,o,a,l)=>{const[c,u]=xe(null),[d,f]=xe(!1),[g,v]=xe(null),[_,w]=xe(!1),y=ce(0),T=ce(null),x=ce(null),I=ce(!1),A=Ge(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),M=Ge(C=>{if(A(),y.current>=ds){ue.error(`Max login retry attempts (${ds}) exceeded`),w(!1);return}y.current+=1,ue.info(`Scheduling login retry attempt ${y.current}/${ds} in ${th}ms due to: ${C}`),w(!0),T.current=window.setTimeout(()=>{var p,m;T.current=null,x.current&&(ue.info(`Executing reconnect attempt ${y.current} (disconnect + clear token + connect)`),x.current.disconnect(),(m=(p=x.current).clearReconnectToken)==null||m.call(p),x.current.connect())},th)},[A]),S=Ge(()=>{A(),y.current=0,w(!1),v(null)},[A]);return Ee(()=>{if(!t)return;const C=R0(t,e,n,i,s,r,o,a,l);x.current=C;const p=()=>{ue.info("Agent connected successfully"),I.current=!0,f(!0),S()},m=()=>{ue.info("Agent disconnected"),I.current=!1,f(!1)},h=b=>{if(ue.error("AI Agent error:",b),P0(b)){if(I.current){ue.debug("Ignoring retryable error — already connected");return}y.current<ds?(v(null),M(b.message)):(v(b),w(!1))}else v(b),w(!1)};return C.on("agent.connected",p),C.on("agent.disconnected",m),C.on("agent.error",h),C.connect(),u(C),()=>{A(),C.off("agent.connected",p),C.off("agent.disconnected",m),C.off("agent.error",h),C.disconnect(),x.current=null}},[t,e,n,i,s,r,o,a,l,A,S,M]),{client:c,isConnected:d,error:g,isReconnecting:_}},N0="telnyx-ai-agent",Nt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function nh(){const t=document.querySelector(N0);return t instanceof HTMLElement?t:null}function Ot(t,e,n){const i=n||nh();if(!i){ue.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),ue.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const O0=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:r}=e,o=ce(null),a=Ei(Gd);Ee(()=>{o.current=nh()},[]),Ee(()=>{if(!t)return;const l=o.current,c=()=>{n();const A=t.telnyxRTC,M={dc:(A==null?void 0:A.dc)??null,region:(A==null?void 0:A.region)??null,callReportId:(A==null?void 0:A.callReportId)??null};a(M),Ot(Nt.AGENT_CONNECTED,M,l)},u=()=>{a(null),Ot(Nt.AGENT_DISCONNECTED,void 0,l)},d=I=>{s(I);const A={message:I.message,name:I.name};Ot(Nt.AGENT_ERROR,A,l)},f=I=>{var A;i(I),Ot(Nt.CONVERSATION_UPDATE,{type:I.type,callState:(A=I.call)==null?void 0:A.state},l)},g=I=>{Ot(Nt.TRANSCRIPT_ITEM,I,l)},v=I=>{Ot(Nt.CONVERSATION_AGENT_STATE,I,l)},_=I=>{Ot(Nt.AGENT_AUDIO_MUTE,{muted:I},l)},y=t.telnyxRTC,T=I=>{r(I)},x=I=>{const A=I,M={code:A==null?void 0:A.code,reason:A==null?void 0:A.reason,wasClean:A==null?void 0:A.wasClean,timestamp:new Date().toISOString()};ue.info("[socket.close]",M),Ot(Nt.SOCKET_CLOSE,M,l)};return y&&typeof y=="object"&&(y.on(O.SocketMessage,T),y.on(O.SocketClose,x)),t.on("agent.connected",c),t.on("agent.disconnected",u),t.on("agent.error",d),t.on("conversation.update",f),t.on("transcript.item",g),t.on("conversation.agent.state",v),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",c),t.off("agent.disconnected",u),t.off("agent.error",d),t.off("conversation.update",f),t.off("transcript.item",g),t.off("conversation.agent.state",v),t.off("agent.audio.mute",_),y&&typeof y=="object"&&(y.off(O.SocketMessage,T),y.off(O.SocketClose,x))}},[t,n,i,s,r,a])},F0=2e3;async function V0(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function ih(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 B0=(t,e)=>{const[n,i]=xe([]),[,s]=Xo(),r=ce(e);Ee(()=>{r.current=e},[e]);const o=ce(void 0),a=ce(void 0);return Ee(()=>{if(!t)return;const c=f=>{i(g=>{const v=g[g.length-1];if(f.role==="assistant"&&v&&ih(v.id)===ih(f.id)&&v.role==="assistant"){const _=r.current.showUserPerceivedLatency&&o.current!==void 0&&v.userPerceivedLatencyMs===void 0,w=r.current.showGreetingLatency&&a.current!==void 0&&v.greetingLatencyMs===void 0,y={...v,content:v.content+f.content,timestamp:f.timestamp,..._&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return _&&(o.current=void 0),w&&(a.current=void 0),[...g.slice(0,-1),y]}if(f.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const _=r.current.showUserPerceivedLatency&&o.current!==void 0,w=r.current.showGreetingLatency&&a.current!==void 0;if(_||w){const y={...f,..._&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return o.current=void 0,a.current=void 0,[...g,y]}o.current=void 0,a.current=void 0}if(f.role==="user"){const _=g.findIndex(y=>y.id===f.id);if(_!==-1){const y=[...g];return y[_]={...g[_],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(v&&v.role==="user"&&f.timestamp.getTime()-v.timestamp.getTime()<F0){const T={...v,id:f.id,content:v.content+" "+f.content,timestamp:f.timestamp,attachments:[...v.attachments||[],...f.attachments||[]]};return[...g.slice(0,-1),T]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...g,f]})},u=({state:f,userPerceivedLatencyMs:g,greetingLatencyMs:v,thinkingStartedAt:_})=>{(g!==void 0||v!==void 0)&&ue.info(`[AgentState] state=${f} userPerceivedLatencyMs=${g} greetingLatencyMs=${v} thinkingStartedAt=${_}`),f==="speaking"?(s("speaking"),g!==void 0&&(o.current=g),v!==void 0&&(a.current=v)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},d=f=>{var v;const g=(v=f.call)==null?void 0:v.state;(g==="destroy"||g==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:n,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const f of u)try{const g=await V0(f);d.push(g)}catch(g){throw ue.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,d)}}},U0=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{const r=Xt(),[o,a]=xe(i?"expanded":r.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=B0(e,n),d=ce(!1);switch(Ee(()=>{if(i&&t&&!d.current){const f="remoteStream"in t?t.remoteStream:null;f&&(d.current=!0,f.getAudioTracks().forEach(g=>{g.enabled=!1,ue.info(`[ChatMode] Disabled remote audio track: ${g.label}`)}))}},[i,t]),o){case"collapsed":return R(Qd,{onExpand:l,call:t,client:e,chatMode:i,debug:s});case"expanded":return R(Oy,{transcript:u,onCollapse:c,call:t,chatMode:i,debug:s});default:return R(Qd,{onExpand:l,call:t,client:e,chatMode:i,debug:s})}},pr=()=>R(vn.div,{layoutId:Qn,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:R("div",{className:"rounded-full animate-spin",children:R(hy,{})})}),j0=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return R(pr,{});case"done":case"purged":case"destroy":return null;case"active":return R(U0,{client:e,call:t,latencySettings:n,chatMode:i,debug:s});default:return R(pr,{})}},$0=({className:t})=>R("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:[R("g",{clipPath:"url(#:R5lfm:)",children:[R("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"}),R("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"}),R("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"}),R("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"}),R("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"})]}),R("defs",{children:R("clipPath",{id:":R5lfm:",children:R("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function sh(){const t=Xt();return t.logo_icon_url?R("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:R("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):R($0,{className:"w-8 h-8 mr-2"})}const H0=({client:t,callProps:e,chatMode:n})=>{const i=Xt(),s=ce(!1),r=Ge(()=>{if(!t){ue.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return Ee(()=>{n&&t&&!s.current&&(s.current=!0,ue.info("[ChatMode] Auto-starting conversation"),r())},[n,t,r]),n?R(vn.div,{layoutId:Qn,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:[R(sh,{}),"Connecting..."]}):R(vn.button,{layoutId:Qn,onClick:r,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:[R(sh,{}),i.start_call_text]})},W0='@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-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--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-green-500{background-color:var(--color-green-500)}.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}.opacity-60{opacity:.6}.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-green-600:hover{background-color:var(--color-green-600)}.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)}}',G0=({children:t})=>R("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:R("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),z0={duration:.1,ease:"circOut"},q0=({children:t,position:e="fixed"})=>{const n=Xt(),s=(e??n.position??"fixed")==="fixed"?R(G0,{children:t}):t;return R("div",{className:Ct(n.theme==="dark"&&"dark"),children:R(im,{transition:z0,children:[R("style",{children:W0}),s]})})},K0=t=>R(vn.div,{layoutId:Qn,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:[R(dy,{className:"w-8 h-8 text-red-400"}),R("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),R("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[R("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),R("li",{children:["Make sure that the"," ",R("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"," ",R(_y,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&R("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[R(vy,{className:"w-4 h-4"}),"Retry"]})]});function fi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function X0({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":r,"call-custom-headers":o,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":f,region:g,environment:v,position:_="fixed","version-id":w}){const y=fi(e),T=fi(n),x=fi(f),I=Xe(()=>{if(l)try{return JSON.parse(l)}catch(H){ue.error("Invalid JSON for vad attribute:",l,H);return}},[l]),A=Xe(()=>({showUserPerceivedLatency:fi(c),showGreetingLatency:fi(u)}),[c,u]),{client:M,error:S,isReconnecting:C}=M0(t,v,w,y,T,I,d,x,g),[p,m]=xe(null),[h,b]=xe(!1),[E,D]=xe(!1),[L,N]=xe(!1),[P,B]=xe(!1),X=Ei(Jd),j=Fv(),ie={};if(i&&(ie.destinationNumber=i),s&&(ie.callerNumber=s),r&&(ie.callerName=r),o)try{ie.customHeaders=JSON.parse(o)}catch(H){ue.error("Invalid JSON for call-custom-headers attribute:",o,H)}if(a)try{ie.audio=JSON.parse(a);const H=ie.audio;if(typeof H=="object"){const se=navigator.mediaDevices.getSupportedConstraints();Object.keys(H).forEach(Ae=>{se[Ae]||ue.warn(`Audio constraint not supported by browser: ${Ae}`)})}}catch(H){ue.error("Invalid JSON for call-audio attribute:",a,H)}const ne=Ge(()=>{b(!1)},[]),$=Ge(H=>{var se;if(((se=H.call)==null?void 0:se.state)==="destroy")return X(!1),B(!0),m(null);m(H)},[X]),de=Ge(()=>{b(!1),C||D(!0)},[C]),Y=Ge(()=>{ue.info("User triggered retry"),D(!1),b(!0),M&&M.connect()},[M]),Q=Ge(H=>{if(Ov(H)){const se=H.params.widget_settings;se&&Object.keys(se).length>0&&(j(se),N(!0))}},[j]);return O0(M,{onReady:ne,onConversationUpdate:$,onError:de,onConfigMessage:Q}),R(q0,{position:_,children:t?E||S?R(K0,{agentId:t,onRetry:Y}):h||C?R(pr,{message:C?"Retrying...":void 0}):p!=null&&p.call?R(j0,{call:p.call,client:M,latencySettings:A,chatMode:x,debug:y}):L?R(H0,{client:M,callProps:ie,chatMode:x&&!P}):null:R("div",{children:"Please provide an assistant ID."})})}wh(X0,"telnyx-ai-agent",Mv,{shadow:!0})})();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@telnyx/ai-agent-widget",
3
3
  "private": false,
4
- "version": "0.33.0-beta.2",
4
+ "version": "0.33.0-beta.3",
5
5
  "description": "A widget for Telnyx AI Agent",
6
6
  "type": "module",
7
7
  "author": "Telnyx",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@fontsource/inter": "^5.2.6",
24
- "@telnyx/ai-agent-lib": "0.4.0-beta.0",
24
+ "@telnyx/ai-agent-lib": "0.4.0-beta.1",
25
25
  "audiomotion-analyzer": "^4.5.1",
26
26
  "clsx": "^2.1.1",
27
27
  "jotai": "^2.12.5",