@xmov/avatar 2.4.0-alpha.3 → 2.4.0-alpha.4

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.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("@xmov/avatar")):"function"==typeof define&&define.amd?define(["@xmov/avatar"],t):(e||self).XingyunAvatarAgentModule=t(e.XmovAvatar)}(this,function(e){function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n,r,i,o,a=/*#__PURE__*/t(e);function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function u(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,f(r.key),r)}}function l(e,t,n){return t&&u(e.prototype,t),n&&u(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return s(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function h(){return h=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h.apply(null,arguments)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function f(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}!function(e){e[e.CONTAINER_NOT_FOUND=10001]="CONTAINER_NOT_FOUND",e[e.CONNECT_SOCKET_ERROR=10002]="CONNECT_SOCKET_ERROR",e[e.START_SESSION_ERROR=10003]="START_SESSION_ERROR",e[e.STOP_SESSION_ERROR=10004]="STOP_SESSION_ERROR",e[e.INIT_ERROR=10005]="INIT_ERROR",e[e.SOCKET_QUIT=10006]="SOCKET_QUIT",e[e.SOCKET_DISCONNECT=10007]="SOCKET_DISCONNECT",e[e.VIDEO_FRAME_EXTRACT_ERROR=20001]="VIDEO_FRAME_EXTRACT_ERROR",e[e.INIT_WORKER_ERROR=20002]="INIT_WORKER_ERROR",e[e.PROCESS_VIDEO_STREAM_ERROR=20003]="PROCESS_VIDEO_STREAM_ERROR",e[e.FACE_PROCESSING_ERROR=20004]="FACE_PROCESSING_ERROR",e[e.RENDER_BODY_ERROR=20005]="RENDER_BODY_ERROR",e[e.RENDER_FACE_ERROR=20006]="RENDER_FACE_ERROR",e[e.WebGL_RENDER_ERROR=20007]="WebGL_RENDER_ERROR",e[e.RENDER_DATA_MISSING=20008]="RENDER_DATA_MISSING",e[e.RENDER_FACE_DATA_MISSING=20009]="RENDER_FACE_DATA_MISSING",e[e.EVENT_WITHOUT_SPEECH_ID=20010]="EVENT_WITHOUT_SPEECH_ID",e[e.EVENT_TRIGGERED=20011]="EVENT_TRIGGERED",e[e.BACKGROUND_IMAGE_LOAD_ERROR=30001]="BACKGROUND_IMAGE_LOAD_ERROR",e[e.FACE_BIN_LOAD_ERROR=30002]="FACE_BIN_LOAD_ERROR",e[e.INVALID_BODY_NAME=30003]="INVALID_BODY_NAME",e[e.VIDEO_DOWNLOAD_ERROR=30004]="VIDEO_DOWNLOAD_ERROR",e[e.BODY_DATA_EXPIRED=30005]="BODY_DATA_EXPIRED",e[e.EVENT_SPEAK_START_EXPIRED=30006]="EVENT_SPEAK_START_EXPIRED",e[e.EVENT_VOICE_START_EXPIRED=30007]="EVENT_VOICE_START_EXPIRED",e[e.AUDIO_DECODE_ERROR=40001]="AUDIO_DECODE_ERROR",e[e.FACE_DECODE_ERROR=40002]="FACE_DECODE_ERROR",e[e.VIDEO_DECODE_ERROR=40003]="VIDEO_DECODE_ERROR",e[e.EVENT_DECODE_ERROR=40004]="EVENT_DECODE_ERROR",e[e.INVALID_DATA_STRUCTURE=40005]="INVALID_DATA_STRUCTURE",e[e.TTSA_ERROR=40006]="TTSA_ERROR",e[e.AUDIO_DATA_EXPIRED=40007]="AUDIO_DATA_EXPIRED",e[e.NETWORK_DOWN=50001]="NETWORK_DOWN",e[e.NETWORK_UP=50002]="NETWORK_UP",e[e.NETWORK_RETRY=50003]="NETWORK_RETRY",e[e.NETWORK_BREAK=50004]="NETWORK_BREAK",e[e.WEBGL_CONTEXT_LOST=60001]="WEBGL_CONTEXT_LOST",e[e.WEBGL_CONTEXT_RESTORED=60002]="WEBGL_CONTEXT_RESTORED",e[e.WEBGL_CONTEXT_RESTORE_TIMEOUT=60003]="WEBGL_CONTEXT_RESTORE_TIMEOUT",e[e.WEBGL_CONTEXT_RECOVERED=60004]="WEBGL_CONTEXT_RECOVERED",e[e.WEBGL_CONTEXT_RECOVERY_FAILED=60005]="WEBGL_CONTEXT_RECOVERY_FAILED",e[e.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS=60006]="WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",e[e.WEBGL_RESOLUTION_RESTORED=60007]="WEBGL_RESOLUTION_RESTORED",e[e.WEBGL_CONTEXT_MANUAL_RESTARTED=60008]="WEBGL_CONTEXT_MANUAL_RESTARTED"}(n||(n={})),function(e){e[e.online=0]="online",e[e.offline=1]="offline",e[e.network_on=2]="network_on",e[e.network_off=3]="network_off",e[e.close=4]="close",e[e.visible=5]="visible",e[e.invisible=6]="invisible",e[e.stopped=7]="stopped"}(r||(r={})),function(e){e.init="init",e.rendering="rendering",e.pausing="pausing",e.paused="paused",e.resumed="resumed",e.stopped="stopped"}(i||(i={})),function(e){e.normal="normal",e.invisible="invisible"}(o||(o={}));var m=2097152,p=/*#__PURE__*/function(){function e(e){var t;this.ws=null,this.connectPromise=null,this.rejectConnect=null,this.options=e,this.audioInputEnabled=null==(t=e.audioInputEnabled)||t;var n=e.WebSocketCtor||globalThis.WebSocket;if(!n)throw new Error("当前环境不支持 WebSocket");this.WebSocketCtor=n}var t=e.prototype;return t.connect=function(){var e,t,n,r=this;return this.isOpen?Promise.resolve():(this.connectPromise||(null==(e=(t=this.options).onStateChange)||e.call(t,"connecting"),n=new Promise(function(e,t){r.rejectConnect=t;var i=!1,o=new r.WebSocketCtor(r.buildWsUrl(r.options.wsUrl,r.options.token));r.ws=o,o.onopen=function(){r.ws===o&&(i=!0,r.connectPromise===n&&(r.connectPromise=null),r.rejectConnect=null,null==r.options.onStateChange||r.options.onStateChange("open"),e())},o.onmessage=function(e){if(r.ws===o){var t=r.parseMessage(e.data);t&&(null==r.options.onEvent||r.options.onEvent(t))}},o.onerror=function(){if(r.ws===o){var e=new Error("E2E WebSocket 连接异常");i||(i=!0,r.connectPromise===n&&(r.connectPromise=null),r.rejectConnect=null,t(e)),null==r.options.onStateChange||r.options.onStateChange("error"),null==r.options.onError||r.options.onError(e)}},o.onclose=function(e){r.ws===o&&(r.ws=null,i||(i=!0,r.connectPromise===n&&(r.connectPromise=null),r.rejectConnect=null,t(new Error(("E2E WebSocket 已关闭: "+e.code+" "+(e.reason||"")).trim()))),null==r.options.onStateChange||r.options.onStateChange("closed"),null==r.options.onClose||r.options.onClose(e))}}),this.connectPromise=n),this.connectPromise)},t.disconnect=function(e,t){void 0===e&&(e=1e3),void 0===t&&(t="client_close");var n=this.detachSocket();n&&this.closeSocket(n,e,t)},t.disconnectAndWait=function(e,t,n){var r=this;void 0===e&&(e=1e3),void 0===t&&(t="client_close"),void 0===n&&(n=3e3);var i=this.ws;return i?(this.cancelPendingConnection(),new Promise(function(o){var a,s=i.onclose,u=!1,l=function(){u||(u=!0,void 0!==a&&globalThis.clearTimeout(a),r.ws===i&&(r.ws=null),i.onclose=s,o())};i.onclose=function(e){try{null==s||s.call(i,e)}finally{l()}},a=globalThis.setTimeout(l,Math.max(0,n));try{r.closeSocket(i,e,t)}catch(e){l()}})):Promise.resolve()},t.detachSocket=function(){if(!this.ws)return null;var e=this.ws;return this.ws=null,this.cancelPendingConnection(),e},t.cancelPendingConnection=function(){this.connectPromise=null;var e=this.rejectConnect;this.rejectConnect=null,null==e||e(new Error("E2E WebSocket 连接已取消"))},t.closeSocket=function(e,t,n){e.readyState!==this.WebSocketCtor.OPEN&&e.readyState!==this.WebSocketCtor.CONNECTING||e.close(t,n)},t.send=function(e){var t;this.assertOpen(),null==(t=this.ws)||t.send(JSON.stringify(e))},t.trySend=function(e){var t;return this.assertOpen(),!(this.ws&&this.ws.bufferedAmount>m||(null==(t=this.ws)||t.send(JSON.stringify(e)),0))},t.sendBinary=function(e){var t;if(this.assertOpen(),this.ws&&this.ws.bufferedAmount>m){var n=new Error("E2E WebSocket 发送缓冲区超限");throw n.name="WebSocketBackpressureError",n}null==(t=this.ws)||t.send(e)},t.ping=function(){this.send({type:"ping"})},t.setAudioInputEnabled=function(e){this.audioInputEnabled=e},t.assertOpen=function(){if(!this.isOpen)throw new Error("E2E WebSocket 未连接")},t.parseMessage=function(e){if("string"!=typeof e)return null;try{var t=JSON.parse(e);return t&&"string"==typeof t.type?t:null}catch(e){var n,r;return null==(n=(r=this.options).onError)||n.call(r,new Error("E2E WebSocket 消息不是合法 JSON")),null}},t.buildWsUrl=function(e,t){try{var n=new URL(e);return!t||n.searchParams.has("token")||n.searchParams.has("e2e_token")||n.searchParams.set("token",t),this.updateAudioInputQuery(n.searchParams),n.toString()}catch(n){var r=e.split("?",2),i=r[0],o=r[1],a=new URLSearchParams(void 0===o?"":o);!t||a.has("token")||a.has("e2e_token")||a.set("token",t),this.updateAudioInputQuery(a);var s=a.toString();return s?i+"?"+s:i}},t.updateAudioInputQuery=function(e){this.audioInputEnabled?e.delete("audio_input_off"):e.set("audio_input_off","1")},l(e,[{key:"isOpen",get:function(){var e;return(null==(e=this.ws)?void 0:e.readyState)===this.WebSocketCtor.OPEN}}])}(),v={format:"webm_opus",mimeType:"audio/webm;codecs=opus",sampleRate:16e3,channels:1,chunkMs:100};function E(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var g=16e3,S="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function y(e,t,n){if(!e.s){if(n instanceof R){if(!n.s)return void(n.o=y.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(y.bind(null,e,t),y.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var R=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var o=1&i?t:n;if(o){try{y(r,1,o(this.v))}catch(e){y(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?y(r,1,t?t(i):i):n?y(r,1,n(i)):y(r,2,i)}catch(e){y(r,2,e)}},r},e}();function A(e){return e instanceof R&&1&e.s}function b(e,t,n){if("function"==typeof e[S]){var r,i,o,a=function(e){try{for(;!((r=s.next()).done||n&&n());)if((e=t(r.value))&&e.then){if(!A(e))return void e.then(a,o||(o=y.bind(null,i=new R,2)));e=e.v}i?y(i,1,e):i=e}catch(e){y(i||(i=new R),2,e)}},s=e[S]();if(a(),s.return){var u=function(e){try{r.done||s.return()}catch(e){}return e};if(i&&i.then)return i.then(u,function(e){throw u(e)});u()}return i}if(!("length"in e))throw new TypeError("Object is not iterable");for(var l=[],c=0;c<e.length;c++)l.push(e[c]);return function(e,t,n){var r,i,o=-1;return function a(s){try{for(;++o<e.length&&(!n||!n());)if((s=t(o))&&s.then){if(!A(s))return void s.then(a,i||(i=y.bind(null,r=new R,2)));s=s.v}r?y(r,1,s):r=s}catch(e){y(r||(r=new R),2,e)}}(),r}(l,function(e){return t(l[e])},n)}function w(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var C=/*#__PURE__*/function(){function e(e){void 0===e&&(e={}),this.inputTrack=null,this.reader=null,this.writer=null,this.generator=null,this.audioContext=null,this.audioSource=null,this.audioDestination=null,this.pumpPromise=null,this.pumpFinished=!1,this.outputClosed=!1,this.draining=!1,this.inputSampleRate=null,this.resampleBuffer=[],this.resamplePosition=0,this.outputBuffer=[],this.outputTimestamp=null,this.startGeneration=0,this.options=e}var t=e.prototype;return t.start=function(e){try{var t=this,n=++t.startGeneration;t.inputTrack=e,t.inputSampleRate=null,t.resampleBuffer=[],t.resamplePosition=0,t.outputBuffer=[],t.outputTimestamp=null,t.pumpFinished=!1,t.outputClosed=!1,t.draining=!1;var r=globalThis,i=r.MediaStreamTrackProcessor,o=r.MediaStreamTrackGenerator,a=r.AudioData;if(!i||!o||!a)return Promise.resolve(t.startWebAudio(e,r,n));var s=new i({track:e}),u=new o({kind:"audio"}),l=new MediaStream([u]),c=l.getAudioTracks()[0],h=null==c?void 0:c.getSettings();if(void 0!==(null==h?void 0:h.sampleRate)&&h.sampleRate!==g||void 0!==(null==h?void 0:h.channelCount)&&1!==h.channelCount)throw u.stop(),t.unsupported("浏览器音频输出格式不符合要求: "+((null==h?void 0:h.sampleRate)||"unknown")+" Hz / "+((null==h?void 0:h.channelCount)||"unknown")+" channel");try{t.reader=s.readable.getReader(),t.writer=u.writable.getWriter()}catch(n){throw u.stop(),"ended"!==e.readyState&&e.stop(),t.inputTrack=null,n}return t.generator=u,t.pumpPromise=t.pump(a),Promise.resolve(l)}catch(e){return Promise.reject(e)}},t.startWebAudio=function(e,t,n){try{var r=this,i=globalThis.AudioContext||t.webkitAudioContext;if(!i)throw r.unsupported("当前浏览器不支持 16 kHz mono 音频处理");var o=null,a=null,s=null;return Promise.resolve(E(function(){function t(t){if(r.assertStartActive(n),"running"!==o.state)throw r.contextSuspended();a=o.createMediaStreamSource(new MediaStream([e])),r.audioSource=a,s=o.createMediaStreamDestination(),r.audioDestination=s,s.channelCount=1,s.channelCountMode="explicit",s.channelInterpretation="speakers",a.connect(s);var i=s.stream.getAudioTracks()[0];if(!i)throw new Error("Web Audio 未返回音频输出轨道");return r.validateOutputTrack(i),r.assertStartActive(n),s.stream}if(o=new i({sampleRate:g}),r.audioContext=o,o.sampleRate!==g)throw r.unsupported("浏览器无法创建 16 kHz AudioContext: "+o.sampleRate+" Hz");var u=function(){if("suspended"===o.state)return E(function(){return Promise.resolve(o.resume()).then(function(){})},function(e){throw r.contextSuspended(e)})}();return u&&u.then?u.then(t):t()},function(t){var n,i;function u(){throw"ended"!==e.readyState&&e.stop(),r.inputTrack=null,r.audioContext===o&&(r.audioContext=null,r.audioSource=null,r.audioDestination=null),r.normalizeWebAudioError(t)}null==(n=a)||n.disconnect(),null==(i=s)||i.stream.getTracks().forEach(function(e){return e.stop()});var l=function(){if(o&&"closed"!==o.state)return Promise.resolve(o.close().catch(function(){})).then(function(){})}();return l&&l.then?l.then(u):u()}))}catch(e){return Promise.reject(e)}},t.stop=function(){try{var e=this;return Promise.resolve(e.drain()).then(function(){var t;function n(n){return t?n:Promise.resolve(e.closeOutput()).then(function(){})}var r=function(){if(e.audioContext)return Promise.resolve(e.closeWebAudioOutput()).then(function(){t=1})}();return r&&r.then?r.then(n):n(r)})}catch(e){return Promise.reject(e)}},t.drain=function(){try{var e,t=this;if(t.startGeneration+=1,t.draining=!0,null==(e=t.inputTrack)||e.stop(),t.inputTrack=null,t.audioContext)return Promise.resolve();var n=t.pumpPromise,r=function(){if(n){var e=n.then(function(){return!0},function(){return!0});return Promise.resolve(Promise.race([e,t.delay(1e3)])).then(function(e){var n=function(){var n;if(!e)return Promise.resolve(Promise.race([null==(n=t.reader)?void 0:n.cancel().catch(function(){}),t.delay(100)])).then(function(){var e;return Promise.resolve(Promise.race([null==(e=t.writer)?void 0:e.abort(new Error("16 kHz mono 音频处理停止超时")).catch(function(){}),t.delay(100)])).then(function(){t.stopGenerator()})})}();if(n&&n.then)return n.then(function(){})})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.closeOutput=function(){try{var e=function(){t.stopGenerator(),n&&t.pumpFinished&&n.releaseLock(),t.reader=null,t.writer=null,t.generator=null,t.pumpPromise=null},t=this,n=t.writer;t.outputClosed=!0;var r=n&&t.pumpFinished?Promise.resolve(Promise.race([n.close().catch(function(){}),t.delay(100)])).then(function(){}):Promise.resolve(Promise.race([null==n?void 0:n.abort(new Error("16 kHz mono 音频处理停止超时")).catch(function(){}),t.delay(100)])).then(function(){});return Promise.resolve(r&&r.then?r.then(e):e())}catch(e){return Promise.reject(e)}},t.closeWebAudioOutput=function(){try{var e=this,t=e.audioContext,n=e.audioSource,r=e.audioDestination;e.audioContext=null,e.audioSource=null,e.audioDestination=null,null==n||n.disconnect(),null==r||r.disconnect(),null==r||r.stream.getTracks().forEach(function(e){return e.stop()});var i=function(){if(t&&"closed"!==t.state)return Promise.resolve(t.close().catch(function(){})).then(function(){})}();return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.pump=function(e){try{var t=this,n=t.reader,r=t.writer;return n&&r?Promise.resolve(w(function(){return E(function(){var i;function o(){function n(){var e;if(a&&!t.draining&&"ended"===(null==(e=t.inputTrack)?void 0:e.readyState)){var n=new Error("麦克风音频轨道已结束");n.name="AudioTransformError",null==t.options.onError||t.options.onError(n),t.stopGenerator()}}var i=b(t.resample(new Float32Array,t.inputSampleRate||g,!0),function(n){return Promise.resolve(t.writeChunk(r,e,n)).then(function(){})});return i&&i.then?i.then(n):n()}var a=!1,s=function(e,t,n){for(var r;;){var i=e();if(A(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!A(o)){r=1;break}o=o.s}}var a=new R,s=y.bind(null,a,2);return(0===r?i.then(l):1===r?o.then(u):(void 0).then(function(){(i=e())?i.then?i.then(l).then(void 0,s):l(i):y(a,1,o)})).then(void 0,s),a;function u(t){o=t;do{if(!(i=e())||A(i)&&!i.v)return void y(a,1,o);if(i.then)return void i.then(l).then(void 0,s);A(o=n())&&(o=o.v)}while(!o||!o.then);o.then(u).then(void 0,s)}function l(e){e?(o=n())&&o.then?o.then(u).then(void 0,s):u(o):y(a,1,o)}}(function(){return!i},0,function(){return Promise.resolve(n.read()).then(function(n){if(n.done)return a=!0,void(i=1);if(n.value){var o=n.value;return w(function(){t.validateAudioData(o);var n=t.toMono(o),i=t.resample(n,o.sampleRate,!1);null===t.outputTimestamp&&(t.outputTimestamp=Number.isFinite(o.timestamp)?o.timestamp:0);var a=b(i,function(n){return Promise.resolve(t.writeChunk(r,e,n)).then(function(){})});if(a&&a.then)return a.then(function(){})},function(e,t){if(o.close(),e)throw t;return t})}})});return s&&s.then?s.then(o):o()},function(e){var n=e instanceof Error?e:new Error("16 kHz mono 音频处理失败");n.name="AudioTransformError",null==t.options.onError||t.options.onError(n)})},function(e,i){if(n.releaseLock(),t.pumpFinished=!0,t.outputClosed&&r.releaseLock(),e)throw i;return i})):Promise.resolve()}catch(e){return Promise.reject(e)}},t.toMono=function(e){for(var t=Math.max(1,e.numberOfChannels),n=new Float32Array(e.numberOfFrames),r=0;r<t;r+=1){var i=new Float32Array(e.numberOfFrames);e.copyTo(i,{format:"f32-planar",planeIndex:r});for(var o=0;o<i.length;o+=1)n[o]+=i[o]/t}return n},t.resample=function(e,t,n){if(null===this.inputSampleRate)this.inputSampleRate=t;else if(this.inputSampleRate!==t)throw new Error("输入音频采样率发生变化: "+this.inputSampleRate+" -> "+t);for(var r,i=c(e);!(r=i()).done;)this.resampleBuffer.push(r.value);if(this.resampleBuffer.length>192e3)throw new Error("输入音频重采样缓冲区超限");n&&this.resampleBuffer.length>0&&this.resampleBuffer.push(this.resampleBuffer[this.resampleBuffer.length-1]);for(var o=t/g,a=[];this.resamplePosition+1<this.resampleBuffer.length;){var s=Math.floor(this.resamplePosition),u=Math.min(s+1,this.resampleBuffer.length-1),l=this.resamplePosition-s;this.outputBuffer.push(this.resampleBuffer[s]*(1-l)+this.resampleBuffer[u]*l),this.resamplePosition+=o;var h=Math.floor(this.resamplePosition);h>0&&(this.resampleBuffer.splice(0,h),this.resamplePosition-=h),this.outputBuffer.length>=320&&a.push(new Float32Array(this.outputBuffer.splice(0,320)))}return n&&this.outputBuffer.length>0&&a.push(new Float32Array(this.outputBuffer.splice(0))),a},t.writeChunk=function(e,t,n){try{var r=this;if(!n.length)return Promise.resolve();var i=r.outputTimestamp||0,o=new t({format:"f32-planar",sampleRate:g,numberOfFrames:n.length,numberOfChannels:1,timestamp:i,data:n});return r.outputTimestamp=i+Math.round(1e6*n.length/g),Promise.resolve(e.write(o)).then(function(){var e;o.close();var t=null==(e=r.generator)?void 0:e.getSettings();if(t&&(void 0!==t.sampleRate&&t.sampleRate!==g||void 0!==t.channelCount&&1!==t.channelCount))throw r.unsupported("浏览器音频输出格式不符合要求: "+(t.sampleRate||"unknown")+" Hz / "+(t.channelCount||"unknown")+" channel")})}catch(e){return Promise.reject(e)}},t.validateAudioData=function(e){if(!Number.isFinite(e.sampleRate)||!Number.isInteger(e.sampleRate)||e.sampleRate<8e3||e.sampleRate>192e3)throw new Error("输入音频采样率无效: "+e.sampleRate);if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<1||e.numberOfChannels>8)throw new Error("输入音频声道数无效: "+e.numberOfChannels);if(!Number.isInteger(e.numberOfFrames)||e.numberOfFrames<1||e.numberOfFrames>96e3)throw new Error("输入音频帧数无效: "+e.numberOfFrames);if(!Number.isFinite(e.timestamp)||Math.abs(e.timestamp)>1e15)throw new Error("输入音频时间戳无效: "+e.timestamp)},t.delay=function(e){return new Promise(function(t){globalThis.setTimeout(function(){return t(!1)},e)})},t.stopGenerator=function(){this.generator&&"ended"!==this.generator.readyState&&this.generator.stop()},t.unsupported=function(e,t){var n=new Error(e);return n.name="NotSupportedError",n.agentCode="AUDIO_FIXED_TRACK_UNSUPPORTED",n.retryable=!1,n.cause=t,n},t.contextSuspended=function(e){var t=new Error("AudioContext 未运行,请在用户操作后重试");return t.name="NotAllowedError",t.agentCode="AUDIO_CONTEXT_SUSPENDED",t.retryable=!0,t.cause=e,t},t.assertStartActive=function(e){if(e!==this.startGeneration){var t=new Error("16 kHz mono 音频处理启动已取消");throw t.name="AbortError",t.agentCode="AUDIO_FIXED_TRACK_CANCELLED",t.retryable=!0,t}},t.normalizeWebAudioError=function(e){var t=e instanceof Error?e:new Error(String(e));if(t.agentCode)return t;if("NotSupportedError"===t.name)return this.unsupported("浏览器无法初始化 16 kHz mono Web Audio: "+t.message,t);var n=new Error("16 kHz mono Web Audio 初始化失败: "+t.message);return n.name=t.name,n.agentCode="AUDIO_FIXED_TRACK_FAILED",n.retryable=!0,n.cause=t,n},t.validateOutputTrack=function(e){var t=e.getSettings();if(void 0!==t.sampleRate&&t.sampleRate!==g||void 0!==t.channelCount&&1!==t.channelCount)throw this.unsupported("浏览器音频输出格式不符合要求: "+(t.sampleRate||"unknown")+" Hz / "+(t.channelCount||"unknown")+" channel")},e}(),_=function(e,t,n,r){void 0===n&&(n={}),void 0===r&&(r=P);try{var i=function(i,o){try{var a=function(){function i(i){var o=new Uint8Array(i),a=Array.from(o.slice(0,r)),s=t instanceof Blob?t.type:n.type;console.log(e,h({},n,{size:o.byteLength,type:s,previewLength:a.length,bytes:a,hex:a.map(k).join(" ")}))}return t instanceof Blob?Promise.resolve(t.arrayBuffer()).then(i):i(ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t)}()}catch(e){return o(e)}return a&&a.then?a.then(void 0,o):a}(0,function(t){console.warn(e,"failed to read audio chunk",t)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},P=64;function k(e){return e.toString(16).padStart(2,"0")}var O=new WeakMap,T=new WeakMap;function D(e){return e.audioSession}function I(e,t){try{return e.type=t,e.type===t}catch(e){return!1}}function N(){var e=globalThis.performance;return e&&Number.isFinite(e.timeOrigin)&&"function"==typeof e.now?e.timeOrigin+e.now():Date.now()}var F=/*#__PURE__*/function(){function e(e,t){void 0===t&&(t=N),this.timecodeScale=null,this.firstTimecode=null,this.lastTimecode=null,this.lastObservedAt=null,this.lastTimestamp=null,this.chunkMs=e,this.now=t,this.startedAt=t()}return e.prototype.resolve=function(e){var t=this.now(),n=Number.isFinite(e)&&e>=0;if(n&&null===this.firstTimecode&&(this.firstTimecode=e),n&&null===this.timecodeScale&&null!==this.lastTimecode&&e>this.lastTimecode){var r=e-this.lastTimecode,i=null===this.lastObservedAt?0:t-this.lastObservedAt,o=i>=this.chunkMs/4?i:this.chunkMs,a=Math.abs(r-o),s=Math.abs(1e3*r-o);this.timecodeScale=s<a?1e3:1}var u,l=t-this.chunkMs,c=n&&null!==this.firstTimecode?e-this.firstTimecode:null;null!==c&&c>=0&&(null!==this.timecodeScale||0===c)&&(l=this.startedAt+c*(null!=(u=this.timecodeScale)?u:1)),null!==this.lastTimestamp&&(l=Math.max(l,this.lastTimestamp+this.chunkMs));var h=Math.max(Math.round(this.startedAt),Math.round(l));return this.lastTimecode=n?e:this.lastTimecode,this.lastObservedAt=t,this.lastTimestamp=h,h},e}();function M(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var U=2e4;function B(e){return{codec:"opus",sampleRate:e.sampleRate,numberOfChannels:e.channels,bitrate:e.bitrate,opus:{format:"opus",frameDuration:U}}}var W=/*#__PURE__*/function(){function e(e){void 0===e&&(e={}),this.encoder=null,this.isInitialized=!1,this.pendingEncode=null,this.timestamp=0,this.config=h({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600},e)}e.isSupported=function(){try{return"undefined"==typeof AudioEncoder?Promise.resolve(!1):Promise.resolve(M(function(){return Promise.resolve(AudioEncoder.isConfigSupported(B({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}))).then(function(e){var t;return!0===e.supported&&(null==(t=e.config)||null==(t=t.opus)?void 0:t.frameDuration)===U})},function(){return!1}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.init=function(){try{var e=this;return e.isInitialized||(e.encoder=e.createEncoder(),e.isInitialized=!0),Promise.resolve()}catch(e){return Promise.reject(e)}},t.encode=function(e){try{var t=this;if(!t.isInitialized||!t.encoder)return Promise.reject(new Error("WebCodecOpusEncoder 未初始化"));if(t.pendingEncode)return Promise.reject(new Error("WebCodecs Opus 编码器仍在处理上一音频块"));var n=new Int16Array(e),r=t.timestamp,i=Math.round(1e6*e.length/t.config.sampleRate),o=r+i,a=i/U;if(!Number.isInteger(a))return Promise.reject(new Error("PCM 音频块无法按 20ms Opus packet 完整分包"));var s=new AudioData({format:"s16",sampleRate:t.config.sampleRate,numberOfFrames:n.length,numberOfChannels:t.config.channels,timestamp:r,data:n}),u=new Promise(function(e,n){var i=globalThis.setTimeout(function(){t.failPending(new Error("WebCodecs Opus 编码输出超过 2 秒"))},2e3);t.pendingEncode={startTimestampUs:r,endTimestampUs:o,expectedFrameCount:a,chunks:[],resolve:e,reject:n,timeoutId:i}});try{t.encoder.encode(s),t.timestamp=o}catch(e){t.failPending(e instanceof Error?e:new Error("WebCodecs Opus 编码失败"))}finally{s.close()}return Promise.resolve(u)}catch(e){return Promise.reject(e)}},t.reset=function(){if(this.timestamp=0,this.failPending(new Error("WebCodecs Opus 编码已重置")),this.encoder){try{this.encoder.close()}catch(e){}this.encoder=this.createEncoder()}},t.destroy=function(){try{var e=function(){t.encoder=null,t.isInitialized=!1},t=this,n=t.encoder,r=function(){if(n){var e=function(){t.failPending(new Error("WebCodecs Opus 编码器已销毁"));try{n.close()}catch(e){}},r=M(function(){return Promise.resolve(n.flush()).then(function(){})},function(){});return r&&r.then?r.then(e):e()}}();return Promise.resolve(r&&r.then?r.then(e):e())}catch(e){return Promise.reject(e)}},t.createEncoder=function(){var e,t=this;return(e=new AudioEncoder({output:function(n){t.encoder===e&&t.handleOutput(n)},error:function(n){if(t.encoder===e){var r=n instanceof Error?n:new Error("WebCodecs Opus 编码失败");(globalThis.avatarSDKLogger||console).error("[WebCodecOpusEncoder] 编码错误:",r),t.failPending(r)}}})).configure(B(this.config)),e},t.handleOutput=function(e){var t=this.pendingEncode;if(t)if(e.timestamp<t.startTimestampUs||e.timestamp>=t.endTimestampUs||null!==e.duration&&e.duration!==U)this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));else if(t.chunks.push(e),t.chunks.length>t.expectedFrameCount)this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));else if(!(t.chunks.length<t.expectedFrameCount)){var n=t.chunks.map(function(e,n){var r,i,o=new Uint8Array(e.byteLength);e.copyTo(o);var a=null!=(r=null==(i=t.chunks[n+1])?void 0:i.timestamp)?r:t.endTimestampUs;return{data:o,durationMs:(e.duration&&e.duration>0?e.duration:Math.max(1,a-e.timestamp))/1e3}}),r=n.reduce(function(e,t){return e+t.durationMs},0);n.some(function(e){return 20!==e.durationMs})||r!==(t.endTimestampUs-t.startTimestampUs)/1e3?this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频")):(globalThis.clearTimeout(t.timeoutId),this.pendingEncode=null,t.resolve(n))}},t.failPending=function(e){var t=this.pendingEncode;t&&(globalThis.clearTimeout(t.timeoutId),this.pendingEncode=null,t.reject(e))},e}(),x=/*#__PURE__*/function(){function e(e){void 0===e&&(e=16e3),this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0,this.frameDuration=100,this.sampleRate=e}var t=e.prototype;return t.writeHeader=function(){if(!this.hasHeader){var e=this.buildEBMLHeader(),t=this.buildSegmentInfo(),n=this.buildOpusTracks();this.chunks.push(e),this.chunks.push(new Uint8Array([24,83,128,103,1,255,255,255,255,255,255,255])),this.chunks.push(t),this.chunks.push(n),this.hasHeader=!0,this.clusterTimestamp=0}},t.feedOpusFrame=function(e,t){void 0===t&&(t=this.frameDuration),this.hasHeader||this.writeHeader();var n=this.buildCluster(Math.round(this.clusterTimestamp),e);this.chunks.push(n),this.clusterTimestamp+=t},t.flush=function(){if(0===this.chunks.length)return new ArrayBuffer(0);for(var e,t=this.chunks.reduce(function(e,t){return e+t.length},0),n=new Uint8Array(t),r=0,i=c(this.chunks);!(e=i()).done;){var o=e.value;n.set(o,r),r+=o.length}return this.chunks=[],n.buffer},t.reset=function(){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0},t.encodeVINT=function(e,t){if(void 0!==t){for(var n=new Uint8Array(t),r=t-1;r>=0;r--)n[r]=255&e,e>>>=8;return n[0]|=1<<8-t,n}if(e<127)return new Uint8Array([128|e]);if(e<16383)return new Uint8Array([64|e>>8,255&e]);if(e<2097151)return new Uint8Array([32|e>>16,e>>8&255,255&e]);if(e<268435455)return new Uint8Array([16|e>>24,e>>16&255,e>>8&255,255&e]);throw new Error("VINT value too large: "+e)},t.encodeID=function(e){return e<=255?new Uint8Array([e]):e<=65535?new Uint8Array([e>>8,255&e]):e<=16777215?new Uint8Array([e>>16,e>>8&255,255&e]):new Uint8Array([e>>>24,e>>16&255,e>>8&255,255&e])},t.encodeUint=function(e){if(0===e)return new Uint8Array([0]);for(var t=[],n=e;n>0;)t.unshift(255&n),n=Math.floor(n/256);return new Uint8Array(t)},t.encodeString=function(e){return(new TextEncoder).encode(e)},t.encodeFloat32=function(e){var t=new ArrayBuffer(4);return new DataView(t).setFloat32(0,e,!1),new Uint8Array(t)},t.encodeElement=function(e,t){var n=this.encodeID(e),r=this.encodeVINT(t.length),i=new Uint8Array(n.length+r.length+t.length);return i.set(n,0),i.set(r,n.length),i.set(t,n.length+r.length),i},t.encodeUintElement=function(e,t){return this.encodeElement(e,this.encodeUint(t))},t.encodeStringElement=function(e,t){return this.encodeElement(e,this.encodeString(t))},t.encodeFloat32Element=function(e,t){return this.encodeElement(e,this.encodeFloat32(t))},t.concatArrays=function(e){for(var t,n=e.reduce(function(e,t){return e+t.length},0),r=new Uint8Array(n),i=0,o=c(e);!(t=o()).done;){var a=t.value;r.set(a,i),i+=a.length}return r},t.buildEBMLHeader=function(){var e=this.concatArrays([this.encodeUintElement(17030,1),this.encodeUintElement(17143,1),this.encodeUintElement(17138,4),this.encodeUintElement(17139,8),this.encodeStringElement(17026,"webm"),this.encodeUintElement(17031,4),this.encodeUintElement(17029,2)]);return this.encodeElement(440786851,e)},t.buildSegmentInfo=function(){var e=this.concatArrays([this.encodeUintElement(2807729,1e6),this.encodeStringElement(19840,"xmov-avatar-sdk"),this.encodeStringElement(22337,"xmov-avatar-sdk")]);return this.encodeElement(357149030,e)},t.buildOpusTracks=function(){var e=new Uint8Array([79,112,117,115,72,101,97,100,1,1,0,0,128,62,0,0,0,0,0]),t=this.concatArrays([this.encodeFloat32Element(181,this.sampleRate),this.encodeUintElement(159,1)]),n=this.concatArrays([this.encodeUintElement(215,1),this.encodeUintElement(29637,1),this.encodeUintElement(131,2),this.encodeUintElement(156,0),this.encodeStringElement(2274716,"und"),this.encodeStringElement(134,"A_OPUS"),this.encodeElement(25506,e),this.encodeUintElement(22186,0),this.encodeUintElement(22203,8e7),this.encodeElement(225,t)]),r=this.encodeElement(174,n);return this.encodeElement(374648427,r)},t.buildCluster=function(e,t){var n=this.encodeUintElement(231,e),r=this.encodeVINT(1),i=new Uint8Array([0,0]),o=new Uint8Array([128]),a=this.concatArrays([r,i,o,t]),s=this.encodeElement(163,a),u=this.concatArrays([n,s]);return this.encodeElement(524531317,u)},e}(),L=/*#__PURE__*/function(){function e(){this.opusEncoder=new W({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}),this.muxer=new x(16e3),this.queue=Promise.resolve(),this.generation=0,this.destroyed=!1,this.pendingBlocks=0}e.isSupported=function(){return W.isSupported()};var t=e.prototype;return t.init=function(){try{return Promise.resolve(this.opusEncoder.init()).then(function(){})}catch(e){return Promise.reject(e)}},t.encode=function(e){try{var t=this;if(1600!==e.length)throw new Error("PCM 音频块必须为 1600 samples,实际为 "+e.length);if(t.pendingBlocks>=20)throw new Error("PCM/Opus 编码队列超过 2 秒");t.pendingBlocks+=1;var n=t.generation,r=new Int16Array(e),i=t.queue.then(function(){try{return t.destroyed||n!==t.generation?Promise.resolve(new ArrayBuffer(0)):Promise.resolve(t.opusEncoder.encode(r)).then(function(e){if(t.destroyed||n!==t.generation)return new ArrayBuffer(0);for(var r,i=c(e);!(r=i()).done;){var o=r.value;t.muxer.feedOpusFrame(o.data,o.durationMs)}return t.muxer.flush()})}catch(e){return Promise.reject(e)}}).finally(function(){t.pendingBlocks-=1});return t.queue=i.then(function(){},function(){}),Promise.resolve(i)}catch(e){return Promise.reject(e)}},t.reset=function(){var e=this,t=++this.generation;this.queue=this.queue.then(function(){e.destroyed||t!==e.generation||(e.opusEncoder.reset(),e.muxer.reset())})},t.destroy=function(){try{var e=this;return e.destroyed=!0,e.generation+=1,Promise.resolve(e.opusEncoder.destroy()).then(function(){return Promise.resolve(e.queue).then(function(){e.muxer.reset()})})}catch(e){return Promise.reject(e)}},e}(),j="audio/webm;codecs=opus";function G(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var z=16e3,K="agent-pcm-capture-processor",V="\nclass AgentPcmCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(1600);\n this.bufferIndex = 0;\n this.sequence = 0;\n this.port.onmessage = (event) => {\n if (event.data?.type === 'flush') {\n this.emitBlock(true);\n this.port.postMessage({ type: 'flushed' });\n }\n };\n }\n\n emitBlock(padPartial = false) {\n if (this.bufferIndex === 0 || (!padPartial && this.bufferIndex < 1600)) return;\n const pcm = new Int16Array(1600);\n for (let index = 0; index < this.bufferIndex; index += 1) {\n const sample = Math.max(-1, Math.min(1, this.buffer[index]));\n pcm[index] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;\n }\n this.port.postMessage(\n { type: 'frame', pcm: pcm.buffer, sequence: this.sequence++ },\n [pcm.buffer],\n );\n this.buffer.fill(0);\n this.bufferIndex = 0;\n }\n\n process(inputs, outputs) {\n for (const output of outputs) {\n for (const channel of output) channel.fill(0);\n }\n const channels = inputs[0];\n if (!channels?.length || !channels[0]?.length) return true;\n for (let frame = 0; frame < channels[0].length; frame += 1) {\n let sample = 0;\n for (let channel = 0; channel < channels.length; channel += 1) {\n sample += channels[channel][frame] || 0;\n }\n this.buffer[this.bufferIndex++] = sample / channels.length;\n if (this.bufferIndex === 1600) this.emitBlock();\n }\n return true;\n }\n}\nregisterProcessor('"+K+"', AgentPcmCaptureProcessor);\n",X=/*#__PURE__*/function(){function e(e){var t,n;this.stream=null,this.recordingStream=null,this.audioTransformer=null,this.mediaRecorder=null,this.pcmAudioContext=null,this.pcmSource=null,this.pcmWorklet=null,this.pcmEncoder=null,this.pcmEncodeQueue=Promise.resolve(),this.pcmStartedAt=0,this.pcmGeneration=0,this.resolvePcmFlush=null,this.startGeneration=0,this.starting=!1,this.hasAudioSessionCapture=!1,this.options=e,this.pendingInputStream=null!=(t=e.inputStream)?t:null,this.usesProvidedInput=Boolean(e.inputStream),this.metadata=h({},v,{chunkMs:(null==(n=e.audio)?void 0:n.chunkMs)||v.chunkMs})}var t=e.prototype;return t.getAudioMetadata=function(){return this.metadata},t.start=function(){try{var e=this;if(e.stream||e.starting)return Promise.resolve();var t=++e.startGeneration;return e.starting=!0,Promise.resolve(G(function(){return function(n,r){try{var i=function(){function n(n){function a(n){var r;function i(n){if(r)return n;var i=new C({onError:function(t){var n=t instanceof Error?t:new Error("16 kHz mono 音频处理失败");n.name="MediaRecorderError",null==e.options.onError||e.options.onError(n)}});return e.audioTransformer=i,Promise.resolve(i.start(a)).then(function(n){e.recordingStream=n,e.assertStartActive(t);var r=e.recordingStream.getAudioTracks()[0],i=null==r?void 0:r.getSettings();e.metadata=h({},e.metadata,{sampleRate:(null==i?void 0:i.sampleRate)||z,channels:(null==i?void 0:i.channelCount)||1}),e.startWebMRecorder(o),null==e.options.onMetadata||e.options.onMetadata(e.metadata)})}e.assertStartActive(t);var a=e.stream.getAudioTracks()[0];if(!a)throw new Error("麦克风未返回音频轨道");var s=function(){if(e.options.usePcmWebCodecs)return Promise.resolve(e.startPcmWebMRecorder(e.stream)).then(function(){e.assertStartActive(t),e.metadata=h({},e.metadata,{sampleRate:z,channels:1,chunkMs:100}),null==e.options.onMetadata||e.options.onMetadata(e.metadata),r=1})}();return s&&s.then?s.then(i):i(s)}e.assertStartActive(t);var s=function(){if(!e.stream){if(e.usesProvidedInput)throw r?e.cancelled():new Error("ASR 输入流已释放");return e.hasAudioSessionCapture=function(e){var t,n;void 0===e&&(e=navigator);var r=D(e);if(!r)return!1;var i=O.get(r),o=null!=(t=null==i?void 0:i.previousType)?t:r.type;return!!I(r,"play-and-record")&&(O.set(r,{count:(null!=(n=null==i?void 0:i.count)?n:0)+1,previousType:o}),!0)}(),Promise.resolve(i.getUserMedia({audio:{sampleRate:{ideal:z},channelCount:{ideal:1},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).then(function(t){e.stream=t})}}();return s&&s.then?s.then(a):a()}var r=e.pendingInputStream;e.stream=null!=r?r:null,e.pendingInputStream=null;var i=navigator.mediaDevices;if(!(e.stream||null!=i&&i.getUserMedia))throw new Error("当前浏览器不支持麦克风采集");var o=globalThis.MediaRecorder,a=function(){if(e.options.usePcmWebCodecs)return Promise.resolve(L.isSupported()).then(function(t){if(!t)throw e.webCodecsOpusUnsupported()});if(null==o||null==o.isTypeSupported||!o.isTypeSupported(j))throw e.webMOpusUnsupported()}();return a&&a.then?a.then(n):n()}()}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(n){var r=t!==e.startGeneration;return Promise.resolve(e.stop()).then(function(){var t=r?e.cancelled():n instanceof Error?n:new Error("麦克风启动失败");throw"AUDIO_FIXED_TRACK_CANCELLED"!==t.agentCode&&(null==e.options.onError||e.options.onError(t)),t})})},function(n,r){if(e.startGeneration===t&&(e.starting=!1),n)throw r;return r}))}catch(e){return Promise.reject(e)}},t.stop=function(){try{var e=this;e.startGeneration+=1,e.starting=!1;var t=G(function(){function t(){var t;e.recordingStream=null,e.stream&&!n&&e.stream.getTracks().forEach(function(e){return e.stop()}),e.stream=null,null==(t=e.pendingInputStream)||t.getTracks().forEach(function(e){return e.stop()}),e.pendingInputStream=null}var n=e.audioTransformer,r=G(function(){return Promise.resolve(null==n?void 0:n.drain()).then(function(){})},function(t,r){return Promise.resolve(e.stopPcmWebMRecorder()).then(function(){return Promise.resolve(e.stopMediaRecorder()).then(function(){return Promise.resolve(null==n?void 0:n.stop()).then(function(){if(e.audioTransformer=null,t)throw r;return r})})})});return r&&r.then?r.then(t):t()},function(t,n){if(e.hasAudioSessionCapture&&(e.hasAudioSessionCapture=!1,function(e){void 0===e&&(e=navigator);var t=D(e);if(!t)return!1;var n=O.get(t);if(!n)return function(e){void 0===e&&(e=navigator);var t=D(e);if(!t)return!1;var n=O.get(t);return I(t,null!=n&&n.count||"play-and-record"===t.type?"play-and-record":"playback")}(e);if(n.count-=1,n.count>0)return I(t,"play-and-record");O.delete(t);var r="play-and-record"===n.previousType?"play-and-record":"playback";I(t,r)&&"playback"===r&&function(e){var t=T.get(e);if(t)for(var n=0,r=[].concat(t);n<r.length;n++){var i=r[n];try{i()}catch(e){}}}(t)}()),t)throw n;return n});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.startWebMRecorder=function(e){var t,n=this;if(!this.recordingStream)throw new Error("16 kHz mono 音频流未就绪");try{t=new e(this.recordingStream,{mimeType:j,audioBitsPerSecond:24e3})}catch(e){if(e instanceof Error&&"NotSupportedError"===e.name)throw this.webMOpusUnsupported(e);throw e}var r=new F(this.metadata.chunkMs);t.ondataavailable=function(e){if(e.data.size>0){var i,o=r.resolve(e.timecode);null==(i=globalThis.avatarSDKLogger)||null==i.log||i.log("[Agent][Microphone]","audio chunk",{size:e.data.size,type:e.data.type,chunkMs:n.metadata.chunkMs,sampleRate:n.metadata.sampleRate,channels:n.metadata.channels,recorderState:t.state,timecode:e.timecode}),n.options.debugAudioChunks&&_("[Agent][Microphone] nearend WebM/Opus chunk",e.data,{chunkMs:n.metadata.chunkMs,sampleRate:n.metadata.sampleRate,channels:n.metadata.channels,recorderState:t.state,timecode:e.timecode}),n.options.onFrame(e.data,o)}},t.onerror=function(e){var t=e.error,r=new Error(t instanceof Error?t.message:"WebM/Opus 麦克风录制失败");r.name="MediaRecorderError",null==n.options.onError||n.options.onError(r)},this.mediaRecorder=t;try{t.start(this.metadata.chunkMs)}catch(e){if(e instanceof Error&&"NotSupportedError"===e.name)throw this.webMOpusUnsupported(e);throw e}},t.assertStartActive=function(e){if(e!==this.startGeneration)throw this.cancelled()},t.cancelled=function(){var e=new Error("麦克风启动已取消");return e.name="AbortError",e.agentCode="AUDIO_FIXED_TRACK_CANCELLED",e.retryable=!0,e},t.webMOpusUnsupported=function(e){var t=new Error("当前浏览器不支持 audio/webm;codecs=opus");return t.name="NotSupportedError",t.agentCode="AUDIO_WEBM_OPUS_UNSUPPORTED",t.retryable=!1,t.cause=e,t},t.webCodecsOpusUnsupported=function(e){var t=new Error("当前浏览器不支持 WebCodecs AudioEncoder Opus");return t.name="NotSupportedError",t.agentCode="AUDIO_WEBCODECS_OPUS_UNSUPPORTED",t.retryable=!1,t.cause=e,t},t.startPcmWebMRecorder=function(e){try{var t=this,n=globalThis,r=globalThis.AudioContext||n.webkitAudioContext;if(!r||void 0===globalThis.AudioWorkletNode)throw t.webCodecsOpusUnsupported(new Error("AudioWorklet 不可用"));var i=new L;return Promise.resolve(i.init()).then(function(){function n(n){function r(){function n(){if("running"!==o.state)throw t.audioContextSuspended();var n=o.createMediaStreamSource(e),r=new AudioWorkletNode(o,K,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1]}),a=++t.pcmGeneration;t.pcmSource=n,t.pcmWorklet=r,t.pcmEncodeQueue=Promise.resolve(),t.pcmStartedAt=t.monotonicEpochNow(),r.port.onmessage=function(e){var n,r;if("flushed"===(null==(n=e.data)?void 0:n.type))return null==t.resolvePcmFlush||t.resolvePcmFlush(),void(t.resolvePcmFlush=null);if("frame"===(null==(r=e.data)?void 0:r.type)&&e.data.pcm instanceof ArrayBuffer){var o=t.pcmStartedAt+100*Number(e.data.sequence||0),s=new Int16Array(e.data.pcm);t.pcmEncodeQueue=t.pcmEncodeQueue.then(function(){try{return Promise.resolve(i.encode(s)).then(function(n){if(a===t.pcmGeneration&&0!==n.byteLength){var r=new Blob([n],{type:j});t.options.debugAudioChunks&&_("[Agent][Microphone] nearend PCM/WebCodecs chunk",r,{chunkMs:100,sampleRate:z,channels:1,sequence:e.data.sequence}),t.options.onFrame(r,o)}})}catch(e){return Promise.reject(e)}}).catch(function(e){var n=e instanceof Error?e:new Error("PCM/Opus 麦克风编码失败");n.name="AudioEncoderError",null==t.options.onError||t.options.onError(n)})}},n.connect(r),r.connect(o.destination)}var r=function(){if("suspended"===o.state)return Promise.resolve(o.resume()).then(function(){})}();return r&&r.then?r.then(n):n()}t.pcmAudioContext=o,t.pcmEncoder=i;var a=URL.createObjectURL(new Blob([V],{type:"application/javascript"})),s=G(function(){return Promise.resolve(o.audioWorklet.addModule(a)).then(function(){})},function(e,t){if(URL.revokeObjectURL(a),e)throw t;return t});return s&&s.then?s.then(r):r()}var o=new r({sampleRate:z}),a=function(){if(o.sampleRate!==z)return Promise.resolve(i.destroy()).then(function(){return Promise.resolve(o.close().catch(function(){})).then(function(){throw t.webCodecsOpusUnsupported(new Error("浏览器无法创建 16000 Hz AudioContext"))})})}();return a&&a.then?a.then(n):n()})}catch(e){return Promise.reject(e)}},t.stopPcmWebMRecorder=function(){try{var e=function(){return Promise.resolve(t.pcmEncodeQueue).then(function(){function e(){return Promise.resolve(null==o?void 0:o.destroy()).then(function(){t.pcmWorklet=null,t.pcmSource=null,t.pcmAudioContext=null,t.pcmEncoder=null,t.pcmEncodeQueue=Promise.resolve()})}t.pcmGeneration+=1,t.resolvePcmFlush=null,n&&(n.port.onmessage=null,n.disconnect(),n.port.close());var r=function(){if(i&&"closed"!==i.state)return Promise.resolve(i.close().catch(function(){})).then(function(){})}();return r&&r.then?r.then(e):e()})},t=this,n=t.pcmWorklet,r=t.pcmSource,i=t.pcmAudioContext,o=t.pcmEncoder;if(!n&&!i&&!o)return Promise.resolve();null==r||r.disconnect();var a=function(){if(n)return Promise.resolve(Promise.race([new Promise(function(e){t.resolvePcmFlush=function(){return e(!0)},n.port.postMessage({type:"flush"})}),new Promise(function(e){return globalThis.setTimeout(function(){return e(!1)},100)})])).then(function(e){e||(t.resolvePcmFlush=null,n.port.onmessage=null)})}();return Promise.resolve(a&&a.then?a.then(e):e())}catch(e){return Promise.reject(e)}},t.monotonicEpochNow=function(){var e=globalThis.performance;return e&&Number.isFinite(e.timeOrigin)?Math.round(e.timeOrigin+e.now()):Date.now()},t.audioContextSuspended=function(){var e=new Error("AudioContext 未运行,请在用户操作后重试");return e.name="NotAllowedError",e.agentCode="AUDIO_CONTEXT_SUSPENDED",e.retryable=!0,e},t.stopMediaRecorder=function(){try{var e=this.mediaRecorder;if(this.mediaRecorder=null,!e)return Promise.resolve();var t="inactive"!==e.state;return Promise.resolve(new Promise(function(n){var r=!1,i=function(){r||(r=!0,globalThis.clearTimeout(a),n())},o=e.onerror,a=globalThis.setTimeout(i,1e3);if(e.onstop=i,e.onerror=function(t){null==o||o.call(e,t),i()},t)try{e.stop()}catch(e){i()}})).then(function(){e.ondataavailable=null,e.onerror=null,e.onstop=null})}catch(e){return Promise.reject(e)}},l(e,[{key:"isRecording",get:function(){return this.starting||Boolean(this.stream)||Boolean(this.pendingInputStream)}}])}(),H="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function q(e,t,n){if(!e.s){if(n instanceof J){if(!n.s)return void(n.o=q.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(q.bind(null,e,t),q.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var J=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var o=1&i?t:n;if(o){try{q(r,1,o(this.v))}catch(e){q(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?q(r,1,t?t(i):i):n?q(r,1,n(i)):q(r,2,i)}catch(e){q(r,2,e)}},r},e}();function Y(e){return e instanceof J&&1&e.s}var Q=function(e){try{var t,n=function(n){var r;if(t)return n;function i(t){return r?t:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var o=function(){if(e instanceof Blob)return Promise.resolve(e.arrayBuffer()).then(function(e){var t=new Uint8Array(e);return r=1,t})}();return o&&o.then?o.then(i):i(o)},r=function(){if(Array.isArray(e))return Promise.resolve(Promise.all(e.map(Q))).then(function(e){for(var n,r=new Uint8Array(e.reduce(function(e,t){return e+t.byteLength},0)),i=0,o=c(e);!(n=o()).done;){var a=n.value;r.set(a,i),i+=a.byteLength}return t=1,r})}();return Promise.resolve(r&&r.then?r.then(n):n(r))}catch(e){return Promise.reject(e)}},$=new Uint8Array([26,69,223,163]);function Z(e,t){var n=globalThis.avatarSDKLogger;null==n||null==n.log||n.log("[Agent][AudioUplink]",e,t)}var ee=/*#__PURE__*/function(){function e(e){this.connectionStartedAt=null,this.connectionGeneration=0,this.sendChain=Promise.resolve(),this.failed=!1,this.pendingFarend=new Map,this.pendingNearend=new Map,this.closedNearendBuckets=new Set,this.lastTimestampByStream=new Map,this.lastSentTimestampByStream=new Map,this.pendingWebmPrefixByStream=new Map,this.farendStreamState="unknown",this.options=e}var t=e.prototype;return t.reset=function(e){void 0===e&&(e=null),this.connectionGeneration+=1,this.connectionStartedAt=e,this.pendingFarend.clear(),this.pendingNearend.clear(),this.closedNearendBuckets.clear(),this.lastTimestampByStream.clear(),this.lastSentTimestampByStream.clear(),this.pendingWebmPrefixByStream.clear(),this.farendStreamState="unknown",this.failed=!1,this.sendChain=Promise.resolve()},t.startInput=function(){this.failed=!1,this.pendingFarend.clear(),this.pendingNearend.clear(),this.closedNearendBuckets.clear(),this.pendingWebmPrefixByStream.clear(),this.farendStreamState="unknown"},t.clearFarend=function(){this.pendingFarend.clear(),this.pendingWebmPrefixByStream.delete(2),this.farendStreamState="unknown"},t.offerFarend=function(e){var t;if(!1!==e.isFirstChunk||"ready"===this.farendStreamState){var n=this.normalizeBlock(2,e);if(n){e.isFirstChunk&&(this.pendingFarend.clear(),this.pendingWebmPrefixByStream.delete(2),this.farendStreamState="ready");var r=null!=(t=this.pendingFarend.get(n.frameKey))?t:[];r.push(n),this.pendingFarend.set(n.frameKey,r),Z("farend.offer",{tsMs:n.tsMs,frameKey:n.frameKey,isFirstChunk:Boolean(n.isFirstChunk),pendingNearend:[].concat(this.pendingNearend.keys())}),this.flushOlderNearend(n.frameKey),this.prune(n.frameKey)}else e.isFirstChunk&&this.abandonFarendStream()}else Z("farend.drop",{reason:"awaiting_webm_header",timestamp:e.timestamp,isFirstChunk:!1})},t.offerNearend=function(e){var t,n=this.normalizeBlock(1,e);if(n&&!this.closedNearendBuckets.has(n.frameKey)){var r=null!=(t=this.pendingNearend.get(n.frameKey))?t:[];r.push(n),this.pendingNearend.set(n.frameKey,r),this.flushExpiredNearend(n.frameKey),this.prune(n.frameKey)}},t.drain=function(){for(var e,t=c([].concat(this.pendingNearend.keys()).sort(function(e,t){return e-t}));!(e=t()).done;)this.flushBucket(e.value,!0);return this.sendChain},t.normalizeBlock=function(e,t){var n=this.connectionStartedAt;if(null===n||!Number.isFinite(t.timestamp))return null;var r=Math.max(0,Math.floor(t.timestamp-n)),i=Math.floor(r/100),o=this.lastTimestampByStream.get(e);return void 0!==o&&r<=o?null:(this.lastTimestampByStream.set(e,r),h({},t,{streamId:e,tsMs:r,frameKey:i}))},t.enqueue=function(e){var t=this,n=this;if(!this.failed){var r=this.connectionGeneration;this.sendChain=this.sendChain.then(function(){try{if(n.failed)return Promise.resolve();var t=function(e,t){if("function"==typeof e[H]){var n,r,i,o=function(e){try{for(;!(n=a.next()).done;)if((e=t(n.value))&&e.then){if(!Y(e))return void e.then(o,i||(i=q.bind(null,r=new J,2)));e=e.v}r?q(r,1,e):r=e}catch(e){q(r||(r=new J),2,e)}},a=e[H]();if(o(),a.return){var s=function(e){try{n.done||a.return()}catch(e){}return e};if(r&&r.then)return r.then(s,function(e){throw s(e)});s()}return r}if(!("length"in e))throw new TypeError("Object is not iterable");for(var u=[],l=0;l<e.length;l++)u.push(e[l]);return function(e,t){var n,r,i=-1;return function o(a){try{for(;++i<e.length;)if((a=t(i))&&a.then){if(!Y(a))return void a.then(o,r||(r=q.bind(null,n=new J,2)));a=a.v}n?q(n,1,a):n=a}catch(e){q(n||(n=new J),2,e)}}(),n}(u,function(e){return t(u[e])})}(e,function(e){var t;return Promise.resolve(Q(null!=(t=e.dataParts)?t:e.data)).then(function(t){if(!n.failed&&r===n.connectionGeneration&&null!==n.connectionStartedAt&&0!==t.byteLength){2===e.streamId&&e.isFirstChunk&&n.pendingWebmPrefixByStream.delete(2);var i=n.coalesceSplitWebmMagic(e.streamId,t);if(i){var o=n.lastSentTimestampByStream.get(e.streamId);void 0!==o&&e.tsMs<=o||(n.options.sendBinary(function(e,t,n){if(1!==e&&2!==e)throw new Error("AU stream_id 无效: "+e);if(!Number.isFinite(t)||t<0||t>4294967295)throw new Error("AU ts_ms 无效: "+t);var r=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength),i=new ArrayBuffer(8+r.byteLength),o=new DataView(i);return o.setUint8(0,65),o.setUint8(1,85),o.setUint8(2,1),o.setUint8(3,e),o.setUint32(4,Math.floor(t),!1),new Uint8Array(i,8).set(r),i}(e.streamId,e.tsMs,i)),n.lastSentTimestampByStream.set(e.streamId,e.tsMs),Z("frame.send",{streamId:e.streamId,tsMs:e.tsMs,bytes:i.byteLength}))}}})});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}).catch(function(e){if(r===t.connectionGeneration){t.failed=!0,t.pendingFarend.clear(),t.pendingNearend.clear();var n=e instanceof Error?e:new Error("AU 音频上行失败");null==t.options.onError||t.options.onError(n)}})}},t.coalesceSplitWebmMagic=function(e,t){var n=this.pendingWebmPrefixByStream.get(e);if(n){var r=new Uint8Array(n.byteLength+t.byteLength);r.set(n),r.set(t,n.byteLength),this.pendingWebmPrefixByStream.delete(e),t=r}return t.byteLength<$.byteLength&&t.every(function(e,t){return e===$[t]})?(this.pendingWebmPrefixByStream.set(e,t.slice()),null):t},t.flushOlderNearend=function(e){for(var t,n=c([].concat(this.pendingNearend.keys()).sort(function(e,t){return e-t}));!(t=n()).done;){var r=t.value;if(r>=e)break;this.flushBucket(r,!0)}},t.flushExpiredNearend=function(e){this.flushOlderNearend(e-1)},t.flushBucket=function(e,t){void 0===t&&(t=!1);var n=this.takeNearend(e);if(n){var r=e-1,i=this.pendingFarend.has(e)||t&&this.pendingFarend.has(r)?this.takeFarendThrough(e):null;this.closedNearendBuckets.add(e),Z("bucket.flush",{nearendFrameKey:e,pairedFarend:Boolean(i),pendingFarend:[].concat(this.pendingFarend.keys())}),this.enqueue(i?[i,n]:[n])}},t.takeNearend=function(e){var t=this.pendingNearend.get(e);return this.pendingNearend.delete(e),null!=t&&t.length?h({},t[0],{dataParts:t.flatMap(function(e){var t;return null!=(t=e.dataParts)?t:[e.data]})}):null},t.takeFarendThrough=function(e){for(var t,n=[],r=c([].concat(this.pendingFarend.keys()).sort(function(e,t){return e-t}));!(t=r()).done;){var i=t.value;if(i>e)break;n.push.apply(n,this.pendingFarend.get(i)),this.pendingFarend.delete(i)}return 0===n.length?null:h({},n[n.length-1],{dataParts:n.map(function(e){return e.data}),isFirstChunk:n.some(function(e){return e.isFirstChunk})})},t.abandonFarendStream=function(){Z("farend.drop",{reason:"stale_bucket_abandons_webm_stream",pendingFarend:[].concat(this.pendingFarend.keys())}),this.pendingFarend.clear(),this.pendingWebmPrefixByStream.delete(2),this.farendStreamState="awaiting-header"},t.prune=function(e){var t=e-3;[].concat(this.pendingFarend.keys()).some(function(e){return e<t})&&this.abandonFarendStream();for(var n,r=c(this.pendingNearend.keys());!(n=r()).done;){var i=n.value;i<t&&this.flushBucket(i,!0)}for(var o,a=c(this.closedNearendBuckets);!(o=a()).done;){var s=o.value;s<t&&this.closedNearendBuckets.delete(s)}},e}(),te=["e2eServer","authToken","audio","reconnect","agentCallbacks","webSocketCtor","asr_id","asr_config","tts_config","features","extras","llm_id","brain_config","session_speak_req_id"];function ne(e,t,n){if(!e.s){if(n instanceof re){if(!n.s)return void(n.o=ne.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(ne.bind(null,e,t),ne.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}const re=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,i=this.s;if(i){const e=1&i?t:n;if(e){try{ne(r,1,e(this.v))}catch(e){ne(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?ne(r,1,t?t(i):i):n?ne(r,1,n(i)):ne(r,2,i)}catch(e){ne(r,2,e)}},r},e}();function ie(e){return e instanceof re&&1&e.s}function oe(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function ae(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function se(e){if(void 0===e)return!1;var t=JSON.stringify(e);return void 0!==t&&"{}"!==t}var ue={1006:"E2E WebSocket 异常断开:未收到 Close frame,请检查 E2EMPServer 日志或中间网络",4e3:"E2E WebSocket 路径未知",4001:"E2E Token 无效",4002:"E2E Session 不存在",4009:"E2E 配额超限",4010:"E2E 服务端主动断开"},le=new Set([1001,1006,1011,1012,1013,1014]);function ce(e,t,n){if(void 0!==n&&(!n||Array.isArray(n)||"object"!=typeof n))throw new Error("Agent "+e+" JSON Config 必须是对象");if(void 0!==t&&se(n))throw new Error("Agent "+e+" 配置不能同时提供 ID 和 JSON Config")}function he(e,t){if(void 0!==t&&(!t||Array.isArray(t)||"object"!=typeof t))throw new Error("Agent "+e+" 必须是对象")}var de=/*#__PURE__*/function(e){function t(t){var n,r,i,o;ce("ASR",t.asr_id,t.asr_config),ce("TTS",void 0,t.tts_config),ce("Brain",t.llm_id,t.brain_config),he("features",t.features),he("extras",t.extras);var a,s=t.e2eServer,u=t.authToken,l=t.audio,c=t.reconnect,d=t.agentCallbacks,f=t.webSocketCtor,m=t.asr_id,p=t.asr_config,v=t.tts_config,E=t.features,g=t.extras,S=t.llm_id,y=t.brain_config,R=t.session_speak_req_id,A=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(t,te),b=A.onMessage,w=A.onRenderChange,C=A.onNetworkInfo,_=A.onSpeakStateChange,P=A.onVoiceStateChange,k=A.onAudioPlaybackData,O=function(e){var t;null==(t=a)||t.forwardFarendAudio(e),null==k||k(e)},T=null!=R?R:1,D=function(e){if(e&&se(e)){var t=e.extra_body;if(void 0!==t&&(!t||Array.isArray(t)||"object"!=typeof t))throw new Error("Agent Brain extra_body 必须是 JSON 对象");return h({},e)}}(y),I=h({},A,{session_speak_req_id:T,sessionRequestData:h({},void 0!==m?{asr_id:m}:{},se(p)?{asr_config:p}:{},se(v)?{tts_config:v}:{},se(E)?{features:E}:{},se(g)?{extras:g}:{},void 0!==S?{llm_id:S}:{},void 0!==D?{brain_config:D}:{},{session_speak_req_id:T}),enableClientInterrupt:null==(n=A.enableClientInterrupt)||n,onMessage:function(e){var t,n;b(e),null!=(t=a)&&t.reportingInitializationFailure||null==(n=a)||n.emitError("sdk",String(e.code||"AVATAR_ERROR"),e.message||"Avatar SDK 错误",!0,e)},onRenderChange:function(e){var t;null==w||w(e),null==(t=a)||t.safeEmit(function(){return null==d||null==d.onRenderChange?void 0:d.onRenderChange(e)})},onNetworkInfo:function(e){var t;null==C||C(e),null==(t=a)||t.safeEmit(function(){return null==d||null==d.onNetworkInfo?void 0:d.onNetworkInfo(e)})},onSpeakStateChange:function(e,t){var n,r,i;null==_||_(e,t),null==(n=a)||n.safeEmit(function(){return null==d||null==d.onSpeakStateChange?void 0:d.onSpeakStateChange({state:e,clientSpeakId:t})}),["speak_start","start","started"].includes(e)&&(null==(r=a)||r.emitConversation({state:"speaking"})),["speak_end","end","ended","completed","finish","finished"].includes(e)&&(null==(i=a)||i.emitConversation({state:"completed"}))},onVoiceStateChange:function(e,t,n){var r;"end"===e&&(null==(r=a)||r.forwardVoiceEnd()),null==P||P(e,t,n)}},k?{onAudioPlaybackData:O}:{});return(o=e.call(this,I)||this).e2eClient=null,o.microphone=null,o.stopASRPromise=null,o.initializationPromise=null,o.rejectInitialization=null,o.initialSessionAttempt=null,o.initialSessionGeneration=0,o.initialTtsaReadySessionIds=new Set,o.initialTtsaReadyBeforeSession=!1,o.asrStartGeneration=0,o.agentState="idle",o.asrState="idle",o.agentDestroyed=!1,o.agentDestroying=!1,o.destroyPromise=null,o.suppressNextVoiceEnd=!1,o.replaySending=!1,o.farendAudioEnabled=!1,o.reconnectTimer=null,o.reconnectAttempt=0,o.reconnectInFlight=!1,o.sessionReloadFallback=!1,o.waitingForTtsaReload=!1,o.stateBeforeReconnect="ready",o.reportingInitializationFailure=!1,o.handleOnlineForReconnect=function(){"reconnecting"!==o.agentState||o.reconnectInFlight||o.sessionReloadFallback||(o.clearReconnectTimer(),o.scheduleE2EReconnect(!0))},a=o,o.agentOptions={e2eServer:s,authToken:u,audio:l,requestedEnableAec:"boolean"==typeof(null==E||null==(r=E.speech_frontend)?void 0:r.enable_aec)?E.speech_frontend.enable_aec:void 0,callbacks:d,webSocketCtor:f,debugAudioChunks:Boolean(A.enableDebugger)},o.audioInputEnabled=null!=(i=null==l?void 0:l.inputEnabled)&&i,o.originalOnAudioPlaybackData=k,o.playbackDataHandler=O,o.reconnectOptions=o.normalizeReconnectOptions(c),o.audioUplink=new ee({sendBinary:function(e){var t;return null==(t=o.e2eClient)?void 0:t.sendBinary(e)},onError:function(e){return o.handleAudioUplinkError(e)}}),o}var n,i;i=e,(n=t).prototype=Object.create(i.prototype),n.prototype.constructor=n,d(n,i);var o=t.prototype;return o.getAgentState=function(){return this.agentState},o.getState=function(){return this.getAgentState()},o.getASRState=function(){return this.asrState},o.init=function(e){var t=this;if(void 0===e&&(e={}),this.initializationPromise)return this.initializationPromise;var n=this.initialize(e).finally(function(){t.initializationPromise===n&&(t.initializationPromise=null)});return this.initializationPromise=n,n},o.initialize=function(t){try{var n=this;n.assertNotDestroyed(),n.setAgentState("initializing");var r=new Promise(function(e,t){n.rejectInitialization=t});return r.catch(function(){}),Promise.resolve(ae(function(){return oe(function(){var i=h({},t,{onDownloadProgress:t.onDownloadProgress||function(){}});return Promise.resolve(e.prototype.initializeSession.call(n,i)).then(function(e){var t;function i(e){n.assertNotDestroyed(),n.assertE2EOpen(),n.setAgentState("ready"),n.start()}if(n.assertNotDestroyed(),!e)throw new Error("XmovAvatar 初始化未返回 sessionInfo");n.applySessionFeatures(e),n.assertNotDestroyed(),n.beginInitialSession(e);var o=function(e,t,n){for(var r;;){var i=e();if(ie(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!ie(o)){r=1;break}o=o.s}}var a=new re,s=ne.bind(null,a,2);return(0===r?i.then(l):1===r?o.then(u):(void 0).then(function(){(i=e())?i.then?i.then(l).then(void 0,s):l(i):ne(a,1,o)})).then(void 0,s),a;function u(t){o=t;do{if(!(i=e())||ie(i)&&!i.v)return void ne(a,1,o);if(i.then)return void i.then(l).then(void 0,s);ie(o=n())&&(o=o.v)}while(!o||!o.then);o.then(u).then(void 0,s)}function l(e){e?(o=n())&&o.then?o.then(u).then(void 0,s):u(o):ne(a,1,o)}}(function(){return!t},0,function(){var e=n.initialSessionAttempt;if(!e)throw new Error("Agent 初始化缺少会话连接任务");return Promise.resolve(Promise.race([Promise.all([e.e2ePromise,e.ttsaReadyPromise]),r])).then(function(){e===n.initialSessionAttempt&&(t=1)})});return o&&o.then?o.then(i):i()})},function(e){function t(){throw e}var r=function(){var t;if(!n.agentDestroyed&&!n.agentDestroying)return null==(t=n.e2eClient)||t.disconnect(1e3,"agent_init_failed"),n.e2eClient=null,Promise.resolve(n.cleanupBeforeInitComplete("agent_init_failed")).then(function(){try{n.setAgentState("failed")}catch(e){}n.reportingInitializationFailure=!0;try{n.reportInitializationFailure("Agent 初始化失败",e)}catch(e){}finally{n.reportingInitializationFailure=!1}try{n.emitError("sdk","AGENT_INIT_FAILED","Agent 初始化失败",!0,e)}catch(e){}n.agentDestroyed=!0})}();return r&&r.then?r.then(t):t()})},function(e,t){var r;if(n.rejectInitialization=null,n.initialSessionGeneration+=1,null==(r=n.initialSessionAttempt)||r.resolveTtsaReady(),n.initialSessionAttempt=null,n.initialTtsaReadySessionIds.clear(),n.initialTtsaReadyBeforeSession=!1,e)throw t;return t}))}catch(e){return Promise.reject(e)}},o.beginInitialSession=function(e){var t=this,n=this.initialSessionAttempt,r=++this.initialSessionGeneration;null==n||n.resolveTtsaReady();var i=function(){},o=new Promise(function(e){i=e}),a=this.replaceE2EConnection(e.e2e_resp).catch(function(e){if(r===t.initialSessionGeneration)throw e}),s={sessionInfo:e,e2ePromise:a,ttsaReadyPromise:o,resolveTtsaReady:i};return this.initialSessionAttempt=s,this.initialTtsaReadySessionIds.delete(e.session_id)?s.resolveTtsaReady():!n&&this.initialTtsaReadyBeforeSession&&(this.initialTtsaReadyBeforeSession=!1,s.resolveTtsaReady()),a.catch(function(){}),a},o.start=function(){var t;"initializing"!==this.agentState&&"running"!==this.agentState&&("reconnecting"!==this.agentState?(this.assertE2EOpen(),e.prototype.start.call(this),this.setAgentState("running")):this.waitingForTtsaReload&&null!=(t=this.e2eClient)&&t.isOpen&&("running"===this.stateBeforeReconnect&&e.prototype.start.call(this),this.finishReconnect()))},o.onTtsaReady=function(t){if(this.rejectInitialization){var n=this.initialSessionAttempt,r=null==t?void 0:t.session_id;!n||r&&n.sessionInfo.session_id!==r?r?this.initialTtsaReadySessionIds.add(r):this.initialTtsaReadyBeforeSession=!0:n.resolveTtsaReady()}else"reconnecting"!==this.agentState?"running"===this.agentState&&e.prototype.start.call(this):this.start()},o.abortInitialization=function(e){var t;null==(t=this.rejectInitialization)||t.call(this,e)},o.stop=function(){try{var t=this;if(t.agentDestroyed)return Promise.resolve();var n="reconnecting"===t.agentState;return n&&(t.stateBeforeReconnect="stopped"),Promise.resolve(t.stopASR()).then(function(){return Promise.resolve(e.prototype.stop.call(t)).then(function(){n||t.setAgentState("stopped")})})}catch(e){return Promise.reject(e)}},o.switchInvisibleMode=function(){try{var t=this,n=t.getStatus(),i=n===r.online||n===r.visible;e.prototype.switchInvisibleMode.call(t);var o=function(){if(i)return Promise.resolve(t.stopASR()).then(function(){})}();return Promise.resolve(o&&o.then?o.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},o.destroy=function(e){var t=this;return void 0===e&&(e="js_sdk_exit"),this.destroyPromise?this.destroyPromise:this.agentDestroyed?("destroyed"!==this.agentState&&this.setAgentState("destroyed"),Promise.resolve()):(this.agentDestroying=!0,this.destroyPromise=Promise.resolve().then(function(){return t.finishDestroy(e)}),this.destroyPromise)},o.finishDestroy=function(e){try{var t=function(){function t(){var t=ae(function(){return Promise.resolve(n.disconnectClientForDestroy(e)).then(function(){})},function(e,t){if(n.agentDestroyed=!0,n.agentDestroying=!1,n.setAgentState("destroyed"),e)throw t;return t});if(t&&t.then)return t.then(function(){})}var r=n.e2eClient,i=ae(function(){return Promise.resolve(null==r?void 0:r.disconnectAndWait(1e3,e)).then(function(){})},function(e,t){if(n.e2eClient===r&&(n.e2eClient=null),n.audioUplink.reset(),e)throw t;return t});return i&&i.then?i.then(t):t()},n=this;n.abortInitialization(new Error("Agent 初始化已取消")),n.cancelReconnect(),n.cancelSessionRestart();var r=oe(function(){return Promise.resolve(n.stopASR()).then(function(){})},function(e){n.emitError("sdk","AGENT_ASR_STOP_FAILED","Agent 销毁时停止 ASR 失败",!1,e)});return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},o.ask=function(e){try{var t=this;return t.assertRunning(),t.suppressNextVoiceEnd=!1,t.emitConversation({state:"asking",text:e}),t.sendControl({type:"ask",message:{text:e}}),Promise.resolve()}catch(e){return Promise.reject(e)}},o.speak=function(t,n,r){if(void 0===n&&(n=!0),void 0===r&&(r=!0),this.replaySending)return r&&(this.suppressNextVoiceEnd=!0),e.prototype.speak.call(this,t,n,r,arguments[3]);this.assertRunning(),this.suppressNextVoiceEnd=!1,n&&this.emitConversation({state:"speaking-directly",text:t}),this.sendControl({type:"speak",message:{text:t,is_start:n,is_end:r}})},o.handleReplaySend=function(t){var n=this.replaySending;this.replaySending=!0;try{e.prototype.handleReplaySend.call(this,t)}finally{this.replaySending=n}},o.speakByE2E=function(e){try{return this.speak(e),Promise.resolve()}catch(e){return Promise.reject(e)}},o.startASR=function(e){void 0===e&&(e={});try{var t=function(){var t;if(null==(t=n.microphone)||!t.isRecording){n.assertAudioChunkDuration();var r=e.inputStream?n.cloneASRInputStream(e.inputStream):void 0,i=++n.asrStartGeneration,o=!n.audioInputEnabled,a=new X({audio:n.agentOptions.audio,debugAudioChunks:n.agentOptions.debugAudioChunks,inputStream:r,usePcmWebCodecs:n.farendAudioEnabled,onFrame:function(e,t){var r;if("running"===n.agentState&&null!=(r=n.e2eClient)&&r.isOpen)try{var i;n.sendAudioFrame({data:e,timestamp:null!=t?t:Date.now()-((null==(i=n.agentOptions.audio)?void 0:i.chunkMs)||v.chunkMs)})}catch(e){n.stopASRAfterSocketClose()}},onError:function(e){return n.handleMicrophoneError(a,e)}});return n.microphone=a,oe(function(){return n.audioUplink.startInput(),o&&n.enableAudioInput(),n.emitConversation({state:"asking"}),n.assertASRStartActive(i),n.setASRState("requesting-permission"),n.assertASRStartActive(i),n.setASRState("starting"),n.assertASRStartActive(i),Promise.resolve(a.start()).then(function(){n.assertRunning(),n.farendAudioEnabled&&n.restartAudioPlaybackCapture(),n.setASRState("listening")})},function(e){return Promise.resolve(a.stop()).then(function(){var t,r,s="AUDIO_FIXED_TRACK_CANCELLED"===(null==e?void 0:e.agentCode),u=i===n.asrStartGeneration,l=!n.agentDestroyed&&!n.agentDestroying&&"running"===n.agentState&&Boolean(null==(t=n.e2eClient)?void 0:t.isOpen);if(n.microphone===a&&(n.microphone=null),u&&!s&&o&&null!=(r=n.e2eClient)&&r.isOpen)try{n.disableAudioInput()}catch(e){}throw!u||n.agentDestroyed||n.agentDestroying||(s&&l?n.setASRState("idle"):s||n.setASRState("failed")),s&&!l&&n.assertRunning(),e})})}},n=this;n.assertASRStartAllowed(),n.suppressNextVoiceEnd=!1;var r=function(){if(n.stopASRPromise)return Promise.resolve(n.stopASRPromise).then(function(){n.assertASRStartAllowed()})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},o.cloneASRInputStream=function(e){var t=e.getAudioTracks().find(function(e){return"ended"!==e.readyState});if(!t)throw new Error("ASR 输入流不包含有效音频轨道");return new MediaStream([t.clone()])},o.assertASRStartActive=function(e){if(e!==this.asrStartGeneration){var t=new Error("麦克风启动已取消");throw t.name="AbortError",t.agentCode="AUDIO_FIXED_TRACK_CANCELLED",t.retryable=!0,t}},o.stopASR=function(){var e=this;if(this.asrStartGeneration+=1,this.stopASRPromise)return this.stopASRPromise;var t,n=this.microphone;return null!=n&&n.isRecording?(this.microphone=null,this.stopASRPromise=this.finishStopASR(n).finally(function(){e.stopASRPromise=null}),this.stopASRPromise):(null!=(t=this.e2eClient)&&t.isOpen&&this.disableAudioInput(),Promise.resolve())},o.finishStopASR=function(e,t){void 0===t&&(t=!0);try{var n=this;return n.setASRState("stopping"),Promise.resolve(e.stop()).then(function(){return Promise.resolve(n.audioUplink.drain()).then(function(){t?(n.disableAudioInput(),n.setASRState("idle")):n.setASRState("failed")})})}catch(e){return Promise.reject(e)}},o.interrupt=function(){if(this.agentDestroyed)return 0;this.sendControl({type:"interrupt"});var t=e.prototype.interrupt.call(this,"speak");return this.emitConversation({state:"interrupted"}),t},o.interruptConversation=function(e){void 0===e&&(e="user");try{return this.interrupt(),Promise.resolve()}catch(e){return Promise.reject(e)}},o.onSessionReloaded=function(e){try{var t,n=function(n){return t?n:("reconnecting"!==r.agentState&&(r.stateBeforeReconnect=r.readRestorableState(),r.setAgentState("reconnecting")),r.clearReconnectTimer(),r.sessionReloadFallback=!0,r.applySessionFeatures(e),Promise.resolve(r.replaceE2EConnection(e.e2e_resp)).then(function(){r.waitingForTtsaReload=!0,r.sessionReloadFallback=!1}))},r=this;if(r.agentDestroyed||r.agentDestroying)return Promise.resolve();var i=function(){if(r.initializationPromise&&"initializing"===r.agentState)return r.applySessionFeatures(e),Promise.resolve(r.beginInitialSession(e)).then(function(){t=1})}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(e){return Promise.reject(e)}},o.onSessionReloadExhausted=function(e){this.rejectInitialization?this.abortInitialization(e instanceof Error?e:new Error("Agent 初始化期间 TTSA Session 恢复失败")):"reconnecting"===this.agentState&&this.failReconnect(e)},o.replaceE2EConnection=function(e){try{var t,n=this,r=n.resolveE2EConnection(e),i=r.wsUrl,o=r.token,a=n.e2eClient;return n.audioUplink.reset(),t=new p({wsUrl:i,token:o,audioInputEnabled:n.audioInputEnabled,WebSocketCtor:n.agentOptions.webSocketCtor,onStateChange:function(e){n.e2eClient===t&&("open"===e&&n.audioUplink.reset(Date.now()),n.safeEmit(function(){var t;return null==(t=n.agentOptions.callbacks)||null==t.onSocketStateChange?void 0:t.onSocketStateChange(e)}))},onEvent:function(e){n.e2eClient===t&&n.handleServerEvent(e)},onError:function(e){n.e2eClient===t&&"initializing"!==n.agentState&&"reconnecting"!==n.agentState&&n.emitError("network","E2E_SOCKET_ERROR",e.message,!0,e)},onClose:function(e){n.e2eClient===t&&n.handleSocketClose(e)}}),n.e2eClient=t,null==a||a.disconnect(1e3,"e2e_connection_replaced"),Promise.resolve(t.connect()).then(function(){})}catch(e){return Promise.reject(e)}},o.resolveE2EConnection=function(e){var t=Boolean(null==e?void 0:e.ws_url),n=Boolean(null==e?void 0:e.e2e_token);if(t!==n)throw new Error("统一 session 响应的 e2e_resp 必须同时返回 ws_url 和 e2e_token");if(t&&n)return{wsUrl:null==e?void 0:e.ws_url,token:null==e?void 0:e.e2e_token};var r=Boolean(this.agentOptions.e2eServer);if(r!==Boolean(this.agentOptions.authToken))throw new Error("e2eServer 和 authToken 必须同时配置");if(!r)throw new Error("统一 session 响应未返回 e2e_resp.ws_url,且未配置 e2eServer");return{wsUrl:this.agentOptions.e2eServer,token:this.agentOptions.authToken}},o.sendControl=function(e){try{var t;null==(t=this.e2eClient)||t.send(e)}catch(e){throw this.emitError("network","E2E_SEND_FAILED","E2E WebSocket 发送失败",!0,e),e}},o.assertAudioChunkDuration=function(){var e,t=(null==(e=this.agentOptions.audio)?void 0:e.chunkMs)||v.chunkMs;if(this.farendAudioEnabled&&t!==v.chunkMs){var n=new Error("AU v1 音频分片固定为 100ms");throw n.name="NotSupportedError",n.agentCode="AUDIO_CHUNK_DURATION_UNSUPPORTED",n.retryable=!1,this.emitError("sdk",n.agentCode,n.message,n.retryable,n),n}},o.sendAudioFrame=function(e){if(this.farendAudioEnabled)this.agentOptions.debugAudioChunks&&_("[Agent][E2E] nearend AU chunk",e.data,{timestamp:e.timestamp,stream_id:1}),this.audioUplink.offerNearend(e);else{this.agentOptions.debugAudioChunks&&_("[Agent][E2E] nearend raw WebM/Opus chunk",e.data,{timestamp:e.timestamp});try{var t;null==(t=this.e2eClient)||t.sendBinary(e.data)}catch(e){this.handleAudioUplinkError(e instanceof Error?e:new Error("E2E nearend 音频帧发送失败"))}}},o.handleAudioUplinkError=function(e){var t=this;this.emitError("network","E2E_AUDIO_SEND_FAILED",this.farendAudioEnabled?"E2E AU 音频帧发送失败":"E2E 音频帧发送失败",!0,e);var n=this.microphone;if(null!=n&&n.isRecording&&!this.stopASRPromise){this.setASRState("failed"),this.microphone=null;var r=this.finishFailedASR(n).finally(function(){t.stopASRPromise===r&&(t.stopASRPromise=null)});this.stopASRPromise=r}},o.applySessionFeatures=function(e){var t,n,r,i,o,a,s=null!=(t=null==(n=e.e2e_resp)||null==(n=n.features)||null==(n=n.speech_frontend)?void 0:n.enable_aec)?t:null==(r=e.features)||null==(r=r.speech_frontend)?void 0:r.enable_aec;if(this.farendAudioEnabled="boolean"==typeof s?s:null!=(i=null!=(o=this.agentOptions.requestedEnableAec)?o:null==(a=this.agentOptions.audio)?void 0:a.echoCancellationEnabled)&&i,this.farendAudioEnabled||this.audioUplink.clearFarend(),this.farendAudioEnabled||this.originalOnAudioPlaybackData)return this.setAudioPlaybackDataHandler(this.playbackDataHandler),void(this.farendAudioEnabled&&this.enableAudioPlaybackCapture());this.setAudioPlaybackDataHandler(void 0)},o.forwardFarendAudio=function(e){var t,n,r,i=Boolean(null==(t=this.microphone)?void 0:t.isRecording),o=Boolean(null==(n=this.e2eClient)?void 0:n.isOpen);this.farendAudioEnabled&&i&&o?(this.agentOptions.debugAudioChunks&&_("[Agent][E2E] farend AU chunk",e.data,{timestamp:e.timestamp,stream_id:2,codec:e.codec,sampleRate:e.sampleRate,channels:1,samples:e.samples,speech_id:e.speech_id,isFirstChunk:e.isFirstChunk}),this.audioUplink.offerFarend({data:e.data,timestamp:e.timestamp,isFirstChunk:e.isFirstChunk})):null==(r=globalThis.avatarSDKLogger)||null==r.log||r.log("[Agent][AudioUplink]","farend.drop",{reason:this.farendAudioEnabled?i?"e2e_not_open":"microphone_not_recording":"aec_disabled",timestamp:e.timestamp,isFirstChunk:e.isFirstChunk})},o.handleMicrophoneError=function(e,t){var n,r=this,i=t,o="MediaRecorderError"===t.name,a="AudioEncoderError"===t.name,s=o||a,u="NotSupportedError"===t.name,l=Boolean(i.agentCode);if(s&&this.microphone===e&&"stopping"!==this.asrState){this.microphone=null;var c=this.finishFailedASR(e).finally(function(){r.stopASRPromise===c&&(r.stopASRPromise=null)});this.stopASRPromise=c}this.emitError(s?"asr":l||u?"sdk":"permission",i.agentCode||(o?"MEDIA_RECORDER_ERROR":a?"AUDIO_ENCODER_ERROR":"MICROPHONE_ERROR"),t.message,null!=(n=i.retryable)?n:!u,t)},o.finishFailedASR=function(e){try{var t=function(){try{n.disableAudioInput()}catch(e){}},n=this,r=oe(function(){return Promise.resolve(e.stop()).then(function(){return Promise.resolve(n.audioUplink.drain()).then(function(){})})},function(e){n.emitError("sdk","MICROPHONE_CLEANUP_FAILED","麦克风异常后的资源清理失败",!1,e)});return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},o.enableAudioInput=function(){var e;this.audioInputEnabled||(this.sendControl({type:"event",message:"audio_input_on"}),this.audioInputEnabled=!0,null==(e=this.e2eClient)||e.setAudioInputEnabled(!0))},o.disableAudioInput=function(){var e;this.audioInputEnabled&&(this.sendControl({type:"event",message:"audio_input_off"}),this.audioInputEnabled=!1,null==(e=this.e2eClient)||e.setAudioInputEnabled(!1))},o.handleServerEvent=function(e){if(!this.agentDestroyed&&!this.agentDestroying)switch(e.type){case"pong":default:return;case"asr_result":return void this.handleASRResult(e);case"llm_response":return void this.handleLLMResponse(e);case"semantic_judge_round_result":return void this.handleSemanticJudgeResult(e);case"error":return void this.handleBackendError(e)}},o.handleASRResult=function(e){var t=this,n={text:"string"==typeof e.text?e.text:"",isFinal:!0===e.is_final,raw:e};this.safeEmit(function(){var e;return null==(e=t.agentOptions.callbacks)||null==e.onASRResult?void 0:e.onASRResult(n)})},o.handleLLMResponse=function(e){var t=this;if("chunk"===e.event||"done"===e.event){var n=e.usage,r=h({event:e.event},"string"==typeof e.text?{text:e.text}:{},!0===e.is_first?{isFirst:!0}:{},n?{usage:{promptTokens:this.readFiniteNumber(n.prompt_tokens),completionTokens:this.readFiniteNumber(n.completion_tokens),totalTokens:this.readFiniteNumber(n.total_tokens),cachedTokens:this.readFiniteNumber(n.cached_tokens)}}:{},{raw:e});this.safeEmit(function(){var e;return null==(e=t.agentOptions.callbacks)||null==e.onLLMResponse?void 0:e.onLLMResponse(r)})}},o.handleSemanticJudgeResult=function(e){var t=this;if(e.message&&"object"==typeof e.message){var n=e.message,r={query:"string"==typeof n.query?n.query:"",meaningful:!0===n.meaningful,action:"string"==typeof n.action?n.action:"",raw:e};this.safeEmit(function(){var e;return null==(e=t.agentOptions.callbacks)||null==e.onSemanticJudgeResult?void 0:e.onSemanticJudgeResult(r)})}},o.forwardVoiceEnd=function(){var e;if(this.suppressNextVoiceEnd)this.suppressNextVoiceEnd=!1;else if(!this.agentDestroyed&&!this.agentDestroying&&"running"===this.agentState&&null!=(e=this.e2eClient)&&e.isOpen)try{this.sendControl({type:"event",message:"voice_end"})}catch(e){}},o.readFiniteNumber=function(e){return"number"==typeof e&&Number.isFinite(e)?e:0},o.handleBackendError=function(e){var t,n=["permission","network","asr","brain","ttsa","quota","sdk"].includes(e.domain)?e.domain:"sdk",r=String(null!=(t=e.code)?t:"BACKEND_ERROR"),i="string"==typeof e.message?e.message:"E2E 后端错误";"asr"===n&&this.stopASRAfterSocketClose(),this.emitConversation({state:"failed"}),this.emitError(n,r,i,"quota"!==n,e)},o.handleSocketClose=function(e){if(!this.agentDestroyed&&!this.agentDestroying)if(this.rejectInitialization)this.abortInitialization(new Error(("Agent 初始化期间 E2E WebSocket 已关闭: "+e.code+" "+(e.reason||"")).trim()));else if(this.audioUplink.reset(),this.stopASRAfterSocketClose(),this.shouldReconnect(e))this.beginReconnect(e);else{this.setAgentState("failed");var t=4009===e.code?"quota":"network";this.emitError(t,"E2E_CLOSE_"+e.code,e.reason||ue[e.code]||"E2E WebSocket 已关闭","quota"!==t,{code:e.code,reason:e.reason,wasClean:e.wasClean})}},o.shouldReconnect=function(e){return this.reconnectOptions.enabled&&"idle"!==this.agentState&&"initializing"!==this.agentState&&"destroyed"!==this.agentState&&le.has(e.code)},o.beginReconnect=function(e){var t;"reconnecting"!==this.agentState&&(this.stateBeforeReconnect=this.readRestorableState(),this.reconnectAttempt=0,this.sessionReloadFallback=!1,this.setAgentState("reconnecting"),null==globalThis.addEventListener||globalThis.addEventListener("online",this.handleOnlineForReconnect),this.emitError("network","E2E_RECONNECTING","E2E WebSocket 已断开,正在重连",!0,{code:e.code,reason:e.reason,wasClean:e.wasClean})),this.audioInputEnabled=!1,null==(t=this.e2eClient)||t.setAudioInputEnabled(!1),this.scheduleE2EReconnect(!1)},o.scheduleE2EReconnect=function(e){var t=this;if(!(this.agentDestroyed||this.agentDestroying||"reconnecting"!==this.agentState||null!==this.reconnectTimer||this.reconnectInFlight||this.sessionReloadFallback))if(this.reconnectAttempt>=this.reconnectOptions.maxAttempts)this.fallbackToSessionReload();else{var n=e?0:this.getReconnectDelay(this.reconnectAttempt);this.reconnectTimer=globalThis.setTimeout(function(){t.reconnectTimer=null,t.attemptE2EReconnect()},n)}},o.attemptE2EReconnect=function(){try{var e=this,t=e.e2eClient;if(!t||e.agentDestroyed||e.agentDestroying||"reconnecting"!==e.agentState)return Promise.resolve();e.reconnectInFlight=!0,e.reconnectAttempt+=1;var n=ae(function(){return oe(function(){return Promise.resolve(t.connect()).then(function(){e.e2eClient!==t||e.agentDestroyed||e.agentDestroying||e.waitingForTtsaReload||e.finishReconnect()})},function(){e.e2eClient!==t||e.agentDestroyed||e.agentDestroying||e.scheduleE2EReconnect(!1)})},function(n,r){if(e.reconnectInFlight=!1,e.e2eClient!==t||"reconnecting"!==e.agentState||null!==e.reconnectTimer||e.sessionReloadFallback||e.scheduleE2EReconnect(!1),n)throw r;return r});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},o.fallbackToSessionReload=function(){try{var e=this;if(e.sessionReloadFallback||e.agentDestroyed||e.agentDestroying)return Promise.resolve();e.sessionReloadFallback=!0,e.clearReconnectTimer();var t=oe(function(){return Promise.resolve(e.restartSessionForTransport("e2e_reconnect_exhausted")).then(function(){})},function(t){e.failReconnect(t)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},o.finishReconnect=function(){var e=this.stateBeforeReconnect;this.cancelReconnect(),"idle"!==this.asrState&&this.setASRState("idle"),this.setAgentState(e)},o.failReconnect=function(e){this.cancelReconnect(),this.setAgentState("failed"),this.emitConversation({state:"failed"}),this.emitError("network","E2E_RECONNECT_EXHAUSTED","E2E WebSocket 重连失败,请重新初始化 Agent",!1,e)},o.cancelReconnect=function(){this.clearReconnectTimer(),null==globalThis.removeEventListener||globalThis.removeEventListener("online",this.handleOnlineForReconnect),this.reconnectAttempt=0,this.reconnectInFlight=!1,this.sessionReloadFallback=!1,this.waitingForTtsaReload=!1},o.clearReconnectTimer=function(){null!==this.reconnectTimer&&(globalThis.clearTimeout(this.reconnectTimer),this.reconnectTimer=null)},o.getReconnectDelay=function(e){var t=Math.min(this.reconnectOptions.maxDelayMs,this.reconnectOptions.initialDelayMs*Math.pow(2,e));return 0===t?0:Math.round(t*(.8+.4*Math.random()))},o.readRestorableState=function(){return"running"===this.agentState||"stopped"===this.agentState||"ready"===this.agentState?this.agentState:"ready"},o.normalizeReconnectOptions=function(e){var t,n=this.readNonNegativeNumber(null==e?void 0:e.initialDelayMs,500);return{enabled:null==(t=null==e?void 0:e.enabled)||t,maxAttempts:Math.max(1,Math.floor(this.readNonNegativeNumber(null==e?void 0:e.maxAttempts,6))),initialDelayMs:n,maxDelayMs:Math.max(n,this.readNonNegativeNumber(null==e?void 0:e.maxDelayMs,8e3))}},o.readNonNegativeNumber=function(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:t},o.stopASRAfterSocketClose=function(){var e=this;if(this.asrStartGeneration+=1,!this.stopASRPromise){var t=this.microphone;null!=t&&t.isRecording&&(this.microphone=null,this.stopASRPromise=this.finishStopASR(t,!1).catch(function(t){e.emitError("sdk","MICROPHONE_CLEANUP_FAILED","WebSocket 断开后清理麦克风失败",!1,t)}).finally(function(){e.stopASRPromise=null}))}},o.setAgentState=function(e){var t;this.agentState=e,this.agentDestroyed&&"destroyed"!==e||null==(t=this.agentOptions.callbacks)||null==t.onAgentStateChange||t.onAgentStateChange(e)},o.setASRState=function(e){var t=this;this.asrState=e,this.safeEmit(function(){var n;return null==(n=t.agentOptions.callbacks)||null==n.onASRStateChange?void 0:n.onASRStateChange(e)})},o.emitConversation=function(e){var t=this;this.safeEmit(function(){var n;return null==(n=t.agentOptions.callbacks)||null==n.onConversationChange?void 0:n.onConversationChange(e)})},o.emitError=function(e,t,n,r,i){var o=this,a={domain:e,code:t,message:n,retryable:r,cause:i};"asr"===e&&this.setASRState("failed"),this.safeEmit(function(){var e;return null==(e=o.agentOptions.callbacks)||null==e.onError?void 0:e.onError(a)})},o.safeEmit=function(e){this.agentDestroyed||this.agentDestroying||e()},o.assertRunning=function(){if(this.assertE2EOpen(),"running"!==this.agentState)throw new Error("Agent 尚未启动,请先调用 start()")},o.assertASRStartAllowed=function(){if(this.assertRunning(),this.getStatus()===r.invisible)throw new Error("数字人处于隐身状态,无法启动 ASR,请先退出隐身模式")},o.assertE2EOpen=function(){var e;if(this.assertNotDestroyed(),null==(e=this.e2eClient)||!e.isOpen)throw new Error("Agent 尚未连接 E2E WebSocket")},o.assertNotDestroyed=function(){if(this.agentDestroyed||this.agentDestroying)throw new Error("Agent 已销毁")},t}(a.default);return de});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("@xmov/avatar")):"function"==typeof define&&define.amd?define(["@xmov/avatar"],t):(e||self).XingyunAvatarAgentModule=t(e.XmovAvatar)}(this,function(e){function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n,r,i,o,a=/*#__PURE__*/t(e);function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function u(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,f(r.key),r)}}function c(e,t,n){return t&&u(e.prototype,t),n&&u(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return s(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function h(){return h=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h.apply(null,arguments)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function f(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}!function(e){e[e.CONTAINER_NOT_FOUND=10001]="CONTAINER_NOT_FOUND",e[e.CONNECT_SOCKET_ERROR=10002]="CONNECT_SOCKET_ERROR",e[e.START_SESSION_ERROR=10003]="START_SESSION_ERROR",e[e.STOP_SESSION_ERROR=10004]="STOP_SESSION_ERROR",e[e.INIT_ERROR=10005]="INIT_ERROR",e[e.SOCKET_QUIT=10006]="SOCKET_QUIT",e[e.SOCKET_DISCONNECT=10007]="SOCKET_DISCONNECT",e[e.VIDEO_FRAME_EXTRACT_ERROR=20001]="VIDEO_FRAME_EXTRACT_ERROR",e[e.INIT_WORKER_ERROR=20002]="INIT_WORKER_ERROR",e[e.PROCESS_VIDEO_STREAM_ERROR=20003]="PROCESS_VIDEO_STREAM_ERROR",e[e.FACE_PROCESSING_ERROR=20004]="FACE_PROCESSING_ERROR",e[e.RENDER_BODY_ERROR=20005]="RENDER_BODY_ERROR",e[e.RENDER_FACE_ERROR=20006]="RENDER_FACE_ERROR",e[e.WebGL_RENDER_ERROR=20007]="WebGL_RENDER_ERROR",e[e.RENDER_DATA_MISSING=20008]="RENDER_DATA_MISSING",e[e.RENDER_FACE_DATA_MISSING=20009]="RENDER_FACE_DATA_MISSING",e[e.EVENT_WITHOUT_SPEECH_ID=20010]="EVENT_WITHOUT_SPEECH_ID",e[e.EVENT_TRIGGERED=20011]="EVENT_TRIGGERED",e[e.BACKGROUND_IMAGE_LOAD_ERROR=30001]="BACKGROUND_IMAGE_LOAD_ERROR",e[e.FACE_BIN_LOAD_ERROR=30002]="FACE_BIN_LOAD_ERROR",e[e.INVALID_BODY_NAME=30003]="INVALID_BODY_NAME",e[e.VIDEO_DOWNLOAD_ERROR=30004]="VIDEO_DOWNLOAD_ERROR",e[e.BODY_DATA_EXPIRED=30005]="BODY_DATA_EXPIRED",e[e.EVENT_SPEAK_START_EXPIRED=30006]="EVENT_SPEAK_START_EXPIRED",e[e.EVENT_VOICE_START_EXPIRED=30007]="EVENT_VOICE_START_EXPIRED",e[e.AUDIO_DECODE_ERROR=40001]="AUDIO_DECODE_ERROR",e[e.FACE_DECODE_ERROR=40002]="FACE_DECODE_ERROR",e[e.VIDEO_DECODE_ERROR=40003]="VIDEO_DECODE_ERROR",e[e.EVENT_DECODE_ERROR=40004]="EVENT_DECODE_ERROR",e[e.INVALID_DATA_STRUCTURE=40005]="INVALID_DATA_STRUCTURE",e[e.TTSA_ERROR=40006]="TTSA_ERROR",e[e.AUDIO_DATA_EXPIRED=40007]="AUDIO_DATA_EXPIRED",e[e.NETWORK_DOWN=50001]="NETWORK_DOWN",e[e.NETWORK_UP=50002]="NETWORK_UP",e[e.NETWORK_RETRY=50003]="NETWORK_RETRY",e[e.NETWORK_BREAK=50004]="NETWORK_BREAK",e[e.WEBGL_CONTEXT_LOST=60001]="WEBGL_CONTEXT_LOST",e[e.WEBGL_CONTEXT_RESTORED=60002]="WEBGL_CONTEXT_RESTORED",e[e.WEBGL_CONTEXT_RESTORE_TIMEOUT=60003]="WEBGL_CONTEXT_RESTORE_TIMEOUT",e[e.WEBGL_CONTEXT_RECOVERED=60004]="WEBGL_CONTEXT_RECOVERED",e[e.WEBGL_CONTEXT_RECOVERY_FAILED=60005]="WEBGL_CONTEXT_RECOVERY_FAILED",e[e.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS=60006]="WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",e[e.WEBGL_RESOLUTION_RESTORED=60007]="WEBGL_RESOLUTION_RESTORED",e[e.WEBGL_CONTEXT_MANUAL_RESTARTED=60008]="WEBGL_CONTEXT_MANUAL_RESTARTED"}(n||(n={})),function(e){e[e.online=0]="online",e[e.offline=1]="offline",e[e.network_on=2]="network_on",e[e.network_off=3]="network_off",e[e.close=4]="close",e[e.visible=5]="visible",e[e.invisible=6]="invisible",e[e.stopped=7]="stopped"}(r||(r={})),function(e){e.init="init",e.rendering="rendering",e.pausing="pausing",e.paused="paused",e.resumed="resumed",e.stopped="stopped"}(i||(i={})),function(e){e.normal="normal",e.invisible="invisible"}(o||(o={}));var m=2097152,p=/*#__PURE__*/function(){function e(e){var t;this.ws=null,this.connectPromise=null,this.rejectConnect=null,this.options=e,this.audioInputEnabled=null==(t=e.audioInputEnabled)||t;var n=e.WebSocketCtor||globalThis.WebSocket;if(!n)throw new Error("当前环境不支持 WebSocket");this.WebSocketCtor=n}var t=e.prototype;return t.connect=function(){var e,t,n,r=this;return this.isOpen?Promise.resolve():(this.connectPromise||(null==(e=(t=this.options).onStateChange)||e.call(t,"connecting"),n=new Promise(function(e,t){r.rejectConnect=t;var i=!1,o=new r.WebSocketCtor(r.buildWsUrl(r.options.wsUrl,r.options.token));r.ws=o,o.onopen=function(){r.ws===o&&(i=!0,r.connectPromise===n&&(r.connectPromise=null),r.rejectConnect=null,null==r.options.onStateChange||r.options.onStateChange("open"),e())},o.onmessage=function(e){if(r.ws===o){var t=r.parseMessage(e.data);t&&(null==r.options.onEvent||r.options.onEvent(t))}},o.onerror=function(){if(r.ws===o){var e=new Error("E2E WebSocket 连接异常");i||(i=!0,r.connectPromise===n&&(r.connectPromise=null),r.rejectConnect=null,t(e)),null==r.options.onStateChange||r.options.onStateChange("error"),null==r.options.onError||r.options.onError(e)}},o.onclose=function(e){r.ws===o&&(r.ws=null,i||(i=!0,r.connectPromise===n&&(r.connectPromise=null),r.rejectConnect=null,t(new Error(("E2E WebSocket 已关闭: "+e.code+" "+(e.reason||"")).trim()))),null==r.options.onStateChange||r.options.onStateChange("closed"),null==r.options.onClose||r.options.onClose(e))}}),this.connectPromise=n),this.connectPromise)},t.disconnect=function(e,t){void 0===e&&(e=1e3),void 0===t&&(t="client_close");var n=this.detachSocket();n&&this.closeSocket(n,e,t)},t.disconnectAndWait=function(e,t,n){var r=this;void 0===e&&(e=1e3),void 0===t&&(t="client_close"),void 0===n&&(n=3e3);var i=this.ws;return i?(this.cancelPendingConnection(),new Promise(function(o){var a,s=i.onclose,u=!1,c=function(e){u||(u=!0,void 0!==a&&globalThis.clearTimeout(a),r.ws===i&&(r.ws=null),i.onclose=s,o(e))};i.onclose=function(e){try{null==s||s.call(i,e)}finally{c(!0)}},a=globalThis.setTimeout(function(){return c(!1)},Math.max(0,n));try{r.closeSocket(i,e,t)}catch(e){c(!1)}})):Promise.resolve(!0)},t.detachSocket=function(){if(!this.ws)return null;var e=this.ws;return this.ws=null,this.cancelPendingConnection(),e},t.cancelPendingConnection=function(){this.connectPromise=null;var e=this.rejectConnect;this.rejectConnect=null,null==e||e(new Error("E2E WebSocket 连接已取消"))},t.closeSocket=function(e,t,n){e.readyState!==this.WebSocketCtor.OPEN&&e.readyState!==this.WebSocketCtor.CONNECTING||e.close(t,n)},t.send=function(e){var t;this.assertOpen(),null==(t=this.ws)||t.send(JSON.stringify(e))},t.trySend=function(e){var t;return this.assertOpen(),!(this.ws&&this.ws.bufferedAmount>m||(null==(t=this.ws)||t.send(JSON.stringify(e)),0))},t.sendBinary=function(e){var t;if(this.assertOpen(),this.ws&&this.ws.bufferedAmount>m){var n=new Error("E2E WebSocket 发送缓冲区超限");throw n.name="WebSocketBackpressureError",n}null==(t=this.ws)||t.send(e)},t.ping=function(){this.send({type:"ping"})},t.setAudioInputEnabled=function(e){this.audioInputEnabled=e},t.assertOpen=function(){if(!this.isOpen)throw new Error("E2E WebSocket 未连接")},t.parseMessage=function(e){if("string"!=typeof e)return null;try{var t=JSON.parse(e);return t&&"string"==typeof t.type?t:null}catch(e){var n,r;return null==(n=(r=this.options).onError)||n.call(r,new Error("E2E WebSocket 消息不是合法 JSON")),null}},t.buildWsUrl=function(e,t){try{var n=new URL(e);return!t||n.searchParams.has("token")||n.searchParams.has("e2e_token")||n.searchParams.set("token",t),this.updateAudioInputQuery(n.searchParams),n.toString()}catch(n){var r=e.split("?",2),i=r[0],o=r[1],a=new URLSearchParams(void 0===o?"":o);!t||a.has("token")||a.has("e2e_token")||a.set("token",t),this.updateAudioInputQuery(a);var s=a.toString();return s?i+"?"+s:i}},t.updateAudioInputQuery=function(e){this.audioInputEnabled?e.delete("audio_input_off"):e.set("audio_input_off","1")},c(e,[{key:"isOpen",get:function(){var e;return(null==(e=this.ws)?void 0:e.readyState)===this.WebSocketCtor.OPEN}}])}(),v={format:"webm_opus",mimeType:"audio/webm;codecs=opus",sampleRate:16e3,channels:1,chunkMs:100};function g(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var E=16e3,S="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function y(e,t,n){if(!e.s){if(n instanceof R){if(!n.s)return void(n.o=y.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(y.bind(null,e,t),y.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var R=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var o=1&i?t:n;if(o){try{y(r,1,o(this.v))}catch(e){y(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?y(r,1,t?t(i):i):n?y(r,1,n(i)):y(r,2,i)}catch(e){y(r,2,e)}},r},e}();function A(e){return e instanceof R&&1&e.s}function b(e,t,n){if("function"==typeof e[S]){var r,i,o,a=function(e){try{for(;!((r=s.next()).done||n&&n());)if((e=t(r.value))&&e.then){if(!A(e))return void e.then(a,o||(o=y.bind(null,i=new R,2)));e=e.v}i?y(i,1,e):i=e}catch(e){y(i||(i=new R),2,e)}},s=e[S]();if(a(),s.return){var u=function(e){try{r.done||s.return()}catch(e){}return e};if(i&&i.then)return i.then(u,function(e){throw u(e)});u()}return i}if(!("length"in e))throw new TypeError("Object is not iterable");for(var c=[],l=0;l<e.length;l++)c.push(e[l]);return function(e,t,n){var r,i,o=-1;return function a(s){try{for(;++o<e.length&&(!n||!n());)if((s=t(o))&&s.then){if(!A(s))return void s.then(a,i||(i=y.bind(null,r=new R,2)));s=s.v}r?y(r,1,s):r=s}catch(e){y(r||(r=new R),2,e)}}(),r}(c,function(e){return t(c[e])},n)}function _(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var w=/*#__PURE__*/function(){function e(e){void 0===e&&(e={}),this.inputTrack=null,this.reader=null,this.writer=null,this.generator=null,this.audioContext=null,this.audioSource=null,this.audioDestination=null,this.pumpPromise=null,this.pumpFinished=!1,this.outputClosed=!1,this.draining=!1,this.inputSampleRate=null,this.resampleBuffer=[],this.resamplePosition=0,this.outputBuffer=[],this.outputTimestamp=null,this.startGeneration=0,this.options=e}var t=e.prototype;return t.start=function(e){try{var t=this,n=++t.startGeneration;t.inputTrack=e,t.inputSampleRate=null,t.resampleBuffer=[],t.resamplePosition=0,t.outputBuffer=[],t.outputTimestamp=null,t.pumpFinished=!1,t.outputClosed=!1,t.draining=!1;var r=globalThis,i=r.MediaStreamTrackProcessor,o=r.MediaStreamTrackGenerator,a=r.AudioData;if(!i||!o||!a)return Promise.resolve(t.startWebAudio(e,r,n));var s=new i({track:e}),u=new o({kind:"audio"}),c=new MediaStream([u]),l=c.getAudioTracks()[0],h=null==l?void 0:l.getSettings();if(void 0!==(null==h?void 0:h.sampleRate)&&h.sampleRate!==E||void 0!==(null==h?void 0:h.channelCount)&&1!==h.channelCount)throw u.stop(),t.unsupported("浏览器音频输出格式不符合要求: "+((null==h?void 0:h.sampleRate)||"unknown")+" Hz / "+((null==h?void 0:h.channelCount)||"unknown")+" channel");try{t.reader=s.readable.getReader(),t.writer=u.writable.getWriter()}catch(n){throw u.stop(),"ended"!==e.readyState&&e.stop(),t.inputTrack=null,n}return t.generator=u,t.pumpPromise=t.pump(a),Promise.resolve(c)}catch(e){return Promise.reject(e)}},t.startWebAudio=function(e,t,n){try{var r=this,i=globalThis.AudioContext||t.webkitAudioContext;if(!i)throw r.unsupported("当前浏览器不支持 16 kHz mono 音频处理");var o=null,a=null,s=null;return Promise.resolve(g(function(){function t(t){if(r.assertStartActive(n),"running"!==o.state)throw r.contextSuspended();a=o.createMediaStreamSource(new MediaStream([e])),r.audioSource=a,s=o.createMediaStreamDestination(),r.audioDestination=s,s.channelCount=1,s.channelCountMode="explicit",s.channelInterpretation="speakers",a.connect(s);var i=s.stream.getAudioTracks()[0];if(!i)throw new Error("Web Audio 未返回音频输出轨道");return r.validateOutputTrack(i),r.assertStartActive(n),s.stream}if(o=new i({sampleRate:E}),r.audioContext=o,o.sampleRate!==E)throw r.unsupported("浏览器无法创建 16 kHz AudioContext: "+o.sampleRate+" Hz");var u=function(){if("suspended"===o.state)return g(function(){return Promise.resolve(o.resume()).then(function(){})},function(e){throw r.contextSuspended(e)})}();return u&&u.then?u.then(t):t()},function(t){var n,i;function u(){throw"ended"!==e.readyState&&e.stop(),r.inputTrack=null,r.audioContext===o&&(r.audioContext=null,r.audioSource=null,r.audioDestination=null),r.normalizeWebAudioError(t)}null==(n=a)||n.disconnect(),null==(i=s)||i.stream.getTracks().forEach(function(e){return e.stop()});var c=function(){if(o&&"closed"!==o.state)return Promise.resolve(o.close().catch(function(){})).then(function(){})}();return c&&c.then?c.then(u):u()}))}catch(e){return Promise.reject(e)}},t.stop=function(){try{var e=this;return Promise.resolve(e.drain()).then(function(){var t;function n(n){return t?n:Promise.resolve(e.closeOutput()).then(function(){})}var r=function(){if(e.audioContext)return Promise.resolve(e.closeWebAudioOutput()).then(function(){t=1})}();return r&&r.then?r.then(n):n(r)})}catch(e){return Promise.reject(e)}},t.drain=function(){try{var e,t=this;if(t.startGeneration+=1,t.draining=!0,null==(e=t.inputTrack)||e.stop(),t.inputTrack=null,t.audioContext)return Promise.resolve();var n=t.pumpPromise,r=function(){if(n){var e=n.then(function(){return!0},function(){return!0});return Promise.resolve(Promise.race([e,t.delay(1e3)])).then(function(e){var n=function(){var n;if(!e)return Promise.resolve(Promise.race([null==(n=t.reader)?void 0:n.cancel().catch(function(){}),t.delay(100)])).then(function(){var e;return Promise.resolve(Promise.race([null==(e=t.writer)?void 0:e.abort(new Error("16 kHz mono 音频处理停止超时")).catch(function(){}),t.delay(100)])).then(function(){t.stopGenerator()})})}();if(n&&n.then)return n.then(function(){})})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.closeOutput=function(){try{var e=function(){t.stopGenerator(),n&&t.pumpFinished&&n.releaseLock(),t.reader=null,t.writer=null,t.generator=null,t.pumpPromise=null},t=this,n=t.writer;t.outputClosed=!0;var r=n&&t.pumpFinished?Promise.resolve(Promise.race([n.close().catch(function(){}),t.delay(100)])).then(function(){}):Promise.resolve(Promise.race([null==n?void 0:n.abort(new Error("16 kHz mono 音频处理停止超时")).catch(function(){}),t.delay(100)])).then(function(){});return Promise.resolve(r&&r.then?r.then(e):e())}catch(e){return Promise.reject(e)}},t.closeWebAudioOutput=function(){try{var e=this,t=e.audioContext,n=e.audioSource,r=e.audioDestination;e.audioContext=null,e.audioSource=null,e.audioDestination=null,null==n||n.disconnect(),null==r||r.disconnect(),null==r||r.stream.getTracks().forEach(function(e){return e.stop()});var i=function(){if(t&&"closed"!==t.state)return Promise.resolve(t.close().catch(function(){})).then(function(){})}();return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.pump=function(e){try{var t=this,n=t.reader,r=t.writer;return n&&r?Promise.resolve(_(function(){return g(function(){var i;function o(){function n(){var e;if(a&&!t.draining&&"ended"===(null==(e=t.inputTrack)?void 0:e.readyState)){var n=new Error("麦克风音频轨道已结束");n.name="AudioTransformError",null==t.options.onError||t.options.onError(n),t.stopGenerator()}}var i=b(t.resample(new Float32Array,t.inputSampleRate||E,!0),function(n){return Promise.resolve(t.writeChunk(r,e,n)).then(function(){})});return i&&i.then?i.then(n):n()}var a=!1,s=function(e,t,n){for(var r;;){var i=e();if(A(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!A(o)){r=1;break}o=o.s}}var a=new R,s=y.bind(null,a,2);return(0===r?i.then(c):1===r?o.then(u):(void 0).then(function(){(i=e())?i.then?i.then(c).then(void 0,s):c(i):y(a,1,o)})).then(void 0,s),a;function u(t){o=t;do{if(!(i=e())||A(i)&&!i.v)return void y(a,1,o);if(i.then)return void i.then(c).then(void 0,s);A(o=n())&&(o=o.v)}while(!o||!o.then);o.then(u).then(void 0,s)}function c(e){e?(o=n())&&o.then?o.then(u).then(void 0,s):u(o):y(a,1,o)}}(function(){return!i},0,function(){return Promise.resolve(n.read()).then(function(n){if(n.done)return a=!0,void(i=1);if(n.value){var o=n.value;return _(function(){t.validateAudioData(o);var n=t.toMono(o),i=t.resample(n,o.sampleRate,!1);null===t.outputTimestamp&&(t.outputTimestamp=Number.isFinite(o.timestamp)?o.timestamp:0);var a=b(i,function(n){return Promise.resolve(t.writeChunk(r,e,n)).then(function(){})});if(a&&a.then)return a.then(function(){})},function(e,t){if(o.close(),e)throw t;return t})}})});return s&&s.then?s.then(o):o()},function(e){var n=e instanceof Error?e:new Error("16 kHz mono 音频处理失败");n.name="AudioTransformError",null==t.options.onError||t.options.onError(n)})},function(e,i){if(n.releaseLock(),t.pumpFinished=!0,t.outputClosed&&r.releaseLock(),e)throw i;return i})):Promise.resolve()}catch(e){return Promise.reject(e)}},t.toMono=function(e){for(var t=Math.max(1,e.numberOfChannels),n=new Float32Array(e.numberOfFrames),r=0;r<t;r+=1){var i=new Float32Array(e.numberOfFrames);e.copyTo(i,{format:"f32-planar",planeIndex:r});for(var o=0;o<i.length;o+=1)n[o]+=i[o]/t}return n},t.resample=function(e,t,n){if(null===this.inputSampleRate)this.inputSampleRate=t;else if(this.inputSampleRate!==t)throw new Error("输入音频采样率发生变化: "+this.inputSampleRate+" -> "+t);for(var r,i=l(e);!(r=i()).done;)this.resampleBuffer.push(r.value);if(this.resampleBuffer.length>192e3)throw new Error("输入音频重采样缓冲区超限");n&&this.resampleBuffer.length>0&&this.resampleBuffer.push(this.resampleBuffer[this.resampleBuffer.length-1]);for(var o=t/E,a=[];this.resamplePosition+1<this.resampleBuffer.length;){var s=Math.floor(this.resamplePosition),u=Math.min(s+1,this.resampleBuffer.length-1),c=this.resamplePosition-s;this.outputBuffer.push(this.resampleBuffer[s]*(1-c)+this.resampleBuffer[u]*c),this.resamplePosition+=o;var h=Math.floor(this.resamplePosition);h>0&&(this.resampleBuffer.splice(0,h),this.resamplePosition-=h),this.outputBuffer.length>=320&&a.push(new Float32Array(this.outputBuffer.splice(0,320)))}return n&&this.outputBuffer.length>0&&a.push(new Float32Array(this.outputBuffer.splice(0))),a},t.writeChunk=function(e,t,n){try{var r=this;if(!n.length)return Promise.resolve();var i=r.outputTimestamp||0,o=new t({format:"f32-planar",sampleRate:E,numberOfFrames:n.length,numberOfChannels:1,timestamp:i,data:n});return r.outputTimestamp=i+Math.round(1e6*n.length/E),Promise.resolve(e.write(o)).then(function(){var e;o.close();var t=null==(e=r.generator)?void 0:e.getSettings();if(t&&(void 0!==t.sampleRate&&t.sampleRate!==E||void 0!==t.channelCount&&1!==t.channelCount))throw r.unsupported("浏览器音频输出格式不符合要求: "+(t.sampleRate||"unknown")+" Hz / "+(t.channelCount||"unknown")+" channel")})}catch(e){return Promise.reject(e)}},t.validateAudioData=function(e){if(!Number.isFinite(e.sampleRate)||!Number.isInteger(e.sampleRate)||e.sampleRate<8e3||e.sampleRate>192e3)throw new Error("输入音频采样率无效: "+e.sampleRate);if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<1||e.numberOfChannels>8)throw new Error("输入音频声道数无效: "+e.numberOfChannels);if(!Number.isInteger(e.numberOfFrames)||e.numberOfFrames<1||e.numberOfFrames>96e3)throw new Error("输入音频帧数无效: "+e.numberOfFrames);if(!Number.isFinite(e.timestamp)||Math.abs(e.timestamp)>1e15)throw new Error("输入音频时间戳无效: "+e.timestamp)},t.delay=function(e){return new Promise(function(t){globalThis.setTimeout(function(){return t(!1)},e)})},t.stopGenerator=function(){this.generator&&"ended"!==this.generator.readyState&&this.generator.stop()},t.unsupported=function(e,t){var n=new Error(e);return n.name="NotSupportedError",n.agentCode="AUDIO_FIXED_TRACK_UNSUPPORTED",n.retryable=!1,n.cause=t,n},t.contextSuspended=function(e){var t=new Error("AudioContext 未运行,请在用户操作后重试");return t.name="NotAllowedError",t.agentCode="AUDIO_CONTEXT_SUSPENDED",t.retryable=!0,t.cause=e,t},t.assertStartActive=function(e){if(e!==this.startGeneration){var t=new Error("16 kHz mono 音频处理启动已取消");throw t.name="AbortError",t.agentCode="AUDIO_FIXED_TRACK_CANCELLED",t.retryable=!0,t}},t.normalizeWebAudioError=function(e){var t=e instanceof Error?e:new Error(String(e));if(t.agentCode)return t;if("NotSupportedError"===t.name)return this.unsupported("浏览器无法初始化 16 kHz mono Web Audio: "+t.message,t);var n=new Error("16 kHz mono Web Audio 初始化失败: "+t.message);return n.name=t.name,n.agentCode="AUDIO_FIXED_TRACK_FAILED",n.retryable=!0,n.cause=t,n},t.validateOutputTrack=function(e){var t=e.getSettings();if(void 0!==t.sampleRate&&t.sampleRate!==E||void 0!==t.channelCount&&1!==t.channelCount)throw this.unsupported("浏览器音频输出格式不符合要求: "+(t.sampleRate||"unknown")+" Hz / "+(t.channelCount||"unknown")+" channel")},e}(),P=function(e,t,n,r){void 0===n&&(n={}),void 0===r&&(r=T);try{var i=function(i,o){try{var a=function(){function i(i){var o=new Uint8Array(i),a=Array.from(o.slice(0,r)),s=t instanceof Blob?t.type:n.type;console.log(e,h({},n,{size:o.byteLength,type:s,previewLength:a.length,bytes:a,hex:a.map(k).join(" ")}))}return t instanceof Blob?Promise.resolve(t.arrayBuffer()).then(i):i(ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t)}()}catch(e){return o(e)}return a&&a.then?a.then(void 0,o):a}(0,function(t){console.warn(e,"failed to read audio chunk",t)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},T=64;function k(e){return e.toString(16).padStart(2,"0")}var C=new WeakMap,O=new WeakMap;function D(e){return e.audioSession}function I(e,t){try{return e.type=t,e.type===t}catch(e){return!1}}function M(){var e=globalThis.performance;return e&&Number.isFinite(e.timeOrigin)&&"function"==typeof e.now?e.timeOrigin+e.now():Date.now()}var N=/*#__PURE__*/function(){function e(e,t){void 0===t&&(t=M),this.timecodeScale=null,this.firstTimecode=null,this.lastTimecode=null,this.lastObservedAt=null,this.lastTimestamp=null,this.chunkMs=e,this.now=t,this.startedAt=t()}return e.prototype.resolve=function(e){var t=this.now(),n=Number.isFinite(e)&&e>=0;if(n&&null===this.firstTimecode&&(this.firstTimecode=e),n&&null===this.timecodeScale&&null!==this.lastTimecode&&e>this.lastTimecode){var r=e-this.lastTimecode,i=null===this.lastObservedAt?0:t-this.lastObservedAt,o=i>=this.chunkMs/4?i:this.chunkMs,a=Math.abs(r-o),s=Math.abs(1e3*r-o);this.timecodeScale=s<a?1e3:1}var u,c=t-this.chunkMs,l=n&&null!==this.firstTimecode?e-this.firstTimecode:null;null!==l&&l>=0&&(null!==this.timecodeScale||0===l)&&(c=this.startedAt+l*(null!=(u=this.timecodeScale)?u:1)),null!==this.lastTimestamp&&(c=Math.max(c,this.lastTimestamp+this.chunkMs));var h=Math.max(Math.round(this.startedAt),Math.round(c));return this.lastTimecode=n?e:this.lastTimecode,this.lastObservedAt=t,this.lastTimestamp=h,h},e}();function F(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var U=2e4;function B(e){return{codec:"opus",sampleRate:e.sampleRate,numberOfChannels:e.channels,bitrate:e.bitrate,opus:{format:"opus",frameDuration:U}}}var x=/*#__PURE__*/function(){function e(e){void 0===e&&(e={}),this.encoder=null,this.isInitialized=!1,this.pendingEncode=null,this.timestamp=0,this.config=h({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600},e)}e.isSupported=function(){try{return"undefined"==typeof AudioEncoder?Promise.resolve(!1):Promise.resolve(F(function(){return Promise.resolve(AudioEncoder.isConfigSupported(B({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}))).then(function(e){var t;return!0===e.supported&&(null==(t=e.config)||null==(t=t.opus)?void 0:t.frameDuration)===U})},function(){return!1}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.init=function(){try{var e=this;return e.isInitialized||(e.encoder=e.createEncoder(),e.isInitialized=!0),Promise.resolve()}catch(e){return Promise.reject(e)}},t.encode=function(e){try{var t=this;if(!t.isInitialized||!t.encoder)return Promise.reject(new Error("WebCodecOpusEncoder 未初始化"));if(t.pendingEncode)return Promise.reject(new Error("WebCodecs Opus 编码器仍在处理上一音频块"));var n=new Int16Array(e),r=t.timestamp,i=Math.round(1e6*e.length/t.config.sampleRate),o=r+i,a=i/U;if(!Number.isInteger(a))return Promise.reject(new Error("PCM 音频块无法按 20ms Opus packet 完整分包"));var s=new AudioData({format:"s16",sampleRate:t.config.sampleRate,numberOfFrames:n.length,numberOfChannels:t.config.channels,timestamp:r,data:n}),u=new Promise(function(e,n){var i=globalThis.setTimeout(function(){t.failPending(new Error("WebCodecs Opus 编码输出超过 2 秒"))},2e3);t.pendingEncode={startTimestampUs:r,endTimestampUs:o,expectedFrameCount:a,chunks:[],resolve:e,reject:n,timeoutId:i}});try{t.encoder.encode(s),t.timestamp=o}catch(e){t.failPending(e instanceof Error?e:new Error("WebCodecs Opus 编码失败"))}finally{s.close()}return Promise.resolve(u)}catch(e){return Promise.reject(e)}},t.reset=function(){if(this.timestamp=0,this.failPending(new Error("WebCodecs Opus 编码已重置")),this.encoder){try{this.encoder.close()}catch(e){}this.encoder=this.createEncoder()}},t.destroy=function(){try{var e=function(){t.encoder=null,t.isInitialized=!1},t=this,n=t.encoder,r=function(){if(n){var e=function(){t.failPending(new Error("WebCodecs Opus 编码器已销毁"));try{n.close()}catch(e){}},r=F(function(){return Promise.resolve(n.flush()).then(function(){})},function(){});return r&&r.then?r.then(e):e()}}();return Promise.resolve(r&&r.then?r.then(e):e())}catch(e){return Promise.reject(e)}},t.createEncoder=function(){var e,t=this;return(e=new AudioEncoder({output:function(n){t.encoder===e&&t.handleOutput(n)},error:function(n){if(t.encoder===e){var r=n instanceof Error?n:new Error("WebCodecs Opus 编码失败");(globalThis.avatarSDKLogger||console).error("[WebCodecOpusEncoder] 编码错误:",r),t.failPending(r)}}})).configure(B(this.config)),e},t.handleOutput=function(e){var t=this.pendingEncode;if(t)if(e.timestamp<t.startTimestampUs||e.timestamp>=t.endTimestampUs||null!==e.duration&&e.duration!==U)this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));else if(t.chunks.push(e),t.chunks.length>t.expectedFrameCount)this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));else if(!(t.chunks.length<t.expectedFrameCount)){var n=t.chunks.map(function(e,n){var r,i,o=new Uint8Array(e.byteLength);e.copyTo(o);var a=null!=(r=null==(i=t.chunks[n+1])?void 0:i.timestamp)?r:t.endTimestampUs;return{data:o,durationMs:(e.duration&&e.duration>0?e.duration:Math.max(1,a-e.timestamp))/1e3}}),r=n.reduce(function(e,t){return e+t.durationMs},0);n.some(function(e){return 20!==e.durationMs})||r!==(t.endTimestampUs-t.startTimestampUs)/1e3?this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频")):(globalThis.clearTimeout(t.timeoutId),this.pendingEncode=null,t.resolve(n))}},t.failPending=function(e){var t=this.pendingEncode;t&&(globalThis.clearTimeout(t.timeoutId),this.pendingEncode=null,t.reject(e))},e}(),W=/*#__PURE__*/function(){function e(e){void 0===e&&(e=16e3),this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0,this.frameDuration=100,this.sampleRate=e}var t=e.prototype;return t.writeHeader=function(){if(!this.hasHeader){var e=this.buildEBMLHeader(),t=this.buildSegmentInfo(),n=this.buildOpusTracks();this.chunks.push(e),this.chunks.push(new Uint8Array([24,83,128,103,1,255,255,255,255,255,255,255])),this.chunks.push(t),this.chunks.push(n),this.hasHeader=!0,this.clusterTimestamp=0}},t.feedOpusFrame=function(e,t){void 0===t&&(t=this.frameDuration),this.hasHeader||this.writeHeader();var n=this.buildCluster(Math.round(this.clusterTimestamp),e);this.chunks.push(n),this.clusterTimestamp+=t},t.flush=function(){if(0===this.chunks.length)return new ArrayBuffer(0);for(var e,t=this.chunks.reduce(function(e,t){return e+t.length},0),n=new Uint8Array(t),r=0,i=l(this.chunks);!(e=i()).done;){var o=e.value;n.set(o,r),r+=o.length}return this.chunks=[],n.buffer},t.reset=function(){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0},t.encodeVINT=function(e,t){if(void 0!==t){for(var n=new Uint8Array(t),r=t-1;r>=0;r--)n[r]=255&e,e>>>=8;return n[0]|=1<<8-t,n}if(e<127)return new Uint8Array([128|e]);if(e<16383)return new Uint8Array([64|e>>8,255&e]);if(e<2097151)return new Uint8Array([32|e>>16,e>>8&255,255&e]);if(e<268435455)return new Uint8Array([16|e>>24,e>>16&255,e>>8&255,255&e]);throw new Error("VINT value too large: "+e)},t.encodeID=function(e){return e<=255?new Uint8Array([e]):e<=65535?new Uint8Array([e>>8,255&e]):e<=16777215?new Uint8Array([e>>16,e>>8&255,255&e]):new Uint8Array([e>>>24,e>>16&255,e>>8&255,255&e])},t.encodeUint=function(e){if(0===e)return new Uint8Array([0]);for(var t=[],n=e;n>0;)t.unshift(255&n),n=Math.floor(n/256);return new Uint8Array(t)},t.encodeString=function(e){return(new TextEncoder).encode(e)},t.encodeFloat32=function(e){var t=new ArrayBuffer(4);return new DataView(t).setFloat32(0,e,!1),new Uint8Array(t)},t.encodeElement=function(e,t){var n=this.encodeID(e),r=this.encodeVINT(t.length),i=new Uint8Array(n.length+r.length+t.length);return i.set(n,0),i.set(r,n.length),i.set(t,n.length+r.length),i},t.encodeUintElement=function(e,t){return this.encodeElement(e,this.encodeUint(t))},t.encodeStringElement=function(e,t){return this.encodeElement(e,this.encodeString(t))},t.encodeFloat32Element=function(e,t){return this.encodeElement(e,this.encodeFloat32(t))},t.concatArrays=function(e){for(var t,n=e.reduce(function(e,t){return e+t.length},0),r=new Uint8Array(n),i=0,o=l(e);!(t=o()).done;){var a=t.value;r.set(a,i),i+=a.length}return r},t.buildEBMLHeader=function(){var e=this.concatArrays([this.encodeUintElement(17030,1),this.encodeUintElement(17143,1),this.encodeUintElement(17138,4),this.encodeUintElement(17139,8),this.encodeStringElement(17026,"webm"),this.encodeUintElement(17031,4),this.encodeUintElement(17029,2)]);return this.encodeElement(440786851,e)},t.buildSegmentInfo=function(){var e=this.concatArrays([this.encodeUintElement(2807729,1e6),this.encodeStringElement(19840,"xmov-avatar-sdk"),this.encodeStringElement(22337,"xmov-avatar-sdk")]);return this.encodeElement(357149030,e)},t.buildOpusTracks=function(){var e=new Uint8Array([79,112,117,115,72,101,97,100,1,1,0,0,128,62,0,0,0,0,0]),t=this.concatArrays([this.encodeFloat32Element(181,this.sampleRate),this.encodeUintElement(159,1)]),n=this.concatArrays([this.encodeUintElement(215,1),this.encodeUintElement(29637,1),this.encodeUintElement(131,2),this.encodeUintElement(156,0),this.encodeStringElement(2274716,"und"),this.encodeStringElement(134,"A_OPUS"),this.encodeElement(25506,e),this.encodeUintElement(22186,0),this.encodeUintElement(22203,8e7),this.encodeElement(225,t)]),r=this.encodeElement(174,n);return this.encodeElement(374648427,r)},t.buildCluster=function(e,t){var n=this.encodeUintElement(231,e),r=this.encodeVINT(1),i=new Uint8Array([0,0]),o=new Uint8Array([128]),a=this.concatArrays([r,i,o,t]),s=this.encodeElement(163,a),u=this.concatArrays([n,s]);return this.encodeElement(524531317,u)},e}(),L=/*#__PURE__*/function(){function e(){this.opusEncoder=new x({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}),this.muxer=new W(16e3),this.queue=Promise.resolve(),this.generation=0,this.destroyed=!1,this.pendingBlocks=0}e.isSupported=function(){return x.isSupported()};var t=e.prototype;return t.init=function(){try{return Promise.resolve(this.opusEncoder.init()).then(function(){})}catch(e){return Promise.reject(e)}},t.encode=function(e){try{var t=this;if(1600!==e.length)throw new Error("PCM 音频块必须为 1600 samples,实际为 "+e.length);if(t.pendingBlocks>=20)throw new Error("PCM/Opus 编码队列超过 2 秒");t.pendingBlocks+=1;var n=t.generation,r=new Int16Array(e),i=t.queue.then(function(){try{return t.destroyed||n!==t.generation?Promise.resolve(new ArrayBuffer(0)):Promise.resolve(t.opusEncoder.encode(r)).then(function(e){if(t.destroyed||n!==t.generation)return new ArrayBuffer(0);for(var r,i=l(e);!(r=i()).done;){var o=r.value;t.muxer.feedOpusFrame(o.data,o.durationMs)}return t.muxer.flush()})}catch(e){return Promise.reject(e)}}).finally(function(){t.pendingBlocks-=1});return t.queue=i.then(function(){},function(){}),Promise.resolve(i)}catch(e){return Promise.reject(e)}},t.reset=function(){var e=this,t=++this.generation;this.queue=this.queue.then(function(){e.destroyed||t!==e.generation||(e.opusEncoder.reset(),e.muxer.reset())})},t.destroy=function(){try{var e=this;return e.destroyed=!0,e.generation+=1,Promise.resolve(e.opusEncoder.destroy()).then(function(){return Promise.resolve(e.queue).then(function(){e.muxer.reset()})})}catch(e){return Promise.reject(e)}},e}(),j="audio/webm;codecs=opus";function G(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var z=16e3,V="agent-pcm-capture-processor",K="\nclass AgentPcmCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(1600);\n this.bufferIndex = 0;\n this.sequence = 0;\n this.port.onmessage = (event) => {\n if (event.data?.type === 'flush') {\n this.emitBlock(true);\n this.port.postMessage({ type: 'flushed' });\n }\n };\n }\n\n emitBlock(padPartial = false) {\n if (this.bufferIndex === 0 || (!padPartial && this.bufferIndex < 1600)) return;\n const pcm = new Int16Array(1600);\n for (let index = 0; index < this.bufferIndex; index += 1) {\n const sample = Math.max(-1, Math.min(1, this.buffer[index]));\n pcm[index] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;\n }\n this.port.postMessage(\n { type: 'frame', pcm: pcm.buffer, sequence: this.sequence++ },\n [pcm.buffer],\n );\n this.buffer.fill(0);\n this.bufferIndex = 0;\n }\n\n process(inputs, outputs) {\n for (const output of outputs) {\n for (const channel of output) channel.fill(0);\n }\n const channels = inputs[0];\n if (!channels?.length || !channels[0]?.length) return true;\n for (let frame = 0; frame < channels[0].length; frame += 1) {\n let sample = 0;\n for (let channel = 0; channel < channels.length; channel += 1) {\n sample += channels[channel][frame] || 0;\n }\n this.buffer[this.bufferIndex++] = sample / channels.length;\n if (this.bufferIndex === 1600) this.emitBlock();\n }\n return true;\n }\n}\nregisterProcessor('"+V+"', AgentPcmCaptureProcessor);\n",X=/*#__PURE__*/function(){function e(e){var t,n;this.stream=null,this.recordingStream=null,this.audioTransformer=null,this.mediaRecorder=null,this.pcmAudioContext=null,this.pcmSource=null,this.pcmWorklet=null,this.pcmEncoder=null,this.pcmEncodeQueue=Promise.resolve(),this.pcmStartedAt=0,this.pcmGeneration=0,this.resolvePcmFlush=null,this.startGeneration=0,this.starting=!1,this.hasAudioSessionCapture=!1,this.options=e,this.pendingInputStream=null!=(t=e.inputStream)?t:null,this.usesProvidedInput=Boolean(e.inputStream),this.metadata=h({},v,{chunkMs:(null==(n=e.audio)?void 0:n.chunkMs)||v.chunkMs})}var t=e.prototype;return t.getAudioMetadata=function(){return this.metadata},t.start=function(){try{var e=this;if(e.stream||e.starting)return Promise.resolve();var t=++e.startGeneration;return e.starting=!0,Promise.resolve(G(function(){return function(n,r){try{var i=function(){function n(n){function a(n){var r;function i(n){if(r)return n;var i=new w({onError:function(t){var n=t instanceof Error?t:new Error("16 kHz mono 音频处理失败");n.name="MediaRecorderError",null==e.options.onError||e.options.onError(n)}});return e.audioTransformer=i,Promise.resolve(i.start(a)).then(function(n){e.recordingStream=n,e.assertStartActive(t);var r=e.recordingStream.getAudioTracks()[0],i=null==r?void 0:r.getSettings();e.metadata=h({},e.metadata,{sampleRate:(null==i?void 0:i.sampleRate)||z,channels:(null==i?void 0:i.channelCount)||1}),e.startWebMRecorder(o),null==e.options.onMetadata||e.options.onMetadata(e.metadata)})}e.assertStartActive(t);var a=e.stream.getAudioTracks()[0];if(!a)throw new Error("麦克风未返回音频轨道");var s=function(){if(e.options.usePcmWebCodecs)return Promise.resolve(e.startPcmWebMRecorder(e.stream)).then(function(){e.assertStartActive(t),e.metadata=h({},e.metadata,{sampleRate:z,channels:1,chunkMs:100}),null==e.options.onMetadata||e.options.onMetadata(e.metadata),r=1})}();return s&&s.then?s.then(i):i(s)}e.assertStartActive(t);var s=function(){if(!e.stream){if(e.usesProvidedInput)throw r?e.cancelled():new Error("ASR 输入流已释放");return e.hasAudioSessionCapture=function(e){var t,n;void 0===e&&(e=navigator);var r=D(e);if(!r)return!1;var i=C.get(r),o=null!=(t=null==i?void 0:i.previousType)?t:r.type;return!!I(r,"play-and-record")&&(C.set(r,{count:(null!=(n=null==i?void 0:i.count)?n:0)+1,previousType:o}),!0)}(),Promise.resolve(i.getUserMedia({audio:{sampleRate:{ideal:z},channelCount:{ideal:1},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).then(function(t){e.stream=t})}}();return s&&s.then?s.then(a):a()}var r=e.pendingInputStream;e.stream=null!=r?r:null,e.pendingInputStream=null;var i=navigator.mediaDevices;if(!(e.stream||null!=i&&i.getUserMedia))throw new Error("当前浏览器不支持麦克风采集");var o=globalThis.MediaRecorder,a=function(){if(e.options.usePcmWebCodecs)return Promise.resolve(L.isSupported()).then(function(t){if(!t)throw e.webCodecsOpusUnsupported()});if(null==o||null==o.isTypeSupported||!o.isTypeSupported(j))throw e.webMOpusUnsupported()}();return a&&a.then?a.then(n):n()}()}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(n){var r=t!==e.startGeneration;return Promise.resolve(e.stop()).then(function(){var t=r?e.cancelled():n instanceof Error?n:new Error("麦克风启动失败");throw"AUDIO_FIXED_TRACK_CANCELLED"!==t.agentCode&&(null==e.options.onError||e.options.onError(t)),t})})},function(n,r){if(e.startGeneration===t&&(e.starting=!1),n)throw r;return r}))}catch(e){return Promise.reject(e)}},t.stop=function(){try{var e=this;e.startGeneration+=1,e.starting=!1;var t=G(function(){function t(){var t;e.recordingStream=null,e.stream&&!n&&e.stream.getTracks().forEach(function(e){return e.stop()}),e.stream=null,null==(t=e.pendingInputStream)||t.getTracks().forEach(function(e){return e.stop()}),e.pendingInputStream=null}var n=e.audioTransformer,r=G(function(){return Promise.resolve(null==n?void 0:n.drain()).then(function(){})},function(t,r){return Promise.resolve(e.stopPcmWebMRecorder()).then(function(){return Promise.resolve(e.stopMediaRecorder()).then(function(){return Promise.resolve(null==n?void 0:n.stop()).then(function(){if(e.audioTransformer=null,t)throw r;return r})})})});return r&&r.then?r.then(t):t()},function(t,n){if(e.hasAudioSessionCapture&&(e.hasAudioSessionCapture=!1,function(e){void 0===e&&(e=navigator);var t=D(e);if(!t)return!1;var n=C.get(t);if(!n)return function(e){void 0===e&&(e=navigator);var t=D(e);if(!t)return!1;var n=C.get(t);return I(t,null!=n&&n.count||"play-and-record"===t.type?"play-and-record":"playback")}(e);if(n.count-=1,n.count>0)return I(t,"play-and-record");C.delete(t);var r="play-and-record"===n.previousType?"play-and-record":"playback";I(t,r)&&"playback"===r&&function(e){var t=O.get(e);if(t)for(var n=0,r=[].concat(t);n<r.length;n++){var i=r[n];try{i()}catch(e){}}}(t)}()),t)throw n;return n});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.startWebMRecorder=function(e){var t,n=this;if(!this.recordingStream)throw new Error("16 kHz mono 音频流未就绪");try{t=new e(this.recordingStream,{mimeType:j,audioBitsPerSecond:24e3})}catch(e){if(e instanceof Error&&"NotSupportedError"===e.name)throw this.webMOpusUnsupported(e);throw e}var r=new N(this.metadata.chunkMs);t.ondataavailable=function(e){if(e.data.size>0){var i,o=r.resolve(e.timecode);null==(i=globalThis.avatarSDKLogger)||null==i.log||i.log("[Agent][Microphone]","audio chunk",{size:e.data.size,type:e.data.type,chunkMs:n.metadata.chunkMs,sampleRate:n.metadata.sampleRate,channels:n.metadata.channels,recorderState:t.state,timecode:e.timecode}),n.options.debugAudioChunks&&P("[Agent][Microphone] nearend WebM/Opus chunk",e.data,{chunkMs:n.metadata.chunkMs,sampleRate:n.metadata.sampleRate,channels:n.metadata.channels,recorderState:t.state,timecode:e.timecode}),n.options.onFrame(e.data,o)}},t.onerror=function(e){var t=e.error,r=new Error(t instanceof Error?t.message:"WebM/Opus 麦克风录制失败");r.name="MediaRecorderError",null==n.options.onError||n.options.onError(r)},this.mediaRecorder=t;try{t.start(this.metadata.chunkMs)}catch(e){if(e instanceof Error&&"NotSupportedError"===e.name)throw this.webMOpusUnsupported(e);throw e}},t.assertStartActive=function(e){if(e!==this.startGeneration)throw this.cancelled()},t.cancelled=function(){var e=new Error("麦克风启动已取消");return e.name="AbortError",e.agentCode="AUDIO_FIXED_TRACK_CANCELLED",e.retryable=!0,e},t.webMOpusUnsupported=function(e){var t=new Error("当前浏览器不支持 audio/webm;codecs=opus");return t.name="NotSupportedError",t.agentCode="AUDIO_WEBM_OPUS_UNSUPPORTED",t.retryable=!1,t.cause=e,t},t.webCodecsOpusUnsupported=function(e){var t=new Error("当前浏览器不支持 WebCodecs AudioEncoder Opus");return t.name="NotSupportedError",t.agentCode="AUDIO_WEBCODECS_OPUS_UNSUPPORTED",t.retryable=!1,t.cause=e,t},t.startPcmWebMRecorder=function(e){try{var t=this,n=globalThis,r=globalThis.AudioContext||n.webkitAudioContext;if(!r||void 0===globalThis.AudioWorkletNode)throw t.webCodecsOpusUnsupported(new Error("AudioWorklet 不可用"));var i=new L;return Promise.resolve(i.init()).then(function(){function n(n){function r(){function n(){if("running"!==o.state)throw t.audioContextSuspended();var n=o.createMediaStreamSource(e),r=new AudioWorkletNode(o,V,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1]}),a=++t.pcmGeneration;t.pcmSource=n,t.pcmWorklet=r,t.pcmEncodeQueue=Promise.resolve(),t.pcmStartedAt=t.monotonicEpochNow(),r.port.onmessage=function(e){var n,r;if("flushed"===(null==(n=e.data)?void 0:n.type))return null==t.resolvePcmFlush||t.resolvePcmFlush(),void(t.resolvePcmFlush=null);if("frame"===(null==(r=e.data)?void 0:r.type)&&e.data.pcm instanceof ArrayBuffer){var o=t.pcmStartedAt+100*Number(e.data.sequence||0),s=new Int16Array(e.data.pcm);t.pcmEncodeQueue=t.pcmEncodeQueue.then(function(){try{return Promise.resolve(i.encode(s)).then(function(n){if(a===t.pcmGeneration&&0!==n.byteLength){var r=new Blob([n],{type:j});t.options.debugAudioChunks&&P("[Agent][Microphone] nearend PCM/WebCodecs chunk",r,{chunkMs:100,sampleRate:z,channels:1,sequence:e.data.sequence}),t.options.onFrame(r,o)}})}catch(e){return Promise.reject(e)}}).catch(function(e){var n=e instanceof Error?e:new Error("PCM/Opus 麦克风编码失败");n.name="AudioEncoderError",null==t.options.onError||t.options.onError(n)})}},n.connect(r),r.connect(o.destination)}var r=function(){if("suspended"===o.state)return Promise.resolve(o.resume()).then(function(){})}();return r&&r.then?r.then(n):n()}t.pcmAudioContext=o,t.pcmEncoder=i;var a=URL.createObjectURL(new Blob([K],{type:"application/javascript"})),s=G(function(){return Promise.resolve(o.audioWorklet.addModule(a)).then(function(){})},function(e,t){if(URL.revokeObjectURL(a),e)throw t;return t});return s&&s.then?s.then(r):r()}var o=new r({sampleRate:z}),a=function(){if(o.sampleRate!==z)return Promise.resolve(i.destroy()).then(function(){return Promise.resolve(o.close().catch(function(){})).then(function(){throw t.webCodecsOpusUnsupported(new Error("浏览器无法创建 16000 Hz AudioContext"))})})}();return a&&a.then?a.then(n):n()})}catch(e){return Promise.reject(e)}},t.stopPcmWebMRecorder=function(){try{var e=function(){return Promise.resolve(t.pcmEncodeQueue).then(function(){function e(){return Promise.resolve(null==o?void 0:o.destroy()).then(function(){t.pcmWorklet=null,t.pcmSource=null,t.pcmAudioContext=null,t.pcmEncoder=null,t.pcmEncodeQueue=Promise.resolve()})}t.pcmGeneration+=1,t.resolvePcmFlush=null,n&&(n.port.onmessage=null,n.disconnect(),n.port.close());var r=function(){if(i&&"closed"!==i.state)return Promise.resolve(i.close().catch(function(){})).then(function(){})}();return r&&r.then?r.then(e):e()})},t=this,n=t.pcmWorklet,r=t.pcmSource,i=t.pcmAudioContext,o=t.pcmEncoder;if(!n&&!i&&!o)return Promise.resolve();null==r||r.disconnect();var a=function(){if(n)return Promise.resolve(Promise.race([new Promise(function(e){t.resolvePcmFlush=function(){return e(!0)},n.port.postMessage({type:"flush"})}),new Promise(function(e){return globalThis.setTimeout(function(){return e(!1)},100)})])).then(function(e){e||(t.resolvePcmFlush=null,n.port.onmessage=null)})}();return Promise.resolve(a&&a.then?a.then(e):e())}catch(e){return Promise.reject(e)}},t.monotonicEpochNow=function(){var e=globalThis.performance;return e&&Number.isFinite(e.timeOrigin)?Math.round(e.timeOrigin+e.now()):Date.now()},t.audioContextSuspended=function(){var e=new Error("AudioContext 未运行,请在用户操作后重试");return e.name="NotAllowedError",e.agentCode="AUDIO_CONTEXT_SUSPENDED",e.retryable=!0,e},t.stopMediaRecorder=function(){try{var e=this.mediaRecorder;if(this.mediaRecorder=null,!e)return Promise.resolve();var t="inactive"!==e.state;return Promise.resolve(new Promise(function(n){var r=!1,i=function(){r||(r=!0,globalThis.clearTimeout(a),n())},o=e.onerror,a=globalThis.setTimeout(i,1e3);if(e.onstop=i,e.onerror=function(t){null==o||o.call(e,t),i()},t)try{e.stop()}catch(e){i()}})).then(function(){e.ondataavailable=null,e.onerror=null,e.onstop=null})}catch(e){return Promise.reject(e)}},c(e,[{key:"isRecording",get:function(){return this.starting||Boolean(this.stream)||Boolean(this.pendingInputStream)}}])}(),H="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function q(e,t,n){if(!e.s){if(n instanceof J){if(!n.s)return void(n.o=q.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(q.bind(null,e,t),q.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var J=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var o=1&i?t:n;if(o){try{q(r,1,o(this.v))}catch(e){q(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?q(r,1,t?t(i):i):n?q(r,1,n(i)):q(r,2,i)}catch(e){q(r,2,e)}},r},e}();function Y(e){return e instanceof J&&1&e.s}var Q=function(e){try{var t,n=function(n){var r;if(t)return n;function i(t){return r?t:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var o=function(){if(e instanceof Blob)return Promise.resolve(e.arrayBuffer()).then(function(e){var t=new Uint8Array(e);return r=1,t})}();return o&&o.then?o.then(i):i(o)},r=function(){if(Array.isArray(e))return Promise.resolve(Promise.all(e.map(Q))).then(function(e){for(var n,r=new Uint8Array(e.reduce(function(e,t){return e+t.byteLength},0)),i=0,o=l(e);!(n=o()).done;){var a=n.value;r.set(a,i),i+=a.byteLength}return t=1,r})}();return Promise.resolve(r&&r.then?r.then(n):n(r))}catch(e){return Promise.reject(e)}},$=new Uint8Array([26,69,223,163]);function Z(e,t){var n=globalThis.avatarSDKLogger;null==n||null==n.log||n.log("[Agent][AudioUplink]",e,t)}var ee=/*#__PURE__*/function(){function e(e){this.connectionStartedAt=null,this.connectionGeneration=0,this.sendChain=Promise.resolve(),this.failed=!1,this.pendingFarend=new Map,this.pendingNearend=new Map,this.closedNearendBuckets=new Set,this.lastTimestampByStream=new Map,this.lastSentTimestampByStream=new Map,this.pendingWebmPrefixByStream=new Map,this.farendStreamState="unknown",this.options=e}var t=e.prototype;return t.reset=function(e){void 0===e&&(e=null),this.connectionGeneration+=1,this.connectionStartedAt=e,this.pendingFarend.clear(),this.pendingNearend.clear(),this.closedNearendBuckets.clear(),this.lastTimestampByStream.clear(),this.lastSentTimestampByStream.clear(),this.pendingWebmPrefixByStream.clear(),this.farendStreamState="unknown",this.failed=!1,this.sendChain=Promise.resolve()},t.startInput=function(){this.failed=!1,this.pendingFarend.clear(),this.pendingNearend.clear(),this.closedNearendBuckets.clear(),this.pendingWebmPrefixByStream.clear(),this.farendStreamState="unknown"},t.clearFarend=function(){this.pendingFarend.clear(),this.pendingWebmPrefixByStream.delete(2),this.farendStreamState="unknown"},t.offerFarend=function(e){var t;if(!1!==e.isFirstChunk||"ready"===this.farendStreamState){var n=this.normalizeBlock(2,e);if(n){e.isFirstChunk&&(this.pendingFarend.clear(),this.pendingWebmPrefixByStream.delete(2),this.farendStreamState="ready");var r=null!=(t=this.pendingFarend.get(n.frameKey))?t:[];r.push(n),this.pendingFarend.set(n.frameKey,r),Z("farend.offer",{tsMs:n.tsMs,frameKey:n.frameKey,isFirstChunk:Boolean(n.isFirstChunk),pendingNearend:[].concat(this.pendingNearend.keys())}),this.flushOlderNearend(n.frameKey),this.prune(n.frameKey)}else e.isFirstChunk&&this.abandonFarendStream()}else Z("farend.drop",{reason:"awaiting_webm_header",timestamp:e.timestamp,isFirstChunk:!1})},t.offerNearend=function(e){var t,n=this.normalizeBlock(1,e);if(n&&!this.closedNearendBuckets.has(n.frameKey)){var r=null!=(t=this.pendingNearend.get(n.frameKey))?t:[];r.push(n),this.pendingNearend.set(n.frameKey,r),this.flushExpiredNearend(n.frameKey),this.prune(n.frameKey)}},t.drain=function(){for(var e,t=l([].concat(this.pendingNearend.keys()).sort(function(e,t){return e-t}));!(e=t()).done;)this.flushBucket(e.value,!0);return this.sendChain},t.normalizeBlock=function(e,t){var n=this.connectionStartedAt;if(null===n||!Number.isFinite(t.timestamp))return null;var r=Math.max(0,Math.floor(t.timestamp-n)),i=Math.floor(r/100),o=this.lastTimestampByStream.get(e);return void 0!==o&&r<=o?null:(this.lastTimestampByStream.set(e,r),h({},t,{streamId:e,tsMs:r,frameKey:i}))},t.enqueue=function(e){var t=this,n=this;if(!this.failed){var r=this.connectionGeneration;this.sendChain=this.sendChain.then(function(){try{if(n.failed)return Promise.resolve();var t=function(e,t){if("function"==typeof e[H]){var n,r,i,o=function(e){try{for(;!(n=a.next()).done;)if((e=t(n.value))&&e.then){if(!Y(e))return void e.then(o,i||(i=q.bind(null,r=new J,2)));e=e.v}r?q(r,1,e):r=e}catch(e){q(r||(r=new J),2,e)}},a=e[H]();if(o(),a.return){var s=function(e){try{n.done||a.return()}catch(e){}return e};if(r&&r.then)return r.then(s,function(e){throw s(e)});s()}return r}if(!("length"in e))throw new TypeError("Object is not iterable");for(var u=[],c=0;c<e.length;c++)u.push(e[c]);return function(e,t){var n,r,i=-1;return function o(a){try{for(;++i<e.length;)if((a=t(i))&&a.then){if(!Y(a))return void a.then(o,r||(r=q.bind(null,n=new J,2)));a=a.v}n?q(n,1,a):n=a}catch(e){q(n||(n=new J),2,e)}}(),n}(u,function(e){return t(u[e])})}(e,function(e){var t;return Promise.resolve(Q(null!=(t=e.dataParts)?t:e.data)).then(function(t){if(!n.failed&&r===n.connectionGeneration&&null!==n.connectionStartedAt&&0!==t.byteLength){2===e.streamId&&e.isFirstChunk&&n.pendingWebmPrefixByStream.delete(2);var i=n.coalesceSplitWebmMagic(e.streamId,t);if(i){var o=n.lastSentTimestampByStream.get(e.streamId);void 0!==o&&e.tsMs<=o||(n.options.sendBinary(function(e,t,n){if(1!==e&&2!==e)throw new Error("AU stream_id 无效: "+e);if(!Number.isFinite(t)||t<0||t>4294967295)throw new Error("AU ts_ms 无效: "+t);var r=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength),i=new ArrayBuffer(8+r.byteLength),o=new DataView(i);return o.setUint8(0,65),o.setUint8(1,85),o.setUint8(2,1),o.setUint8(3,e),o.setUint32(4,Math.floor(t),!1),new Uint8Array(i,8).set(r),i}(e.streamId,e.tsMs,i)),n.lastSentTimestampByStream.set(e.streamId,e.tsMs),Z("frame.send",{streamId:e.streamId,tsMs:e.tsMs,bytes:i.byteLength}))}}})});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}).catch(function(e){if(r===t.connectionGeneration){t.failed=!0,t.pendingFarend.clear(),t.pendingNearend.clear();var n=e instanceof Error?e:new Error("AU 音频上行失败");null==t.options.onError||t.options.onError(n)}})}},t.coalesceSplitWebmMagic=function(e,t){var n=this.pendingWebmPrefixByStream.get(e);if(n){var r=new Uint8Array(n.byteLength+t.byteLength);r.set(n),r.set(t,n.byteLength),this.pendingWebmPrefixByStream.delete(e),t=r}return t.byteLength<$.byteLength&&t.every(function(e,t){return e===$[t]})?(this.pendingWebmPrefixByStream.set(e,t.slice()),null):t},t.flushOlderNearend=function(e){for(var t,n=l([].concat(this.pendingNearend.keys()).sort(function(e,t){return e-t}));!(t=n()).done;){var r=t.value;if(r>=e)break;this.flushBucket(r,!0)}},t.flushExpiredNearend=function(e){this.flushOlderNearend(e-1)},t.flushBucket=function(e,t){void 0===t&&(t=!1);var n=this.takeNearend(e);if(n){var r=e-1,i=this.pendingFarend.has(e)||t&&this.pendingFarend.has(r)?this.takeFarendThrough(e):null;this.closedNearendBuckets.add(e),Z("bucket.flush",{nearendFrameKey:e,pairedFarend:Boolean(i),pendingFarend:[].concat(this.pendingFarend.keys())}),this.enqueue(i?[i,n]:[n])}},t.takeNearend=function(e){var t=this.pendingNearend.get(e);return this.pendingNearend.delete(e),null!=t&&t.length?h({},t[0],{dataParts:t.flatMap(function(e){var t;return null!=(t=e.dataParts)?t:[e.data]})}):null},t.takeFarendThrough=function(e){for(var t,n=[],r=l([].concat(this.pendingFarend.keys()).sort(function(e,t){return e-t}));!(t=r()).done;){var i=t.value;if(i>e)break;n.push.apply(n,this.pendingFarend.get(i)),this.pendingFarend.delete(i)}return 0===n.length?null:h({},n[n.length-1],{dataParts:n.map(function(e){return e.data}),isFirstChunk:n.some(function(e){return e.isFirstChunk})})},t.abandonFarendStream=function(){Z("farend.drop",{reason:"stale_bucket_abandons_webm_stream",pendingFarend:[].concat(this.pendingFarend.keys())}),this.pendingFarend.clear(),this.pendingWebmPrefixByStream.delete(2),this.farendStreamState="awaiting-header"},t.prune=function(e){var t=e-3;[].concat(this.pendingFarend.keys()).some(function(e){return e<t})&&this.abandonFarendStream();for(var n,r=l(this.pendingNearend.keys());!(n=r()).done;){var i=n.value;i<t&&this.flushBucket(i,!0)}for(var o,a=l(this.closedNearendBuckets);!(o=a()).done;){var s=o.value;s<t&&this.closedNearendBuckets.delete(s)}},e}(),te=["e2eServer","authToken","audio","reconnect","agentCallbacks","webSocketCtor","asr_id","asr_config","tts_config","features","extras","llm_id","brain_config","session_speak_req_id"];function ne(e,t,n){if(!e.s){if(n instanceof re){if(!n.s)return void(n.o=ne.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(ne.bind(null,e,t),ne.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var re=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var o=1&i?t:n;if(o){try{ne(r,1,o(this.v))}catch(e){ne(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?ne(r,1,t?t(i):i):n?ne(r,1,n(i)):ne(r,2,i)}catch(e){ne(r,2,e)}},r},e}();function ie(e){return e instanceof re&&1&e.s}function oe(e,t,n){for(var r;;){var i=e();if(ie(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!ie(o)){r=1;break}o=o.s}if(t){var a=t();if(a&&a.then&&!ie(a)){r=2;break}}}var s=new re,u=ne.bind(null,s,2);return(0===r?i.then(l):1===r?o.then(c):a.then(h)).then(void 0,u),s;function c(r){o=r;do{if(t&&(a=t())&&a.then&&!ie(a))return void a.then(h).then(void 0,u);if(!(i=e())||ie(i)&&!i.v)return void ne(s,1,o);if(i.then)return void i.then(l).then(void 0,u);ie(o=n())&&(o=o.v)}while(!o||!o.then);o.then(c).then(void 0,u)}function l(e){e?(o=n())&&o.then?o.then(c).then(void 0,u):c(o):ne(s,1,o)}function h(){(i=e())?i.then?i.then(l).then(void 0,u):l(i):ne(s,1,o)}}function ae(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function se(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var ue=2147483647;function ce(e){if(void 0===e)return!1;var t=JSON.stringify(e);return void 0!==t&&"{}"!==t}var le={1006:"E2E WebSocket 异常断开:未收到 Close frame,请检查 E2EMPServer 日志或中间网络",4e3:"E2E WebSocket 路径未知",4001:"E2E Token 无效",4002:"E2E Session 不存在",4009:"E2E 配额超限",4010:"E2E 服务端主动断开"},he=new Set([1001,1006,1011,1012,1013,1014]);function de(e,t,n){if(void 0!==n&&(!n||Array.isArray(n)||"object"!=typeof n))throw new Error("Agent "+e+" JSON Config 必须是对象");if(void 0!==t&&ce(n))throw new Error("Agent "+e+" 配置不能同时提供 ID 和 JSON Config")}function fe(e,t){if(void 0!==t&&(!t||Array.isArray(t)||"object"!=typeof t))throw new Error("Agent "+e+" 必须是对象")}var me=/*#__PURE__*/function(e){function t(t){var n,r,i,o;de("ASR",t.asr_id,t.asr_config),de("TTS",void 0,t.tts_config),de("Brain",t.llm_id,t.brain_config),fe("features",t.features),fe("extras",t.extras);var a,s=t.e2eServer,u=t.authToken,c=t.audio,l=t.reconnect,d=t.agentCallbacks,f=t.webSocketCtor,m=t.asr_id,p=t.asr_config,v=t.tts_config,g=t.features,E=t.extras,S=t.llm_id,y=t.brain_config,R=t.session_speak_req_id,A=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(t,te),b=A.onMessage,_=A.onRenderChange,w=A.onNetworkInfo,P=A.onSpeakStateChange,T=A.onVoiceStateChange,k=A.onAudioPlaybackData,C=function(e){var t;null==(t=a)||t.forwardFarendAudio(e),null==k||k(e)},O=null!=R?R:1,D=function(e){if(e&&ce(e)){var t=e.extra_body;if(void 0!==t&&(!t||Array.isArray(t)||"object"!=typeof t))throw new Error("Agent Brain extra_body 必须是 JSON 对象");return h({},e)}}(y),I=h({},A,{session_speak_req_id:O,sessionRequestData:h({},void 0!==m?{asr_id:m}:{},ce(p)?{asr_config:p}:{},ce(v)?{tts_config:v}:{},ce(g)?{features:g}:{},ce(E)?{extras:E}:{},void 0!==S?{llm_id:S}:{},void 0!==D?{brain_config:D}:{},{session_speak_req_id:O}),enableClientInterrupt:null==(n=A.enableClientInterrupt)||n,onMessage:function(e){var t,n;b(e),null!=(t=a)&&t.reportingInitializationFailure||null==(n=a)||n.emitError("sdk",String(e.code||"AVATAR_ERROR"),e.message||"Avatar SDK 错误",!0,e)},onRenderChange:function(e){var t;null==_||_(e),null==(t=a)||t.safeEmit(function(){return null==d||null==d.onRenderChange?void 0:d.onRenderChange(e)})},onNetworkInfo:function(e){var t;null==w||w(e),null==(t=a)||t.safeEmit(function(){return null==d||null==d.onNetworkInfo?void 0:d.onNetworkInfo(e)})},onSpeakStateChange:function(e,t){var n,r,i;null==P||P(e,t),null==(n=a)||n.safeEmit(function(){return null==d||null==d.onSpeakStateChange?void 0:d.onSpeakStateChange({state:e,clientSpeakId:t})}),["speak_start","start","started"].includes(e)&&(a&&(a.interactionPending=!0,a.voicePlaying=!0),null==(r=a)||r.emitConversation({state:"speaking"})),["speak_end","end","ended","completed","finish","finished"].includes(e)&&(null==(i=a)||i.emitConversation({state:"completed"}))},onVoiceStateChange:function(e,t,n){var r;a&&"start"===e&&(a.voicePlaying=!0),"end"===e&&(a&&(a.voicePlaying=!1),null==(r=a)||r.forwardVoiceEnd()),null==T||T(e,t,n)}},k?{onAudioPlaybackData:C}:{});return(o=e.call(this,I)||this).e2eClient=null,o.microphone=null,o.stopASRPromise=null,o.initializationPromise=null,o.rejectInitialization=null,o.initialSessionAttempt=null,o.initialSessionGeneration=0,o.initialTtsaReadySessionIds=new Set,o.initialTtsaReadyBeforeSession=!1,o.asrStartGeneration=0,o.agentState="idle",o.asrState="idle",o.agentDestroyed=!1,o.agentDestroying=!1,o.destroyPromise=null,o.suppressNextVoiceEnd=!1,o.replaySending=!1,o.farendAudioEnabled=!1,o.reconnectTimer=null,o.reconnectAttempt=0,o.reconnectInFlight=!1,o.sessionReloadFallback=!1,o.waitingForTtsaReload=!1,o.stateBeforeReconnect="ready",o.e2eSessionId="",o.currentE2EUrl="",o.serviceReconnect=null,o.serviceMigration=null,o.interactionPending=!1,o.llmPending=!1,o.llmProducedText=!1,o.directSpeakOpen=!1,o.pendingASR=!1,o.autoSendASRToLLM=!0,o.voicePlaying=!1,o.reportingInitializationFailure=!1,o.handleOnlineForReconnect=function(){o.serviceMigration||"reconnecting"!==o.agentState||o.reconnectInFlight||o.sessionReloadFallback||(o.clearReconnectTimer(),o.scheduleE2EReconnect(!0))},a=o,o.agentOptions={e2eServer:s,authToken:u,audio:c,requestedEnableAec:"boolean"==typeof(null==g||null==(r=g.speech_frontend)?void 0:r.enable_aec)?g.speech_frontend.enable_aec:void 0,callbacks:d,webSocketCtor:f,debugAudioChunks:Boolean(A.enableDebugger)},o.audioInputEnabled=null!=(i=null==c?void 0:c.inputEnabled)&&i,o.autoSendASRToLLM=!1!==(null==g?void 0:g.auto_send_asr_to_llm),o.originalOnAudioPlaybackData=k,o.playbackDataHandler=C,o.reconnectOptions=o.normalizeReconnectOptions(l),o.audioUplink=new ee({sendBinary:function(e){var t;return null==(t=o.e2eClient)?void 0:t.sendBinary(e)},onError:function(e){return o.handleAudioUplinkError(e)}}),o}var n,i;i=e,(n=t).prototype=Object.create(i.prototype),n.prototype.constructor=n,d(n,i);var o=t.prototype;return o.getAgentState=function(){return this.agentState},o.getState=function(){return this.getAgentState()},o.getASRState=function(){return this.asrState},o.init=function(e){var t=this;if(void 0===e&&(e={}),this.initializationPromise)return this.initializationPromise;var n=this.initialize(e).finally(function(){t.initializationPromise===n&&(t.initializationPromise=null)});return this.initializationPromise=n,n},o.initialize=function(t){try{var n=this;n.assertNotDestroyed(),n.setAgentState("initializing");var r=new Promise(function(e,t){n.rejectInitialization=t});return r.catch(function(){}),Promise.resolve(se(function(){return ae(function(){var i=h({},t,{onDownloadProgress:t.onDownloadProgress||function(){}});return Promise.resolve(e.prototype.initializeSession.call(n,i)).then(function(e){var t;function i(e){function t(){n.assertE2EOpen(),n.setAgentState("ready"),n.start()}n.assertNotDestroyed();var r=oe(function(){return!!n.serviceMigration},void 0,function(){return Promise.resolve(n.serviceMigration.completion).then(function(){})});return r&&r.then?r.then(t):t()}if(n.assertNotDestroyed(),!e)throw new Error("XmovAvatar 初始化未返回 sessionInfo");n.applySessionFeatures(e),n.assertNotDestroyed(),n.beginInitialSession(e);var o=oe(function(){return!t},void 0,function(){var e=n.initialSessionAttempt;if(!e)throw new Error("Agent 初始化缺少会话连接任务");return Promise.resolve(Promise.race([Promise.all([e.e2ePromise,e.ttsaReadyPromise]),r])).then(function(){e===n.initialSessionAttempt&&(t=1)})});return o&&o.then?o.then(i):i()})},function(e){function t(){throw e}if(n.serviceMigration&&!n.agentDestroying&&!n.agentDestroyed)throw n.failServiceMigration("E2E_MIGRATION_FAILED","E2E 更新迁移失败"),e;var r=function(){var t;if(!n.agentDestroyed&&!n.agentDestroying)return null==(t=n.e2eClient)||t.disconnect(1e3,"agent_init_failed"),n.e2eClient=null,Promise.resolve(n.cleanupBeforeInitComplete("agent_init_failed")).then(function(){try{n.setAgentState("failed")}catch(e){}n.reportingInitializationFailure=!0;try{n.reportInitializationFailure("Agent 初始化失败",e)}catch(e){}finally{n.reportingInitializationFailure=!1}try{n.emitError("sdk","AGENT_INIT_FAILED","Agent 初始化失败",!0,e)}catch(e){}n.agentDestroyed=!0})}();return r&&r.then?r.then(t):t()})},function(e,t){var r;if(n.rejectInitialization=null,n.initialSessionGeneration+=1,null==(r=n.initialSessionAttempt)||r.resolveTtsaReady(),n.initialSessionAttempt=null,n.initialTtsaReadySessionIds.clear(),n.initialTtsaReadyBeforeSession=!1,e)throw t;return t}))}catch(e){return Promise.reject(e)}},o.beginInitialSession=function(e){var t=this;this.e2eSessionId=e.session_id;var n=this.initialSessionAttempt,r=++this.initialSessionGeneration;null==n||n.resolveTtsaReady();var i=function(){},o=new Promise(function(e){i=e}),a=this.replaceE2EConnection(e.e2e_resp).catch(function(e){if(r===t.initialSessionGeneration)throw e}),s={sessionInfo:e,e2ePromise:a,ttsaReadyPromise:o,resolveTtsaReady:i};return this.initialSessionAttempt=s,this.initialTtsaReadySessionIds.delete(e.session_id)?s.resolveTtsaReady():!n&&this.initialTtsaReadyBeforeSession&&(this.initialTtsaReadyBeforeSession=!1,s.resolveTtsaReady()),a.catch(function(){}),a},o.start=function(){var t;"initializing"!==this.agentState&&"running"!==this.agentState&&("reconnecting"!==this.agentState?(this.assertE2EOpen(),e.prototype.start.call(this),this.setAgentState("running")):this.waitingForTtsaReload&&null!=(t=this.e2eClient)&&t.isOpen&&("running"===this.stateBeforeReconnect&&e.prototype.start.call(this),this.finishReconnect()))},o.onTtsaReady=function(t){if(this.rejectInitialization){var n=this.initialSessionAttempt,r=null==t?void 0:t.session_id;!n||r&&n.sessionInfo.session_id!==r?r?this.initialTtsaReadySessionIds.add(r):this.initialTtsaReadyBeforeSession=!0:n.resolveTtsaReady()}else"reconnecting"!==this.agentState?"running"===this.agentState&&e.prototype.start.call(this):this.start()},o.abortInitialization=function(e){var t;null==(t=this.rejectInitialization)||t.call(this,e)},o.stop=function(){try{var t=this;if(t.agentDestroyed)return Promise.resolve();var n="reconnecting"===t.agentState;return n&&(t.stateBeforeReconnect="stopped",t.serviceMigration&&(t.serviceMigration.previousState="stopped")),Promise.resolve(t.stopASR()).then(function(){return Promise.resolve(e.prototype.stop.call(t)).then(function(){n||t.setAgentState("stopped")})})}catch(e){return Promise.reject(e)}},o.switchInvisibleMode=function(){try{var t=this,n=t.getStatus(),i=n===r.online||n===r.visible;e.prototype.switchInvisibleMode.call(t);var o=function(){if(i)return Promise.resolve(t.stopASR()).then(function(){})}();return Promise.resolve(o&&o.then?o.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},o.destroy=function(e){var t=this;return void 0===e&&(e="js_sdk_exit"),this.destroyPromise?this.destroyPromise:this.agentDestroyed?("destroyed"!==this.agentState&&this.setAgentState("destroyed"),Promise.resolve()):(this.agentDestroying=!0,this.destroyPromise=Promise.resolve().then(function(){return t.finishDestroy(e)}),this.destroyPromise)},o.finishDestroy=function(e){try{var t=function(){function t(){var t=se(function(){return Promise.resolve(n.disconnectClientForDestroy(e)).then(function(){})},function(e,t){if(n.agentDestroyed=!0,n.agentDestroying=!1,n.setAgentState("destroyed"),e)throw t;return t});if(t&&t.then)return t.then(function(){})}var r=n.e2eClient,i=se(function(){return Promise.resolve(null==r?void 0:r.disconnectAndWait(1e3,e)).then(function(){})},function(e,t){if(n.e2eClient===r&&(n.e2eClient=null),n.audioUplink.reset(),e)throw t;return t});return i&&i.then?i.then(t):t()},n=this;n.abortInitialization(new Error("Agent 初始化已取消")),n.cancelServiceMigration(),n.serviceReconnect=null,n.cancelReconnect(),n.cancelSessionRestart();var r=ae(function(){return Promise.resolve(n.stopASR()).then(function(){})},function(e){n.emitError("sdk","AGENT_ASR_STOP_FAILED","Agent 销毁时停止 ASR 失败",!1,e)});return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},o.ask=function(e){try{var t=this;return t.assertRunning(),t.interactionPending=!0,t.llmPending=!0,t.llmProducedText=!1,t.suppressNextVoiceEnd=!1,t.emitConversation({state:"asking",text:e}),t.sendControl({type:"ask",message:{text:e}}),Promise.resolve()}catch(e){return Promise.reject(e)}},o.speak=function(t,n,r){var i;if(void 0===n&&(n=!0),void 0===r&&(r=!0),this.replaySending)return r&&(this.suppressNextVoiceEnd=!0),e.prototype.speak.call(this,t,n,r,arguments[3]);"draining"===(null==(i=this.serviceMigration)?void 0:i.phase)&&this.directSpeakOpen&&!n?this.assertE2EOpen():this.assertRunning(),this.interactionPending=!0,this.directSpeakOpen=!r,this.suppressNextVoiceEnd=!1,n&&this.emitConversation({state:"speaking-directly",text:t}),this.sendControl({type:"speak",message:{text:t,is_start:n,is_end:r}})},o.handleReplaySend=function(t){if(!this.serviceMigration){var n=this.replaySending;this.replaySending=!0;try{e.prototype.handleReplaySend.call(this,t)}finally{this.replaySending=n}}},o.speakByE2E=function(e){try{return this.speak(e),Promise.resolve()}catch(e){return Promise.reject(e)}},o.startASR=function(e){void 0===e&&(e={});try{var t=function(){var t;if(null==(t=n.microphone)||!t.isRecording){n.assertAudioChunkDuration();var r=e.inputStream?n.cloneASRInputStream(e.inputStream):void 0,i=++n.asrStartGeneration,o=!n.audioInputEnabled,a=new X({audio:n.agentOptions.audio,debugAudioChunks:n.agentOptions.debugAudioChunks,inputStream:r,usePcmWebCodecs:n.farendAudioEnabled,onFrame:function(e,t){var r,i;if(("running"===n.agentState||"draining"===(null==(r=n.serviceMigration)?void 0:r.phase))&&null!=(i=n.e2eClient)&&i.isOpen)try{var o;n.sendAudioFrame({data:e,timestamp:null!=t?t:Date.now()-((null==(o=n.agentOptions.audio)?void 0:o.chunkMs)||v.chunkMs)})}catch(e){n.stopASRAfterSocketClose()}},onError:function(e){return n.handleMicrophoneError(a,e)}});return n.microphone=a,ae(function(){return n.audioUplink.startInput(),o&&n.enableAudioInput(),n.emitConversation({state:"asking"}),n.assertASRStartActive(i),n.setASRState("requesting-permission"),n.assertASRStartActive(i),n.setASRState("starting"),n.assertASRStartActive(i),Promise.resolve(a.start()).then(function(){n.assertRunning(),n.farendAudioEnabled&&n.restartAudioPlaybackCapture(),n.setASRState("listening")})},function(e){return Promise.resolve(a.stop()).then(function(){var t,r,s="AUDIO_FIXED_TRACK_CANCELLED"===(null==e?void 0:e.agentCode),u=i===n.asrStartGeneration,c=!n.agentDestroyed&&!n.agentDestroying&&"running"===n.agentState&&Boolean(null==(t=n.e2eClient)?void 0:t.isOpen);if(n.microphone===a&&(n.microphone=null),u&&!s&&o&&null!=(r=n.e2eClient)&&r.isOpen)try{n.disableAudioInput()}catch(e){}throw!u||n.agentDestroyed||n.agentDestroying||(s&&c?n.setASRState("idle"):s||n.setASRState("failed")),s&&!c&&n.assertRunning(),e})})}},n=this;n.assertASRStartAllowed(),n.suppressNextVoiceEnd=!1;var r=function(){if(n.stopASRPromise)return Promise.resolve(n.stopASRPromise).then(function(){n.assertASRStartAllowed()})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},o.cloneASRInputStream=function(e){var t=e.getAudioTracks().find(function(e){return"ended"!==e.readyState});if(!t)throw new Error("ASR 输入流不包含有效音频轨道");return new MediaStream([t.clone()])},o.assertASRStartActive=function(e){if(e!==this.asrStartGeneration){var t=new Error("麦克风启动已取消");throw t.name="AbortError",t.agentCode="AUDIO_FIXED_TRACK_CANCELLED",t.retryable=!0,t}},o.stopASR=function(){var e=this;if(this.asrStartGeneration+=1,this.stopASRPromise)return this.stopASRPromise;var t,n=this.microphone;return null!=n&&n.isRecording?(this.microphone=null,this.stopASRPromise=this.finishStopASR(n).finally(function(){e.stopASRPromise=null}),this.stopASRPromise):(null!=(t=this.e2eClient)&&t.isOpen&&this.disableAudioInput(),Promise.resolve())},o.finishStopASR=function(e,t){void 0===t&&(t=!0);try{var n=this;return n.setASRState("stopping"),Promise.resolve(e.stop()).then(function(){return Promise.resolve(n.audioUplink.drain()).then(function(){t?(n.disableAudioInput(),n.setASRState("idle")):n.setASRState("failed")})})}catch(e){return Promise.reject(e)}},o.interrupt=function(){if(this.agentDestroyed||this.agentDestroying||this.serviceMigration&&"draining"!==this.serviceMigration.phase)return 0;this.sendControl({type:"interrupt"});var t=e.prototype.interrupt.call(this,"speak");return this.interactionPending=!1,this.llmPending=!1,this.llmProducedText=!1,this.directSpeakOpen=!1,this.pendingASR=!1,this.voicePlaying=!1,this.emitConversation({state:"interrupted"}),this.checkServiceMigration(),t},o.interruptConversation=function(e){void 0===e&&(e="user");try{return this.interrupt(),Promise.resolve()}catch(e){return Promise.reject(e)}},o.onSessionReloaded=function(e){try{var t,n=function(n){return t?n:("reconnecting"!==r.agentState&&(r.stateBeforeReconnect=r.readRestorableState(),r.setAgentState("reconnecting")),r.clearReconnectTimer(),r.sessionReloadFallback=!0,r.applySessionFeatures(e),Promise.resolve(r.replaceE2EConnection(e.e2e_resp)).then(function(){r.waitingForTtsaReload=!0,r.sessionReloadFallback=!1}))},r=this;if(r.agentDestroyed||r.agentDestroying)return Promise.resolve();r.cancelServiceMigration(),r.serviceReconnect=null,r.e2eSessionId=e.session_id;var i=function(){if(r.rejectInitialization)return r.applySessionFeatures(e),Promise.resolve(r.beginInitialSession(e)).then(function(){t=1})}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(e){return Promise.reject(e)}},o.onSessionReloadExhausted=function(e){this.rejectInitialization?this.abortInitialization(e instanceof Error?e:new Error("Agent 初始化期间 TTSA Session 恢复失败")):"reconnecting"===this.agentState&&this.failReconnect(e)},o.replaceE2EConnection=function(e,t){void 0===t&&(t=!0);try{var n=this,r=n.resolveE2EConnection(e),i=r.wsUrl,o=r.token;n.currentE2EUrl=i;var a,s=n.e2eClient;n.audioUplink.reset(),a=new p({wsUrl:i,token:o,audioInputEnabled:n.audioInputEnabled,WebSocketCtor:n.agentOptions.webSocketCtor,onStateChange:function(e){n.e2eClient===a&&("open"===e&&n.audioUplink.reset(Date.now()),n.safeEmit(function(){var t;return null==(t=n.agentOptions.callbacks)||null==t.onSocketStateChange?void 0:t.onSocketStateChange(e)}))},onEvent:function(e){var t,r;n.e2eClient===a&&"closing"!==(null==(t=n.serviceMigration)?void 0:t.phase)&&"failed"!==(null==(r=n.serviceMigration)?void 0:r.phase)&&n.handleServerEvent(e)},onError:function(e){n.e2eClient===a&&"initializing"!==n.agentState&&"reconnecting"!==n.agentState&&n.emitError("network","E2E_SOCKET_ERROR",e.message,!0,e)},onClose:function(e){n.e2eClient===a&&n.handleSocketClose(e)}}),n.e2eClient=a,null==s||s.disconnect(1e3,"e2e_connection_replaced");var u=function(){if(t)return Promise.resolve(a.connect()).then(function(){})}();return Promise.resolve(u&&u.then?u.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},o.resolveE2EConnection=function(e){var t=Boolean(null==e?void 0:e.ws_url),n=Boolean(null==e?void 0:e.e2e_token);if(t!==n)throw new Error("统一 session 响应的 e2e_resp 必须同时返回 ws_url 和 e2e_token");if(t&&n)return{wsUrl:null==e?void 0:e.ws_url,token:null==e?void 0:e.e2e_token};var r=Boolean(this.agentOptions.e2eServer);if(r!==Boolean(this.agentOptions.authToken))throw new Error("e2eServer 和 authToken 必须同时配置");if(!r)throw new Error("统一 session 响应未返回 e2e_resp.ws_url,且未配置 e2eServer");return{wsUrl:this.agentOptions.e2eServer,token:this.agentOptions.authToken}},o.sendControl=function(e){try{var t;null==(t=this.e2eClient)||t.send(e)}catch(e){throw this.emitError("network","E2E_SEND_FAILED","E2E WebSocket 发送失败",!0,e),e}},o.assertAudioChunkDuration=function(){var e,t=(null==(e=this.agentOptions.audio)?void 0:e.chunkMs)||v.chunkMs;if(this.farendAudioEnabled&&t!==v.chunkMs){var n=new Error("AU v1 音频分片固定为 100ms");throw n.name="NotSupportedError",n.agentCode="AUDIO_CHUNK_DURATION_UNSUPPORTED",n.retryable=!1,this.emitError("sdk",n.agentCode,n.message,n.retryable,n),n}},o.sendAudioFrame=function(e){if(this.farendAudioEnabled)this.agentOptions.debugAudioChunks&&P("[Agent][E2E] nearend AU chunk",e.data,{timestamp:e.timestamp,stream_id:1}),this.audioUplink.offerNearend(e);else{this.agentOptions.debugAudioChunks&&P("[Agent][E2E] nearend raw WebM/Opus chunk",e.data,{timestamp:e.timestamp});try{var t;null==(t=this.e2eClient)||t.sendBinary(e.data)}catch(e){this.handleAudioUplinkError(e instanceof Error?e:new Error("E2E nearend 音频帧发送失败"))}}},o.handleAudioUplinkError=function(e){var t=this;this.emitError("network","E2E_AUDIO_SEND_FAILED",this.farendAudioEnabled?"E2E AU 音频帧发送失败":"E2E 音频帧发送失败",!0,e);var n=this.microphone;if(null!=n&&n.isRecording&&!this.stopASRPromise){this.setASRState("failed"),this.microphone=null;var r=this.finishFailedASR(n).finally(function(){t.stopASRPromise===r&&(t.stopASRPromise=null)});this.stopASRPromise=r}},o.applySessionFeatures=function(e){var t,n,r,i,o,a,s,u,c,l=null!=(t=null==(n=e.e2e_resp)||null==(n=n.features)?void 0:n.auto_send_asr_to_llm)?t:null==(r=e.features)?void 0:r.auto_send_asr_to_llm;"boolean"==typeof l&&(this.autoSendASRToLLM=l);var h=null!=(i=null==(o=e.e2e_resp)||null==(o=o.features)||null==(o=o.speech_frontend)?void 0:o.enable_aec)?i:null==(a=e.features)||null==(a=a.speech_frontend)?void 0:a.enable_aec;if(this.farendAudioEnabled="boolean"==typeof h?h:null!=(s=null!=(u=this.agentOptions.requestedEnableAec)?u:null==(c=this.agentOptions.audio)?void 0:c.echoCancellationEnabled)&&s,this.farendAudioEnabled||this.audioUplink.clearFarend(),this.farendAudioEnabled||this.originalOnAudioPlaybackData)return this.setAudioPlaybackDataHandler(this.playbackDataHandler),void(this.farendAudioEnabled&&this.enableAudioPlaybackCapture());this.setAudioPlaybackDataHandler(void 0)},o.forwardFarendAudio=function(e){var t,n,r,i=Boolean(null==(t=this.microphone)?void 0:t.isRecording),o=Boolean(null==(n=this.e2eClient)?void 0:n.isOpen);this.farendAudioEnabled&&i&&o?(this.agentOptions.debugAudioChunks&&P("[Agent][E2E] farend AU chunk",e.data,{timestamp:e.timestamp,stream_id:2,codec:e.codec,sampleRate:e.sampleRate,channels:1,samples:e.samples,speech_id:e.speech_id,isFirstChunk:e.isFirstChunk}),this.audioUplink.offerFarend({data:e.data,timestamp:e.timestamp,isFirstChunk:e.isFirstChunk})):null==(r=globalThis.avatarSDKLogger)||null==r.log||r.log("[Agent][AudioUplink]","farend.drop",{reason:this.farendAudioEnabled?i?"e2e_not_open":"microphone_not_recording":"aec_disabled",timestamp:e.timestamp,isFirstChunk:e.isFirstChunk})},o.handleMicrophoneError=function(e,t){var n,r=this,i=t,o="MediaRecorderError"===t.name,a="AudioEncoderError"===t.name,s=o||a,u="NotSupportedError"===t.name,c=Boolean(i.agentCode);if(s&&this.microphone===e&&"stopping"!==this.asrState){this.microphone=null;var l=this.finishFailedASR(e).finally(function(){r.stopASRPromise===l&&(r.stopASRPromise=null)});this.stopASRPromise=l}this.emitError(s?"asr":c||u?"sdk":"permission",i.agentCode||(o?"MEDIA_RECORDER_ERROR":a?"AUDIO_ENCODER_ERROR":"MICROPHONE_ERROR"),t.message,null!=(n=i.retryable)?n:!u,t)},o.finishFailedASR=function(e){try{var t=function(){try{n.disableAudioInput()}catch(e){}},n=this,r=ae(function(){return Promise.resolve(e.stop()).then(function(){return Promise.resolve(n.audioUplink.drain()).then(function(){})})},function(e){n.emitError("sdk","MICROPHONE_CLEANUP_FAILED","麦克风异常后的资源清理失败",!1,e)});return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},o.enableAudioInput=function(){var e;this.audioInputEnabled||(this.sendControl({type:"event",message:"audio_input_on"}),this.audioInputEnabled=!0,null==(e=this.e2eClient)||e.setAudioInputEnabled(!0))},o.disableAudioInput=function(){var e;this.audioInputEnabled&&(this.sendControl({type:"event",message:"audio_input_off"}),this.audioInputEnabled=!1,null==(e=this.e2eClient)||e.setAudioInputEnabled(!1))},o.handleServerEvent=function(e){var t;if(!this.agentDestroyed&&!this.agentDestroying)switch(e.type){case"service_update":return void this.handleServiceUpdate(e);case"pong":default:return;case"asr_result":return void this.handleASRResult(e);case"llm_response":return void this.handleLLMResponse(e);case"semantic_judge_round_result":return void this.handleSemanticJudgeResult(e);case"volume_and_repetition_text_response":return void(!0===(null==(t=e.message)?void 0:t.skip)&&(this.pendingASR=!1,this.checkServiceMigration()));case"error":return void this.handleBackendError(e)}},o.handleASRResult=function(e){var t=this;this.autoSendASRToLLM&&(this.pendingASR="string"==typeof e.text&&Boolean(e.text.trim()));var n={text:"string"==typeof e.text?e.text:"",isFinal:!0===e.is_final,raw:e};this.safeEmit(function(){var e;return null==(e=t.agentOptions.callbacks)||null==e.onASRResult?void 0:e.onASRResult(n)}),this.checkServiceMigration()},o.handleLLMResponse=function(e){var t=this;if("chunk"===e.event||"done"===e.event){this.llmPending="done"!==e.event,this.pendingASR=!1,"chunk"===e.event&&e.text&&(this.interactionPending=!0,this.llmProducedText=!0),"done"===e.event&&(this.llmProducedText||(this.interactionPending=!1),this.llmProducedText=!1);var n=e.usage,r=h({event:e.event},"string"==typeof e.text?{text:e.text}:{},!0===e.is_first?{isFirst:!0}:{},n?{usage:{promptTokens:this.readFiniteNumber(n.prompt_tokens),completionTokens:this.readFiniteNumber(n.completion_tokens),totalTokens:this.readFiniteNumber(n.total_tokens),cachedTokens:this.readFiniteNumber(n.cached_tokens)}}:{},{raw:e});this.safeEmit(function(){var e;return null==(e=t.agentOptions.callbacks)||null==e.onLLMResponse?void 0:e.onLLMResponse(r)}),this.checkServiceMigration()}},o.handleSemanticJudgeResult=function(e){var t=this;if(e.message&&"object"==typeof e.message){var n=e.message,r={query:"string"==typeof n.query?n.query:"",meaningful:!0===n.meaningful,action:"string"==typeof n.action?n.action:"",raw:e};this.safeEmit(function(){var e;return null==(e=t.agentOptions.callbacks)||null==e.onSemanticJudgeResult?void 0:e.onSemanticJudgeResult(r)}),!1===n.meaningful&&(this.pendingASR=!1,this.checkServiceMigration())}},o.forwardVoiceEnd=function(){var e,t;if(this.suppressNextVoiceEnd)return this.suppressNextVoiceEnd=!1,this.interactionPending=!1,void this.checkServiceMigration();if(!(this.agentDestroyed||this.agentDestroying||"running"!==this.agentState&&"draining"!==(null==(e=this.serviceMigration)?void 0:e.phase)||null==(t=this.e2eClient))&&t.isOpen)try{this.sendControl({type:"event",message:"voice_end"}),this.interactionPending=!1,this.checkServiceMigration()}catch(e){}},o.readFiniteNumber=function(e){return"number"==typeof e&&Number.isFinite(e)?e:0},o.handleBackendError=function(e){var t,n=["permission","network","asr","brain","ttsa","quota","sdk"].includes(e.domain)?e.domain:"sdk",r=String(null!=(t=e.code)?t:"BACKEND_ERROR"),i="string"==typeof e.message?e.message:"E2E 后端错误";"asr"===n&&(this.stopASRAfterSocketClose(),this.pendingASR=!1),"brain"===n&&(this.pendingASR=!1,this.llmPending=!1,this.llmProducedText||(this.interactionPending=!1)),this.emitConversation({state:"failed"}),this.emitError(n,r,i,"quota"!==n,e),this.checkServiceMigration()},o.handleServiceUpdate=function(e){var t;if(!this.serviceMigration||"connecting"===this.serviceMigration.phase&&null!=(t=this.e2eClient)&&t.isOpen){var n=null,r=e.grace_period_ms;try{var i=e.reconnect;if(!i||"string"!=typeof i.ws_url||"string"!=typeof i.e2e_token||!i.e2e_token||i.session_id!==this.e2eSessionId||"number"!=typeof r||!Number.isSafeInteger(r)||r<0||r>ue||"number"!=typeof i.expires_in_ms||!Number.isSafeInteger(i.expires_in_ms)||i.expires_in_ms<=0||i.expires_in_ms>ue)throw new Error("Invalid migration payload");var o=new URL(i.ws_url);if(!["ws:","wss:"].includes(o.protocol)||o.username||o.password||o.hash||this.currentE2EUrl.startsWith("wss:")&&"wss:"!==o.protocol||1!==o.searchParams.getAll("session_id").length||o.searchParams.get("session_id")!==this.e2eSessionId||1!==o.searchParams.getAll("token").length||o.searchParams.get("token")!==i.e2e_token)throw new Error("Invalid migration URL");n={session_id:this.e2eSessionId,ws_url:i.ws_url,e2e_token:i.e2e_token,expiresAt:Date.now()+i.expires_in_ms,attempts:0}}catch(e){return void(this.serviceMigration?this.failServiceMigration("E2E_SERVICE_UPDATE_INVALID","服务更新缺少有效的同房重连凭据"):this.startServiceMigration(null,0))}this.serviceMigration&&(this.stateBeforeReconnect=this.serviceMigration.previousState,this.cancelServiceMigration()),this.serviceReconnect=n,this.startServiceMigration(n,r)}},o.startServiceMigration=function(e,t){var n,r=this;if(!(this.serviceMigration||this.agentDestroyed||this.agentDestroying)){var i="reconnecting"===this.agentState?this.stateBeforeReconnect:this.agentState;this.cancelReconnect();var o=function(){},a=function(e){},s=new Promise(function(e,t){o=e,a=t});s.catch(function(){});var u={reconnect:e,previousState:i,phase:"draining",departAt:Date.now()+Math.max(0,t-3e3),quietUntil:0,audioStopped:!1,timer:null,expiryTimer:null,completion:s,resolve:o,reject:a};if(this.serviceMigration=u,this.stateBeforeReconnect=this.readRestorableState(),e){if(u.expiryTimer=setTimeout(function(){r.failServiceMigration("E2E_MIGRATION_TOKEN_EXPIRED","E2E 迁移凭据已过期,请结束会话后重新初始化")},Math.max(0,e.expiresAt-Date.now())),this.setMigrationState("reconnecting"),this.serviceMigration===u&&!this.agentDestroying){var c=Boolean((null==(n=this.microphone)?void 0:n.isRecording)||this.stopASRPromise||this.audioInputEnabled);u.timer=setTimeout(function(){r.closeForServiceMigration(u)},Math.max(0,u.departAt-Date.now())),this.stopASR().then(function(){r.serviceMigration===u&&"draining"===u.phase&&(u.audioStopped=!0,u.quietUntil=Date.now()+(c?2e3:0),r.checkServiceMigration())}).catch(function(){r.serviceMigration===u&&r.failServiceMigration("E2E_MIGRATION_AUDIO_STOP_FAILED","E2E 迁移时停止音频失败")})}}else this.failServiceMigration("E2E_SERVICE_UPDATE_INVALID","服务更新缺少有效的同房重连凭据")}},o.checkServiceMigration=function(){var e=this,t=this.serviceMigration;if(t&&"draining"===t.phase&&t.audioStopped){var n=t.quietUntil-Date.now();Date.now()>=t.departAt||n<=0&&!this.interactionPending&&!this.llmPending&&!this.directSpeakOpen&&!this.pendingASR&&!this.voicePlaying?this.closeForServiceMigration(t):n>0?(null!==t.timer&&clearTimeout(t.timer),t.timer=setTimeout(function(){return e.checkServiceMigration()},Math.max(0,Math.min(n,t.departAt-Date.now())))):(null!==t.timer&&clearTimeout(t.timer),t.timer=setTimeout(function(){e.closeForServiceMigration(t)},Math.max(0,t.departAt-Date.now())))}},o.closeForServiceMigration=function(e){try{var t=this;if(t.serviceMigration!==e||"draining"!==e.phase||t.agentDestroying||t.agentDestroyed)return Promise.resolve();e.phase="closing",null!==e.timer&&clearTimeout(e.timer),e.timer=null,t.audioUplink.reset(),t.audioInputEnabled=!1;var n=t.e2eClient;return Promise.resolve(null==n?void 0:n.disconnectAndWait(1e3,"service_update",3e3)).then(function(r){var i;function o(n){var r;if(i)return n;t.serviceMigration!==e||t.agentDestroying||t.agentDestroyed||(e.phase="connecting",t.interactionPending=!1,t.llmPending=!1,t.llmProducedText=!1,t.directSpeakOpen=!1,t.pendingASR=!1,t.voicePlaying=!1,t.scheduleServiceReconnect(e,0===(null==(r=e.reconnect)?void 0:r.attempts)))}if(t.serviceMigration===e&&"closing"===e.phase&&!t.agentDestroying&&!t.agentDestroyed){if(!1!==r){t.e2eClient===n&&(t.e2eClient=null);var a=ae(function(){return Promise.resolve(t.replaceE2EConnection(e.reconnect,!1)).then(function(){})},function(){t.serviceMigration===e&&t.failServiceMigration("E2E_MIGRATION_FAILED","创建迁移连接失败"),i=1});return a&&a.then?a.then(o):o(a)}t.failServiceMigration("E2E_MIGRATION_CLOSE_TIMEOUT","旧 E2E 未确认关闭,已停止迁移以避免双连接")}})}catch(e){return Promise.reject(e)}},o.scheduleServiceReconnect=function(e,t){var n,r,i=this;if(void 0===t&&(t=!1),!(this.serviceMigration!==e||"connecting"!==e.phase||this.agentDestroying||this.agentDestroyed||this.reconnectInFlight)){null!==e.timer&&clearTimeout(e.timer);var o=t?0:Math.max(100,this.getReconnectDelay((null!=(n=null==(r=e.reconnect)?void 0:r.attempts)?n:1)-1));e.timer=setTimeout(function(){i.attemptServiceReconnect(e)},o)}},o.attemptServiceReconnect=function(e){try{var t=this;if(t.serviceMigration!==e||"connecting"!==e.phase||t.agentDestroying||t.agentDestroyed)return Promise.resolve();e.timer=null;var n=t.e2eClient;if(!n||!e.reconnect)return Promise.resolve();if(Date.now()>=e.reconnect.expiresAt)return t.failServiceMigration("E2E_MIGRATION_TOKEN_EXPIRED","E2E 迁移凭据已过期,请结束会话后重新初始化"),Promise.resolve();t.reconnectInFlight=!0,e.reconnect.attempts+=1;var r=setTimeout(function(){return n.disconnect(1e3,"migration_connect_timeout")},1e4);return Promise.resolve(se(function(){return ae(function(){return Promise.resolve(n.connect()).then(function(){if(clearTimeout(r),t.serviceMigration===e&&n.isOpen&&!t.agentDestroying&&!t.agentDestroyed)return Promise.resolve(t.stopASRPromise).then(function(){if(t.serviceMigration===e&&n.isOpen&&!t.agentDestroying&&!t.agentDestroyed){try{t.setASRState("idle")}catch(e){}if(t.serviceMigration===e&&!t.agentDestroyed&&!t.agentDestroying){var r=e.previousState;t.cancelServiceMigration(),t.setMigrationState(r)}}})})},function(){})},function(n,i){if(clearTimeout(r),t.serviceMigration===e&&(t.reconnectInFlight=!1,t.scheduleServiceReconnect(e)),n)throw i;return i}))}catch(e){return Promise.reject(e)}},o.failServiceMigration=function(e,t){var n,r=this.serviceMigration;r&&"failed"!==r.phase&&(r.phase="failed",null!==r.timer&&clearTimeout(r.timer),null!==r.expiryTimer&&clearTimeout(r.expiryTimer),r.timer=null,r.expiryTimer=null,this.cancelReconnect(),this.stopASRAfterSocketClose(),null==(n=this.e2eClient)||n.disconnect(1e3,"migration_failed"),r.reject(new Error(t)),this.abortInitialization(new Error(t)),this.setMigrationState("failed"),this.emitError("E2E_CLOSE_4009"===e?"quota":"network",e,t,!1))},o.setMigrationState=function(e){try{this.setAgentState(e)}catch(e){}},o.cancelServiceMigration=function(){var e=this.serviceMigration;e&&(this.serviceMigration=null,null!==e.timer&&clearTimeout(e.timer),null!==e.expiryTimer&&clearTimeout(e.expiryTimer),this.reconnectInFlight=!1,e.resolve())},o.handleSocketClose=function(e){if(!this.agentDestroyed&&!this.agentDestroying)if(this.serviceMigration){var t=this.serviceMigration;"draining"===t.phase?4011===e.code||he.has(e.code)?this.closeForServiceMigration(t):this.failServiceMigration("E2E_CLOSE_"+e.code,"E2E 更新迁移被服务端终止"):"connecting"===t.phase&&(4011===e.code||he.has(e.code)?this.scheduleServiceReconnect(t):this.failServiceMigration("E2E_CLOSE_"+e.code,"E2E 更新迁移被服务端终止"))}else if(4011!==e.code)if(this.rejectInitialization)this.abortInitialization(new Error(("Agent 初始化期间 E2E WebSocket 已关闭: "+e.code+" "+(e.reason||"")).trim()));else if(this.audioUplink.reset(),this.stopASRAfterSocketClose(),this.shouldReconnect(e))this.beginReconnect(e);else{this.setAgentState("failed");var n=4009===e.code?"quota":"network";this.emitError(n,"E2E_CLOSE_"+e.code,e.reason||le[e.code]||"E2E WebSocket 已关闭","quota"!==n,{code:e.code,reason:e.reason,wasClean:e.wasClean})}else this.startServiceMigration(this.serviceReconnect,0)},o.shouldReconnect=function(e){return this.reconnectOptions.enabled&&"idle"!==this.agentState&&"initializing"!==this.agentState&&"destroyed"!==this.agentState&&he.has(e.code)},o.beginReconnect=function(e){var t;"reconnecting"!==this.agentState&&(this.stateBeforeReconnect=this.readRestorableState(),this.reconnectAttempt=0,this.sessionReloadFallback=!1,this.setAgentState("reconnecting"),null==globalThis.addEventListener||globalThis.addEventListener("online",this.handleOnlineForReconnect),this.emitError("network","E2E_RECONNECTING","E2E WebSocket 已断开,正在重连",!0,{code:e.code,reason:e.reason,wasClean:e.wasClean})),this.audioInputEnabled=!1,null==(t=this.e2eClient)||t.setAudioInputEnabled(!1),this.scheduleE2EReconnect(!1)},o.scheduleE2EReconnect=function(e){var t=this;if(!(this.agentDestroyed||this.agentDestroying||this.serviceMigration||"reconnecting"!==this.agentState||null!==this.reconnectTimer||this.reconnectInFlight||this.sessionReloadFallback))if(this.reconnectAttempt>=this.reconnectOptions.maxAttempts)this.fallbackToSessionReload();else{var n=e?0:this.getReconnectDelay(this.reconnectAttempt);this.reconnectTimer=globalThis.setTimeout(function(){t.reconnectTimer=null,t.attemptE2EReconnect()},n)}},o.attemptE2EReconnect=function(){try{var e=this,t=e.e2eClient;if(!t||e.serviceMigration||e.agentDestroyed||e.agentDestroying||"reconnecting"!==e.agentState)return Promise.resolve();e.reconnectInFlight=!0,e.reconnectAttempt+=1;var n=se(function(){return ae(function(){return Promise.resolve(t.connect()).then(function(){e.e2eClient!==t||e.serviceMigration||e.agentDestroyed||e.agentDestroying||e.waitingForTtsaReload||e.finishReconnect()})},function(){e.e2eClient!==t||e.serviceMigration||e.agentDestroyed||e.agentDestroying||e.scheduleE2EReconnect(!1)})},function(n,r){if(e.e2eClient!==t||e.serviceMigration||(e.reconnectInFlight=!1),e.e2eClient!==t||e.serviceMigration||"reconnecting"!==e.agentState||null!==e.reconnectTimer||e.sessionReloadFallback||e.scheduleE2EReconnect(!1),n)throw r;return r});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},o.fallbackToSessionReload=function(){try{var e=this;if(e.serviceMigration||e.sessionReloadFallback||e.agentDestroyed||e.agentDestroying)return Promise.resolve();e.sessionReloadFallback=!0,e.clearReconnectTimer();var t=ae(function(){return Promise.resolve(e.restartSessionForTransport("e2e_reconnect_exhausted")).then(function(){})},function(t){e.failReconnect(t)});return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},o.finishReconnect=function(){var e=this.stateBeforeReconnect;this.cancelReconnect(),"idle"!==this.asrState&&this.setASRState("idle"),this.setAgentState(e)},o.failReconnect=function(e){this.cancelReconnect(),this.setAgentState("failed"),this.emitConversation({state:"failed"}),this.emitError("network","E2E_RECONNECT_EXHAUSTED","E2E WebSocket 重连失败,请重新初始化 Agent",!1,e)},o.cancelReconnect=function(){this.clearReconnectTimer(),null==globalThis.removeEventListener||globalThis.removeEventListener("online",this.handleOnlineForReconnect),this.reconnectAttempt=0,this.reconnectInFlight=!1,this.sessionReloadFallback=!1,this.waitingForTtsaReload=!1},o.clearReconnectTimer=function(){null!==this.reconnectTimer&&(globalThis.clearTimeout(this.reconnectTimer),this.reconnectTimer=null)},o.getReconnectDelay=function(e){if(0===this.reconnectOptions.initialDelayMs)return 0;var t=Math.min(this.reconnectOptions.maxDelayMs,this.reconnectOptions.initialDelayMs*Math.pow(2,e));return 0===t?0:Math.round(t*(.8+.4*Math.random()))},o.readRestorableState=function(){return"running"===this.agentState||"stopped"===this.agentState||"ready"===this.agentState?this.agentState:"ready"},o.normalizeReconnectOptions=function(e){var t,n=this.readNonNegativeNumber(null==e?void 0:e.initialDelayMs,500);return{enabled:null==(t=null==e?void 0:e.enabled)||t,maxAttempts:Math.max(1,Math.floor(this.readNonNegativeNumber(null==e?void 0:e.maxAttempts,6))),initialDelayMs:n,maxDelayMs:Math.max(n,this.readNonNegativeNumber(null==e?void 0:e.maxDelayMs,8e3))}},o.readNonNegativeNumber=function(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:t},o.stopASRAfterSocketClose=function(){var e=this;if(this.asrStartGeneration+=1,!this.stopASRPromise){var t=this.microphone;null!=t&&t.isRecording&&(this.microphone=null,this.stopASRPromise=this.finishStopASR(t,!1).catch(function(t){e.emitError("sdk","MICROPHONE_CLEANUP_FAILED","WebSocket 断开后清理麦克风失败",!1,t)}).finally(function(){e.stopASRPromise=null}))}},o.setAgentState=function(e){var t;this.agentState=e,this.agentDestroyed&&"destroyed"!==e||null==(t=this.agentOptions.callbacks)||null==t.onAgentStateChange||t.onAgentStateChange(e)},o.setASRState=function(e){var t=this;this.asrState=e,this.safeEmit(function(){var n;return null==(n=t.agentOptions.callbacks)||null==n.onASRStateChange?void 0:n.onASRStateChange(e)})},o.emitConversation=function(e){var t=this;this.safeEmit(function(){var n;return null==(n=t.agentOptions.callbacks)||null==n.onConversationChange?void 0:n.onConversationChange(e)})},o.emitError=function(e,t,n,r,i){var o=this,a={domain:e,code:t,message:n,retryable:r,cause:i};"asr"===e&&this.setASRState("failed"),this.safeEmit(function(){var e;return null==(e=o.agentOptions.callbacks)||null==e.onError?void 0:e.onError(a)})},o.safeEmit=function(e){this.agentDestroyed||this.agentDestroying||e()},o.assertRunning=function(){if(this.assertE2EOpen(),this.serviceMigration)throw new Error("Agent 正在迁移 E2E,请等待恢复后再开始新交互");if("running"!==this.agentState)throw new Error("Agent 尚未启动,请先调用 start()")},o.assertASRStartAllowed=function(){if(this.assertRunning(),this.getStatus()===r.invisible)throw new Error("数字人处于隐身状态,无法启动 ASR,请先退出隐身模式")},o.assertE2EOpen=function(){var e;if(this.assertNotDestroyed(),null==(e=this.e2eClient)||!e.isOpen)throw new Error("Agent 尚未连接 E2E WebSocket")},o.assertNotDestroyed=function(){if(this.agentDestroyed||this.agentDestroying)throw new Error("Agent 已销毁")},t}(a.default);return me});
@@ -32,6 +32,17 @@ export default class XingyunAvatarAgent extends XmovAvatar {
32
32
  private sessionReloadFallback;
33
33
  private waitingForTtsaReload;
34
34
  private stateBeforeReconnect;
35
+ private e2eSessionId;
36
+ private currentE2EUrl;
37
+ private serviceReconnect;
38
+ private serviceMigration;
39
+ private interactionPending;
40
+ private llmPending;
41
+ private llmProducedText;
42
+ private directSpeakOpen;
43
+ private pendingASR;
44
+ private autoSendASRToLLM;
45
+ private voicePlaying;
35
46
  private reportingInitializationFailure;
36
47
  private readonly handleOnlineForReconnect;
37
48
  constructor(options: XingyunAvatarAgentOptions);
@@ -89,6 +100,15 @@ export default class XingyunAvatarAgent extends XmovAvatar {
89
100
  private forwardVoiceEnd;
90
101
  private readFiniteNumber;
91
102
  private handleBackendError;
103
+ private handleServiceUpdate;
104
+ private startServiceMigration;
105
+ private checkServiceMigration;
106
+ private closeForServiceMigration;
107
+ private scheduleServiceReconnect;
108
+ private attemptServiceReconnect;
109
+ private failServiceMigration;
110
+ private setMigrationState;
111
+ private cancelServiceMigration;
92
112
  private handleSocketClose;
93
113
  private shouldReconnect;
94
114
  private beginReconnect;