@anam-ai/js-sdk 4.21.0-alpha.0 → 4.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main/modules/SignallingClient.d.ts +6 -0
- package/dist/main/modules/SignallingClient.d.ts.map +1 -1
- package/dist/main/modules/SignallingClient.js +52 -17
- package/dist/main/modules/SignallingClient.js.map +1 -1
- package/dist/main/modules/StreamingClient.d.ts.map +1 -1
- package/dist/main/modules/StreamingClient.js +2 -3
- package/dist/main/modules/StreamingClient.js.map +1 -1
- package/dist/main/types/PersonaConfig.d.ts +0 -1
- package/dist/main/types/PersonaConfig.d.ts.map +1 -1
- package/dist/main/types/PersonaConfig.js.map +1 -1
- package/dist/main/types/streaming/WebRtcPersonaConfigUpdateAppliedEvent.d.ts +0 -1
- package/dist/main/types/streaming/WebRtcPersonaConfigUpdateAppliedEvent.d.ts.map +1 -1
- package/dist/module/modules/SignallingClient.d.ts +6 -0
- package/dist/module/modules/SignallingClient.d.ts.map +1 -1
- package/dist/module/modules/SignallingClient.js +52 -17
- package/dist/module/modules/SignallingClient.js.map +1 -1
- package/dist/module/modules/StreamingClient.d.ts.map +1 -1
- package/dist/module/modules/StreamingClient.js +2 -3
- package/dist/module/modules/StreamingClient.js.map +1 -1
- package/dist/module/types/PersonaConfig.d.ts +0 -1
- package/dist/module/types/PersonaConfig.d.ts.map +1 -1
- package/dist/module/types/PersonaConfig.js.map +1 -1
- package/dist/module/types/streaming/WebRtcPersonaConfigUpdateAppliedEvent.d.ts +0 -1
- package/dist/module/types/streaming/WebRtcPersonaConfigUpdateAppliedEvent.d.ts.map +1 -1
- package/dist/umd/anam.js +1 -1
- package/package.json +2 -2
package/dist/umd/anam.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! For license information please see anam.js.LICENSE.txt */
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.anam=t():e.anam=t()}(self,()=>{return e={18:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreApiRestClient=void 0;const s=n(71),o=n(985),r=n(672);function a(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function l(e){return!(e instanceof s.ClientError)||e.statusCode>=500&&e.statusCode<600}function c(e){return new Promise(t=>setTimeout(t,e))}t.CoreApiRestClient=class{constructor(e,t,n){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(null==n?void 0:n.baseUrl)||o.DEFAULT_API_BASE_URL,this.apiVersion=(null==n?void 0:n.apiVersion)||o.DEFAULT_API_VERSION,this.apiGatewayConfig=(null==n?void 0:n.apiGateway)||void 0,this.retryOptions=function(e){const t=Math.max(1,Math.floor(a(null==e?void 0:e.maxAttempts,o.DEFAULT_START_SESSION_MAX_ATTEMPTS))),n=Math.max(0,a(null==e?void 0:e.initialBackoffMs,o.DEFAULT_START_SESSION_INITIAL_BACKOFF_MS));return{maxAttempts:t,initialBackoffMs:n,maxBackoffMs:Math.max(n,a(null==e?void 0:e.maxBackoffMs,o.DEFAULT_START_SESSION_MAX_BACKOFF_MS))}}(null==n?void 0:n.retry),this.requestTimeoutMs=Math.max(0,a(null==n?void 0:n.requestTimeoutMs,o.DEFAULT_START_SESSION_REQUEST_TIMEOUT_MS))}buildGatewayUrlAndHeaders(e,t){var n,i;if((null===(n=this.apiGatewayConfig)||void 0===n?void 0:n.enabled)&&(null===(i=this.apiGatewayConfig)||void 0===i?void 0:i.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,i=new URL(`${this.baseUrl}${e}`);return{url:n,headers:Object.assign(Object.assign({},t),{"X-Anam-Target-Url":i.href})}}return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return i(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new s.ClientError("Persona configuration must be provided when using apiKey",s.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");const{maxAttempts:n}=this.retryOptions;let i;for(let s=1;s<=n;s++)try{return yield this.attemptStartSession(e,t)}catch(e){if(i=e,s>=n||!l(e))throw e;yield c(this.computeBackoffDelay(s))}throw i})}attemptStartSession(e,t){return i(this,void 0,void 0,function*(){const n=this.requestTimeoutMs>0?new AbortController:void 0,i=void 0!==n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:a}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),l=yield fetch(r,{method:"POST",headers:a,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:o.CLIENT_METADATA}),signal:null==n?void 0:n.signal}),c=yield l.json(),d=c.error;switch(l.status){case 200:case 201:return c;case 400:throw new s.ClientError("Invalid request to start session",s.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:c.message});case 401:throw new s.ClientError("Authentication failed when starting session",s.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:c.message});case 402:throw new s.ClientError("Please sign up for a plan to start a session",s.ErrorCode.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:c.message});case 403:throw new s.ClientError("Authentication failed when starting session",s.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:c.message});case 429:throw"Concurrent session limit reached"===d?new s.ClientError("Concurrency limit reached, please upgrade your plan",s.ErrorCode.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:c.message}):"Spend cap reached"===d?new s.ClientError("Spend cap reached, please upgrade your plan",s.ErrorCode.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:c.message}):new s.ClientError("Usage limit reached, please upgrade your plan",s.ErrorCode.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:c.message});case 503:throw new s.ClientError("There are no available personas, please try again later",s.ErrorCode.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:c.message});default:throw new s.ClientError("Unknown error when starting session",s.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,l.status,{cause:c.message})}}catch(e){if(e instanceof s.ClientError)throw e;throw new s.ClientError("Failed to start session",s.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e)})}finally{void 0!==i&&clearTimeout(i)}})}computeBackoffDelay(e){const{initialBackoffMs:t,maxBackoffMs:n}=this.retryOptions,i=Math.min(n,t*Math.pow(2,e-1));return Math.floor(i/2+Math.random()*(i/2))}unsafe_getSessionToken(e){return i(this,void 0,void 0,function*(){if(console.warn("Using an insecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};(0,r.isCustomPersonaConfig)(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const e=`${this.apiVersion}/auth/session-token`,{url:n,headers:i}=this.buildGatewayUrlAndHeaders(e,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}),s=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(t)});return(yield s.json()).sessionToken}catch(e){throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}},21:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AnamEvent=void 0,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_SPEECH_STARTED",e.USER_SPEECH_ENDED="USER_SPEECH_ENDED",e.DIRECTOR_NOTE_CUE_APPLIED="DIRECTOR_NOTE_CUE_APPLIED",e.PERSONA_CONFIG_UPDATE_APPLIED="PERSONA_CONFIG_UPDATE_APPLIED"}(n||(t.AnamEvent=n={}))},35:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.ToolCallManager=void 0;const s=n(170),o=(e,t)=>{if(isNaN(e)||isNaN(t))return 0;const n=t-e;return n>0?n:0};t.ToolCallManager=class{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 i(this,void 0,void 0,function*(){if(this.activeSessionId!==e.session_id)return;const{tool_name:t,timestamp:n}=e,i=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),s=new Date(n);if(this.pendingCalls[e.tool_call_id]={payload:i,timestamp:s.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let t=yield o.onStart(i);if("client"===e.tool_type)return 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}),void(yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:t,timestamp:(new Date).toISOString()})))}catch(t){const n=t instanceof Error?t.message:String(t);return"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: ${n}`}),void(yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${n}`,timestamp:(new Date).toISOString()})))}})}processToolCallCompletedEvent(e){return i(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:n,timestamp:i}=e;if(this.activeSessionId!==e.session_id)return;if(n in this.failedCalls)return void delete this.failedCalls[n];const o=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(n in this.pendingCalls&&delete this.pendingCalls[n],!(t in this.handlers))return;const r=this.handlers[t];if(r.onComplete){"client"===e.tool_type&&this.publicEventEmitter.emit(s.AnamEvent.TOOL_CALL_COMPLETED,o);try{yield r.onComplete(o)}catch(e){return void console.error(`Error in onComplete handler for tool ${t}:`,e)}}})}processToolCallFailedEvent(e){return i(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:n,timestamp:i}=e;if(this.activeSessionId!==e.session_id)return;const o=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(this.failedCalls[n]=o,n in this.pendingCalls&&delete this.pendingCalls[n],!(t in this.handlers))return;const r=this.handlers[t];if(r.onFail){"client"===e.tool_type&&this.publicEventEmitter.emit(s.AnamEvent.TOOL_CALL_FAILED,o);try{yield r.onFail(o)}catch(e){return void console.error(`Error in onFail handler for tool ${t}:`,e)}}})}sendToolResult(e){const t={sessionId:e.sessionId,toolCallId:e.toolCallId,result:e.result,errorMessage:e.errorMessage,userActionCorrelationId:e.userActionCorrelationId,timestampUserAction:e.timestampUserAction};this.internalEventEmitter.emit(s.InternalEvent.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){const t=new Date(e.timestamp),n=this.pendingCalls[e.tool_call_id],i=n?o(n.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:i>0?i:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),n=this.pendingCalls[e.tool_call_id],i=n?o(n.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:i>0?i:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}},60:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionClosedCode=void 0,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"}(n||(t.ConnectionClosedCode=n={}))},71:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClientError=t.ErrorCode=void 0;const i=n(948);var s;!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"}(s||(t.ErrorCode=s={}));class o extends Error{constructor(e,t,n=500,s){super(e),this.name="ClientError",this.code=t,this.statusCode=n,this.details=s,Object.setPrototypeOf(this,o.prototype),(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:s,statusCode:n})}}t.ClientError=o},170:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentAudioInputStream=t.ConnectionClosedCode=t.InternalEvent=t.AnamEvent=t.MessageRole=t.AudioPermissionState=t.DataChannelMessage=t.SignalMessageAction=void 0;var i=n(295);Object.defineProperty(t,"SignalMessageAction",{enumerable:!0,get:function(){return i.SignalMessageAction}});var s=n(513);Object.defineProperty(t,"DataChannelMessage",{enumerable:!0,get:function(){return s.DataChannelMessage}});var o=n(793);Object.defineProperty(t,"AudioPermissionState",{enumerable:!0,get:function(){return o.AudioPermissionState}});var r=n(822);Object.defineProperty(t,"MessageRole",{enumerable:!0,get:function(){return r.MessageRole}});var a=n(878);Object.defineProperty(t,"AnamEvent",{enumerable:!0,get:function(){return a.AnamEvent}});var l=n(878);Object.defineProperty(t,"InternalEvent",{enumerable:!0,get:function(){return l.InternalEvent}});var c=n(878);Object.defineProperty(t,"ConnectionClosedCode",{enumerable:!0,get:function(){return c.ConnectionClosedCode}});var d=n(421);Object.defineProperty(t,"AgentAudioInputStream",{enumerable:!0,get:function(){return d.AgentAudioInputStream}})},251:(e,t)=>{t.read=function(e,t,n,i,s){var o,r,a=8*s-i-1,l=(1<<a)-1,c=l>>1,d=-7,u=n?s-1:0,h=n?-1:1,E=e[t+u];for(u+=h,o=E&(1<<-d)-1,E>>=-d,d+=a;d>0;o=256*o+e[t+u],u+=h,d-=8);for(r=o&(1<<-d)-1,o>>=-d,d+=i;d>0;r=256*r+e[t+u],u+=h,d-=8);if(0===o)o=1-c;else{if(o===l)return r?NaN:1/0*(E?-1:1);r+=Math.pow(2,i),o-=c}return(E?-1:1)*r*Math.pow(2,o-i)},t.write=function(e,t,n,i,s,o){var r,a,l,c=8*o-s-1,d=(1<<c)-1,u=d>>1,h=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,E=i?0:o-1,p=i?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,r=d):(r=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-r))<1&&(r--,l*=2),(t+=r+u>=1?h/l:h*Math.pow(2,1-u))*l>=2&&(r++,l/=2),r+u>=d?(a=0,r=d):r+u>=1?(a=(t*l-1)*Math.pow(2,s),r+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,s),r=0));s>=8;e[n+E]=255&a,E+=p,a/=256,s-=8);for(r=r<<s|a,c+=s;c>0;e[n+E]=255&r,E+=p,r/=256,c-=8);e[n+E-p]|=128*f}},259:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalEventEmitter=void 0,t.InternalEventEmitter=class{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)})}}},272:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateApiGatewayConfig=void 0,t.validateApiGatewayConfig=function(e){if(e&&e.enabled){if(!e.baseUrl)return"API Gateway baseUrl is required when enabled";try{const 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}`}return e.wsPath&&!e.wsPath.startsWith("/")?"API Gateway wsPath must start with /":void 0}}},273:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MessageRole=void 0,function(e){e.USER="user",e.PERSONA="persona"}(n||(t.MessageRole=n={}))},279:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.SignallingClient=void 0;const s=n(170);t.SignallingClient=class{constructor(e,t,n,i,s,o){var r,a,l,c,d;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.permanentlyClosed=!1,this.iceRestartReconnectInProgress=!1,this.heartBeatIntervalRef=null,this.reconnectTimer=null,this.publicEventEmitter=n,this.internalEventEmitter=i,this.apiGatewayConfig=s,this.connectionMilestones=o,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:h,url:E}=t;if(this.heartbeatIntervalSeconds=u||5,this.maxWsReconnectionAttempts=h||5,!E.baseUrl)throw new Error("Signalling Client: baseUrl is required");if((null===(r=this.apiGatewayConfig)||void 0===r?void 0:r.enabled)&&(null===(a=this.apiGatewayConfig)||void 0===a?void 0:a.baseUrl)){const t=new URL(this.apiGatewayConfig.baseUrl),n=null!==(l=this.apiGatewayConfig.wsPath)&&void 0!==l?l:"/ws";t.protocol=t.protocol.replace("http","ws"),t.pathname=n,this.url=t;const i=E.protocol||"https",s="http"===i?"ws":"wss",o=`${i}://${E.baseUrl}`,r=null!==(c=E.signallingPath)&&void 0!==c?c:"/ws",a=new URL(o);a.protocol="ws"===s?"ws:":"wss:",E.port&&(a.port=E.port),a.pathname=r,a.searchParams.append("session_id",e),this.url.searchParams.append("target_url",a.href)}else{const t=`${E.protocol||"https"}://${E.baseUrl}`;this.url=new URL(t),this.url.protocol="http"===E.protocol?"ws:":"wss:",E.port&&(this.url.port=E.port),this.url.pathname=null!==(d=E.signallingPath)&&void 0!==d?d:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){var e;this.clearReconnectTimer(),null===(e=this.connectionMilestones)||void 0===e||e.record("websocket_connecting",{attemptNumber:this.wsConnectionAttempts+1});const t=new WebSocket(this.url.href);return this.socket=t,t.onopen=()=>{this.onOpen(t)},t.onclose=e=>{this.onClose(t,e)},t.onerror=e=>{this.onError(t,e)},t}reconnectForIceRestart(){if(!this.isPermanentlyClosed()){if(this.clearReconnectTimer(),this.socket){this.socket.onopen=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null;try{this.socket.close()}catch(e){console.warn("SignallingClient - reconnectForIceRestart: error closing stale socket",e)}this.socket=null}this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.wsConnectionAttempts=0,this.iceRestartReconnectInProgress=!0,this.connect()}}endIceRestartReconnect(){this.iceRestartReconnectInProgress=!1}isConnected(){var e;return(null===(e=this.socket)||void 0===e?void 0:e.readyState)===WebSocket.OPEN}isPermanentlyClosed(){return this.permanentlyClosed||this.stopSignal}sendOffer(e){return i(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},n={actionType:s.SignalMessageAction.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(n)})}sendIceCandidate(e){return i(this,void 0,void 0,function*(){const t={actionType:s.SignalMessageAction.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if((null===(t=this.socket)||void 0===t?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 i(this,void 0,void 0,function*(){const t={actionType:s.SignalMessageAction.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:s.SignalMessageAction.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:s.SignalMessageAction.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.clearReconnectTimer(),this.iceRestartReconnectInProgress=!1,this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(e){return i(this,void 0,void 0,function*(){var t;if(this.socket===e)try{null===(t=this.connectionMilestones)||void 0===t||t.record("websocket_open",{attemptNumber:this.wsConnectionAttempts+1}),this.wsConnectionAttempts=0,this.flushSendingBuffer(),e.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(s.InternalEvent.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.permanentlyClosed=!0}})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}onClose(e,t){return i(this,void 0,void 0,function*(){var n,i,o;if(this.socket!==e)return;if(null===(n=this.connectionMilestones)||void 0===n||n.record("websocket_closed",{attemptNumber:this.wsConnectionAttempts+1,closeCode:null==t?void 0:t.code,wasClean:null==t?void 0:t.wasClean}),this.wsConnectionAttempts+=1,this.stopSignal)return;const r=this.getMaxReconnectionAttempts();if(this.wsConnectionAttempts<=r){const e=100*this.wsConnectionAttempts;null===(i=this.connectionMilestones)||void 0===i||i.record("websocket_retry_scheduled",{attemptNumber:this.wsConnectionAttempts+1,delayMs:e}),this.socket=null,this.clearReconnectTimer(),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}else this.clearReconnectTimer(),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),null===(o=this.connectionMilestones)||void 0===o||o.publishFailure({failureStage:"websocket",closeCode:null==t?void 0:t.code}),this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.iceRestartReconnectInProgress=!1,this.permanentlyClosed=!0})}getMaxReconnectionAttempts(){return this.iceRestartReconnectInProgress?Math.max(this.maxWsReconnectionAttempts,24):this.maxWsReconnectionAttempts}onError(e,t){var n;this.stopSignal||this.socket!==e||(null===(n=this.connectionMilestones)||void 0===n||n.record("websocket_error",{eventType:t.type}),console.error("SignallingClient - onError: ",t))}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var n;(null===(n=this.socket)||void 0===n?void 0:n.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return i(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(s.InternalEvent.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=1e3*this.heartbeatIntervalSeconds,t={actionType:s.SignalMessageAction.HEARTBEAT,sessionId:this.sessionId,payload:""},n=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var e;this.stopSignal||(null===(e=this.socket)||void 0===e?void 0:e.readyState)===WebSocket.OPEN&&this.socket.send(n)},e)}}},287:(e,t,n)=>{"use strict";const i=n(526),s=n(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=function(e){return+e!=e&&(e=0),l.alloc(+e)},t.INSPECT_MAX_BYTES=50;const r=2147483647;function a(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let i=a(n);const s=i.write(e,t);return s!==n&&(i=i.slice(0,s)),i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Y(e,Uint8Array)){const t=new Uint8Array(e);return E(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Y(e,ArrayBuffer)||e&&Y(e.buffer,ArrayBuffer))return E(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(Y(e,SharedArrayBuffer)||e&&Y(e.buffer,SharedArrayBuffer)))return E(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return l.from(i,t,n);const s=function(e){if(l.isBuffer(e)){const t=0|p(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||X(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function d(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return d(e),a(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),n=a(t);for(let i=0;i<t;i+=1)n[i]=255&e[i];return n}function E(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(i,l.prototype),i}function p(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Y(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;let s=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return K(e).length;default:if(s)return i?-1:z(e).length;t=(""+t).toLowerCase(),s=!0}}function g(e,t,n){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return y(this,t,n);case"ascii":return b(this,t,n);case"latin1":case"binary":return M(this,t,n);case"base64":return R(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function m(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function C(e,t,n,i,s){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),X(n=+n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=l.from(t,i)),l.isBuffer(t))return 0===t.length?-1:_(e,t,n,i,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):_(e,[t],n,i,s);throw new TypeError("val must be string, number or Buffer")}function _(e,t,n,i,s){let o,r=1,a=e.length,l=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;r=2,a/=2,l/=2,n/=2}function c(e,t){return 1===r?e[t]:e.readUInt16BE(t*r)}if(s){let i=-1;for(o=n;o<a;o++)if(c(e,o)===c(t,-1===i?0:o-i)){if(-1===i&&(i=o),o-i+1===l)return i*r}else-1!==i&&(o-=o-i),i=-1}else for(n+l>a&&(n=a-l),o=n;o>=0;o--){let n=!0;for(let i=0;i<l;i++)if(c(e,o+i)!==c(t,i)){n=!1;break}if(n)return o}return-1}function v(e,t,n,i){n=Number(n)||0;const s=e.length-n;i?(i=Number(i))>s&&(i=s):i=s;const o=t.length;let r;for(i>o/2&&(i=o/2),r=0;r<i;++r){const i=parseInt(t.substr(2*r,2),16);if(X(i))return r;e[n+r]=i}return r}function S(e,t,n,i){return q(z(t,e.length-n),e,n,i)}function T(e,t,n,i){return q(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,i)}function A(e,t,n,i){return q(K(t),e,n,i)}function I(e,t,n,i){return q(function(e,t){let n,i,s;const o=[];for(let r=0;r<e.length&&!((t-=2)<0);++r)n=e.charCodeAt(r),i=n>>8,s=n%256,o.push(s),o.push(i);return o}(t,e.length-n),e,n,i)}function R(e,t,n){return 0===t&&n===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,n))}function y(e,t,n){n=Math.min(e.length,n);const i=[];let s=t;for(;s<n;){const t=e[s];let o=null,r=t>239?4:t>223?3:t>191?2:1;if(s+r<=n){let n,i,a,l;switch(r){case 1:t<128&&(o=t);break;case 2:n=e[s+1],128==(192&n)&&(l=(31&t)<<6|63&n,l>127&&(o=l));break;case 3:n=e[s+1],i=e[s+2],128==(192&n)&&128==(192&i)&&(l=(15&t)<<12|(63&n)<<6|63&i,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:n=e[s+1],i=e[s+2],a=e[s+3],128==(192&n)&&128==(192&i)&&128==(192&a)&&(l=(15&t)<<18|(63&n)<<12|(63&i)<<6|63&a,l>65535&&l<1114112&&(o=l))}}null===o?(o=65533,r=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),s+=r}return function(e){const t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);let n="",i=0;for(;i<t;)n+=String.fromCharCode.apply(String,e.slice(i,i+=O));return n}(i)}t.kMaxLength=r,l.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,n){return function(e,t,n){return d(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}(e,t,n)},l.allocUnsafe=function(e){return u(e)},l.allocUnsafeSlow=function(e){return u(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(Y(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),Y(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.length;for(let s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==t[s]){n=e[s],i=t[s];break}return n<i?-1:i<n?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const i=l.allocUnsafe(t);let s=0;for(n=0;n<e.length;++n){let t=e[n];if(Y(t,Uint8Array))s+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,s)):Uint8Array.prototype.set.call(i,t,s);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,s)}s+=t.length}return i},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)m(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)m(this,t,t+3),m(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)m(this,t,t+7),m(this,t+1,t+6),m(this,t+2,t+5),m(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?y(this,0,e):g.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let e="";const n=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(e,t,n,i,s){if(Y(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),t<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=n)return 0;if(i>=s)return-1;if(t>=n)return 1;if(this===e)return 0;let o=(s>>>=0)-(i>>>=0),r=(n>>>=0)-(t>>>=0);const a=Math.min(o,r),c=this.slice(i,s),d=e.slice(t,n);for(let e=0;e<a;++e)if(c[e]!==d[e]){o=c[e],r=d[e];break}return o<r?-1:r<o?1:0},l.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},l.prototype.indexOf=function(e,t,n){return C(this,e,t,n,!0)},l.prototype.lastIndexOf=function(e,t,n){return C(this,e,t,n,!1)},l.prototype.write=function(e,t,n,i){if(void 0===t)i="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)i=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}const s=this.length-t;if((void 0===n||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return v(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":case"latin1":case"binary":return T(this,e,t,n);case"base64":return A(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const O=4096;function b(e,t,n){let i="";n=Math.min(e.length,n);for(let s=t;s<n;++s)i+=String.fromCharCode(127&e[s]);return i}function M(e,t,n){let i="";n=Math.min(e.length,n);for(let s=t;s<n;++s)i+=String.fromCharCode(e[s]);return i}function N(e,t,n){const i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);let s="";for(let i=t;i<n;++i)s+=J[e[i]];return s}function w(e,t,n){const i=e.slice(t,n);let s="";for(let e=0;e<i.length-1;e+=2)s+=String.fromCharCode(i[e]+256*i[e+1]);return s}function D(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function L(e,t,n,i,s,o){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<o)throw new RangeError('"value" argument is out of bounds');if(n+i>e.length)throw new RangeError("Index out of range")}function P(e,t,n,i,s){x(t,i,s,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let r=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=r,r>>=8,e[n++]=r,r>>=8,e[n++]=r,r>>=8,e[n++]=r,n}function U(e,t,n,i,s){x(t,i,s,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let r=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=r,r>>=8,e[n+2]=r,r>>=8,e[n+1]=r,r>>=8,e[n]=r,n+8}function k(e,t,n,i,s,o){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function B(e,t,n,i,o){return t=+t,n>>>=0,o||k(e,0,n,4),s.write(e,t,n,i,23,4),n+4}function F(e,t,n,i,o){return t=+t,n>>>=0,o||k(e,0,n,8),s.write(e,t,n,i,52,8),n+8}l.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,l.prototype),i},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e],s=1,o=0;for(;++o<t&&(s*=256);)i+=this[e+o]*s;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e+--t],s=1;for(;t>0&&(s*=256);)i+=this[e+--t]*s;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q(function(e){W(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,s=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(i)+(BigInt(s)<<BigInt(32))}),l.prototype.readBigUInt64BE=Q(function(e){W(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],s=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(i)<<BigInt(32))+BigInt(s)}),l.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e],s=1,o=0;for(;++o<t&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=t,s=1,o=this[e+--i];for(;i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*t)),o},l.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q(function(e){W(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),l.prototype.readBigInt64BE=Q(function(e){W(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),s.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),s.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),s.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),s.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||L(this,e,t,n,Math.pow(2,8*n)-1,0);let s=1,o=0;for(this[t]=255&e;++o<n&&(s*=256);)this[t+o]=e/s&255;return t+n},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||L(this,e,t,n,Math.pow(2,8*n)-1,0);let s=n-1,o=1;for(this[t+s]=255&e;--s>=0&&(o*=256);)this[t+s]=e/o&255;return t+n},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);L(this,e,t,n,i-1,-i)}let s=0,o=1,r=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===r&&0!==this[t+s-1]&&(r=1),this[t+s]=(e/o|0)-r&255;return t+n},l.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);L(this,e,t,n,i-1,-i)}let s=n-1,o=1,r=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===r&&0!==this[t+s+1]&&(r=1),this[t+s]=(e/o|0)-r&255;return t+n},l.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,n){return B(this,e,t,!0,n)},l.prototype.writeFloatBE=function(e,t,n){return B(this,e,t,!1,n)},l.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},l.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},l.prototype.copy=function(e,t,n,i){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);const s=i-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),t),s},l.prototype.fill=function(e,t,n,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{const o=l.isBuffer(e)?e:l.from(e,i),r=o.length;if(0===r)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=o[s%r]}return this};const j={};function G(e,t,n){j[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function V(e){let t="",n=e.length;const i="-"===e[0]?1:0;for(;n>=i+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function x(e,t,n,i,s,o){if(e>n||e<t){const i="bigint"==typeof t?"n":"";let s;throw s=o>3?0===t||t===BigInt(0)?`>= 0${i} and < 2${i} ** ${8*(o+1)}${i}`:`>= -(2${i} ** ${8*(o+1)-1}${i}) and < 2 ** ${8*(o+1)-1}${i}`:`>= ${t}${i} and <= ${n}${i}`,new j.ERR_OUT_OF_RANGE("value",s,e)}!function(e,t,n){W(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||$(t,e.length-(n+1))}(i,s,o)}function W(e,t){if("number"!=typeof e)throw new j.ERR_INVALID_ARG_TYPE(t,"number",e)}function $(e,t,n){if(Math.floor(e)!==e)throw W(e,n),new j.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}G("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),G("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),G("ERR_OUT_OF_RANGE",function(e,t,n){let i=`The value of "${e}" is out of range.`,s=n;return Number.isInteger(n)&&Math.abs(n)>2**32?s=V(String(n)):"bigint"==typeof n&&(s=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(s=V(s)),s+="n"),i+=` It must be ${t}. Received ${s}`,i},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function z(e,t){let n;t=t||1/0;const i=e.length;let s=null;const o=[];for(let r=0;r<i;++r){if(n=e.charCodeAt(r),n>55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(r+1===i){(t-=3)>-1&&o.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&o.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function K(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,n,i){let s;for(s=0;s<i&&!(s+n>=t.length||s>=e.length);++s)t[s+n]=e[s];return s}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}const J=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const i=16*n;for(let s=0;s<16;++s)t[i+s]=e[n]+e[s]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},295:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignalMessageAction=void 0;var i=n(656);Object.defineProperty(t,"SignalMessageAction",{enumerable:!0,get:function(){return i.SignalMessageAction}})},322:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TalkMessageStreamState=void 0,function(e){e[e.UNSTARTED=0]="UNSTARTED",e[e.STREAMING=1]="STREAMING",e[e.INTERRUPTED=2]="INTERRUPTED",e[e.ENDED=3]="ENDED"}(n||(t.TalkMessageStreamState=n={}))},353:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateCorrelationId=void 0,t.generateCorrelationId=function(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}},421:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentAudioInputStream=void 0,t.AgentAudioInputStream=class{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const 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){const t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array.from(t,e=>String.fromCharCode(e)).join("");return btoa(n)}}},440:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorCode=t.ClientError=t.unsafe_createClientWithApiKey=t.createClient=void 0;const r=o(n(816)),a=n(71);Object.defineProperty(t,"ClientError",{enumerable:!0,get:function(){return a.ClientError}}),Object.defineProperty(t,"ErrorCode",{enumerable:!0,get:function(){return a.ErrorCode}}),t.createClient=(e,t)=>new r.default(e,void 0,t),t.unsafe_createClientWithApiKey=(e,t,n)=>new r.default(void 0,t,Object.assign(Object.assign({},n),{apiKey:e})),s(n(170),t)},462:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHistoryClient=void 0;const i=n(170);t.MessageHistoryClient=class{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(i.InternalEvent.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return Object.assign({id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted},e.cue_tag?{cueTag:e.cue_tag}:{})}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},n=this.messages.findIndex(e=>e.id===t.id);if(-1!==n){const e=this.messages[n];this.messages[n]=Object.assign(Object.assign({},e),{content:e.content+t.content,interrupted:e.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(i.AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case i.MessageRole.USER:this.processUserMessage(t);break;case i.MessageRole.PERSONA:this.processPersonaMessage(t)}t.endOfSpeech&&this.publicEventEmitter.emit(i.AnamEvent.MESSAGE_HISTORY_UPDATED,this.messages)}}},471:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasoningHistoryClient=void 0;const i=n(170);t.ReasoningHistoryClient=class{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(i.InternalEvent.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(i.AnamEvent.REASONING_STREAM_EVENT_RECEIVED,t);const n={id:t.id,content:t.content,role:t.role},s=this.reasoning_messages.findIndex(e=>e.id===n.id);if(-1!==s){const e=this.reasoning_messages[s];e.content+=n.content,this.reasoning_messages[s]=e}else this.reasoning_messages.push(n);t.endOfThought&&this.publicEventEmitter.emit(i.AnamEvent.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}},513:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebRtcReasoningTextMessageEvent=t.DataChannelMessage=void 0;var i=n(676);Object.defineProperty(t,"DataChannelMessage",{enumerable:!0,get:function(){return i.DataChannelMessage}});var s=n(540);Object.defineProperty(t,"WebRtcReasoningTextMessageEvent",{enumerable:!0,get:function(){return s.WebRtcReasoningTextMessageEvent}})},526:(e,t)=>{"use strict";t.byteLength=function(e){var t=a(e),n=t[0],i=t[1];return 3*(n+i)/4-i},t.toByteArray=function(e){var t,n,o=a(e),r=o[0],l=o[1],c=new s(function(e,t,n){return 3*(t+n)/4-n}(0,r,l)),d=0,u=l>0?r-4:r;for(n=0;n<u;n+=4)t=i[e.charCodeAt(n)]<<18|i[e.charCodeAt(n+1)]<<12|i[e.charCodeAt(n+2)]<<6|i[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===l&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===l&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c},t.fromByteArray=function(e){for(var t,i=e.length,s=i%3,o=[],r=16383,a=0,l=i-s;a<l;a+=r)o.push(c(e,a,a+r>l?l:a+r));return 1===s?(t=e[i-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===s&&(t=(e[i-2]<<8)+e[i-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),o.join("")};for(var n=[],i=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0;r<64;++r)n[r]=o[r],i[o.charCodeAt(r)]=r;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function c(e,t,n){for(var i,s=[],o=t;o<n;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),s.push(l(i));return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},529:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.EngineApiRestClient=void 0,t.EngineApiRestClient=class{constructor(e,t,n){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=n}sendTalkCommand(e){return n(this,void 0,void 0,function*(){var t,n;try{let i,s={"Content-Type":"application/json"};const o="/talk",r=`?session_id=${this.sessionId}`;if((null===(t=this.apiGatewayConfig)||void 0===t?void 0:t.enabled)&&(null===(n=this.apiGatewayConfig)||void 0===n?void 0:n.baseUrl)){i=`${this.apiGatewayConfig.baseUrl}${o}${r}`;const e=new URL(`${this.baseUrl}${o}${r}`);s["X-Anam-Target-Url"]=e.href}else i=`${this.baseUrl}${o}${r}`;const a=yield fetch(i,{method:"POST",headers:s,body:JSON.stringify({content:e})});if(!a.ok)throw new Error(`Failed to send talk command: ${a.status} ${a.statusText}`)}catch(e){throw console.error(e),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}},540:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},577:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.StreamingClient=void 0;const s=n(948),o=n(958),r=n(170),a=n(421),l=n(711),c=n(35),d=15e3,u=3e3;t.StreamingClient=class{constructor(e,t,n,i,s,a){var l,c,d,u;this.peerConnection=null,this.connectionEstablishedEmitted=!1,this.iceRestartInProgress=!1,this.iceRestartAttempts=0,this.iceRestartAwaitedAnswer=!1,this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,this.iceRestartStopped=!1,this.iceDisconnectedGraceTimer=null,this.iceRestartWatchdogTimer=null,this.pendingWsOpenListener=null,this.pendingWsOpenTimeout=null,this.pendingWsOpenReject=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.iceRestartCandidateBuffer=null,this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:r.AudioPermissionState.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.firstLocalIceCandidateSent=!1,this.firstRemoteIceCandidateReceived=!1,this.firstRemoteIceCandidateApplied=!1,this.connectionEstablishedMilestoneRecorded=!1,this.publicEventEmitter=n,this.internalEventEmitter=i,this.toolCallManager=s,this.connectionMilestones=a,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=!0===t.inputAudio.disableInputAudio,this.internalEventEmitter.addListener(r.InternalEvent.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(r.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(r.InternalEvent.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(r.InternalEvent.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(r.InternalEvent.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(r.InternalEvent.TOOL_CALL_RESULT_READY,this.onToolCallResultReceived.bind(this)),this.iceServers=t.iceServers,this.iceTransportPolicy=t.iceTransportPolicy,this.rtcConfiguration=t.rtcConfiguration,this.signallingClient=new o.SignallingClient(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig,this.connectionMilestones),this.engineApiRestClient=new o.EngineApiRestClient(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=null!==(c=null===(l=t.metrics)||void 0===l?void 0:l.showPeerConnectionStatsReport)&&void 0!==c&&c,this.peerConnectionStatsReportOutputFormat=null!==(u=null===(d=t.metrics)||void 0===d?void 0:d.peerConnectionStatsReportOutputFormat)&&void 0!==u?u:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;null===(e=this.inputAudioStream)||void 0===e||e.getAudioTracks().forEach(e=>{e.enabled=!1})}unmuteAllAudioTracks(){var e;null===(e=this.inputAudioStream)||void 0===e||e.getAudioTracks().forEach(e=>{e.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>i(this,void 0,void 0,function*(){if(this.peerConnection&&this.dataChannel&&"open"===this.dataChannel.readyState)try{const 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=>{if("inbound-rtp"===e.type){const t={message_type:"remote_rtp_stats",data:e};this.dataChannel&&"open"===this.dataChannel.readyState&&this.dataChannel.send(JSON.stringify(t))}})}recordSessionSuccess(e){var t,n;this.successMetricFired||(this.successMetricFired=!0,null===(t=this.connectionMilestones)||void 0===t||t.record("first_video_frame",{detectionMethod:e}),null===(n=this.connectionMilestones)||void 0===n||n.recordSessionSuccess({detectionMethod:e}),(0,s.sendClientMetric)(s.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:e}))}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{var e,t;this.successMetricPoller&&(null===(e=this.connectionMilestones)||void 0===e||e.record("first_video_frame_timeout",{timeoutMs:d}),null===(t=this.connectionMilestones)||void 0===t||t.publishFailure({failureStage:"first_video_frame",timeoutMs:d}),console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},d);this.successMetricPoller=setInterval(()=>i(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired)return this.successMetricPoller&&clearInterval(this.successMetricPoller),void clearTimeout(e);try{const t=yield this.peerConnection.getStats();let n=!1,i=null;t.forEach(e=>{"inbound-rtp"===e.type&&"video"===e.kind&&(void 0!==e.framesDecoded&&e.framesDecoded>0?(n=!0,i="framesDecoded"):void 0!==e.framesReceived&&e.framesReceived>0?(n=!0,i="framesReceived"):e.bytesReceived>0&&e.packetsReceived>0&&e.bytesReceived>1e5&&(n=!0,i="bytesReceived"))}),n&&!this.successMetricFired&&(this.recordSessionSuccess(null!=i?i:"unknown"),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch(e){}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const 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 i(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(null==e)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(e=>{e.stop()});const n={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:n}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(r.AnamEvent.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(e){throw console.error("Failed to change audio input device:",e),new Error(`StreamingClient - changeAudioInputDevice: ${e instanceof Error?e.message:String(e)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}onToolCallResultReceived(e){const 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){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){var e;try{if(this.peerConnection)return void console.error("StreamingClient - startConnection: peer connection already exists");this.resetAttemptScopedMilestoneState(),null===(e=this.connectionMilestones)||void 0===e||e.record("connection_start_requested"),this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}resetAttemptScopedMilestoneState(){this.firstLocalIceCandidateSent=!1,this.firstRemoteIceCandidateReceived=!1,this.firstRemoteIceCandidateApplied=!1,this.connectionEstablishedMilestoneRecorded=!1}stopConnection(){return i(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return i(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new l.TalkMessageStream(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new a.AgentAudioInputStream(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return i(this,void 0,void 0,function*(){var e,t,n,i,s,o,r,a,l,c;null===(e=this.connectionMilestones)||void 0===e||e.record("peer_connection_creating"),this.peerConnection=new RTCPeerConnection(Object.assign(Object.assign({iceCandidatePoolSize:2},this.rtcConfiguration),{iceTransportPolicy:null!==(i=null!==(n=null===(t=this.rtcConfiguration)||void 0===t?void 0:t.iceTransportPolicy)&&void 0!==n?n:this.iceTransportPolicy)&&void 0!==i?i:void 0,iceServers:this.iceServers})),null===(s=this.connectionMilestones)||void 0===s||s.record("peer_connection_created",{iceCandidatePoolSize:2,iceServerCount:this.iceServers.length,iceTransportPolicy:null!==(a=null!==(r=null===(o=this.rtcConfiguration)||void 0===o?void 0:o.iceTransportPolicy)&&void 0!==r?r:this.iceTransportPolicy)&&void 0!==a?a:"all"}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?(null===(l=this.connectionMilestones)||void 0===l||l.record("microphone_permission_skipped",{reason:"input_audio_disabled"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?(null===(c=this.connectionMilestones)||void 0===c||c.record("input_audio_stream_provided",{audioTrackCount:this.inputAudioStream.getAudioTracks().length}),yield this.setupAudioTrack()):this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return i(this,void 0,void 0,function*(){var t,n,i,s;if(this.peerConnection)switch(e.actionType){case r.SignalMessageAction.ANSWER:{null===(t=this.connectionMilestones)||void 0===t||t.record("answer_received");const i=e.payload;if("have-local-offer"!==this.peerConnection.signalingState)break;try{yield this.peerConnection.setRemoteDescription(i)}catch(e){console.error("StreamingClient - setRemoteDescription(answer) failed",e),this.connectionEstablishedEmitted||this.isAwaitingRestartAnswer()||this.handleWebrtcFailure(e);break}null===(n=this.connectionMilestones)||void 0===n||n.record("remote_description_set"),this.connectionReceivedAnswer=!0,this.onAnswerAccepted(),yield this.flushRemoteIceCandidateBuffer();break}case r.SignalMessageAction.ICE_CANDIDATE:{const t=e.payload,n=new RTCIceCandidate(t);this.firstRemoteIceCandidateReceived||(this.firstRemoteIceCandidateReceived=!0,null===(i=this.connectionMilestones)||void 0===i||i.record("first_remote_ice_candidate_received",h(n))),this.connectionReceivedAnswer?yield this.addRemoteIceCandidate(n):this.remoteIceCandidateBuffer.push(n);break}case r.SignalMessageAction.END_SESSION:const o=e.payload;this.sendIceRestartMetric("aborted"),null===(s=this.connectionMilestones)||void 0===s||s.publishFailure({failureStage:"server_closed_connection"}),this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.SERVER_CLOSED_CONNECTION,o),this.shutdown();break;case r.SignalMessageAction.WARNING:const a=e.payload;console.warn("Warning received from server: "+a),this.publicEventEmitter.emit(r.AnamEvent.SERVER_WARNING,a);break;case r.SignalMessageAction.TALK_STREAM_INTERRUPTED:const l=e.payload;this.publicEventEmitter.emit(r.AnamEvent.TALK_STREAM_INTERRUPTED,l.correlationId);break;case r.SignalMessageAction.SESSION_READY:const c=e.sessionId;this.publicEventEmitter.emit(r.AnamEvent.SESSION_READY,c);break;case r.SignalMessageAction.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your @anam-ai/js-sdk version up to date?",e)}else console.error("StreamingClient - onSignalMessage: peerConnection is not initialized")})}onSignallingClientConnected(){return i(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){return i(this,void 0,void 0,function*(){const e=[...this.remoteIceCandidateBuffer];this.remoteIceCandidateBuffer=[];for(const t of e)yield this.addRemoteIceCandidate(t)})}addRemoteIceCandidate(e){return i(this,void 0,void 0,function*(){if(this.peerConnection)try{yield this.peerConnection.addIceCandidate(e),this.recordFirstRemoteIceCandidateApplied(e)}catch(e){console.warn("StreamingClient - addRemoteIceCandidate: failed to add remote ICE candidate",e)}})}recordFirstRemoteIceCandidateApplied(e){var t;this.firstRemoteIceCandidateApplied||(this.firstRemoteIceCandidateApplied=!0,null===(t=this.connectionMilestones)||void 0===t||t.record("first_remote_ice_candidate_applied",h(e)))}onIceCandidate(e){var t,n;if(e.candidate){if(this.firstLocalIceCandidateSent||(this.firstLocalIceCandidateSent=!0,null===(t=this.connectionMilestones)||void 0===t||t.record("first_local_ice_candidate_sent",h(e.candidate))),this.iceRestartCandidateBuffer)return void this.iceRestartCandidateBuffer.push(e.candidate);this.signallingClient.sendIceCandidate(e.candidate)}else null===(n=this.connectionMilestones)||void 0===n||n.record("ice_gathering_complete")}onIceConnectionStateChange(){var e,t,n;const i=null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState;switch(i&&(null===(t=this.connectionMilestones)||void 0===t||t.record("ice_connection_state_changed",{iceConnectionState:i})),i){case"connected":case"completed":this.clearIceDisconnectedGraceTimer(),this.clearIceRestartWatchdog(),this.iceRestartInProgress=!1,this.sendIceRestartMetric("recovered"),this.iceRestartAttempts=0,this.signallingClient.endIceRestartReconnect(),this.connectionEstablishedMilestoneRecorded||(this.connectionEstablishedMilestoneRecorded=!0,null===(n=this.connectionMilestones)||void 0===n||n.record("client_connection_established",{iceConnectionState:i})),this.connectionEstablishedEmitted||(this.connectionEstablishedEmitted=!0,this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_ESTABLISHED)),this.startStatsCollection();break;case"disconnected":this.scheduleIceRestartAfterGrace();break;case"failed":this.clearIceDisconnectedGraceTimer(),this.restartIce()}}clearIceDisconnectedGraceTimer(){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null)}clearIceRestartWatchdog(){this.iceRestartWatchdogTimer&&(clearTimeout(this.iceRestartWatchdogTimer),this.iceRestartWatchdogTimer=null)}sendIceRestartMetric(e){var t;if(null===this.iceRestartEpisodeStartMs)return;const n=Math.round(performance.now()-this.iceRestartEpisodeStartMs),i=null!==(t=this.iceRestartEpisodeTrigger)&&void 0!==t?t:"unknown";this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,(0,s.sendClientMetric)(s.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_ICE_RESTART,n,{outcome:e,attempts:this.iceRestartAttempts,trigger:i})}isAwaitingRestartAnswer(){return this.iceRestartInProgress||this.iceRestartAwaitedAnswer||null!==this.iceRestartWatchdogTimer}onAnswerAccepted(){var e;const t=this.isAwaitingRestartAnswer();if(this.clearIceRestartWatchdog(),this.iceRestartAwaitedAnswer=!1,!t)return;this.iceRestartInProgress=!1;const n=null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState;"disconnected"!==n&&"failed"!==n||this.scheduleIceRestartAfterGrace()}clearPendingWsOpenWait(){this.pendingWsOpenTimeout&&(clearTimeout(this.pendingWsOpenTimeout),this.pendingWsOpenTimeout=null),this.pendingWsOpenListener&&(this.internalEventEmitter.removeListener(r.InternalEvent.WEB_SOCKET_OPEN,this.pendingWsOpenListener),this.pendingWsOpenListener=null),this.pendingWsOpenReject=null}cancelIceRestart(){this.clearIceDisconnectedGraceTimer(),this.clearIceRestartWatchdog();const e=this.pendingWsOpenReject;this.clearPendingWsOpenWait(),e&&e(new Error("ice restart cancelled")),this.iceRestartCandidateBuffer=null,this.iceRestartInProgress=!1,this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,this.signallingClient.endIceRestartReconnect()}flushIceRestartCandidateBuffer(){const e=this.iceRestartCandidateBuffer;if(this.iceRestartCandidateBuffer=null,e)for(const t of e)this.signallingClient.sendIceCandidate(t)}scheduleIceRestartAfterGrace(){this.iceRestartStopped||this.iceRestartInProgress||this.iceDisconnectedGraceTimer||(this.iceDisconnectedGraceTimer=setTimeout(()=>{var e;if(this.iceDisconnectedGraceTimer=null,this.iceRestartStopped)return;const t=null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState;"disconnected"!==t&&"failed"!==t||this.restartIce()},2e3))}ensureSignallingConnected(){return this.signallingClient.isConnected()?Promise.resolve():this.signallingClient.isPermanentlyClosed()?Promise.reject(new Error("signalling permanently closed")):new Promise((e,t)=>{this.pendingWsOpenReject=t,this.pendingWsOpenTimeout=setTimeout(()=>{this.clearPendingWsOpenWait(),t(new Error("timed out waiting for signalling WebSocket"))},5e3);const n=()=>{this.clearPendingWsOpenWait(),e()};this.pendingWsOpenListener=n,this.internalEventEmitter.addListener(r.InternalEvent.WEB_SOCKET_OPEN,n)})}restartIce(){return i(this,void 0,void 0,function*(){var e,t;if(this.peerConnection&&!this.iceRestartInProgress&&!this.iceRestartStopped){if(this.signallingClient.isPermanentlyClosed())return this.sendIceRestartMetric("aborted"),void this.cancelIceRestart();if(this.iceRestartAttempts>=3)return console.error("StreamingClient - restartIce: exhausted attempts"),null===(e=this.connectionMilestones)||void 0===e||e.publishFailure({failureStage:"ice_connection",iceConnectionState:null===(t=this.peerConnection)||void 0===t?void 0:t.iceConnectionState}),this.sendIceRestartMetric("exhausted"),this.cancelIceRestart(),void this.handleWebrtcFailure("The connection to our servers was lost. Please try again.");0===this.iceRestartAttempts&&(this.iceRestartEpisodeStartMs=performance.now(),this.iceRestartEpisodeTrigger=this.peerConnection.iceConnectionState),this.iceRestartInProgress=!0,this.iceRestartAttempts+=1;try{if("stable"!==this.peerConnection.signalingState&&(yield this.peerConnection.setLocalDescription({type:"rollback"})),1===this.iceRestartAttempts&&this.signallingClient.reconnectForIceRestart(),yield this.ensureSignallingConnected(),this.iceRestartStopped)return;const e=this.peerConnection.iceConnectionState;if("connected"===e||"completed"===e)return this.iceRestartInProgress=!1,this.sendIceRestartMetric("recovered"),void this.signallingClient.endIceRestartReconnect();this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[];const t=yield this.peerConnection.createOffer({iceRestart:!0});if(this.iceRestartCandidateBuffer=[],yield this.peerConnection.setLocalDescription(t),!this.peerConnection.localDescription)throw new Error("null local description after ICE restart offer");yield this.signallingClient.sendOffer(this.peerConnection.localDescription),this.flushIceRestartCandidateBuffer(),this.iceRestartAwaitedAnswer=!1,this.clearIceRestartWatchdog(),this.iceRestartWatchdogTimer=setTimeout(()=>this.onIceRestartWatchdog(),u)}catch(e){if(this.iceRestartCandidateBuffer=null,console.error("StreamingClient - restartIce: error",e),this.iceRestartInProgress=!1,this.iceRestartStopped)return void this.cancelIceRestart();if(this.signallingClient.isPermanentlyClosed())return this.sendIceRestartMetric("aborted"),void this.cancelIceRestart();this.clearIceRestartWatchdog(),this.iceRestartWatchdogTimer=setTimeout(()=>{this.iceRestartWatchdogTimer=null,this.restartIce()},u)}}})}onIceRestartWatchdog(){var e;if(this.iceRestartWatchdogTimer=null,this.iceRestartInProgress=!1,this.iceRestartStopped)return;const t=null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState;return"connected"!==t&&"completed"!==t?this.connectionReceivedAnswer||this.iceRestartAwaitedAnswer?void this.restartIce():(this.iceRestartAwaitedAnswer=!0,this.iceRestartInProgress=!0,void(this.iceRestartWatchdogTimer=setTimeout(()=>this.onIceRestartWatchdog(),u))):void 0}onConnectionStateChange(){var e,t,n,i,s;const o=null===(e=this.peerConnection)||void 0===e?void 0:e.connectionState;if(o&&(null===(t=this.connectionMilestones)||void 0===t||t.record("webrtc_connection_state_changed",{connectionState:o})),"failed"===o){const e=null===(n=this.peerConnection)||void 0===n?void 0:n.iceConnectionState;!this.iceRestartStopped&&("disconnected"===e||"failed"===e)||null===(i=this.connectionMilestones)||void 0===i||i.publishFailure({failureStage:"webrtc_connection",connectionState:o})}"closed"===(null===(s=this.peerConnection)||void 0===s?void 0:s.connectionState)&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){var t,n;null===(t=this.connectionMilestones)||void 0===t||t.record("webrtc_failure",E(e)),null===(n=this.connectionMilestones)||void 0===n||n.publishFailure(Object.assign({failureStage:"webrtc"},E(e))),console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),"NotAllowedError"===e.name&&"Permission denied"===e.message?this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.WEBRTC_FAILURE);try{this.stopConnection()}catch(e){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",e)}}onTrackEventHandler(e){var t,n;if("video"===e.track.kind){if(null===(t=this.connectionMilestones)||void 0===t||t.record("video_track_received"),this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(r.AnamEvent.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const e=this.videoElement.requestVideoFrameCallback(()=>{var t;null===(t=this.videoElement)||void 0===t||t.cancelVideoFrameCallback(e),this.publicEventEmitter.emit(r.AnamEvent.VIDEO_PLAY_STARTED),this.recordSessionSuccess("videoElement")})}}else"audio"===e.track.kind&&(null===(n=this.connectionMilestones)||void 0===n||n.record("audio_track_received"),this.audioStream=e.streams[0],this.publicEventEmitter.emit(r.AnamEvent.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return i(this,void 0,void 0,function*(){var e;if(!this.peerConnection)return void console.error("StreamingClient - setupDataChannels: peer connection is not initialized");if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const t=this.peerConnection.createDataChannel("session",{ordered:!0});null===(e=this.connectionMilestones)||void 0===e||e.record("data_channel_created"),t.onopen=()=>{var e;this.dataChannel=null!=t?t:null,null===(e=this.connectionMilestones)||void 0===e||e.record("data_channel_open")},t.onclose=()=>{var e;null===(e=this.connectionMilestones)||void 0===e||e.record("data_channel_closed")},t.onmessage=e=>{var t,n,i,s,o,a,l,d;try{const u=JSON.parse(e.data);switch(u.messageType){case r.DataChannelMessage.SPEECH_TEXT:this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_CHAT_MESSAGE_RECEIVED,u.data);break;case r.DataChannelMessage.CLIENT_TOOL_EVENT:const e=u.data;this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,e);const h=c.ToolCallManager.WebRTCClientToolEventToClientToolEvent(e);this.publicEventEmitter.emit(r.AnamEvent.CLIENT_TOOL_EVENT_RECEIVED,h);break;case r.DataChannelMessage.TOOL_CALL_STARTED_EVENT:const E=u.data;this.publicEventEmitter.emit(r.AnamEvent.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(E)),this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,E);break;case r.DataChannelMessage.TOOL_CALL_COMPLETED_EVENT:const p=u.data;this.publicEventEmitter.emit(r.AnamEvent.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(p)),this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,p);break;case r.DataChannelMessage.TOOL_CALL_FAILED_EVENT:const f=u.data;this.publicEventEmitter.emit(r.AnamEvent.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(f)),this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,f);break;case r.DataChannelMessage.REASONING_TEXT:this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,u.data);break;case r.DataChannelMessage.USER_SPEECH_STARTED:this.publicEventEmitter.emit(r.AnamEvent.USER_SPEECH_STARTED,null!==(n=null===(t=u.data)||void 0===t?void 0:t.user_action_correlation_id)&&void 0!==n?n:"unknown");break;case r.DataChannelMessage.USER_SPEECH_ENDED:this.publicEventEmitter.emit(r.AnamEvent.USER_SPEECH_ENDED,null!==(s=null===(i=u.data)||void 0===i?void 0:i.user_action_correlation_id)&&void 0!==s?s:"unknown");break;case r.DataChannelMessage.DIRECTOR_NOTE_CUE_APPLIED:const g=u.data;this.publicEventEmitter.emit(r.AnamEvent.DIRECTOR_NOTE_CUE_APPLIED,{cueTag:null!==(o=null==g?void 0:g.cue_tag)&&void 0!==o?o:"unknown",correlationId:null!==(a=null==g?void 0:g.user_action_correlation_id)&&void 0!==a?a:"unknown"});break;case r.DataChannelMessage.PERSONA_CONFIG_UPDATE_APPLIED:const m=u.data;this.publicEventEmitter.emit(r.AnamEvent.PERSONA_CONFIG_UPDATE_APPLIED,{consumer:null!==(l=null==m?void 0:m.consumer)&&void 0!==l?l:"unknown",changedFields:null!==(d=null==m?void 0:m.changed_fields)&&void 0!==d?d:{}})}}catch(e){console.error("Failed to parse data channel message:",e)}}})}requestMicrophonePermissionAsync(){return i(this,void 0,void 0,function*(){var e,t,n;if(this.inputAudioState.permissionState!==r.AudioPermissionState.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:r.AudioPermissionState.PENDING}),null===(e=this.connectionMilestones)||void 0===e||e.record("microphone_permission_pending"),this.publicEventEmitter.emit(r.AnamEvent.MIC_PERMISSION_PENDING);try{const 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:r.AudioPermissionState.GRANTED}),null===(t=this.connectionMilestones)||void 0===t||t.record("microphone_permission_granted"),this.publicEventEmitter.emit(r.AnamEvent.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:r.AudioPermissionState.DENIED}),null===(n=this.connectionMilestones)||void 0===n||n.record("microphone_permission_denied",Object.assign({},E(e)));const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(r.AnamEvent.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return i(this,void 0,void 0,function*(){var e;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();const t=this.inputAudioStream.getAudioTracks()[0],n=this.peerConnection.getSenders().find(e=>{var t;return"audio"===(null===(t=e.track)||void 0===t?void 0:t.kind)||null===e.track&&null!==e.dtmf});if(n)try{yield n.replaceTrack(t)}catch(e){console.error("Failed to replace audio track:",e),this.peerConnection.addTrack(t,this.inputAudioStream)}else this.peerConnection.addTrack(t,this.inputAudioStream);null===(e=this.connectionMilestones)||void 0===e||e.record("input_audio_stream_started",{audioTrackCount:this.inputAudioStream.getAudioTracks().length}),this.publicEventEmitter.emit(r.AnamEvent.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return i(this,void 0,void 0,function*(){var e,t,n,i,s,o;if(yield this.initPeerConnection(),this.peerConnection){try{null===(e=this.connectionMilestones)||void 0===e||e.record("offer_creation_started");const i=yield this.peerConnection.createOffer();null===(t=this.connectionMilestones)||void 0===t||t.record("offer_creation_completed"),yield this.peerConnection.setLocalDescription(i),null===(n=this.connectionMilestones)||void 0===n||n.record("local_description_set")}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e),null===(i=this.connectionMilestones)||void 0===i||i.record("offer_creation_failed",Object.assign({},E(e))),null===(s=this.connectionMilestones)||void 0===s||s.publishFailure(Object.assign({failureStage:"offer_creation"},E(e)))}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription),null===(o=this.connectionMilestones)||void 0===o||o.record("offer_sent")}else console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized")})}shutdown(){return i(this,void 0,void 0,function*(){var e;if(this.iceRestartStopped=!0,this.cancelIceRestart(),this.showPeerConnectionStatsReport){const t=yield null===(e=this.peerConnection)||void 0===e?void 0:e.getStats();if(t){const e=(0,s.createRTCStatsReport)(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)}})}};const h=e=>{const t=e;return p({candidateType:t.type,protocol:t.protocol,relayProtocol:t.relayProtocol,tcpType:t.tcpType,component:t.component})},E=e=>{if(e instanceof Error)return p({errorName:e.name});if("object"==typeof e&&null!==e){const t=e;return p({errorName:"string"==typeof t.name?t.name:void 0,errorCode:"string"==typeof t.code||"number"==typeof t.code?t.code:void 0})}return{}},p=e=>{const t={};return Object.entries(e).forEach(([e,n])=>{void 0!==n&&(t[e]=n)}),t}},645:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.InternalEvent=void 0,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"}(n||(t.InternalEvent=n={}))},656:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SignalMessageAction=void 0,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"}(n||(t.SignalMessageAction=n={}))},672:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isCustomPersonaConfig=void 0,t.isCustomPersonaConfig=function(e){return"brainType"in e||"llmId"in e}},676:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DataChannelMessage=void 0,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",e.DIRECTOR_NOTE_CUE_APPLIED="directorNoteCueApplied",e.PERSONA_CONFIG_UPDATE_APPLIED="personaConfigUpdateApplied"}(n||(t.DataChannelMessage=n={}))},711:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.TalkMessageStream=void 0;const s=n(170),o=n(322);t.TalkMessageStream=class{constructor(e,t,n){this.state=o.TalkMessageStreamState.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=n,this.internalEventEmitter.addListener(s.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(s.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return i(this,void 0,void 0,function*(){e.actionType===s.SignalMessageAction.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=o.TalkMessageStreamState.INTERRUPTED,this.onDeactivate())})}endMessage(){return i(this,void 0,void 0,function*(){if(this.state===o.TalkMessageStreamState.ENDED)return void console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");if(this.state!==o.TalkMessageStreamState.STREAMING)return void console.warn("Talk stream is not in an active state: "+this.state);const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=o.TalkMessageStreamState.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return i(this,void 0,void 0,function*(){if(this.state!==o.TalkMessageStreamState.STREAMING&&this.state!==o.TalkMessageStreamState.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const n={content:e,startOfSpeech:this.state===o.TalkMessageStreamState.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?o.TalkMessageStreamState.ENDED:o.TalkMessageStreamState.STREAMING,this.state===o.TalkMessageStreamState.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(n)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===o.TalkMessageStreamState.STREAMING||this.state===o.TalkMessageStreamState.UNSTARTED}getState(){return this.state}}},733:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClientConnectionMilestoneRecorder=t.DEFAULT_SLOW_CONNECTION_THRESHOLD_MS=t.DEFAULT_CONNECTION_MILESTONE_SAMPLE_RATIO=void 0;const i=n(948);t.DEFAULT_CONNECTION_MILESTONE_SAMPLE_RATIO=0,t.DEFAULT_SLOW_CONNECTION_THRESHOLD_MS=5e3,t.ClientConnectionMilestoneRecorder=class{constructor(e={}){var n,i,a,l;this.milestones=[],this.context={sessionId:null,organizationId:null,attemptCorrelationId:null},this.published=!1,this.sessionSuccessful=!1,this.now=null!==(n=e.now)&&void 0!==n?n:s,this.attemptStartedAtMs=this.now(),this.sampleRatio=o(null!==(i=e.connectionMilestoneSampleRatio)&&void 0!==i?i:t.DEFAULT_CONNECTION_MILESTONE_SAMPLE_RATIO),this.slowConnectionThresholdMs=Math.max(0,r(e.slowConnectionThresholdMs,t.DEFAULT_SLOW_CONNECTION_THRESHOLD_MS)),this.sampled=(null!==(a=e.random)&&void 0!==a?a:Math.random)()<this.sampleRatio,this.updateContext(null!==(l=e.context)&&void 0!==l?l:{}),this.record("client_session_attempt")}updateContext(e){this.context=Object.assign(Object.assign({},this.context),e)}record(e,t){if(this.published)return;const n=a(t),i={name:e,elapsedMs:this.elapsedMs(),clientTimestamp:(new Date).toISOString()};Object.keys(n).length>0&&(i.tags=n),this.milestones.push(i)}recordSessionSuccess(e){this.sessionSuccessful||(this.sessionSuccessful=!0,this.record("client_session_success",e),this.publishIfNeeded(),this.finalize())}finalize(){this.published=!0,this.milestones.length=0}publishFailure(e){this.sessionSuccessful||this.published||(this.record("connection_attempt_failed",e),this.publish("failed",e))}publishIfNeeded(){this.published||(this.elapsedMs()>=this.slowConnectionThresholdMs?this.publish("slow"):this.sampled&&this.publish("sampled"))}publish(e,t){if(this.published||0===this.milestones.length)return;this.published=!0;const n=l(Object.assign(Object.assign(Object.assign({},t),this.context),{publishReason:e,attemptDurationMs:this.elapsedMs(),milestoneCount:this.milestones.length,connectionMilestoneSampleRatio:this.sampleRatio,slowConnectionThresholdMs:this.slowConnectionThresholdMs,wasSampled:this.sampled?1:0})),s=[{name:i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONES,value:"1",tags:n},...this.milestones.map((t,n)=>({name:i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONE,value:t.elapsedMs,clientTimestamp:t.clientTimestamp,tags:l(Object.assign(Object.assign(Object.assign({},this.context),{publishReason:e,milestone:t.name,sequence:n}),t.tags))}))];(0,i.sendClientMetrics)(s)}elapsedMs(){return Math.max(0,Math.round(this.now()-this.attemptStartedAtMs))}};const s=()=>"undefined"!=typeof performance?performance.now():Date.now(),o=e=>{const n=r(e,t.DEFAULT_CONNECTION_MILESTONE_SAMPLE_RATIO);return Math.min(1,Math.max(0,n))},r=(e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t,a=e=>{if(!e)return{};const t={};return Object.entries(e).forEach(([e,n])=>{null!=n&&("number"!=typeof n||Number.isFinite(n))&&(t[e]=n)}),t},l=e=>{const t={};return Object.entries(a(e)).forEach(([e,n])=>{t[e]="boolean"==typeof n?String(n):n}),t}},793:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AudioPermissionState=void 0,function(e){e.PENDING="pending",e.GRANTED="granted",e.DENIED="denied",e.NOT_REQUESTED="not_requested"}(n||(t.AudioPermissionState=n={}))},816:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0});const s=n(287),o=n(71),r=n(948),a=n(353),l=n(733),c=n(272),d=n(958),u=n(170),h=n(35);t.default=class{constructor(e,t,n){var i,s,a,l,c;this.inputAudioState={isMuted:!1,permissionState:u.AudioPermissionState.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const E=this.validateClientConfig(e,t,n);if(E)throw new o.ClientError(E,o.ErrorCode.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=n,((null===(i=null==n?void 0:n.api)||void 0===i?void 0:i.baseUrl)||(null===(s=null==n?void 0:n.api)||void 0===s?void 0:s.apiVersion))&&(0,r.setClientMetricsBaseUrl)(n.api.baseUrl||r.DEFAULT_ANAM_METRICS_BASE_URL,n.api.apiVersion||r.DEFAULT_ANAM_API_VERSION),(null===(l=null===(a=null==n?void 0:n.api)||void 0===a?void 0:a.apiGateway)||void 0===l?void 0:l.enabled)&&(0,r.setClientMetricsApiGateway)(n.api.apiGateway),(null===(c=null==n?void 0:n.metrics)||void 0===c?void 0:c.disableClientMetrics)&&(0,r.setClientMetricsDisabled)(!0),this.publicEventEmitter=new d.PublicEventEmitter,this.internalEventEmitter=new d.InternalEventEmitter,this.toolCallManager=new h.ToolCallManager(this.publicEventEmitter,this.internalEventEmitter),this.apiClient=new d.CoreApiRestClient(e,null==n?void 0:n.apiKey,null==n?void 0:n.api),this.messageHistoryClient=new d.MessageHistoryClient(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new d.ReasoningHistoryClient(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],n=s.Buffer.from(t,"base64").toString("utf8");return JSON.parse(n)}catch(e){throw new Error("Invalid session token format")}}validateClientConfig(e,t,n){var i,s;if(!e&&!(null==n?void 0:n.apiKey))return"Either sessionToken or apiKey must be provided";if((null==n?void 0:n.apiKey)&&e)return"Only one of sessionToken or apiKey should be used";const o=(0,c.validateApiGatewayConfig)(null===(i=null==n?void 0:n.api)||void 0===i?void 0:i.apiGateway);if(o)return o;if(e){const n=this.decodeJwt(e);this.organizationId=n.accountId,(0,r.setMetricsContext)({organizationId:this.organizationId});const i=null===(s=n.type)||void 0===s?void 0:s.toLowerCase();if("legacy"===i)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"===i||"stateful"===i)&&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==n?void 0:n.voiceDetection){if(n.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(void 0!==n.voiceDetection.endOfSpeechSensitivity){if("number"!=typeof n.voiceDetection.endOfSpeechSensitivity)return"End of speech sensitivity must be a number";if(n.voiceDetection.endOfSpeechSensitivity<0||n.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if((null===(e=this.clientOptions)||void 0===e?void 0:e.voiceDetection)&&(t.voiceDetection=this.clientOptions.voiceDetection),0!==Object.keys(t).length)return t}startConnectionAttempt(){var e,t,n,i;const s=(0,a.generateCorrelationId)();(0,r.setMetricsContext)({attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId});const o=new l.ClientConnectionMilestoneRecorder({context:{attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId},connectionMilestoneSampleRatio:null===(t=null===(e=this.clientOptions)||void 0===e?void 0:e.metrics)||void 0===t?void 0:t.connectionMilestoneSampleRatio,slowConnectionThresholdMs:null===(i=null===(n=this.clientOptions)||void 0===n?void 0:n.metrics)||void 0===i?void 0:i.slowConnectionThresholdMs});return(0,r.sendClientMetric)(r.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),o}startSession(e,t){return i(this,void 0,void 0,function*(){var n,i,s,a,l,c,u,h,p,f,g,m,C,_,v,S,T;const A=this.personaConfig,I=this.buildStartSessionOptionsForClient();let R;null==t||t.record("start_session_request_started");try{R=yield this.apiClient.startSession(A,I),null==t||t.record("start_session_request_completed")}catch(e){throw null==t||t.record("start_session_request_failed",Object.assign({},E(e))),null==t||t.publishFailure(Object.assign({failureStage:"start_session_request"},E(e))),e}const{sessionId:y,clientConfig:O,engineHost:b,engineProtocol:M,signallingEndpoint:N}=R,{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:D,iceServers:L,iceTransportPolicy:P}=O;this.sessionId=y,this.toolCallManager.setActiveSession(y),(0,r.setMetricsContext)({sessionId:this.sessionId}),null==t||t.updateContext({sessionId:this.sessionId,organizationId:this.organizationId});const U=null!==(l=null!==(i=null===(n=this.clientOptions)||void 0===n?void 0:n.iceServers)&&void 0!==i?i:null===(a=null===(s=this.clientOptions)||void 0===s?void 0:s.rtcConfiguration)||void 0===a?void 0:a.iceServers)&&void 0!==l?l:L;try{this.streamingClient=new d.StreamingClient(y,{engine:{baseUrl:`${M}://${b}`},signalling:{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:D,url:{baseUrl:b,protocol:M,signallingPath:N}},iceServers:U,iceTransportPolicy:P,rtcConfiguration:null===(c=this.clientOptions)||void 0===c?void 0:c.rtcConfiguration,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:(null===(u=this.clientOptions)||void 0===u?void 0:u.disableInputAudio)?void 0:e,audioDeviceId:null===(h=this.clientOptions)||void 0===h?void 0:h.audioDeviceId,disableInputAudio:null===(p=this.clientOptions)||void 0===p?void 0:p.disableInputAudio},apiGateway:null===(g=null===(f=this.clientOptions)||void 0===f?void 0:f.api)||void 0===g?void 0:g.apiGateway,metrics:{showPeerConnectionStatsReport:null!==(_=null===(C=null===(m=this.clientOptions)||void 0===m?void 0:m.metrics)||void 0===C?void 0:C.showPeerConnectionStatsReport)&&void 0!==_&&_,peerConnectionStatsReportOutputFormat:null!==(T=null===(S=null===(v=this.clientOptions)||void 0===v?void 0:v.metrics)||void 0===S?void 0:S.peerConnectionStatsReportOutputFormat)&&void 0!==T?T:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager,t)}catch(e){throw null==t||t.publishFailure(Object.assign({failureStage:"streaming_client_initialization"},E(e))),this.toolCallManager.clearSessionState(),(0,r.setMetricsContext)({sessionId:null}),new o.ClientError("Failed to initialize streaming client",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:y})}return y})}startSessionIfNeeded(e,t){return i(this,void 0,void 0,function*(){if(!(this.sessionId&&this.streamingClient||(yield this.startSession(e,t),this.sessionId&&this.streamingClient)))throw null==t||t.publishFailure({failureStage:"start_session_validation"}),new o.ClientError("Session ID or streaming client is not available after starting session",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return i(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const n=this.startConnectionAttempt();(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)&&e&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(e,n)}catch(e){throw n.publishFailure(Object.assign({failureStage:"start_session"},E(e))),e}return this._isStreaming=!0,new Promise(e=>{var t;const n=[];let i=!1,s=!1;this.publicEventEmitter.addListener(u.AnamEvent.VIDEO_STREAM_STARTED,t=>{n.push(t),i=!0,s&&e(n)}),this.publicEventEmitter.addListener(u.AnamEvent.AUDIO_STREAM_STARTED,t=>{n.push(t),s=!0,i&&e(n)}),null===(t=this.streamingClient)||void 0===t||t.startConnection()})})}streamToVideoAndAudioElements(e,t,n){return i(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,n)})}streamToVideoElement(e,t){return i(this,void 0,void 0,function*(){var n;const i=this.startConnectionAttempt();(null===(n=this.clientOptions)||void 0===n?void 0:n.disableInputAudio)&&t&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t,i)}catch(e){if(i.publishFailure(Object.assign({failureStage:"start_session"},E(e))),e instanceof o.ClientError)throw e;throw new o.ClientError("Failed to start session",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:this.sessionId})}if(this._isStreaming)throw i.publishFailure({failureStage:"already_streaming"}),new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw i.publishFailure({failureStage:"streaming_client_missing"}),new Error("Failed to stream: streaming client is not available");try{this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()}catch(e){throw i.publishFailure(Object.assign({failureStage:"start_connection"},E(e))),e}})}talk(e){return i(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(!this.streamingClient)throw new Error("Failed to send message: session is not started.");this.streamingClient.sendDataMessage(e)}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const n=(new Date).toISOString().replace("Z",""),i=JSON.stringify({content:e,timestamp:n,session_id:t,message_type:"speech"});this.sendDataMessage(i)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:(new Date).toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const n=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(n)}stopStreaming(){return i(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(u.AnamEvent.CONNECTION_CLOSED,u.ConnectionClosedCode.NORMAL),this.toolCallManager.clearSessionState(),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,(0,r.setMetricsContext)({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?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?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?void 0:t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return(null===(e=this.clientOptions)||void 0===e?void 0:e.disableInputAudio)&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return i(this,void 0,void 0,function*(){var t;if(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&""===e.trim())throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,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)}};const E=e=>e instanceof o.ClientError?{errorName:e.name,errorCode:e.code,httpStatusCode:e.statusCode}:e instanceof Error?{errorName:e.name}:{}},822:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageRole=void 0;var i=n(273);Object.defineProperty(t,"MessageRole",{enumerable:!0,get:function(){return i.MessageRole}})},878:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionClosedCode=t.InternalEvent=t.AnamEvent=void 0;var i=n(21);Object.defineProperty(t,"AnamEvent",{enumerable:!0,get:function(){return i.AnamEvent}});var s=n(645);Object.defineProperty(t,"InternalEvent",{enumerable:!0,get:function(){return s.InternalEvent}});var o=n(60);Object.defineProperty(t,"ConnectionClosedCode",{enumerable:!0,get:function(){return o.ConnectionClosedCode}})},948:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.createRTCStatsReport=t.sendClientMetrics=t.sendClientMetric=t.setMetricsContext=t.setClientMetricsDisabled=t.setClientMetricsApiGateway=t.setClientMetricsBaseUrl=t.ClientMetricMeasurement=t.DEFAULT_ANAM_API_VERSION=t.DEFAULT_ANAM_METRICS_BASE_URL=void 0;const s=n(985);var o;t.DEFAULT_ANAM_METRICS_BASE_URL="https://api.anam.ai",t.DEFAULT_ANAM_API_VERSION="/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_CONNECTION_MILESTONE="client_connection_milestone",e.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONES="client_connection_milestones",e.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",e.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success",e.CLIENT_METRIC_MEASUREMENT_ICE_RESTART="client_ice_restart"}(o||(t.ClientMetricMeasurement=o={}));let r,a=t.DEFAULT_ANAM_METRICS_BASE_URL,l=t.DEFAULT_ANAM_API_VERSION,c=!1;t.setClientMetricsBaseUrl=(e,n=t.DEFAULT_ANAM_API_VERSION)=>{a=e,l=n},t.setClientMetricsApiGateway=e=>{r=e},t.setClientMetricsDisabled=e=>{c=e};let d={sessionId:null,organizationId:null,attemptCorrelationId:null};t.setMetricsContext=e=>{d=Object.assign(Object.assign({},d),e)},t.sendClientMetric=(e,n,s)=>i(void 0,void 0,void 0,function*(){yield(0,t.sendClientMetrics)([{name:e,value:n,tags:s}])}),t.sendClientMetrics=e=>i(void 0,void 0,void 0,function*(){if(!c&&0!==e.length)try{const t=`${l}/metrics/client`;let n;const i={"Content-Type":"application/json"};(null==r?void 0:r.enabled)&&(null==r?void 0:r.baseUrl)?(n=`${r.baseUrl}${t}`,i["X-Anam-Target-Url"]=`${a}${t}`):n=`${a}${t}`;const s=e.map(e=>{var t;return Object.assign(Object.assign({},e),{clientTimestamp:null!==(t=e.clientTimestamp)&&void 0!==t?t:(new Date).toISOString(),tags:u(e.tags)})});for(let e=0;e<s.length;e+=50){const t=s.slice(e,e+50),o=1===t.length?t[0]:{metrics:t};yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(o)})}}catch(e){console.error("Failed to send client metric:",e)}});const u=e=>{const t=Object.assign(Object.assign({},s.CLIENT_METADATA),e);return d.sessionId&&void 0===t.sessionId&&(t.sessionId=d.sessionId),d.organizationId&&void 0===t.organizationId&&(t.organizationId=d.organizationId),d.attemptCorrelationId&&void 0===t.attemptCorrelationId&&(t.attemptCorrelationId=d.attemptCorrelationId),t};t.createRTCStatsReport=(e,t="console")=>{var n,i,s;const o={};e.forEach(e=>{o[e.type]||(o[e.type]=[]),o[e.type].push(e)});const r={issues:[]},a=(null===(n=o["inbound-rtp"])||void 0===n?void 0:n.filter(e=>"video"===e.kind))||[];a.length>0&&(r.personaVideoStream=[],a.forEach(e=>{var t,n,i,s,o;const a={framesReceived:null!==(t=e.framesReceived)&&void 0!==t?t:"unknown",framesDropped:null!==(n=e.framesDropped)&&void 0!==n?n:"unknown",framesPerSecond:null!==(i=e.framesPerSecond)&&void 0!==i?i:"unknown",packetsReceived:null!==(s=e.packetsReceived)&&void 0!==s?s:"unknown",packetsLost:null!==(o=e.packetsLost)&&void 0!==o?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)}));const l=(null===(i=o["inbound-rtp"])||void 0===i?void 0:i.filter(e=>"audio"===e.kind))||[];l.length>0&&(r.personaAudioStream=[],l.forEach(e=>{var t,n,i;const s={packetsReceived:null!==(t=e.packetsReceived)&&void 0!==t?t:"unknown",packetsLost:null!==(n=e.packetsLost)&&void 0!==n?n:"unknown",audioLevel:null!==(i=e.audioLevel)&&void 0!==i?i:"unknown",jitter:void 0!==e.jitter?e.jitter:void 0,totalAudioEnergy:void 0!==e.totalAudioEnergy?e.totalAudioEnergy:void 0};r.personaAudioStream.push(s)}));const c=(null===(s=o["outbound-rtp"])||void 0===s?void 0:s.filter(e=>"audio"===e.kind))||[];c.length>0&&(r.userAudioInput=[],c.forEach(e=>{var t,n;const i={packetsSent:null!==(t=e.packetsSent)&&void 0!==t?t:"unknown",retransmittedPackets:null!==(n=e.retransmittedPacketsSent)&&void 0!==n?n:void 0,avgPacketSendDelay:void 0!==e.totalPacketSendDelay?e.totalPacketSendDelay/(e.packetsSent||1)*1e3:void 0};r.userAudioInput.push(i)})),o.codec&&(r.codecs=[],o.codec.forEach(e=>{const 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=>{const t={dtlsState:e.dtlsState||"unknown",iceState:e.iceState||"unknown",bytesSent:e.bytesSent||void 0,bytesReceived:e.bytesReceived||void 0};r.transportLayer.push(t)}));const 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&&d.push(`Audio: High jitter (${(1e3*e.jitter).toFixed(1)}ms)`)}),r.issues=d,"json"===t)return r;console.group("📊 WebRTC Session Statistics Report"),r.personaVideoStream&&r.personaVideoStream.length>0&&(console.group("📹 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("🔊 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("🎤 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("🔧 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("🚚 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()}},958:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasoningHistoryClient=t.StreamingClient=t.PublicEventEmitter=t.MessageHistoryClient=t.InternalEventEmitter=t.EngineApiRestClient=t.CoreApiRestClient=t.SignallingClient=void 0;var i=n(279);Object.defineProperty(t,"SignallingClient",{enumerable:!0,get:function(){return i.SignallingClient}});var s=n(18);Object.defineProperty(t,"CoreApiRestClient",{enumerable:!0,get:function(){return s.CoreApiRestClient}});var o=n(529);Object.defineProperty(t,"EngineApiRestClient",{enumerable:!0,get:function(){return o.EngineApiRestClient}});var r=n(259);Object.defineProperty(t,"InternalEventEmitter",{enumerable:!0,get:function(){return r.InternalEventEmitter}});var a=n(462);Object.defineProperty(t,"MessageHistoryClient",{enumerable:!0,get:function(){return a.MessageHistoryClient}});var l=n(995);Object.defineProperty(t,"PublicEventEmitter",{enumerable:!0,get:function(){return l.PublicEventEmitter}});var c=n(577);Object.defineProperty(t,"StreamingClient",{enumerable:!0,get:function(){return c.StreamingClient}});var d=n(471);Object.defineProperty(t,"ReasoningHistoryClient",{enumerable:!0,get:function(){return d.ReasoningHistoryClient}})},985:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_START_SESSION_REQUEST_TIMEOUT_MS=t.DEFAULT_START_SESSION_MAX_BACKOFF_MS=t.DEFAULT_START_SESSION_INITIAL_BACKOFF_MS=t.DEFAULT_START_SESSION_MAX_ATTEMPTS=t.CLIENT_METADATA=t.DEFAULT_API_VERSION=t.DEFAULT_API_BASE_URL=t.DEFAULT_HEADERS=void 0,t.DEFAULT_HEADERS={"Content-Type":"application/json"},t.DEFAULT_API_BASE_URL="https://api.anam.ai",t.DEFAULT_API_VERSION="/v1",t.CLIENT_METADATA={client:"js-sdk",version:"0.0.0-automated"},t.DEFAULT_START_SESSION_MAX_ATTEMPTS=3,t.DEFAULT_START_SESSION_INITIAL_BACKOFF_MS=250,t.DEFAULT_START_SESSION_MAX_BACKOFF_MS=2e3,t.DEFAULT_START_SESSION_REQUEST_TIMEOUT_MS=1e4},995:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PublicEventEmitter=void 0;const i=n(948),s=n(170);t.PublicEventEmitter=class{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===s.AnamEvent.CONNECTION_ESTABLISHED&&(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===s.AnamEvent.CONNECTION_CLOSED){const[e,n]=t;(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,e,n?{details:n}:void 0)}this.listeners[e]&&this.listeners[e].forEach(e=>{e(...t)})}}}},t={},function n(i){var s=t[i];if(void 0!==s)return s.exports;var o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.exports}(440);var e,t});
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.anam=t():e.anam=t()}(self,()=>{return e={18:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreApiRestClient=void 0;const s=n(71),o=n(985),r=n(672);function a(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function l(e){return!(e instanceof s.ClientError)||e.statusCode>=500&&e.statusCode<600}function c(e){return new Promise(t=>setTimeout(t,e))}t.CoreApiRestClient=class{constructor(e,t,n){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(null==n?void 0:n.baseUrl)||o.DEFAULT_API_BASE_URL,this.apiVersion=(null==n?void 0:n.apiVersion)||o.DEFAULT_API_VERSION,this.apiGatewayConfig=(null==n?void 0:n.apiGateway)||void 0,this.retryOptions=function(e){const t=Math.max(1,Math.floor(a(null==e?void 0:e.maxAttempts,o.DEFAULT_START_SESSION_MAX_ATTEMPTS))),n=Math.max(0,a(null==e?void 0:e.initialBackoffMs,o.DEFAULT_START_SESSION_INITIAL_BACKOFF_MS));return{maxAttempts:t,initialBackoffMs:n,maxBackoffMs:Math.max(n,a(null==e?void 0:e.maxBackoffMs,o.DEFAULT_START_SESSION_MAX_BACKOFF_MS))}}(null==n?void 0:n.retry),this.requestTimeoutMs=Math.max(0,a(null==n?void 0:n.requestTimeoutMs,o.DEFAULT_START_SESSION_REQUEST_TIMEOUT_MS))}buildGatewayUrlAndHeaders(e,t){var n,i;if((null===(n=this.apiGatewayConfig)||void 0===n?void 0:n.enabled)&&(null===(i=this.apiGatewayConfig)||void 0===i?void 0:i.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,i=new URL(`${this.baseUrl}${e}`);return{url:n,headers:Object.assign(Object.assign({},t),{"X-Anam-Target-Url":i.href})}}return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return i(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new s.ClientError("Persona configuration must be provided when using apiKey",s.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");const{maxAttempts:n}=this.retryOptions;let i;for(let s=1;s<=n;s++)try{return yield this.attemptStartSession(e,t)}catch(e){if(i=e,s>=n||!l(e))throw e;yield c(this.computeBackoffDelay(s))}throw i})}attemptStartSession(e,t){return i(this,void 0,void 0,function*(){const n=this.requestTimeoutMs>0?new AbortController:void 0,i=void 0!==n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:a}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),l=yield fetch(r,{method:"POST",headers:a,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:o.CLIENT_METADATA}),signal:null==n?void 0:n.signal}),c=yield l.json(),d=c.error;switch(l.status){case 200:case 201:return c;case 400:throw new s.ClientError("Invalid request to start session",s.ErrorCode.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:c.message});case 401:throw new s.ClientError("Authentication failed when starting session",s.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:c.message});case 402:throw new s.ClientError("Please sign up for a plan to start a session",s.ErrorCode.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:c.message});case 403:throw new s.ClientError("Authentication failed when starting session",s.ErrorCode.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:c.message});case 429:throw"Concurrent session limit reached"===d?new s.ClientError("Concurrency limit reached, please upgrade your plan",s.ErrorCode.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:c.message}):"Spend cap reached"===d?new s.ClientError("Spend cap reached, please upgrade your plan",s.ErrorCode.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:c.message}):new s.ClientError("Usage limit reached, please upgrade your plan",s.ErrorCode.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:c.message});case 503:throw new s.ClientError("There are no available personas, please try again later",s.ErrorCode.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:c.message});default:throw new s.ClientError("Unknown error when starting session",s.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,l.status,{cause:c.message})}}catch(e){if(e instanceof s.ClientError)throw e;throw new s.ClientError("Failed to start session",s.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e)})}finally{void 0!==i&&clearTimeout(i)}})}computeBackoffDelay(e){const{initialBackoffMs:t,maxBackoffMs:n}=this.retryOptions,i=Math.min(n,t*Math.pow(2,e-1));return Math.floor(i/2+Math.random()*(i/2))}unsafe_getSessionToken(e){return i(this,void 0,void 0,function*(){if(console.warn("Using an insecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};(0,r.isCustomPersonaConfig)(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const e=`${this.apiVersion}/auth/session-token`,{url:n,headers:i}=this.buildGatewayUrlAndHeaders(e,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}),s=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(t)});return(yield s.json()).sessionToken}catch(e){throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}},21:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AnamEvent=void 0,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_SPEECH_STARTED",e.USER_SPEECH_ENDED="USER_SPEECH_ENDED",e.DIRECTOR_NOTE_CUE_APPLIED="DIRECTOR_NOTE_CUE_APPLIED",e.PERSONA_CONFIG_UPDATE_APPLIED="PERSONA_CONFIG_UPDATE_APPLIED"}(n||(t.AnamEvent=n={}))},35:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.ToolCallManager=void 0;const s=n(170),o=(e,t)=>{if(isNaN(e)||isNaN(t))return 0;const n=t-e;return n>0?n:0};t.ToolCallManager=class{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 i(this,void 0,void 0,function*(){if(this.activeSessionId!==e.session_id)return;const{tool_name:t,timestamp:n}=e,i=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),s=new Date(n);if(this.pendingCalls[e.tool_call_id]={payload:i,timestamp:s.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let t=yield o.onStart(i);if("client"===e.tool_type)return 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}),void(yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:t,timestamp:(new Date).toISOString()})))}catch(t){const n=t instanceof Error?t.message:String(t);return"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: ${n}`}),void(yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${n}`,timestamp:(new Date).toISOString()})))}})}processToolCallCompletedEvent(e){return i(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:n,timestamp:i}=e;if(this.activeSessionId!==e.session_id)return;if(n in this.failedCalls)return void delete this.failedCalls[n];const o=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(n in this.pendingCalls&&delete this.pendingCalls[n],!(t in this.handlers))return;const r=this.handlers[t];if(r.onComplete){"client"===e.tool_type&&this.publicEventEmitter.emit(s.AnamEvent.TOOL_CALL_COMPLETED,o);try{yield r.onComplete(o)}catch(e){return void console.error(`Error in onComplete handler for tool ${t}:`,e)}}})}processToolCallFailedEvent(e){return i(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:n,timestamp:i}=e;if(this.activeSessionId!==e.session_id)return;const o=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(this.failedCalls[n]=o,n in this.pendingCalls&&delete this.pendingCalls[n],!(t in this.handlers))return;const r=this.handlers[t];if(r.onFail){"client"===e.tool_type&&this.publicEventEmitter.emit(s.AnamEvent.TOOL_CALL_FAILED,o);try{yield r.onFail(o)}catch(e){return void console.error(`Error in onFail handler for tool ${t}:`,e)}}})}sendToolResult(e){const t={sessionId:e.sessionId,toolCallId:e.toolCallId,result:e.result,errorMessage:e.errorMessage,userActionCorrelationId:e.userActionCorrelationId,timestampUserAction:e.timestampUserAction};this.internalEventEmitter.emit(s.InternalEvent.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){const t=new Date(e.timestamp),n=this.pendingCalls[e.tool_call_id],i=n?o(n.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:i>0?i:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),n=this.pendingCalls[e.tool_call_id],i=n?o(n.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:i>0?i:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}},60:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionClosedCode=void 0,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"}(n||(t.ConnectionClosedCode=n={}))},71:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClientError=t.ErrorCode=void 0;const i=n(948);var s;!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"}(s||(t.ErrorCode=s={}));class o extends Error{constructor(e,t,n=500,s){super(e),this.name="ClientError",this.code=t,this.statusCode=n,this.details=s,Object.setPrototypeOf(this,o.prototype),(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:s,statusCode:n})}}t.ClientError=o},170:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentAudioInputStream=t.ConnectionClosedCode=t.InternalEvent=t.AnamEvent=t.MessageRole=t.AudioPermissionState=t.DataChannelMessage=t.SignalMessageAction=void 0;var i=n(295);Object.defineProperty(t,"SignalMessageAction",{enumerable:!0,get:function(){return i.SignalMessageAction}});var s=n(513);Object.defineProperty(t,"DataChannelMessage",{enumerable:!0,get:function(){return s.DataChannelMessage}});var o=n(793);Object.defineProperty(t,"AudioPermissionState",{enumerable:!0,get:function(){return o.AudioPermissionState}});var r=n(822);Object.defineProperty(t,"MessageRole",{enumerable:!0,get:function(){return r.MessageRole}});var a=n(878);Object.defineProperty(t,"AnamEvent",{enumerable:!0,get:function(){return a.AnamEvent}});var l=n(878);Object.defineProperty(t,"InternalEvent",{enumerable:!0,get:function(){return l.InternalEvent}});var c=n(878);Object.defineProperty(t,"ConnectionClosedCode",{enumerable:!0,get:function(){return c.ConnectionClosedCode}});var d=n(421);Object.defineProperty(t,"AgentAudioInputStream",{enumerable:!0,get:function(){return d.AgentAudioInputStream}})},251:(e,t)=>{t.read=function(e,t,n,i,s){var o,r,a=8*s-i-1,l=(1<<a)-1,c=l>>1,d=-7,u=n?s-1:0,h=n?-1:1,E=e[t+u];for(u+=h,o=E&(1<<-d)-1,E>>=-d,d+=a;d>0;o=256*o+e[t+u],u+=h,d-=8);for(r=o&(1<<-d)-1,o>>=-d,d+=i;d>0;r=256*r+e[t+u],u+=h,d-=8);if(0===o)o=1-c;else{if(o===l)return r?NaN:1/0*(E?-1:1);r+=Math.pow(2,i),o-=c}return(E?-1:1)*r*Math.pow(2,o-i)},t.write=function(e,t,n,i,s,o){var r,a,l,c=8*o-s-1,d=(1<<c)-1,u=d>>1,h=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,E=i?0:o-1,p=i?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,r=d):(r=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-r))<1&&(r--,l*=2),(t+=r+u>=1?h/l:h*Math.pow(2,1-u))*l>=2&&(r++,l/=2),r+u>=d?(a=0,r=d):r+u>=1?(a=(t*l-1)*Math.pow(2,s),r+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,s),r=0));s>=8;e[n+E]=255&a,E+=p,a/=256,s-=8);for(r=r<<s|a,c+=s;c>0;e[n+E]=255&r,E+=p,r/=256,c-=8);e[n+E-p]|=128*f}},259:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalEventEmitter=void 0,t.InternalEventEmitter=class{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)})}}},272:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateApiGatewayConfig=void 0,t.validateApiGatewayConfig=function(e){if(e&&e.enabled){if(!e.baseUrl)return"API Gateway baseUrl is required when enabled";try{const 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}`}return e.wsPath&&!e.wsPath.startsWith("/")?"API Gateway wsPath must start with /":void 0}}},273:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MessageRole=void 0,function(e){e.USER="user",e.PERSONA="persona"}(n||(t.MessageRole=n={}))},279:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.SignallingClient=void 0;const s=n(170);t.SignallingClient=class{constructor(e,t,n,i,s,o){var r,a,l,c,d;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.permanentlyClosed=!1,this.iceRestartReconnectInProgress=!1,this.heartBeatIntervalRef=null,this.reconnectTimer=null,this.stableConnectionTimer=null,this.publicEventEmitter=n,this.internalEventEmitter=i,this.apiGatewayConfig=s,this.connectionMilestones=o,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:h,url:E}=t;if(this.heartbeatIntervalSeconds=u||5,this.maxWsReconnectionAttempts=h||5,!E.baseUrl)throw new Error("Signalling Client: baseUrl is required");if((null===(r=this.apiGatewayConfig)||void 0===r?void 0:r.enabled)&&(null===(a=this.apiGatewayConfig)||void 0===a?void 0:a.baseUrl)){const t=new URL(this.apiGatewayConfig.baseUrl),n=null!==(l=this.apiGatewayConfig.wsPath)&&void 0!==l?l:"/ws";t.protocol=t.protocol.replace("http","ws"),t.pathname=n,this.url=t;const i=E.protocol||"https",s="http"===i?"ws":"wss",o=`${i}://${E.baseUrl}`,r=null!==(c=E.signallingPath)&&void 0!==c?c:"/ws",a=new URL(o);a.protocol="ws"===s?"ws:":"wss:",E.port&&(a.port=E.port),a.pathname=r,a.searchParams.append("session_id",e),this.url.searchParams.append("target_url",a.href)}else{const t=`${E.protocol||"https"}://${E.baseUrl}`;this.url=new URL(t),this.url.protocol="http"===E.protocol?"ws:":"wss:",E.port&&(this.url.port=E.port),this.url.pathname=null!==(d=E.signallingPath)&&void 0!==d?d:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){var e;this.clearReconnectTimer(),this.clearStableConnectionTimer(),null===(e=this.connectionMilestones)||void 0===e||e.record("websocket_connecting",{attemptNumber:this.wsConnectionAttempts+1});const t=new WebSocket(this.url.href);return this.socket=t,t.onopen=()=>{this.onOpen(t)},t.onclose=e=>{this.onClose(t,e)},t.onerror=e=>{this.onError(t,e)},t}reconnectForIceRestart(){if(!this.isPermanentlyClosed()){if(this.clearReconnectTimer(),this.socket){this.socket.onopen=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null;try{this.socket.close()}catch(e){console.warn("SignallingClient - reconnectForIceRestart: error closing stale socket",e)}this.socket=null}this.clearHeartbeatInterval(),this.wsConnectionAttempts=0,this.iceRestartReconnectInProgress=!0,this.connect()}}endIceRestartReconnect(){this.iceRestartReconnectInProgress=!1}isConnected(){var e;return(null===(e=this.socket)||void 0===e?void 0:e.readyState)===WebSocket.OPEN}isPermanentlyClosed(){return this.permanentlyClosed||this.stopSignal}sendOffer(e){return i(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},n={actionType:s.SignalMessageAction.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(n)})}sendIceCandidate(e){return i(this,void 0,void 0,function*(){const t={actionType:s.SignalMessageAction.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if((null===(t=this.socket)||void 0===t?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 i(this,void 0,void 0,function*(){const t={actionType:s.SignalMessageAction.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:s.SignalMessageAction.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:s.SignalMessageAction.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.clearReconnectTimer(),this.clearStableConnectionTimer(),this.iceRestartReconnectInProgress=!1,this.socket&&(this.socket.close(),this.socket=null),this.clearHeartbeatInterval()}onOpen(e){return i(this,void 0,void 0,function*(){var t;if(this.socket===e)try{null===(t=this.connectionMilestones)||void 0===t||t.record("websocket_open",{attemptNumber:this.wsConnectionAttempts+1}),this.scheduleStableConnectionReset(e),this.flushSendingBuffer(),e.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(s.InternalEvent.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.permanentlyClosed=!0}})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}clearStableConnectionTimer(){this.stableConnectionTimer&&(clearTimeout(this.stableConnectionTimer),this.stableConnectionTimer=null)}clearHeartbeatInterval(){this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}scheduleStableConnectionReset(e){this.clearStableConnectionTimer(),this.stableConnectionTimer=setTimeout(()=>{this.stableConnectionTimer=null,this.socket===e&&e.readyState===WebSocket.OPEN&&(this.wsConnectionAttempts=0)},5e3)}onClose(e,t){return i(this,void 0,void 0,function*(){var n,i,o;if(this.socket!==e)return;if(this.clearStableConnectionTimer(),this.clearHeartbeatInterval(),null===(n=this.connectionMilestones)||void 0===n||n.record("websocket_closed",{attemptNumber:this.wsConnectionAttempts+1,closeCode:null==t?void 0:t.code,closeReason:null==t?void 0:t.reason,wasClean:null==t?void 0:t.wasClean}),this.wsConnectionAttempts+=1,this.stopSignal)return;const r=this.getMaxReconnectionAttempts(t);if(this.shouldRetryCloseEvent(t)&&this.wsConnectionAttempts<=r){const e=100*this.wsConnectionAttempts;null===(i=this.connectionMilestones)||void 0===i||i.record("websocket_retry_scheduled",{attemptNumber:this.wsConnectionAttempts+1,delayMs:e}),this.socket=null,this.clearReconnectTimer(),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}else this.clearReconnectTimer(),this.clearHeartbeatInterval(),null===(o=this.connectionMilestones)||void 0===o||o.publishFailure({failureStage:"websocket",closeCode:null==t?void 0:t.code,closeReason:null==t?void 0:t.reason}),this.publicEventEmitter.emit(s.AnamEvent.CONNECTION_CLOSED,s.ConnectionClosedCode.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.iceRestartReconnectInProgress=!1,this.permanentlyClosed=!0})}getMaxReconnectionAttempts(e){return!this.iceRestartReconnectInProgress||this.isApiGatewayBackendClose(e)?this.maxWsReconnectionAttempts:Math.max(this.maxWsReconnectionAttempts,24)}shouldRetryCloseEvent(e){return!(this.isApiGatewayBackendClose(e)&&1008===(null==e?void 0:e.code))}isApiGatewayBackendClose(e){var t;return!0===(null===(t=this.apiGatewayConfig)||void 0===t?void 0:t.enabled)&&"string"==typeof(null==e?void 0:e.reason)&&e.reason.startsWith("Backend WebSocket")}onError(e,t){var n;this.stopSignal||this.socket!==e||(null===(n=this.connectionMilestones)||void 0===n||n.record("websocket_error",{eventType:t.type}),console.error("SignallingClient - onError: ",t))}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var n;(null===(n=this.socket)||void 0===n?void 0:n.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return i(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(s.InternalEvent.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=1e3*this.heartbeatIntervalSeconds,t={actionType:s.SignalMessageAction.HEARTBEAT,sessionId:this.sessionId,payload:""},n=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var e;this.stopSignal||(null===(e=this.socket)||void 0===e?void 0:e.readyState)===WebSocket.OPEN&&this.socket.send(n)},e)}}},287:(e,t,n)=>{"use strict";const i=n(526),s=n(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=function(e){return+e!=e&&(e=0),l.alloc(+e)},t.INSPECT_MAX_BYTES=50;const r=2147483647;function a(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|f(e,t);let i=a(n);const s=i.write(e,t);return s!==n&&(i=i.slice(0,s)),i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Y(e,Uint8Array)){const t=new Uint8Array(e);return E(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Y(e,ArrayBuffer)||e&&Y(e.buffer,ArrayBuffer))return E(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(Y(e,SharedArrayBuffer)||e&&Y(e.buffer,SharedArrayBuffer)))return E(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return l.from(i,t,n);const s=function(e){if(l.isBuffer(e)){const t=0|p(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||X(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function d(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return d(e),a(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),n=a(t);for(let i=0;i<t;i+=1)n[i]=255&e[i];return n}function E(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(i,l.prototype),i}function p(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Y(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;let s=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return K(e).length;default:if(s)return i?-1:z(e).length;t=(""+t).toLowerCase(),s=!0}}function g(e,t,n){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return y(this,t,n);case"ascii":return b(this,t,n);case"latin1":case"binary":return M(this,t,n);case"base64":return R(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function m(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function C(e,t,n,i,s){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),X(n=+n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=l.from(t,i)),l.isBuffer(t))return 0===t.length?-1:_(e,t,n,i,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):_(e,[t],n,i,s);throw new TypeError("val must be string, number or Buffer")}function _(e,t,n,i,s){let o,r=1,a=e.length,l=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;r=2,a/=2,l/=2,n/=2}function c(e,t){return 1===r?e[t]:e.readUInt16BE(t*r)}if(s){let i=-1;for(o=n;o<a;o++)if(c(e,o)===c(t,-1===i?0:o-i)){if(-1===i&&(i=o),o-i+1===l)return i*r}else-1!==i&&(o-=o-i),i=-1}else for(n+l>a&&(n=a-l),o=n;o>=0;o--){let n=!0;for(let i=0;i<l;i++)if(c(e,o+i)!==c(t,i)){n=!1;break}if(n)return o}return-1}function v(e,t,n,i){n=Number(n)||0;const s=e.length-n;i?(i=Number(i))>s&&(i=s):i=s;const o=t.length;let r;for(i>o/2&&(i=o/2),r=0;r<i;++r){const i=parseInt(t.substr(2*r,2),16);if(X(i))return r;e[n+r]=i}return r}function S(e,t,n,i){return q(z(t,e.length-n),e,n,i)}function T(e,t,n,i){return q(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,i)}function A(e,t,n,i){return q(K(t),e,n,i)}function I(e,t,n,i){return q(function(e,t){let n,i,s;const o=[];for(let r=0;r<e.length&&!((t-=2)<0);++r)n=e.charCodeAt(r),i=n>>8,s=n%256,o.push(s),o.push(i);return o}(t,e.length-n),e,n,i)}function R(e,t,n){return 0===t&&n===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,n))}function y(e,t,n){n=Math.min(e.length,n);const i=[];let s=t;for(;s<n;){const t=e[s];let o=null,r=t>239?4:t>223?3:t>191?2:1;if(s+r<=n){let n,i,a,l;switch(r){case 1:t<128&&(o=t);break;case 2:n=e[s+1],128==(192&n)&&(l=(31&t)<<6|63&n,l>127&&(o=l));break;case 3:n=e[s+1],i=e[s+2],128==(192&n)&&128==(192&i)&&(l=(15&t)<<12|(63&n)<<6|63&i,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:n=e[s+1],i=e[s+2],a=e[s+3],128==(192&n)&&128==(192&i)&&128==(192&a)&&(l=(15&t)<<18|(63&n)<<12|(63&i)<<6|63&a,l>65535&&l<1114112&&(o=l))}}null===o?(o=65533,r=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),s+=r}return function(e){const t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);let n="",i=0;for(;i<t;)n+=String.fromCharCode.apply(String,e.slice(i,i+=O));return n}(i)}t.kMaxLength=r,l.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,n){return function(e,t,n){return d(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}(e,t,n)},l.allocUnsafe=function(e){return u(e)},l.allocUnsafeSlow=function(e){return u(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(Y(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),Y(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.length;for(let s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==t[s]){n=e[s],i=t[s];break}return n<i?-1:i<n?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const i=l.allocUnsafe(t);let s=0;for(n=0;n<e.length;++n){let t=e[n];if(Y(t,Uint8Array))s+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,s)):Uint8Array.prototype.set.call(i,t,s);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,s)}s+=t.length}return i},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)m(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)m(this,t,t+3),m(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)m(this,t,t+7),m(this,t+1,t+6),m(this,t+2,t+5),m(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?y(this,0,e):g.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let e="";const n=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(e,t,n,i,s){if(Y(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),t<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=n)return 0;if(i>=s)return-1;if(t>=n)return 1;if(this===e)return 0;let o=(s>>>=0)-(i>>>=0),r=(n>>>=0)-(t>>>=0);const a=Math.min(o,r),c=this.slice(i,s),d=e.slice(t,n);for(let e=0;e<a;++e)if(c[e]!==d[e]){o=c[e],r=d[e];break}return o<r?-1:r<o?1:0},l.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},l.prototype.indexOf=function(e,t,n){return C(this,e,t,n,!0)},l.prototype.lastIndexOf=function(e,t,n){return C(this,e,t,n,!1)},l.prototype.write=function(e,t,n,i){if(void 0===t)i="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)i=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}const s=this.length-t;if((void 0===n||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return v(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":case"latin1":case"binary":return T(this,e,t,n);case"base64":return A(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const O=4096;function b(e,t,n){let i="";n=Math.min(e.length,n);for(let s=t;s<n;++s)i+=String.fromCharCode(127&e[s]);return i}function M(e,t,n){let i="";n=Math.min(e.length,n);for(let s=t;s<n;++s)i+=String.fromCharCode(e[s]);return i}function N(e,t,n){const i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);let s="";for(let i=t;i<n;++i)s+=J[e[i]];return s}function w(e,t,n){const i=e.slice(t,n);let s="";for(let e=0;e<i.length-1;e+=2)s+=String.fromCharCode(i[e]+256*i[e+1]);return s}function D(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function L(e,t,n,i,s,o){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<o)throw new RangeError('"value" argument is out of bounds');if(n+i>e.length)throw new RangeError("Index out of range")}function P(e,t,n,i,s){W(t,i,s,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let r=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=r,r>>=8,e[n++]=r,r>>=8,e[n++]=r,r>>=8,e[n++]=r,n}function U(e,t,n,i,s){W(t,i,s,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let r=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=r,r>>=8,e[n+2]=r,r>>=8,e[n+1]=r,r>>=8,e[n]=r,n+8}function k(e,t,n,i,s,o){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function B(e,t,n,i,o){return t=+t,n>>>=0,o||k(e,0,n,4),s.write(e,t,n,i,23,4),n+4}function F(e,t,n,i,o){return t=+t,n>>>=0,o||k(e,0,n,8),s.write(e,t,n,i,52,8),n+8}l.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,l.prototype),i},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e],s=1,o=0;for(;++o<t&&(s*=256);)i+=this[e+o]*s;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e+--t],s=1;for(;t>0&&(s*=256);)i+=this[e+--t]*s;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,s=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(i)+(BigInt(s)<<BigInt(32))}),l.prototype.readBigUInt64BE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],s=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(i)<<BigInt(32))+BigInt(s)}),l.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=this[e],s=1,o=0;for(;++o<t&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);let i=t,s=1,o=this[e+--i];for(;i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*t)),o},l.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),l.prototype.readBigInt64BE=Q(function(e){x(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||$(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),s.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),s.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),s.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),s.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||L(this,e,t,n,Math.pow(2,8*n)-1,0);let s=1,o=0;for(this[t]=255&e;++o<n&&(s*=256);)this[t+o]=e/s&255;return t+n},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||L(this,e,t,n,Math.pow(2,8*n)-1,0);let s=n-1,o=1;for(this[t+s]=255&e;--s>=0&&(o*=256);)this[t+s]=e/o&255;return t+n},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);L(this,e,t,n,i-1,-i)}let s=0,o=1,r=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===r&&0!==this[t+s-1]&&(r=1),this[t+s]=(e/o|0)-r&255;return t+n},l.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);L(this,e,t,n,i-1,-i)}let s=n-1,o=1,r=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===r&&0!==this[t+s+1]&&(r=1),this[t+s]=(e/o|0)-r&255;return t+n},l.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||L(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,n){return B(this,e,t,!0,n)},l.prototype.writeFloatBE=function(e,t,n){return B(this,e,t,!1,n)},l.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},l.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},l.prototype.copy=function(e,t,n,i){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);const s=i-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),t),s},l.prototype.fill=function(e,t,n,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{const o=l.isBuffer(e)?e:l.from(e,i),r=o.length;if(0===r)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=o[s%r]}return this};const j={};function G(e,t,n){j[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function V(e){let t="",n=e.length;const i="-"===e[0]?1:0;for(;n>=i+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function W(e,t,n,i,s,o){if(e>n||e<t){const i="bigint"==typeof t?"n":"";let s;throw s=o>3?0===t||t===BigInt(0)?`>= 0${i} and < 2${i} ** ${8*(o+1)}${i}`:`>= -(2${i} ** ${8*(o+1)-1}${i}) and < 2 ** ${8*(o+1)-1}${i}`:`>= ${t}${i} and <= ${n}${i}`,new j.ERR_OUT_OF_RANGE("value",s,e)}!function(e,t,n){x(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||$(t,e.length-(n+1))}(i,s,o)}function x(e,t){if("number"!=typeof e)throw new j.ERR_INVALID_ARG_TYPE(t,"number",e)}function $(e,t,n){if(Math.floor(e)!==e)throw x(e,n),new j.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}G("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),G("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),G("ERR_OUT_OF_RANGE",function(e,t,n){let i=`The value of "${e}" is out of range.`,s=n;return Number.isInteger(n)&&Math.abs(n)>2**32?s=V(String(n)):"bigint"==typeof n&&(s=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(s=V(s)),s+="n"),i+=` It must be ${t}. Received ${s}`,i},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function z(e,t){let n;t=t||1/0;const i=e.length;let s=null;const o=[];for(let r=0;r<i;++r){if(n=e.charCodeAt(r),n>55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(r+1===i){(t-=3)>-1&&o.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&o.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function K(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,n,i){let s;for(s=0;s<i&&!(s+n>=t.length||s>=e.length);++s)t[s+n]=e[s];return s}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}const J=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const i=16*n;for(let s=0;s<16;++s)t[i+s]=e[n]+e[s]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},295:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignalMessageAction=void 0;var i=n(656);Object.defineProperty(t,"SignalMessageAction",{enumerable:!0,get:function(){return i.SignalMessageAction}})},322:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TalkMessageStreamState=void 0,function(e){e[e.UNSTARTED=0]="UNSTARTED",e[e.STREAMING=1]="STREAMING",e[e.INTERRUPTED=2]="INTERRUPTED",e[e.ENDED=3]="ENDED"}(n||(t.TalkMessageStreamState=n={}))},353:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateCorrelationId=void 0,t.generateCorrelationId=function(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}},421:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentAudioInputStream=void 0,t.AgentAudioInputStream=class{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const 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){const t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array.from(t,e=>String.fromCharCode(e)).join("");return btoa(n)}}},440:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorCode=t.ClientError=t.unsafe_createClientWithApiKey=t.createClient=void 0;const r=o(n(816)),a=n(71);Object.defineProperty(t,"ClientError",{enumerable:!0,get:function(){return a.ClientError}}),Object.defineProperty(t,"ErrorCode",{enumerable:!0,get:function(){return a.ErrorCode}}),t.createClient=(e,t)=>new r.default(e,void 0,t),t.unsafe_createClientWithApiKey=(e,t,n)=>new r.default(void 0,t,Object.assign(Object.assign({},n),{apiKey:e})),s(n(170),t)},462:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHistoryClient=void 0;const i=n(170);t.MessageHistoryClient=class{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(i.InternalEvent.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return Object.assign({id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted},e.cue_tag?{cueTag:e.cue_tag}:{})}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},n=this.messages.findIndex(e=>e.id===t.id);if(-1!==n){const e=this.messages[n];this.messages[n]=Object.assign(Object.assign({},e),{content:e.content+t.content,interrupted:e.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(i.AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case i.MessageRole.USER:this.processUserMessage(t);break;case i.MessageRole.PERSONA:this.processPersonaMessage(t)}t.endOfSpeech&&this.publicEventEmitter.emit(i.AnamEvent.MESSAGE_HISTORY_UPDATED,this.messages)}}},471:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasoningHistoryClient=void 0;const i=n(170);t.ReasoningHistoryClient=class{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(i.InternalEvent.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(i.AnamEvent.REASONING_STREAM_EVENT_RECEIVED,t);const n={id:t.id,content:t.content,role:t.role},s=this.reasoning_messages.findIndex(e=>e.id===n.id);if(-1!==s){const e=this.reasoning_messages[s];e.content+=n.content,this.reasoning_messages[s]=e}else this.reasoning_messages.push(n);t.endOfThought&&this.publicEventEmitter.emit(i.AnamEvent.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}},513:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebRtcReasoningTextMessageEvent=t.DataChannelMessage=void 0;var i=n(676);Object.defineProperty(t,"DataChannelMessage",{enumerable:!0,get:function(){return i.DataChannelMessage}});var s=n(540);Object.defineProperty(t,"WebRtcReasoningTextMessageEvent",{enumerable:!0,get:function(){return s.WebRtcReasoningTextMessageEvent}})},526:(e,t)=>{"use strict";t.byteLength=function(e){var t=a(e),n=t[0],i=t[1];return 3*(n+i)/4-i},t.toByteArray=function(e){var t,n,o=a(e),r=o[0],l=o[1],c=new s(function(e,t,n){return 3*(t+n)/4-n}(0,r,l)),d=0,u=l>0?r-4:r;for(n=0;n<u;n+=4)t=i[e.charCodeAt(n)]<<18|i[e.charCodeAt(n+1)]<<12|i[e.charCodeAt(n+2)]<<6|i[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===l&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===l&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c},t.fromByteArray=function(e){for(var t,i=e.length,s=i%3,o=[],r=16383,a=0,l=i-s;a<l;a+=r)o.push(c(e,a,a+r>l?l:a+r));return 1===s?(t=e[i-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===s&&(t=(e[i-2]<<8)+e[i-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),o.join("")};for(var n=[],i=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0;r<64;++r)n[r]=o[r],i[o.charCodeAt(r)]=r;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function c(e,t,n){for(var i,s=[],o=t;o<n;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),s.push(l(i));return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},529:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.EngineApiRestClient=void 0,t.EngineApiRestClient=class{constructor(e,t,n){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=n}sendTalkCommand(e){return n(this,void 0,void 0,function*(){var t,n;try{let i,s={"Content-Type":"application/json"};const o="/talk",r=`?session_id=${this.sessionId}`;if((null===(t=this.apiGatewayConfig)||void 0===t?void 0:t.enabled)&&(null===(n=this.apiGatewayConfig)||void 0===n?void 0:n.baseUrl)){i=`${this.apiGatewayConfig.baseUrl}${o}${r}`;const e=new URL(`${this.baseUrl}${o}${r}`);s["X-Anam-Target-Url"]=e.href}else i=`${this.baseUrl}${o}${r}`;const a=yield fetch(i,{method:"POST",headers:s,body:JSON.stringify({content:e})});if(!a.ok)throw new Error(`Failed to send talk command: ${a.status} ${a.statusText}`)}catch(e){throw console.error(e),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}},540:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},577:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.StreamingClient=void 0;const s=n(948),o=n(958),r=n(170),a=n(421),l=n(711),c=n(35),d=15e3,u=3e3;t.StreamingClient=class{constructor(e,t,n,i,s,a){var l,c,d,u;this.peerConnection=null,this.connectionEstablishedEmitted=!1,this.iceRestartInProgress=!1,this.iceRestartAttempts=0,this.iceRestartAwaitedAnswer=!1,this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,this.iceRestartStopped=!1,this.iceDisconnectedGraceTimer=null,this.iceRestartWatchdogTimer=null,this.pendingWsOpenListener=null,this.pendingWsOpenTimeout=null,this.pendingWsOpenReject=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.iceRestartCandidateBuffer=null,this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:r.AudioPermissionState.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.firstLocalIceCandidateSent=!1,this.firstRemoteIceCandidateReceived=!1,this.firstRemoteIceCandidateApplied=!1,this.connectionEstablishedMilestoneRecorded=!1,this.publicEventEmitter=n,this.internalEventEmitter=i,this.toolCallManager=s,this.connectionMilestones=a,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=!0===t.inputAudio.disableInputAudio,this.internalEventEmitter.addListener(r.InternalEvent.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(r.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(r.InternalEvent.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(r.InternalEvent.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(r.InternalEvent.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(r.InternalEvent.TOOL_CALL_RESULT_READY,this.onToolCallResultReceived.bind(this)),this.iceServers=t.iceServers,this.iceTransportPolicy=t.iceTransportPolicy,this.rtcConfiguration=t.rtcConfiguration,this.signallingClient=new o.SignallingClient(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig,this.connectionMilestones),this.engineApiRestClient=new o.EngineApiRestClient(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=null!==(c=null===(l=t.metrics)||void 0===l?void 0:l.showPeerConnectionStatsReport)&&void 0!==c&&c,this.peerConnectionStatsReportOutputFormat=null!==(u=null===(d=t.metrics)||void 0===d?void 0:d.peerConnectionStatsReportOutputFormat)&&void 0!==u?u:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;null===(e=this.inputAudioStream)||void 0===e||e.getAudioTracks().forEach(e=>{e.enabled=!1})}unmuteAllAudioTracks(){var e;null===(e=this.inputAudioStream)||void 0===e||e.getAudioTracks().forEach(e=>{e.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>i(this,void 0,void 0,function*(){if(this.peerConnection&&this.dataChannel&&"open"===this.dataChannel.readyState)try{const 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=>{if("inbound-rtp"===e.type){const t={message_type:"remote_rtp_stats",data:e};this.dataChannel&&"open"===this.dataChannel.readyState&&this.dataChannel.send(JSON.stringify(t))}})}recordSessionSuccess(e){var t,n;this.successMetricFired||(this.successMetricFired=!0,null===(t=this.connectionMilestones)||void 0===t||t.record("first_video_frame",{detectionMethod:e}),null===(n=this.connectionMilestones)||void 0===n||n.recordSessionSuccess({detectionMethod:e}),(0,s.sendClientMetric)(s.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:e}))}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{var e,t;this.successMetricPoller&&(null===(e=this.connectionMilestones)||void 0===e||e.record("first_video_frame_timeout",{timeoutMs:d}),null===(t=this.connectionMilestones)||void 0===t||t.publishFailure({failureStage:"first_video_frame",timeoutMs:d}),console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},d);this.successMetricPoller=setInterval(()=>i(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired)return this.successMetricPoller&&clearInterval(this.successMetricPoller),void clearTimeout(e);try{const t=yield this.peerConnection.getStats();let n=!1,i=null;t.forEach(e=>{"inbound-rtp"===e.type&&"video"===e.kind&&(void 0!==e.framesDecoded&&e.framesDecoded>0?(n=!0,i="framesDecoded"):void 0!==e.framesReceived&&e.framesReceived>0?(n=!0,i="framesReceived"):e.bytesReceived>0&&e.packetsReceived>0&&e.bytesReceived>1e5&&(n=!0,i="bytesReceived"))}),n&&!this.successMetricFired&&(this.recordSessionSuccess(null!=i?i:"unknown"),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch(e){}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const 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 i(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(null==e)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(e=>{e.stop()});const n={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:n}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(r.AnamEvent.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(e){throw console.error("Failed to change audio input device:",e),new Error(`StreamingClient - changeAudioInputDevice: ${e instanceof Error?e.message:String(e)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}onToolCallResultReceived(e){const 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){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){var e;try{if(this.peerConnection)return void console.error("StreamingClient - startConnection: peer connection already exists");this.resetAttemptScopedMilestoneState(),null===(e=this.connectionMilestones)||void 0===e||e.record("connection_start_requested"),this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}resetAttemptScopedMilestoneState(){this.firstLocalIceCandidateSent=!1,this.firstRemoteIceCandidateReceived=!1,this.firstRemoteIceCandidateApplied=!1,this.connectionEstablishedMilestoneRecorded=!1}stopConnection(){return i(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return i(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new l.TalkMessageStream(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new a.AgentAudioInputStream(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return i(this,void 0,void 0,function*(){var e,t,n,i,s,o,r,a,l,c;null===(e=this.connectionMilestones)||void 0===e||e.record("peer_connection_creating"),this.peerConnection=new RTCPeerConnection(Object.assign(Object.assign({iceCandidatePoolSize:2},this.rtcConfiguration),{iceTransportPolicy:null!==(i=null!==(n=null===(t=this.rtcConfiguration)||void 0===t?void 0:t.iceTransportPolicy)&&void 0!==n?n:this.iceTransportPolicy)&&void 0!==i?i:void 0,iceServers:this.iceServers})),null===(s=this.connectionMilestones)||void 0===s||s.record("peer_connection_created",{iceCandidatePoolSize:2,iceServerCount:this.iceServers.length,iceTransportPolicy:null!==(a=null!==(r=null===(o=this.rtcConfiguration)||void 0===o?void 0:o.iceTransportPolicy)&&void 0!==r?r:this.iceTransportPolicy)&&void 0!==a?a:"all"}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?(null===(l=this.connectionMilestones)||void 0===l||l.record("microphone_permission_skipped",{reason:"input_audio_disabled"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?(null===(c=this.connectionMilestones)||void 0===c||c.record("input_audio_stream_provided",{audioTrackCount:this.inputAudioStream.getAudioTracks().length}),yield this.setupAudioTrack()):this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return i(this,void 0,void 0,function*(){var t,n,i,s;if(this.peerConnection)switch(e.actionType){case r.SignalMessageAction.ANSWER:{null===(t=this.connectionMilestones)||void 0===t||t.record("answer_received");const i=e.payload;if("have-local-offer"!==this.peerConnection.signalingState)break;try{yield this.peerConnection.setRemoteDescription(i)}catch(e){console.error("StreamingClient - setRemoteDescription(answer) failed",e),this.connectionEstablishedEmitted||this.isAwaitingRestartAnswer()||this.handleWebrtcFailure(e);break}null===(n=this.connectionMilestones)||void 0===n||n.record("remote_description_set"),this.connectionReceivedAnswer=!0,this.onAnswerAccepted(),yield this.flushRemoteIceCandidateBuffer();break}case r.SignalMessageAction.ICE_CANDIDATE:{const t=e.payload,n=new RTCIceCandidate(t);this.firstRemoteIceCandidateReceived||(this.firstRemoteIceCandidateReceived=!0,null===(i=this.connectionMilestones)||void 0===i||i.record("first_remote_ice_candidate_received",h(n))),this.connectionReceivedAnswer?yield this.addRemoteIceCandidate(n):this.remoteIceCandidateBuffer.push(n);break}case r.SignalMessageAction.END_SESSION:const o=e.payload;this.sendIceRestartMetric("aborted"),null===(s=this.connectionMilestones)||void 0===s||s.publishFailure({failureStage:"server_closed_connection"}),this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.SERVER_CLOSED_CONNECTION,o),this.shutdown();break;case r.SignalMessageAction.WARNING:const a=e.payload;console.warn("Warning received from server: "+a),this.publicEventEmitter.emit(r.AnamEvent.SERVER_WARNING,a);break;case r.SignalMessageAction.TALK_STREAM_INTERRUPTED:const l=e.payload;this.publicEventEmitter.emit(r.AnamEvent.TALK_STREAM_INTERRUPTED,l.correlationId);break;case r.SignalMessageAction.SESSION_READY:const c=e.sessionId;this.publicEventEmitter.emit(r.AnamEvent.SESSION_READY,c);break;case r.SignalMessageAction.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your @anam-ai/js-sdk version up to date?",e)}else console.error("StreamingClient - onSignalMessage: peerConnection is not initialized")})}onSignallingClientConnected(){return i(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){return i(this,void 0,void 0,function*(){const e=[...this.remoteIceCandidateBuffer];this.remoteIceCandidateBuffer=[];for(const t of e)yield this.addRemoteIceCandidate(t)})}addRemoteIceCandidate(e){return i(this,void 0,void 0,function*(){if(this.peerConnection)try{yield this.peerConnection.addIceCandidate(e),this.recordFirstRemoteIceCandidateApplied(e)}catch(e){console.warn("StreamingClient - addRemoteIceCandidate: failed to add remote ICE candidate",e)}})}recordFirstRemoteIceCandidateApplied(e){var t;this.firstRemoteIceCandidateApplied||(this.firstRemoteIceCandidateApplied=!0,null===(t=this.connectionMilestones)||void 0===t||t.record("first_remote_ice_candidate_applied",h(e)))}onIceCandidate(e){var t,n;if(e.candidate){if(this.firstLocalIceCandidateSent||(this.firstLocalIceCandidateSent=!0,null===(t=this.connectionMilestones)||void 0===t||t.record("first_local_ice_candidate_sent",h(e.candidate))),this.iceRestartCandidateBuffer)return void this.iceRestartCandidateBuffer.push(e.candidate);this.signallingClient.sendIceCandidate(e.candidate)}else null===(n=this.connectionMilestones)||void 0===n||n.record("ice_gathering_complete")}onIceConnectionStateChange(){var e,t,n;const i=null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState;switch(i&&(null===(t=this.connectionMilestones)||void 0===t||t.record("ice_connection_state_changed",{iceConnectionState:i})),i){case"connected":case"completed":this.clearIceDisconnectedGraceTimer(),this.clearIceRestartWatchdog(),this.iceRestartInProgress=!1,this.sendIceRestartMetric("recovered"),this.iceRestartAttempts=0,this.signallingClient.endIceRestartReconnect(),this.connectionEstablishedMilestoneRecorded||(this.connectionEstablishedMilestoneRecorded=!0,null===(n=this.connectionMilestones)||void 0===n||n.record("client_connection_established",{iceConnectionState:i})),this.connectionEstablishedEmitted||(this.connectionEstablishedEmitted=!0,this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_ESTABLISHED)),this.startStatsCollection();break;case"disconnected":this.scheduleIceRestartAfterGrace();break;case"failed":this.clearIceDisconnectedGraceTimer(),this.restartIce()}}clearIceDisconnectedGraceTimer(){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null)}clearIceRestartWatchdog(){this.iceRestartWatchdogTimer&&(clearTimeout(this.iceRestartWatchdogTimer),this.iceRestartWatchdogTimer=null)}sendIceRestartMetric(e){var t;if(null===this.iceRestartEpisodeStartMs)return;const n=Math.round(performance.now()-this.iceRestartEpisodeStartMs),i=null!==(t=this.iceRestartEpisodeTrigger)&&void 0!==t?t:"unknown";this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,(0,s.sendClientMetric)(s.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_ICE_RESTART,n,{outcome:e,attempts:this.iceRestartAttempts,trigger:i})}isAwaitingRestartAnswer(){return this.iceRestartInProgress||this.iceRestartAwaitedAnswer||null!==this.iceRestartWatchdogTimer}onAnswerAccepted(){var e;const t=this.isAwaitingRestartAnswer();if(this.clearIceRestartWatchdog(),this.iceRestartAwaitedAnswer=!1,!t)return;this.iceRestartInProgress=!1;const n=null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState;"disconnected"!==n&&"failed"!==n||this.scheduleIceRestartAfterGrace()}clearPendingWsOpenWait(){this.pendingWsOpenTimeout&&(clearTimeout(this.pendingWsOpenTimeout),this.pendingWsOpenTimeout=null),this.pendingWsOpenListener&&(this.internalEventEmitter.removeListener(r.InternalEvent.WEB_SOCKET_OPEN,this.pendingWsOpenListener),this.pendingWsOpenListener=null),this.pendingWsOpenReject=null}cancelIceRestart(){this.clearIceDisconnectedGraceTimer(),this.clearIceRestartWatchdog();const e=this.pendingWsOpenReject;this.clearPendingWsOpenWait(),e&&e(new Error("ice restart cancelled")),this.iceRestartCandidateBuffer=null,this.iceRestartInProgress=!1,this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,this.signallingClient.endIceRestartReconnect()}flushIceRestartCandidateBuffer(){const e=this.iceRestartCandidateBuffer;if(this.iceRestartCandidateBuffer=null,e)for(const t of e)this.signallingClient.sendIceCandidate(t)}scheduleIceRestartAfterGrace(){this.iceRestartStopped||this.iceRestartInProgress||this.iceDisconnectedGraceTimer||(this.iceDisconnectedGraceTimer=setTimeout(()=>{var e;if(this.iceDisconnectedGraceTimer=null,this.iceRestartStopped)return;const t=null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState;"disconnected"!==t&&"failed"!==t||this.restartIce()},2e3))}ensureSignallingConnected(){return this.signallingClient.isConnected()?Promise.resolve():this.signallingClient.isPermanentlyClosed()?Promise.reject(new Error("signalling permanently closed")):new Promise((e,t)=>{this.pendingWsOpenReject=t,this.pendingWsOpenTimeout=setTimeout(()=>{this.clearPendingWsOpenWait(),t(new Error("timed out waiting for signalling WebSocket"))},5e3);const n=()=>{this.clearPendingWsOpenWait(),e()};this.pendingWsOpenListener=n,this.internalEventEmitter.addListener(r.InternalEvent.WEB_SOCKET_OPEN,n)})}restartIce(){return i(this,void 0,void 0,function*(){var e,t;if(this.peerConnection&&!this.iceRestartInProgress&&!this.iceRestartStopped){if(this.signallingClient.isPermanentlyClosed())return this.sendIceRestartMetric("aborted"),void this.cancelIceRestart();if(this.iceRestartAttempts>=3)return console.error("StreamingClient - restartIce: exhausted attempts"),null===(e=this.connectionMilestones)||void 0===e||e.publishFailure({failureStage:"ice_connection",iceConnectionState:null===(t=this.peerConnection)||void 0===t?void 0:t.iceConnectionState}),this.sendIceRestartMetric("exhausted"),this.cancelIceRestart(),void this.handleWebrtcFailure("The connection to our servers was lost. Please try again.");0===this.iceRestartAttempts&&(this.iceRestartEpisodeStartMs=performance.now(),this.iceRestartEpisodeTrigger=this.peerConnection.iceConnectionState),this.iceRestartInProgress=!0,this.iceRestartAttempts+=1;try{if("stable"!==this.peerConnection.signalingState&&(yield this.peerConnection.setLocalDescription({type:"rollback"})),1===this.iceRestartAttempts&&this.signallingClient.reconnectForIceRestart(),yield this.ensureSignallingConnected(),this.iceRestartStopped)return;const e=this.peerConnection.iceConnectionState;if("connected"===e||"completed"===e)return this.iceRestartInProgress=!1,this.sendIceRestartMetric("recovered"),void this.signallingClient.endIceRestartReconnect();this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[];const t=yield this.peerConnection.createOffer({iceRestart:!0});if(this.iceRestartCandidateBuffer=[],yield this.peerConnection.setLocalDescription(t),!this.peerConnection.localDescription)throw new Error("null local description after ICE restart offer");yield this.signallingClient.sendOffer(this.peerConnection.localDescription),this.flushIceRestartCandidateBuffer(),this.iceRestartAwaitedAnswer=!1,this.clearIceRestartWatchdog(),this.iceRestartWatchdogTimer=setTimeout(()=>this.onIceRestartWatchdog(),u)}catch(e){if(this.iceRestartCandidateBuffer=null,console.error("StreamingClient - restartIce: error",e),this.iceRestartInProgress=!1,this.iceRestartStopped)return void this.cancelIceRestart();if(this.signallingClient.isPermanentlyClosed())return this.sendIceRestartMetric("aborted"),void this.cancelIceRestart();this.clearIceRestartWatchdog(),this.iceRestartWatchdogTimer=setTimeout(()=>{this.iceRestartWatchdogTimer=null,this.restartIce()},u)}}})}onIceRestartWatchdog(){var e;if(this.iceRestartWatchdogTimer=null,this.iceRestartInProgress=!1,this.iceRestartStopped)return;const t=null===(e=this.peerConnection)||void 0===e?void 0:e.iceConnectionState;return"connected"!==t&&"completed"!==t?this.connectionReceivedAnswer||this.iceRestartAwaitedAnswer?void this.restartIce():(this.iceRestartAwaitedAnswer=!0,this.iceRestartInProgress=!0,void(this.iceRestartWatchdogTimer=setTimeout(()=>this.onIceRestartWatchdog(),u))):void 0}onConnectionStateChange(){var e,t,n,i,s;const o=null===(e=this.peerConnection)||void 0===e?void 0:e.connectionState;if(o&&(null===(t=this.connectionMilestones)||void 0===t||t.record("webrtc_connection_state_changed",{connectionState:o})),"failed"===o){const e=null===(n=this.peerConnection)||void 0===n?void 0:n.iceConnectionState;!this.iceRestartStopped&&("disconnected"===e||"failed"===e)||null===(i=this.connectionMilestones)||void 0===i||i.publishFailure({failureStage:"webrtc_connection",connectionState:o})}"closed"===(null===(s=this.peerConnection)||void 0===s?void 0:s.connectionState)&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){var t,n;null===(t=this.connectionMilestones)||void 0===t||t.record("webrtc_failure",E(e)),null===(n=this.connectionMilestones)||void 0===n||n.publishFailure(Object.assign({failureStage:"webrtc"},E(e))),console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),"NotAllowedError"===e.name&&"Permission denied"===e.message?this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(r.AnamEvent.CONNECTION_CLOSED,r.ConnectionClosedCode.WEBRTC_FAILURE);try{this.stopConnection()}catch(e){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",e)}}onTrackEventHandler(e){var t,n;if("video"===e.track.kind){if(null===(t=this.connectionMilestones)||void 0===t||t.record("video_track_received"),this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(r.AnamEvent.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const e=this.videoElement.requestVideoFrameCallback(()=>{var t;null===(t=this.videoElement)||void 0===t||t.cancelVideoFrameCallback(e),this.publicEventEmitter.emit(r.AnamEvent.VIDEO_PLAY_STARTED),this.recordSessionSuccess("videoElement")})}}else"audio"===e.track.kind&&(null===(n=this.connectionMilestones)||void 0===n||n.record("audio_track_received"),this.audioStream=e.streams[0],this.publicEventEmitter.emit(r.AnamEvent.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return i(this,void 0,void 0,function*(){var e;if(!this.peerConnection)return void console.error("StreamingClient - setupDataChannels: peer connection is not initialized");if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const t=this.peerConnection.createDataChannel("session",{ordered:!0});null===(e=this.connectionMilestones)||void 0===e||e.record("data_channel_created"),t.onopen=()=>{var e;this.dataChannel=null!=t?t:null,null===(e=this.connectionMilestones)||void 0===e||e.record("data_channel_open")},t.onclose=()=>{var e;null===(e=this.connectionMilestones)||void 0===e||e.record("data_channel_closed")},t.onmessage=e=>{var t,n,i,s,o,a,l;try{const d=JSON.parse(e.data);switch(d.messageType){case r.DataChannelMessage.SPEECH_TEXT:this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_CHAT_MESSAGE_RECEIVED,d.data);break;case r.DataChannelMessage.CLIENT_TOOL_EVENT:const e=d.data;this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,e);const u=c.ToolCallManager.WebRTCClientToolEventToClientToolEvent(e);this.publicEventEmitter.emit(r.AnamEvent.CLIENT_TOOL_EVENT_RECEIVED,u);break;case r.DataChannelMessage.TOOL_CALL_STARTED_EVENT:const h=d.data;this.publicEventEmitter.emit(r.AnamEvent.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(h)),this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,h);break;case r.DataChannelMessage.TOOL_CALL_COMPLETED_EVENT:const E=d.data;this.publicEventEmitter.emit(r.AnamEvent.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(E)),this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,E);break;case r.DataChannelMessage.TOOL_CALL_FAILED_EVENT:const p=d.data;this.publicEventEmitter.emit(r.AnamEvent.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(p)),this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,p);break;case r.DataChannelMessage.REASONING_TEXT:this.internalEventEmitter.emit(r.InternalEvent.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,d.data);break;case r.DataChannelMessage.USER_SPEECH_STARTED:this.publicEventEmitter.emit(r.AnamEvent.USER_SPEECH_STARTED,null!==(n=null===(t=d.data)||void 0===t?void 0:t.user_action_correlation_id)&&void 0!==n?n:"unknown");break;case r.DataChannelMessage.USER_SPEECH_ENDED:this.publicEventEmitter.emit(r.AnamEvent.USER_SPEECH_ENDED,null!==(s=null===(i=d.data)||void 0===i?void 0:i.user_action_correlation_id)&&void 0!==s?s:"unknown");break;case r.DataChannelMessage.DIRECTOR_NOTE_CUE_APPLIED:const f=d.data;this.publicEventEmitter.emit(r.AnamEvent.DIRECTOR_NOTE_CUE_APPLIED,{cueTag:null!==(o=null==f?void 0:f.cue_tag)&&void 0!==o?o:"unknown",correlationId:null!==(a=null==f?void 0:f.user_action_correlation_id)&&void 0!==a?a:"unknown"});break;case r.DataChannelMessage.PERSONA_CONFIG_UPDATE_APPLIED:const g=d.data;this.publicEventEmitter.emit(r.AnamEvent.PERSONA_CONFIG_UPDATE_APPLIED,{changedFields:null!==(l=null==g?void 0:g.changed_fields)&&void 0!==l?l:{}})}}catch(e){console.error("Failed to parse data channel message:",e)}}})}requestMicrophonePermissionAsync(){return i(this,void 0,void 0,function*(){var e,t,n;if(this.inputAudioState.permissionState!==r.AudioPermissionState.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:r.AudioPermissionState.PENDING}),null===(e=this.connectionMilestones)||void 0===e||e.record("microphone_permission_pending"),this.publicEventEmitter.emit(r.AnamEvent.MIC_PERMISSION_PENDING);try{const 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:r.AudioPermissionState.GRANTED}),null===(t=this.connectionMilestones)||void 0===t||t.record("microphone_permission_granted"),this.publicEventEmitter.emit(r.AnamEvent.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:r.AudioPermissionState.DENIED}),null===(n=this.connectionMilestones)||void 0===n||n.record("microphone_permission_denied",Object.assign({},E(e)));const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(r.AnamEvent.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return i(this,void 0,void 0,function*(){var e;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();const t=this.inputAudioStream.getAudioTracks()[0],n=this.peerConnection.getSenders().find(e=>{var t;return"audio"===(null===(t=e.track)||void 0===t?void 0:t.kind)||null===e.track&&null!==e.dtmf});if(n)try{yield n.replaceTrack(t)}catch(e){console.error("Failed to replace audio track:",e),this.peerConnection.addTrack(t,this.inputAudioStream)}else this.peerConnection.addTrack(t,this.inputAudioStream);null===(e=this.connectionMilestones)||void 0===e||e.record("input_audio_stream_started",{audioTrackCount:this.inputAudioStream.getAudioTracks().length}),this.publicEventEmitter.emit(r.AnamEvent.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return i(this,void 0,void 0,function*(){var e,t,n,i,s,o;if(yield this.initPeerConnection(),this.peerConnection){try{null===(e=this.connectionMilestones)||void 0===e||e.record("offer_creation_started");const i=yield this.peerConnection.createOffer();null===(t=this.connectionMilestones)||void 0===t||t.record("offer_creation_completed"),yield this.peerConnection.setLocalDescription(i),null===(n=this.connectionMilestones)||void 0===n||n.record("local_description_set")}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e),null===(i=this.connectionMilestones)||void 0===i||i.record("offer_creation_failed",Object.assign({},E(e))),null===(s=this.connectionMilestones)||void 0===s||s.publishFailure(Object.assign({failureStage:"offer_creation"},E(e)))}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription),null===(o=this.connectionMilestones)||void 0===o||o.record("offer_sent")}else console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized")})}shutdown(){return i(this,void 0,void 0,function*(){var e;if(this.iceRestartStopped=!0,this.cancelIceRestart(),this.showPeerConnectionStatsReport){const t=yield null===(e=this.peerConnection)||void 0===e?void 0:e.getStats();if(t){const e=(0,s.createRTCStatsReport)(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)}})}};const h=e=>{const t=e;return p({candidateType:t.type,protocol:t.protocol,relayProtocol:t.relayProtocol,tcpType:t.tcpType,component:t.component})},E=e=>{if(e instanceof Error)return p({errorName:e.name});if("object"==typeof e&&null!==e){const t=e;return p({errorName:"string"==typeof t.name?t.name:void 0,errorCode:"string"==typeof t.code||"number"==typeof t.code?t.code:void 0})}return{}},p=e=>{const t={};return Object.entries(e).forEach(([e,n])=>{void 0!==n&&(t[e]=n)}),t}},645:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.InternalEvent=void 0,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"}(n||(t.InternalEvent=n={}))},656:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SignalMessageAction=void 0,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"}(n||(t.SignalMessageAction=n={}))},672:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isCustomPersonaConfig=void 0,t.isCustomPersonaConfig=function(e){return"brainType"in e||"llmId"in e}},676:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DataChannelMessage=void 0,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",e.DIRECTOR_NOTE_CUE_APPLIED="directorNoteCueApplied",e.PERSONA_CONFIG_UPDATE_APPLIED="personaConfigUpdateApplied"}(n||(t.DataChannelMessage=n={}))},711:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.TalkMessageStream=void 0;const s=n(170),o=n(322);t.TalkMessageStream=class{constructor(e,t,n){this.state=o.TalkMessageStreamState.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=n,this.internalEventEmitter.addListener(s.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(s.InternalEvent.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return i(this,void 0,void 0,function*(){e.actionType===s.SignalMessageAction.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=o.TalkMessageStreamState.INTERRUPTED,this.onDeactivate())})}endMessage(){return i(this,void 0,void 0,function*(){if(this.state===o.TalkMessageStreamState.ENDED)return void console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");if(this.state!==o.TalkMessageStreamState.STREAMING)return void console.warn("Talk stream is not in an active state: "+this.state);const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=o.TalkMessageStreamState.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return i(this,void 0,void 0,function*(){if(this.state!==o.TalkMessageStreamState.STREAMING&&this.state!==o.TalkMessageStreamState.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const n={content:e,startOfSpeech:this.state===o.TalkMessageStreamState.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?o.TalkMessageStreamState.ENDED:o.TalkMessageStreamState.STREAMING,this.state===o.TalkMessageStreamState.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(n)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===o.TalkMessageStreamState.STREAMING||this.state===o.TalkMessageStreamState.UNSTARTED}getState(){return this.state}}},733:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClientConnectionMilestoneRecorder=t.DEFAULT_SLOW_CONNECTION_THRESHOLD_MS=t.DEFAULT_CONNECTION_MILESTONE_SAMPLE_RATIO=void 0;const i=n(948);t.DEFAULT_CONNECTION_MILESTONE_SAMPLE_RATIO=0,t.DEFAULT_SLOW_CONNECTION_THRESHOLD_MS=5e3,t.ClientConnectionMilestoneRecorder=class{constructor(e={}){var n,i,a,l;this.milestones=[],this.context={sessionId:null,organizationId:null,attemptCorrelationId:null},this.published=!1,this.sessionSuccessful=!1,this.now=null!==(n=e.now)&&void 0!==n?n:s,this.attemptStartedAtMs=this.now(),this.sampleRatio=o(null!==(i=e.connectionMilestoneSampleRatio)&&void 0!==i?i:t.DEFAULT_CONNECTION_MILESTONE_SAMPLE_RATIO),this.slowConnectionThresholdMs=Math.max(0,r(e.slowConnectionThresholdMs,t.DEFAULT_SLOW_CONNECTION_THRESHOLD_MS)),this.sampled=(null!==(a=e.random)&&void 0!==a?a:Math.random)()<this.sampleRatio,this.updateContext(null!==(l=e.context)&&void 0!==l?l:{}),this.record("client_session_attempt")}updateContext(e){this.context=Object.assign(Object.assign({},this.context),e)}record(e,t){if(this.published)return;const n=a(t),i={name:e,elapsedMs:this.elapsedMs(),clientTimestamp:(new Date).toISOString()};Object.keys(n).length>0&&(i.tags=n),this.milestones.push(i)}recordSessionSuccess(e){this.sessionSuccessful||(this.sessionSuccessful=!0,this.record("client_session_success",e),this.publishIfNeeded(),this.finalize())}finalize(){this.published=!0,this.milestones.length=0}publishFailure(e){this.sessionSuccessful||this.published||(this.record("connection_attempt_failed",e),this.publish("failed",e))}publishIfNeeded(){this.published||(this.elapsedMs()>=this.slowConnectionThresholdMs?this.publish("slow"):this.sampled&&this.publish("sampled"))}publish(e,t){if(this.published||0===this.milestones.length)return;this.published=!0;const n=l(Object.assign(Object.assign(Object.assign({},t),this.context),{publishReason:e,attemptDurationMs:this.elapsedMs(),milestoneCount:this.milestones.length,connectionMilestoneSampleRatio:this.sampleRatio,slowConnectionThresholdMs:this.slowConnectionThresholdMs,wasSampled:this.sampled?1:0})),s=[{name:i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONES,value:"1",tags:n},...this.milestones.map((t,n)=>({name:i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONE,value:t.elapsedMs,clientTimestamp:t.clientTimestamp,tags:l(Object.assign(Object.assign(Object.assign({},this.context),{publishReason:e,milestone:t.name,sequence:n}),t.tags))}))];(0,i.sendClientMetrics)(s)}elapsedMs(){return Math.max(0,Math.round(this.now()-this.attemptStartedAtMs))}};const s=()=>"undefined"!=typeof performance?performance.now():Date.now(),o=e=>{const n=r(e,t.DEFAULT_CONNECTION_MILESTONE_SAMPLE_RATIO);return Math.min(1,Math.max(0,n))},r=(e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t,a=e=>{if(!e)return{};const t={};return Object.entries(e).forEach(([e,n])=>{null!=n&&("number"!=typeof n||Number.isFinite(n))&&(t[e]=n)}),t},l=e=>{const t={};return Object.entries(a(e)).forEach(([e,n])=>{t[e]="boolean"==typeof n?String(n):n}),t}},793:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AudioPermissionState=void 0,function(e){e.PENDING="pending",e.GRANTED="granted",e.DENIED="denied",e.NOT_REQUESTED="not_requested"}(n||(t.AudioPermissionState=n={}))},816:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0});const s=n(287),o=n(71),r=n(948),a=n(353),l=n(733),c=n(272),d=n(958),u=n(170),h=n(35);t.default=class{constructor(e,t,n){var i,s,a,l,c;this.inputAudioState={isMuted:!1,permissionState:u.AudioPermissionState.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const E=this.validateClientConfig(e,t,n);if(E)throw new o.ClientError(E,o.ErrorCode.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=n,((null===(i=null==n?void 0:n.api)||void 0===i?void 0:i.baseUrl)||(null===(s=null==n?void 0:n.api)||void 0===s?void 0:s.apiVersion))&&(0,r.setClientMetricsBaseUrl)(n.api.baseUrl||r.DEFAULT_ANAM_METRICS_BASE_URL,n.api.apiVersion||r.DEFAULT_ANAM_API_VERSION),(null===(l=null===(a=null==n?void 0:n.api)||void 0===a?void 0:a.apiGateway)||void 0===l?void 0:l.enabled)&&(0,r.setClientMetricsApiGateway)(n.api.apiGateway),(null===(c=null==n?void 0:n.metrics)||void 0===c?void 0:c.disableClientMetrics)&&(0,r.setClientMetricsDisabled)(!0),this.publicEventEmitter=new d.PublicEventEmitter,this.internalEventEmitter=new d.InternalEventEmitter,this.toolCallManager=new h.ToolCallManager(this.publicEventEmitter,this.internalEventEmitter),this.apiClient=new d.CoreApiRestClient(e,null==n?void 0:n.apiKey,null==n?void 0:n.api),this.messageHistoryClient=new d.MessageHistoryClient(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new d.ReasoningHistoryClient(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],n=s.Buffer.from(t,"base64").toString("utf8");return JSON.parse(n)}catch(e){throw new Error("Invalid session token format")}}validateClientConfig(e,t,n){var i,s;if(!e&&!(null==n?void 0:n.apiKey))return"Either sessionToken or apiKey must be provided";if((null==n?void 0:n.apiKey)&&e)return"Only one of sessionToken or apiKey should be used";const o=(0,c.validateApiGatewayConfig)(null===(i=null==n?void 0:n.api)||void 0===i?void 0:i.apiGateway);if(o)return o;if(e){const n=this.decodeJwt(e);this.organizationId=n.accountId,(0,r.setMetricsContext)({organizationId:this.organizationId});const i=null===(s=n.type)||void 0===s?void 0:s.toLowerCase();if("legacy"===i)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"===i||"stateful"===i)&&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==n?void 0:n.voiceDetection){if(n.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(void 0!==n.voiceDetection.endOfSpeechSensitivity){if("number"!=typeof n.voiceDetection.endOfSpeechSensitivity)return"End of speech sensitivity must be a number";if(n.voiceDetection.endOfSpeechSensitivity<0||n.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if((null===(e=this.clientOptions)||void 0===e?void 0:e.voiceDetection)&&(t.voiceDetection=this.clientOptions.voiceDetection),0!==Object.keys(t).length)return t}startConnectionAttempt(){var e,t,n,i;const s=(0,a.generateCorrelationId)();(0,r.setMetricsContext)({attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId});const o=new l.ClientConnectionMilestoneRecorder({context:{attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId},connectionMilestoneSampleRatio:null===(t=null===(e=this.clientOptions)||void 0===e?void 0:e.metrics)||void 0===t?void 0:t.connectionMilestoneSampleRatio,slowConnectionThresholdMs:null===(i=null===(n=this.clientOptions)||void 0===n?void 0:n.metrics)||void 0===i?void 0:i.slowConnectionThresholdMs});return(0,r.sendClientMetric)(r.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),o}startSession(e,t){return i(this,void 0,void 0,function*(){var n,i,s,a,l,c,u,h,p,f,g,m,C,_,v,S,T;const A=this.personaConfig,I=this.buildStartSessionOptionsForClient();let R;null==t||t.record("start_session_request_started");try{R=yield this.apiClient.startSession(A,I),null==t||t.record("start_session_request_completed")}catch(e){throw null==t||t.record("start_session_request_failed",Object.assign({},E(e))),null==t||t.publishFailure(Object.assign({failureStage:"start_session_request"},E(e))),e}const{sessionId:y,clientConfig:O,engineHost:b,engineProtocol:M,signallingEndpoint:N}=R,{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:D,iceServers:L,iceTransportPolicy:P}=O;this.sessionId=y,this.toolCallManager.setActiveSession(y),(0,r.setMetricsContext)({sessionId:this.sessionId}),null==t||t.updateContext({sessionId:this.sessionId,organizationId:this.organizationId});const U=null!==(l=null!==(i=null===(n=this.clientOptions)||void 0===n?void 0:n.iceServers)&&void 0!==i?i:null===(a=null===(s=this.clientOptions)||void 0===s?void 0:s.rtcConfiguration)||void 0===a?void 0:a.iceServers)&&void 0!==l?l:L;try{this.streamingClient=new d.StreamingClient(y,{engine:{baseUrl:`${M}://${b}`},signalling:{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:D,url:{baseUrl:b,protocol:M,signallingPath:N}},iceServers:U,iceTransportPolicy:P,rtcConfiguration:null===(c=this.clientOptions)||void 0===c?void 0:c.rtcConfiguration,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:(null===(u=this.clientOptions)||void 0===u?void 0:u.disableInputAudio)?void 0:e,audioDeviceId:null===(h=this.clientOptions)||void 0===h?void 0:h.audioDeviceId,disableInputAudio:null===(p=this.clientOptions)||void 0===p?void 0:p.disableInputAudio},apiGateway:null===(g=null===(f=this.clientOptions)||void 0===f?void 0:f.api)||void 0===g?void 0:g.apiGateway,metrics:{showPeerConnectionStatsReport:null!==(_=null===(C=null===(m=this.clientOptions)||void 0===m?void 0:m.metrics)||void 0===C?void 0:C.showPeerConnectionStatsReport)&&void 0!==_&&_,peerConnectionStatsReportOutputFormat:null!==(T=null===(S=null===(v=this.clientOptions)||void 0===v?void 0:v.metrics)||void 0===S?void 0:S.peerConnectionStatsReportOutputFormat)&&void 0!==T?T:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager,t)}catch(e){throw null==t||t.publishFailure(Object.assign({failureStage:"streaming_client_initialization"},E(e))),this.toolCallManager.clearSessionState(),(0,r.setMetricsContext)({sessionId:null}),new o.ClientError("Failed to initialize streaming client",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:y})}return y})}startSessionIfNeeded(e,t){return i(this,void 0,void 0,function*(){if(!(this.sessionId&&this.streamingClient||(yield this.startSession(e,t),this.sessionId&&this.streamingClient)))throw null==t||t.publishFailure({failureStage:"start_session_validation"}),new o.ClientError("Session ID or streaming client is not available after starting session",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return i(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const n=this.startConnectionAttempt();(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)&&e&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(e,n)}catch(e){throw n.publishFailure(Object.assign({failureStage:"start_session"},E(e))),e}return this._isStreaming=!0,new Promise(e=>{var t;const n=[];let i=!1,s=!1;this.publicEventEmitter.addListener(u.AnamEvent.VIDEO_STREAM_STARTED,t=>{n.push(t),i=!0,s&&e(n)}),this.publicEventEmitter.addListener(u.AnamEvent.AUDIO_STREAM_STARTED,t=>{n.push(t),s=!0,i&&e(n)}),null===(t=this.streamingClient)||void 0===t||t.startConnection()})})}streamToVideoAndAudioElements(e,t,n){return i(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,n)})}streamToVideoElement(e,t){return i(this,void 0,void 0,function*(){var n;const i=this.startConnectionAttempt();(null===(n=this.clientOptions)||void 0===n?void 0:n.disableInputAudio)&&t&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t,i)}catch(e){if(i.publishFailure(Object.assign({failureStage:"start_session"},E(e))),e instanceof o.ClientError)throw e;throw new o.ClientError("Failed to start session",o.ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:e instanceof Error?e.message:String(e),sessionId:this.sessionId})}if(this._isStreaming)throw i.publishFailure({failureStage:"already_streaming"}),new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw i.publishFailure({failureStage:"streaming_client_missing"}),new Error("Failed to stream: streaming client is not available");try{this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()}catch(e){throw i.publishFailure(Object.assign({failureStage:"start_connection"},E(e))),e}})}talk(e){return i(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(!this.streamingClient)throw new Error("Failed to send message: session is not started.");this.streamingClient.sendDataMessage(e)}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const n=(new Date).toISOString().replace("Z",""),i=JSON.stringify({content:e,timestamp:n,session_id:t,message_type:"speech"});this.sendDataMessage(i)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:(new Date).toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const n=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(n)}stopStreaming(){return i(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(u.AnamEvent.CONNECTION_CLOSED,u.ConnectionClosedCode.NORMAL),this.toolCallManager.clearSessionState(),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,(0,r.setMetricsContext)({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?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?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?void 0:t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return(null===(e=this.clientOptions)||void 0===e?void 0:e.disableInputAudio)&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return i(this,void 0,void 0,function*(){var t;if(null===(t=this.clientOptions)||void 0===t?void 0:t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&""===e.trim())throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,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)}};const E=e=>e instanceof o.ClientError?{errorName:e.name,errorCode:e.code,httpStatusCode:e.statusCode}:e instanceof Error?{errorName:e.name}:{}},822:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageRole=void 0;var i=n(273);Object.defineProperty(t,"MessageRole",{enumerable:!0,get:function(){return i.MessageRole}})},878:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionClosedCode=t.InternalEvent=t.AnamEvent=void 0;var i=n(21);Object.defineProperty(t,"AnamEvent",{enumerable:!0,get:function(){return i.AnamEvent}});var s=n(645);Object.defineProperty(t,"InternalEvent",{enumerable:!0,get:function(){return s.InternalEvent}});var o=n(60);Object.defineProperty(t,"ConnectionClosedCode",{enumerable:!0,get:function(){return o.ConnectionClosedCode}})},948:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(e){try{l(i.next(e))}catch(e){o(e)}}function a(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.createRTCStatsReport=t.sendClientMetrics=t.sendClientMetric=t.setMetricsContext=t.setClientMetricsDisabled=t.setClientMetricsApiGateway=t.setClientMetricsBaseUrl=t.ClientMetricMeasurement=t.DEFAULT_ANAM_API_VERSION=t.DEFAULT_ANAM_METRICS_BASE_URL=void 0;const s=n(985);var o;t.DEFAULT_ANAM_METRICS_BASE_URL="https://api.anam.ai",t.DEFAULT_ANAM_API_VERSION="/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_CONNECTION_MILESTONE="client_connection_milestone",e.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONES="client_connection_milestones",e.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",e.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success",e.CLIENT_METRIC_MEASUREMENT_ICE_RESTART="client_ice_restart"}(o||(t.ClientMetricMeasurement=o={}));let r,a=t.DEFAULT_ANAM_METRICS_BASE_URL,l=t.DEFAULT_ANAM_API_VERSION,c=!1;t.setClientMetricsBaseUrl=(e,n=t.DEFAULT_ANAM_API_VERSION)=>{a=e,l=n},t.setClientMetricsApiGateway=e=>{r=e},t.setClientMetricsDisabled=e=>{c=e};let d={sessionId:null,organizationId:null,attemptCorrelationId:null};t.setMetricsContext=e=>{d=Object.assign(Object.assign({},d),e)},t.sendClientMetric=(e,n,s)=>i(void 0,void 0,void 0,function*(){yield(0,t.sendClientMetrics)([{name:e,value:n,tags:s}])}),t.sendClientMetrics=e=>i(void 0,void 0,void 0,function*(){if(!c&&0!==e.length)try{const t=`${l}/metrics/client`;let n;const i={"Content-Type":"application/json"};(null==r?void 0:r.enabled)&&(null==r?void 0:r.baseUrl)?(n=`${r.baseUrl}${t}`,i["X-Anam-Target-Url"]=`${a}${t}`):n=`${a}${t}`;const s=e.map(e=>{var t;return Object.assign(Object.assign({},e),{clientTimestamp:null!==(t=e.clientTimestamp)&&void 0!==t?t:(new Date).toISOString(),tags:u(e.tags)})});for(let e=0;e<s.length;e+=50){const t=s.slice(e,e+50),o=1===t.length?t[0]:{metrics:t};yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(o)})}}catch(e){console.error("Failed to send client metric:",e)}});const u=e=>{const t=Object.assign(Object.assign({},s.CLIENT_METADATA),e);return d.sessionId&&void 0===t.sessionId&&(t.sessionId=d.sessionId),d.organizationId&&void 0===t.organizationId&&(t.organizationId=d.organizationId),d.attemptCorrelationId&&void 0===t.attemptCorrelationId&&(t.attemptCorrelationId=d.attemptCorrelationId),t};t.createRTCStatsReport=(e,t="console")=>{var n,i,s;const o={};e.forEach(e=>{o[e.type]||(o[e.type]=[]),o[e.type].push(e)});const r={issues:[]},a=(null===(n=o["inbound-rtp"])||void 0===n?void 0:n.filter(e=>"video"===e.kind))||[];a.length>0&&(r.personaVideoStream=[],a.forEach(e=>{var t,n,i,s,o;const a={framesReceived:null!==(t=e.framesReceived)&&void 0!==t?t:"unknown",framesDropped:null!==(n=e.framesDropped)&&void 0!==n?n:"unknown",framesPerSecond:null!==(i=e.framesPerSecond)&&void 0!==i?i:"unknown",packetsReceived:null!==(s=e.packetsReceived)&&void 0!==s?s:"unknown",packetsLost:null!==(o=e.packetsLost)&&void 0!==o?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)}));const l=(null===(i=o["inbound-rtp"])||void 0===i?void 0:i.filter(e=>"audio"===e.kind))||[];l.length>0&&(r.personaAudioStream=[],l.forEach(e=>{var t,n,i;const s={packetsReceived:null!==(t=e.packetsReceived)&&void 0!==t?t:"unknown",packetsLost:null!==(n=e.packetsLost)&&void 0!==n?n:"unknown",audioLevel:null!==(i=e.audioLevel)&&void 0!==i?i:"unknown",jitter:void 0!==e.jitter?e.jitter:void 0,totalAudioEnergy:void 0!==e.totalAudioEnergy?e.totalAudioEnergy:void 0};r.personaAudioStream.push(s)}));const c=(null===(s=o["outbound-rtp"])||void 0===s?void 0:s.filter(e=>"audio"===e.kind))||[];c.length>0&&(r.userAudioInput=[],c.forEach(e=>{var t,n;const i={packetsSent:null!==(t=e.packetsSent)&&void 0!==t?t:"unknown",retransmittedPackets:null!==(n=e.retransmittedPacketsSent)&&void 0!==n?n:void 0,avgPacketSendDelay:void 0!==e.totalPacketSendDelay?e.totalPacketSendDelay/(e.packetsSent||1)*1e3:void 0};r.userAudioInput.push(i)})),o.codec&&(r.codecs=[],o.codec.forEach(e=>{const 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=>{const t={dtlsState:e.dtlsState||"unknown",iceState:e.iceState||"unknown",bytesSent:e.bytesSent||void 0,bytesReceived:e.bytesReceived||void 0};r.transportLayer.push(t)}));const 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&&d.push(`Audio: High jitter (${(1e3*e.jitter).toFixed(1)}ms)`)}),r.issues=d,"json"===t)return r;console.group("📊 WebRTC Session Statistics Report"),r.personaVideoStream&&r.personaVideoStream.length>0&&(console.group("📹 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("🔊 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("🎤 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("🔧 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("🚚 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()}},958:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasoningHistoryClient=t.StreamingClient=t.PublicEventEmitter=t.MessageHistoryClient=t.InternalEventEmitter=t.EngineApiRestClient=t.CoreApiRestClient=t.SignallingClient=void 0;var i=n(279);Object.defineProperty(t,"SignallingClient",{enumerable:!0,get:function(){return i.SignallingClient}});var s=n(18);Object.defineProperty(t,"CoreApiRestClient",{enumerable:!0,get:function(){return s.CoreApiRestClient}});var o=n(529);Object.defineProperty(t,"EngineApiRestClient",{enumerable:!0,get:function(){return o.EngineApiRestClient}});var r=n(259);Object.defineProperty(t,"InternalEventEmitter",{enumerable:!0,get:function(){return r.InternalEventEmitter}});var a=n(462);Object.defineProperty(t,"MessageHistoryClient",{enumerable:!0,get:function(){return a.MessageHistoryClient}});var l=n(995);Object.defineProperty(t,"PublicEventEmitter",{enumerable:!0,get:function(){return l.PublicEventEmitter}});var c=n(577);Object.defineProperty(t,"StreamingClient",{enumerable:!0,get:function(){return c.StreamingClient}});var d=n(471);Object.defineProperty(t,"ReasoningHistoryClient",{enumerable:!0,get:function(){return d.ReasoningHistoryClient}})},985:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_START_SESSION_REQUEST_TIMEOUT_MS=t.DEFAULT_START_SESSION_MAX_BACKOFF_MS=t.DEFAULT_START_SESSION_INITIAL_BACKOFF_MS=t.DEFAULT_START_SESSION_MAX_ATTEMPTS=t.CLIENT_METADATA=t.DEFAULT_API_VERSION=t.DEFAULT_API_BASE_URL=t.DEFAULT_HEADERS=void 0,t.DEFAULT_HEADERS={"Content-Type":"application/json"},t.DEFAULT_API_BASE_URL="https://api.anam.ai",t.DEFAULT_API_VERSION="/v1",t.CLIENT_METADATA={client:"js-sdk",version:"0.0.0-automated"},t.DEFAULT_START_SESSION_MAX_ATTEMPTS=3,t.DEFAULT_START_SESSION_INITIAL_BACKOFF_MS=250,t.DEFAULT_START_SESSION_MAX_BACKOFF_MS=2e3,t.DEFAULT_START_SESSION_REQUEST_TIMEOUT_MS=1e4},995:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PublicEventEmitter=void 0;const i=n(948),s=n(170);t.PublicEventEmitter=class{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===s.AnamEvent.CONNECTION_ESTABLISHED&&(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===s.AnamEvent.CONNECTION_CLOSED){const[e,n]=t;(0,i.sendClientMetric)(i.ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,e,n?{details:n}:void 0)}this.listeners[e]&&this.listeners[e].forEach(e=>{e(...t)})}}}},t={},function n(i){var s=t[i];if(void 0!==s)return s.exports;var o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.exports}(440);var e,t});
|