1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[3084],{6206:(e,t,i)=>{i.d(t,{A:()=>n});let n=(0,i(98832).A)("trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]])},9591:(e,t,i)=>{let n;i.d(t,{es:()=>d,e4:()=>c,UU:()=>q});var s,o,r,a,l,c,d,u,h,E,p=i(15599);let m={client:"js-sdk",version:"4.15.0"},S="https://api.anam.ai",C="/v1";!function(e){e.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",e.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",e.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",e.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",e.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"}(s||(s={}));let _=S,g=C,f=!1,T={sessionId:null,organizationId:null,attemptCorrelationId:null},v=e=>{T=Object.assign(Object.assign({},T),e)},R=(e,t,i)=>(function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})})(void 0,void 0,void 0,function*(){if(!f)try{let s,o=Object.assign(Object.assign({},m),i);T.sessionId&&(o.sessionId=T.sessionId),T.organizationId&&(o.organizationId=T.organizationId),T.attemptCorrelationId&&(o.attemptCorrelationId=T.attemptCorrelationId);let r=`${g}/metrics/client`,a={"Content-Type":"application/json"};(null==n?void 0:n.enabled)&&(null==n?void 0:n.baseUrl)?(s=`${n.baseUrl}${r}`,a["X-Anam-Target-Url"]=`${_}${r}`):s=`${_}${r}`,yield fetch(s,{method:"POST",headers:a,body:JSON.stringify({name:e,value:t,tags:o})})}catch(e){console.error("Failed to send error metric:",e)}});!function(e){e.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",e.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",e.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",e.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",e.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",e.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",e.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",e.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",e.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"}(o||(o={}));class A extends Error{constructor(e,t,i=500,n){super(e),this.name="ClientError",this.code=t,this.statusCode=i,this.details=n,Object.setPrototypeOf(this,A.prototype),R(s.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:n,statusCode:i})}}function I(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}!function(e){e.OFFER="offer",e.ANSWER="answer",e.ICE_CANDIDATE="icecandidate",e.END_SESSION="endsession",e.HEARTBEAT="heartbeat",e.WARNING="warning",e.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",e.TALK_STREAM_INPUT="talkstream",e.SESSION_READY="sessionready",e.AGENT_AUDIO_INPUT="agentaudioinput",e.AGENT_AUDIO_INPUT_END="agentaudioinputend"}(r||(r={})),function(e){e.SPEECH_TEXT="speechText",e.CLIENT_TOOL_EVENT="clientToolEvent",e.TOOL_CALL_STARTED_EVENT="toolCallStarted",e.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",e.TOOL_CALL_FAILED_EVENT="toolCallFailed",e.REASONING_TEXT="reasoningText",e.USER_SPEECH_STARTED="userSpeechStarted",e.USER_SPEECH_ENDED="userSpeechEnded"}(a||(a={})),function(e){e.PENDING="pending",e.GRANTED="granted",e.DENIED="denied",e.NOT_REQUESTED="not_requested"}(l||(l={})),function(e){e.USER="user",e.PERSONA="persona"}(c||(c={})),function(e){e.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",e.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",e.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",e.CONNECTION_CLOSED="CONNECTION_CLOSED",e.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",e.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",e.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",e.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",e.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",e.SESSION_READY="SESSION_READY",e.SERVER_WARNING="SERVER_WARNING",e.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",e.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",e.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",e.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",e.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",e.TOOL_CALL_STARTED="TOOL_CALL_STARTED",e.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",e.TOOL_CALL_FAILED="TOOL_CALL_FAILED",e.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",e.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",e.USER_SPEECH_STARTED="USER_
1SPEECH_STARTED",e.USER_SPEECH_ENDED="USER_SPEECH_ENDED"}(d||(d={})),function(e){e.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",e.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",e.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",e.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",e.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",e.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED",e.TOOL_CALL_RESULT_READY="TOOL_CALL_RESULT_READY"}(u||(u={})),function(e){e.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",e.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",e.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",e.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",e.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"}(h||(h={}));var O=function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class y{constructor(e,t,i,n,s){var o,r,a,l,c;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=i,this.internalEventEmitter=n,this.apiGatewayConfig=s,!e)throw Error("Signalling Client: sessionId is required");this.sessionId=e;let{heartbeatIntervalSeconds:d,maxWsReconnectionAttempts:u,url:h}=t;if(this.heartbeatIntervalSeconds=d||5,this.maxWsReconnectionAttempts=u||5,!h.baseUrl)throw Error("Signalling Client: baseUrl is required");if((null==(o=this.apiGatewayConfig)?void 0:o.enabled)&&(null==(r=this.apiGatewayConfig)?void 0:r.baseUrl)){let t=new URL(this.apiGatewayConfig.baseUrl),i=null!=(a=this.apiGatewayConfig.wsPath)?a:"/ws";t.protocol=t.protocol.replace("http","ws"),t.pathname=i,this.url=t;let n=h.protocol||"https",s=`${n}://${h.baseUrl}`,o=null!=(l=h.signallingPath)?l:"/ws",r=new URL(s);r.protocol="ws"==("http"===n?"ws":"wss")?"ws:":"wss:",h.port&&(r.port=h.port),r.pathname=o,r.searchParams.append("session_id",e),this.url.searchParams.append("target_url",r.href)}else{let t=h.protocol||"https",i=`${t}://${h.baseUrl}`;this.url=new URL(i),this.url.protocol="http"===h.protocol?"ws:":"wss:",h.port&&(this.url.port=h.port),this.url.pathname=null!=(c=h.signallingPath)?c:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return O(this,void 0,void 0,function*(){let t={connectionDescription:e,userUid:this.sessionId},i={actionType:r.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(i)})}sendIceCandidate(e){return O(this,void 0,void 0,function*(){let t={actionType:r.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if((null==(t=this.socket)?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(e){console.error("SignallingClient - sendSignalMessage: error sending message",e)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return O(this,void 0,void 0,function*(){let t={actionType:r.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){let t={actionType:r.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){let e={actionType:r.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return O(this,void 0,void 0,function*(){if(!this.socket)throw Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(u.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(d.CONNECTION_CLOSED,h.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return O(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,this.stopSignal||(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(d.CONNECTION_CLOSED,h.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){let e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var i;(null==(i=this.socket)?void 0:i.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return O(this,void 0,void 0,function*(){let t=JSON.parse(e.data);this.internalEventEmitter.emit(u.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");let e=1e3*this.heartbeatIntervalSeconds,t=JSON.stringify({actionType:r.HEARTBEAT,sessionId:this.sessionId,payload:""});this.heartBeatIntervalRef=setInterval(()=>{var e;this.stopSignal||(null==(e=this.socket)?void 0:e.readyState)===WebSocket.OPEN&&this.socket.send(t)},e)}}
1var b=function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class N{constructor(e,t,i){if(!e&&!t)throw Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(null==i?void 0:i.baseUrl)||"https://api.anam.ai",this.apiVersion=(null==i?void 0:i.apiVersion)||"/v1",this.apiGatewayConfig=(null==i?void 0:i.apiGateway)||void 0,this.retryOptions=function(e){let t=Math.max(1,Math.floor(D(null==e?void 0:e.maxAttempts,3))),i=Math.max(0,D(null==e?void 0:e.initialBackoffMs,250)),n=Math.max(i,D(null==e?void 0:e.maxBackoffMs,2e3));return{maxAttempts:t,initialBackoffMs:i,maxBackoffMs:n}}(null==i?void 0:i.retry),this.requestTimeoutMs=Math.max(0,D(null==i?void 0:i.requestTimeoutMs,1e4))}buildGatewayUrlAndHeaders(e,t){var i,n;if(null==(i=this.apiGatewayConfig)||!i.enabled||null==(n=this.apiGatewayConfig)||!n.baseUrl)return{url:`${this.baseUrl}${e}`,headers:t};{let i=`${this.apiGatewayConfig.baseUrl}${e}`,n=new URL(`${this.baseUrl}${e}`);return{url:i,headers:Object.assign(Object.assign({},t),{"X-Anam-Target-Url":n.href})}}}startSession(e,t){return b(this,void 0,void 0,function*(){let i;if(!this.sessionToken){if(!e)throw new A("Persona configuration must be provided when using apiKey",o.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let{maxAttempts:n}=this.retryOptions;for(let o=1;o<=n;o++)try{return yield this.attemptStartSession(e,t)}catch(e){var s;if(i=e,o>=n||!(!((s=e)instanceof A)||s.statusCode>=500&&s.statusCode<600))throw e;yield function(e){return new Promise(t=>setTimeout(t,e))}(this.computeBackoffDelay(o))}throw i})}attemptStartSession(e,t){return b(this,void 0,void 0,function*(){let i=this.requestTimeoutMs>0?new AbortController:void 0,n=void 0!==i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let n=`${this.apiVersion}/engine/session`,{url:s,headers:r}=this.buildGatewayUrlAndHeaders(n,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),a=yield fetch(s,{method:"POST",headers:r,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:m}),signal:null==i?void 0:i.signal}),l=yield a.json(),c=l.error;switch(a.status){case 200:case 201:return l;case 400:throw new A("Invalid request to start session",o.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:l.message});case 401:throw new A("Authentication failed when starting session",o.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:l.message});case 402:throw new A("Please sign up for a plan to start a session",o.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:l.message});case 403:throw new A("Authentication failed when starting session",o.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:l.message});case 429:if("Concurrent session limit reached"===c)throw new A("Concurrency limit reached, please upgrade your plan",o.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:l.message});if("Spend cap reached"===c)throw new A("Spend cap reached, please upgrade your plan",o.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:l.message});throw new A("Usage limit reached, please upgrade your plan",o.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:l.message});case 503:throw new A("There are no available personas, please try again later",o.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:l.message});default:throw new A("Unknown error when starting session",o.CLIENT_ERROR_CODE_SERVER_ERROR,a.status,{cause:l.message})}}catch(e){if(e instanceof A)throw e;throw new A("Failed to start session",o.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e)})}finally{void 0!==n&&clearTimeout(n)}})}computeBackoffDelay(e){let{initialBackoffMs:t,maxBackoffMs:i}=this.retryOptions,n=Math.min(i,t*Math.pow(2,e-1));return Math.floor(n/2+n/2*Math.random())}unsafe_getSessionToken(e){return b(this,void 0,void 0,function*(){if(console.warn("Using an insecure method. This method should not be used in production."),!this.apiKey)throw Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};("brainType"in e||"llmId"in e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{let e=`${this.apiVersion}/auth/session-token`,{url:i,headers:n}=this.buildGatewayUrlAndHeaders(e,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}),s=yield fetch(i,{method:"POST",headers:n,body:JSON.stringify(t)});return(yield s.json()).sessionToken}catch(e){throw Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}function D(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}class w{constructor(e,t,i){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=i}sendTalkCommand(e){var t,i,n,s;return t=this,i=void 0,n=void 0,s=function*(){var t,i;try{let n,s={"Content-Type":"application/json"},o="/talk",r=`?session_id=${this.sessionId}`;if((null==(t=this.apiGatewayConfig)?void 0:t.enabled)&&(null==(i=this.apiGatewayConfig)?void 0:i.baseUrl)){n=`${this.apiGatewayConfig.baseUrl}${o}${r}`;let e=new URL(`${this.baseUrl}${o}${r}`);s["X-Anam-Target-Url"]=e.href}else n=`${this.baseUrl}${o}${r}`;let a=yield fetch(n,{method:"POST",headers:s,body:JSON.stringify({content:e})});if(!a.ok)throw Error(`Failed to send talk command: ${a.status} ${a.statusText}`)}catch(e){throw console.error(e),Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}}
1,new(n||(n=Promise))(function(e,o){function r(e){try{l(s.next(e))}catch(e){o(e)}}function a(e){try{l(s.throw(e))}catch(e){o(e)}}function l(t){var i;t.done?e(t.value):((i=t.value)instanceof n?i:new n(function(e){e(i)})).then(r,a)}l((s=s.apply(t,i||[])).next())})}}class M{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(e=>{e(...t)})}}class L{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(u.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){let t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){let t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},i=this.messages.findIndex(e=>e.id===t.id);if(-1!==i){let e=this.messages[i];this.messages[i]=Object.assign(Object.assign({},e),{content:e.content+t.content,interrupted:e.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){let t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(d.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case c.USER:this.processUserMessage(t);break;case c.PERSONA:this.processPersonaMessage(t)}t.endOfSpeech&&this.publicEventEmitter.emit(d.MESSAGE_HISTORY_UPDATED,this.messages)}}class k{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===d.CONNECTION_ESTABLISHED&&R(s.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===d.CONNECTION_CLOSED){let[e,i]=t;R(s.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,e,i?{details:i}:void 0)}this.listeners[e]&&this.listeners[e].forEach(e=>{e(...t)})}}class P{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){let t={audioData:"string"==typeof e?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(t)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){return btoa(Array.from(e instanceof Uint8Array?e:new Uint8Array(e),e=>String.fromCharCode(e)).join(""))}}!function(e){e[e.UNSTARTED=0]="UNSTARTED",e[e.STREAMING=1]="STREAMING",e[e.INTERRUPTED=2]="INTERRUPTED",e[e.ENDED=3]="ENDED"}(E||(E={}));var U=function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class x{constructor(e,t,i){this.state=E.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=i,this.internalEventEmitter.addListener(u.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(u.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return U(this,void 0,void 0,function*(){e.actionType===r.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=E.INTERRUPTED,this.onDeactivate())})}endMessage(){return U(this,void 0,void 0,function*(){if(this.state===E.ENDED)return void console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");if(this.state!==E.STREAMING)return void console.warn("Talk stream is not in an active state: "+this.state);let e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=E.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return U(this,void 0,void 0,function*(){if(this.state!==E.STREAMING&&this.state!==E.UNSTARTED)throw Error("Talk stream is not in an active state: "+this.state);let i={content:e,startOfSpeech:this.state===E.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?E.ENDED:E.STREAMING,this.state===E.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(i)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===E.STREAMING||this.state===E.UNSTARTED}getState(){return this.state}}
1var F=function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};let V=(e,t)=>{if(isNaN(e)||isNaN(t))return 0;let i=t-e;return i>0?i:0};class G{constructor(e,t){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.failedCalls=Object.create(null),this.activeSessionId=null,this.publicEventEmitter=e,this.internalEventEmitter=t}setActiveSession(e){this.activeSessionId=e,this.clearPendingCalls(),this.clearFailedCalls()}clearSessionState(){this.activeSessionId=null,this.clearPendingCalls(),this.clearFailedCalls()}clearPendingCalls(){this.pendingCalls=Object.create(null)}clearFailedCalls(){this.failedCalls=Object.create(null)}registerHandler(e,t){return this.handlers[e]=t,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return F(this,void 0,void 0,function*(){if(this.activeSessionId!==e.session_id)return;let{tool_name:t,timestamp:i}=e,n=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),s=new Date(i);if(this.pendingCalls[e.tool_call_id]={payload:n,timestamp:s.getTime()},!(t in this.handlers))return;let o=this.handlers[t];if(o.onStart)try{let t=yield o.onStart(n);if("client"===e.tool_type){this.sendToolResult({sessionId:e.session_id,toolCallId:e.tool_call_id,userActionCorrelationId:e.user_action_correlation_id,timestampUserAction:e.timestamp_user_action,result:null!=t?t:void 0,errorMessage:void 0}),yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:t,timestamp:new Date().toISOString()}));return}}catch(i){let t=i instanceof Error?i.message:String(i);"client"===e.tool_type&&this.sendToolResult({sessionId:e.session_id,toolCallId:e.tool_call_id,userActionCorrelationId:e.user_action_correlation_id,timestampUserAction:e.timestamp_user_action,result:void 0,errorMessage:`Error in handler: ${t}`}),yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${t}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return F(this,void 0,void 0,function*(){let{tool_name:t,tool_call_id:i,timestamp:n}=e;if(this.activeSessionId!==e.session_id)return;if(i in this.failedCalls)return void delete this.failedCalls[i];let s=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;let o=this.handlers[t];if(o.onComplete){"client"===e.tool_type&&this.publicEventEmitter.emit(d.TOOL_CALL_COMPLETED,s);try{yield o.onComplete(s)}catch(e){console.error(`Error in onComplete handler for tool ${t}:`,e);return}}})}processToolCallFailedEvent(e){return F(this,void 0,void 0,function*(){let{tool_name:t,tool_call_id:i,timestamp:n}=e;if(this.activeSessionId!==e.session_id)return;let s=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(this.failedCalls[i]=s,i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;let o=this.handlers[t];if(o.onFail){"client"===e.tool_type&&this.publicEventEmitter.emit(d.TOOL_CALL_FAILED,s);try{yield o.onFail(s)}catch(e){console.error(`Error in onFail handler for tool ${t}:`,e);return}}})}sendToolResult(e){let t={sessionId:e.sessionId,toolCallId:e.toolCallId,result:e.result,errorMessage:e.errorMessage,userActionCorrelationId:e.userActionCorrelationId,timestampUserAction:e.timestampUserAction};this.internalEventEmitter.emit(u.TOOL_CALL_RESULT_READY,t)}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){let t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],n=i?V(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:n>0?n:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){let t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],n=i?V(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:n>0?n:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}
1var B=function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class ${constructor(e,t,i,n,s){var o,r,a,c;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:l.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=i,this.internalEventEmitter=n,this.toolCallManager=s,this.apiGatewayConfig=t.apiGateway;let{inputAudio:d}=t;this.inputAudioState=d.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=!0===t.inputAudio.disableInputAudio,this.internalEventEmitter.addListener(u.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(u.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(u.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(u.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(u.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(u.TOOL_CALL_RESULT_READY,this.onToolCallResultReceived.bind(this)),this.iceServers=t.iceServers,this.rtcConfiguration=t.rtcConfiguration,this.signallingClient=new y(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new w(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=null!=(r=null==(o=t.metrics)?void 0:o.showPeerConnectionStatsReport)&&r,this.peerConnectionStatsReportOutputFormat=null!=(c=null==(a=t.metrics)?void 0:a.peerConnectionStatsReportOutputFormat)?c:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;null==(e=this.inputAudioStream)||e.getAudioTracks().forEach(e=>{e.enabled=!1})}unmuteAllAudioTracks(){var e;null==(e=this.inputAudioStream)||e.getAudioTracks().forEach(e=>{e.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>B(this,void 0,void 0,function*(){if(this.peerConnection&&this.dataChannel&&"open"===this.dataChannel.readyState)try{let e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),5e3))}sendClientSideMetrics(e){e.forEach(e=>
1{"inbound-rtp"===e.type&&this.dataChannel&&"open"===this.dataChannel.readyState&&this.dataChannel.send(JSON.stringify({message_type:"remote_rtp_stats",data:e}))})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;let e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},15e3);this.successMetricPoller=setInterval(()=>B(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{let t=yield this.peerConnection.getStats(),i=!1,n=null;t.forEach(e=>{"inbound-rtp"===e.type&&"video"===e.kind&&(void 0!==e.framesDecoded&&e.framesDecoded>0?(i=!0,n="framesDecoded"):void 0!==e.framesReceived&&e.framesReceived>0?(i=!0,n="framesReceived"):e.bytesReceived>0&&e.packetsReceived>0&&e.bytesReceived>1e5&&(i=!0,n="bytesReceived"))}),i&&!this.successMetricFired&&(this.successMetricFired=!0,R(s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",n?{detectionMethod:n}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch(e){}}),500)}muteInputAudio(){let e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){let e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return B(this,void 0,void 0,function*(){if(!this.peerConnection)throw Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(null==e)throw Error("StreamingClient - changeAudioInputDevice: deviceId is required");let t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(e=>{e.stop()}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,deviceId:{exact:e}}}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(d.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(e){throw console.error("Failed to change audio input device:",e),Error(`StreamingClient - changeAudioInputDevice: ${e instanceof Error?e.message:String(e)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}onToolCallResultReceived(e){let t={session_id:e.sessionId,message_type:"tool_result",tool_call_id:e.toolCallId,user_action_correlation_id:e.userActionCorrelationId,timestamp_user_action:e.timestampUserAction};void 0!==e.result&&(t.result=e.result),e.errorMessage&&(t.error=e.errorMessage),this.sendDataMessage(JSON.stringify(t))}sendDataMessage(e){this.dataChannel&&"open"===this.dataChannel.readyState&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){let t=document.getElementById(e);if(!t)throw Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection)return void console.error("StreamingClient - startConnection: peer connection already exists");this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return B(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return B(this,void 0,void 0,function*(){if(!this.peerConnection)throw Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new x(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new P(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return B(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection(Object.assign(Object.assign({iceCandidatePoolSize:2},this.rtcConfiguration),{iceServers:this.iceServers})),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return B(this,void 0,void 0,function*(){if(!this.peerConnection)return void console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");switch(e.actionType){case r.ANSWER:let t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;
1case r.ICE_CANDIDATE:let i=new RTCIceCandidate(e.payload);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(i):this.remoteIceCandidateBuffer.push(i);break;case r.END_SESSION:let n=e.payload;this.publicEventEmitter.emit(d.CONNECTION_CLOSED,h.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case r.WARNING:let s=e.payload;console.warn("Warning received from server: "+s),this.publicEventEmitter.emit(d.SERVER_WARNING,s);break;case r.TALK_STREAM_INTERRUPTED:let o=e.payload;this.publicEventEmitter.emit(d.TALK_STREAM_INTERRUPTED,o.correlationId);break;case r.SESSION_READY:let a=e.sessionId;this.publicEventEmitter.emit(d.SESSION_READY,a);break;case r.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your @anam-ai/js-sdk version up to date?",e)}})}onSignallingClientConnected(){return B(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;null==(t=this.peerConnection)||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;((null==(e=this.peerConnection)?void 0:e.iceConnectionState)==="connected"||(null==(t=this.peerConnection)?void 0:t.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(d.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;(null==(e=this.peerConnection)?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),"NotAllowedError"===e.name&&"Permission denied"===e.message?this.publicEventEmitter.emit(d.CONNECTION_CLOSED,h.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(d.CONNECTION_CLOSED,h.WEBRTC_FAILURE);try{this.stopConnection()}catch(e){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",e)}}onTrackEventHandler(e){if("video"===e.track.kind){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(d.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;let e=this.videoElement.requestVideoFrameCallback(()=>{var t;null==(t=this.videoElement)||t.cancelVideoFrameCallback(e),this.publicEventEmitter.emit(d.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,R(s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else"audio"===e.track.kind&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(d.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return B(this,void 0,void 0,function*(){if(!this.peerConnection)return void console.error("StreamingClient - setupDataChannels: peer connection is not initialized");if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");let e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=null!=e?e:null},e.onclose=()=>{},e.onmessage=e=>{var t,i,n,s;try{let o=JSON.parse(e.data);switch(o.messageType){case a.SPEECH_TEXT:this.internalEventEmitter.emit(u.WEBRTC_CHAT_MESSAGE_RECEIVED,o.data);break;case a.CLIENT_TOOL_EVENT:let r=o.data;this.internalEventEmitter.emit(u.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,r);let l=G.WebRTCClientToolEventToClientToolEvent(r);this.publicEventEmitter.emit(d.CLIENT_TOOL_EVENT_RECEIVED,l);break;case a.TOOL_CALL_STARTED_EVENT:let c=o.data;this.publicEventEmitter.emit(d.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(c)),this.internalEventEmitter.emit(u.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,c);break;case a.TOOL_CALL_COMPLETED_EVENT:let h=o.data;this.publicEventEmitter.emit(d.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(h)),this.internalEventEmitter.emit(u.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,h);break;case a.TOOL_CALL_FAILED_EVENT:let E=o.data;this.publicEventEmitter.emit(d.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(E)),this.internalEventEmitter.emit(u.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,E);break;case a.REASONING_TEXT:this.internalEventEmitter.emit(u.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,o.data);break;case a.USER_SPEECH_STARTED:this.publicEventEmitter.emit(d.USER_SPEECH_STARTED,null!=(i=null==(t=o.data)?void 0:t.user_action_correlation_id)?i:"unknown");break;case a.USER_SPEECH_ENDED:this.publicEventEmitter.emit(d.USER_SPEECH_ENDED,null!=(s=null==(n=o.data)?void 0:n.user_action_correlation_id)?s:"unknown")}}catch(e){console.error("Failed to parse data channel message:",e)}}})}requestMicrophonePermissionAsync(){return B(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==l.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:l.PENDING}),this.publicEventEmitter.emit(d.MIC_PERMISSION_PENDING);try{let e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:l.GRANTED}),this.publicEventEmitter.emit(d.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(t){console.error("Failed to get microphone permission:",t),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:l.DENIED});let e=t instanceof Error?t.message:String(t);this.publicEventEmitter.emit(d.MIC_PERMISSION_DENIED,e)}}})}setupAudioTrack(){return B(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length)return void console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");this.inputAudioState.isMuted&&this.muteAllAudioTracks();let e=this.inputAudioStream.getAudioTracks()[0],t=this.peerConnection.getSenders().find(e=>{var t;return(null==(t=e.track)?void 0:t.kind)==="audio"||null===e.track&&null!==e.dtmf});if(t)try{yield t.replaceTrack(e)}catch(t){console.error("Failed to replace audio track:",t),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(d.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return B(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection)return void console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");try{let e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return B(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){let t=yield null==(e=this.peerConnection)?void 0:e.getStats();if(t){let e=((e,t="console")=>{var i,n,s;let o={};
1e.forEach(e=>{o[e.type]||(o[e.type]=[]),o[e.type].push(e)});let r={issues:[]},a=(null==(i=o["inbound-rtp"])?void 0:i.filter(e=>"video"===e.kind))||[];a.length>0&&(r.personaVideoStream=[],a.forEach(e=>{var t,i,n,s,o;let a={framesReceived:null!=(t=e.framesReceived)?t:"unknown",framesDropped:null!=(i=e.framesDropped)?i:"unknown",framesPerSecond:null!=(n=e.framesPerSecond)?n:"unknown",packetsReceived:null!=(s=e.packetsReceived)?s:"unknown",packetsLost:null!=(o=e.packetsLost)?o:"unknown",resolution:e.frameWidth&&e.frameHeight?`${e.frameWidth}x${e.frameHeight}`:void 0,jitter:void 0!==e.jitter?e.jitter:void 0};r.personaVideoStream.push(a)}));let l=(null==(n=o["inbound-rtp"])?void 0:n.filter(e=>"audio"===e.kind))||[];l.length>0&&(r.personaAudioStream=[],l.forEach(e=>{var t,i,n;let s={packetsReceived:null!=(t=e.packetsReceived)?t:"unknown",packetsLost:null!=(i=e.packetsLost)?i:"unknown",audioLevel:null!=(n=e.audioLevel)?n:"unknown",jitter:void 0!==e.jitter?e.jitter:void 0,totalAudioEnergy:void 0!==e.totalAudioEnergy?e.totalAudioEnergy:void 0};r.personaAudioStream.push(s)}));let c=(null==(s=o["outbound-rtp"])?void 0:s.filter(e=>"audio"===e.kind))||[];c.length>0&&(r.userAudioInput=[],c.forEach(e=>{var t,i;let n={packetsSent:null!=(t=e.packetsSent)?t:"unknown",retransmittedPackets:null!=(i=e.retransmittedPacketsSent)?i:void 0,avgPacketSendDelay:void 0!==e.totalPacketSendDelay?e.totalPacketSendDelay/(e.packetsSent||1)*1e3:void 0};r.userAudioInput.push(n)})),o.codec&&(r.codecs=[],o.codec.forEach(e=>{let t={status:e.payloadType?"Active":"Available",mimeType:e.mimeType||"Unknown",payloadType:e.payloadType||"N/A",clockRate:e.clockRate||void 0,channels:e.channels||void 0};r.codecs.push(t)})),o.transport&&(r.transportLayer=[],o.transport.forEach(e=>{let t={dtlsState:e.dtlsState||"unknown",iceState:e.iceState||"unknown",bytesSent:e.bytesSent||void 0,bytesReceived:e.bytesReceived||void 0};r.transportLayer.push(t)}));let d=[];if(a.forEach(e=>{"number"==typeof e.framesDropped&&e.framesDropped>0&&d.push(`Video: ${e.framesDropped} frames dropped`),"number"==typeof e.packetsLost&&e.packetsLost>0&&d.push(`Video: ${e.packetsLost} packets lost`),"number"==typeof e.framesPerSecond&&e.framesPerSecond<23&&d.push(`Video: Low frame rate (${e.framesPerSecond} fps)`)}),l.forEach(e=>{"number"==typeof e.packetsLost&&e.packetsLost>0&&d.push(`Audio: ${e.packetsLost} packets lost`),"number"==typeof e.jitter&&e.jitter>
1.1&&d.push(`Audio: High jitter (${(1e3*e.jitter).toFixed(1)}ms)`)}),r.issues=d,"json"===t)return r;console.group("\uD83D\uDCCA WebRTC Session Statistics Report"),r.personaVideoStream&&r.personaVideoStream.length>0&&(console.group("\uD83D\uDCF9 Persona Video Stream (Inbound)"),r.personaVideoStream.forEach(e=>{console.log(`Frames Received: ${e.framesReceived}`),console.log(`Frames Dropped: ${e.framesDropped}`),console.log(`Frames Per Second: ${e.framesPerSecond}`),console.log(`Packets Received: ${"number"==typeof e.packetsReceived?e.packetsReceived.toLocaleString():e.packetsReceived}`),console.log(`Packets Lost: ${e.packetsLost}`),e.resolution&&console.log(`Resolution: ${e.resolution}`),void 0!==e.jitter&&console.log(`Jitter: ${e.jitter.toFixed(5)}ms`)}),console.groupEnd()),r.personaAudioStream&&r.personaAudioStream.length>0&&(console.group("\uD83D\uDD0A Persona Audio Stream (Inbound)"),r.personaAudioStream.forEach(e=>{console.log(`Packets Received: ${"number"==typeof e.packetsReceived?e.packetsReceived.toLocaleString():e.packetsReceived}`),console.log(`Packets Lost: ${e.packetsLost}`),console.log(`Audio Level: ${e.audioLevel}`),void 0!==e.jitter&&console.log(`Jitter: ${e.jitter.toFixed(5)}ms`),void 0!==e.totalAudioEnergy&&console.log(`Total Audio Energy: ${e.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),r.userAudioInput&&r.userAudioInput.length>0&&(console.group("\uD83C\uDFA4 User Audio Input (Outbound)"),r.userAudioInput.forEach(e=>{console.log(`Packets Sent: ${"number"==typeof e.packetsSent?e.packetsSent.toLocaleString():e.packetsSent}`),e.retransmittedPackets&&console.log(`Retransmitted Packets: ${e.retransmittedPackets}`),void 0!==e.avgPacketSendDelay&&console.log(`Avg Packet Send Delay: ${e.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),r.codecs&&r.codecs.length>0&&(console.group("\uD83D\uDD27 Codecs Used"),r.codecs.forEach(e=>{console.log(`${e.status} ${e.mimeType} - Payload Type: ${e.payloadType}`),e.clockRate&&console.log(` Clock Rate: ${e.clockRate}Hz`),e.channels&&console.log(` Channels: ${e.channels}`)}),console.groupEnd()),r.transportLayer&&r.transportLayer.length>0&&(console.group("\uD83D\uDE9A Transport Layer"),r.transportLayer.forEach(e=>{console.log(`DTLS State: ${e.dtlsState}`),console.log(`ICE State: ${e.iceState}`),(e.bytesReceived||e.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(e.bytesSent||0).toLocaleString()}, Received: ${(e.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),r.issues.length>0?(console.group("â ï¸ Potential Issues Detected"),r.issues.forEach(e=>console.warn(e)),console.groupEnd()):console.log("â
No significant issues detected"),console.groupEnd()})(t,this.peerConnectionStatsReportOutputFormat);e&&console.log(e,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(e=>{e.stop()}),this.inputAudioStream=null}catch(e){console.error("StreamingClient - shutdown: error stopping input audio stream",e)}try{this.signallingClient.stop()}catch(e){console.error("StreamingClient - shutdown: error stopping signallilng",e)}try{this.peerConnection&&"closed"!==this.peerConnection.connectionState&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(e){console.error("StreamingClient - shutdown: error closing peer connection",e)}})}}class W{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(u.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){let t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(d.REASONING_STREAM_EVENT_RECEIVED,t);let i={id:t.id,content:t.content,role:t.role},n=this.reasoning_messages.findIndex(e=>e.id===i.id);if(-1!==n){let e=this.reasoning_messages[n];e.content+=i.content,this.reasoning_messages[n]=e}else this.reasoning_messages.push(i);t.endOfThought&&this.publicEventEmitter.emit(d.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}
1var H=function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class j{constructor(e,t,i){var s,r,a,c,d;this.inputAudioState={isMuted:!1,permissionState:l.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;let u=this.validateClientConfig(e,t,i);if(u)throw new A(u,o.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=i,((null==(s=null==i?void 0:i.api)?void 0:s.baseUrl)||(null==(r=null==i?void 0:i.api)?void 0:r.apiVersion))&&((e,t=C)=>{_=e,g=t})(i.api.baseUrl||S,i.api.apiVersion||C),(null==(c=null==(a=null==i?void 0:i.api)?void 0:a.apiGateway)?void 0:c.enabled)&&(n=i.api.apiGateway),(null==(d=null==i?void 0:i.metrics)?void 0:d.disableClientMetrics)&&(f=!0),this.publicEventEmitter=new k,this.internalEventEmitter=new M,this.toolCallManager=new G(this.publicEventEmitter,this.internalEventEmitter),this.apiClient=new N(e,null==i?void 0:i.apiKey,null==i?void 0:i.api),this.messageHistoryClient=new L(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new W(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{let t=e.split(".")[1],i=p.hp.from(t,"base64").toString("utf8");return JSON.parse(i)}catch(e){throw Error("Invalid session token format")}}validateClientConfig(e,t,i){var n,s;if(!e&&!(null==i?void 0:i.apiKey))return"Either sessionToken or apiKey must be provided";if((null==i?void 0:i.apiKey)&&e)return"Only one of sessionToken or apiKey should be used";let o=function(e){if(e&&e.enabled){if(!e.baseUrl)return"API Gateway baseUrl is required when enabled";try{let t=new URL(e.baseUrl);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return`Invalid API Gateway baseUrl protocol: ${t.protocol}. Must be http:, https:, ws:, or wss:`}catch(t){return`Invalid API Gateway baseUrl: ${e.baseUrl}`}if(e.wsPath&&!e.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}(null==(n=null==i?void 0:i.api)?void 0:n.apiGateway);if(o)return o;if(e){let i=this.decodeJwt(e);this.organizationId=i.accountId,v({organizationId:this.organizationId});let n=null==(s=i.type)?void 0:s.toLowerCase();if("legacy"===n)return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if(("ephemeral"===n||"stateful"===n)&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(null==i?void 0:i.voiceDetection){if(i.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(void 0!==i.voiceDetection.endOfSpeechSensitivity){if("number"!=typeof i.voiceDetection.endOfSpeechSensitivity)return"End of speech sensitivity must be a number";if(i.voiceDetection.endOfSpeechSensitivity<0||i.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;let t={};if((null==(e=this.clientOptions)?void 0:e.voiceDetection)&&(t.voiceDetection=this.clientOptions.voiceDetection),0!==Object.keys(t).length)return t}startSession(e){return H(this,void 0,void 0,function*(){var t,i,n,s,r,a,l,c,d,u,h,E,p,m,S,C,_;let g=this.personaConfig,f=this.buildStartSessionOptionsForClient(),{sessionId:T,clientConfig:R,engineHost:I,engineProtocol:O,signallingEndpoint:y}=yield this.apiClient.startSession(g,f),{heartbeatIntervalSeconds:b,maxWsReconnectionAttempts:N,iceServers:D}=R;this.sessionId=T,this.toolCallManager.setActiveSession(T),v({sessionId:this.sessionId});let w=null!=(r=null!=(i=null==(t=this.clientOptions)?void 0:t.iceServers)?i:null==(s=null==(n=this.clientOptions)?void 0:n.rtcConfiguration)?void 0:s.iceServers)?r:D;try{this.streamingClient=new $(T,{engine:{baseUrl:`${O}://${I}`},signalling:{heartbeatIntervalSeconds:b,maxWsReconnectionAttempts:N,url:{baseUrl:I,protocol:O,signallingPath:y}},iceServers:w,rtcConfiguration:null==(a=this.clientOptions)?void 0:a.rtcConfiguration,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:(null==(l=this.clientOptions)?void 0:l.disableInputAudio)?void 0:e,audioDeviceId:null==(c=this.clientOptions)?void 0:c.audioDeviceId,disableInputAudio:null==(d=this.clientOptions)?void 0:d.disableInputAudio},apiGateway:null==(h=null==(u=this.clientOptions)?void 0:u.api)?void 0:h.apiGateway,metrics:{showPeerConnectionStatsReport:null!=(m=null==(p=null==(E=this.clientOptions)?void 0:E.metrics)?void 0:p.showPeerConnectionStatsReport)&&m,peerConnectionStatsReportOutputFormat:null!=(_=null==(C=null==(S=this.clientOptions)?void 0:S.metrics)?void 0:C.peerConnectionStatsReportOutputFormat)?_:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(e){throw this.toolCallManager.clearSessionState(),v({sessionId:null}),new A("Failed to initialize streaming client",o.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:T})}return T})}startSessionIfNeeded(e){return H(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new A("Session ID or streaming client is not available after starting session",o.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return H(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw Error("Already streaming");return v({attemptCorrelationId:I(),sessionId:null}),R(s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),(null==(t=this.clientOptions)?void 0:t.disableInputAudio)&&e&&console.warn("AnamClient: In
1put audio is disabled. User-provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(e=>{var t;let i=[],n=!1,s=!1;this.publicEventEmitter.addListener(d.VIDEO_STREAM_STARTED,t=>{i.push(t),n=!0,s&&e(i)}),this.publicEventEmitter.addListener(d.AUDIO_STREAM_STARTED,t=>{i.push(t),s=!0,n&&e(i)}),null==(t=this.streamingClient)||t.startConnection()})})}streamToVideoAndAudioElements(e,t,i){return H(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,i)})}streamToVideoElement(e,t){return H(this,void 0,void 0,function*(){var i;v({attemptCorrelationId:I(),sessionId:null}),R(s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),(null==(i=this.clientOptions)?void 0:i.disableInputAudio)&&t&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(e){if(e instanceof A)throw e;throw new A("Failed to start session",o.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:this.sessionId})}if(this._isStreaming)throw Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return H(this,void 0,void 0,function*(){if(!this.streamingClient)throw Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),Error("Failed to send user message: not currently streaming");let t=this.getActiveSessionId();if(!t)throw Error("Failed to send user message: no active session");let i=JSON.stringify({content:e,timestamp:new Date().toISOString().replace("Z",""),session_id:t,message_type:"speech"});this.sendDataMessage(i)}interruptPersona(){if(!this._isStreaming)throw Error("Failed to send interrupt command: not currently streaming");let e=this.getActiveSessionId();if(!e)throw Error("Failed to send interrupt command: no active session");let t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw Error("Failed to add context: not currently streaming");let t=this.getActiveSessionId();if(!t)throw Error("Failed to add context: no active session");let i=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(i)}stopStreaming(){return H(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(d.CONNECTION_CLOSED,h.NORMAL),this.toolCallManager.clearSessionState(),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,v({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return(null==(e=this.clientOptions)?void 0:e.disableInputAudio)&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return(null==(e=this.clientOptions)?void 0:e.disableInputAudio)&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),!this.streamingClient||(null==(t=this.clientOptions)?void 0:t.disableInputAudio)?this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}):this.inputAudioState=this.streamingClient.muteInputAudio(),this.inputAudioState}unmuteInputAudio(){var e,t;return(null==(e=this.clientOptions)?void 0:e.disableInputAudio)&&console.warn("AnamClient: In
1put audio is disabled. Unmuting input audio will have no effect."),!this.streamingClient||(null==(t=this.clientOptions)?void 0:t.disableInputAudio)?this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}):this.inputAudioState=this.streamingClient.unmuteInputAudio(),this.inputAudioState}changeAudioInputDevice(e){return H(this,void 0,void 0,function*(){var t;if(null==(t=this.clientOptions)?void 0:t.disableInputAudio)throw Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw Error("Failed to start talk message stream: session is not started.");if(e&&""===e.trim())throw Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){return this.toolCallManager.registerHandler(e,t)}}let q=(e,t)=>new j(e,void 0,t)},10883:(e,t,i)=>{i.d(t,{A:()=>n});let n=(0,i(98832).A)("panel-left-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]])},21104:(e,t,i)=>{i.d(t,{A:()=>n});let n=(0,i(98832).A)("panel-right-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]])},24176:(e,t,i)=>{i.d(t,{d:()=>a});var n=i(17510),s=i(65162),o=i(24137),r=i(86050);function a(e){let t=(0,r.M)(()=>(0,n.OQ)(e)),{isStatic:i}=(0,s.useContext)(o.Q);if(i){let[,i]=(0,s.useState)(e);(0,s.useEffect)(()=>t.on("change",i),[])}return t}},32126:(e,t,i)=>{i.d(t,{A:()=>n});let n=(0,i(98832).A)("wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}
1],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]])},64088:(e,t,i)=>{let n;i.d(t,{A:()=>a});let s={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},o=new Uint8Array(16),r=[];for(let e=0;e<256;++e)r.push((e+256).toString(16).slice(1));let a=function(e,t,i){if(s.randomUUID&&!t&&!e)return s.randomUUID();let a=(e=e||{}).random??e.rng?.()??function(){if(!n){if("undefined"==typeof crypto||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");n=crypto.getRandomValues.bind(crypto)}return n(o)}();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((i=i||0)<0||i+16>t.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[i+e]=a[e];return t}return function(e,t=0){return(r[e[t+0]]+r[e[t+1]]+r[e[t+2]]+r[e[t+3]]+"-"+r[e[t+4]]+r[e[t+5]]+"-"+r[e[t+6]]+r[e[t+7]]+"-"+r[e[t+8]]+r[e[t+9]]+"-"+r[e[t+10]]+r[e[t+11]]+r[e[t+12]]+r[e[t+13]]+r[e[t+14]]+r[e[t+15]]).toLowerCase()}(a)}},72560:(e,t,i)=>{i.d(t,{i:()=>$});class n{constructor(e){this.stop=()=>this.runAll("stop"),this.animations=e.filter(Boolean)}get finished(){return Promise.all(this.animations.map(e=>e.finished))}getAll(e){return this.animations[0][e]}setAll(e,t){for(let i=0;i<this.animations.length;i++)this.animations[i][e]=t}attachTimeline(e){let t=this.animations.map(t=>t.attachTimeline(e));return()=>{t.forEach((e,t)=>{e&&e(),this.animations[t].stop()})}}get time(){return this.getAll("time")}set time(e){this.setAll("time",e)}get speed(){return this.getAll("speed")}set speed(e){this.setAll("speed",e)}get state(){return this.getAll("state")}get startTime(){return this.getAll("startTime")}get duration(){return s(this.animations,"duration")}get iterationDuration(){return s(this.animations,"iterationDuration")}runAll(e){this.animations.forEach(t=>t[e]())}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}function s(e,t){let i=0;for(let n=0;n<e.length;n++){let s=e[n][t];null!==s&&s>i&&(i=s)}return i}class o extends n{then(e,t){return this.finished.finally(e).then(()=>{})}}var r=i(13684),a=i(17510),l=i(47493),c=i(54363),d=i(43520),u=i(7192),h=i(92757),E=i(29515),p=i(83143),m=i(20090),S=i(11517);function C(e,t){return(0,S.h)(e)?e[((e,t,i)=>{let n=t-e;return((i-e)%n+n)%n+e})(0,e.length,t)]:e}var _=i(7462),g=i(89506);function f(e){return"object"==typeof e&&!Array.isArray(e)}function T(e,t,i,n){return null==e?[]:"string"==typeof e&&f(t)?(0,g.K)(e,i,n):e instanceof NodeList?Array.from(e):Array.isArray(e)?e.filter(e=>null!=e):[e]}function v(e,t,i,n){return"number"==typeof t?t:t.startsWith("-")||t.startsWith("+")?Math.max(0,e+parseFloat(t)):"<"===t?i:t.startsWith("<")?Math.max(0,i+parseFloat(t.slice(1))):n.get(t)??e}var R=i(10070);function A(e,t){return e.at!==t.at?e.at-t.at:null===e.value?1:null===t.value?-1:0}function I(e,t){return t.has(e)||t.set(e,{}),t.get(e)}function O(e,t){return t[e]||(t[e]=[]),t[e]}let y=e=>"number"==typeof e,b=e=>e.every(y);var N=i(19823),D=i(25688),w=i(32921),M=i(4226),L=i(19711),k=i(77571),P=i(56016),U=i(63373),x=i(31325);class F extends x.BX{constructor(){super(...arguments),this.type="object"}readValueFromInstance(e,t){if(t in e){let i=e[t];if("string"==typeof i||"number"==typeof i)return i}}getBaseTargetFromProps(){}removeValueFromRenderState(e,t){delete t.output[e]}measureInstanceViewportBox(){return(0,U.ge)()}build(e,t){Object.assign(e.output,t)}renderInstance(e,{output:t}){Object.assign(e,t)}sortInstanceNodePosition(){return 0}}function V(e){let t={presenceContext:null,props:{},visualState:{renderState:{transform:{},transformOrigin:{},style:{},vars:{},attrs:{}},latestValues:{}}},i=(0,M.x)(e)&&!(0,L.h)(e)?new k.l(t):new P.M(t);i.mount(e),D.C.set(e,i)}function G(e){let t=new F({presenceContext:null,props:{}
1,visualState:{renderState:{output:{}},latestValues:{}}});t.mount(e),D.C.set(e,t)}function B(e,t,i,n){let s=[];if((0,E.S)(e)||"number"==typeof e||"string"==typeof e&&!f(t))s.push((0,N.z)(e,f(t)&&t.default||t,i&&i.default||i));else{if(null==e)return s;let o=T(e,t,n),r=o.length;(0,m.V)(!!r,"No valid elements provided.","no-valid-elements");for(let e=0;e<r;e++){let n=o[e],a=n instanceof Element?V:G;D.C.has(n)||a(n);let l=D.C.get(n),c={...i};"delay"in c&&"function"==typeof c.delay&&(c.delay=c.delay(e,r)),s.push(...(0,w.$)(l,{...t,transition:c},{}))}}return s}let $=function(e={}){let{scope:t,reduceMotion:i}=e;return function(e,n,s){let S,g=[];if(Array.isArray(e)&&e.some(Array.isArray))g=function(e,t,i){let n=[];return(function(e,{defaultTransition:t={},...i}={},n,s){let o=t.duration||.3,a=new Map,l=new Map,S={},g=new Map,f=0,y=0,N=0;for(let i=0;i<e.length;i++){let a=e[i];if("string"==typeof a){g.set(a,y);continue}if(!Array.isArray(a)){g.set(a.name,v(y,a.at,f,g));continue}let[_,A,M={}]=a;void 0!==M.at&&(y=v(y,M.at,f,g));let L=0,k=(e,i,n,a=0,l=0)=>{var E;let S=Array.isArray(E=e)?E:[E],{delay:_=0,times:g=(0,c.Z)(S),type:f=t.type||"ke
1yframes",repeat:T,repeatType:v,repeatDelay:A=0,...I}=i,{ease:O=t.ease||"easeOut",duration:D}=i,w="function"==typeof _?_(a,l):_,M=S.length,k=(0,d.W)(f)?f:s?.[f||"keyframes"];if(M<=2&&k){let e=100;2===M&&b(S)&&(e=Math.abs(S[1]-S[0]));let i={...t,...I};void 0!==D&&(i.duration=(0,p.f)(D));let n=(0,u.X)(i,e,k);O=n.ease,D=n.duration}D??(D=o);let P=y+w;1===g.length&&0===g[0]&&(g[1]=1);let U=g.length-S.length;if(U>0&&(0,h.f)(g,U),1===S.length&&S.unshift(null),T){(0,m.V)(T<20,"Repeat count too high, must be less than 20","repeat-count-high");D*=T+1;let e=[...S],t=[...g],i=[...O=Array.isArray(O)?[...O]:[O]];for(let n=0;n<T;n++){S.push(...e);for(let s=0;s<e.length;s++)g.push(t[s]+(n+1)),O.push(0===s?"linear":C(i,s-1))}for(let e=0;e<g.length;e++)g[e]=g[e]/(T+1)}let x=P+D;!function(e,t,i,n,s,o){for(let t=0;t<e.length;t++){let i=e[t];i.at>s&&i.at<o&&((0,r.Ai)(e,i),t--)}for(let r=0;r<t.length;r++)e.push({value:t[r],at:(0,R.k)(s,o,n[r]),easing:C(i,r)})}(n,S,O,g,P,x),L=Math.max(w+D,L),N=Math.max(x,N)};if((0,E.S)(_))k(A,M,O("default",I(_,l)));else{let e=T(_,A,n,S),t=e.length;for(let i=0;i<t;i++){let n=I(e[i],l);for(let e in A){var D,w;k(A[e],(D=M,w=e,D&&D[w]?{...D,...D[w]}:{...D}),O(e,n),i,t)}}}f=y,y+=L}return l.forEach((e,n)=>{for(let s in e){let o=e[s];o.sort(A);let r=[],l=[],c=[];for(let e=0;e<o.length;e++){let{at:t,value:i,easing:n}=o[e];r.push(i),l.push((0,_.q)(0,N,t)),c.push(n||"easeOut")}0!==l[0]&&(l.unshift(0),r.unshift(r[0]),c.unshift("easeInOut")),1!==l[l.length-1]&&(l.push(1),r.push(null)),a.has(n)||a.set(n,{keyframes:{},transition:{}});let d=a.get(n);d.keyframes[s]=r;let{type:u,...h}=t;d.transition[s]={...h,duration:N,ease:c,times:l,...i}}}),a})(e.map(e=>{if(Array.isArray(e)&&"function"==typeof e[0]){let t=e[0],i=(0,a.OQ)(0);return(i.on("change",t),1===e.length)?[i,[0,1]]:2===e.length?[i,[0,1],e[1]]:[i,e[1],e[2]]}return e}),t,i,{spring:l.o}).forEach(({keyframes:e,transition:t},i)=>{n.push(...B(i,e,t))}),n}(e,void 0!==i?{reduceMotion:i,...n}:n,t);else{let{onComplete:o,...r}=s||{};"function"==typeof o&&(S=o),g=B(e,n,void 0!==i?{reduceMotion:i,...r}:r,t)}let f=new o(g);return S&&f.finished.then(S),t&&(t.animations.push(f),f.finished.then(()=>{(0,r.Ai)(t.animations,f)})),f}}()},78347:(e,t,i)=>{i.d(t,{L:()=>s});var n=i(65162);function s(e,t,i){(0,n.useInsertionEffect)(()=>e.on(t,i),[e,t,i])}},80967:(e,t,i)=>{i.d(t,{A:()=>n});let n=(0,i(98832).A)("volume-x",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]])},82546:(e,t,i)=>{let n;i.d(t,{h6:()=>d,yX:()=>x});class s extends Error{closeCode;closeReason;constructor(e,t){super(e),this.name="SessionConnectionError",this.closeCode=t?.closeCode,this.closeReason=t?.closeReason}}let o=Object.freeze({name:"js_sdk",version:"1.13.0"});class r{queue=[];disconnectionDetails=null;onDisconnectCallback=null;onMessageCallback=null;onModeChangeCallback=null;onDebug;constructor(e={}){this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;let t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;let t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){this.onModeChangeCallback?.(e)}disconnect(e){this.disconnectionDetails||(this.disconnectionDetails=e,this.onDisconnectCallback?.(e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}}function a(e){let[t,i]=e.split("_");if(!["pcm","ulaw"].includes(t))throw Error(`Invalid format: ${e}`);let n=Number.parseInt(i);if(Number.isNaN(n))throw Error(`Invalid sample rate: ${i}`);return{format:t,sampleRate:n}}var l,c,d,u=i(83648);let h="conversation_initiation_client_data";function E(e){let t={type:h};return e.overrides&&(t.conversation_config_override={agent:{prompt:e.overrides.agent?.prompt,first_message:e.overrides.agent?.firstMessage,language:e.overrides.agent?.language},tts:{voice_id:e.overrides.tts?.voiceId,speed:e.overrides.tts?.speed,stability:e.overrides.tts?.stability,similarity_boost:e.overrides.tts?.similarityBoost},...e.overrides.asr?.keywords!==void 0?{asr:{keywords:e.overrides.asr.keywords}}:{},conversation:{text_only:e.overrides.conversation?.textOnly}}),e.customLlmExtraBody&&(t.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(t.dynamic_variables=e.dynamicVariables),e.userId&&(t.user_id=e.userId),t.source_info={source:o.name,version:o.version},e.toolMockConfig&&(t.tool_mock_config={mocking_strategy:e.toolMockConfig.mockingStrategy,mocked_tool_names:e.toolMockConfig.mockedToolNames,fallback_strategy:e.toolMockConfig.fallbackStrategy}),t}function p(e){return btoa(String.fromCharCode(...new Uint8Array(e)))}function m(e,t,i){let n=e.length,s=i/2/n,o=Math.floor(100/s),r=M
1ath.min(Math.ceil(8e3/s),n),a=r-o,l=t.length;for(let i=0;i<l;i++){let n=i/l*a,s=o+Math.floor(n),c=Math.min(s+1,r-1),d=n-Math.floor(n);t[i]=Math.round(e[s]*(1-d)+e[c]*d)}}class S extends r{socket;conversationId;inputFormat;outputFormat;outputListeners=new Set;pendingAudioEvents=[];constructor(e,t,i,n){super(),this.socket=e,this.conversationId=t,this.inputFormat=i,this.outputFormat=n,this.socket.addEventListener("error",e=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:{type:e.type}}),0)}),this.socket.addEventListener("close",e=>{let t=e.code,i=e.reason||void 0,n={type:e.type,code:t,reason:i};this.disconnect(1e3===t?{reason:"agent",context:n,closeCode:t,closeReason:i}:{reason:"error",message:i||"The connection was closed by the server.",context:n,closeCode:t,closeReason:i})}),this.socket.addEventListener("message",e=>{try{let t=JSON.parse(e.data);if(!t.type)return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:e.data});this.handleMessage(t)}catch(t){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:t instanceof Error?t.message:String(t),data:e.data})}})}static async create(e){let t=null;try{let i,n=e.origin??"wss://api.elevenlabs.io",{name:r,version:l}=o;if(e.signedUrl){let t=e.signedUrl.includes("?")?"&":"?";i=`${e.signedUrl}${t}source=${r}&version=${l}`}else i=`${n}/v1/convai/conversation?agent_id=${e.agentId}&source=${r}&version=${l}`;e.environment&&(i+=`&environment=${encodeURIComponent(e.environment)}`);let c=["convai"];e.authorization&&c.push(`bearer.${e.authorization}`),t=new WebSocket(i,c);let{conversation_id:d,agent_output_audio_format:u,user_input_audio_format:h}=await new Promise((i,n)=>{t.addEventListener("open",()=>{let i=E(e);t?.send(JSON.stringify(i))},{once:!0}),t.addEventListener("error",e=>{setTimeout(()=>n(new s("The connection was closed due to a socket error.")),0)}),t.addEventListener("close",e=>{let t=e.reason||(1e3===e.code?"Connection closed normally before session could be established.":"Connection closed unexpectedly before session could be established.");n(new s(t,{closeCode:e.code,closeReason:e.reason||void 0}))}),t.addEventListener("message",e=>{let t=JSON.parse(e.data);t.type&&("conversation_initiation_metadata"===t.type?i(t.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),p=a(h??"pcm_16000"),m=a(u);return new S(t,d,p,m)}catch(e){throw t?.close(),e}}close(){this.pendingAudioEvents=[],this.socket.close(1e3,"User ended conversation")}sendMessage(e){this.socket.send(JSON.stringify(e))}addListener(e){let t=this.outputListeners.size>0;if(this.outputListeners.add(e),t||0===this.pendingAudioEvents.length)return;let i=this.pendingAudioEvents;for(let t of(this.pendingAudioEvents=[],i))e(t)}removeListener(e){this.outputListeners.delete(e)}handleMessage(e){if(super.handleMessage(e),"audio"===e.type&&e.audio_event.audio_base_64){let t={audio_base_64:e.audio_event.audio_base_64};if(0===this.outputListeners.size)return void this.pendingAudioEvents.push(t);this.outputListeners.forEach(e=>e(t))}}}let C=new Map;function _(e,t){return async(i,n)=>{let s=C.get(e);if(s)return i.addModule(s);if(n)try{await i.addModule(n),C.set(e,n);return}catch(t){throw Error(`Failed to load the ${e} worklet module from path: ${n}. Error: ${t}`)}let o=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(o);try{await i.addModule(r),C.set(e,r);return}catch{URL.revokeObjectURL(r)}try{let n=btoa(t),s=`data:application/javascript;base64,${n}`;await i.addModule(s),C.set(e,s)}catch(t){throw Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}_("audioConcatProcessor",`/* 2 * ulaw decoding logic taken from the wavefile library 3 * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js 4 * USED BY @elevenlabs/client 5 */ 6 7const decodeTable = [0, 132, 396, 924, 1980, 4092, 8316, 16764]; 8 9function decodeSample(muLawSample) { 10 let sign; 11 let exponent; 12 let mantissa; 13 let sample; 14 muLawSample = ~muLawSample; 15 sign = muLawSample & 0x80; 16 exponent = (muLawSample >> 4) & 0x07; 17 mantissa = muLawSample & 0x0f; 18 sample = decodeTable[exponent] + (mantissa << (exponent + 3)); 19 if (sign !== 0) sample = -sample; 20 21 return sample; 22} 23 24class AudioConcatProcessor extends AudioWorkletProcessor { 25 constructor() { 26 super(); 27 this.buffers = []; // Initialize an empty buffer 28 this.cursor = 0; 29 this.currentBuffer = null; 30 this.wasInterrupted = false;
31 this.finished = false; 32 33 this.port.onmessage = ({ data }) => { 34 switch (data.type) { 35 case "setFormat": 36 this.format = data.format; 37 if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) { 38 globalThis.LibSampleRate.create( 39 1, 40 data.sampleRate, 41 sampleRate 42 ).then(resampler => { 43 this.resampler = resampler; 44 }); 45 } 46 break; 47 case "buffer": 48 this.wasInterrupted = false; 49 this.buffers.push( 50 this.format === "ulaw" 51 ? new Uint8Array(data.buffer) 52 : new Int16Array(data.buffer) 53 ); 54 break; 55 case "interrupt": 56 this.wasInterrupted = true; 57 break; 58 case "clearInterrupted": 59 if (this.wasInterrupted) { 60 this.wasInterrupted = false; 61 this.buffers = []; 62 this.currentBuffer = null; 63 } 64 } 65 }; 66 } 67 process(_, outputs) { 68 let finished = false; 69 const output = outputs[0][0]; 70 for (let i = 0; i < output.length; i++) { 71 if (!this.currentBuffer) { 72 if (this.buffers.length === 0) { 73 finished = true; 74 break; 75 } 76 this.currentBuffer = this.buffers.shift(); 77 if (this.resampler) { 78 this.currentBuffer = this.resampler.full(this.currentBuffer); 79 } 80 this.cursor = 0; 81 } 82 83 let value = this.currentBuffer[this.cursor]; 84 if (this.format === "ulaw") { 85 value = decodeSample(value); 86 } 87 output[i] = value / 32768; 88 this.cursor++; 89 90 if (this.cursor >= this.currentBuffer.length) { 91 this.currentBuffer = null; 92 } 93 } 94 95 if (this.finished !== finished) { 96 this.finished = finished; 97 this.port.postMessage({ type: "process", finished }); 98 } 99 100 return true; // Continue processing 101 } 102} 103 104registerProcessor("audioConcatProcessor", AudioConcatProcessor); 105`);function g(e,t){let i,n,s=e.frequencyBinCount;return{getVolume(){i??=new Uint8Array(s),n??=new Uint8Array(s),e.getByteFrequencyData(i),m(i,n,t);if(0===n.length)return 0;let o=0;for(let e=0;e<n.length;e++)o+=n[e]/255;return(o/=n.length)<0?0:o>1?1:o},getByteFrequencyData(n){i??=new Uint8Array(s),e.getByteFrequencyData(i),m(i,n,t)}}}function f(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}let T=_("rawAudioProcessor",`/* 106 * ulaw encoding logic taken from the wavefile library 107 * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js 108 * USED BY @elevenlabs/client 109 */ 110 111const BIAS = 0x84; 112const CLIP = 32635; 113const encodeTable = [ 114 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3, 115 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 116 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 117 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 118 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 119 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 120 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 121 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 122 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 123 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 124 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 125 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 126 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 127 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 128 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 129 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 130]; 131 132function encodeSample(sample) { 133 let sign; 134 let exponent; 135 let mantissa; 136 let muLawSample; 137 sign = (sample >> 8) & 0x80; 138 if (sign !== 0) sample = -sample; 139 sample = sample + BIAS; 140 if (sample > CLIP) sample = CLIP; 141 exponent = encodeTable[(sample>>7) & 0xFF]; 142 mantissa = (sample >> (exponent+3)) & 0x0F; 143 muLawSample = ~(sign | (exponent << 4) | mantissa); 144 145 return muLawSample; 146} 147 148class RawAudioProcessor extends AudioWorkletProcessor { 149 constructor() { 150 super(); 151 152 this.port.onmessage = ({ data }) => { 153 switch (data.type) { 154 case "setFormat": 155 this.isMuted = false; 156 this.buffer = []; // Initialize an empty buffer 157 const chunkDurationMs = data.chunkDurationMs ?? 25; 158 this.bufferSize = Math.max( 159 1, 160 Math.round((data.sampleRate * chunkDurationMs) / 1000) 161 ); 162 this.format = data.format; 163 164 if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) { 165 globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => { 166 this.resampler = resampler; 167 }); 168 } 169 break; 170 case "setMuted": 171 this.isMuted = data.isMuted; 172 break; 173 } 174 }; 175 } 176 process(inputs) { 177 if (!this.buffer) { 178 return true; 179 } 180 181 const input = inputs[0]; // Get the first input node 182 if (input.length > 0) { 183 let channelData = input[0]; // Get the first channel's data 184 185 // Resample the audio if necessary 186 if (this.resampler) { 187 channelData = this.resampler.full(channelData); 188 } 189 190 // Add channel data to the buffer 191 this.buffer.push(...channelData); 192 // Get max volume 193 let sum = 0.0; 194 for (let i = 0; i < channelData.length; i++) { 195 sum += channelData[i] * channelData[i]; 196 } 197 const maxVolume = Math.sqrt(sum / channelData.length); 198 // Check if buffer size has reached or exceeded the threshold 199 if (this.buffer.length >= this.bufferSize) { 200 const float32Array = this.isMuted 201 ? new Float32Array(this.buffer.length) 202 : new Float32Array(this.buffer); 203 204 let encodedArray = this.format === "ulaw" 205 ? new Uint8Array(float32Array.length) 206 : new Int16Array(float32Array.length); 207 208 // Iterate through the Float32Array and convert each sample to PCM16 209 for (let i = 0; i < float32Array.length; i++) { 210 // Clamp the value to the range [-1, 1] 211 let sample = Math.max(-1, Math.min(1, float32Array[i])); 212 213 // Scale the sample to the range [-32768, 32767] 214 let value = sample < 0 ? sample * 32768 : sample * 32767; 215 if (this.format === "ulaw") { 216 value = encodeSample(Math.round(value)); 217 } 218 219 encodedArray[i] = value; 220 } 221 222 // Send the buffered data to the main script 223 this.port.postMessage([encodedArray, maxVolume]); 224 225 // Clear the buffer after sending 226 this.buffer = []; 227 } 228 } 229 return true; // Continue processing 230 } 231} 232registerProcessor("rawAudioProcessor", RawAudioProcessor); 233`),v={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},R=["touchstart","touchend","click"],A=null,I=null,O=!1;function y(){I&&(clearTimeout(I),I=null)}function b(){A&&(A.close().catch(()=>{}),A=null,y())}class N{audioElements=[];inputAudioContext=null;audioCaptureContext=null;async attachRemoteTrack(e,t){let i=e.attach();if(i.autoplay=!0,i.controls=!1,t&&i.setSinkId)try{await i.setSinkId(t)}catch(e){console.warn("Failed to set output device for new audio element:",e)}i.style.display="none",document.body.appendChild(i),this.audioElements.push(i)}setupInputAnalysis(e){this.inputAudioContext&&(this.inputAudioContext.close().catch(()=>{}),this.inputAudioContext=null);let t=new AudioContext,i=t.createAnalyser();return t.createMediaStreamSource(new MediaStream([e])).connect(i),this.inputAudioContext=t,{volumeProvider:g(i,t.s
233ampleRate),analyser:i}}async setupOutputAnalysis(e,t,i){this.audioCaptureContext&&(this.audioCaptureContext.close().catch(()=>{}),this.audioCaptureContext=null);let n=new AudioContext;this.audioCaptureContext=n;let s=n.createAnalyser();s.fftSize=2048,s.smoothingTimeConstant=.8;let o=new MediaStream([e.mediaStreamTrack]),r=n.createMediaStreamSource(o),a=g(s,n.sampleRate);await T(n.audioWorklet);let l=new AudioWorkletNode(n,"rawAudioProcessor");return l.port.postMessage({type:"setFormat",format:t.format,sampleRate:t.sampleRate}),l.port.onmessage=e=>{let[t,n]=e.data;i(t.buffer,n)},r.connect(s),s.connect(l),{volumeProvider:a,analyser:s}}setVolume(e){for(let t of this.audioElements)t.volume=e}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw Error("setSinkId is not supported in this browser");await Promise.all(this.audioElements.map(async t=>{try{await t.setSinkId(e)}catch(e){throw console.error("Failed to set sink ID for audio element:",e),e}}))}cleanup(){for(let e of(this.inputAudioContext&&(this.inputAudioContext.close().catch(e=>{console.warn("Error closing input audio context:",e)}),this.inputAudioContext=null),this.audioCaptureContext&&(this.audioCaptureContext.close().catch(e=>{console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null),this.audioElements))e.remove();this.audioElements=[]}}let D=null,w=_("scribeAudioProcessor",`/* 234 * Scribe Audio Processor for converting microphone audio to PCM16 format 235 * Supports resampling for browsers like Firefox that don't support 236 * AudioContext sample rate constraints. 237 * USED BY @elevenlabs/client 238 */ 239 240class ScribeAudioProcessor extends AudioWorkletProcessor { 241 constructor() { 242 super(); 243 this.buffer = []; 244 this.bufferSize = 4096; // Buffer size for optimal chunk transmission 245 246 // Resampling state 247 this.inputSampleRate = null; 248 this.outputSampleRate = null; 249 this.resampleRatio = 1; 250 this.lastSample = 0; 251 this.resampleAccumulator = 0; 252 253 this.port.onmessage = ({ data }) => { 254 if (data.type === "configure") { 255 this.inputSampleRate = data.inputSampleRate; 256 this.outputSampleRate = data.outputSampleRate; 257 if (this.inputSampleRate && this.outputSampleRate) { 258 this.resampleRatio = this.inputSampleRate / this.outputSampleRate; 259 } 260 } 261 }; 262 } 263 264 // Linear interpolation resampling 265 resample(inputData) { 266 if (this.resampleRatio === 1 || !this.inputSampleRate) { 267 return inputData; 268 } 269 270 const outputSamples = []; 271 272 for (let i = 0; i < inputData.length; i++) { 273 const currentSample = inputData[i]; 274 275 // Generate output samples using linear interpolation 276 while (this.resampleAccumulator < 1) { 277 const interpolated = 278 this.lastSample + 279 (currentSample - this.lastSample) * this.resampleAccumulator; 280 outputSamples.push(interpolated); 281 this.resampleAccumulator += this.resampleRatio; 282 } 283 284 this.resampleAccumulator -= 1; 285 this.lastSample = currentSample; 286 } 287 288 return new Float32Array(outputSamples); 289 } 290 291 process(inputs) { 292 const input = inputs[0]; 293 if (input.length > 0) { 294 let channelData = input[0]; // Get first channel (mono) 295 296 // Resample if needed (for Firefox and other browsers that don't 297 // support AudioContext sample rate constraints) 298 if (this.resampleRatio !== 1) { 299 channelData = this.resample(channelData); 300 } 301 302 // Add incoming audio to buffer 303 for (let i = 0; i < channelData.length; i++) { 304 this.buffer.push(channelData[i]); 305 } 306 307 // When buffer reaches threshold, convert and send 308 if (this.buffer.length >= this.bufferSize) { 309 const float32Array = new Float32Array(this.buffer); 310 const int16Array = new Int16Array(float32Array.length); 311 312 // Convert Float32 [-1, 1] to Int16 [-32768, 32767] 313 for (let i = 0; i < float32Array.length; i++) { 314 // Clamp the value to prevent overflow 315 const sample = Math.max(-1, Math.min(1, float32Array[i])); 316 // Scale to PCM16 range 317 int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767; 318 } 319 320 // Send to main thread as transferable ArrayBuffer 321 this.port.postMessage( 322 { 323 audioData: int16Array.buffer 324 }, 325 [int16Array.buffer] 326 ); 327 328 // Clear buffer 329 this.buffer = []; 330 } 331 } 332 333 return true; // Continue processing 334 } 335} 336 337registerProcessor("scribeAudioProcessor", ScribeAudioProcessor); 338 339`),M=async(e,t)=>{let i=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.deviceId,echoCancellation:e.echoCancellation??!0,noiseSuppression:e.n
339oiseSuppression??!0,autoGainControl:e.autoGainControl??!0,channelCount:e.channelCount??1,sampleRate:{ideal:16e3}}}),[n]=i.getAudioTracks(),s=n?.getSettings().sampleRate,o=new AudioContext(s?{sampleRate:s}:{});await w(o.audioWorklet);let r=o.createMediaStreamSource(i),a=new AudioWorkletNode(o,"scribeAudioProcessor");return 16e3!==o.sampleRate&&a.port.postMessage({type:"configure",inputSampleRate:o.sampleRate,outputSampleRate:16e3}),a.port.onmessage=e=>{t(p(e.data.audioData))},r.connect(a),"suspended"===o.state&&await o.resume(),{mediaStreamTrack:n,cleanup:()=>{for(let e of i.getTracks())e.stop();r.disconnect(),a.disconnect(),o.close()}}};new Uint8Array(0);class L{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let i=this.listeners.get(e);i&&i.add(t)}off(e,t){let i=this.listeners.get(e);i&&i.delete(t)}emit(e,...t){let i=this.listeners.get(e);i&&i.forEach(e=>{e(...t)})}}!function(e){e.SESSION_STARTED="session_started",e.PARTIAL_TRANSCRIPT="partial_transcript",e.COMMITTED_TRANSCRIPT="committed_transcript",e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",e.AUTH_ERROR="auth_error",e.ERROR="error",e.OPEN="open",e.CLOSE="close",e.QUOTA_EXCEEDED="quota_exceeded",e.COMMIT_THROTTLED="commit_throttled",e.TRANSCRIBER_ERROR="transcriber_error",e.UNACCEPTED_TERMS="unaccepted_terms",e.RATE_LIMITED="rate_limited",e.INPUT_ERROR="input_error",e.QUEUE_OVERFLOW="queue_overflow",e.RESOURCE_EXHAUSTED="resource_exhausted",e.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",e.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",e.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity"}(l||(l={}));class k{websocket=null;eventEmitter=new L;currentSampleRate=16e3;_muted=!1;_audioCleanup;_mediaStreamTrack;constructor(e){this.currentSampleRate=e}get isMuted(){return this._muted}getMediaStreamTrackForMute(e){if(!this._mediaStreamTrack)throw Error(`Cannot ${e} audio without an active microphone MediaStreamTrack. mute() and unmute() are only supported for microphone connections.`);return this._mediaStreamTrack}mute(){let e=this.getMediaStreamTrackForMute("mute");this._muted=!0,e.enabled=!1}unmute(){let e=this.getMediaStreamTrackForMute("unmute");this._muted=!1,e.enabled=!0}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(l.OPEN):this.websocket.addEventListener("open",()=>{this.eventEmitter.emit(l.OPEN)}),this.websocket.addEventListener("message",e=>{try{let t=JSON.parse(e.data);switch(t.message_type){case"session_started":this.eventEmitter.emit(l.SESSION_STARTED,t);break;case"partial_transcript":this.eventEmitter.emit(l.PARTIAL_TRANSCRIPT,t);break;case"committed_transcript":this.eventEmitter.emit(l.COMMITTED_TRANSCRIPT,t);break;case"committed_transcript_with_timestamps":this.eventEmitter.emit(l.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case"auth_error":this.eventEmitter.emit(l.AUTH_ERROR,t),this.eventEmitter.emit(l.ERROR,t);break;case"quota_exceeded":this.eventEmitter.emit(l.QUOTA_EXCEEDED,t),this.eventEmitter.emit(l.ERROR,t);break;case"commit_throttled":this.eventEmitter.emit(l.COMMIT_THROTTLED,t),this.eventEmitter.emit(l.ERROR,t);break;case"transcriber_error":this.eventEmitter.emit(l.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(l.ERROR,t);break;case"unaccepted_terms":this.eventEmitter.emit(l.UNACCEPTED_TERMS,t),this.eventEmitter.emit(l.ERROR,t);break;case"rate_limited":this.eventEmitter.emit(l.RATE_LIMITED,t),this.eventEmitter.emit(l.ERROR,t);break;case"input_error":this.eventEmitter.emit(l.INPUT_ERROR,t),this.eventEmitter.emit(l.ERROR,t);break;case"queue_overflow":this.eventEmitter.emit(l.QUEUE_OVERFLOW,t),this.eventEmitter.emit(l.ERROR,t);break;case"resource_exhausted":this.eventEmitter.emit(l.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(l.ERROR,t);break;case"session_time_limit_exceeded":this.eventEmitter.emit(l.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(l.ERROR,t);break;case"chunk_size_exceeded":this.eventEmitter.emit(l.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(l.ERROR,t);break;case"insufficient_audio_activity":this.eventEmitter.emit(l.INSUFFICIENT_AU
339DIO_ACTIVITY,t),this.eventEmitter.emit(l.ERROR,t);break;case"error":this.eventEmitter.emit(l.ERROR,t);break;default:console.warn("Unknown message type:",t)}}catch(t){console.error("Failed to parse WebSocket message:",t,e.data),this.eventEmitter.emit(l.ERROR,Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener("error",e=>{console.error("WebSocket error:",e),this.eventEmitter.emit(l.ERROR,e)}),this.websocket.addEventListener("close",e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||1e3!==e.code&&1005!==e.code){let t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||"No reason provided"}`;console.error(t),this.eventEmitter.emit(l.ERROR,Error(t))}this.eventEmitter.emit(l.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error("WebSocket is not connected");let t={message_type:"input_audio_chunk",audio_base_64:e.audioBase64,commit:e.commit??!1,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(t))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error("WebSocket is not connected");let e={message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:this.currentSampleRate};this.websocket.send(JSON.stringify(e))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,"User ended session")}}!function(e){e.PCM_8000="pcm_8000",e.PCM_16000="pcm_16000",e.PCM_22050="pcm_22050",e.PCM_24000="pcm_24000",e.PCM_44100="pcm_44100",e.PCM_48000="pcm_48000",e.ULAW_8000="ulaw_8000"}(c||(c={})),function(e){e.MANUAL="manual",e.VAD="vad"}(d||(d={}));class P{static DEFAULT_BASE_URI="wss://api.elevenlabs.io";static getWebSocketUri(e=P.DEFAULT_BASE_URI){return`${e}
339/v1/speech-to-text/realtime`}static buildWebSocketUri(e){let t=P.getWebSocketUri(e.baseUri),i=new URLSearchParams;if(i.append("model_id",e.modelId),i.append("token",e.token),void 0!==e.commitStrategy&&i.append("commit_strategy",e.commitStrategy),void 0!==e.audioFormat&&i.append("audio_format",e.audioFormat),void 0!==e.vadSilenceThresholdSecs){if(e.vadSilenceThresholdSecs<=.3||e.vadSilenceThresholdSecs>3)throw Error("vadSilenceThresholdSecs must be between 0.3 and 3.0");i.append("vad_silence_threshold_secs",e.vadSilenceThresholdSecs.toString())}if(void 0!==e.vadThreshold){if(e.vadThreshold<.1||e.vadThreshold>.9)throw Error("vadThreshold must be between 0.1 and 0.9");i.append("vad_threshold",e.vadThreshold.toString())}if(void 0!==e.minSpeechDurationMs){if(e.minSpeechDurationMs<=50||e.minSpeechDurationMs>2e3)throw Error("minSpeechDurationMs must be between 50 and 2000");i.append("min_speech_duration_ms",e.minSpeechDurationMs.toString())}if(void 0!==e.minSilenceDurationMs){if(e.minSilenceDurationMs<=50||e.minSilenceDurationMs>2e3)throw Error("minSilenceDurationMs must be between 50 and 2000");i.append("min_silence_duration_ms",e.minSilenceDurationMs.toString())}if(void 0!==e.languageCode&&i.append("language_code",e.languageCode),void 0!==e.includeTimestamps&&i.append("include_timestamps",e.includeTimestamps?"true":"false"),void 0!==e.includeLanguageDetection&&i.append("include_language_detection",e.includeLanguageDetection?"true":"false"),void 0!==e.ke
339yterms)for(let t of e.keyterms)i.append("keyterms",t);void 0!==e.noVerbatim&&i.append("no_verbatim",e.noVerbatim?"true":"false");let n=i.toString();return n?`${t}?${n}`:t}static connect(e){if(!e.modelId)throw Error("modelId is required");let t=new k("microphone"in e&&e.microphone?16e3:e.sampleRate),i=new WebSocket(P.buildWebSocketUri(e));return"microphone"in e&&e.microphone&&i.addEventListener("open",()=>{P.streamFromMicrophone(e,t)}),t.setWebSocket(i),t}static async streamFromMicrophone(e,t){try{let i=function(){if(!D)throw Error("No Scribe microphone implementation registered. Import '@elevenlabs/client/platform/web' or provide a custom implementation via setScribeMicrophoneSetup().");return D}(),n=await i(e.microphone??{},e=>{t.send({audioBase64:e})});t._mediaStreamTrack=n.mediaStreamTrack,t._audioCleanup=n.cleanup}catch(e){throw console.error("Failed to start microphone streaming:",e),e}}}!function(){if(!f()||O||"undefined"==typeof document)return;O=!0;let e=()=>{!function(){if(!f()||A)return;let e=new AudioContext,t=e.createBuffer(1,1,22050),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),e.resume().catch(()=>{}),A=e,I&&clearTimeout(I),I=setTimeout(()=>{I=null,b()},3e4)}()};for(let t of R)document.addEventListener(t,e,!0)}(),n=()=>new N,D=M;var U=i(65162);function x(e={}){let{onSessionStarted:t,onPartialTranscript:i,onCommittedTranscript:n,onCommittedTranscriptWithTimestamps:s,onError:o,onAuthError:r,onQuotaExceededError:a,onCommitThrottledError:c,onTranscriberError:d,onUnacceptedTermsError:u,onRateLimitedError:h,onInputError:E,onQueueOverflowError:p,onResourceExhaustedError:m,onSessionTimeLimitExceededError:S,onChunkSizeExceededError:C,onInsufficientAudioActivityError:_,onConnect:g,onDisconnect:f,token:T,modelId:v,baseUri:R,commitStrategy:A,vadSilenceThresholdSecs:I,vadThreshold:O,minSpeechDurationMs:y,minSilenceDurationMs:b,languageCode:N,microphone:D,audioFormat:w,sampleRate:
339M,autoConnect:L=!1,includeTimestamps:k,includeLanguageDetection:F,keyterms:V,noVerbatim:G}=e,B=(0,U.useRef)(null),[$,W]=(0,U.useState)("disconnected"),[H,j]=(0,U.useState)(!1),[q,z]=(0,U.useState)(""),[K,X]=(0,U.useState)([]),[J,Y]=(0,U.useState)(null);(0,U.useEffect)(()=>()=>{B.current?.close()},[]);let Q=(0,U.useCallback)(async(e={})=>{if(B.current)return void console.warn("Already connected");try{let L;W("connecting"),Y(null);let U=e.token||T,x=e.modelId||v;if(!U)throw Error("Token is required");if(!x)throw Error("Model ID is required");let $=e.microphone||D,H=e.audioFormat||w,q=e.sampleRate||M,K=e.includeTimestamps??k??!!(e.onCommittedTranscriptWithTimestamps||s),J=e.includeLanguageDetection??F;if($)L=P.connect({token:U,modelId:x,baseUri:e.baseUri||R,commitStrategy:e.commitStrategy||A,vadSilenceThresholdSecs:e.vadSilenceThresholdSecs||I,vadThreshold:e.vadThreshold||O,minSpeechDurationMs:e.minSpeechDurationMs||y,minSilenceDurationMs:e.minSilenceDurationMs||b,languageCode:e.languageCode||N,keyterms:e.keyterms||V,noVerbatim:e.noVerbatim??G,microphone:$,includeTimestamps:K,includeLanguageDetection:J});else if(H&&q)L=P.connect({token:U,modelId:x,baseUri:e.baseUri||R,commitStrategy:e.commitStrategy||A,vadSilenceThresholdSecs:e.vadSilenceThresholdSecs||I,vadThreshold:e.vadThreshold||O,minSpeechDurationMs:e.minSpeechDurationMs||y,minSilenceDurationMs:e.minSilenceDurationMs||b,languageCode:e.languageCode||N,keyterms:e.keyterms||V,noVerbatim:e.noVerbatim??G,includeTimestamps:K,includeLanguageDetection:J,audioFormat:H,sampleRate:q});else throw Error("Either microphone options or (audioFormat + sampleRate) must be provided");B.current=L,L.on(l.SESSION_STARTED,()=>{W("connected"),t?.()}),L.on(l.PARTIAL_TRANSCRIPT,e=>{z(e.text),W("transcribing"),i?.(e)}),L.on(l.COMMITTED_TRANSCRIPT,e=>{let t={id:`${Date.now()}-${Math.random()}`,text:e.text,timestamp:Date.now(),isFinal:!0};X(e=>[...e,t]),z(""),n?.(e)}),L.on(l.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,e=>{let t={id:`${Date.now()}-${Math.random()}`,text:e.text,timestamp:Date.now(),isFinal:!0,languageCode:e.language_code,words:e.words};X(e=>[...e,t]),z(""),s?.(e)}),L.on(l.ERROR,e=>{Y(e.error),W("error"),o?.(Error(e.error))}),L.on(l.AUTH_ERROR,e=>{Y(e.error),W("error"),r?.(e)}),L.on(l.QUOTA_EXCEEDED,e=>{Y(e.error),W("error"),a?.(e)}),L.on(l.COMMIT_THROTTLED,e=>{Y(e.error),W("error"),c?.(e)}),L.on(l.TRANSCRIBER_ERROR,e=>{Y(e.error),W("error"),d?.(e)}),L.on(l.UNACCEPTED_TERMS,e=>{Y(e.error),W("error"),u?.(e)}),L.on(l.RATE_LIMITED,e=>{Y(e.error),W("error"),h?.(e)}),L.on(l.INPUT_ERROR,e=>{Y(e.error),W("error"),E?.(e)}),L.on(l.QUEUE_OVERFLOW,e=>{Y(e.error),W("error"),p?.(e)}),L.on(l.RESOURCE_EXHAUSTED,e=>{Y(e.error),W("error"),m?.(e)}),L.on(l.SESSION_TIME_LIMIT_EXCEEDED,e=>{Y(e.error),W("error"),S?.(e)}),L.on(l.CHUNK_SIZE_EXCEEDED,e=>{Y(e.error),W("error"),C?.(e)}),L.on(l.INSUFFICIENT_AUDIO_ACTIVITY,e=>{Y(e.error),W("error"),_?.(e)}),L.on(l.OPEN,()=>{g?.()}),L.on(l.CLOSE,()=>{W("disconnected"),j(!1),B.current=null,f?.()})}catch(e){throw Y(e instanceof Error?e.message:"Failed to connect"),W("error"),e}},[T,v,R,A,I,O,y,b,N,D,w,M,k,F,V,G,t,i,n,s,o,r,a,c,d,u,h,E,p,m,S,C,_,g,f]),Z=(0,U.useCallback)(()=>{B.current?.close(),B.current=null,W("disconnected"),j(!1)},[]),ee=(0,U.useCallback)(()=>{if(!B.current)throw Error("Not connected to Scribe");B.current.mute(),j(!0)},[]),et=(0,U.useCallback)(()=>{if(!B.current)throw Error("Not connected to Scribe");B.current.unmute(),j(!1)},[]),ei=(0,U.useCallback)((e,t)=>{if(!B.current)throw Error("Not connected to Scribe");B.current.send({audioBase64:e,...t})},[]),en=(0,U.useCallback)(()=>{if(!B.current)throw Error("Not connected to Scribe");B.current.commit()},[]),es=(0,U.useCallback)(()=>{X([]),z("")},[]),eo=(0,U.useCallback)(()=>B.current,[]);return(0,U.useEffect)(()=>{L&&Q()},[L,Q]),{status:$,isConnected:"connected"===$||"transcribing"===$,isTranscribing:"transcribing"===$,isMuted:H,partialTranscript:q,committedTranscripts:K,error:J,connect:Q,disconnect:Z,mute:ee,unmute:et,sendAudio:ei,commit:en,clearTranscripts:es,getConnection:eo}}i(4930),(0,U.createContext)(null),new Uint8Array(0),(0,U.createContext)(null),(0,U.createContext)(null),(0,U.createContext)(null),(0,U.createContext)(null),(0,U.createContext)(null),(0,U.createContext)(null),o=Object.freeze({name:"react_sdk",version:"1.8.0"})}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.